feat(panel): add Antigravity host UI localization and language packs

- Add standalone host-i18n language pack manager with GitHub/jsDelivr
  download, SHA-256 integrity checks, offline light/deep tier switching,
  and lossless DOM translation over the CDP window bridge
- Add Settings -> General host interface language controls, untranslated
  UI string collector, and loopback-only /api/host-i18n endpoints
- Include zh-CN layered language pack assets and source/audit/build scripts
  under host-i18n/ while keeping the Release ZIP runtime whitelist isolated
This commit is contained in:
fish
2026-11-25 13:38:23 +09:00
parent 5565133710
commit 8a01705e6f
48 changed files with 32522 additions and 38 deletions
@@ -0,0 +1,914 @@
/**
* @fileoverview 注入到 Antigravity 渲染进程的无损运行时 DOM 翻译引擎与按需词条采集器。
*
* 工程底线:
* 1. 绝不替换、拆裂或增删 React 托管的任何 DOM 元素,仅原地改写 `Text.nodeValue` 及
* `placeholder` / `title` / `aria-label` / `aria-description` / `aria-placeholder` 属性;
* 2. 通过 `WeakMap` 精确记录每个被改写节点/属性的原文与译文,既支持 `light ↔ deep` /
* `关闭` 秒级无损还原,也能自动识别 React 原地更新的新英文文案并重新翻译;
* 3. 对齐 Antigravity 真实 DOM 结构,严格豁免用户消息正文(`user-message-content`)、
* 代码块、Diff 行、编辑器、终端、可编辑区以及本插件双 Shadow Host,不误伤工具栏按钮;
* 4. 针对数千条精确词条 + 数百条动态模板做 O(1) 精确查表 + 首词桶索引,并经
* `requestAnimationFrame` 分帧合批,杜绝流式输出掉帧。
*/
import { HOST_I18N_GLOBAL_KEY } from '../../shared/host-i18n-protocol.mjs';
/**
* 在宿主页面执行:安装或热更新无损 DOM 翻译器,并续期 18 秒看门狗。
*
* @param {object} payload `{ locale, depth, revision, exact, patterns }`
* @param {string} bootId
* @param {string} [globalKey]
*/
export function applyHostI18nInPage(payload, bootId, globalKey = '__AGUsageMonitorHostI18n') {
if (typeof window === 'undefined' || typeof document === 'undefined') {
return { applied: false, reason: 'no_dom' };
}
const root = document.body || document.documentElement;
if (!root) {
return { applied: false, reason: 'no_root' };
}
const WATCHDOG_MS = 18_000;
const FRAME_NODE_BUDGET = 450;
const INITIAL_SCAN_BUDGET = 4000;
const MAX_PENDING_NODES = 4096;
const MAX_MISS_CACHE = 1024;
const MAX_EXACT_LEN = 1000;
const MAX_PATTERN_LEN = 360;
const TRANSLATABLE_ATTRS = [
'placeholder',
'title',
'aria-label',
'aria-description',
'aria-placeholder',
];
const SKIP_TAGS = new Set([
'SCRIPT',
'STYLE',
'NOSCRIPT',
'CODE',
'PRE',
'TEXTAREA',
'SVG',
'MATH',
'KBD',
'SAMP',
'VAR',
'CANVAS',
'VIDEO',
'AUDIO',
'IFRAME',
]);
const SKIP_TESTIDS = new Set([
'user-message-content',
'markdown-code-block-preview',
'markdown-frontmatter',
'automation-instructions-markdown',
'code-gutter',
'code-gutter-diff',
'diff-gutter-strip',
'artifact-pdf-view',
]);
const SKIP_CLASSES = new Set([
'monaco-editor',
'xterm',
'cm-editor',
'ProseMirror',
'markdown-body',
'prose',
'diff-line',
'view-lines',
]);
function isSkippedSelf(el) {
if (!el || el.nodeType !== 1) return false;
if (SKIP_TAGS.has(el.tagName)) return true;
if (el.isContentEditable === true) return true;
const id = el.id;
if (id === 'ag-usage-monitor-capsule' || id === 'ag-usage-monitor-portal') return true;
if (typeof el.hasAttribute === 'function' && el.hasAttribute('data-ag-i18n-ignore')) return true;
if (typeof el.getAttribute === 'function') {
if (el.getAttribute('contenteditable') === 'true') return true;
const tid = el.getAttribute('data-testid');
if (tid && SKIP_TESTIDS.has(tid)) return true;
}
const cls = el.className;
if (typeof cls === 'string' && cls) {
if (cls.indexOf(' ') === -1) {
if (SKIP_CLASSES.has(cls)) return true;
} else {
const parts = cls.split(/\s+/);
for (let i = 0; i < parts.length; i += 1) {
if (SKIP_CLASSES.has(parts[i])) return true;
}
}
}
return false;
}
function isSkippedElement(el) {
let cur = el;
while (cur && cur.nodeType === 1) {
if (isSkippedSelf(cur)) return true;
cur = cur.parentElement || (cur.parentNode && cur.parentNode.nodeType === 1 ? cur.parentNode : null);
}
return false;
}
function hasAsciiLetter(str) {
for (let i = 0; i < str.length; i += 1) {
const code = str.charCodeAt(i);
if ((code >= 65 && code <= 90) || (code >= 97 && code <= 122)) return true;
}
return false;
}
function isAsciiLetterCode(code) {
return (code >= 65 && code <= 90) || (code >= 97 && code <= 122);
}
function extractFirstWordLower(str) {
const m = str.match(/^[A-Za-z][A-Za-z0-9'-]*/);
return m ? m[0].toLowerCase() : '';
}
function extractLastWordLower(str) {
const m = str.match(/([A-Za-z]{2,})[.)?!'"\u201d\u2019…]*$/);
return m ? m[1].toLowerCase() : '';
}
function extractPatternLeadingWordLower(source) {
// 匹配以 `^Word` 开头的锚定模板(忽略反转义前的普通字母首词)
const m = String(source || '').match(/^\^([A-Za-z]{2,})/);
return m ? m[1].toLowerCase() : '';
}
function isNumericStartPattern(source) {
return /^\^(?:\\d|\(\\d|\\\(|\\\+|, \\\+)/.test(String(source || ''));
}
function extractPatternTrailingWordsLower(source) {
const s = String(source || '');
// 跳过结尾是通配捕获或字符集的模板,仅索引以固定英文词结尾的模板(兼容可选复数 s?)
const plural = s.match(/([A-Za-z]{2,})s\?(?:\\\)|\\\.|\?|!|"|'|…)*\$$/);
if (plural) {
const base = plural[1].toLowerCase();
return [base, `${base}s`];
}
const exact = s.match(/(?:^|[\s(\\/-])([A-Za-z]{2,})(?:\\\)|\\\.|\?|!|"|'|…)*\$$/);
if (exact) {
return [exact[1].toLowerCase()];
}
return [];
}
function computePatternSpecificity(source) {
const s = String(source || '');
let literalChars = 0;
let parenDepth = 0;
let inCharClass = false;
for (let i = 0; i < s.length; i += 1) {
const ch = s[i];
if (ch === '\\' && i + 1 < s.length) {
const next = s[i + 1];
if (parenDepth === 0 && !inCharClass && !/[dDwWsSbB]/.test(next)) {
literalChars += 1;
}
i += 1;
continue;
}
if (ch === '[' && !inCharClass) {
inCharClass = true;
continue;
}
if (ch === ']' && inCharClass) {
inCharClass = false;
continue;
}
if (inCharClass) continue;
if (ch === '(') {
parenDepth += 1;
continue;
}
if (ch === ')') {
if (parenDepth > 0) parenDepth -= 1;
continue;
}
if (parenDepth === 0 && !'^$.*+?{}|'.includes(ch)) {
literalChars += 1;
}
}
const looseWildcards = (s.match(/\(\.\+\?\)|\(\.\*\?\)/g) || []).length;
const typedCaptures = (s.match(/\\d\+/g) || []).length;
return literalChars * 4 + typedCaptures * 3 - looseWildcards * 6;
}
function compileMatchers(rawPayload) {
const exactMap = new Map();
const exactLowerMap = new Map();
const rawExact = rawPayload?.exact;
if (rawExact && typeof rawExact === 'object') {
for (const [k, v] of Object.entries(rawExact)) {
if (typeof v !== 'string' || !v) continue;
exactMap.set(k, v);
if (k.length <= 80) {
const lowerK = k.toLowerCase();
if (!exactLowerMap.has(lowerK)) {
exactLowerMap.set(lowerK, v);
}
}
}
}
const prefixBuckets = new Map();
const suffixBuckets = new Map();
const numericFallbacks = [];
const fallbackPatterns = [];
const rawPatterns = Array.isArray(rawPayload?.patterns) ? rawPayload.patterns : [];
for (let i = 0; i < rawPatterns.length; i += 1) {
const item = rawPatterns[i];
if (!item || typeof item.source !== 'string' || typeof item.replace !== 'string') continue;
try {
const compiled = {
re: new RegExp(item.source, typeof item.flags === 'string' ? item.flags : ''),
replace: item.replace,
hintLower: typeof item.hint === 'string' ? item.hint.toLowerCase() : '',
specificity: computePatternSpecificity(item.source),
sourceLen: item.source.length,
order: i,
};
const leadWord = extractPatternLeadingWordLower(item.source);
if (leadWord) {
let bucket = prefixBuckets.get(leadWord);
if (!bucket) {
bucket = [];
prefixBuckets.set(leadWord, bucket);
}
bucket.push(compiled);
} else if (isNumericStartPattern(item.source)) {
numericFallbacks.push(compiled);
} else {
const tailWords = extractPatternTrailingWordsLower(item.source);
if (tailWords.length > 0) {
for (let t = 0; t < tailWords.length; t += 1) {
const tw = tailWords[t];
let sBucket = suffixBuckets.get(tw);
if (!sBucket) {
sBucket = [];
suffixBuckets.set(tw, sBucket);
}
sBucket.push(compiled);
}
} else {
fallbackPatterns.push(compiled);
}
}
} catch {
// 忽略单条非法正则
}
}
const sortBySpecificity = (a, b) =>
b.specificity - a.specificity || b.sourceLen - a.sourceLen || a.order - b.order;
for (const bucket of prefixBuckets.values()) {
if (bucket.length > 1) bucket.sort(sortBySpecificity);
}
for (const bucket of suffixBuckets.values()) {
if (bucket.length > 1) bucket.sort(sortBySpecificity);
}
if (numericFallbacks.length > 1) numericFallbacks.sort(sortBySpecificity);
if (fallbackPatterns.length > 1) fallbackPatterns.sort(sortBySpecificity);
return {
exactMap,
exactLowerMap,
prefixBuckets,
suffixBuckets,
numericFallbacks,
fallbackPatterns,
missCache: new Set(),
};
}
function runPatternList(trimmed, lowerRef, list) {
if (!list || list.length === 0) return undefined;
for (let i = 0; i < list.length; i += 1) {
const pat = list[i];
if (pat.hintLower) {
if (lowerRef.value === null) lowerRef.value = trimmed.toLowerCase();
if (!lowerRef.value.includes(pat.hintLower)) continue;
}
if (pat.re.test(trimmed)) {
const next = trimmed.replace(pat.re, pat.replace);
if (next && next !== trimmed) return next;
}
}
return undefined;
}
function translateTextWithMatchers(rawText, matchers) {
if (typeof rawText !== 'string' || !rawText || rawText.length > MAX_EXACT_LEN) return null;
const normalizedRaw = rawText.includes('\r') ? rawText.replace(/\r\n/g, '\n') : rawText;
const trimmed = normalizedRaw.trim();
if (!trimmed || trimmed.length > MAX_EXACT_LEN) return null;
if (trimmed.length <= 160 && matchers.missCache.has(trimmed)) return null;
let translatedCore = matchers.exactMap.get(trimmed);
const hasLetter = translatedCore === undefined ? hasAsciiLetter(trimmed) : false;
let lowerRef = { value: null };
if (translatedCore === undefined && trimmed.length <= 80 && hasLetter) {
lowerRef.value = trimmed.toLowerCase();
translatedCore = matchers.exactLowerMap.get(lowerRef.value);
}
if (
translatedCore === undefined &&
trimmed.length <= MAX_PATTERN_LEN &&
!trimmed.includes('\n') &&
hasLetter
) {
const firstCode = trimmed.charCodeAt(0);
if (isAsciiLetterCode(firstCode)) {
const leadWord = extractFirstWordLower(trimmed);
if (leadWord) {
translatedCore = runPatternList(trimmed, lowerRef, matchers.prefixBuckets.get(leadWord));
}
} else if (matchers.numericFallbacks.length > 0) {
translatedCore = runPatternList(trimmed, lowerRef, matchers.numericFallbacks);
}
if (translatedCore === undefined) {
const tailWord = extractLastWordLower(trimmed);
if (tailWord) {
translatedCore = runPatternList(trimmed, lowerRef, matchers.suffixBuckets.get(tailWord));
}
}
if (translatedCore === undefined && matchers.fallbackPatterns.length > 0) {
translatedCore = runPatternList(trimmed, lowerRef, matchers.fallbackPatterns);
}
}
if (translatedCore === undefined || translatedCore === trimmed) {
if (trimmed.length <= 160) {
if (matchers.missCache.size >= MAX_MISS_CACHE) {
matchers.missCache.clear();
}
matchers.missCache.add(trimmed);
}
return null;
}
const startIdx = normalizedRaw.indexOf(trimmed);
const leading = startIdx > 0 ? normalizedRaw.slice(0, startIdx) : '';
const trailing =
startIdx + trimmed.length < normalizedRaw.length
? normalizedRaw.slice(startIdx + trimmed.length)
: '';
return leading + translatedCore + trailing;
}
let state = window[globalKey];
function restoreSubtree(scanRoot, targetState) {
if (!scanRoot) return;
if (typeof document.createTreeWalker === 'function') {
const textWalker = document.createTreeWalker(scanRoot, 4);
let node = textWalker.nextNode();
while (node) {
const rec = targetState.textRecords.get(node);
if (rec) {
if (node.nodeValue === rec.translated) {
node.nodeValue = rec.orig;
}
targetState.textRecords.delete(node);
}
node = textWalker.nextNode();
}
const elWalker = document.createTreeWalker(scanRoot, 1);
let el = elWalker.nextNode();
while (el) {
const attrMap = targetState.attrRecords.get(el);
if (attrMap) {
for (const [attrName, rec] of attrMap.entries()) {
if (el.getAttribute(attrName) === rec.translated) {
el.setAttribute(attrName, rec.orig);
}
}
targetState.attrRecords.delete(el);
}
if (el.shadowRoot && el.id !== 'ag-usage-monitor-capsule' && el.id !== 'ag-usage-monitor-portal') {
restoreSubtree(el.shadowRoot, targetState);
}
el = elWalker.nextNode();
}
} else {
const walkFallback = (cur) => {
if (!cur) return;
if (cur.nodeType === 3) {
const rec = targetState.textRecords.get(cur);
if (rec) {
if (cur.nodeValue === rec.translated) cur.nodeValue = rec.orig;
targetState.textRecords.delete(cur);
}
return;
}
if (cur.nodeType === 1 || cur.nodeType === 11) {
if (cur.nodeType === 1) {
const attrMap = targetState.attrRecords.get(cur);
if (attrMap) {
for (const [attrName, rec] of attrMap.entries()) {
if (cur.getAttribute?.(attrName) === rec.translated) {
cur.setAttribute(attrName, rec.orig);
}
}
targetState.attrRecords.delete(cur);
}
if (cur.shadowRoot && cur.id !== 'ag-usage-monitor-capsule' && cur.id !== 'ag-usage-monitor-portal') {
walkFallback(cur.shadowRoot);
}
}
const children = cur.childNodes || [];
for (let i = 0; i < children.length; i += 1) {
walkFallback(children[i]);
}
}
};
walkFallback(scanRoot);
}
}
function restoreAllTracked(targetState) {
if (!targetState) return;
targetState.isMutating = true;
try {
const scanRoot = document.body || document.documentElement;
restoreSubtree(scanRoot, targetState);
} finally {
targetState.isMutating = false;
}
}
if (state && state.bootId !== bootId) {
state.dispose?.();
state = null;
}
if (!state) {
const scheduleFrame =
typeof window.requestAnimationFrame === 'function'
? (cb) => ({ kind: 'raf', id: window.requestAnimationFrame(cb) })
: (cb) => ({ kind: 'timer', id: setTimeout(cb, 16) });
const cancelFrame = (handle) => {
if (!handle) return;
if (handle.kind === 'raf' && typeof window.cancelAnimationFrame === 'function') {
window.cancelAnimationFrame(handle.id);
} else {
clearTimeout(handle.id);
}
};
state = {
bootId,
revision: '',
locale: '',
depth: '',
matchers: {
exactMap: new Map(),
exactLowerMap: new Map(),
prefixBuckets: new Map(),
suffixBuckets: new Map(),
numericFallbacks: [],
fallbackPatterns: [],
missCache: new Set(),
},
textRecords: new WeakMap(),
attrRecords: new WeakMap(),
pendingNodes: new Set(),
fullRescanPending: false,
frameHandle: null,
watchdogTimer: null,
observer: null,
isMutating: false,
translatedCount: 0,
applyTextNode(node, parentVerifiedSafe = false) {
if (!node || node.nodeType !== 3) return;
if (!parentVerifiedSafe) {
const parent = node.parentElement || node.parentNode;
if (parent && isSkippedElement(parent)) return;
}
const curVal = node.nodeValue;
if (typeof curVal !== 'string' || !curVal) return;
const existing = state.textRecords.get(node);
let origVal = curVal;
if (existing) {
if (curVal === existing.translated) {
return;
}
origVal = curVal;
state.textRecords.delete(node);
}
const nextVal = translateTextWithMatchers(origVal, state.matchers);
if (nextVal !== null && nextVal !== origVal) {
state.textRecords.set(node, { orig: origVal, translated: nextVal });
state.isMutating = true;
try {
node.nodeValue = nextVal;
state.translatedCount += 1;
} finally {
state.isMutating = false;
}
}
},
applyElementAttrs(el, selfVerifiedSafe = false) {
if (!el || el.nodeType !== 1) return;
if (!selfVerifiedSafe && isSkippedElement(el)) return;
if (typeof el.getAttribute !== 'function' || typeof el.setAttribute !== 'function') return;
for (let i = 0; i < TRANSLATABLE_ATTRS.length; i += 1) {
const attrName = TRANSLATABLE_ATTRS[i];
const curVal = el.getAttribute(attrName);
if (!curVal) continue;
let attrMap = state.attrRecords.get(el);
const existing = attrMap?.get(attrName);
let origVal = curVal;
if (existing) {
if (curVal === existing.translated) continue;
origVal = curVal;
attrMap.delete(attrName);
}
const nextVal = translateTextWithMatchers(origVal, state.matchers);
if (nextVal !== null && nextVal !== origVal) {
if (!attrMap) {
attrMap = new Map();
state.attrRecords.set(el, attrMap);
}
attrMap.set(attrName, { orig: origVal, translated: nextVal });
state.isMutating = true;
try {
el.setAttribute(attrName, nextVal);
state.translatedCount += 1;
} finally {
state.isMutating = false;
}
}
}
},
walkSubtree(node, budgetRef, ancestorsVerifiedSafe = false) {
if (!node || budgetRef.remaining <= 0) return false;
if (node.nodeType === 3) {
budgetRef.remaining -= 1;
state.applyTextNode(node, ancestorsVerifiedSafe);
return true;
}
if (node.nodeType !== 1 && node.nodeType !== 11) return true;
if (node.nodeType === 1) {
if (ancestorsVerifiedSafe ? isSkippedSelf(node) : isSkippedElement(node)) return true;
budgetRef.remaining -= 1;
state.applyElementAttrs(node, true);
if (node.shadowRoot && node.id !== 'ag-usage-monitor-capsule' && node.id !== 'ag-usage-monitor-portal') {
state.walkSubtree(node.shadowRoot, budgetRef, true);
}
}
const children = node.childNodes || [];
for (let i = 0; i < children.length; i += 1) {
if (budgetRef.remaining <= 0) {
state.pendingNodes.add(children[i]);
return false;
}
if (!state.walkSubtree(children[i], budgetRef, true)) {
for (let j = i + 1; j < children.length; j += 1) {
state.pendingNodes.add(children[j]);
}
return false;
}
}
return true;
},
flushPending() {
state.frameHandle = null;
if (state.fullRescanPending) {
state.fullRescanPending = false;
state.pendingNodes.clear();
const scanRoot = document.body || document.documentElement;
if (scanRoot) state.pendingNodes.add(scanRoot);
}
const budgetRef = { remaining: FRAME_NODE_BUDGET };
const batch = Array.from(state.pendingNodes);
state.pendingNodes.clear();
for (let i = 0; i < batch.length; i += 1) {
if (budgetRef.remaining <= 0) {
for (let j = i; j < batch.length; j += 1) {
state.pendingNodes.add(batch[j]);
}
break;
}
state.walkSubtree(batch[i], budgetRef, false);
}
if (state.pendingNodes.size > 0 || state.fullRescanPending) {
state.scheduleFlush();
}
},
scheduleFlush() {
if (state.frameHandle) return;
state.frameHandle = scheduleFrame(() => state.flushPending());
},
enqueue(node) {
if (!node) return;
if (state.pendingNodes.size >= MAX_PENDING_NODES) {
state.fullRescanPending = true;
state.pendingNodes.clear();
} else {
state.pendingNodes.add(node);
}
state.scheduleFlush();
},
scanAllNow() {
const scanRoot = document.body || document.documentElement;
if (!scanRoot) return;
const budgetRef = { remaining: INITIAL_SCAN_BUDGET };
state.walkSubtree(scanRoot, budgetRef, true);
if (state.pendingNodes.size > 0) {
state.scheduleFlush();
}
},
touchWatchdog() {
clearTimeout(state.watchdogTimer);
state.watchdogTimer = setTimeout(() => {
state.dispose();
}, WATCHDOG_MS);
},
dispose() {
clearTimeout(state.watchdogTimer);
state.watchdogTimer = null;
cancelFrame(state.frameHandle);
state.frameHandle = null;
try {
state.observer?.disconnect?.();
} catch {
// 忽略断开异常
}
state.observer = null;
state.pendingNodes.clear();
state.fullRescanPending = false;
restoreAllTracked(state);
state.matchers.exactMap.clear();
state.matchers.exactLowerMap.clear();
state.matchers.prefixBuckets.clear();
state.matchers.suffixBuckets.clear();
state.matchers.numericFallbacks.length = 0;
state.matchers.fallbackPatterns.length = 0;
state.matchers.missCache.clear();
if (window[globalKey] === state) {
delete window[globalKey];
}
},
};
if (typeof window.MutationObserver === 'function') {
state.observer = new window.MutationObserver((mutations) => {
if (state.isMutating) return;
for (let i = 0; i < mutations.length; i += 1) {
const m = mutations[i];
if (m.type === 'characterData' || m.type === 'attributes') {
state.enqueue(m.target);
} else if (m.type === 'childList') {
const added = m.addedNodes || [];
for (let j = 0; j < added.length; j += 1) {
state.enqueue(added[j]);
}
}
}
});
state.observer.observe(root, {
subtree: true,
childList: true,
characterData: true,
attributes: true,
attributeFilter: TRANSLATABLE_ATTRS,
});
}
window[globalKey] = state;
}
state.touchWatchdog();
const nextRevision = String(payload?.revision || '');
if (state.revision !== nextRevision) {
if (state.revision) {
restoreAllTracked(state);
}
state.revision = nextRevision;
state.locale = String(payload?.locale || '');
state.depth = String(payload?.depth || '');
state.matchers = compileMatchers(payload);
state.translatedCount = 0;
state.scanAllNow();
}
return {
applied: true,
revision: state.revision,
locale: state.locale,
depth: state.depth,
translatedCount: state.translatedCount,
};
}
/**
* 轻量心跳表达式:若当前页面已加载同一 `bootId` 且同 `revision`,直接续期看门狗,无需重传大词表。
*/
export function createHostI18nHeartbeatExpression(bootId, revision) {
return `(() => {
try {
const st = typeof window !== 'undefined' ? window[${JSON.stringify(HOST_I18N_GLOBAL_KEY)}] : null;
if (!st || st.bootId !== ${JSON.stringify(bootId)} || st.revision !== ${JSON.stringify(revision)}) {
return { alive: false, needsApply: true };
}
st.touchWatchdog?.();
return { alive: true, needsApply: false, revision: st.revision, translatedCount: Number(st.translatedCount || 0) };
} catch {
return { alive: false, needsApply: true };
}
})()`;
}
/**
* 生成完整注入/切换词表表达式。
*/
export function createHostI18nApplyExpression(payload, bootId) {
return `(${applyHostI18nInPage.toString()})(${JSON.stringify(payload)}, ${JSON.stringify(bootId)}, ${JSON.stringify(HOST_I18N_GLOBAL_KEY)})`;
}
/**
* 生成停止翻译并无损还原原文的清理表达式。
*/
export function createHostI18nDisposeExpression() {
return `(() => {
try {
const st = typeof window !== 'undefined' ? window[${JSON.stringify(HOST_I18N_GLOBAL_KEY)}] : null;
if (!st) return { disposed: false };
st.dispose?.();
return { disposed: true };
} catch {
return { disposed: false };
}
})()`;
}
/**
* 在宿主页面按需执行:只读采集当前可见 UI 控件与说明中尚未翻译的英文短语
* (严格排除聊天用户正文、代码块、Diff、编辑器与隐私路径)。
*/
export function collectUntranslatedHostUiInPage(globalKey = '__AGUsageMonitorHostI18n') {
if (typeof window === 'undefined' || typeof document === 'undefined') {
return { count: 0, items: [] };
}
const root = document.body || document.documentElement;
if (!root) return { count: 0, items: [] };
const activeState = window[globalKey] || null;
const SKIP_TAGS = new Set([
'SCRIPT',
'STYLE',
'NOSCRIPT',
'CODE',
'PRE',
'TEXTAREA',
'SVG',
'MATH',
'KBD',
'SAMP',
'VAR',
'CANVAS',
'VIDEO',
'AUDIO',
'IFRAME',
]);
const SKIP_SELECTOR = [
'#ag-usage-monitor-capsule',
'#ag-usage-monitor-portal',
'[data-ag-i18n-ignore]',
'[contenteditable="true"]',
'.monaco-editor',
'.xterm',
'.cm-editor',
'.ProseMirror',
'.markdown-body',
'.prose',
'[data-testid="user-message-content"]',
'[data-testid="markdown-code-block-preview"]',
'[data-testid="markdown-frontmatter"]',
'[data-testid="automation-instructions-markdown"]',
'[data-testid="code-gutter"]',
'[data-testid="code-gutter-diff"]',
'[data-testid="diff-gutter-strip"]',
'[data-testid="artifact-pdf-view"]',
'.diff-line',
'.view-lines',
].join(',');
const UI_CONTROL_SELECTOR = [
'button',
'[role="button"]',
'[role="menuitem"]',
'[role="tab"]',
'[role="option"]',
'[role="switch"]',
'[role="checkbox"]',
'[role="radio"]',
'[role="heading"]',
'[role="tooltip"]',
'[role="status"]',
'label',
'legend',
'caption',
'h1',
'h2',
'h3',
'h4',
'h5',
'h6',
'th',
'dt',
'dd',
'p',
'span',
'nav a',
'[placeholder]',
'[title]',
'[aria-label]',
'[aria-description]',
].join(',');
const NON_LATIN_RE = /[\u3000-\u9fff\uac00-\ud7af\u0400-\u04ff]/;
const NOISE_RE =
/^(?:https?:\/\/|file:\/\/|\/|~\.|[A-Za-z]:\\|[\w.+-]+@[\w.-]+\.[a-z]{2,}$|[0-9a-f]{8}-[0-9a-f]{4}-|v?\d+(?:\.\d+)+$|\/[a-z0-9_-]+$|(?:gemini|claude|gpt|o[134])\b)/i;
function isSkipped(el) {
if (!el || el.nodeType !== 1) return false;
if (SKIP_TAGS.has(el.tagName)) return true;
if (el.isContentEditable === true) return true;
if (el.id === 'ag-usage-monitor-capsule' || el.id === 'ag-usage-monitor-portal') return true;
if (typeof el.closest === 'function') {
try {
if (el.closest(SKIP_SELECTOR)) return true;
} catch {
// 忽略选择器异常
}
}
return false;
}
const counts = new Map();
const kinds = new Map();
function recordCandidate(raw, kind) {
if (typeof raw !== 'string') return;
if (raw.includes('\n') || raw.includes('\r')) return;
const text = raw.trim();
if (text.length < 2 || text.length > 260) return;
if (!/[A-Za-z]{2,}/.test(text)) return;
if (NON_LATIN_RE.test(text)) return;
if (NOISE_RE.test(text)) return;
if (/^[0-9.,:%$+\-*/\s()[\]]+$/.test(text)) return;
if (activeState?.matchers?.exactMap?.has(text)) return;
if (text.length <= 80 && activeState?.matchers?.exactLowerMap?.has(text.toLowerCase())) return;
counts.set(text, (counts.get(text) || 0) + 1);
if (!kinds.has(text)) kinds.set(text, kind);
}
const elements =
typeof root.querySelectorAll === 'function' ? root.querySelectorAll(UI_CONTROL_SELECTOR) : [];
for (let i = 0; i < elements.length; i += 1) {
const el = elements[i];
if (isSkipped(el)) continue;
for (const attrName of ['placeholder', 'title', 'aria-label', 'aria-description']) {
const val = el.getAttribute?.(attrName);
const attrMap = activeState?.attrRecords?.get(el);
if (val && !(attrMap && attrMap.has(attrName))) {
recordCandidate(val, attrName);
}
}
const children = el.childNodes || [];
for (let j = 0; j < children.length; j += 1) {
const ch = children[j];
if (ch && ch.nodeType === 3) {
if (activeState?.textRecords?.has(ch)) continue;
recordCandidate(ch.nodeValue, 'text');
}
}
}
const items = Array.from(counts.entries())
.sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : 1))
.slice(0, 500)
.map(([text, count]) => ({ text, kind: kinds.get(text) || 'text', count }));
return { count: items.length, items };
}
/**
* 生成按需采集未命中 UI 词条的只读 CDP 表达式。
*/
export function createHostI18nCollectExpression() {
return `(${collectUntranslatedHostUiInPage.toString()})(${JSON.stringify(HOST_I18N_GLOBAL_KEY)})`;
}