translator-api

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Translator API

Translator API

Procedures

操作流程

Step 1: Identify the browser integration surface
  1. Inspect the workspace for browser entry points, text-input flows, localization UI, and any existing AI abstraction layer.
  2. Execute
    node scripts/find-translator-targets.mjs .
    to inventory likely frontend files and existing Translator API markers when a Node runtime is available.
  3. If a Node runtime is unavailable, inspect the nearest
    package.json
    , HTML entry point, and framework bootstrap files manually to identify the browser app boundary.
  4. If the workspace contains multiple frontend apps, prefer the app that contains the active route, translation UI, or user-requested feature surface.
  5. If the inventory still leaves multiple plausible frontend targets, stop and ask which app should receive the Translator API integration.
  6. If the project is not a browser web app, stop and explain that this skill does not apply.
Step 2: Confirm API viability and choose the integration shape
  1. Read
    references/translator-reference.md
    before writing code.
  2. Read
    references/examples.md
    when the feature needs a session wrapper, download-progress UI, streaming output, cancellation, or cleanup shape.
  3. Read
    references/compatibility.md
    when preview flags, browser channels, iframe rules, or environment constraints matter.
  4. Read
    references/troubleshooting.md
    when support checks, session creation, translation, or cleanup fail.
  5. Verify that the feature runs in a secure
    Window
    context.
  6. Verify that the current frame is allowed to use the
    translator
    permissions-policy feature.
  7. Choose the narrowest session shape that matches the task:
    • bare
      Translator.create()
      for a fixed language pair and full-result translation
    • monitored
      create()
      when the UI must surface model download progress
    • translateStreaming()
      when the UI should reveal translated output incrementally
    • measureInputUsage()
      when quota or input-size budgeting affects the flow
  8. If the feature must run in a worker, on the server, or through a cloud translation contract, stop and explain the platform mismatch.
  9. If the project uses TypeScript, add or preserve narrow typings for the Translator API surface used by the feature.
Step 3: Implement a guarded translator session
  1. Read
    assets/translator-session.template.ts
    and adapt it to the framework, state model, and file layout in the workspace.
  2. Centralize support checks around
    globalThis.isSecureContext
    ,
    Translator
    , and the same
    sourceLanguage
    and
    targetLanguage
    shape the feature will use at runtime.
  3. Gate session creation behind
    Translator.availability()
    using the same language pair that will be passed to
    Translator.create()
    .
  4. Treat
    availability()
    as a capability check, not a guarantee that creation will succeed without download time, policy approval, or user activation.
  5. Create sessions only after user activation when creation may trigger a model download.
  6. Use the
    monitor
    option during
    create()
    when the product needs download progress.
  7. Use
    AbortController
    for cancelable
    create()
    ,
    translate()
    ,
    translateStreaming()
    , or
    measureInputUsage()
    calls, and call
    destroy()
    when the session is no longer needed.
  8. Recreate the session instead of mutating
    sourceLanguage
    or
    targetLanguage
    after creation; session options are fixed per instance.
  9. If the feature lives in a cross-origin iframe, require explicit delegation through
    allow="translator"
    .
Step 4: Wire UX and fallback behavior
  1. Surface distinct states for missing APIs, insecure contexts, blocked frames, unsupported language pairs, downloadable or downloading models, ready sessions, in-flight translation, and aborted work.
  2. Keep a non-AI fallback for unsupported browsers, blocked frames, or environments that do not meet current preview requirements.
  3. Preserve the source and target language pair explicitly in product state instead of inferring them from translated output.
  4. Use
    translate()
    when downstream logic needs the full result before continuing, and use
    translateStreaming()
    when the UI should reveal translated text incrementally.
  5. Use
    measureInputUsage()
    when large inputs can exceed session quota.
  6. Treat same-language or best-fit identity translations as valid outcomes instead of forcing a fallback when the translated result matches the input.
  7. Chunk or queue long-running product workflows deliberately; translation requests are not a substitute for general summarization, writing, or chat tasks.
  8. Do not route generic cloud translation, document localization pipelines, or server-side batch translation through this API; switch to the approved service or runtime when the task is not browser on-device translation.
