language-detector-api

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Language Detector API

Language Detector API

Procedures

操作流程

Step 1: Identify the browser integration surface
  1. Inspect the workspace for browser entry points, UI handlers, text-input flows, and any existing AI abstraction layer.
  2. Execute
    node scripts/find-language-detector-targets.mjs .
    to inventory likely frontend files and existing Language Detector 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, component, or user-requested feature surface.
  5. If the inventory still leaves multiple plausible frontend targets, stop and ask which app should receive the Language Detector 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/language-detector-reference.md
    before writing code.
  2. Read
    references/examples.md
    when the feature needs a session wrapper, download-progress UI, confidence thresholding, 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, creation, detection, 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
    language-detector
    permissions-policy feature.
  7. Choose the narrowest session shape that matches the task:
    • bare
      LanguageDetector.create()
      for general language detection
    • expectedInputLanguages
      when the product depends on a narrower language set or better accuracy for known languages
    • monitor
      when the UI must surface model download progress
  8. If the feature must run in a worker, on the server, or through a cloud-only contract, stop and explain the platform mismatch.
  9. If the project uses TypeScript, add or preserve narrow typings for the Language Detector API surface used by the feature.
Step 3: Implement a guarded session wrapper
  1. Read
    assets/language-detector-session.template.ts
    and adapt it to the framework, state model, and file layout in the workspace.
  2. Centralize support checks around
    globalThis.isSecureContext
    ,
    LanguageDetector
    , and the same
    expectedInputLanguages
    shape the feature will use at runtime.
  3. Gate session creation behind
    LanguageDetector.availability()
    using the same create options that will be passed to
    LanguageDetector.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()
    ,
    detect()
    , or
    measureInputUsage()
    calls, and call
    destroy()
    when the session is no longer needed.
  8. Recreate the session instead of mutating
    expectedInputLanguages
    after creation; session options are fixed per instance.
  9. If the feature lives in a cross-origin iframe, require explicit delegation through
    allow="language-detector"
    .
Step 4: Wire UX and fallback behavior
  1. Surface distinct states for missing APIs, insecure contexts, blocked frames, downloadable or downloading models, ready sessions, in-flight detection, and aborted work.
  2. Keep a non-AI fallback for unsupported browsers, blocked frames, or environments that do not meet current preview requirements.
  3. Treat very short text, single words, and mixed-language snippets as lower-confidence inputs; present confidence-aware UI instead of pretending the top result is always reliable.
  4. Preserve the full ordered result list when the product needs ranked candidates, and apply any confidence threshold or
    und
    handling in product logic instead of truncating silently.
  5. Treat the trailing
    und
    result as meaningful uncertainty, not as a defect to remove.
  6. Use
    measureInputUsage()
    when quota or input-size budgeting affects the flow.
  7. Do not route translation, summarization, or generic chat tasks through this API; switch to Translator, Writing Assistance APIs, Prompt API, or another approved capability when the task is not language detection.
Step 5: Validate behavior
  1. Execute
    node scripts/find-language-detector-targets.mjs .
    to confirm that the intended app boundary and Language Detector API markers still resolve to the edited integration surface.
  2. Verify secure-context checks,
    LanguageDetector
    feature detection, and
    availability()
    behavior before debugging deeper runtime failures.
  3. Test at least one
    create()
    plus
    detect()
    flow with representative user text.
  4. If the feature depends on
    expectedInputLanguages
    , test both the constrained and unconstrained path or confirm why only one is valid.
  5. Confirm that cancellation rejects with the expected abort reason and that destroyed sessions are not reused.
  6. 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.
  7. Run the workspace build, typecheck, or tests after editing.
步骤1:确定浏览器集成边界
  1. 检查工作区中的浏览器入口点、UI处理逻辑、文本输入流程,以及所有现有的AI抽象层。
  2. 当有可用Node运行环境时,执行
    node scripts/find-language-detector-targets.mjs .
    来清点可能的前端文件和现有Language Detector API标记。
  3. 若没有Node运行环境,手动检查最近的
    package.json
    、HTML入口文件和框架启动文件,确定浏览器应用的边界。
  4. 如果工作区包含多个前端应用,优先选择包含活跃路由、组件或用户需求功能模块的应用。
  5. 如果清点后仍有多个可能的前端目标,停止操作并询问应该在哪个应用中集成Language Detector API。
  6. 如果项目不是浏览器网页应用,停止操作并说明本技能不适用该场景。
步骤2:确认API可行性并选择集成形式
  1. 编写代码前请阅读
    references/language-detector-reference.md
  2. 当功能需要会话封装、下载进度UI、置信度阈值设置或清理逻辑时,请阅读
    references/examples.md
  3. 当需要考虑预览标记、浏览器渠道、iframe规则或环境约束时,请阅读
    references/compatibility.md
  4. 当支持检查、创建、检测或清理操作失败时,请阅读
    references/troubleshooting.md
  5. 确认功能运行在安全的
    Window
    上下文中。
  6. 确认当前框架被允许使用
    language-detector
    权限策略特性。
  7. 选择符合任务需求的最小范围会话形式:
    • 通用语言检测使用基础的
      LanguageDetector.create()
    • 当产品依赖更小的语言集合或需要提升已知语言的检测准确率时使用
      expectedInputLanguages
    • 当UI需要展示模型下载进度时使用
      monitor
  8. 如果功能必须运行在Worker、服务端或仅通过云协议运行,停止操作并说明平台不匹配。
  9. 如果项目使用TypeScript,为功能用到的Language Detector API接口添加或保留窄类型定义。
