返回 CodeWhale
gt-site.mjs
根目录 / web / scripts / gt-site.mjs
1 #!/usr/bin/env node
2 /**
3 * Website/docs General Translation pipeline.
4 *
5 * Runtime authority stays web/lib/i18n/dictionaries (one logical path).
6 * This script exports those dictionaries to web/gt-catalog/[locale].json
7 * so the MIT `gt` CLI can translate updated English copy, then imports
8 * reviewed JSON back into the same dictionary files.
9 *
10 * Not for the TUI. Not for model completions. Not a /translate replacement.
11 * Never call `gt generate` here — that scanner is framework-only and would
12 * look for <T> JSX this site does not use.
13 */
14 import { spawnSync } from "node:child_process";
15 import { createHash } from "node:crypto";
16 import { existsSync } from "node:fs";
17 import { mkdir, readFile, readdir, writeFile } from "node:fs/promises";
18 import path from "node:path";
19 import { fileURLToPath } from "node:url";
20
21 const webRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
22 const repoRoot = path.resolve(webRoot, "..");
23 const configPath = path.join(webRoot, "gt.config.json");
24 const catalogDir = path.join(webRoot, "gt-catalog");
25 const dictDir = path.join(webRoot, "lib", "i18n", "dictionaries");
26 const pinnedCli = "2.17.2";
27 const tuiLocaleDir = path.join(repoRoot, "crates", "localization", "locales");
28 const promptPath = path.join(repoRoot, "crates", "engine", "src", "prompts", "text.rs");
29
30 const STEMS = {
31 project: { exportName: "project", typeName: "ProjectDict" },
32 features: { exportName: "features", typeName: "FeaturesDict" },
33 "docs-skills": { exportName: "docsSkills", typeName: "DocsPageDict" },
34 "docs-claude-code": { exportName: "docsClaudeCode", typeName: "DocsPageDict" },
35 chrome: { exportName: "chrome", typeName: "ChromeDict" },
36 home: { exportName: "home", typeName: "HomeDict" },
37 "docs-guide": { exportName: "docsGuide", typeName: "DocsGuideDict" },
38 "docs-shell": { exportName: "docsShell", typeName: "DocsShellDict" },
39 "docs-hooks": { exportName: "docsHooks", typeName: "DocsHooksDict" },
40 "docs-troubleshooting": { exportName: "docsTroubleshooting", typeName: "DocsTroubleshootingDict" },
41 "docs-configuration": { exportName: "docsConfiguration", typeName: "DocsConfigurationDict" },
42 "docs-constitution": { exportName: "docsConstitution", typeName: "DocsConstitutionDict" },
43 "docs-fleet": { exportName: "docsFleet", typeName: "DocsFleetDict" },
44 "docs-mcp": { exportName: "docsMcp", typeName: "DocsMcpDict" },
45 "docs-modes": { exportName: "docsModes", typeName: "DocsModesDict" },
46 "docs-runtime-api": { exportName: "docsRuntimeApi", typeName: "DocsRuntimeApiDict" },
47 "docs-sandbox": { exportName: "docsSandbox", typeName: "DocsSandboxDict" },
48 "docs-subagents": { exportName: "docsSubagents", typeName: "DocsSubagentsDict" },
49 "docs-web": { exportName: "docsWeb", typeName: "DocsWebDict" },
50 "docs-auth": { exportName: "docsAuth", typeName: "DocsAuthDict" },
51 "docs-trust": { exportName: "docsTrust", typeName: "DocsTrustDict" },
52 "docs-first-time": { exportName: "docsFirstTime", typeName: "DocsFirstTimeDict" },
53 states: { exportName: "states", typeName: "StatesDict" },
54 changelog: { exportName: "changelog", typeName: "ChangelogDict" },
55 "computer-use": { exportName: "computerUse", typeName: "ComputerUseDict" },
56 };
57
58 const REQUIRED_STEMS = ["chrome", "home"];
59
60 function fail(message) {
61 throw new Error(message);
62 }
63
64 function assertExactKeys(value, expected, label) {
65 if (!value || typeof value !== "object" || Array.isArray(value)) {
66 fail(`${label} must be an object`);
67 }
68 const actual = Object.keys(value).sort();
69 const wanted = [...expected].sort();
70 if (JSON.stringify(actual) !== JSON.stringify(wanted)) {
71 fail(`${label} keys must be exactly: ${wanted.join(", ")} (found: ${actual.join(", ")})`);
72 }
73 }
74
75 function stableStringify(value) {
76 return `${JSON.stringify(value, null, 2)}\n`;
77 }
78
79 function deepEqual(left, right) {
80 return JSON.stringify(left) === JSON.stringify(right);
81 }
82
83 async function readConfig() {
84 const config = JSON.parse(await readFile(configPath, "utf8"));
85 assertExactKeys(config, ["defaultLocale", "locales", "files"], "gt.config.json");
86 assertExactKeys(config.files, ["json"], "gt.config.json files");
87 assertExactKeys(config.files.json, ["include"], "gt.config.json files.json");
88 if (config.defaultLocale !== "en") fail("defaultLocale must remain en");
89 if (
90 !Array.isArray(config.locales) ||
91 config.locales.length === 0 ||
92 !config.locales.every((locale) => typeof locale === "string" && locale.length > 0) ||
93 new Set(config.locales).size !== config.locales.length
94 ) {
95 fail("locales must be a non-empty, duplicate-free string array");
96 }
97 if (config.locales.includes("en")) fail("locales must not include the default locale");
98 const include = config.files.json.include;
99 if (!Array.isArray(include) || include.length !== 1 || include[0] !== "gt-catalog/[locale].json") {
100 fail("the JSON source must remain web/gt-catalog/[locale].json");
101 }
102 for (const locale of config.locales) {
103 if (locale.includes("..") || locale.includes("/") || locale.includes("\\")) {
104 fail(`locale ${locale} is not a safe catalog name`);
105 }
106 }
107 return config;
108 }
109
110 async function assertWebsiteOnlyAsync() {
111 const source = await readFile(configPath, "utf8");
112 if (
113 source.includes("crates/localization") ||
114 source.includes("crates/tui") ||
115 source.includes("prompts/text.rs")
116 ) {
117 fail("gt.config.json must not mention TUI paths");
118 }
119 if (!source.includes("gt-catalog/[locale].json")) {
120 fail("gt.config.json must target the website catalog only");
121 }
122 }
123
124 async function loadDictionaryModule(locale, stem) {
125 const spec = STEMS[stem];
126 if (!spec) fail(`unknown dictionary stem ${stem}`);
127 const filePath = path.join(dictDir, locale, `${stem}.ts`);
128 if (!existsSync(filePath)) return null;
129 const ts = await import("typescript");
130 const source = await readFile(filePath, "utf8");
131 const { outputText } = ts.transpileModule(source, {
132 compilerOptions: {
133 module: ts.ModuleKind.ESNext,
134 target: ts.ScriptTarget.ES2022,
135 },
136 fileName: filePath,
137 });
138 const mod = await import(`data:text/javascript;base64,${Buffer.from(outputText).toString("base64")}`);
139 const value = mod[spec.exportName];
140 if (value == null) fail(`missing export ${spec.exportName} in ${filePath}`);
141 return value;
142 }
143
144 async function loadCatalogFromDictionaries(locale) {
145 const catalog = {};
146 for (const stem of Object.keys(STEMS)) {
147 const value = await loadDictionaryModule(locale, stem);
148 if (value == null) {
149 if (REQUIRED_STEMS.includes(stem) && locale === "en") {
150 fail(`English is missing required dictionary ${stem}.ts`);
151 }
152 continue;
153 }
154 catalog[stem] = value;
155 }
156 return catalog;
157 }
158
159 async function readCatalogFile(locale) {
160 const filePath = path.join(catalogDir, `${locale}.json`);
161 const source = await readFile(filePath, "utf8");
162 let parsed;
163 try {
164 parsed = JSON.parse(source);
165 } catch (error) {
166 fail(`${filePath} is not valid JSON: ${error.message}`);
167 }
168 if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
169 fail(`${filePath} must be a JSON object of dictionary stems`);
170 }
171 for (const stem of Object.keys(parsed)) {
172 if (!STEMS[stem]) fail(`${filePath} contains unknown stem ${stem}`);
173 }
174 for (const stem of REQUIRED_STEMS) {
175 if (!parsed[stem]) fail(`${filePath} is missing required stem ${stem}`);
176 }
177 return parsed;
178 }
179
180 async function writeCatalogFile(locale, catalog) {
181 await mkdir(catalogDir, { recursive: true });
182 const filePath = path.join(catalogDir, `${locale}.json`);
183 await writeFile(filePath, stableStringify(catalog));
184 return filePath;
185 }
186
187 function emitTsValue(value, indent) {
188 const pad = " ".repeat(indent);
189 if (typeof value === "string") return JSON.stringify(value);
190 if (Array.isArray(value)) {
191 if (value.every((row) => Array.isArray(row) && row.every((cell) => typeof cell === "string"))) {
192 const rows = value.map((row) => `${pad} [${row.map((cell) => JSON.stringify(cell)).join(", ")}]`);
193 return `[\n${rows.join(",\n")},\n${pad}]`;
194 }
195 fail("catalog arrays must be [string, string] rows");
196 }
197 if (value && typeof value === "object") {
198 const keys = Object.keys(value);
199 const lines = keys.map((key) => `${pad} ${key}: ${emitTsValue(value[key], indent + 2)},`);
200 return `{\n${lines.join("\n")}\n${pad}}`;
201 }
202 fail(`unsupported catalog value type ${typeof value}`);
203 }
204
205 async function writeDictionaryFile(locale, stem, value) {
206 const spec = STEMS[stem];
207 const filePath = path.join(dictDir, locale, `${stem}.ts`);
208 await mkdir(path.dirname(filePath), { recursive: true });
209 const body = `import type { ${spec.typeName} } from "../types";
210
211 /**
212 * Website dictionary for locale \`${locale}\`.
213 * Runtime authority is this file (web/lib/i18n/dictionaries).
214 * Source/sink for General Translation is web/gt-catalog/${locale}.json.
215 */
216 export const ${spec.exportName}: ${spec.typeName} = ${emitTsValue(value, 0)};
217 `;
218 await writeFile(filePath, body);
219 return filePath;
220 }
221
222 async function check() {
223 const config = await readConfig();
224 await assertWebsiteOnlyAsync();
225 if (existsSync(tuiLocaleDir)) {
226 const tuiPacks = (await readdir(tuiLocaleDir)).filter((name) => name.endsWith(".json"));
227 if (tuiPacks.length === 0) fail("TUI locale directory exists but is empty — refusing to proceed");
228 }
229 if (existsSync(promptPath)) {
230 const digest = createHash("sha256").update(await readFile(promptPath)).digest("hex");
231 if (digest.length !== 64) fail("could not fingerprint prompts/text.rs");
232 }
233
234 const locales = [config.defaultLocale, ...config.locales];
235 for (const locale of locales) {
236 const fromDict = await loadCatalogFromDictionaries(locale);
237 const fromFile = await readCatalogFile(locale);
238 if (!deepEqual(fromDict, fromFile)) {
239 fail(
240 `gt-catalog/${locale}.json is out of sync with web/lib/i18n/dictionaries/${locale}/ — run npm run i18n:gt -- export`,
241 );
242 }
243 for (const stem of Object.keys(fromFile)) {
244 if (REQUIRED_STEMS.includes(stem)) continue;
245 const enValue = (await loadCatalogFromDictionaries("en"))[stem];
246 if (enValue && !deepEqual(Object.keys(fromFile[stem]).sort(), Object.keys(enValue).sort())) {
247 fail(`gt-catalog/${locale}.json stem ${stem} does not have English key parity`);
248 }
249 }
250 }
251 console.log(
252 `Website GT catalog OK — ${config.locales.join(", ")} (local JSON; TUI packs untouched; no API)`,
253 );
254 }
255
256 async function exportCatalogs() {
257 const config = await readConfig();
258 const locales = [config.defaultLocale, ...config.locales];
259 const written = [];
260 for (const locale of locales) {
261 const catalog = await loadCatalogFromDictionaries(locale);
262 written.push(await writeCatalogFile(locale, catalog));
263 }
264 console.log(`Exported ${written.length} website catalogs:\n${written.map((file) => ` ${path.relative(webRoot, file)}`).join("\n")}`);
265 }
266
267 async function importCatalogs() {
268 const config = await readConfig();
269 const written = [];
270 for (const locale of config.locales) {
271 const catalog = await readCatalogFile(locale);
272 for (const [stem, value] of Object.entries(catalog)) {
273 written.push(await writeDictionaryFile(locale, stem, value));
274 }
275 }
276 console.log(
277 `Imported ${written.length} website dictionaries from gt-catalog (TUI packs not written):\n${written
278 .map((file) => ` ${path.relative(webRoot, file)}`)
279 .join("\n")}`,
280 );
281 }
282
283 async function validatePinnedCli() {
284 const packagePath = path.join(webRoot, "node_modules", "gt", "package.json");
285 let packageJson;
286 try {
287 packageJson = JSON.parse(await readFile(packagePath, "utf8"));
288 } catch {
289 fail("gt is not installed locally; run npm ci in web/ (this wrapper never downloads packages)");
290 }
291 if (packageJson.version !== pinnedCli) {
292 fail(`expected the locked gt ${pinnedCli} package (found ${packageJson.version})`);
293 }
294 const bin = packageJson.bin;
295 const binPath = typeof bin === "string" ? bin : bin.gt;
296 if (!binPath) fail("gt package.json is missing a bin");
297 return path.join(path.dirname(packagePath), binPath);
298 }
299
300 function translateEnvironment() {
301 const key = process.env.GT_API_KEY?.trim();
302 const project = process.env.GT_PROJECT_ID?.trim();
303 if (!key || !project) {
304 fail(
305 "gt translate is fail-closed. Set BYOK env GT_API_KEY and GT_PROJECT_ID (never commit them). Local export/import/check do not need a key.",
306 );
307 }
308 const environment = { ...process.env };
309 environment.NO_COLOR = "1";
310 environment.GT_API_KEY = key;
311 environment.GT_PROJECT_ID = project;
312 return environment;
313 }
314
315 async function translate() {
316 await readConfig();
317 await assertWebsiteOnlyAsync();
318 const environment = translateEnvironment();
319 const cli = await validatePinnedCli();
320 const result = spawnSync(
321 process.execPath,
322 [cli, "--skip-version-check", "translate", "--config", "gt.config.json"],
323 {
324 cwd: webRoot,
325 env: environment,
326 stdio: "inherit",
327 windowsHide: true,
328 },
329 );
330 if (result.error) fail(result.error.message);
331 if (result.status !== 0) fail(`gt translate exited with status ${result.status ?? "unknown"}`);
332 console.log("gt translate finished — review gt-catalog/*.json then run npm run i18n:gt -- import");
333 }
334
335 function usage() {
336 console.log(`Usage: node scripts/gt-site.mjs <check|export|import|translate>
337
338 check catalogs match dictionaries; website-only schema
339 export dictionaries → gt-catalog/[locale].json (no API)
340 import gt-catalog → website dictionary TS only (no TUI writes)
341 translate fail-closed without GT_API_KEY + GT_PROJECT_ID
342
343 Never wraps inference. Never edits crates/engine/src/prompts/text.rs.`);
344 }
345
346 const command = process.argv[2] ?? "check";
347
348 try {
349 if (command === "check") await check();
350 else if (command === "export") await exportCatalogs();
351 else if (command === "import") await importCatalogs();
352 else if (command === "translate") await translate();
353 else if (command === "-h" || command === "--help") usage();
354 else {
355 usage();
356 fail(`unknown command ${command}`);
357 }
358 } catch (error) {
359 console.error(`[gt-site] FAIL — ${error.message}`);
360 process.exitCode = 1;
361 }
362
362 lines Plain Text