ext-localize 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js ADDED
@@ -0,0 +1,620 @@
1
+ #!/usr/bin/env node
2
+ import { readFileSync, realpathSync, writeFileSync } from "node:fs";
3
+ import { dirname, join, resolve } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { parseArgs } from "node:util";
6
+ import { checkProject, formatIssue } from "./check.js";
7
+ import { loadGlossary } from "./glossary.js";
8
+ import { parseTargetLocales } from "./locales.js";
9
+ import { ProjectError, loadProject } from "./messages.js";
10
+ import { createProvider, limitsFor, PROVIDER_NAMES } from "./providers/index.js";
11
+ import { ANTHROPIC_DEFAULT_MODEL } from "./providers/anthropic.js";
12
+ import { FORMALITIES } from "./providers/types.js";
13
+ import { loadState, statePath } from "./state.js";
14
+ import { runJob, translateProject } from "./translate.js";
15
+ import { ConfigError, loadConfig, parseStores } from "./config.js";
16
+ import { STALE_MODES } from "./stale.js";
17
+ import { ListingError, defaultListingTargets, listingDir, listingJob, loadListing, readAllListings, } from "./listing.js";
18
+ import { AMO_HOST, AMO_PROD_LOCALES, addonUrl, amoDefaultLocale, buildPatchBody, sendPatch } from "./stores/firefox.js";
19
+ import { buildDiagnoseScript, buildPasteScript, chromeDescriptions, copyToClipboard, isItemId, outDir, } from "./stores/chrome.js";
20
+ import { AUTO_WARNING, DEFAULT_PROFILE, openLoginBrowser, runAuto, writeAutoReport } from "./stores/chrome-auto.js";
21
+ import { edgeBlock, writeEdgeFiles } from "./stores/edge.js";
22
+ const HELP = `ext-localize - translate, check and deliver Chrome extension _locales and store listings
23
+
24
+ Usage:
25
+ ext-localize translate --provider <name> [--to <locales>] [options]
26
+ ext-localize translate --listing --provider <name> [options]
27
+ ext-localize check [options]
28
+ ext-localize push firefox --addon <id> [--send]
29
+ ext-localize push chrome [--copy]
30
+ ext-localize push chrome --auto --item <id> [--save] (EXPERIMENTAL)
31
+ ext-localize push edge [--print]
32
+
33
+ translate options:
34
+ --listing Translate the store listing (listing/<locale>.json) instead of _locales
35
+ --store <list> With --listing: stores whose length limits apply (default: config "stores", else chrome)
36
+ --json Print a machine-readable result on stdout (progress goes to stderr)
37
+ --provider <name> ${PROVIDER_NAMES.join(" | ")}
38
+ --to <locales> "all" (all 55 Chrome locales) or a list: de,fr,pt-BR
39
+ Default: the locale folders that already exist.
40
+ --model <id> Model id. anthropic default: ${ANTHROPIC_DEFAULT_MODEL}.
41
+ Required for openai and ollama.
42
+ --effort <level> anthropic only: low | medium | high | xhigh | max (default: medium)
43
+ --formality <value> default | more | less | prefer_more | prefer_less
44
+ DeepL: its formality setting. LLMs: formal or informal tone.
45
+ --glossary <file> Default: .localizer/glossary.json if it exists
46
+ --dry-run Show what would be translated and the request count. No API calls.
47
+ --force Re-translate every key, even unchanged ones
48
+ --batch-size <n> Max strings per request
49
+ --concurrency <n> Locales translated at the same time (default: 4)
50
+
51
+ check options:
52
+ --json Machine-readable output
53
+ --strict Exit with an error on warnings too
54
+ --store <list> Stores whose listing limits apply: chrome,firefox,edge (default: config "stores", else chrome)
55
+ --stale <level> Stale strings (source changed after translation): warning (default) | error | off
56
+
57
+ push firefox options (dry run unless --send):
58
+ --addon <id> Add-on id, slug or guid (or config firefox.addon)
59
+ --send Really send the PATCH. Needs AMO_JWT_ISSUER and AMO_JWT_SECRET.
60
+ --remove <list> Also delete these AMO locales (sends null)
61
+ --default-locale <c> The add-on default locale on AMO (default: from manifest default_locale)
62
+ --extra-locales <l> AMO locales to accept beyond the built-in list of 44
63
+ --host <url> Default: ${AMO_HOST}
64
+
65
+ push chrome options (default: write a script you paste into the dashboard):
66
+ --copy Also copy the script to the clipboard (macOS)
67
+ --mode <m> fill-all (default) | save-each
68
+ --out <file> Default: .localizer/out/chrome-paste.js
69
+ --auto EXPERIMENTAL: drive the dashboard over the DevTools Protocol (needs playwright-core)
70
+ --item <id> Item id (32 letters). Required with --auto (or config chrome.item).
71
+ --save With --auto: click "Save draft", reload and check. Never Publish or Submit.
72
+ --allow-live With --save: allow an item that is not in config chrome.testItems
73
+ --browser <b> launch (default) | port:<n>
74
+ --profile <dir> Chrome profile for launch (default: ~/.ext-localize/chrome-profile)
75
+ --login Open plain Chrome on that profile to sign in to Google once, then exit
76
+
77
+ push edge options:
78
+ --print Print copy-ready blocks instead of only writing files
79
+
80
+ Common:
81
+ --dir <path> Extension folder with manifest.json (default: current folder)
82
+ -h, --help Show this help
83
+ -v, --version Show version
84
+
85
+ Exit codes: 0 ok, 1 failed (errors found, strings failed, run stopped), 2 usage or setup error,
86
+ 3 translate had no target locales.
87
+
88
+ Keys are read from the environment only:
89
+ ANTHROPIC_API_KEY, OPENAI_API_KEY (+ OPENAI_BASE_URL), DEEPL_API_KEY, OLLAMA_HOST,
90
+ AMO_JWT_ISSUER, AMO_JWT_SECRET
91
+ Defaults for most options can be set in .localizer/config.json (see README).
92
+ `;
93
+ function version() {
94
+ const here = dirname(fileURLToPath(import.meta.url));
95
+ const pkg = JSON.parse(readFileSync(join(here, "..", "package.json"), "utf8"));
96
+ return pkg.version;
97
+ }
98
+ function positiveInt(value, flag) {
99
+ if (value === undefined)
100
+ return undefined;
101
+ const n = Number(value);
102
+ if (!Number.isInteger(n) || n < 1)
103
+ throw new UsageError(`${flag} must be a positive whole number`);
104
+ return n;
105
+ }
106
+ class UsageError extends Error {
107
+ }
108
+ function shorten(text, max) {
109
+ return text.length > max ? `${text.slice(0, max - 1)}…` : text;
110
+ }
111
+ function printPlan(result, dryRun, providerName) {
112
+ const rows = result.locales.map((r) => {
113
+ const count = (reason) => r.plan.translate.filter((t) => t.reason === reason).length;
114
+ return {
115
+ locale: r.locale,
116
+ new: count("new") + count("missing"),
117
+ changed: count("changed"),
118
+ invalid: count("invalid"),
119
+ forced: count("forced"),
120
+ removed: r.plan.remove.length,
121
+ kept: r.plan.keep.length,
122
+ requests: r.requests,
123
+ note: shorten(r.skipped ?? (r.plan.manual.length ? `${r.plan.manual.length} edited by hand (kept)` : ""), 70),
124
+ };
125
+ });
126
+ const head = ["locale", "new", "changed", "invalid", "forced", "removed", "kept", "requests", "note"];
127
+ const table = [head, ...rows.map((r) => head.map((h) => String(r[h])))];
128
+ const widths = head.map((_, i) => Math.max(...table.map((row) => (row[i] ?? "").length)));
129
+ for (const row of table)
130
+ console.log(row.map((c, i) => c.padEnd(widths[i] ?? 0)).join(" ").trimEnd());
131
+ console.log("");
132
+ if (dryRun) {
133
+ const head = `Dry run: ${result.totalStrings} string(s) to translate in ${result.locales.length} locale(s), about ${result.totalRequests} request(s)`;
134
+ if (providerName === "deepl") {
135
+ console.log(`${head} to DeepL, about ${result.totalChars} characters billed.`);
136
+ }
137
+ else {
138
+ // Rough: ~3.5 chars per token, plus the fixed prompt per request; output about 1.5x the source text.
139
+ const tokensIn = Math.ceil(result.totalPromptChars / 3.5 + result.totalRequests * 450);
140
+ const tokensOut = Math.ceil((result.totalChars / 3.5) * 1.5 + result.totalStrings * 12);
141
+ console.log(`${head} to ${providerName ?? "an LLM provider"}, roughly ${tokensIn} input and ${tokensOut} output tokens (rough guess).`);
142
+ }
143
+ console.log("Nothing was written.");
144
+ }
145
+ }
146
+ /** Exit codes. See README "Exit codes". */
147
+ export const EXIT_OK = 0;
148
+ export const EXIT_FAILED = 1;
149
+ export const EXIT_USAGE = 2;
150
+ export const EXIT_NO_TARGETS = 3;
151
+ /** The `translate --json` result. See README "translate --json". */
152
+ function translateJson(result, o) {
153
+ return {
154
+ command: "translate",
155
+ target: o.listing ? "listing" : "messages",
156
+ dryRun: o.dryRun,
157
+ provider: o.provider ?? null,
158
+ exitCode: o.exitCode,
159
+ ok: o.exitCode === 0,
160
+ noTargets: o.noTargets,
161
+ stopped: result.stopped ?? null,
162
+ locales: result.locales.map((r) => {
163
+ const count = (reason) => r.plan.translate.filter((t) => t.reason === reason).length;
164
+ return {
165
+ locale: r.locale,
166
+ new: count("new") + count("missing"),
167
+ changed: count("changed"),
168
+ invalid: count("invalid"),
169
+ forced: count("forced"),
170
+ removed: r.plan.remove.length,
171
+ kept: r.plan.keep.length,
172
+ adopted: r.plan.adopt.length,
173
+ manual: r.plan.manual.length,
174
+ translated: r.translated.length,
175
+ failed: r.failed.length,
176
+ requests: r.requests,
177
+ skipped: r.skipped ?? null,
178
+ failedKeys: r.failed,
179
+ written: r.written,
180
+ };
181
+ }),
182
+ totals: {
183
+ strings: result.totalStrings,
184
+ requests: result.totalRequests,
185
+ characters: result.totalChars,
186
+ failed: result.failedCount,
187
+ },
188
+ filesWritten: result.filesWritten,
189
+ mayWrite: o.mayWrite,
190
+ check: o.check,
191
+ };
192
+ }
193
+ async function runTranslate(args) {
194
+ const { values } = parseArgs({
195
+ args,
196
+ options: {
197
+ dir: { type: "string" },
198
+ to: { type: "string" },
199
+ provider: { type: "string" },
200
+ model: { type: "string" },
201
+ effort: { type: "string" },
202
+ formality: { type: "string" },
203
+ glossary: { type: "string" },
204
+ "dry-run": { type: "boolean" },
205
+ force: { type: "boolean" },
206
+ "batch-size": { type: "string" },
207
+ concurrency: { type: "string" },
208
+ listing: { type: "boolean" },
209
+ store: { type: "string" },
210
+ json: { type: "boolean" },
211
+ },
212
+ strict: true,
213
+ });
214
+ const json = values.json ?? false;
215
+ // With --json, stdout carries only the JSON result; progress goes to stderr.
216
+ const say = json ? (line) => console.error(line) : (line) => console.log(line);
217
+ const root = resolve(values.dir ?? ".");
218
+ const config = loadConfig(root);
219
+ if (values.store && !values.listing)
220
+ throw new UsageError(`--store only works with --listing`);
221
+ const stores = values.store ? parseStores(values.store) : config.stores;
222
+ values.provider ??= config.provider;
223
+ values.model ??= config.model;
224
+ values.effort ??= config.effort;
225
+ values.formality ??= config.formality;
226
+ values.to ??= config.to;
227
+ const project = loadProject(root);
228
+ const targets = values.to ? parseTargetLocales(values.to, project.defaultLocale) : undefined;
229
+ const dryRun = values["dry-run"] ?? false;
230
+ if (!dryRun && !values.provider)
231
+ throw new UsageError(`--provider is required (${PROVIDER_NAMES.join(", ")}). Use --dry-run to preview without one.`);
232
+ if (values.provider && !PROVIDER_NAMES.includes(values.provider)) {
233
+ throw new UsageError(`unknown provider "${values.provider}". Use one of: ${PROVIDER_NAMES.join(", ")}`);
234
+ }
235
+ const formality = values.formality;
236
+ if (formality !== undefined && !FORMALITIES.includes(formality)) {
237
+ throw new UsageError(`--formality must be one of ${FORMALITIES.join(", ")}`);
238
+ }
239
+ const provider = dryRun ? undefined : createProvider({ name: values.provider, model: values.model, effort: values.effort });
240
+ // A --glossary flag is relative to the current folder; the config value to the extension folder.
241
+ const glossaryFile = values.glossary ? resolve(values.glossary) : config.glossary ? resolve(root, config.glossary) : undefined;
242
+ const glossary = loadGlossary(root, glossaryFile);
243
+ const state = loadState(root, project.defaultLocale);
244
+ if (!targets && !dryRun) {
245
+ // Default targets are the existing folders; make that visible.
246
+ say(values.listing ? `No --to given: using the existing locale folders and listing files.` : `No --to given: using the existing locale folders.`);
247
+ }
248
+ const common = {
249
+ provider,
250
+ limits: limitsFor(values.provider),
251
+ dryRun,
252
+ force: values.force,
253
+ glossary,
254
+ formality: formality,
255
+ concurrency: positiveInt(values.concurrency, "--concurrency"),
256
+ batchSize: positiveInt(values["batch-size"], "--batch-size"),
257
+ log: say,
258
+ };
259
+ let result;
260
+ if (values.listing) {
261
+ const lp = loadListing(project, listingDir(root, config.listing?.dir));
262
+ const synced = Object.entries(lp.synced).map(([f, k]) => `${f} <- ${k}`);
263
+ if (synced.length)
264
+ say(`Copied from _locales, not translated (manifest uses __MSG_): ${synced.join(", ")}`);
265
+ result = await runJob(listingJob(project, lp, stores ?? ["chrome"]), state, {
266
+ ...common,
267
+ targets: targets ?? defaultListingTargets(project, lp.dir),
268
+ });
269
+ }
270
+ else {
271
+ result = await translateProject(project, state, { ...common, targets });
272
+ }
273
+ const listingRel = (config.listing?.dir ?? "listing").replace(/\\/g, "/").replace(/\/+$/, "");
274
+ const mayWrite = values.listing
275
+ ? [`${listingRel}/<locale>.json`, ".localizer/state.json"]
276
+ : ["_locales/<locale>/messages.json", ".localizer/state.json"];
277
+ const noTargets = result.locales.length === 0;
278
+ let exitCode = noTargets ? EXIT_NO_TARGETS : 0;
279
+ let check = null;
280
+ if (!noTargets && !dryRun) {
281
+ const report = checkProject(root, { stores, listingDir: config.listing?.dir });
282
+ check = { errors: report.errors, warnings: report.warnings, stale: report.stale };
283
+ if (result.failedCount > 0 || result.stopped)
284
+ exitCode = 1;
285
+ }
286
+ if (json) {
287
+ console.log(JSON.stringify(translateJson(result, { listing: !!values.listing, dryRun, provider: values.provider, exitCode, noTargets, mayWrite, check }), null, 2));
288
+ return exitCode;
289
+ }
290
+ if (noTargets) {
291
+ console.log(`No target locales. Use --to (for example --to de,fr or --to all).`);
292
+ return exitCode;
293
+ }
294
+ console.log("");
295
+ printPlan(result, dryRun, values.provider);
296
+ if (dryRun)
297
+ return 0;
298
+ const failures = result.locales.flatMap((r) => r.failed.map((f) => `FAILED ${r.locale} > ${f.key}: ${f.error}`));
299
+ for (const line of failures.slice(0, 20))
300
+ console.log(line);
301
+ if (failures.length > 20)
302
+ console.log(`... and ${failures.length - 20} more failed string(s)`);
303
+ if (result.stopped)
304
+ console.error(`Stopped early: ${result.stopped}`);
305
+ console.log(`State saved to ${statePath(root)}`);
306
+ if (check) {
307
+ console.log(`check: ${check.errors} error(s), ${check.warnings} warning(s), ${check.stale} stale. Run "ext-localize check" for details.`);
308
+ }
309
+ return exitCode;
310
+ }
311
+ function runCheck(args) {
312
+ const { values } = parseArgs({
313
+ args,
314
+ options: {
315
+ dir: { type: "string" },
316
+ json: { type: "boolean" },
317
+ strict: { type: "boolean" },
318
+ store: { type: "string" },
319
+ stale: { type: "string" },
320
+ },
321
+ strict: true,
322
+ });
323
+ const root = resolve(values.dir ?? ".");
324
+ const config = loadConfig(root);
325
+ const stores = values.store ? parseStores(values.store) : config.stores;
326
+ const stale = values.stale ?? "warning";
327
+ if (!STALE_MODES.includes(stale))
328
+ throw new UsageError(`--stale must be one of ${STALE_MODES.join(", ")}`);
329
+ const report = checkProject(root, { stores, listingDir: config.listing?.dir, stale: stale });
330
+ if (values.json) {
331
+ console.log(JSON.stringify(report, null, 2));
332
+ }
333
+ else {
334
+ for (const issue of report.issues)
335
+ console.log(formatIssue(issue));
336
+ if (report.issues.length)
337
+ console.log("");
338
+ console.log(`${report.locales.length} locale(s) checked: ${report.errors} error(s), ${report.warnings} warning(s), ${report.stale} stale.`);
339
+ }
340
+ const fail = report.errors > 0 || (values.strict && report.warnings > 0);
341
+ return fail ? 1 : 0;
342
+ }
343
+ const list = (s) => (s ?? "").split(",").map((x) => x.trim()).filter(Boolean);
344
+ /** All listing files, with the synced fields of the source filled in from _locales. */
345
+ function loadAllListings(root, config) {
346
+ const project = loadProject(root);
347
+ const dir = listingDir(root, config.listing?.dir);
348
+ const lp = loadListing(project, dir);
349
+ const listings = readAllListings(dir, project.defaultLocale);
350
+ listings[project.defaultLocale] = lp.source;
351
+ return { listings, defaultLocale: project.defaultLocale };
352
+ }
353
+ async function runPushFirefox(args) {
354
+ const { values } = parseArgs({
355
+ args,
356
+ options: {
357
+ dir: { type: "string" },
358
+ addon: { type: "string" },
359
+ send: { type: "boolean" },
360
+ remove: { type: "string" },
361
+ "default-locale": { type: "string" },
362
+ "extra-locales": { type: "string" },
363
+ host: { type: "string" },
364
+ },
365
+ strict: true,
366
+ });
367
+ const root = resolve(values.dir ?? ".");
368
+ const config = loadConfig(root);
369
+ const addon = values.addon ?? config.firefox?.addon;
370
+ if (!addon)
371
+ throw new UsageError(`--addon <id|slug|guid> is required (or set firefox.addon in .localizer/config.json)`);
372
+ const { listings, defaultLocale } = loadAllListings(root, config);
373
+ const supported = [...AMO_PROD_LOCALES, ...(config.firefox?.extraLocales ?? []), ...list(values["extra-locales"])];
374
+ const amoDefault = values["default-locale"] ?? config.firefox?.defaultLocale ?? amoDefaultLocale(defaultLocale, supported) ?? "en-US";
375
+ const result = buildPatchBody(listings, { supported, defaultLocale: amoDefault, remove: list(values.remove) });
376
+ const url = addonUrl(values.host ?? config.firefox?.host ?? AMO_HOST, addon);
377
+ const issuer = process.env.AMO_JWT_ISSUER;
378
+ const secret = process.env.AMO_JWT_SECRET;
379
+ console.log(`PATCH ${url}`);
380
+ console.log("Content-Type: application/json");
381
+ console.log(`Authorization: JWT <redacted; AMO_JWT_ISSUER ${issuer ? "set" : "not set"}, AMO_JWT_SECRET ${secret ? "set" : "not set"}>`);
382
+ console.log("");
383
+ console.log(JSON.stringify(result.body, null, 2));
384
+ console.log("");
385
+ console.log(`AMO default locale: ${amoDefault}`);
386
+ console.log("Locale sources: " + (Object.entries(result.sources).map(([a, c]) => `${a}<-${c}`).join(" ") || "(none)"));
387
+ const skipped = result.warnings.filter((w) => w.startsWith("skip "));
388
+ if (skipped.length) {
389
+ console.log(`Cannot be sent to AMO (${skipped.length}):`);
390
+ for (const w of skipped)
391
+ console.log(` ${w.slice(5)}`);
392
+ }
393
+ for (const w of result.warnings.filter((w) => !w.startsWith("skip ")))
394
+ console.error(`warning: ${w}`);
395
+ for (const e of result.errors)
396
+ console.error(`error: ${e}`);
397
+ if (result.errors.length > 0) {
398
+ console.error(`\n${result.errors.length} error(s); not sending.`);
399
+ return 1;
400
+ }
401
+ if (!values.send) {
402
+ console.error(`\nDry run: nothing sent. Add --send (and set AMO_JWT_ISSUER, AMO_JWT_SECRET) to send.`);
403
+ return 0;
404
+ }
405
+ if (!issuer || !secret) {
406
+ console.error(`\nError: --send needs AMO_JWT_ISSUER and AMO_JWT_SECRET in the environment.`);
407
+ return 2;
408
+ }
409
+ const res = await sendPatch(url, result.body, { issuer, secret });
410
+ console.error(`\nHTTP ${res.status}`);
411
+ console.log(res.text);
412
+ return res.ok ? 0 : 1;
413
+ }
414
+ async function runPushChrome(args) {
415
+ const { values } = parseArgs({
416
+ args,
417
+ options: {
418
+ dir: { type: "string" },
419
+ copy: { type: "boolean" },
420
+ mode: { type: "string" },
421
+ out: { type: "string" },
422
+ auto: { type: "boolean" },
423
+ item: { type: "string" },
424
+ save: { type: "boolean" },
425
+ "allow-live": { type: "boolean" },
426
+ browser: { type: "string" },
427
+ profile: { type: "string" },
428
+ login: { type: "boolean" },
429
+ url: { type: "string" },
430
+ headless: { type: "boolean" },
431
+ },
432
+ strict: true,
433
+ });
434
+ const root = resolve(values.dir ?? ".");
435
+ const config = loadConfig(root);
436
+ const mode = (values.mode ?? "fill-all");
437
+ if (mode !== "fill-all" && mode !== "save-each")
438
+ throw new UsageError(`--mode must be fill-all or save-each`);
439
+ if (!values.auto) {
440
+ for (const flag of ["item", "save", "allow-live", "browser", "profile", "login", "url", "headless"]) {
441
+ if (values[flag] !== undefined)
442
+ throw new UsageError(`--${flag} only works with --auto`);
443
+ }
444
+ const { listings } = loadAllListings(root, config);
445
+ const { descriptions, problems } = chromeDescriptions(listings);
446
+ for (const p of problems)
447
+ console.error(`skip ${p}`);
448
+ if (!Object.keys(descriptions).length) {
449
+ console.error("Error: no description to fill.");
450
+ return 1;
451
+ }
452
+ const dir = outDir(root);
453
+ const file = values.out ? resolve(values.out) : `${dir}/chrome-paste.js`;
454
+ const script = buildPasteScript(descriptions, { mode });
455
+ writeFileSync(file, script);
456
+ const diag = `${dir}/chrome-diagnose.js`;
457
+ writeFileSync(diag, buildDiagnoseScript(Object.keys(descriptions)));
458
+ console.log(`Wrote ${file} (${Object.keys(descriptions).length} language(s): ${Object.keys(descriptions).join(", ")})`);
459
+ console.log(`Wrote ${diag} (read-only check, changes nothing)`);
460
+ if (values.copy) {
461
+ const err = copyToClipboard(script);
462
+ console.log(err ? `Could not copy: ${err}` : "Copied the script to the clipboard.");
463
+ }
464
+ console.log(`
465
+ Steps:
466
+ 1. In Chrome, open the Developer Dashboard, your item, then the "Store listing" tab.
467
+ 2. Open the DevTools console: Cmd+Option+J (Mac) or Ctrl+Shift+J.
468
+ 3. Paste the script${values.copy ? " (it is on the clipboard)" : ""} and press Enter.
469
+ The first time, Chrome may ask you to type "allow pasting".
470
+ 4. Wait for the report in the console. Check a few languages.
471
+ 5. Click "Save draft" yourself.${mode === "save-each" ? " (save-each: the script waits for your click after each language.)" : ""}
472
+ Name and summary come from _locales (the manifest); only the description is filled here.
473
+ The script never clicks Submit for review or Publish.`);
474
+ return 0;
475
+ }
476
+ console.error(AUTO_WARNING + "\n");
477
+ const profile = values.profile ?? config.chrome?.profile ?? DEFAULT_PROFILE;
478
+ if (values.login) {
479
+ openLoginBrowser(resolve(profile.replace(/^~(?=\/)/, process.env.HOME ?? "~")));
480
+ console.log(`Opened Chrome on ${profile}. Sign in to Google, open the dashboard once, then quit Chrome (Cmd+Q).`);
481
+ return 0;
482
+ }
483
+ const item = values.item ?? config.chrome?.item;
484
+ if (!item)
485
+ throw new UsageError(`--auto needs --item <itemId> (or chrome.item in .localizer/config.json)`);
486
+ if (!isItemId(item))
487
+ throw new UsageError(`--item must be a 32-letter Chrome item id (letters a-p), not "${item}"`);
488
+ const { listings } = loadAllListings(root, config);
489
+ const { descriptions, problems } = chromeDescriptions(listings);
490
+ for (const p of problems)
491
+ console.error(`skip ${p}`);
492
+ if (!Object.keys(descriptions).length) {
493
+ console.error("Error: no description to fill.");
494
+ return 1;
495
+ }
496
+ const report = await runAuto(descriptions, {
497
+ item,
498
+ save: values.save,
499
+ allowLive: values["allow-live"],
500
+ testItems: config.chrome?.testItems,
501
+ browser: values.browser ?? config.chrome?.browser,
502
+ profile: resolve(profile.replace(/^~(?=\/)/, process.env.HOME ?? "~")),
503
+ publisher: config.chrome?.publisher,
504
+ url: values.url,
505
+ headless: values.headless,
506
+ log: (line) => console.log(line),
507
+ });
508
+ const file = writeAutoReport(outDir(root), report);
509
+ const f = report.fill;
510
+ if (f) {
511
+ for (const u of f.unmatched)
512
+ console.log(`not in the dashboard language list: ${u.locale} (${u.dashboardCode})`);
513
+ for (const e of f.errors)
514
+ console.log(`error ${e.locale}: ${e.error}`);
515
+ if (f.hint)
516
+ console.log(f.hint);
517
+ }
518
+ for (const r of report.afterReload?.rows.filter((r) => !r.ok) ?? [])
519
+ console.log(`after reload, ${r.locale} differs: ${r.error ?? `${r.gotLength} vs ${r.wantLength} chars`}`);
520
+ if (report.error)
521
+ console.error(`Error: ${report.error}`);
522
+ console.log(`Report: ${file}`);
523
+ const ok = !report.error && report.fillOk && (!values.save || report.afterReload?.ok === true);
524
+ return ok ? 0 : 1;
525
+ }
526
+ function runPushEdge(args) {
527
+ const { values } = parseArgs({
528
+ args,
529
+ options: { dir: { type: "string" }, print: { type: "boolean" } },
530
+ strict: true,
531
+ });
532
+ const root = resolve(values.dir ?? ".");
533
+ const config = loadConfig(root);
534
+ const { listings } = loadAllListings(root, config);
535
+ const dir = `${outDir(root)}/edge`;
536
+ const entries = writeEdgeFiles(listings, dir);
537
+ if (values.print)
538
+ for (const e of entries)
539
+ if (e.file)
540
+ console.log(edgeBlock(e.locale, listings[e.locale] ?? {}));
541
+ for (const e of entries)
542
+ console.log(`${e.locale.padEnd(7)} ${String(e.length).padStart(6)} chars ${e.problem ?? "ok"}`);
543
+ console.log(`
544
+ Wrote ${entries.filter((e) => e.file).length} file(s) to ${dir}
545
+ Edge has no API for listing text. In Partner Center, open your extension, "Store listings",
546
+ pick each language and paste its Description. Name and short description come from the
547
+ manifest (_locales), so they are not in these files.`);
548
+ return entries.some((e) => e.problem) ? 1 : 0;
549
+ }
550
+ async function runPush(args) {
551
+ const [store, ...rest] = args;
552
+ switch (store) {
553
+ case "firefox":
554
+ return runPushFirefox(rest);
555
+ case "chrome":
556
+ return runPushChrome(rest);
557
+ case "edge":
558
+ return runPushEdge(rest);
559
+ default:
560
+ throw new UsageError(`push needs a store: firefox, chrome or edge`);
561
+ }
562
+ }
563
+ export async function main(argv) {
564
+ const [command, ...rest] = argv;
565
+ try {
566
+ switch (command) {
567
+ case "translate":
568
+ return await runTranslate(rest);
569
+ case "check":
570
+ return runCheck(rest);
571
+ case "push":
572
+ return await runPush(rest);
573
+ case "-v":
574
+ case "--version":
575
+ console.log(version());
576
+ return 0;
577
+ case undefined:
578
+ case "-h":
579
+ case "--help":
580
+ case "help":
581
+ console.log(HELP);
582
+ return 0;
583
+ default:
584
+ console.error(`Unknown command "${command}".\n`);
585
+ console.error(HELP);
586
+ return 2;
587
+ }
588
+ }
589
+ catch (e) {
590
+ const err = e;
591
+ const usage = e instanceof UsageError || e instanceof ProjectError || e instanceof ListingError || e instanceof ConfigError || !!err.code?.startsWith("ERR_PARSE_ARGS");
592
+ const code = usage ? EXIT_USAGE : EXIT_FAILED;
593
+ if (argv.includes("--json")) {
594
+ // Keep stdout machine-readable even on errors.
595
+ console.log(JSON.stringify({ command: command ?? null, exitCode: code, ok: false, error: err.message }, null, 2));
596
+ }
597
+ if (e instanceof UsageError || err.code?.startsWith("ERR_PARSE_ARGS")) {
598
+ console.error(`Error: ${err.message}\nRun "ext-localize --help" for usage.`);
599
+ }
600
+ else {
601
+ console.error(`Error: ${err.message}`);
602
+ }
603
+ return code;
604
+ }
605
+ }
606
+ // npm installs the bin as a symlink, so compare real paths.
607
+ function isMainModule() {
608
+ try {
609
+ return !!process.argv[1] && realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url));
610
+ }
611
+ catch {
612
+ return false;
613
+ }
614
+ }
615
+ const isMain = isMainModule();
616
+ if (isMain) {
617
+ main(process.argv.slice(2)).then((code) => {
618
+ process.exitCode = code;
619
+ });
620
+ }