TransKit

专为油猴脚本 (Userscript) 打造的高性能单文件翻译 SDK。内置 7 大开箱即用稳定翻译源,提供两级缓存 (L1/L2)、并发去重、自动批处理、故障转移 (Failover) 与半开熔断防护等核心能力。

Цей скрипт не слід встановлювати безпосередньо. Це - бібліотека для інших скриптів для включення в мета директиву // @require https://update.greasyfork.org/scripts/591255/1902101/TransKit.js

You will need to install an extension such as Tampermonkey, Greasemonkey or Violentmonkey to install this script.

You will need to install an extension such as Tampermonkey or Violentmonkey to install this script.

You will need to install an extension such as Tampermonkey or Violentmonkey to install this script.

You will need to install an extension such as Tampermonkey or Userscripts to install this script.

You will need to install an extension such as Tampermonkey to install this script.

You will need to install a user script manager extension to install this script.

(У мене вже є менеджер скриптів, дайте мені встановити його!)

You will need to install an extension such as Stylus to install this style.

You will need to install an extension such as Stylus to install this style.

You will need to install an extension such as Stylus to install this style.

You will need to install a user style manager extension to install this style.

You will need to install a user style manager extension to install this style.

You will need to install a user style manager extension to install this style.

(I already have a user style manager, let me install it!)

Автор
You Boy
Версія
1.0.1
Створено
14.08.2026
Оновлено
14.08.2026
Size
66,5 кБ
Ліцензія
MIT

📖 TransKit 开发者帮助手册

TransKit 是一个专为 Userscript(油猴/ Violentmonkey / ScriptCat)环境设计的单文件翻译 SDK。内置 7 大开箱即用的稳定翻译源,提供两级缓存、批量翻译、并发去重、自动故障转移(Failover)与熔断防护机制。


🚀 1. 快速开始

1.1 在油猴脚本中引入 (Userscript Header)

在你的脚本元数据中通过 @require 引入 TransKit.js,并声明必要的 GM 权限与跨域域名:

// ==UserScript==
// @name         我的网页翻译脚本
// @namespace    https://your-domain.com
// @version      1.0.0
// @description  使用 TransKit SDK 实现的高效翻译脚本
// @author       You
// @match        *://*/*
//
// === 引入 TransKit SDK ===
// @require https://update.greasyfork.org/scripts/591255/1902099/TransKit.js

//
// === 油猴 API 权限声明 ===
// @grant        GM_xmlhttpRequest
// @grant        GM_getValue
// @grant        GM_setValue
// @grant        GM_deleteValue
// @grant        GM_listValues
//
// === 跨域请求权限声明(内置 7 大翻译源) ===
// @connect      translate.google.com
// @connect      translate.googleapis.com
// @connect      edge.microsoft.com
// @connect      transmart.qq.com
// @connect      www2.deepl.com
// @connect      api.interpreter.caiyunai.com
// @connect      m.youdao.com
// ==/UserScript==

💡 提示:声明网络权限时,也可以直接使用 @connect * 允许跨域连接。


1.2 最小使用示例

无需复杂初始化,直接调用全局 TransKit API:

(async () => {
    // 1. 单文本翻译(默认自动识别源语言,翻译为 zh-CN 中文)
    const text = await TransKit.translate('Hello, world!');
    console.log(text); // "你好,世界!"

    // 2. 批量翻译(自动去重、分批请求、恢复原始顺序)
    const list = await TransKit.translate(['Apple', 'Banana', 'Apple']);
    console.log(list); // ["苹果", "香蕉", "苹果"]

    // 3. 语种检测
    const lang = await TransKit.detect('Bonjour');
    console.log(lang); // "fr"
})();

🛠️ 2. 核心 API 详解

2.1 TransKit.translate(input, options?)

普通翻译 API。翻译成功时返回结果;若所有翻译源尝试失败,Promise 将会被 Reject。

  • 参数
    • input: stringstring[] — 单文本或文本数组。
    • options: object(可选)— 单次请求级配置参数。
  • 返回值Promise<string>Promise<string[]>(保持与输入类型一致)。
// 指定目标语言与翻译源
const result = await TransKit.translate('Hello', {
    target: 'ja',         // 目标语言:日语
    providers: ['deepl', 'google'] // 优先用 DeepL,失败则自动故障转移至 Google
});
console.log(result); // "こんにちは"

2.2 TransKit.translateWithDetails(input, options?)

诊断级翻译 API。无论输入是字符串还是数组,始终返回包含详细诊断信息的数组。允许部分成功、部分失败,绝不中断 Reject。

  • 参数:与 translate 一致。
  • 返回值Promise<Array<ResultDetails>>

返回的诊断对象结构:

[
  {
    originalText: "Hello",       // 原始文本
    text: "你好",                 // 翻译结果(失败时为 null)
    success: true,               // 是否成功
    provider: "google",          // 最终成功的翻译源 ID
    fromCache: false,            // 是否命中缓存
    duration: 128,               // 耗时 (ms)
    attempts: [                  // 轮询尝试历史
      { provider: "google", success: true, duration: 128 }
    ]
  },
  {
    originalText: "Unknown",
    text: null,                  // 失败时 text 为 null
    success: false,
    provider: null,
    fromCache: false,
    duration: 3050,
    error: TransKitError         // 详细错误对象
  }
]

2.3 实例创建与全局配置

如果你需要隔离不同的翻译场景(例如:悬浮取词用一套配置,全文翻译用另一套配置),可以使用 TransKit.create() 创建独立实例:

