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
+483
View File
@@ -0,0 +1,483 @@
#!/usr/bin/env node
/**
* @fileoverview Zero-dependency Antigravity Host I18n coverage auditor & live CDP drift scanner.
*
* Compares the latest extracted host UI strings (from Desktop `language_server.exe` JS + embedded
* feature-flag JSONC and Antigravity IDE `jetskiAgent/main.js`) against a compiled locale pack
* (`host-i18n/dist/packs/<locale>.json`), optionally also scanning live open Antigravity windows
* over read-only CDP to catch server-pushed runtime strings (e.g., model tags like `Leaving Soon`).
*
* Usage:
* node host-i18n/scripts/audit-host-i18n.mjs --locale zh-CN
* node host-i18n/scripts/audit-host-i18n.mjs --locale zh-CN --extract --live-cdp --emit-missing tmp/missing.json
* node host-i18n/scripts/audit-host-i18n.mjs --locale zh-CN --no-extract --strict
*/
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { homedir } from 'node:os';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import {
DEFAULT_CATALOG_OUT,
discoverLocalAntigravitySources,
runHostStringExtraction,
} from './extract-host-strings.mjs';
import { compileHostI18nRuntimePayload } from '../../sidecars/panel/backend/host-i18n/pack-manager.mjs';
import { createHostI18nCollectExpression } from '../../sidecars/panel/backend/host-i18n/runtime-translator.mjs';
import { resolveDevToolsPortCandidates } from '../../sidecars/panel/backend/window-bridge.mjs';
const __dirname = dirname(fileURLToPath(import.meta.url));
export const HOST_I18N_ROOT = resolve(__dirname, '..');
export const DEFAULT_IGNORE_PATH = join(HOST_I18N_ROOT, 'sources', 'ignore.json');
export function loadIgnoreLists(ignorePath = DEFAULT_IGNORE_PATH) {
if (!existsSync(ignorePath)) {
return { exact: new Set(), templates: new Set() };
}
const raw = JSON.parse(readFileSync(ignorePath, 'utf8'));
return {
exact: new Set(Array.isArray(raw?.exact) ? raw.exact : []),
templates: new Set(Array.isArray(raw?.templates) ? raw.templates : []),
};
}
function buildRuntimeMatcher(payload) {
const exactMap = new Map(Object.entries(payload.exact || {}));
const exactLowerMap = new Map();
for (const [k, v] of exactMap.entries()) {
if (k.length <= 80) {
const lk = k.toLowerCase();
if (!exactLowerMap.has(lk)) exactLowerMap.set(lk, v);
}
}
const patterns = [];
for (const rule of payload.patterns || []) {
try {
patterns.push({
source: rule.source,
re: new RegExp(rule.source, rule.flags || ''),
replace: rule.replace,
hintLower: String(rule.hint || '').toLowerCase(),
});
} catch {
// invalid regex caught separately
}
}
return {
match(text) {
const t = String(text || '').trim();
if (!t) return null;
if (exactMap.has(t)) return { kind: 'exact', value: exactMap.get(t) };
if (t.length <= 80) {
const lv = exactLowerMap.get(t.toLowerCase());
if (lv !== undefined) return { kind: 'exact-ci', value: lv };
}
if (t.length <= 360 && !t.includes('\n')) {
const lower = t.toLowerCase();
for (const p of patterns) {
if (p.hintLower && !lower.includes(p.hintLower)) continue;
if (p.re.test(t)) {
const next = t.replace(p.re, p.replace);
if (next && next !== t) return { kind: 'pattern', value: next, source: p.source };
}
}
}
return null;
},
};
}
function countCaptureGroups(source) {
let count = 0;
let inCharClass = false;
for (let i = 0; i < source.length; i += 1) {
const ch = source[i];
if (ch === '\\') {
i += 1;
continue;
}
if (ch === '[') {
inCharClass = true;
continue;
}
if (ch === ']') {
inCharClass = false;
continue;
}
if (inCharClass) continue;
if (ch === '(' && source[i + 1] !== '?') {
count += 1;
}
}
return count;
}
/**
* Pure coverage & integrity audit comparing a catalog against a compiled pack JSON.
*/
export function auditCatalogAgainstPack(catalog, packObj, ignoreLists = { exact: new Set(), templates: new Set() }) {
const lightPayload = compileHostI18nRuntimePayload(packObj, 'light');
const deepPayload = compileHostI18nRuntimePayload(packObj, 'deep');
const lightMatcher = buildRuntimeMatcher(lightPayload);
const deepMatcher = buildRuntimeMatcher(deepPayload);
const packPatternSources = new Set([
...(packObj?.base?.patterns || []).map((r) => r.source),
...(packObj?.modes?.light?.patterns || []).map((r) => r.source),
...(packObj?.modes?.deep?.patterns || []).map((r) => r.source),
]);
const missingExact = [];
const coveredExactByPattern = [];
let ignoredExactCount = 0;
for (const str of catalog.exact || []) {
if (ignoreLists.exact.has(str)) {
ignoredExactCount += 1;
continue;
}
const deepHit = deepMatcher.match(str);
const lightHit = lightMatcher.match(str);
if (!deepHit && !lightHit) {
missingExact.push(str);
} else if (deepHit?.kind === 'pattern' && !deepPayload.exact[str]) {
coveredExactByPattern.push({ text: str, translated: deepHit.value, by: deepHit.source });
}
}
const missingTemplates = [];
let ignoredTemplateCount = 0;
for (const tpl of catalog.templates || []) {
if (ignoreLists.templates.has(tpl.source)) {
ignoredTemplateCount += 1;
continue;
}
if (!packPatternSources.has(tpl.source)) {
// Also check if a slightly tightened boundary variant of this template already exists
// (e.g. `^Continue(.+?)$` tightened to `^Continue(\s+\(.+?\))$`).
const tightenedVariant = tpl.source.replace(/\(\.\+\?\)\$$/, '(\\s+\\(.+?\\))$');
if (packPatternSources.has(tightenedVariant)) continue;
missingTemplates.push(tpl);
}
}
// Audit pattern backreference integrity & redundant light===deep rules
const brokenPatterns = [];
const redundantModeExact = [];
for (const tierName of ['base', 'light', 'deep']) {
const list =
tierName === 'base'
? packObj?.base?.patterns || []
: packObj?.modes?.[tierName]?.patterns || [];
for (const rule of list) {
const capCount = countCaptureGroups(rule.source);
const refs = Array.from(String(rule.replace || '').matchAll(/\$(\d+)/g)).map((m) => Number(m[1]));
const badRef = refs.find((n) => n < 1 || n > capCount);
if (badRef !== undefined) {
brokenPatterns.push({ tier: tierName, source: rule.source, replace: rule.replace, badRef, capCount });
}
}
}
const lightExact = packObj?.modes?.light?.exact || {};
const deepExact = packObj?.modes?.deep?.exact || {};
for (const [k, v] of Object.entries(lightExact)) {
if (Object.prototype.hasOwnProperty.call(deepExact, k) && deepExact[k] === v) {
redundantModeExact.push(k);
}
}
return {
locale: packObj.locale,
version: packObj.version,
catalogCounts: {
exact: (catalog.exact || []).length,
templates: (catalog.templates || []).length,
},
packCounts: {
baseExact: Object.keys(packObj?.base?.exact || {}).length,
lightExact: Object.keys(lightExact).length,
deepExact: Object.keys(deepExact).length,
basePatterns: (packObj?.base?.patterns || []).length,
lightPatterns: (packObj?.modes?.light?.patterns || []).length,
deepPatterns: (packObj?.modes?.deep?.patterns || []).length,
},
ignoredExactCount,
ignoredTemplateCount,
missingExact,
missingTemplates,
coveredExactByPatternCount: coveredExactByPattern.length,
brokenPatterns,
redundantModeExact,
};
}
function discoverDevToolsPorts(explicitPorts = []) {
const candidates = resolveDevToolsPortCandidates({
platform: process.platform,
env: process.env,
homeDir: homedir(),
});
const ports = new Set(explicitPorts.filter((p) => Number.isInteger(p) && p > 0 && p < 65536));
const envPort = Number(process.env.USAGE_MONITOR_CDP_PORT || 0);
if (Number.isInteger(envPort) && envPort > 0 && envPort < 65536) ports.add(envPort);
for (const file of candidates) {
if (!existsSync(file)) continue;
try {
const firstLine = readFileSync(file, 'utf8').split(/\r?\n/)[0]?.trim();
const port = Number(firstLine);
if (Number.isInteger(port) && port > 0 && port < 65536) ports.add(port);
} catch {
// ignore unreadable port file
}
}
return Array.from(ports);
}
async function evalCdpOnce(wsUrl, expression, timeoutMs = 4000) {
const WS = globalThis.WebSocket;
if (typeof WS !== 'function') {
throw new Error('Global WebSocket unavailable in this Node runtime');
}
return new Promise((resolvePromise, rejectPromise) => {
const ws = new WS(wsUrl);
let settled = false;
const timer = setTimeout(() => {
if (settled) return;
settled = true;
try { ws.close(); } catch {}
rejectPromise(new Error(`CDP evaluate timeout (${timeoutMs}ms)`));
}, timeoutMs);
const finish = (err, val) => {
if (settled) return;
settled = true;
clearTimeout(timer);
try { ws.close(); } catch {}
if (err) rejectPromise(err);
else resolvePromise(val);
};
ws.addEventListener('open', () => {
ws.send(
JSON.stringify({
id: 1,
method: 'Runtime.evaluate',
params: { expression, returnByValue: true, awaitPromise: false },
})
);
});
ws.addEventListener('message', (ev) => {
try {
const msg = JSON.parse(String(ev.data || ''));
if (msg.id === 1) {
finish(null, msg?.result?.result?.value ?? null);
}
} catch (err) {
finish(err);
}
});
ws.addEventListener('error', () => finish(new Error('CDP WebSocket error')));
});
}
/**
* Connects read-only to running Antigravity CDP targets and collects any visible untranslated UI strings.
*/
export async function scanLiveCdpUntranslated({ ignoreLists = { exact: new Set() }, explicitPorts = [] } = {}) {
const ports = discoverDevToolsPorts(explicitPorts);
const merged = new Map();
let scannedTargets = 0;
for (const port of ports) {
let targets = [];
try {
const res = await fetch(`http://127.0.0.1:${port}/json/list`, {
signal: AbortSignal.timeout(2000),
});
if (!res.ok) continue;
targets = await res.json();
} catch {
continue;
}
const collectExpr = createHostI18nCollectExpression();
for (const t of Array.isArray(targets) ? targets : []) {
const url = String(t?.url || '');
const wsUrl = String(t?.webSocketDebuggerUrl || '');
if (!wsUrl) continue;
if (url.startsWith('vscode-file://') || url.includes('workbench.html') || url.startsWith('devtools://')) {
continue;
}
if (t.type !== 'page' && !(t.type === 'iframe' && url.includes('extensionView=true'))) {
continue;
}
try {
const res = await evalCdpOnce(wsUrl, collectExpr, 4000);
scannedTargets += 1;
for (const item of res?.items || []) {
const text = String(item?.text || '').trim();
if (!text || ignoreLists.exact.has(text)) continue;
const prev = merged.get(text);
merged.set(text, {
text,
kind: prev?.kind || item.kind || 'text',
count: (prev?.count || 0) + (Number(item.count) || 1),
});
}
} catch {
// Target closed or unavailable
}
}
}
return {
ports,
scannedTargets,
items: Array.from(merged.values()).sort((a, b) => b.count - a.count || (a.text < b.text ? -1 : 1)),
};
}
function parseCliArgs(argv) {
const opts = {
locale: 'zh-CN',
extract: false,
noExtract: false,
liveCdp: false,
cdpPorts: [],
strict: false,
emitMissing: '',
catalogPath: DEFAULT_CATALOG_OUT,
ignorePath: DEFAULT_IGNORE_PATH,
lsPaths: [],
jsPaths: [],
};
for (let i = 0; i < argv.length; i += 1) {
const arg = argv[i];
if (arg === '--locale' && argv[i + 1]) opts.locale = argv[++i];
else if (arg === '--extract') opts.extract = true;
else if (arg === '--no-extract') opts.noExtract = true;
else if (arg === '--live-cdp') opts.liveCdp = true;
else if (arg === '--cdp-port' && argv[i + 1]) opts.cdpPorts.push(Number(argv[++i]));
else if (arg === '--strict') opts.strict = true;
else if (arg === '--emit-missing' && argv[i + 1]) opts.emitMissing = resolve(argv[++i]);
else if (arg === '--catalog' && argv[i + 1]) opts.catalogPath = resolve(argv[++i]);
else if (arg === '--ignore' && argv[i + 1]) opts.ignorePath = resolve(argv[++i]);
else if (arg === '--ls' && argv[i + 1]) opts.lsPaths.push(resolve(argv[++i]));
else if (arg === '--js' && argv[i + 1]) opts.jsPaths.push(resolve(argv[++i]));
}
return opts;
}
if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
const cli = parseCliArgs(process.argv.slice(2));
let catalog;
const shouldExtract = cli.extract || (!cli.noExtract && !existsSync(cli.catalogPath));
if (shouldExtract) {
const lsPaths = [...cli.lsPaths];
const jsPaths = [...cli.jsPaths];
if (lsPaths.length === 0 && jsPaths.length === 0) {
const discovered = discoverLocalAntigravitySources();
lsPaths.push(...discovered.lsBinaries);
jsPaths.push(...discovered.jsFiles);
}
if (lsPaths.length === 0 && jsPaths.length === 0) {
console.error('[audit-host-i18n] No local Antigravity installation found. Pass --ls/--js or --no-extract.');
process.exit(1);
}
catalog = runHostStringExtraction({ lsPaths, jsPaths, outPath: cli.catalogPath });
} else {
catalog = JSON.parse(readFileSync(cli.catalogPath, 'utf8'));
}
const packPath = join(HOST_I18N_ROOT, 'dist', 'packs', `${cli.locale}.json`);
if (!existsSync(packPath)) {
console.error(`[audit-host-i18n] Compiled pack not found: ${packPath}. Run build-packs.mjs first.`);
process.exit(1);
}
const packObj = JSON.parse(readFileSync(packPath, 'utf8'));
const ignoreLists = loadIgnoreLists(cli.ignorePath);
const report = auditCatalogAgainstPack(catalog, packObj, ignoreLists);
let liveCdp = null;
if (cli.liveCdp) {
liveCdp = await scanLiveCdpUntranslated({ ignoreLists, explicitPorts: cli.cdpPorts });
}
console.log(
`[audit-host-i18n] Locale ${report.locale}@${report.version} vs catalog (${report.catalogCounts.exact} exact, ${report.catalogCounts.templates} templates)`
);
console.log(
` Pack size: base=${report.packCounts.baseExact}, light=${report.packCounts.lightExact}, deep=${report.packCounts.deepExact}, patterns=${report.packCounts.basePatterns}+${report.packCounts.lightPatterns}/${report.packCounts.deepPatterns}`
);
console.log(
` Ignored allowlist: ${report.ignoredExactCount} exact, ${report.ignoredTemplateCount} templates`
);
console.log(
` Missing static: ${report.missingExact.length} exact, ${report.missingTemplates.length} templates (covered via pattern: ${report.coveredExactByPatternCount})`
);
console.log(
` Integrity: ${report.brokenPatterns.length} broken pattern(s), ${report.redundantModeExact.length} redundant identical light/deep key(s)`
);
if (report.missingExact.length > 0) {
console.log(' Sample missing exact (first 25):');
for (const s of report.missingExact.slice(0, 25)) {
console.log(` - ${JSON.stringify(s)}`);
}
}
if (report.missingTemplates.length > 0) {
console.log(' Sample missing templates (first 15):');
for (const t of report.missingTemplates.slice(0, 15)) {
console.log(` - ${JSON.stringify(t.key)} (${t.source})`);
}
}
if (report.brokenPatterns.length > 0) {
console.log(' Broken pattern backreferences:');
for (const b of report.brokenPatterns) {
console.log(` - [${b.tier}] ${b.source} -> ${b.replace} ($${b.badRef} > ${b.capCount})`);
}
}
if (liveCdp) {
console.log(
` Live CDP scan: ports=[${liveCdp.ports.join(',')}], targets=${liveCdp.scannedTargets}, untranslated=${liveCdp.items.length}`
);
for (const item of liveCdp.items.slice(0, 25)) {
console.log(` - [${item.kind} x${item.count}] ${JSON.stringify(item.text)}`);
}
}
if (cli.emitMissing) {
mkdirSync(dirname(cli.emitMissing), { recursive: true });
writeFileSync(
cli.emitMissing,
JSON.stringify(
{
generatedAt: new Date().toISOString(),
locale: report.locale,
version: report.version,
missingExact: report.missingExact,
missingTemplates: report.missingTemplates,
liveCdpUntranslated: liveCdp ? liveCdp.items : [],
brokenPatterns: report.brokenPatterns,
redundantModeExact: report.redundantModeExact,
},
null,
2
) + '\n',
'utf8'
);
console.log(`[audit-host-i18n] Emitted missing report -> ${cli.emitMissing}`);
}
const hasGap =
report.missingExact.length > 0 ||
report.missingTemplates.length > 0 ||
report.brokenPatterns.length > 0 ||
(liveCdp && liveCdp.items.length > 0);
if (hasGap && cli.strict) {
process.exit(2);
}
}
+396
View File
@@ -0,0 +1,396 @@
#!/usr/bin/env node
/**
* @fileoverview Zero-dependency builder and validator for Antigravity Host I18n packs.
*
* Reads modular source dictionaries under `host-i18n/sources/<locale>/`, validates
* key conflicts, regex anchoring/safety, and schema integrity, and emits deterministic
* compressed packs under `host-i18n/dist/packs/<locale>.json` alongside
* `host-i18n/dist/manifest.json` with SHA-256 digests.
*
* Usage:
* node host-i18n/scripts/build-packs.mjs
* node host-i18n/scripts/build-packs.mjs --check
*/
import { createHash } from 'node:crypto';
import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
const __dirname = dirname(fileURLToPath(import.meta.url));
export const DEFAULT_HOST_I18N_ROOT = resolve(__dirname, '..');
export const PACK_SCHEMA_VERSION = 1;
export const SUPPORTED_DEPTHS = Object.freeze(['light', 'deep']);
const LOCALE_RE = /^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8}){0,2}$/;
const ALLOWED_REGEX_FLAGS_RE = /^[i]?$/;
const UNSAFE_NESTED_QUANTIFIER_RE = /\([^)]*[+*][^)]*\)[+*{]/;
function isPlainObject(val) {
return Boolean(val && typeof val === 'object' && !Array.isArray(val));
}
function sha256Hex(text) {
return createHash('sha256').update(String(text), 'utf8').digest('hex');
}
function sortRecordKeys(record) {
const out = {};
for (const key of Object.keys(record).sort((a, b) => (a < b ? -1 : a > b ? 1 : 0))) {
out[key] = record[key];
}
return out;
}
/**
* Validates a single anchored regex pattern rule for safety and determinism.
*
* @param {object} rule
* @param {string} contextLabel
* @returns {{ source: string, flags: string, replace: string, hint?: string }}
*/
export function validatePatternRule(rule, contextLabel = 'pattern') {
if (!isPlainObject(rule)) {
throw new Error(`${contextLabel}: pattern entry must be an object`);
}
const source = typeof rule.source === 'string' ? rule.source : '';
const flags = typeof rule.flags === 'string' ? rule.flags : '';
const replace = typeof rule.replace === 'string' ? rule.replace : '';
const hint = typeof rule.hint === 'string' ? rule.hint.trim() : '';
if (!source || source.length > 360) {
throw new Error(`${contextLabel}: pattern source must be 1..360 chars`);
}
if (!source.startsWith('^') || !source.endsWith('$')) {
throw new Error(`${contextLabel}: pattern "${source}" must be strictly anchored with ^ and $`);
}
if (!ALLOWED_REGEX_FLAGS_RE.test(flags)) {
throw new Error(`${contextLabel}: unsupported regex flags "${flags}" (only "" or "i" allowed)`);
}
if (UNSAFE_NESTED_QUANTIFIER_RE.test(source)) {
throw new Error(`${contextLabel}: potentially catastrophic nested quantifier in "${source}"`);
}
if (!replace) {
throw new Error(`${contextLabel}: replacement string cannot be empty`);
}
try {
// Compile to ensure valid JS RegExp syntax.
// eslint-disable-next-line no-new
new RegExp(source, flags);
} catch (err) {
throw new Error(`${contextLabel}: invalid RegExp "${source}": ${err.message}`);
}
return hint ? { source, flags, replace, hint } : { source, flags, replace };
}
function mergeExactBucket(target, bucket, fileLabel, bucketName) {
if (bucket === undefined) return;
if (!isPlainObject(bucket)) {
throw new Error(`${fileLabel}: "${bucketName}" must be a plain object`);
}
for (const [rawKey, rawVal] of Object.entries(bucket)) {
const key = String(rawKey).trim();
const val = typeof rawVal === 'string' ? rawVal.trim() : '';
if (!key) {
throw new Error(`${fileLabel}: empty key in "${bucketName}"`);
}
if (!val) {
throw new Error(`${fileLabel}: empty translation for "${key}" in "${bucketName}"`);
}
if (Object.prototype.hasOwnProperty.call(target, key)) {
throw new Error(`${fileLabel}: duplicate key "${key}" in "${bucketName}"`);
}
target[key] = val;
}
}
function patternLiteralSpecificity(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 sortPatternsBySpecificity(list) {
return [...list].sort((a, b) => {
const specDiff = patternLiteralSpecificity(b.source) - patternLiteralSpecificity(a.source);
if (specDiff !== 0) return specDiff;
const lenDiff = b.source.length - a.source.length;
if (lenDiff !== 0) return lenDiff;
return a.source < b.source ? -1 : a.source > b.source ? 1 : 0;
});
}
function mergePatternBucket(target, list, fileLabel, bucketName) {
if (list === undefined) return;
if (!Array.isArray(list)) {
throw new Error(`${fileLabel}: "${bucketName}" patterns must be an array`);
}
const seen = new Set(target.map((p) => `${p.flags}:${p.source}`));
for (let i = 0; i < list.length; i += 1) {
const rule = validatePatternRule(list[i], `${fileLabel}[${bucketName}#${i}]`);
const sig = `${rule.flags}:${rule.source}`;
if (seen.has(sig)) continue;
seen.add(sig);
target.push(rule);
}
}
/**
* Compiles one locale folder under `sources/<locale>/` into a validated pack object.
*
* @param {string} localeDir
* @param {string} folderLocale
*/
export function compileLocaleSourceDir(localeDir, folderLocale) {
if (!LOCALE_RE.test(folderLocale)) {
throw new Error(`Invalid locale folder name: "${folderLocale}"`);
}
const metaPath = join(localeDir, 'meta.json');
if (!existsSync(metaPath)) {
throw new Error(`Missing meta.json in ${localeDir}`);
}
const meta = JSON.parse(readFileSync(metaPath, 'utf8'));
if (!isPlainObject(meta)) {
throw new Error(`${metaPath}: meta.json must be a JSON object`);
}
const locale = String(meta.locale || '').trim();
if (locale !== folderLocale) {
throw new Error(`${metaPath}: meta.locale "${locale}" must match folder "${folderLocale}"`);
}
const name = String(meta.name || '').trim();
const nativeName = String(meta.nativeName || '').trim();
const version = String(meta.version || '').trim();
if (!name || !nativeName || !/^\d+\.\d+\.\d+(?:-[a-zA-Z0-9.-]+)?$/.test(version)) {
throw new Error(`${metaPath}: name, nativeName, and SemVer version are required`);
}
const baseExact = {};
const lightExact = {};
const deepExact = {};
const basePatterns = [];
const lightPatterns = [];
const deepPatterns = [];
const fileNames = readdirSync(localeDir)
.filter((f) => f.endsWith('.json') && f !== 'meta.json')
.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
if (fileNames.length === 0) {
throw new Error(`${localeDir}: at least one dictionary JSON file is required`);
}
for (const fileName of fileNames) {
const absPath = join(localeDir, fileName);
const parsed = JSON.parse(readFileSync(absPath, 'utf8'));
if (!isPlainObject(parsed)) {
throw new Error(`${absPath}: dictionary file must be a JSON object`);
}
const label = `${folderLocale}/${fileName}`;
if (fileName === 'patterns.json' || Array.isArray(parsed.base) || Array.isArray(parsed.light) || Array.isArray(parsed.deep)) {
mergePatternBucket(basePatterns, parsed.base, label, 'base');
mergePatternBucket(lightPatterns, parsed.light, label, 'light');
mergePatternBucket(deepPatterns, parsed.deep, label, 'deep');
} else {
mergeExactBucket(baseExact, parsed.base, label, 'base');
mergeExactBucket(lightExact, parsed.light, label, 'light');
mergeExactBucket(deepExact, parsed.deep, label, 'deep');
}
}
// Ensure light/deep overlays do not silently shadow base keys unless intentional:
// disallow exact key duplication between base and light/deep so layering stays unambiguous.
for (const key of Object.keys(lightExact)) {
if (Object.prototype.hasOwnProperty.call(baseExact, key)) {
throw new Error(`${folderLocale}: key "${key}" exists in both "base" and "light"`);
}
}
for (const key of Object.keys(deepExact)) {
if (Object.prototype.hasOwnProperty.call(baseExact, key)) {
throw new Error(`${folderLocale}: key "${key}" exists in both "base" and "deep"`);
}
}
const sortedBaseExact = sortRecordKeys(baseExact);
const sortedLightExact = sortRecordKeys(lightExact);
const sortedDeepExact = sortRecordKeys(deepExact);
const sortedBasePatterns = sortPatternsBySpecificity(basePatterns);
const sortedLightPatterns = sortPatternsBySpecificity(lightPatterns);
const sortedDeepPatterns = sortPatternsBySpecificity(deepPatterns);
const packObj = {
schemaVersion: PACK_SCHEMA_VERSION,
locale,
name,
nativeName,
version,
depths: [...SUPPORTED_DEPTHS],
base: {
exact: sortedBaseExact,
patterns: sortedBasePatterns,
},
modes: {
light: {
exact: sortedLightExact,
patterns: sortedLightPatterns,
},
deep: {
exact: sortedDeepExact,
patterns: sortedDeepPatterns,
},
},
};
const jsonText = JSON.stringify(packObj) + '\n';
const sha256 = sha256Hex(jsonText);
const bytes = Buffer.byteLength(jsonText, 'utf8');
return {
locale,
meta: {
locale,
name,
nativeName,
version,
file: `packs/${locale}.json`,
sha256,
bytes,
depths: [...SUPPORTED_DEPTHS],
stats: {
baseExact: Object.keys(sortedBaseExact).length,
lightExact: Object.keys(sortedLightExact).length,
deepExact: Object.keys(sortedDeepExact).length,
basePatterns: basePatterns.length,
lightPatterns: lightPatterns.length,
deepPatterns: deepPatterns.length,
},
},
packObj,
jsonText,
};
}
/**
* Builds or validates (`checkOnly: true`) all packs under `rootDir/sources` into `rootDir/dist`.
*
* @param {{ rootDir?: string, checkOnly?: boolean }} [options]
*/
export function buildAllHostI18nPacks({
rootDir = DEFAULT_HOST_I18N_ROOT,
checkOnly = false,
} = {}) {
const sourcesDir = join(rootDir, 'sources');
const distDir = join(rootDir, 'dist');
const packsOutDir = join(distDir, 'packs');
if (!existsSync(sourcesDir)) {
throw new Error(`Missing host-i18n sources directory: ${sourcesDir}`);
}
const localeFolders = readdirSync(sourcesDir, { withFileTypes: true })
.filter((entry) => entry.isDirectory() && !entry.name.startsWith('.'))
.map((entry) => entry.name)
.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
if (localeFolders.length === 0) {
throw new Error(`No locale directories found in ${sourcesDir}`);
}
const compiled = localeFolders.map((folder) =>
compileLocaleSourceDir(join(sourcesDir, folder), folder)
);
const manifestObj = {
schemaVersion: PACK_SCHEMA_VERSION,
packs: compiled.map((item) => item.meta),
};
const manifestText = JSON.stringify(manifestObj, null, 2) + '\n';
if (checkOnly) {
const manifestPath = join(distDir, 'manifest.json');
if (!existsSync(manifestPath)) {
throw new Error(`Check failed: missing ${manifestPath}`);
}
const diskManifest = readFileSync(manifestPath, 'utf8').replace(/\r\n/g, '\n');
if (diskManifest !== manifestText) {
throw new Error('Check failed: host-i18n/dist/manifest.json is out of date with sources');
}
for (const item of compiled) {
const packPath = join(packsOutDir, `${item.locale}.json`);
if (!existsSync(packPath)) {
throw new Error(`Check failed: missing ${packPath}`);
}
const diskPack = readFileSync(packPath, 'utf8').replace(/\r\n/g, '\n');
if (diskPack !== item.jsonText) {
throw new Error(`Check failed: ${packPath} is out of date with sources`);
}
if (sha256Hex(diskPack) !== item.meta.sha256) {
throw new Error(`Check failed: SHA-256 mismatch for ${packPath}`);
}
}
return { checked: true, manifest: manifestObj, packs: compiled };
}
mkdirSync(packsOutDir, { recursive: true });
const expectedFiles = new Set(compiled.map((item) => `${item.locale}.json`));
for (const existing of readdirSync(packsOutDir)) {
if (existing.endsWith('.json') && !expectedFiles.has(existing)) {
rmSync(join(packsOutDir, existing), { force: true });
}
}
for (const item of compiled) {
writeFileSync(join(packsOutDir, `${item.locale}.json`), item.jsonText, 'utf8');
}
writeFileSync(join(distDir, 'manifest.json'), manifestText, 'utf8');
return { checked: false, manifest: manifestObj, packs: compiled };
}
if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
const checkOnly = process.argv.includes('--check');
const res = buildAllHostI18nPacks({ checkOnly });
const summary = res.manifest.packs
.map(
(p) =>
`${p.locale}@${p.version} (base=${p.stats.baseExact}, light=${p.stats.lightExact}, deep=${p.stats.deepExact}, patterns=${p.stats.basePatterns + p.stats.lightPatterns + p.stats.deepPatterns}, ${(p.bytes / 1024).toFixed(1)} KB)`
)
.join(', ');
console.log(
checkOnly
? `[host-i18n] Check passed: ${summary}`
: `[host-i18n] Built ${res.manifest.packs.length} pack(s): ${summary}`
);
}
File diff suppressed because it is too large Load Diff
+290
View File
@@ -0,0 +1,290 @@
#!/usr/bin/env node
/**
* @fileoverview Conflict-free incremental merger for Antigravity Host I18n source dictionaries.
*
* Accepts a translation batch JSON (`exact`, `patterns`, `ignore`), routes entries into the right
* modular files under `host-i18n/sources/<locale>/` without duplicating keys across files or
* between `base` and `light`/`deep`, updates `host-i18n/sources/ignore.json`, optionally bumps
* `meta.json` SemVer, and rebuilds + verifies `host-i18n/dist/`.
*
* Input JSON format:
* {
* "exact": {
* "Light Theme": "浅色主题",
* "Queue": { "light": "Queue", "deep": "排队" }
* },
* "patterns": [
* { "source": "^Settings for conversations outside of (.+?)\\.$", "flags": "", "hint": "outside of", "light": "...", "deep": "..." }
* ],
* "ignore": {
* "exact": ["..."],
* "templates": ["^...$"]
* }
* }
*
* Usage:
* node host-i18n/scripts/merge-translations.mjs --locale zh-CN --in patch.json [--bump patch|minor]
*/
import { existsSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { buildAllHostI18nPacks } from './build-packs.mjs';
import { DEFAULT_IGNORE_PATH, HOST_I18N_ROOT } from './audit-host-i18n.mjs';
const __dirname = dirname(fileURLToPath(import.meta.url));
function sortKeys(obj) {
const out = {};
for (const k of Object.keys(obj).sort((a, b) => (a < b ? -1 : a > b ? 1 : 0))) {
out[k] = obj[k];
}
return out;
}
function readJson(filePath, fallback) {
if (!existsSync(filePath)) return fallback;
return JSON.parse(readFileSync(filePath, 'utf8'));
}
function writeJson(filePath, data) {
writeFileSync(filePath, JSON.stringify(data, null, 2) + '\n', 'utf8');
}
function bumpSemver(version, kind) {
const m = String(version || '').match(/^(\d+)\.(\d+)\.(\d+)(.*)$/);
if (!m) return version;
let [, major, minor, patch] = m;
major = Number(major);
minor = Number(minor);
patch = Number(patch);
if (kind === 'major') return `${major + 1}.0.0`;
if (kind === 'minor') return `${major}.${minor + 1}.0`;
if (kind === 'patch') return `${major}.${minor}.${patch + 1}`;
return version;
}
function pickShardFileName(key) {
const first = String(key || '').trim().charAt(0).toLowerCase();
if (first >= 'a' && first <= 'm') return 'ui-a-m.json';
return 'ui-n-z.json';
}
export function mergeHostI18nTranslations({
locale,
patch,
rootDir = HOST_I18N_ROOT,
ignorePath = DEFAULT_IGNORE_PATH,
bump = '',
rebuild = true,
} = {}) {
const localeDir = join(rootDir, 'sources', locale);
if (!existsSync(join(localeDir, 'meta.json'))) {
throw new Error(`Locale source directory not initialized: ${localeDir}`);
}
// Load all existing exact dictionary files and build key -> fileName index
const dictFileNames = readdirSync(localeDir)
.filter((f) => f.endsWith('.json') && f !== 'meta.json' && f !== 'patterns.json')
.sort();
const dictFiles = new Map();
const keyToFile = new Map();
for (const f of dictFileNames) {
const obj = readJson(join(localeDir, f), { base: {}, light: {}, deep: {} });
obj.base = obj.base || {};
obj.light = obj.light || {};
obj.deep = obj.deep || {};
dictFiles.set(f, obj);
for (const bucket of ['base', 'light', 'deep']) {
for (const k of Object.keys(obj[bucket])) {
keyToFile.set(k, f);
}
}
}
const ensureShard = (fileName) => {
if (!dictFiles.has(fileName)) {
dictFiles.set(fileName, { base: {}, light: {}, deep: {} });
}
return dictFiles.get(fileName);
};
let exactAdded = 0;
let exactUpdated = 0;
const dirtyFiles = new Set();
for (const [rawKey, rawVal] of Object.entries(patch?.exact || {})) {
const key = String(rawKey || '').trim();
if (!key) continue;
let lightVal = '';
let deepVal = '';
if (typeof rawVal === 'string') {
lightVal = rawVal.trim();
deepVal = rawVal.trim();
} else if (rawVal && typeof rawVal === 'object') {
lightVal = String(rawVal.light ?? rawVal.base ?? '').trim();
deepVal = String(rawVal.deep ?? rawVal.base ?? lightVal).trim();
}
if (!lightVal || !deepVal) continue;
const existingFile = keyToFile.get(key);
const targetFileName = existingFile || pickShardFileName(key);
const targetObj = ensureShard(targetFileName);
const existed =
Object.prototype.hasOwnProperty.call(targetObj.base, key) ||
Object.prototype.hasOwnProperty.call(targetObj.light, key) ||
Object.prototype.hasOwnProperty.call(targetObj.deep, key);
// Clear all three buckets for this key before writing to guarantee zero base/mode collisions
delete targetObj.base[key];
delete targetObj.light[key];
delete targetObj.deep[key];
if (lightVal === deepVal) {
targetObj.base[key] = lightVal;
} else {
targetObj.light[key] = lightVal;
targetObj.deep[key] = deepVal;
}
keyToFile.set(key, targetFileName);
dirtyFiles.add(targetFileName);
if (existed) exactUpdated += 1;
else exactAdded += 1;
}
for (const fileName of dirtyFiles) {
const obj = dictFiles.get(fileName);
const out = {};
if (Object.keys(obj.base).length > 0) out.base = sortKeys(obj.base);
if (Object.keys(obj.light).length > 0) out.light = sortKeys(obj.light);
if (Object.keys(obj.deep).length > 0) out.deep = sortKeys(obj.deep);
writeJson(join(localeDir, fileName), out);
}
// Merge patterns cleanly
let patternsAdded = 0;
let patternsUpdated = 0;
const rawPatterns = Array.isArray(patch?.patterns) ? patch.patterns : [];
if (rawPatterns.length > 0) {
const patPath = join(localeDir, 'patterns.json');
const patObj = readJson(patPath, { base: [], light: [], deep: [] });
patObj.base = Array.isArray(patObj.base) ? patObj.base : [];
patObj.light = Array.isArray(patObj.light) ? patObj.light : [];
patObj.deep = Array.isArray(patObj.deep) ? patObj.deep : [];
const sigOf = (r) => `${r.flags || ''}:${r.source}`;
const removeBySig = (sig) => {
let removed = false;
for (const tier of ['base', 'light', 'deep']) {
const before = patObj[tier].length;
patObj[tier] = patObj[tier].filter((r) => sigOf(r) !== sig);
if (patObj[tier].length !== before) removed = true;
}
return removed;
};
for (const item of rawPatterns) {
if (!item || typeof item.source !== 'string') continue;
const source = item.source.trim();
const flags = typeof item.flags === 'string' ? item.flags : '';
const hint = typeof item.hint === 'string' ? item.hint.trim() : '';
const lightRep = String(item.light ?? item.replace ?? '').trim();
const deepRep = String(item.deep ?? item.replace ?? lightRep).trim();
if (!source || !lightRep || !deepRep) continue;
const sig = `${flags}:${source}`;
const existed = removeBySig(sig);
const makeRule = (replace) => (hint ? { source, flags, replace, hint } : { source, flags, replace });
if (lightRep === deepRep) {
patObj.base.push(makeRule(lightRep));
} else {
patObj.light.push(makeRule(lightRep));
patObj.deep.push(makeRule(deepRep));
}
if (existed) patternsUpdated += 1;
else patternsAdded += 1;
}
writeJson(patPath, patObj);
}
// Merge verified ignore entries
let ignoreAdded = 0;
const ignoreExact = Array.isArray(patch?.ignore?.exact) ? patch.ignore.exact : [];
const ignoreTemplates = Array.isArray(patch?.ignore?.templates) ? patch.ignore.templates : [];
if (ignoreExact.length > 0 || ignoreTemplates.length > 0) {
const curIgnore = readJson(ignorePath, {
description: 'Verified non-UI code literals, vendor noise, and intentionally untranslated brand/model tokens excluded from missing-translation audits.',
exact: [],
templates: [],
});
const exSet = new Set(Array.isArray(curIgnore.exact) ? curIgnore.exact : []);
const tpSet = new Set(Array.isArray(curIgnore.templates) ? curIgnore.templates : []);
const before = exSet.size + tpSet.size;
for (const s of ignoreExact) if (typeof s === 'string' && s.trim()) exSet.add(s.trim());
for (const s of ignoreTemplates) if (typeof s === 'string' && s.trim()) tpSet.add(s.trim());
ignoreAdded = exSet.size + tpSet.size - before;
curIgnore.exact = Array.from(exSet).sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
curIgnore.templates = Array.from(tpSet).sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
writeJson(ignorePath, curIgnore);
}
let version = '';
const metaPath = join(localeDir, 'meta.json');
const meta = readJson(metaPath, {});
if (bump) {
meta.version = bumpSemver(meta.version, bump);
writeJson(metaPath, meta);
}
version = meta.version;
let buildResult = null;
if (rebuild) {
buildResult = buildAllHostI18nPacks({ rootDir, checkOnly: false });
buildAllHostI18nPacks({ rootDir, checkOnly: true });
}
return {
locale,
version,
exactAdded,
exactUpdated,
patternsAdded,
patternsUpdated,
ignoreAdded,
buildResult,
};
}
function parseCliArgs(argv) {
const opts = { locale: 'zh-CN', inPath: '', bump: '', noBuild: false };
for (let i = 0; i < argv.length; i += 1) {
const arg = argv[i];
if (arg === '--locale' && argv[i + 1]) opts.locale = argv[++i];
else if (arg === '--in' && argv[i + 1]) opts.inPath = resolve(argv[++i]);
else if (arg === '--bump' && argv[i + 1]) opts.bump = argv[++i];
else if (arg === '--no-build') opts.noBuild = true;
}
return opts;
}
if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
const cli = parseCliArgs(process.argv.slice(2));
if (!cli.inPath || !existsSync(cli.inPath)) {
console.error('[merge-translations] Required --in <patch.json> file not found.');
process.exit(1);
}
const patch = JSON.parse(readFileSync(cli.inPath, 'utf8'));
const res = mergeHostI18nTranslations({
locale: cli.locale,
patch,
bump: cli.bump,
rebuild: !cli.noBuild,
});
console.log(
`[merge-translations] Merged into ${res.locale}@${res.version}: exact +${res.exactAdded}/~${res.exactUpdated}, patterns +${res.patternsAdded}/~${res.patternsUpdated}, ignore +${res.ignoreAdded}`
);
}