返回 CodeWhale
check-locales.mjs
根目录 / web / scripts / check-locales.mjs
1 #!/usr/bin/env node
2 /**
3 * check-locales.mjs — CI gate against website dictionary drift (#3091).
4 *
5 * web/lib/i18n/dictionaries/en/ is the reference. Every other locale
6 * directory must define chrome.ts and home.ts with exactly the same
7 * top-level keys, and every `{token}` template placeholder in the English
8 * values must survive translation (call sites interpolate with `fill()`,
9 * so a dropped token renders literal braces on the page).
10 *
11 * This is the dependency-free half of the gate; web/lib/i18n/dictionaries.test.ts
12 * covers the same contract through the real module imports.
13 *
14 * Exits non-zero on any parity violation.
15 */
16 import { readFileSync, readdirSync, existsSync } from "node:fs";
17 import { fileURLToPath } from "node:url";
18 import { join } from "node:path";
19
20 const ROOT = fileURLToPath(new URL("..", import.meta.url));
21 const DICT_DIR = join(ROOT, "lib", "i18n", "dictionaries");
22 const REFERENCE = "en";
23 const FILES = ["chrome.ts", "home.ts"];
24 // Per-page dictionaries (#5337): optional per locale. English is the
25 // required reference; a locale that ships the file is held to the same
26 // key/token parity, and a locale without it falls back to English at
27 // lookup time — so absence is a valid state, never a failure.
28 const OPTIONAL_FILES = [
29 "project.ts",
30 "features.ts",
31 "docs-skills.ts",
32 "docs-claude-code.ts",
33 "docs-guide.ts",
34 "docs-shell.ts",
35 "docs-hooks.ts",
36 "docs-troubleshooting.ts",
37 "docs-configuration.ts",
38 "docs-fleet.ts",
39 "docs-mcp.ts",
40 "docs-modes.ts",
41 "docs-runtime-api.ts",
42 "docs-sandbox.ts",
43 "docs-subagents.ts",
44 "docs-web.ts",
45 "docs-auth.ts",
46 "docs-trust.ts",
47 "docs-work.ts",
48 "docs-pet.ts",
49 "docs-review.ts",
50 "docs-vocabulary.ts",
51 "states.ts",
52 "changelog.ts",
53 "legal-terms.ts",
54 "legal-privacy.ts",
55 "faq.ts",
56 "contribute.ts",
57 "constitution.ts",
58 "computer-use.ts",
59 ];
60
61 /** Top-level keys of the exported object literal (two-space indented `key:`). */
62 function extractKeys(source) {
63 return new Set(
64 [...source.matchAll(/^ {2}(\w+):/gm)].map((m) => m[1]),
65 );
66 }
67
68 const PLURAL_CATEGORIES = ["zero", "one", "two", "few", "many", "other"];
69
70 function extractPluralBlocks(source) {
71 const blocks = new Map();
72 let key = null;
73 for (const line of source.split("\n")) {
74 const open = line.match(/^ {2}(\w+): \{$/);
75 if (open) {
76 key = open[1];
77 blocks.set(key, new Map());
78 continue;
79 }
80 if (key && /^ {2}\},?$/.test(line)) {
81 key = null;
82 continue;
83 }
84 const form = key && line.match(/^ {4}(\w+): (".*"),?$/);
85 if (form) blocks.get(key).set(form[1], JSON.parse(form[2]));
86 }
87 for (const [name, forms] of blocks) {
88 if (![...forms.keys()].every((category) => PLURAL_CATEGORIES.includes(category))) blocks.delete(name);
89 }
90 return blocks;
91 }
92
93 function neededCategories(locale) {
94 const rules = new Intl.PluralRules(locale);
95 const reached = new Set(["other"]);
96 for (let n = 0; n <= 1000; n += 1) reached.add(rules.select(n));
97 return PLURAL_CATEGORIES.filter((category) => reached.has(category));
98 }
99
100 function checkPluralForms(locale, file, source) {
101 const needed = neededCategories(locale);
102 for (const [key, forms] of extractPluralBlocks(source)) {
103 const missing = needed.filter((category) => !forms.has(category));
104 if (missing.length) fail(`${locale}/${file}: ${key} lacks plural form(s) ${missing.join(", ")} that ${locale} needs`);
105 for (const [category, text] of forms) {
106 if (!text.includes("{n}")) fail(`${locale}/${file}: ${key}.${category} dropped {n}`);
107 }
108 }
109 }
110
111 function extractTokens(source) {
112 const tokens = new Map();
113 // Per-key token sets: walk `key: "…"` and array entries line by line.
114 let current = null;
115 for (const line of source.split("\n")) {
116 const keyMatch = line.match(/^ {2}(\w+):/);
117 if (keyMatch) current = keyMatch[1];
118 for (const t of line.matchAll(/\{(\w+)\}/g)) {
119 if (!current) continue;
120 if (!tokens.has(current)) tokens.set(current, new Set());
121 tokens.get(current).add(t[1]);
122 }
123 }
124 return tokens;
125 }
126
127 let failed = false;
128 const fail = (msg) => {
129 console.error(`[check-locales] FAIL — ${msg}`);
130 failed = true;
131 };
132
133 const locales = readdirSync(DICT_DIR, { withFileTypes: true })
134 .filter((d) => d.isDirectory() && d.name !== REFERENCE)
135 .map((d) => d.name)
136 .sort();
137
138 console.log(`[check-locales] reference ${REFERENCE}: ${FILES.join(", ")}`);
139 console.log(`[check-locales] locale dirs: ${locales.join(", ")}`);
140
141 /** Compare one locale file against the English reference (parity + tokens). */
142 function checkLocaleFile(locale, file, refKeys, refTokens) {
143 const path = join(DICT_DIR, locale, file);
144 const source = readFileSync(path, "utf8");
145 const keys = extractKeys(source);
146 const missing = [...refKeys].filter((k) => !keys.has(k));
147 const extra = [...keys].filter((k) => !refKeys.has(k));
148 if (missing.length) fail(`${locale}/${file}: missing keys: ${missing.join(", ")}`);
149 if (extra.length) fail(`${locale}/${file}: keys the reference lacks: ${extra.join(", ")}`);
150
151 checkPluralForms(locale, file, source);
152
153 const tokens = extractTokens(source);
154 for (const [key, refSet] of refTokens) {
155 const got = tokens.get(key) ?? new Set();
156 const dropped = [...refSet].filter((t) => !got.has(t));
157 if (dropped.length) {
158 fail(`${locale}/${file}: ${key} dropped template token(s): ${dropped.join(", ")}`);
159 }
160 }
161 if (!missing.length && !extra.length) {
162 console.log(`[check-locales] ${locale}/${file}: ${keys.size}/${refKeys.size} keys — complete`);
163 }
164 }
165
166 for (const file of [...FILES, ...OPTIONAL_FILES]) {
167 const required = FILES.includes(file);
168 const refPath = join(DICT_DIR, REFERENCE, file);
169 if (!existsSync(refPath)) {
170 fail(`${REFERENCE}/${file}: reference file missing`);
171 continue;
172 }
173 const refSource = readFileSync(refPath, "utf8");
174 const refKeys = extractKeys(refSource);
175 const refTokens = extractTokens(refSource);
176 checkPluralForms(REFERENCE, file, refSource);
177
178 for (const locale of locales) {
179 if (!existsSync(join(DICT_DIR, locale, file))) {
180 if (required) {
181 fail(`${locale}/${file}: missing (reference has ${refKeys.size} keys)`);
182 } else {
183 console.log(`[check-locales] ${locale}/${file}: absent — falls back to English`);
184 }
185 continue;
186 }
187 checkLocaleFile(locale, file, refKeys, refTokens);
188 }
189 }
190
191 if (failed) {
192 console.error("[check-locales] FAIL");
193 process.exit(1);
194 }
195 console.log("[check-locales] PASS");
196
196 lines Plain Text