// 全局修改默认配置
TransKit.configure({
    timeout: 5000,
    debug: true
});

// 创建独立 Translator 实例
const fastTranslator = TransKit.create({
    providers: ['google', 'bing'],
    timeout: 3000,
    cache: { ttl: 24 * 60 * 60 * 1000 } // 缓存 1 天
});

const text = await fastTranslator.translate('Fast translation');

⚙️ 3. 配置项说明 (Configuration)

配置优先级为:请求级 options > 实例级 options > 全局 configure > 默认值

配置项 类型 默认值 说明
source string 'auto' 源语言代码(如 'auto', 'en', 'ja'
target string 'zh-CN' 目标语言代码(如 'zh-CN', 'en', 'ja'
providers `string \ string[]` 'auto'
batchSize number 30 批量翻译时每批的最大文本数(批次间顺序执行)
timeout number 10000 HTTP 请求超时时间 (ms)
retry `number \ object` 0
debug boolean false 是否开启 Console 调试日志输出
cache.enabled boolean true 是否开启缓存(两级缓存:L1 内存 + L2 存储)
cache.ttl number 604800000 缓存有效期 (ms),默认 7 天
cache.refreshOnHit boolean true 命中缓存时是否自动热刷新续期
cache.refreshInterval number 21600000 触发热刷新的最小间隔 (ms),默认 6 小时
cache.maxEntries number 10000 L1 内存缓存最大条数(超限自动 LRU 淘汰)
cache.persistent boolean true 是否持久化写入 Userscript GM Storage
circuitBreaker.enabled boolean false 是否开启自动熔断防护
circuitBreaker.failureThreshold number 10 连续失败达到该次数后触发熔断
circuitBreaker.cooldown number 21600000 熔断冷却时间 (ms),默认 6 小时

📦 4. 内置 Provider 列表

TransKit 内置了 7 个经过实际环境验证的稳定翻译源:

Provider ID 翻译源名称 默认优先级 特点
google Google Translate 100 速度快,准确率高
bing Bing Translator 90 微软翻译,稳定
tencent-ai 腾讯 Transmart 82 交互式 AI 翻译,适合长句
deepl DeepL 70 翻译质量高
caiyun 彩云小译 65 中英翻译流畅
youdao-mobile 有道移动版 40 兜底源
google-mobile Google 移动版 35 兜底源

💡 5. 进阶指南

5.1 限制翻译源白名单与自定义 Failover 顺序

// 严格按顺序尝试 DeepL -> 微软 -> 腾讯,且绝不使用其他翻译源
const translator = TransKit.create({
    providers: ['deepl', 'bing', 'tencent-ai']
});

5.2 运行时诊断与缓存清理

// 1. 获取当前全局正在并发请求的文本数量
console.log(TransKit.runtime.getInflightCount());

// 2. 查看各个翻译源的熔断健康状态
console.log(TransKit.runtime.getCircuitState());

// 3. 手动重置某个 Provider 的熔断状态
TransKit.runtime.resetCircuit('google');

// 4. 清空翻译缓存(同时清理 L1 内存和 L2 油猴存储)
await TransKit.clearCache();

5.3 扩展自定义翻译源 (Custom Provider)

你可以非常轻松地为 TransKit 注册第三方 API 或自建翻译服务:

class MyCustomProvider {
    static id = 'my-api';
    static name = '我的自定义翻译器';
    static priority = 120; // 优先级高于内置 Google

    async translate(request, context) {
        // 使用 context.services.request 统一请求,自动继承 Timeout 和代理
        const response = await context.services.request.request({
            method: 'POST',
            url: 'https://api.example.com/translate',
            headers: { 'Content-Type': 'application/json' },
            data: JSON.stringify({
                text: request.text,
                from: request.source,
                to: request.target
            })
        });

        const data = JSON.parse(response.responseText);

        // 成功时返回包含 text 的对象
        return { text: data.translated_result };
    }
}

// 注册自定义 Provider
TransKit.providers.register(MyCustomProvider);

// 使用自定义 Provider 翻译
const res = await TransKit.translate('Hello', { providers: 'my-api' });

5.4 替换底层 Service (例如使用自定义网络器或数据库)

// 替换全局 Storage 为自定义的高性能数据库适配器
TransKit.services.register('storage', {
    async get(key) { /* 自定义读取 */ },
    async set(key, val) { /* 自定义写入 */ },
    async delete(key) { /* 自定义删除 */ }
}, { override: true });

❓ 常见问题 (FAQ)

Q1: 为什么我的脚本提示跨域失败 (Network Error)?

:请检查脚本开头的元数据区域是否正确添加了对应域名(如 @connect translate.google.com@connect *),并确保添加了 @grant GM_xmlhttpRequest 权限。

Q2: 多个组件同时请求同一个句子会造成重复翻译吗?

:不会。TransKit 内部实现了 Inflight 并发去重 机制。如果在毫秒级时间内发起多个相同句子、相同语言和相同翻译源的请求,TransKit 只会向远端发送一次 HTTP 请求,其余调用将自动共享同一个 Promise 结果。

Q3: translate()translateWithDetails() 我应该用哪个?

:普通业务场景(如给 DOM 节点替换文本)直接使用 translate(),代码最简洁,失败时自动抛出异常;若在写诊断工具、控制面板或需要展示耗时、耗用源等信息时,建议使用 translateWithDetails()


📄 开源协议

MIT License. Welcome to contribute or submit issues!