Step 5: Validate behavior
  1. Execute
    node scripts/find-translator-targets.mjs .
    to confirm that the intended app boundary and Translator API markers still resolve to the edited integration surface.
  2. Verify secure-context checks,
    Translator
    feature detection, and
    availability()
    behavior before debugging deeper runtime failures.
  3. Test at least one
    create()
    plus
    translate()
    flow with representative user text for the target language pair.
  4. If the feature exposes streaming, test
    translateStreaming()
    separately and confirm partial output stops cleanly on abort.
  5. If the feature depends on quota budgeting, verify
    measureInputUsage()
    behavior before sending large input.
  6. Confirm that cancellation rejects with the expected abort reason and that destroyed sessions are not reused.
  7. If the target environment depends on preview browser flags or channel-specific behavior, confirm the required browser state from
    references/compatibility.md
    before treating failures as application bugs.
  8. Run the workspace build, typecheck, or tests after editing.
步骤1:确定浏览器集成范围
  1. 检查工作区中的浏览器入口点、文本输入流程、本地化UI以及所有现有AI抽象层。
  2. 当有Node运行时可用时,执行
    node scripts/find-translator-targets.mjs .
    来盘点可能的前端文件和现有Translator API标记。
  3. 若没有Node运行时,手动检查就近的
    package.json
    、HTML入口点和框架启动文件,确定浏览器应用边界。
  4. 如果工作区包含多个前端应用,优先选择包含活跃路由、翻译UI或用户请求功能界面的应用。
  5. 如果盘点后仍有多个可能的前端目标,暂停操作并询问需要将Translator API集成到哪个应用中。
  6. 如果项目不是浏览器Web应用,暂停操作并说明本技能不适用。
步骤2:确认API可行性并选择集成形式
  1. 编写代码前先阅读
    references/translator-reference.md
  2. 当功能需要会话封装、下载进度UI、流式输出、取消或清理逻辑时,阅读
    references/examples.md
  3. 当涉及预览标志、浏览器渠道、iframe规则或环境约束时,阅读
    references/compatibility.md
  4. 当支持检测、会话创建、翻译或清理操作失败时,阅读
    references/troubleshooting.md
  5. 确认功能运行在安全的
    Window
    上下文中。
  6. 确认当前框架允许使用
    translator
    权限策略特性。
  7. 选择符合任务要求的最小会话形式:
    • Translator.create()
      适用于固定语言对和全量结果翻译场景
    • 带监控的
      create()
      适用于UI需要展示模型下载进度的场景
    • translateStreaming()
      适用于UI需要逐步展示翻译输出的场景
    • measureInputUsage()
      适用于配额或输入大小预算会影响流程的场景
  8. 如果功能必须运行在Worker、服务端或通过云翻译协议调用,暂停操作并说明平台不匹配。
  9. 如果项目使用TypeScript,为功能用到的Translator API接口添加或保留窄类型定义。
步骤3:实现带防护的翻译器会话
  1. 阅读
    assets/translator-session.template.ts
    ,并适配工作区中的框架、状态模型和文件结构。
  2. 围绕
    globalThis.isSecureContext
    Translator
    以及功能运行时会用到的
    sourceLanguage
    targetLanguage
    结构集中做支持检测。
  3. 使用和传入
    Translator.create()
    相同的语言对,通过
    Translator.availability()
    来做会话创建的前置校验。
  4. availability()
    视为能力检测,不代表会话创建一定能成功,可能会受下载耗时、策略审批或用户激活等因素影响。
  5. 当创建会话可能触发模型下载时,仅在用户激活后再创建会话。
  6. 当产品需要展示下载进度时,在
    create()
    调用时使用
    monitor
    选项。
  7. 对可取消的
    create()
    translate()
    translateStreaming()
    measureInputUsage()
    调用使用
    AbortController
    ,会话不再需要时调用
    destroy()
  8. 会话创建后不要修改
    sourceLanguage
    targetLanguage
    ,而是重新创建会话;每个实例的会话选项是固定的。
  9. 如果功能位于跨源iframe中,需要通过
    allow="translator"
    显式授权。
