返回 CodeWhale
dictionaries.test.ts
根目录 / web / lib / i18n / dictionaries.test.ts
1 import { existsSync } from "node:fs";
2 import { describe, expect, it } from "vitest";
3 import {
4 DICTIONARY_LOCALES,
5 EN_CHROME,
6 EN_DOCS_GUIDE,
7 EN_DOCS_HOOKS,
8 EN_DOCS_MCP,
9 EN_DOCS_RUNTIME_API,
10 EN_DOCS_SANDBOX,
11 EN_DOCS_SUBAGENTS,
12 EN_DOCS_WEB,
13 EN_DOCS_WORK,
14 EN_DOCS_PET,
15 EN_DOCS_AUTH,
16 EN_DOCS_TRUST,
17 EN_DOCS_FIRST_TIME,
18 EN_DOCS_REVIEW,
19 EN_DOCS_VOCABULARY,
20 EN_COMPUTER_USE,
21 EN_CHANGELOG,
22 EN_DOCS_SHELL,
23 EN_DOCS_TROUBLESHOOTING,
24 EN_FAQ,
25 EN_HOME,
26 EN_LEGAL_PRIVACY,
27 EN_LEGAL_TERMS,
28 EN_CONTRIBUTE,
29 EN_CONSTITUTION,
30 fill,
31 getChrome,
32 getDocsGuide,
33 getDocsHooks,
34 getDocsMcp,
35 getDocsRuntimeApi,
36 getDocsSandbox,
37 getDocsSubagents,
38 getDocsWeb,
39 getDocsWork,
40 getDocsPet,
41 getDocsAuth,
42 getDocsTrust,
43 getDocsFirstTime,
44 getComputerUse,
45 getChangelog,
46 getDocsShell,
47 getDocsTroubleshooting,
48 getDocsConfiguration,
49 getDocsFleet,
50 getDocsModes,
51 getDocsReview,
52 getDocsVocabulary,
53 getFaq,
54 getHome,
55 getLegalPrivacy,
56 getLegalTerms,
57 getContribute,
58 getConstitution,
59 pickText,
60 pickTextLocale,
61 splitToken,
62 } from "./dictionaries";
63 import { locales, partialLocales } from "./config";
64 import type { ChromeDict, HomeDict } from "./dictionaries/types";
65
66 /**
67 * Keys whose value is a mark, a proper noun, or a formatting tag rather
68 * than prose — a locale sharing English's value here is correct, not a
69 * missing translation.
70 */
71 const NON_PROSE_KEYS = new Set([
72 "dateLocale",
73 ]);
74
75 /** Chrome keys that are real sentences/labels and must be translated. */
76 const CHROME_PROSE_KEYS = [
77 "skipToContent",
78 "navDocs",
79 "navSignIn",
80 "translationMachineDraft",
81 "navPrimaryAria",
82 "navHomeAria",
83 "menuOpen",
84 "menuClose",
85 "themeAria",
86 "themeTitle",
87 "footerProduct",
88 "footerProject",
89 "footerGuide",
90 "footerCanonicalSource",
91 "footerReleasesLink",
92 "switcherLabel",
93 "switcherSwitchTo",
94 "partialBadge",
95 ] as const satisfies readonly (keyof ChromeDict)[];
96
97 /**
98 * Locale/key pairs whose English-identical value is a native loanword in
99 * that locale, not a missing translation — asserted below so the equality
100 * is deliberate and visible. German "Community" matches the TUI pack
101 * (crates/tui/locales/de.json: "Community & Mitwirken").
102 */
103 const CHROME_LOANWORDS: Record<string, readonly string[]> = {};
104
105 /** Home keys that are real sentences and must be translated. */
106 const HOME_PROSE_KEYS = [
107 "metaTitle",
108 "metaDescription",
109 "heroTitle",
110 "heroTitleLead",
111 "heroIntro",
112 "readTheCode",
113 "installNote",
114 "captionReleased",
115 "captureFrameNoPosture",
116 "sectionModelHeading",
117 "sectionModelBody",
118 "sectionControlHeading",
119 "sectionControlBody",
120 "sectionAgentsHeading",
121 "sectionAgentsBody",
122 "agentsRolesLabel",
123 "agentRoleExplore",
124 "agentRoleImplement",
125 "agentRoleReviewer",
126 "agentsLink",
127 "directionShotAlt",
128 "directionShotCaption",
129 "directionShotLink",
130 "factRust",
131 "factLicense",
132 "sectionDirectionHeading",
133 "sectionDirectionBody",
134 "sectionOpenHeading",
135 "sectionOpenBody",
136 "sectionStartHeading",
137 "sectionStartBody",
138 "mapHeading",
139 "mapStateReleased",
140 "mapStateDeveloping",
141 "mapStateInviteOnly",
142 "mapStateBeingBuilt",
143 "mapTerminal",
144 "mapTerminalSentence",
145 "mapLocalBrowser",
146 "mapLocalBrowserSentence",
147 "mapManyAgents",
148 "mapManyAgentsSentence",
149 "mapDesktop",
150 "mapDesktopSentence",
151 "mapCloud",
152 "mapCloudSentence",
153 "mapOneSession",
154 "mapOneSessionSentence",
155 "getCodewhale",
156 "heroInstallAria",
157 "shotPreview",
158 "frameSummaryPrompt",
159 "frameSummaryEdit",
160 "frameSummaryApproval",
161 "frameSummaryResult",
162 "frameSummaryProvider",
163 "frameSummaryReceipt",
164 ] as const satisfies readonly (keyof HomeDict)[];
165
166 function templateTokens(value: string): string[] {
167 return [...value.matchAll(/\{(\w+)\}/g)].map((m) => m[1]).sort();
168 }
169
170 function flattenStrings(dict: object): Record<string, string> {
171 const out: Record<string, string> = {};
172 for (const [key, value] of Object.entries(dict)) {
173 if (typeof value === "string") {
174 out[key] = value;
175 } else if (Array.isArray(value)) {
176 value.forEach((row: string | string[], i: number) => {
177 if (typeof row === "string") {
178 out[`${key}[${i}]`] = row;
179 } else {
180 row.forEach((cell, j) => {
181 out[`${key}[${i}][${j}]`] = cell;
182 });
183 }
184 });
185 }
186 }
187 return out;
188 }
189
190 describe("website dictionaries", () => {
191 it("cover every routed locale except the English reference", () => {
192 expect([...DICTIONARY_LOCALES].sort()).toEqual(
193 [
194 "zh", "es", "id", "ja", "ko", "pt-BR", "ru", "uk", "vi",
195 "fr", "de", "ca", "hi", "tr", "it", "pl", "ar",
196 ].sort(),
197 );
198 // Chinese is dictionary-backed like every other locale — no inline
199 // en/zh special case survives in the page/component sources (#4934).
200 expect(DICTIONARY_LOCALES).toContain("zh");
201 // Every routed locale either has its own dictionary or *is* English.
202 for (const locale of locales) {
203 expect(
204 locale === "en" || DICTIONARY_LOCALES.includes(locale),
205 `${locale} has no dictionary`,
206 ).toBe(true);
207 }
208 // Every partial locale is dictionary-backed, so the partial badge marks
209 // untranslated page bodies — never untranslated chrome.
210 for (const locale of partialLocales) {
211 expect(DICTIONARY_LOCALES, `${locale} partial pack`).toContain(locale);
212 }
213 });
214
215 it("holds every dictionary to exact key parity with the English reference", () => {
216 const enChromeKeys = Object.keys(EN_CHROME).sort();
217 const enHomeKeys = Object.keys(EN_HOME).sort();
218 for (const locale of DICTIONARY_LOCALES) {
219 expect(Object.keys(getChrome(locale)).sort(), `${locale} chrome keys`).toEqual(
220 enChromeKeys,
221 );
222 expect(Object.keys(getHome(locale)).sort(), `${locale} home keys`).toEqual(
223 enHomeKeys,
224 );
225 }
226 });
227
228 it("preserves {token} template placeholders through translation", () => {
229 const enChromeTokens = flattenStrings(EN_CHROME);
230 const enHomeTokens = flattenStrings(EN_HOME);
231 for (const locale of DICTIONARY_LOCALES) {
232 const chrome = flattenStrings(getChrome(locale));
233 const home = flattenStrings(getHome(locale));
234 for (const key of Object.keys(enChromeTokens)) {
235 expect(templateTokens(chrome[key]), `${locale} chrome ${key}`).toEqual(
236 templateTokens(enChromeTokens[key]),
237 );
238 }
239 for (const key of Object.keys(enHomeTokens)) {
240 expect(templateTokens(home[key]), `${locale} home ${key}`).toEqual(
241 templateTokens(enHomeTokens[key]),
242 );
243 }
244 }
245 });
246
247 it("holds every shipped page dictionary to key parity and English fallback (#5337)", () => {
248 const enKeys = Object.keys(EN_DOCS_GUIDE).sort();
249 for (const locale of [...DICTIONARY_LOCALES, "fr", "und"]) {
250 // Page dictionaries are optional per locale: whatever getDocsGuide
251 // resolves — the locale's own file or the English fallback — must
252 // carry the exact reference shape, so a page never sees a missing key.
253 expect(Object.keys(getDocsGuide(locale)).sort(), `${locale} docs-guide keys`).toEqual(
254 enKeys,
255 );
256 }
257 // zh ships a real translation, not an English pass-through.
258 expect(getDocsGuide("zh").overviewTitle).not.toBe(EN_DOCS_GUIDE.overviewTitle);
259 // The wave-2 locales ship docs-guide too, translated rather than passed through.
260 for (const locale of ["fr", "de", "ca", "hi", "tr", "it", "pl", "ar"]) {
261 expect(getDocsGuide(locale).overviewTitle, `${locale} docs-guide`).not.toBe(
262 EN_DOCS_GUIDE.overviewTitle,
263 );
264 }
265 // A locale without the file falls back to the English reference object.
266 expect(getDocsGuide("ja")).toBe(EN_DOCS_GUIDE);
267 });
268
269 it("holds the docs shell dictionary to the same contract (#5337)", () => {
270 const enKeys = Object.keys(EN_DOCS_SHELL).sort();
271 for (const locale of [...DICTIONARY_LOCALES, "fr", "und"]) {
272 expect(Object.keys(getDocsShell(locale)).sort(), `${locale} docs-shell keys`).toEqual(
273 enKeys,
274 );
275 }
276 // zh ships a real translation, not an English pass-through.
277 expect(getDocsShell("zh").heroTitle).not.toBe(EN_DOCS_SHELL.heroTitle);
278 // Every other locale renders the English shell today, exactly as the
279 // `isZh` ternaries in docs/layout.tsx did before the move.
280 for (const locale of ["ja", "fr", "ar", "und"]) {
281 expect(getDocsShell(locale), `${locale} docs-shell`).toBe(EN_DOCS_SHELL);
282 }
283 });
284
285 it("holds the docs page-body dictionaries to the same contract (#5337)", () => {
286 for (const [label, get, reference] of [
287 ["docs-hooks", getDocsHooks, EN_DOCS_HOOKS],
288 ["docs-troubleshooting", getDocsTroubleshooting, EN_DOCS_TROUBLESHOOTING],
289 ["docs-runtime-api", getDocsRuntimeApi, EN_DOCS_RUNTIME_API],
290 ["docs-sandbox", getDocsSandbox, EN_DOCS_SANDBOX],
291 ["docs-subagents", getDocsSubagents, EN_DOCS_SUBAGENTS],
292 ["docs-mcp", getDocsMcp, EN_DOCS_MCP],
293 ["docs-web", getDocsWeb, EN_DOCS_WEB],
294 ["docs-work", getDocsWork, EN_DOCS_WORK],
295 ["docs-pet", getDocsPet, EN_DOCS_PET],
296 ["docs-auth", getDocsAuth, EN_DOCS_AUTH],
297 ["docs-trust", getDocsTrust, EN_DOCS_TRUST],
298 ["docs-first-time", getDocsFirstTime, EN_DOCS_FIRST_TIME],
299 ["docs-review", getDocsReview, EN_DOCS_REVIEW],
300 ["docs-vocabulary", getDocsVocabulary, EN_DOCS_VOCABULARY],
301 ["changelog", getChangelog, EN_CHANGELOG],
302 ["legal-terms", getLegalTerms, EN_LEGAL_TERMS],
303 ["legal-privacy", getLegalPrivacy, EN_LEGAL_PRIVACY],
304 ["faq", getFaq, EN_FAQ],
305 ["contribute", getContribute, EN_CONTRIBUTE],
306 ["constitution", getConstitution, EN_CONSTITUTION],
307 ] as const) {
308 const enKeys = Object.keys(reference).sort();
309 for (const locale of [...DICTIONARY_LOCALES, "fr", "und"]) {
310 expect(Object.keys(get(locale)).sort(), `${locale} ${label} keys`).toEqual(enKeys);
311 }
312 // zh ships a real translation, not an English pass-through. The probe is
313 // `metaTitle` rather than `overviewTitle` because docs/mcp's heading is
314 // the code-owned literal `MCP` and stays in the page.
315 expect(get("zh").metaTitle, `zh ${label}`).not.toBe(reference.metaTitle);
316 // Contribute ships in every routed locale; the other page
317 // dictionaries still render English outside en and zh.
318 const translated = label === "contribute";
319 for (const locale of ["ja", "fr", "ar"]) {
320 if (translated) expect(get(locale).metaTitle, `${locale} ${label}`).not.toBe(reference.metaTitle);
321 else expect(get(locale), `${locale} ${label}`).toBe(reference);
322 }
323 expect(get("und"), `und ${label}`).toBe(reference);
324 }
325 });
326
327 it("ships the Computer Use page dictionary for every routed locale", () => {
328 const enKeys = Object.keys(EN_COMPUTER_USE).sort();
329 for (const locale of [...DICTIONARY_LOCALES, "und"]) {
330 expect(Object.keys(getComputerUse(locale)).sort(), `${locale} computer-use keys`).toEqual(enKeys);
331 expect(getComputerUse(locale).steps, `${locale} computer-use steps`).toHaveLength(3);
332 }
333 // The download page is translated for every routed locale, not passed
334 // through: each dictionary locale resolves its own object with its own
335 // primary-button label; only an unknown locale gets the English reference.
336 for (const locale of DICTIONARY_LOCALES) {
337 expect(getComputerUse(locale), `${locale} computer-use`).not.toBe(EN_COMPUTER_USE);
338 expect(getComputerUse(locale).download, `${locale} computer-use download`).not.toBe(EN_COMPUTER_USE.download);
339 }
340 expect(getComputerUse("und")).toBe(EN_COMPUTER_USE);
341 });
342
343 it("keeps every docs task page aligned between English and Chinese", () => {
344 const routeExists = (href: string) =>
345 existsSync(new URL(`../../app/[locale]${href.split("#")[0]}/page.tsx`, import.meta.url));
346 const internalLinks = (text: string) =>
347 [...text.matchAll(/\]\((\/[^)\s]*)\)/g)].map((m) => m[1]);
348 for (const [label, get] of [
349 ["docs-auth", getDocsAuth],
350 ["docs-configuration", getDocsConfiguration],
351 ["docs-fleet", getDocsFleet],
352 ["docs-hooks", getDocsHooks],
353 ["docs-mcp", getDocsMcp],
354 ["docs-modes", getDocsModes],
355 ["docs-review", getDocsReview],
356 ["docs-runtime-api", getDocsRuntimeApi],
357 ["docs-sandbox", getDocsSandbox],
358 ["docs-subagents", getDocsSubagents],
359 ["docs-troubleshooting", getDocsTroubleshooting],
360 ["docs-trust", getDocsTrust],
361 ["docs-first-time", getDocsFirstTime],
362 ["docs-web", getDocsWeb],
363 ["docs-work", getDocsWork],
364 ["docs-pet", getDocsPet],
365 ] as const) {
366 const en = get("en");
367 const zh = get("zh");
368 expect(zh, label).not.toBe(en);
369 // Same sections, in the same order, with the same block shapes.
370 expect(zh.sections.map((x) => x.id), label).toEqual(en.sections.map((x) => x.id));
371 en.sections.forEach((section, i) => {
372 const other = zh.sections[i].blocks;
373 expect(other.map((b) => Object.keys(b)[0]), `${label}#${section.id}`).toEqual(
374 section.blocks.map((b) => Object.keys(b)[0]),
375 );
376 section.blocks.forEach((block, j) => {
377 const peer = other[j];
378 // Commands are shown verbatim: a translation never edits one.
379 if ("code" in block && "code" in peer) {
380 expect(peer.code, `${label}#${section.id} code`).toBe(block.code);
381 }
382 if ("rows" in block && "rows" in peer) {
383 expect(peer.rows.length, `${label}#${section.id} rows`).toBe(block.rows.length);
384 if (block.codeTerms) {
385 expect(peer.rows.map(([term]) => term)).toEqual(block.rows.map(([term]) => term));
386 }
387 }
388 if ("steps" in block && "steps" in peer) {
389 expect(peer.steps.length, `${label}#${section.id} steps`).toBe(block.steps.length);
390 }
391 if ("list" in block && "list" in peer) {
392 expect(peer.list.length, `${label}#${section.id} list`).toBe(block.list.length);
393 }
394 });
395 });
396 expect(zh.next.map((n) => n.href), label).toEqual(en.next.map((n) => n.href));
397 // Every internal link — inline or "next" — lands on a real page.
398 for (const dict of [en, zh]) {
399 const text = JSON.stringify(dict.sections);
400 for (const href of [...internalLinks(text), ...dict.next.map((n) => n.href)]) {
401 expect(routeExists(href), `${label}: ${href}`).toBe(true);
402 }
403 }
404 }
405 });
406
407 it("pickText selects the locale side of legacy { en, zh } pairs", () => {
408 const pair = { en: "English", zh: "中文" };
409 expect(pickText(pair, "zh")).toBe("中文");
410 expect(pickText(pair, "en")).toBe("English");
411 expect(pickText(pair, "ja"), "non-zh locales read the English side").toBe("English");
412 expect(pickTextLocale("zh")).toBe("zh");
413 for (const locale of ["en", "ja", "ar"]) expect(pickTextLocale(locale)).toBe("en");
414 });
415
416 it("falls back to the English dictionary for unrouted locales — no missing markers", () => {
417 for (const key of Object.keys(EN_CHROME) as (keyof ChromeDict)[]) {
418 expect(getChrome("xx")[key]).toBe(EN_CHROME[key]);
419 expect(getChrome("en")[key]).toBe(EN_CHROME[key]);
420 }
421 for (const key of Object.keys(EN_HOME) as (keyof HomeDict)[]) {
422 expect(getHome("xx")[key]).toEqual(EN_HOME[key]);
423 }
424 });
425
426 it("has no empty strings anywhere", () => {
427 for (const locale of ["en", ...DICTIONARY_LOCALES]) {
428 for (const [key, value] of Object.entries(flattenStrings(getChrome(locale)))) {
429 expect(value.trim().length, `${locale} chrome ${key}`).toBeGreaterThan(0);
430 }
431 for (const [key, value] of Object.entries(flattenStrings(getHome(locale)))) {
432 expect(value.trim().length, `${locale} home ${key}`).toBeGreaterThan(0);
433 }
434 }
435 });
436
437 it("keeps the Cyrillic packs script-pure (no cross-leakage, no mixed copy)", () => {
438 const cyrillic = /[Ѐ-ӿ]/;
439 for (const [key, value] of Object.entries(flattenStrings(getChrome("uk")))) {
440 expect(value, `uk chrome ${key}`).not.toMatch(/[ыэъЫЭЪ]/);
441 void cyrillic;
442 }
443 for (const [key, value] of Object.entries(flattenStrings(getHome("uk")))) {
444 expect(value, `uk home ${key}`).not.toMatch(/[ыэъЫЭЪ]/);
445 }
446 for (const [key, value] of Object.entries(flattenStrings(getChrome("ru")))) {
447 expect(value, `ru chrome ${key}`).not.toMatch(/[іІїЇєЄґҐ]/);
448 }
449 for (const [key, value] of Object.entries(flattenStrings(getHome("ru")))) {
450 expect(value, `ru home ${key}`).not.toMatch(/[іІїЇєЄґҐ]/);
451 }
452 // Prose values are actually translated, not English pass-through.
453 expect(getHome("ru").heroIntro).toMatch(cyrillic);
454 expect(getHome("uk").heroIntro).toMatch(cyrillic);
455 expect(getChrome("ru").navDocs).not.toBe(EN_CHROME.navDocs);
456 expect(getChrome("uk").navDocs).not.toBe(EN_CHROME.navDocs);
457 expect(getChrome("ru").navDocs).not.toBe(getChrome("uk").navDocs);
458 });
459
460 it("keeps the Chinese pack in Han script for prose (no English pass-through)", () => {
461 const han = /[一-鿿]/;
462 const chrome = getChrome("zh");
463 const home = getHome("zh");
464 for (const key of CHROME_PROSE_KEYS) {
465 expect(chrome[key], `zh chrome ${key}`).toMatch(han);
466 }
467 for (const key of HOME_PROSE_KEYS) {
468 expect(home[key], `zh home ${key}`).toMatch(han);
469 }
470 // Chinese resolves to its OWN dictionary, not the English reference.
471 expect(chrome.navDocs).not.toBe(EN_CHROME.navDocs);
472 expect(home.heroTitle).not.toBe(EN_HOME.heroTitle);
473 });
474
475 it("leaves no unmarked English prose in any non-English dictionary", () => {
476 for (const locale of DICTIONARY_LOCALES) {
477 const chrome = getChrome(locale);
478 const home = getHome(locale);
479 const loanwords = new Set(CHROME_LOANWORDS[locale] ?? []);
480 for (const key of CHROME_PROSE_KEYS) {
481 if (loanwords.has(key)) {
482 // A documented loanword: the shared value IS the native word.
483 expect(chrome[key], `${locale} chrome ${key} loanword`).toBe(EN_CHROME[key]);
484 continue;
485 }
486 expect(chrome[key], `${locale} chrome ${key} is English pass-through`).not.toBe(
487 EN_CHROME[key],
488 );
489 }
490 for (const key of HOME_PROSE_KEYS) {
491 expect(home[key], `${locale} home ${key} is English pass-through`).not.toBe(
492 EN_HOME[key],
493 );
494 }
495 }
496 });
497
498 it("keeps marks, tags, and proper nouns out of the translated-prose rule", () => {
499 // Documents the deliberate exceptions so a future audit does not read a
500 // shared value here as a missing translation.
501 for (const key of NON_PROSE_KEYS) {
502 const inChrome = key in EN_CHROME;
503 const inHome = key in EN_HOME;
504 expect(inChrome || inHome, `${key} is not a real dictionary key`).toBe(true);
505 expect(CHROME_PROSE_KEYS as readonly string[]).not.toContain(key);
506 expect(HOME_PROSE_KEYS as readonly string[]).not.toContain(key);
507 }
508 });
509
510 it("carries the {brand} token through every hero lede for splitToken()", () => {
511 for (const locale of ["en", ...DICTIONARY_LOCALES]) {
512 const lede = getHome(locale).heroIntro;
513 expect(lede, `${locale} heroIntro`).toContain("{brand}");
514 const parts = splitToken(lede, "brand");
515 expect(parts.length, `${locale} heroIntro brand split`).toBe(2);
516 expect(parts.join("").includes("{brand}")).toBe(false);
517 }
518 });
519
520 it("starts every headline with its lead sentence so a page can set the two sentences apart", () => {
521 for (const locale of ["en", ...DICTIONARY_LOCALES]) {
522 const home = getHome(locale);
523 expect(home.heroTitle.startsWith(home.heroTitleLead), `${locale} heroTitle`).toBe(true);
524 expect(home.heroTitle.length, `${locale} heroTitle has a second sentence`).toBeGreaterThan(home.heroTitleLead.length);
525 expect(home.metaTitle, `${locale} metaTitle`).toBe(`Codewhale · ${home.heroTitle}`);
526 }
527 });
528
529 it("carries {date} through both legal pages' effective-date line", () => {
530 // The date used to sit in the JSX between two translated fragments. Now
531 // it is a fill() token, so a translation that drops it would ship a legal
532 // page that no longer says when it took effect.
533 for (const locale of ["en", "zh"]) {
534 expect(getLegalTerms(locale).updated, `${locale} legal-terms`).toContain("{date}");
535 expect(getLegalPrivacy(locale).updated, `${locale} legal-privacy`).toContain("{date}");
536 }
537 });
538
539 it("interpolates templates with fill() and leaves unknown tokens visible", () => {
540 expect(fill("Latest release {tag}", { tag: "v0.9.2" })).toBe("Latest release v0.9.2");
541 expect(fill("{count} provider routes", { count: 30 })).toBe("30 provider routes");
542 expect(fill("v{version} {state}", { version: "0.9.2" })).toBe("v0.9.2 {state}");
543 });
544 });
545
545 lines TYPESCRIPT