步骤3:实现带防护的会话封装
  1. 阅读
    assets/language-detector-session.template.ts
    ,并适配工作区中的框架、状态模型和文件结构。
  2. 将支持检查逻辑集中在
    globalThis.isSecureContext
    LanguageDetector
    以及功能运行时会用到的
    expectedInputLanguages
    结构上。
  3. 使用和传入
    LanguageDetector.create()
    相同的创建参数,将会话创建逻辑前置校验
    LanguageDetector.availability()
    的结果。
  4. availability()
    视为能力检查,而不是创建操作一定会成功的保证,因为可能存在下载耗时、策略审批或用户激活要求等限制。
  5. 当创建会话可能触发模型下载时,仅在用户激活后再创建会话。
  6. 当产品需要下载进度展示时,在
    create()
    调用中传入
    monitor
    选项。
  7. 对可取消的
    create()
    detect()
    measureInputUsage()
    调用使用
    AbortController
    ,并在不再需要会话时调用
    destroy()
  8. 会话创建后不要修改
    expectedInputLanguages
    ,而是重新创建会话;每个实例的会话选项是固定的。
  9. 如果功能位于跨域iframe中,需要通过
    allow="language-detector"
    显式授权。
步骤4:对接UX和降级逻辑
  1. 为以下场景提供清晰的状态展示:API缺失、上下文不安全、框架被拦截、模型可下载/下载中、会话就绪、检测进行中、任务已终止。
  2. 为不支持的浏览器、被拦截的框架或不符合当前预览要求的环境保留非AI降级方案。
  3. 将极短文本、单个单词和混合语言片段视为低置信度输入;展示带置信度提示的UI,而不是默认认为返回的第一个结果始终可靠。
  4. 当产品需要候选结果排序时,保留完整的有序结果列表,在产品逻辑中应用置信度阈值或
    und
    结果处理,不要静默截断结果。
  5. 将末尾的
    und
    结果视为有意义的不确定性提示,而不是需要移除的缺陷。
  6. 当配额或输入大小预算会影响流程时,使用
    measureInputUsage()
  7. 不要将翻译、摘要或通用聊天任务路由到该API;如果任务不是语言检测,请切换到Translator、写作辅助API、Prompt API或其他获批的能力。
步骤5:验证行为
  1. 执行
    node scripts/find-language-detector-targets.mjs .
    ,确认预期的应用边界和Language Detector API标记仍指向修改后的集成模块。
  2. 在调试更深层的运行时故障前,先验证安全上下文检查、
    LanguageDetector
    特性检测和
    availability()
    的行为是否正常。
  3. 使用有代表性的用户文本,至少测试一次完整的
    create()
    detect()
    流程。
  4. 如果功能依赖
    expectedInputLanguages
    ,同时测试约束和非约束路径,或确认仅有一种路径有效的原因。
  5. 确认取消操作会按预期返回终止原因,且已销毁的会话不会被复用。
  6. 如果目标环境依赖预览浏览器标记或特定渠道的行为,在将故障判定为应用bug前,先对照
    references/compatibility.md
    确认所需的浏览器配置。
  7. 修改完成后运行工作区的构建、类型检查或测试流程。

Error Handling

错误处理

  • If
    LanguageDetector
    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 detection is ready.
  • If
    create()
    throws
    NotAllowedError
    , check permissions-policy constraints, missing user activation for downloads, browser policy restrictions, or user rejection.
  • If
    detect()
    throws
    InvalidStateError
    , confirm the document is still fully active and recreate the session after major lifecycle changes if needed.
  • If a detection call throws
    QuotaExceededError
    , reduce the input size or measure usage before retrying.
  • If the feature must run in a worker or server context, stop and explain that the Language Detector API is a window-only browser API.
  • 如果
    LanguageDetector
    不存在,保留非AI降级方案,在修改产品逻辑前先确认安全上下文、浏览器、渠道和标记要求是否满足。
  • 如果
    availability()
    返回
    downloadable
    downloading
    ,在承诺检测能力就绪前,需要用户主动触发会话创建。
  • 如果
    create()
    抛出
    NotAllowedError
    ,检查权限策略约束、下载所需的用户激活是否缺失、浏览器策略限制或用户拒绝授权。
  • 如果
    detect()
    抛出
    InvalidStateError
    ,确认文档仍处于完全活跃状态,若有必要在重大生命周期变更后重新创建会话。
  • 如果检测调用抛出
    QuotaExceededError
    ,减小输入大小或在重试前统计使用量。
  • 如果功能必须运行在Worker或服务端上下文,停止操作并说明Language Detector API是仅适用于window上下文的浏览器API。