步骤4:对接UX和降级逻辑
  1. 为以下场景分别展示不同状态:API缺失、不安全上下文、框架被屏蔽、语言对不支持、模型可下载/下载中、会话就绪、翻译中、任务已中止。
  2. 为不支持的浏览器、被屏蔽的框架或不符合当前预览要求的环境保留非AI降级方案。
  3. 在产品状态中显式存储源语言和目标语言对,不要通过翻译输出反向推断。
  4. 当下游逻辑需要获取全量结果后再继续时使用
    translate()
    ,UI需要逐步展示翻译文本时使用
    translateStreaming()
  5. 当大输入可能超出会话配额时使用
    measureInputUsage()
  6. 当翻译结果和输入一致时,将同语言或最佳匹配的同一性翻译视为合法结果,不要强制降级。
  7. 对长时间运行的产品工作流做刻意的分块或队列处理;翻译请求不能替代通用的摘要、写作或聊天任务。
  8. 不要将通用云翻译、文档本地化流水线或服务端批量翻译路由到该API;如果任务不是浏览器端侧翻译,切换到获批的服务或运行时。
步骤5:验证行为
  1. 执行
    node scripts/find-translator-targets.mjs .
    ,确认预期的应用边界和Translator API标记仍指向修改后的集成范围。
  2. 在调试更深层的运行时故障前,先验证安全上下文检测、
    Translator
    特性检测和
    availability()
    的行为是否正常。
  3. 针对目标语言对,使用有代表性的用户文本测试至少一次
    create()
    translate()
    的完整流程。
  4. 如果功能支持流式输出,单独测试
    translateStreaming()
    ,确认中止时部分输出会正常停止。
  5. 如果功能依赖配额预算,在发送大输入前验证
    measureInputUsage()
    的行为是否正常。
  6. 确认取消操作会按预期抛出中止原因,且已销毁的会话不会被复用。
  7. 如果目标环境依赖预览浏览器标志或特定渠道的行为,在将故障判定为应用bug前,先从
    references/compatibility.md
    确认所需的浏览器状态。
  8. 修改完成后运行工作区的构建、类型检查或测试任务。

Error Handling

错误处理

  • If
    Translator
    is missing, keep a non-AI fallback and confirm secure-context, browser, channel, and flag requirements before changing product logic.
  • If
    availability()
    returns
    downloadable
    or
    downloading
    , require user-driven session creation before promising that translation is ready.
  • If
    create()
    throws
    NotAllowedError
    , check permissions-policy constraints, missing user activation for downloads, browser policy restrictions, or user rejection.
  • If
    create()
    throws
    OperationError
    , treat model initialization as failed and retry only after checking browser state, required flags, and download readiness.
  • If a translation call throws
    QuotaExceededError
    , reduce the input size or measure usage before retrying.
  • If a translation call throws
    NotReadableError
    or
    UnknownError
    , surface a visible fallback instead of retrying blindly with the same input.
  • If the feature must run in a worker or server context, stop and explain that the Translator API is a window-only browser API.
  • 如果
    Translator
    不存在,保留非AI降级方案,修改产品逻辑前先确认安全上下文、浏览器、渠道和标志要求是否满足。
  • 如果
    availability()
    返回
    downloadable
    downloading
    ,在承诺翻译就绪前需要用户主动触发会话创建。
  • 如果
    create()
    抛出
    NotAllowedError
    ,检查权限策略约束、下载缺少用户激活、浏览器策略限制或用户拒绝授权等情况。
  • 如果
    create()
    抛出
    OperationError
    ,判定为模型初始化失败,仅在检查浏览器状态、所需标志和下载就绪状态后再重试。
  • 如果翻译调用抛出
    QuotaExceededError
    ,减小输入大小或先统计使用量再重试。
  • 如果翻译调用抛出
    NotReadableError
    UnknownError
    ,展示可见的降级提示,不要用相同输入盲目重试。
  • 如果功能必须运行在Worker或服务端上下文,暂停操作并说明Translator API是仅Window可用的浏览器API。