@verbaly/compiler 0.67.0 → 0.68.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 CHANGED
@@ -1,12 +1,12 @@
1
1
  #!/usr/bin/env node
2
- import { basename, dirname, join, relative, resolve } from "node:path";
3
2
  import { parseArgs } from "node:util";
4
3
  import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, rmSync, watch, writeFileSync } from "node:fs";
4
+ import { basename, dirname, join, relative, resolve } from "node:path";
5
5
  import { CATALOG_SCRIPT, LOCALE_STORAGE_KEY, RICH_TAGS, VOID_TAGS, alternateLinks, createVerbaly, flatten, localeDirection, normalizeLink, parse, parseIcu, parseTags, safeAttribute } from "verbaly";
6
- import { pathToFileURL } from "node:url";
7
- import { createHash } from "node:crypto";
8
6
  import { glob } from "tinyglobby";
9
7
  import { parse as parse$1 } from "@babel/parser";
8
+ import { createHash } from "node:crypto";
9
+ import { pathToFileURL } from "node:url";
10
10
  import MagicString from "magic-string";
11
11
  import picomatch from "picomatch";
12
12
  //#region src/catalog.ts
@@ -139,594 +139,835 @@ function wantsNesting(cfg, locale, existing, previous) {
139
139
  return isNested(readTree(cfg, cfg.sourceLocale));
140
140
  }
141
141
  //#endregion
142
- //#region src/pseudo.ts
143
- const PSEUDO_LOCALE = "en-XA";
144
- const ACCENTS = {
145
- a: "á",
146
- b: "ƀ",
147
- c: "ç",
148
- d: "đ",
149
- e: "é",
150
- f: "ƒ",
151
- g: "ğ",
152
- h: "ĥ",
153
- i: "í",
154
- j: "ĵ",
155
- k: "ķ",
156
- l: "ĺ",
157
- m: "ɱ",
158
- n: "ñ",
159
- o: "ó",
160
- p: "þ",
161
- q: "ǫ",
162
- r: "ŕ",
163
- s: "š",
164
- t: "ţ",
165
- u: "ú",
166
- v: "ṽ",
167
- w: "ŵ",
168
- x: "ẋ",
169
- y: "ý",
170
- z: "ž",
171
- A: "Á",
172
- B: "Ɓ",
173
- C: "Ç",
174
- D: "Đ",
175
- E: "É",
176
- F: "Ƒ",
177
- G: "Ğ",
178
- H: "Ĥ",
179
- I: "Í",
180
- J: "Ĵ",
181
- K: "Ķ",
182
- L: "Ĺ",
183
- M: "Ḿ",
184
- N: "Ñ",
185
- O: "Ó",
186
- P: "Þ",
187
- Q: "Ǫ",
188
- R: "Ŕ",
189
- S: "Š",
190
- T: "Ţ",
191
- U: "Ú",
192
- V: "Ṽ",
193
- W: "Ŵ",
194
- X: "Ẍ",
195
- Y: "Ý",
196
- Z: "Ž"
197
- };
198
- const TAG_AT = /<\/?[a-zA-Z][\w-]*\/?>/y;
199
- function pseudoLocalize(message) {
200
- let out = "";
201
- let letters = 0;
202
- let i = 0;
203
- while (i < message.length) {
204
- const two = message.slice(i, i + 2);
205
- if (two === "{{" || two === "}}" || two === "||" || two === "##") {
206
- out += two;
207
- i += 2;
208
- continue;
209
- }
210
- const ch = message[i];
211
- if (ch === "{") {
212
- const end = matchBrace$1(message, i);
213
- out += message.slice(i, end);
214
- i = end;
215
- continue;
216
- }
217
- if (ch === "<") {
218
- TAG_AT.lastIndex = i;
219
- const m = TAG_AT.exec(message);
220
- if (m) {
221
- out += m[0];
222
- i += m[0].length;
223
- continue;
224
- }
142
+ //#region src/registry.ts
143
+ var MessageRegistry = class {
144
+ files = /* @__PURE__ */ new Map();
145
+ update(file, analysis) {
146
+ this.files.set(file, analysis);
147
+ }
148
+ remove(file) {
149
+ this.files.delete(file);
150
+ }
151
+ messages() {
152
+ const out = /* @__PURE__ */ new Map();
153
+ for (const analysis of this.inOrder()) for (const msg of analysis.tagged) {
154
+ const held = out.get(msg.key);
155
+ if (!held || earlier(msg, held)) out.set(msg.key, msg);
225
156
  }
226
- const mapped = ACCENTS[ch];
227
- if (mapped) {
228
- out += mapped;
229
- letters += 1;
230
- } else out += ch;
231
- i += 1;
157
+ return out;
232
158
  }
233
- const pad = "~".repeat(Math.ceil(letters / 3));
234
- return `⟦${out}${pad ? " " + pad : ""}⟧`;
235
- }
236
- function matchBrace$1(message, start) {
237
- let depth = 0;
238
- for (let i = start; i < message.length; i++) {
239
- const two = message.slice(i, i + 2);
240
- if (two === "{{" || two === "}}") {
241
- i += 1;
242
- continue;
159
+ collisions() {
160
+ const winners = this.messages();
161
+ const dropped = /* @__PURE__ */ new Map();
162
+ for (const analysis of this.inOrder()) for (const msg of analysis.tagged) {
163
+ if (msg.message === winners.get(msg.key).message) continue;
164
+ dropped.set(msg.key, [...dropped.get(msg.key) ?? [], msg]);
243
165
  }
244
- const ch = message[i];
245
- if (ch === "{") depth += 1;
246
- else if (ch === "}") {
247
- depth -= 1;
248
- if (depth === 0) return i + 1;
166
+ return [...dropped].map(([key, others]) => ({
167
+ key,
168
+ kept: winners.get(key),
169
+ dropped: others.sort((a, b) => earlier(a, b) ? -1 : 1)
170
+ }));
171
+ }
172
+ usedKeys(strict = false) {
173
+ const out = /* @__PURE__ */ new Map();
174
+ for (const analysis of this.inOrder()) for (const used of analysis.usedKeys) {
175
+ if (strict && used.loose) continue;
176
+ const files = out.get(used.key) ?? [];
177
+ if (!files.includes(used.file)) files.push(used.file);
178
+ out.set(used.key, files);
249
179
  }
180
+ return out;
250
181
  }
251
- return message.length;
252
- }
253
- function pseudoCatalogs(cfg, catalogs, locale = PSEUDO_LOCALE) {
254
- const source = catalogs[cfg.sourceLocale] ?? {};
255
- const target = emptyCatalog();
256
- for (const [key, msg] of Object.entries(source)) target[key] = msg ? pseudoLocalize(msg) : "";
257
- catalogs[locale] = target;
258
- return Object.keys(target).filter((key) => target[key]);
259
- }
260
- //#endregion
261
- //#region src/config.ts
262
- function resolveConfig(config = {}) {
263
- const root = resolve(config.root ?? process.cwd());
264
- const dir = resolve(root, config.dir ?? "locales");
265
- const sourceLocale = config.sourceLocale ?? "en";
266
- const localesDeclared = config.locales !== void 0;
267
- const locales = /* @__PURE__ */ new Set([sourceLocale, ...config.locales ?? []]);
268
- if (!localesDeclared && existsSync(dir)) {
269
- for (const file of readdirSync(dir)) if (file.endsWith(".json") && !file.startsWith(".") && file !== `en-XA.json`) locales.add(file.slice(0, -5));
182
+ strayImports() {
183
+ return this.inOrder().flatMap((analysis) => analysis.strayImports);
270
184
  }
271
- return {
272
- root,
273
- dir,
274
- sourceLocale,
275
- localesDeclared,
276
- routing: config.routing ?? (config.render ? "prefix-except-source" : "no-prefix"),
277
- icu: config.icu,
278
- relative: config.relative,
279
- locales: [...locales],
280
- include: config.include ?? ["{src,app}/**/*.{js,jsx,ts,tsx,mjs,mts,svelte,vue,astro}"],
281
- exclude: config.exclude ?? ["**/node_modules/**", "**/dist/**"],
282
- dts: typeof config.dts === "string" ? resolve(root, config.dts) : config.dts,
283
- translate: config.translate ?? {},
284
- render: config.render ?? {},
285
- bundle: config.bundle ?? {}
286
- };
287
- }
288
- const CONFIG_FILES = [
289
- "verbaly.config.js",
290
- "verbaly.config.mjs",
291
- "verbaly.config.ts",
292
- "verbaly.config.mts",
293
- "verbaly.config.json"
294
- ];
295
- function findConfigFile(root) {
296
- return CONFIG_FILES.find((name) => existsSync(join(root, name)));
297
- }
298
- async function loadConfigFile(root) {
299
- for (const name of ["verbaly.config.js", "verbaly.config.mjs"]) {
300
- const path = join(root, name);
301
- if (existsSync(path)) return (await import(pathToFileURL(path).href)).default ?? {};
185
+ missed() {
186
+ return this.inOrder().flatMap((analysis) => analysis.missed);
302
187
  }
303
- for (const name of ["verbaly.config.ts", "verbaly.config.mts"]) {
304
- const path = join(root, name);
305
- if (existsSync(path)) return loadTsConfig(path);
188
+ parseErrors() {
189
+ const out = [];
190
+ for (const file of [...this.files.keys()].sort()) {
191
+ const { parseError } = this.files.get(file);
192
+ if (parseError) out.push({
193
+ file,
194
+ message: parseError
195
+ });
196
+ }
197
+ return out;
306
198
  }
307
- const jsonPath = join(root, "verbaly.config.json");
308
- if (existsSync(jsonPath)) return readJsonConfig(jsonPath);
309
- return {};
310
- }
311
- function readJsonConfig(path) {
312
- const content = readFileSync(path, "utf8");
313
- const body = content.charCodeAt(0) === 65279 ? content.slice(1) : content;
314
- try {
315
- return JSON.parse(body);
316
- } catch (error) {
317
- throw new Error(`[verbaly] ${path} is not valid JSON: ${error.message}`, { cause: error });
199
+ origins() {
200
+ const out = this.usedKeys();
201
+ for (const analysis of this.inOrder()) for (const msg of analysis.tagged) {
202
+ const files = out.get(msg.key) ?? [];
203
+ if (!files.includes(msg.file)) files.push(msg.file);
204
+ out.set(msg.key, files);
205
+ }
206
+ return out;
318
207
  }
319
- }
320
- async function loadTsConfig(path) {
321
- try {
322
- const { bundleRequire } = await import("bundle-require");
323
- const { mod } = await bundleRequire({ filepath: path });
324
- return mod.default ?? {};
325
- } catch (error) {
326
- if (isModuleNotFound(error, "esbuild")) throw new Error(`[verbaly] ${path} needs esbuild: install it with pnpm add -D esbuild`, { cause: error });
327
- throw error;
208
+ inOrder() {
209
+ return [...this.files.keys()].sort().map((file) => this.files.get(file));
328
210
  }
329
- }
330
- function isModuleNotFound(error, name) {
331
- return error instanceof Error && error.code === "ERR_MODULE_NOT_FOUND" && error.message.includes(name);
332
- }
333
- function targetLocales(cfg, override) {
334
- return (override ?? cfg.locales).filter((locale) => locale !== cfg.sourceLocale && cfg.locales.includes(locale));
335
- }
336
- async function loadConfig(root, overrides = {}) {
337
- return resolveConfig({
338
- ...await loadConfigFile(root),
339
- ...definedOnly(overrides),
340
- root
341
- });
342
- }
343
- function definedOnly(config) {
344
- return Object.fromEntries(Object.entries(config).filter(([, value]) => value !== void 0));
211
+ };
212
+ function earlier(a, b) {
213
+ return a.file === b.file ? a.start < b.start : a.file < b.file;
345
214
  }
346
215
  //#endregion
347
- //#region src/tag.ts
348
- function isLocaleTag(tag) {
349
- try {
350
- Intl.getCanonicalLocales(tag);
351
- return true;
352
- } catch {
353
- return false;
354
- }
216
+ //#region src/key.ts
217
+ function stableKey(message) {
218
+ return createHash("sha256").update(message).digest("base64url").slice(0, 8);
355
219
  }
356
- function suggestTag(tag) {
357
- const near = tag.replace(/_/g, "-");
358
- return near !== tag && isLocaleTag(near) ? near : void 0;
220
+ //#endregion
221
+ //#region src/analyze.ts
222
+ function parseErrorMessage(error) {
223
+ return error instanceof Error ? error.message : String(error);
359
224
  }
360
- function projectLocale(tag, locales) {
361
- if (locales.includes(tag)) return tag;
362
- const plain = (value) => value.replace(/_/g, "-").toLowerCase();
363
- return locales.find((locale) => plain(locale) === plain(tag));
225
+ const SKIP_KEYS = /* @__PURE__ */ new Set([
226
+ "loc",
227
+ "leadingComments",
228
+ "trailingComments",
229
+ "innerComments",
230
+ "extra"
231
+ ]);
232
+ const DEFAULT_T_NAMES = ["t"];
233
+ const JSX_FILE_RE = /\.(?:[cm]?jsx?|tsx)$/;
234
+ const DEFINE_KEYS = "defineKeys";
235
+ function analyze(code, file, options = {}) {
236
+ return analyzeScript(code, file, options).analysis;
364
237
  }
365
- //#endregion
366
- //#region src/init.ts
367
- const HOSTS = [
368
- {
369
- name: "nuxt",
370
- dep: "nuxt",
371
- pkg: "@verbaly/nuxt",
372
- wire: "add '@verbaly/nuxt' to the modules in nuxt.config"
373
- },
374
- {
375
- name: "next",
376
- dep: "next",
377
- pkg: "@verbaly/next",
378
- wire: "wrap the export of next.config with withVerbaly"
379
- },
380
- {
381
- name: "sveltekit",
382
- dep: "@sveltejs/kit",
383
- pkg: "@verbaly/vite",
384
- wire: "add verbaly() to the plugins in vite.config (per-request locale: @verbaly/sveltekit)"
385
- },
386
- {
387
- name: "astro",
388
- dep: "astro",
389
- pkg: "@verbaly/astro",
390
- wire: "add verbaly() to the integrations in astro.config"
391
- },
392
- {
393
- name: "vite",
394
- dep: "vite",
395
- pkg: "@verbaly/vite",
396
- wire: "add verbaly() to the plugins in vite.config"
397
- },
398
- {
399
- name: "webpack",
400
- dep: "webpack",
401
- pkg: "@verbaly/unplugin",
402
- wire: "add the verbaly webpack plugin to your build config"
403
- },
404
- {
405
- name: "rspack",
406
- dep: "@rspack/core",
407
- pkg: "@verbaly/unplugin",
408
- wire: "add the verbaly rspack plugin to your build config"
409
- },
410
- {
411
- name: "rollup",
412
- dep: "rollup",
413
- pkg: "@verbaly/unplugin",
414
- wire: "add the verbaly rollup plugin to your build config"
415
- },
416
- {
417
- name: "esbuild",
418
- dep: "esbuild",
419
- pkg: "@verbaly/unplugin",
420
- wire: "add the verbaly esbuild plugin to your build config"
238
+ function analyzeScript(code, file, options = {}) {
239
+ const names = new Set(options.tNames ?? DEFAULT_T_NAMES);
240
+ const ast = parse$1(code, {
241
+ sourceType: "module",
242
+ errorRecovery: true,
243
+ plugins: JSX_FILE_RE.test(file) ? ["typescript", "jsx"] : ["typescript"]
244
+ });
245
+ const tagged = [];
246
+ const usedKeys = [];
247
+ const strayImports = [];
248
+ const bindings = new Bindings(names);
249
+ const candidates = [];
250
+ walk$1(ast.program, (node) => {
251
+ if (node.type === "ImportDeclaration") {
252
+ collectStrayImports(node, file, strayImports);
253
+ bindings.addImport(node);
254
+ } else if (node.type === "VariableDeclarator") bindings.addDeclarator(node);
255
+ else if (node.type === "TaggedTemplateExpression") {
256
+ const tag = node.tag;
257
+ const explicit = explicitId(tag, names);
258
+ if (!explicit && !isTReference(tag, names)) {
259
+ candidates.push({
260
+ kind: "tag",
261
+ node
262
+ });
263
+ return;
264
+ }
265
+ const quasi = node.quasi;
266
+ const message = buildMessage(code, quasi, names);
267
+ if (!message) return;
268
+ tagged.push({
269
+ key: explicit ? explicit.key : stableKey(message.text),
270
+ message: message.text,
271
+ params: message.params,
272
+ start: node.start,
273
+ end: node.end,
274
+ line: lineOf(node),
275
+ tagStart: explicit ? explicit.refStart : tag.start,
276
+ tagEnd: explicit ? explicit.refEnd : tag.end,
277
+ file
278
+ });
279
+ } else if (node.type === "CallExpression") {
280
+ const callee = node.callee;
281
+ const args = node.arguments;
282
+ if (callee.type === "Identifier" && callee.name === DEFINE_KEYS) {
283
+ collectDeclaredKeys(args[0], file, usedKeys);
284
+ return;
285
+ }
286
+ if (!isTReference(callee, names)) {
287
+ const key = callee.type === "Identifier" ? staticString(args[0]) : void 0;
288
+ if (key !== void 0) candidates.push({
289
+ kind: "call",
290
+ name: callee.name,
291
+ key
292
+ });
293
+ return;
294
+ }
295
+ const key = staticString(args[0]);
296
+ if (key !== void 0) usedKeys.push(usedKey(key, file, args[0]));
297
+ } else if (node.type === "JSXElement") handleTrans(code, node, file, tagged, usedKeys, names);
298
+ });
299
+ const renamed = bindings.renamed(options.renamed);
300
+ const missed = [];
301
+ for (const candidate of candidates) {
302
+ if (candidate.kind === "call") {
303
+ if (renamed.has(candidate.name)) usedKeys.push({
304
+ key: candidate.key,
305
+ file,
306
+ loose: true
307
+ });
308
+ continue;
309
+ }
310
+ const { node } = candidate;
311
+ const name = renamedTag(node.tag, renamed);
312
+ if (!name) continue;
313
+ missed.push({
314
+ name,
315
+ file,
316
+ start: node.start,
317
+ line: lineOf(node)
318
+ });
319
+ const key = missedKey(code, node, names);
320
+ if (key !== void 0) usedKeys.push({
321
+ key,
322
+ file,
323
+ loose: true
324
+ });
421
325
  }
422
- ];
423
- const WIRING_PACKAGES = [...new Set(HOSTS.map((host) => host.pkg))];
424
- function readDependencies(root) {
425
- const path = join(root, "package.json");
426
- if (!existsSync(path)) return {};
427
- try {
428
- const pkg = JSON.parse(readFileSync(path, "utf8"));
326
+ return {
327
+ analysis: {
328
+ tagged,
329
+ usedKeys,
330
+ strayImports,
331
+ missed
332
+ },
333
+ renamed: [...renamed]
334
+ };
335
+ }
336
+ function lineOf(node) {
337
+ return node.loc?.start.line ?? 1;
338
+ }
339
+ const VERBALY_SOURCE = /^(?:verbaly|virtual:verbaly|@verbaly\/[\w-]+(?:\/[\w-]+)*)$/;
340
+ const T_FACTORIES = /* @__PURE__ */ new Map([["useT", "call"], ["getT", "await"]]);
341
+ const INSTANCE_FACTORIES = /* @__PURE__ */ new Set(["useVerbaly", "getVerbaly"]);
342
+ var Bindings = class {
343
+ names;
344
+ imports = /* @__PURE__ */ new Map();
345
+ direct = /* @__PURE__ */ new Set();
346
+ declared = [];
347
+ destructured = [];
348
+ constructor(names) {
349
+ this.names = names;
350
+ }
351
+ addImport(node) {
352
+ const source = node.source.value;
353
+ if (typeof source !== "string") return;
354
+ for (const spec of node.specifiers) {
355
+ const local = identifierName(spec.local);
356
+ if (!local) continue;
357
+ const imported = spec.type === "ImportSpecifier" ? importedName(spec.imported) : spec.type;
358
+ this.imports.set(local, {
359
+ source,
360
+ imported
361
+ });
362
+ if (source === "virtual:verbaly" && imported === "t") this.direct.add(local);
363
+ }
364
+ }
365
+ addDeclarator(node) {
366
+ const id = node.id;
367
+ const init = node.init;
368
+ if (!init) return;
369
+ if (id.type === "Identifier") {
370
+ this.declared.push({
371
+ name: id.name,
372
+ init
373
+ });
374
+ return;
375
+ }
376
+ if (id.type !== "ObjectPattern") return;
377
+ for (const property of id.properties) {
378
+ if (property.type !== "ObjectProperty" || property.computed) continue;
379
+ if (identifierName(property.key) !== "t") continue;
380
+ const value = property.value;
381
+ const name = identifierName(value.type === "AssignmentPattern" ? value.left : value);
382
+ if (name) this.destructured.push({
383
+ name,
384
+ init
385
+ });
386
+ }
387
+ }
388
+ renamed(seed = []) {
389
+ const out = new Set(seed);
390
+ const add = (name) => {
391
+ if (this.names.has(name)) return;
392
+ out.add(name);
393
+ if (this.names.has("$t")) out.add(`$${name}`);
394
+ };
395
+ for (const name of this.direct) add(name);
396
+ for (const { name, init } of this.declared) if (this.handsOutT(init)) add(name);
397
+ for (const { name, init } of this.destructured) if (this.carriesT(init)) add(name);
398
+ return out;
399
+ }
400
+ handsOutT(init) {
401
+ const awaited = init.type === "AwaitExpression";
402
+ const call = awaited ? init.argument : init;
403
+ if (call.type !== "CallExpression") return false;
404
+ const origin = this.origin(identifierName(call.callee));
405
+ if (origin.verbaly === false) return false;
406
+ const how = T_FACTORIES.get(origin.imported);
407
+ return how !== void 0 && how === "await" === awaited;
408
+ }
409
+ carriesT(init) {
410
+ const inner = init.type === "AwaitExpression" ? init.argument : init;
411
+ const name = identifierName(inner.type === "CallExpression" ? inner.callee : inner);
412
+ if (!name) return false;
413
+ return this.origin(name).verbaly ?? INSTANCE_FACTORIES.has(name);
414
+ }
415
+ origin(local) {
416
+ const found = this.imports.get(local);
417
+ if (!found) return {
418
+ verbaly: void 0,
419
+ imported: local
420
+ };
429
421
  return {
430
- ...pkg.dependencies,
431
- ...pkg.devDependencies
422
+ verbaly: VERBALY_SOURCE.test(found.source),
423
+ imported: found.imported
432
424
  };
433
- } catch {
434
- return {};
435
425
  }
426
+ };
427
+ function importedName(node) {
428
+ return node.type === "StringLiteral" ? node.value : identifierName(node);
436
429
  }
437
- function cliReachable(root) {
438
- const bin = join(root, "node_modules", ".bin");
439
- return existsSync(join(bin, "verbaly")) || existsSync(join(bin, "verbaly.CMD"));
430
+ function identifierName(node) {
431
+ return node?.type === "Identifier" ? node.name : "";
440
432
  }
441
- const CLI_INSTALL_FIX = "add `@verbaly/compiler` to your dev dependencies, then `npx verbaly` resolves";
442
- function detectHost(root) {
443
- const deps = readDependencies(root);
444
- return HOSTS.find((host) => deps[host.dep]);
433
+ function renamedTag(tag, renamed) {
434
+ if (renamed.size === 0) return void 0;
435
+ const name = identifierName(tag);
436
+ if (renamed.has(name)) return name;
437
+ if (tag.type !== "CallExpression") return void 0;
438
+ const callee = tag.callee;
439
+ if (callee.type !== "MemberExpression" || callee.computed) return void 0;
440
+ if (identifierName(callee.property) !== "id") return void 0;
441
+ const object = identifierName(callee.object);
442
+ return renamed.has(object) ? object : void 0;
445
443
  }
446
- function configSource(options, typescript) {
447
- const fields = [` sourceLocale: '${options.sourceLocale ?? "en"}',`];
448
- if (options.locales?.length) fields.push(` locales: [${options.locales.map((l) => `'${l}'`).join(", ")}],`);
449
- if (options.dir) fields.push(` dir: '${options.dir}',`);
450
- const body = `export default {\n${fields.join("\n")}\n}`;
451
- if (typescript) return `import type { VerbalyConfig } from '@verbaly/compiler';\n\n${body} satisfies VerbalyConfig;\n`;
452
- return `/** @type {import('@verbaly/compiler').VerbalyConfig} */\n${body};\n`;
444
+ function missedKey(code, node, names) {
445
+ const tag = node.tag;
446
+ if (tag.type === "CallExpression") {
447
+ const args = tag.arguments;
448
+ const first = args[0];
449
+ return args.length === 1 && first?.type === "StringLiteral" ? first.value : void 0;
450
+ }
451
+ const message = buildMessage(code, node.quasi, names);
452
+ return message ? stableKey(message.text) : void 0;
453
453
  }
454
- async function init(input = {}) {
455
- const root = input.root ?? process.cwd();
456
- const created = [];
457
- const skipped = [];
458
- const renamed = [];
459
- const refused = [];
460
- const typed = input.locales?.flatMap((locale) => {
461
- if (isLocaleTag(locale)) return [locale];
462
- const near = suggestTag(locale);
463
- if (near) renamed.push({
464
- from: locale,
465
- to: near
454
+ function collectDeclaredKeys(node, file, out) {
455
+ if (node?.type !== "ObjectExpression") return;
456
+ for (const property of node.properties) {
457
+ if (property.type !== "ObjectProperty") continue;
458
+ const value = property.value;
459
+ const key = staticString(value);
460
+ if (key !== void 0) {
461
+ if (key !== "") out.push(usedKey(key, file, value));
462
+ } else if (value.type === "ObjectExpression") collectDeclaredKeys(value, file, out);
463
+ }
464
+ }
465
+ function usedKey(key, file, node) {
466
+ return node?.type === "StringLiteral" ? {
467
+ key,
468
+ file
469
+ } : {
470
+ key,
471
+ file,
472
+ loose: true
473
+ };
474
+ }
475
+ function staticString(node) {
476
+ if (!node) return void 0;
477
+ if (node.type === "StringLiteral") return node.value;
478
+ if (node.type === "TemplateLiteral" && node.expressions.length === 0) return cookedValue(node.quasis[0]);
479
+ if (node.type === "JSXExpressionContainer") return staticString(node.expression);
480
+ }
481
+ const VERBALY_PACKAGE = /^(?:verbaly|@verbaly\/[\w-]+)$/;
482
+ function collectStrayImports(node, file, out) {
483
+ const source = node.source;
484
+ if (typeof source.value !== "string" || !VERBALY_PACKAGE.test(source.value)) return;
485
+ for (const spec of node.specifiers) {
486
+ if (spec.type !== "ImportSpecifier") continue;
487
+ const imported = spec.imported;
488
+ if (imported.type !== "Identifier") continue;
489
+ const name = imported.name;
490
+ if (name === "t" || name === DEFINE_KEYS) out.push({
491
+ name,
492
+ source: source.value,
493
+ file
466
494
  });
467
- else refused.push(locale);
468
- return near ? [near] : [];
495
+ }
496
+ }
497
+ function handleTrans(code, node, file, tagged, usedKeys, names) {
498
+ const opening = node.openingElement;
499
+ const nameNode = opening.name;
500
+ if (nameNode.type !== "JSXIdentifier" || nameNode.name !== "Trans") return;
501
+ const attrs = opening.attributes;
502
+ const idAttr = attrs.find((a) => a.type === "JSXAttribute" && a.name.name === "id");
503
+ const children = node.children;
504
+ const push = (key, built) => tagged.push({
505
+ key,
506
+ message: built.text,
507
+ params: built.params,
508
+ start: node.start,
509
+ end: node.end,
510
+ line: lineOf(node),
511
+ tagStart: nameNode.start,
512
+ tagEnd: nameNode.end,
513
+ file,
514
+ jsx: {
515
+ name: nameNode.name,
516
+ components: built.components
517
+ }
469
518
  });
470
- const locales = typed && [...new Set(typed)];
471
- let sourceLocale = input.sourceLocale;
472
- if (sourceLocale !== void 0 && !isLocaleTag(sourceLocale)) {
473
- const near = suggestTag(sourceLocale);
474
- if (!near) throw new Error(`[verbaly] "${sourceLocale}" is not a locale tag: pass --source with one like en or pt-BR`);
475
- renamed.push({
476
- from: sourceLocale,
477
- to: near
478
- });
479
- sourceLocale = near;
519
+ if (idAttr) {
520
+ const value = idAttr.value;
521
+ const id = staticString(value);
522
+ if (id === void 0) return;
523
+ if (value?.type === "StringLiteral" && attrs.length === 1 && children?.length) {
524
+ const built = buildTransMessage(code, children, names);
525
+ if (built?.text.trim()) {
526
+ push(id, built);
527
+ return;
528
+ }
529
+ }
530
+ usedKeys.push(usedKey(id, file, value));
531
+ return;
480
532
  }
481
- const options = {
482
- ...input,
483
- locales,
484
- sourceLocale
533
+ if (attrs.length > 0) return;
534
+ if (!children?.length) return;
535
+ const built = buildTransMessage(code, children, names);
536
+ if (!built || !built.text.trim()) return;
537
+ push(stableKey(built.text), built);
538
+ }
539
+ function explicitId(tag, names) {
540
+ if (tag.type !== "CallExpression") return void 0;
541
+ const callee = tag.callee;
542
+ if (callee.type !== "MemberExpression" || callee.computed) return void 0;
543
+ const prop = callee.property;
544
+ if (prop.type !== "Identifier" || prop.name !== "id") return void 0;
545
+ const obj = callee.object;
546
+ if (!isTReference(obj, names)) return void 0;
547
+ const args = tag.arguments;
548
+ const first = args[0];
549
+ if (args.length !== 1 || first?.type !== "StringLiteral") return void 0;
550
+ return {
551
+ key: first.value,
552
+ refStart: obj.start,
553
+ refEnd: obj.end
485
554
  };
486
- const existing = findConfigFile(root);
487
- const typescript = existsSync(join(root, "tsconfig.json"));
488
- const configFile = existing ?? (typescript ? "verbaly.config.ts" : "verbaly.config.mjs");
489
- if (existing) skipped.push(existing);
490
- else {
491
- writeFileSync(join(root, configFile), configSource(options, typescript));
492
- created.push(configFile);
555
+ }
556
+ function buildTransMessage(code, children, names) {
557
+ const params = [];
558
+ const components = [];
559
+ const takenParams = /* @__PURE__ */ new Map();
560
+ const takenTags = /* @__PURE__ */ new Map();
561
+ function walkChildren(nodes) {
562
+ let text = "";
563
+ for (const child of nodes) if (child.type === "JSXText") text += escapeText(cleanJsxText(child.value));
564
+ else if (child.type === "JSXExpressionContainer") {
565
+ const expr = child.expression;
566
+ if (expr.type === "JSXEmptyExpression") continue;
567
+ if (expr.type === "StringLiteral") {
568
+ text += escapeText(expr.value);
569
+ continue;
570
+ }
571
+ if (containsTaggedT(expr, names)) return void 0;
572
+ const source = code.slice(expr.start, expr.end);
573
+ const name = uniqueName(deriveName(expr, params.length), source, takenParams);
574
+ params.push({
575
+ name,
576
+ start: expr.start,
577
+ end: expr.end
578
+ });
579
+ text += `{${name}}`;
580
+ } else if (child.type === "JSXElement") {
581
+ const opening = child.openingElement;
582
+ const nameNode = opening.name;
583
+ if (nameNode.type !== "JSXIdentifier" || nameNode.name === "Trans") return void 0;
584
+ const source = selfClosedSource(code, opening);
585
+ const tag = uniqueName(nameNode.name.toLowerCase(), source, takenTags);
586
+ if (!components.some((c) => c.name === tag)) components.push({
587
+ name: tag,
588
+ source
589
+ });
590
+ if (!child.closingElement) text += `<${tag}/>`;
591
+ else {
592
+ const inner = walkChildren(child.children);
593
+ if (inner === void 0) return void 0;
594
+ text += `<${tag}>${inner}</${tag}>`;
595
+ }
596
+ } else return;
597
+ return text;
493
598
  }
494
- const fromFile = existing ? await loadConfigFile(root) : {};
495
- const scaffold = {
496
- dir: options.dir ?? fromFile.dir,
497
- sourceLocale: options.sourceLocale ?? fromFile.sourceLocale,
498
- locales: options.locales ?? fromFile.locales
599
+ const text = walkChildren(children);
600
+ if (text === void 0) return void 0;
601
+ return {
602
+ text,
603
+ params,
604
+ components
499
605
  };
500
- const dir = join(root, scaffold.dir ?? "locales");
501
- if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
502
- for (const locale of /* @__PURE__ */ new Set([scaffold.sourceLocale ?? "en", ...scaffold.locales ?? []])) {
503
- const file = join(dir, `${locale}.json`);
504
- const label = relative(root, file).replaceAll("\\", "/");
505
- if (existsSync(file)) skipped.push(label);
506
- else {
507
- writeFileSync(file, "{}\n");
508
- created.push(label);
509
- }
606
+ }
607
+ function cleanJsxText(raw) {
608
+ const lines = raw.split(/\r\n|[\r\n]/);
609
+ let out = "";
610
+ for (let i = 0; i < lines.length; i++) {
611
+ let line = lines[i].replace(/\t/g, " ");
612
+ if (i !== 0) line = line.replace(/^ +/, "");
613
+ if (i !== lines.length - 1) line = line.replace(/ +$/, "");
614
+ if (!line) continue;
615
+ if (out && i !== 0) out += " ";
616
+ out += line;
617
+ }
618
+ return out;
619
+ }
620
+ function selfClosedSource(code, opening) {
621
+ const src = code.slice(opening.start, opening.end);
622
+ return src.endsWith("/>") ? src : `${src.slice(0, -1).trimEnd()} />`;
623
+ }
624
+ function containsTaggedT(node, names) {
625
+ let found = false;
626
+ walk$1(node, (n) => {
627
+ if (n.type !== "TaggedTemplateExpression") return;
628
+ const tag = n.tag;
629
+ if (isTReference(tag, names) || explicitId(tag, names)) found = true;
630
+ });
631
+ return found;
632
+ }
633
+ function isTReference(node, names) {
634
+ if (node.type === "Identifier") return names.has(node.name);
635
+ if (node.type === "MemberExpression" && !node.computed) {
636
+ const prop = node.property;
637
+ return prop.type === "Identifier" && names.has(prop.name);
638
+ }
639
+ return false;
640
+ }
641
+ function buildMessage(code, quasi, names) {
642
+ const quasis = quasi.quasis;
643
+ const expressions = quasi.expressions;
644
+ const params = [];
645
+ const taken = /* @__PURE__ */ new Map();
646
+ let text = escapeText(cookedValue(quasis[0]));
647
+ for (let i = 0; i < expressions.length; i++) {
648
+ const expr = expressions[i];
649
+ if (!expr) return void 0;
650
+ if (containsTaggedT(expr, names)) return void 0;
651
+ const source = code.slice(expr.start, expr.end);
652
+ const name = uniqueName(deriveName(expr, i), source, taken);
653
+ params.push({
654
+ name,
655
+ start: expr.start,
656
+ end: expr.end
657
+ });
658
+ text += `{${name}}` + escapeText(cookedValue(quasis[i + 1]));
510
659
  }
511
- const host = detectHost(root);
512
- const next = host ? [`pnpm add -D ${host.pkg}`, host.wire] : ["run \"verbaly extract\" after writing your first t`…` message"];
513
660
  return {
514
- created,
515
- skipped,
516
- host: host?.name,
517
- configFile,
518
- next,
519
- renamed,
520
- refused
661
+ text,
662
+ params
521
663
  };
522
664
  }
523
- //#endregion
524
- //#region src/location.ts
525
- function lineAt(content, offset) {
526
- let line = 1;
527
- const end = Math.min(offset, content.length);
528
- for (let i = 0; i < end; i++) if (content[i] === "\n") line += 1;
529
- return line;
530
- }
531
- function createLocator() {
532
- const contents = /* @__PURE__ */ new Map();
533
- return (file, offset) => {
534
- if (!contents.has(file)) try {
535
- contents.set(file, readFileSync(file, "utf8"));
536
- } catch {
537
- contents.set(file, void 0);
538
- }
539
- const content = contents.get(file);
540
- return content === void 0 ? void 0 : lineAt(content, offset);
541
- };
665
+ function cookedValue(element) {
666
+ if (!element) return "";
667
+ const value = element.value;
668
+ return value.cooked ?? value.raw;
669
+ }
670
+ function escapeText(text) {
671
+ return text.replace(/[{}]/g, (m) => m + m);
672
+ }
673
+ function deriveName(expr, index) {
674
+ if (expr.type === "Identifier") return expr.name;
675
+ if (expr.type === "MemberExpression" && !expr.computed) {
676
+ const prop = expr.property;
677
+ if (prop.type === "Identifier") return prop.name;
678
+ }
679
+ return `_${index}`;
680
+ }
681
+ function uniqueName(base, source, taken) {
682
+ let name = base;
683
+ let n = 2;
684
+ while (taken.has(name) && taken.get(name) !== source) {
685
+ name = `${base}${n}`;
686
+ n += 1;
687
+ }
688
+ taken.set(name, source);
689
+ return name;
690
+ }
691
+ function walk$1(node, visit) {
692
+ visit(node);
693
+ for (const key in node) {
694
+ if (SKIP_KEYS.has(key)) continue;
695
+ const value = node[key];
696
+ if (Array.isArray(value)) {
697
+ for (const item of value) if (isNode(item)) walk$1(item, visit);
698
+ } else if (isNode(value)) walk$1(value, visit);
699
+ }
542
700
  }
543
- //#endregion
544
- //#region src/key.ts
545
- function stableKey(message) {
546
- return createHash("sha256").update(message).digest("base64url").slice(0, 8);
701
+ function isNode(value) {
702
+ return typeof value === "object" && value !== null && typeof value.type === "string";
547
703
  }
548
704
  //#endregion
549
- //#region src/state.ts
550
- const STATE_FILE = ".verbaly-state.json";
551
- const LEGACY_DRAFTS_FILE = ".verbaly-drafts.json";
552
- function statePath(cfg, file = STATE_FILE) {
553
- return join(cfg.dir, file);
554
- }
555
- function loadState(cfg) {
556
- const current = readJson(statePath(cfg));
557
- if (current !== void 0) {
558
- if (!isObject(current)) throw corrupt(statePath(cfg));
705
+ //#region src/sfc.ts
706
+ const SFC_FILE_RE = /\.(?:svelte|vue|astro)$/;
707
+ function analyzeFile(code, file) {
708
+ if (SFC_FILE_RE.test(file)) return analyzeSfc(code, file);
709
+ try {
710
+ return analyze(code, file);
711
+ } catch (error) {
559
712
  return {
560
- drafts: readDrafts(current.drafts),
561
- fingerprints: readFingerprints(current.fingerprints)
713
+ tagged: [],
714
+ usedKeys: [],
715
+ strayImports: [],
716
+ missed: [],
717
+ parseError: parseErrorMessage(error)
562
718
  };
563
719
  }
564
- const legacy = readJson(statePath(cfg, LEGACY_DRAFTS_FILE));
565
- if (legacy === void 0) return {
566
- drafts: {},
567
- fingerprints: {}
720
+ }
721
+ const SCRIPT_RE = /(<script\b[^>]*>)([\s\S]*?)(<\/script\s*>)/gi;
722
+ const STYLE_RE = /<style\b[^>]*>[\s\S]*?<\/style\s*>/gi;
723
+ const COMMENT_RE = /<!--[\s\S]*?-->/g;
724
+ const FRONTMATTER_RE = /^(\uFEFF?\s*---\r?\n)([\s\S]*?)\r?\n---(?=\r?\n|$)/;
725
+ const MUSTACHE_RE = /\{\{[\s\S]*?\}\}/g;
726
+ const DIRECTIVE_RE = /\s(?:v-[\w-]+(?::[^\s=>/]+)?|[:@][^\s=>/]+)\s*=\s*("[^"]*"|'[^']*')/g;
727
+ function analyzeSfc(code, file) {
728
+ const svelte = file.endsWith(".svelte");
729
+ const tNames = svelte ? ["t", "$t"] : ["t"];
730
+ const tagged = [];
731
+ const usedKeys = [];
732
+ const strayImports = [];
733
+ const missed = [];
734
+ const renamed = /* @__PURE__ */ new Set();
735
+ const lineAt = lineCounter(code);
736
+ let parseError;
737
+ const block = (content, offset) => {
738
+ const segment = analyzeSegment(content, file, { tNames });
739
+ parseError ??= segment.error;
740
+ for (const name of segment.renamed) renamed.add(name);
741
+ merge(segment.analysis, offset, false);
568
742
  };
569
- if (!isObject(legacy)) throw corrupt(statePath(cfg, LEGACY_DRAFTS_FILE));
570
- return {
571
- drafts: readDrafts(legacy),
572
- fingerprints: {}
743
+ const frontmatter = file.endsWith(".astro") ? FRONTMATTER_RE.exec(code) : null;
744
+ if (frontmatter?.[2]) block(frontmatter[2], frontmatter[1].length);
745
+ for (const match of code.matchAll(SCRIPT_RE)) {
746
+ const content = match[2];
747
+ if (content) block(content, match.index + match[1].length);
748
+ }
749
+ const markup = blank(blank(blank(frontmatter ? " ".repeat(frontmatter[0].length) + code.slice(frontmatter[0].length) : code, SCRIPT_RE), STYLE_RE), COMMENT_RE);
750
+ const markupOptions = {
751
+ tNames,
752
+ renamed: [...renamed]
573
753
  };
574
- }
575
- function saveState(cfg, state) {
576
- const serialized = serializeState(state);
577
- const path = statePath(cfg);
578
- const legacy = statePath(cfg, LEGACY_DRAFTS_FILE);
579
- if (serialized === void 0) {
580
- rmSync(path, { force: true });
581
- rmSync(legacy, { force: true });
582
- return;
754
+ const ranges = file.endsWith(".vue") ? vueExpressionRanges(markup) : braceRanges(markup);
755
+ let range = 0;
756
+ let consumedTo = 0;
757
+ for (const match of markup.matchAll(candidatePattern(svelte, renamed))) {
758
+ const start = match.index;
759
+ if (start < consumedTo) continue;
760
+ while (range < ranges.length && ranges[range][1] <= start) range += 1;
761
+ if (range >= ranges.length || start < ranges[range][0]) continue;
762
+ const end = expressionExtent(markup, start, match[0].length);
763
+ if (end === void 0) continue;
764
+ merge(analyzeSegment(code.slice(start, end), file, markupOptions).analysis, start, true);
765
+ consumedTo = end;
583
766
  }
584
- let existing;
585
- try {
586
- existing = readFileSync(path, "utf8");
587
- } catch {
588
- mkdirSync(cfg.dir, { recursive: true });
767
+ return {
768
+ tagged,
769
+ usedKeys,
770
+ strayImports,
771
+ missed,
772
+ ...parseError && { parseError }
773
+ };
774
+ function merge(analysis, offset, markupSegment) {
775
+ if (!analysis) return;
776
+ const lines = lineAt(offset) - 1;
777
+ for (const msg of analysis.tagged) tagged.push({
778
+ ...msg,
779
+ start: msg.start + offset,
780
+ end: msg.end + offset,
781
+ line: msg.line + lines,
782
+ tagStart: msg.tagStart + offset,
783
+ tagEnd: msg.tagEnd + offset,
784
+ params: msg.params.map((p) => ({
785
+ ...p,
786
+ start: p.start + offset,
787
+ end: p.end + offset
788
+ })),
789
+ ...markupSegment && { singleQuote: true }
790
+ });
791
+ for (const call of analysis.missed) missed.push({
792
+ ...call,
793
+ start: call.start + offset,
794
+ line: call.line + lines
795
+ });
796
+ usedKeys.push(...analysis.usedKeys);
797
+ strayImports.push(...analysis.strayImports);
589
798
  }
590
- if (existing !== serialized) writeFileSync(path, serialized);
591
- if (existsSync(legacy)) rmSync(legacy);
592
799
  }
593
- function updateState(cfg, catalogs) {
594
- const state = loadState(cfg);
595
- const next = {
596
- drafts: effectiveDrafts(state.drafts, catalogs),
597
- fingerprints: refreshFingerprints(cfg, catalogs, state.fingerprints)
800
+ function candidatePattern(svelte, renamed) {
801
+ const names = [.../* @__PURE__ */ new Set(["t", ...[...renamed].map((name) => name.replace(/^\$/, ""))])].map((name) => name.replace(/[$]/g, "\\$")).join("|");
802
+ return new RegExp(`(?<![\\w$])${svelte ? "\\$?" : ""}(?:${names})(?=[\`(]|\\.id\\()`, "g");
803
+ }
804
+ function lineCounter(code) {
805
+ const breaks = [];
806
+ for (let i = code.indexOf("\n"); i !== -1; i = code.indexOf("\n", i + 1)) breaks.push(i);
807
+ return (offset) => {
808
+ let low = 0;
809
+ let high = breaks.length;
810
+ while (low < high) {
811
+ const mid = low + high >> 1;
812
+ if (breaks[mid] < offset) low = mid + 1;
813
+ else high = mid;
814
+ }
815
+ return low + 1;
598
816
  };
599
- saveState(cfg, next);
600
- return next;
601
817
  }
602
- function effectiveDrafts(drafts, catalogs) {
603
- const out = {};
604
- for (const [locale, keys] of Object.entries(drafts)) {
605
- const catalog = catalogs[locale] ?? {};
606
- const live = keys.filter((key) => own(catalog, key));
607
- if (live.length) out[locale] = live;
818
+ function analyzeSegment(code, file, options) {
819
+ try {
820
+ return analyzeScript(code, file, options);
821
+ } catch (error) {
822
+ return {
823
+ renamed: [],
824
+ error: parseErrorMessage(error)
825
+ };
608
826
  }
609
- return out;
610
- }
611
- function fingerprint(text) {
612
- return stableKey(text);
613
- }
614
- function tracked(key, text) {
615
- return stableKey(text) !== key;
616
827
  }
617
- function stamp(source, translated) {
618
- return `${fingerprint(source)}.${fingerprint(translated)}`;
828
+ function blank(source, re) {
829
+ return source.replace(re, (m) => " ".repeat(m.length));
619
830
  }
620
- function refreshFingerprints(cfg, catalogs, previous) {
621
- const source = catalogs[cfg.sourceLocale] ?? {};
622
- const out = {};
623
- for (const locale of targetLocales(cfg)) {
624
- const catalog = catalogs[locale] ?? {};
625
- const before = previous[locale] ?? {};
626
- const after = emptyCatalog();
627
- for (const [key, text] of Object.entries(source)) {
628
- const translated = own(catalog, key);
629
- if (!text || !translated || !tracked(key, text)) continue;
630
- const was = own(before, key);
631
- after[key] = was !== void 0 && translationOf(was) === fingerprint(translated) ? was : stamp(text, translated);
831
+ function braceRanges(markup) {
832
+ const ranges = [];
833
+ let i = 0;
834
+ while (i < markup.length) {
835
+ if (markup[i] === "{") {
836
+ const end = balancedEnd(markup, i);
837
+ if (end !== void 0) {
838
+ ranges.push([i + 1, end - 1]);
839
+ i = end;
840
+ continue;
841
+ }
632
842
  }
633
- if (Object.keys(after).length) out[locale] = after;
843
+ i += 1;
634
844
  }
635
- return out;
845
+ return ranges;
636
846
  }
637
- function outdatedTranslations(cfg, catalogs, fingerprints) {
638
- const source = catalogs[cfg.sourceLocale] ?? {};
639
- const out = [];
640
- for (const locale of targetLocales(cfg)) {
641
- const catalog = catalogs[locale] ?? {};
642
- for (const [key, was] of Object.entries(fingerprints[locale] ?? {})) {
643
- const text = own(source, key);
644
- const translated = own(catalog, key);
645
- if (!text || !translated) continue;
646
- if (translationOf(was) !== fingerprint(translated)) continue;
647
- if (sourceOf(was) !== fingerprint(text)) out.push({
648
- locale,
649
- key
650
- });
651
- }
847
+ function vueExpressionRanges(markup) {
848
+ const ranges = [];
849
+ for (const match of markup.matchAll(MUSTACHE_RE)) ranges.push([match.index + 2, match.index + match[0].length - 2]);
850
+ for (const match of markup.matchAll(DIRECTIVE_RE)) {
851
+ const valueStart = match.index + match[0].length - match[1].length + 1;
852
+ ranges.push([valueStart, valueStart + match[1].length - 2]);
652
853
  }
653
- return out.sort((a, b) => a.locale.localeCompare(b.locale) || a.key.localeCompare(b.key));
854
+ return ranges.sort((a, b) => a[0] - b[0]);
654
855
  }
655
- function acceptOutdated(cfg, catalogs, fingerprints, entries) {
656
- const source = catalogs[cfg.sourceLocale] ?? {};
657
- for (const { locale, key } of entries) {
658
- const text = own(source, key);
659
- const translated = own(catalogs[locale] ?? {}, key);
660
- if (!text || !translated) continue;
661
- (fingerprints[locale] ??= emptyCatalog())[key] = stamp(text, translated);
856
+ function expressionExtent(code, start, nameLength) {
857
+ const i = start + nameLength;
858
+ if (code.startsWith(".id(", i)) {
859
+ const close = balancedEnd(code, i + 3);
860
+ if (close === void 0 || code[close] !== "`") return void 0;
861
+ return balancedEnd(code, close);
662
862
  }
863
+ if (code[i] === "`" || code[i] === "(") return balancedEnd(code, i);
663
864
  }
664
- function sourceOf(stamped) {
665
- return stamped.slice(0, stamped.indexOf("."));
666
- }
667
- function translationOf(stamped) {
668
- return stamped.slice(stamped.indexOf(".") + 1);
669
- }
670
- function serializeState(state) {
671
- const drafts = {};
672
- for (const locale of Object.keys(state.drafts).sort()) {
673
- const keys = [...new Set(state.drafts[locale])].sort();
674
- if (keys.length) drafts[locale] = keys;
675
- }
676
- const fingerprints = {};
677
- for (const locale of Object.keys(state.fingerprints).sort()) {
678
- const entries = state.fingerprints[locale] ?? {};
679
- const keys = Object.keys(entries).sort();
680
- if (!keys.length) continue;
681
- fingerprints[locale] = Object.fromEntries(keys.map((key) => [key, entries[key]]));
865
+ function balancedEnd(code, open) {
866
+ const stack = [];
867
+ let i = open;
868
+ while (i < code.length) {
869
+ const ch = code[i];
870
+ if (stack[stack.length - 1] === "`") {
871
+ if (ch === "\\") i += 1;
872
+ else if (ch === "`") stack.pop();
873
+ else if (ch === "$" && code[i + 1] === "{") {
874
+ stack.push("{");
875
+ i += 1;
876
+ }
877
+ } else if (ch === "'" || ch === "\"") i = stringEnd(code, i);
878
+ else if (ch === "`" || ch === "(" || ch === "{") stack.push(ch);
879
+ else if (ch === ")" || ch === "}") {
880
+ if (stack[stack.length - 1] !== (ch === ")" ? "(" : "{")) return void 0;
881
+ stack.pop();
882
+ }
883
+ i += 1;
884
+ if (stack.length === 0) return i;
682
885
  }
683
- const out = {};
684
- if (Object.keys(drafts).length) out.drafts = drafts;
685
- if (Object.keys(fingerprints).length) out.fingerprints = fingerprints;
686
- if (!out.drafts && !out.fingerprints) return void 0;
687
- return JSON.stringify(out, null, 2) + "\n";
688
886
  }
689
- function readJson(path) {
690
- let content;
691
- try {
692
- content = readFileSync(path, "utf8");
693
- } catch {
694
- return;
695
- }
696
- try {
697
- return JSON.parse(content.charCodeAt(0) === 65279 ? content.slice(1) : content);
698
- } catch (error) {
699
- throw corrupt(path, error);
700
- }
887
+ function stringEnd(code, start) {
888
+ const quote = code[start];
889
+ let i = start + 1;
890
+ while (i < code.length) if (code[i] === "\\") i += 2;
891
+ else if (code[i] === quote) return i;
892
+ else i += 1;
893
+ return code.length;
894
+ }
895
+ //#endregion
896
+ //#region src/extract.ts
897
+ async function extractProject(cfg) {
898
+ const files = await glob(cfg.include, {
899
+ cwd: cfg.root,
900
+ ignore: cfg.exclude,
901
+ absolute: true
902
+ });
903
+ const registry = new MessageRegistry();
904
+ for (const file of files.sort()) registry.update(file, analyzeFile(readFileSync(file, "utf8"), file));
905
+ return registry;
701
906
  }
702
- function corrupt(path, cause) {
703
- return new Error(`[verbaly] ${path} is not valid JSON, fix or delete the file`, { cause });
907
+ async function collectOrigins(cfg, reuse) {
908
+ const registry = reuse ?? await extractProject(cfg);
909
+ const origins = Object.create(null);
910
+ for (const [key, files] of registry.origins()) origins[key] = files.map((file) => relative(cfg.root, file).replaceAll("\\", "/"));
911
+ return origins;
704
912
  }
705
- function isObject(value) {
706
- return typeof value === "object" && value !== null && !Array.isArray(value);
913
+ function syncCatalogs(cfg, catalogs, registry) {
914
+ const added = {};
915
+ const replaced = [];
916
+ const source = catalogs[cfg.sourceLocale] ??= emptyCatalog();
917
+ for (const [key, msg] of registry.messages()) {
918
+ const before = own(source, key);
919
+ if (before === msg.message) continue;
920
+ source[key] = msg.message;
921
+ if (before) replaced.push({
922
+ key,
923
+ before
924
+ });
925
+ else (added[cfg.sourceLocale] ??= []).push(key);
926
+ }
927
+ const needed = Object.keys(source);
928
+ for (const locale of cfg.locales) {
929
+ if (locale === cfg.sourceLocale) continue;
930
+ const catalog = catalogs[locale] ??= emptyCatalog();
931
+ for (const key of needed) if (own(catalog, key) === void 0) {
932
+ catalog[key] = "";
933
+ (added[locale] ??= []).push(key);
934
+ }
935
+ }
936
+ return {
937
+ added,
938
+ replaced
939
+ };
707
940
  }
708
- function readDrafts(value) {
709
- const out = {};
710
- if (!isObject(value)) return out;
711
- for (const [locale, keys] of Object.entries(value)) if (Array.isArray(keys)) out[locale] = keys.filter((key) => typeof key === "string");
712
- return out;
941
+ function shippedCatalogs(cfg, catalogs, registry, options = {}) {
942
+ const source = Object.assign(emptyCatalog(), flatten(catalogs[cfg.sourceLocale] ?? {}));
943
+ for (const [key, msg] of registry.messages()) if (options.newKeys !== false || own(source, key) !== void 0) source[key] = msg.message;
944
+ return {
945
+ ...catalogs,
946
+ [cfg.sourceLocale]: source
947
+ };
713
948
  }
714
- function readFingerprints(value) {
715
- const out = {};
716
- if (!isObject(value)) return out;
717
- for (const [locale, entries] of Object.entries(value)) {
718
- if (!isObject(entries)) continue;
719
- const kept = emptyCatalog();
720
- for (const [key, stamped] of Object.entries(entries)) if (typeof stamped === "string" && stamped.includes(".")) kept[key] = stamped;
721
- out[locale] = kept;
949
+ function pruneCatalogs(cfg, catalogs, registry) {
950
+ const removed = {};
951
+ if (registry.parseErrors().length > 0) return removed;
952
+ const keep = /* @__PURE__ */ new Set([...registry.messages().keys(), ...registry.usedKeys().keys()]);
953
+ for (const locale of cfg.locales) {
954
+ const catalog = catalogs[locale];
955
+ if (!catalog) continue;
956
+ for (const key of Object.keys(catalog)) if (!keep.has(key)) {
957
+ delete catalog[key];
958
+ (removed[locale] ??= []).push(key);
959
+ }
722
960
  }
723
- return out;
961
+ return removed;
724
962
  }
725
963
  //#endregion
726
964
  //#region src/text.ts
727
965
  function counted(count, noun, many = `${noun}s`) {
728
966
  return `${count} ${count === 1 ? noun : many}`;
729
967
  }
968
+ function truncate(text, max) {
969
+ return text.length > max ? text.slice(0, max - 1) + "…" : text;
970
+ }
730
971
  //#endregion
731
972
  //#region src/validate.ts
732
973
  const read = (message) => parse(message, parseIcu);
@@ -740,10 +981,10 @@ const PLURAL_CATEGORIES = /* @__PURE__ */ new Set([
740
981
  const EXACT = /^=\d+$/;
741
982
  function shapes(message) {
742
983
  const out = /* @__PURE__ */ new Map();
743
- walk$1(read(message), out);
984
+ walk(read(message), out);
744
985
  return out;
745
986
  }
746
- function walk$1(nodes, out) {
987
+ function walk(nodes, out) {
747
988
  for (const node of nodes) {
748
989
  if (node.kind !== "param" || !node.variants) continue;
749
990
  const selectors = node.variants.map(([key]) => key);
@@ -752,7 +993,7 @@ function walk$1(nodes, out) {
752
993
  plural: selectors.some((key) => PLURAL_CATEGORIES.has(key)),
753
994
  ordinal: node.ordinal === true
754
995
  });
755
- for (const [, body] of node.variants) walk$1(body, out);
996
+ for (const [, body] of node.variants) walk(body, out);
756
997
  }
757
998
  }
758
999
  function paramNames(message) {
@@ -891,1056 +1132,1092 @@ function reachableCategories(locale, ordinal) {
891
1132
  return out;
892
1133
  }
893
1134
  //#endregion
894
- //#region src/check.ts
895
- function gatePasses(result) {
896
- return result.missing.length === 0 && result.unknown.length === 0 && !result.broken.some((entry) => entry.severity === "error");
897
- }
898
- function check(cfg, catalogs, registry, fingerprints = {}) {
899
- const extracted = registry.messages();
900
- const locate = createLocator();
901
- const site = (msg) => ({
1135
+ //#region src/findings.ts
1136
+ function siteOf(msg) {
1137
+ return {
902
1138
  file: msg.file,
903
- line: locate(msg.file, msg.start),
1139
+ line: msg.line,
904
1140
  message: msg.message
905
- });
906
- const flat = {};
907
- for (const locale of cfg.locales) flat[locale] = flatten(catalogs[locale] ?? {});
908
- const source = flat[cfg.sourceLocale] ?? {};
909
- const used = registry.usedKeys();
910
- const unknown = [];
911
- for (const [key, files] of registry.usedKeys(true)) if (!(extracted.has(key) || cfg.locales.some((locale) => flat[locale]?.[key] !== void 0))) unknown.push({
912
- key,
913
- files
914
- });
915
- const needed = /* @__PURE__ */ new Set([...extracted.keys(), ...Object.keys(source)]);
916
- const missing = [];
917
- for (const key of extracted.keys()) if (!source[key]) missing.push({
918
- locale: cfg.sourceLocale,
1141
+ };
1142
+ }
1143
+ function collisionEntries(registry) {
1144
+ return registry.collisions().map(({ key, kept, dropped }) => ({
919
1145
  key,
920
- source: extracted.get(key)?.message
921
- });
922
- for (const locale of cfg.locales) {
923
- if (locale === cfg.sourceLocale) continue;
924
- for (const key of needed) if (!flat[locale]?.[key]) missing.push({
925
- locale,
1146
+ sites: [kept, ...dropped].map(siteOf)
1147
+ }));
1148
+ }
1149
+ function scanFindings(cfg, registry, replaced = []) {
1150
+ const messages = registry.messages();
1151
+ const out = [];
1152
+ for (const { key, before } of replaced) {
1153
+ const msg = messages.get(key);
1154
+ if (msg) out.push({
1155
+ kind: "replaced",
1156
+ locale: cfg.sourceLocale,
926
1157
  key,
927
- source: source[key] ?? extracted.get(key)?.message
1158
+ before,
1159
+ site: siteOf(msg)
928
1160
  });
929
1161
  }
930
- const broken = [];
931
- const add = (locale, key, issues) => {
932
- for (const issue of issues) broken.push({
933
- locale,
934
- key,
935
- severity: issue.severity,
936
- issue: issue.message
1162
+ for (const entry of collisionEntries(registry)) out.push({
1163
+ kind: "collision",
1164
+ ...entry
1165
+ });
1166
+ for (const { name, file, line } of registry.missed()) out.push({
1167
+ kind: "renamed",
1168
+ name,
1169
+ file,
1170
+ line
1171
+ });
1172
+ for (const msg of messages.values()) {
1173
+ const params = msg.params.map((param) => param.name).filter((name) => /^_\d+$/.test(name));
1174
+ if (params.length > 0) out.push({
1175
+ kind: "positional",
1176
+ params,
1177
+ site: siteOf(msg)
937
1178
  });
938
- };
939
- const sourceText = Object.assign(emptyCatalog(), source);
940
- const divergent = [];
941
- for (const [key, entry] of extracted) {
942
- const written = sourceText[key];
943
- if (written && written !== entry.message) divergent.push({
944
- key,
945
- catalog: written,
946
- code: site(entry)
1179
+ const slice = escapedSyntax(msg.message);
1180
+ if (slice) out.push({
1181
+ kind: "escaped",
1182
+ slice,
1183
+ site: siteOf(msg)
947
1184
  });
948
- sourceText[key] = entry.message;
949
1185
  }
950
- for (const [key, text] of Object.entries(sourceText)) add(cfg.sourceLocale, key, validateMessage(text, cfg.sourceLocale));
951
- for (const locale of cfg.locales) {
952
- if (locale === cfg.sourceLocale) continue;
953
- for (const [key, translated] of Object.entries(flat[locale] ?? {})) {
954
- if (!translated) continue;
955
- add(locale, key, validateMessage(translated, locale));
956
- const text = sourceText[key];
957
- if (text) add(locale, key, validatePair(text, translated));
1186
+ for (const { file, message } of registry.parseErrors()) out.push({
1187
+ kind: "unparsed",
1188
+ file,
1189
+ message
1190
+ });
1191
+ return out;
1192
+ }
1193
+ function sourcePlace(at, root) {
1194
+ const file = root ? relative(root, at.file).replaceAll("\\", "/") : at.file;
1195
+ return at.line ? `${file}:${at.line}` : file;
1196
+ }
1197
+ function quoted(at, root) {
1198
+ return `"${truncate(at.message, 40)}" (${sourcePlace(at, root)})`;
1199
+ }
1200
+ function formatCollision({ key, sites }, root) {
1201
+ const [kept, ...others] = sites;
1202
+ const texts = new Set(sites.map((at) => at.message)).size;
1203
+ return `${key}: one key with ${counted(texts, "text")}, and every place shows ${quoted(kept, root)}, never ${others.map((at) => quoted(at, root)).join(" or ")}: give each text its own key`;
1204
+ }
1205
+ function formatFinding(finding, root) {
1206
+ switch (finding.kind) {
1207
+ case "collision": return formatCollision(finding, root);
1208
+ case "replaced": {
1209
+ const place = sourcePlace(finding.site, root);
1210
+ return finding.edited ? `${finding.locale}.json: your edit of "${finding.key}" was replaced, its text lives in ${place}: change it there` : `${finding.locale}: ${finding.key} follows the code (${place}): "${truncate(finding.site.message, 40)}", was "${truncate(finding.before, 40)}"`;
1211
+ }
1212
+ case "renamed": return `${sourcePlace(finding, root)}: ${finding.name}\`…\` is never extracted, so it stays in the source language: name it t`;
1213
+ case "positional": {
1214
+ const names = finding.params.map((name) => `{${name}}`).join(", ");
1215
+ return `${sourcePlace(finding.site, root)}: ${names} in "${truncate(finding.site.message, 60)}" reaches the translator without a name, put the value in a named variable first`;
1216
+ }
1217
+ case "escaped": return `${sourcePlace(finding.site, root)}: ${finding.slice} renders as literal text, a tagged template has no params (use t(key, params) for a plural or format block, or pass a \${…} value)`;
1218
+ case "unparsed": return `${sourcePlace(finding, root)}: could not be parsed (${finding.message}), its messages were not extracted`;
1219
+ case "outdated": return `[${finding.locale}] ${finding.key}: translated from an older source text, update it or keep it with \`npx verbaly review --approve\``;
1220
+ }
1221
+ }
1222
+ function findingId(finding) {
1223
+ switch (finding.kind) {
1224
+ case "collision":
1225
+ case "replaced": return `${finding.kind}:${finding.key}`;
1226
+ case "outdated": return `outdated:${finding.locale}:${finding.key}`;
1227
+ case "renamed": return `renamed:${finding.file}:${finding.name}`;
1228
+ case "positional": return `positional:${finding.site.file}:${finding.params.join(",")}`;
1229
+ case "escaped": return `escaped:${finding.site.file}:${finding.slice}`;
1230
+ case "unparsed": return `unparsed:${finding.file}`;
1231
+ }
1232
+ }
1233
+ function createDevReporter(root, print = (line) => console.warn(`[verbaly] ${line}`), cap = 5) {
1234
+ const shown = /* @__PURE__ */ new Map();
1235
+ return { report(channel, findings) {
1236
+ const before = shown.get(channel) ?? /* @__PURE__ */ new Set();
1237
+ const now = /* @__PURE__ */ new Set();
1238
+ const fresh = [];
1239
+ for (const finding of findings) {
1240
+ const id = findingId(finding);
1241
+ if (now.has(id)) continue;
1242
+ now.add(id);
1243
+ if (!before.has(id)) fresh.push(finding);
1244
+ }
1245
+ shown.set(channel, now);
1246
+ for (const finding of fresh.slice(0, cap)) print(formatFinding(finding, root));
1247
+ if (fresh.length > cap) print(`and ${fresh.length - cap} more: \`npx verbaly doctor\` names them`);
1248
+ } };
1249
+ }
1250
+ //#endregion
1251
+ //#region src/pseudo.ts
1252
+ const PSEUDO_LOCALE = "en-XA";
1253
+ const ACCENTS = {
1254
+ a: "á",
1255
+ b: "ƀ",
1256
+ c: "ç",
1257
+ d: "đ",
1258
+ e: "é",
1259
+ f: "ƒ",
1260
+ g: "ğ",
1261
+ h: "ĥ",
1262
+ i: "í",
1263
+ j: "ĵ",
1264
+ k: "ķ",
1265
+ l: "ĺ",
1266
+ m: "ɱ",
1267
+ n: "ñ",
1268
+ o: "ó",
1269
+ p: "þ",
1270
+ q: "ǫ",
1271
+ r: "ŕ",
1272
+ s: "š",
1273
+ t: "ţ",
1274
+ u: "ú",
1275
+ v: "ṽ",
1276
+ w: "ŵ",
1277
+ x: "ẋ",
1278
+ y: "ý",
1279
+ z: "ž",
1280
+ A: "Á",
1281
+ B: "Ɓ",
1282
+ C: "Ç",
1283
+ D: "Đ",
1284
+ E: "É",
1285
+ F: "Ƒ",
1286
+ G: "Ğ",
1287
+ H: "Ĥ",
1288
+ I: "Í",
1289
+ J: "Ĵ",
1290
+ K: "Ķ",
1291
+ L: "Ĺ",
1292
+ M: "Ḿ",
1293
+ N: "Ñ",
1294
+ O: "Ó",
1295
+ P: "Þ",
1296
+ Q: "Ǫ",
1297
+ R: "Ŕ",
1298
+ S: "Š",
1299
+ T: "Ţ",
1300
+ U: "Ú",
1301
+ V: "Ṽ",
1302
+ W: "Ŵ",
1303
+ X: "Ẍ",
1304
+ Y: "Ý",
1305
+ Z: "Ž"
1306
+ };
1307
+ const TAG_AT = /<\/?[a-zA-Z][\w-]*\/?>/y;
1308
+ function pseudoLocalize(message) {
1309
+ let out = "";
1310
+ let letters = 0;
1311
+ let i = 0;
1312
+ while (i < message.length) {
1313
+ const two = message.slice(i, i + 2);
1314
+ if (two === "{{" || two === "}}" || two === "||" || two === "##") {
1315
+ out += two;
1316
+ i += 2;
1317
+ continue;
1318
+ }
1319
+ const ch = message[i];
1320
+ if (ch === "{") {
1321
+ const end = matchBrace$1(message, i);
1322
+ out += message.slice(i, end);
1323
+ i = end;
1324
+ continue;
1325
+ }
1326
+ if (ch === "<") {
1327
+ TAG_AT.lastIndex = i;
1328
+ const m = TAG_AT.exec(message);
1329
+ if (m) {
1330
+ out += m[0];
1331
+ i += m[0].length;
1332
+ continue;
1333
+ }
958
1334
  }
1335
+ const mapped = ACCENTS[ch];
1336
+ if (mapped) {
1337
+ out += mapped;
1338
+ letters += 1;
1339
+ } else out += ch;
1340
+ i += 1;
959
1341
  }
960
- const extra = [];
961
- for (const locale of cfg.locales) {
962
- if (locale === cfg.sourceLocale) continue;
963
- for (const key of Object.keys(flat[locale] ?? {})) {
964
- if (source[key] !== void 0 || extracted.has(key)) continue;
965
- extra.push({
966
- locale,
967
- key,
968
- files: used.get(key) ?? []
969
- });
1342
+ const pad = "~".repeat(Math.ceil(letters / 3));
1343
+ return `⟦${out}${pad ? " " + pad : ""}⟧`;
1344
+ }
1345
+ function matchBrace$1(message, start) {
1346
+ let depth = 0;
1347
+ for (let i = start; i < message.length; i++) {
1348
+ const two = message.slice(i, i + 2);
1349
+ if (two === "{{" || two === "}}") {
1350
+ i += 1;
1351
+ continue;
1352
+ }
1353
+ const ch = message[i];
1354
+ if (ch === "{") depth += 1;
1355
+ else if (ch === "}") {
1356
+ depth -= 1;
1357
+ if (depth === 0) return i + 1;
970
1358
  }
971
1359
  }
972
- const collisions = collisionEntries(registry, locate);
973
- const outdated = outdatedTranslations(cfg, flat, fingerprints);
1360
+ return message.length;
1361
+ }
1362
+ function pseudoCatalogs(cfg, catalogs, locale = PSEUDO_LOCALE) {
1363
+ const source = catalogs[cfg.sourceLocale] ?? {};
1364
+ const target = emptyCatalog();
1365
+ for (const [key, msg] of Object.entries(source)) target[key] = msg ? pseudoLocalize(msg) : "";
1366
+ catalogs[locale] = target;
1367
+ return Object.keys(target).filter((key) => target[key]);
1368
+ }
1369
+ //#endregion
1370
+ //#region src/config.ts
1371
+ function resolveConfig(config = {}) {
1372
+ const root = resolve(config.root ?? process.cwd());
1373
+ const dir = resolve(root, config.dir ?? "locales");
1374
+ const sourceLocale = config.sourceLocale ?? "en";
1375
+ const localesDeclared = config.locales !== void 0;
1376
+ const locales = /* @__PURE__ */ new Set([sourceLocale, ...config.locales ?? []]);
1377
+ if (!localesDeclared && existsSync(dir)) {
1378
+ for (const file of readdirSync(dir)) if (file.endsWith(".json") && !file.startsWith(".") && file !== `en-XA.json`) locales.add(file.slice(0, -5));
1379
+ }
974
1380
  return {
975
- ok: gatePasses({
976
- missing,
977
- unknown,
978
- broken
979
- }),
980
- missing,
981
- unknown,
982
- broken,
983
- extra,
984
- collisions,
985
- divergent,
986
- outdated
1381
+ root,
1382
+ dir,
1383
+ sourceLocale,
1384
+ localesDeclared,
1385
+ routing: config.routing ?? (config.render ? "prefix-except-source" : "no-prefix"),
1386
+ icu: config.icu,
1387
+ relative: config.relative,
1388
+ locales: [...locales],
1389
+ include: config.include ?? ["{src,app}/**/*.{js,jsx,ts,tsx,mjs,mts,svelte,vue,astro}"],
1390
+ exclude: config.exclude ?? ["**/node_modules/**", "**/dist/**"],
1391
+ dts: typeof config.dts === "string" ? resolve(root, config.dts) : config.dts,
1392
+ translate: config.translate ?? {},
1393
+ render: config.render ?? {},
1394
+ bundle: config.bundle ?? {}
987
1395
  };
988
1396
  }
989
- function formatCheckResult(result, root) {
990
- const show = (file) => root ? relative(root, file).replaceAll("\\", "/") : file;
991
- const lines = [];
992
- if (result.missing.length > 0) {
993
- lines.push("missing translations:");
994
- for (const entry of result.missing) {
995
- const hint = entry.source ? `: "${truncate(entry.source, 40)}"` : "";
996
- lines.push(` [${entry.locale}] ${entry.key}${hint}`);
997
- }
1397
+ const CONFIG_FILES = [
1398
+ "verbaly.config.js",
1399
+ "verbaly.config.mjs",
1400
+ "verbaly.config.ts",
1401
+ "verbaly.config.mts",
1402
+ "verbaly.config.json"
1403
+ ];
1404
+ function findConfigFile(root) {
1405
+ return CONFIG_FILES.find((name) => existsSync(join(root, name)));
1406
+ }
1407
+ async function loadConfigFile(root) {
1408
+ for (const name of ["verbaly.config.js", "verbaly.config.mjs"]) {
1409
+ const path = join(root, name);
1410
+ if (existsSync(path)) return (await import(pathToFileURL(path).href)).default ?? {};
998
1411
  }
999
- if (result.unknown.length > 0) {
1000
- lines.push("unknown keys (not in any catalog):");
1001
- for (const entry of result.unknown) lines.push(` ${entry.key} (used in ${entry.files.map(show).join(", ")})`);
1412
+ for (const name of ["verbaly.config.ts", "verbaly.config.mts"]) {
1413
+ const path = join(root, name);
1414
+ if (existsSync(path)) return loadTsConfig(path);
1002
1415
  }
1003
- const errors = result.broken.filter((entry) => entry.severity === "error");
1004
- if (errors.length > 0) {
1005
- lines.push("broken translations:");
1006
- for (const entry of errors) lines.push(` [${entry.locale}] ${entry.key}: ${entry.issue}`);
1416
+ const jsonPath = join(root, "verbaly.config.json");
1417
+ if (existsSync(jsonPath)) return readJsonConfig(jsonPath);
1418
+ return {};
1419
+ }
1420
+ function readJsonConfig(path) {
1421
+ const content = readFileSync(path, "utf8");
1422
+ const body = content.charCodeAt(0) === 65279 ? content.slice(1) : content;
1423
+ try {
1424
+ return JSON.parse(body);
1425
+ } catch (error) {
1426
+ throw new Error(`[verbaly] ${path} is not valid JSON: ${error.message}`, { cause: error });
1007
1427
  }
1008
- return lines.join("\n");
1009
1428
  }
1010
- function checkNextSteps(result, cliReachable = true) {
1011
- const steps = [];
1012
- if (result.missing.length > 0) steps.push("missing: run `npx verbaly extract` to scaffold the keys, then fill them (or run `npx verbaly translate`)");
1013
- if (result.unknown.length > 0) steps.push("unknown keys: the key used in the code is in no catalog, fix the key or run `npx verbaly extract`");
1014
- if (result.broken.some((entry) => entry.severity === "error")) steps.push("broken: a translation has to keep the params, tags and plural cases of its source message");
1015
- if (steps.length > 0 && !cliReachable) steps.push(`the verbaly command is not linked in this project: ${CLI_INSTALL_FIX}`);
1016
- return steps.join("\n");
1429
+ async function loadTsConfig(path) {
1430
+ try {
1431
+ const { bundleRequire } = await import("bundle-require");
1432
+ const { mod } = await bundleRequire({ filepath: path });
1433
+ return mod.default ?? {};
1434
+ } catch (error) {
1435
+ if (isModuleNotFound(error, "esbuild")) throw new Error(`[verbaly] ${path} needs esbuild: install it with pnpm add -D esbuild`, { cause: error });
1436
+ throw error;
1437
+ }
1017
1438
  }
1018
- function collisionEntries(registry, locate = createLocator()) {
1019
- return registry.collisions().map(({ key, kept, dropped }) => ({
1020
- key,
1021
- sites: [kept, ...dropped].map((msg) => ({
1022
- file: msg.file,
1023
- line: locate(msg.file, msg.start),
1024
- message: msg.message
1025
- }))
1026
- }));
1439
+ function isModuleNotFound(error, name) {
1440
+ return error instanceof Error && error.code === "ERR_MODULE_NOT_FOUND" && error.message.includes(name);
1027
1441
  }
1028
- function sourcePlace(at, root) {
1029
- const file = root ? relative(root, at.file).replaceAll("\\", "/") : at.file;
1030
- return at.line ? `${file}:${at.line}` : file;
1442
+ function targetLocales(cfg, override) {
1443
+ return (override ?? cfg.locales).filter((locale) => locale !== cfg.sourceLocale && cfg.locales.includes(locale));
1031
1444
  }
1032
- function quoted(at, root) {
1033
- return `"${truncate(at.message, 40)}" (${sourcePlace(at, root)})`;
1445
+ async function loadConfig(root, overrides = {}) {
1446
+ return resolveConfig({
1447
+ ...await loadConfigFile(root),
1448
+ ...definedOnly(overrides),
1449
+ root
1450
+ });
1034
1451
  }
1035
- function formatCollision({ key, sites }, root) {
1036
- const [kept, ...others] = sites;
1037
- return ` ${key}: one key with ${counted(sites.length, "text")}, and every place shows ${quoted(kept, root)}, never ${others.map((at) => quoted(at, root)).join(" or ")}: give each text its own key`;
1452
+ function definedOnly(config) {
1453
+ return Object.fromEntries(Object.entries(config).filter(([, value]) => value !== void 0));
1038
1454
  }
1039
- function formatCheckWarnings(result, root) {
1040
- const lines = result.broken.filter((entry) => entry.severity === "warning").map((entry) => ` [${entry.locale}] ${entry.key}: ${entry.issue}`);
1041
- for (const entry of result.extra) lines.push(entry.files.length > 0 ? ` [${entry.locale}] ${entry.key}: only this translation has it, so the source language shows the key itself` : ` [${entry.locale}] ${entry.key}: only this translation has it, and no code reads it`);
1042
- for (const entry of result.collisions) lines.push(formatCollision(entry, root));
1043
- for (const { key, catalog, code } of result.divergent) lines.push(` ${key}: the source catalog says "${truncate(catalog, 40)}" and the code says ${quoted(code, root)}: the code wins, so edit the text there (extract writes it into the catalog)`);
1044
- for (const { locale, key } of result.outdated) lines.push(` [${locale}] ${key}: translated from an older source text, update it or keep it with \`npx verbaly review --approve\``);
1045
- return lines.join("\n");
1455
+ //#endregion
1456
+ //#region src/tag.ts
1457
+ function isLocaleTag(tag) {
1458
+ try {
1459
+ Intl.getCanonicalLocales(tag);
1460
+ return true;
1461
+ } catch {
1462
+ return false;
1463
+ }
1046
1464
  }
1047
- function truncate(text, max) {
1048
- return text.length > max ? text.slice(0, max - 1) + "…" : text;
1465
+ function suggestTag(tag) {
1466
+ const near = tag.replace(/_/g, "-");
1467
+ return near !== tag && isLocaleTag(near) ? near : void 0;
1049
1468
  }
1050
- function githubCheckAnnotations(result, registry, root) {
1051
- const messages = registry.messages();
1052
- const locate = createLocator();
1053
- const rel = (file) => escapeProperty(relative(root, file).replaceAll("\\", "/"));
1054
- const at = (file, line) => `file=${rel(file)}${line ? `,line=${line}` : ""}`;
1055
- const lines = [];
1056
- const byKey = /* @__PURE__ */ new Map();
1057
- for (const entry of result.missing) {
1058
- const grouped = byKey.get(entry.key);
1059
- if (grouped) grouped.locales.push(entry.locale);
1060
- else byKey.set(entry.key, {
1061
- ...entry,
1062
- locales: [entry.locale]
1063
- });
1064
- }
1065
- for (const entry of byKey.values()) {
1066
- const origin = messages.get(entry.key);
1067
- const hint = entry.source ? `: "${truncate(entry.source, 60)}"` : "";
1068
- const text = escapeData(`missing [${entry.locales.join(", ")}] ${entry.key}${hint}`);
1069
- if (origin) lines.push(`::error ${at(origin.file, locate(origin.file, origin.start))}::${text}`);
1070
- else lines.push(`::error::${text}`);
1071
- }
1072
- for (const entry of result.unknown) {
1073
- const text = escapeData(`unknown key "${entry.key}" (not in any catalog)`);
1074
- const file = entry.files[0];
1075
- lines.push(file ? `::error file=${rel(file)}::${text}` : `::error::${text}`);
1076
- }
1077
- for (const entry of result.broken) {
1078
- const origin = messages.get(entry.key);
1079
- const text = escapeData(`[${entry.locale}] ${entry.key}: ${entry.issue}`);
1080
- const command = entry.severity === "error" ? "error" : "warning";
1081
- if (!origin) {
1082
- lines.push(`::${command}::${text}`);
1083
- continue;
1084
- }
1085
- lines.push(`::${command} ${at(origin.file, locate(origin.file, origin.start))}::${text}`);
1086
- }
1087
- for (const entry of result.extra) {
1088
- const text = escapeData(`[${entry.locale}] ${entry.key}: only this translation has it`);
1089
- const file = entry.files[0];
1090
- lines.push(file ? `::warning file=${rel(file)}::${text}` : `::warning::${text}`);
1091
- }
1092
- for (const { key, sites } of result.collisions) {
1093
- const text = escapeData(`"${key}" has ${counted(sites.length, "text")}, and every place shows the first one`);
1094
- for (const place of sites) lines.push(`::warning ${at(place.file, place.line)}::${text}`);
1095
- }
1096
- for (const { key, code } of result.divergent) {
1097
- const text = escapeData(`"${key}": the source catalog has another text, the code's one ships`);
1098
- lines.push(`::warning ${at(code.file, code.line)}::${text}`);
1469
+ function projectLocale(tag, locales) {
1470
+ if (locales.includes(tag)) return tag;
1471
+ const plain = (value) => value.replace(/_/g, "-").toLowerCase();
1472
+ return locales.find((locale) => plain(locale) === plain(tag));
1473
+ }
1474
+ //#endregion
1475
+ //#region src/init.ts
1476
+ const HOSTS = [
1477
+ {
1478
+ name: "nuxt",
1479
+ dep: "nuxt",
1480
+ pkg: "@verbaly/nuxt",
1481
+ wire: "add '@verbaly/nuxt' to the modules in nuxt.config"
1482
+ },
1483
+ {
1484
+ name: "next",
1485
+ dep: "next",
1486
+ pkg: "@verbaly/next",
1487
+ wire: "wrap the export of next.config with withVerbaly"
1488
+ },
1489
+ {
1490
+ name: "sveltekit",
1491
+ dep: "@sveltejs/kit",
1492
+ pkg: "@verbaly/vite",
1493
+ wire: "add verbaly() to the plugins in vite.config (per-request locale: @verbaly/sveltekit)"
1494
+ },
1495
+ {
1496
+ name: "astro",
1497
+ dep: "astro",
1498
+ pkg: "@verbaly/astro",
1499
+ wire: "add verbaly() to the integrations in astro.config"
1500
+ },
1501
+ {
1502
+ name: "vite",
1503
+ dep: "vite",
1504
+ pkg: "@verbaly/vite",
1505
+ wire: "add verbaly() to the plugins in vite.config"
1506
+ },
1507
+ {
1508
+ name: "webpack",
1509
+ dep: "webpack",
1510
+ pkg: "@verbaly/unplugin",
1511
+ wire: "add the verbaly webpack plugin to your build config"
1512
+ },
1513
+ {
1514
+ name: "rspack",
1515
+ dep: "@rspack/core",
1516
+ pkg: "@verbaly/unplugin",
1517
+ wire: "add the verbaly rspack plugin to your build config"
1518
+ },
1519
+ {
1520
+ name: "rollup",
1521
+ dep: "rollup",
1522
+ pkg: "@verbaly/unplugin",
1523
+ wire: "add the verbaly rollup plugin to your build config"
1524
+ },
1525
+ {
1526
+ name: "esbuild",
1527
+ dep: "esbuild",
1528
+ pkg: "@verbaly/unplugin",
1529
+ wire: "add the verbaly esbuild plugin to your build config"
1099
1530
  }
1100
- for (const { locale, key } of result.outdated) {
1101
- const text = escapeData(`[${locale}] ${key}: translated from an older source text`);
1102
- lines.push(`::warning::${text}`);
1531
+ ];
1532
+ const WIRING_PACKAGES = [...new Set(HOSTS.map((host) => host.pkg))];
1533
+ function readDependencies(root) {
1534
+ const path = join(root, "package.json");
1535
+ if (!existsSync(path)) return {};
1536
+ try {
1537
+ const pkg = JSON.parse(readFileSync(path, "utf8"));
1538
+ return {
1539
+ ...pkg.dependencies,
1540
+ ...pkg.devDependencies
1541
+ };
1542
+ } catch {
1543
+ return {};
1103
1544
  }
1104
- return lines;
1105
1545
  }
1106
- function escapeData(text) {
1107
- return text.replaceAll("%", "%25").replaceAll("\r", "%0D").replaceAll("\n", "%0A");
1546
+ function cliReachable(root) {
1547
+ const bin = join(root, "node_modules", ".bin");
1548
+ return existsSync(join(bin, "verbaly")) || existsSync(join(bin, "verbaly.CMD"));
1108
1549
  }
1109
- function escapeProperty(text) {
1110
- return escapeData(text).replaceAll(":", "%3A").replaceAll(",", "%2C");
1550
+ const CLI_INSTALL_FIX = "add `@verbaly/compiler` to your dev dependencies, then `npx verbaly` resolves";
1551
+ function detectHost(root) {
1552
+ const deps = readDependencies(root);
1553
+ return HOSTS.find((host) => deps[host.dep]);
1111
1554
  }
1112
- //#endregion
1113
- //#region src/params.ts
1114
- const NUMBER_FORMATS = /* @__PURE__ */ new Set([
1115
- "number",
1116
- "integer",
1117
- "percent",
1118
- "currency"
1119
- ]);
1120
- const DATE_FORMATS = /* @__PURE__ */ new Set(["date", "time"]);
1121
- function collectParams(message) {
1122
- const out = /* @__PURE__ */ new Map();
1123
- visit(parse(message, parseIcu), out);
1124
- return out;
1555
+ function configSource(options, typescript) {
1556
+ const fields = [` sourceLocale: '${options.sourceLocale ?? "en"}',`];
1557
+ if (options.locales?.length) fields.push(` locales: [${options.locales.map((l) => `'${l}'`).join(", ")}],`);
1558
+ if (options.dir) fields.push(` dir: '${options.dir}',`);
1559
+ const body = `export default {\n${fields.join("\n")}\n}`;
1560
+ if (typescript) return `import type { VerbalyConfig } from '@verbaly/compiler';\n\n${body} satisfies VerbalyConfig;\n`;
1561
+ return `/** @type {import('@verbaly/compiler').VerbalyConfig} */\n${body};\n`;
1125
1562
  }
1126
- function visit(nodes, out) {
1127
- for (const node of nodes) {
1128
- if (node.kind !== "param") continue;
1129
- const types = out.get(node.name) ?? /* @__PURE__ */ new Set();
1130
- out.set(node.name, types);
1131
- if (node.variants) {
1132
- for (const [key, body] of node.variants) {
1133
- if (PLURAL_CATEGORIES.has(key) || /^=\d+$/.test(key)) types.add("number");
1134
- else if (key !== "other") types.add("string");
1135
- visit(body, out);
1136
- }
1137
- if (types.size === 0) types.add("string");
1138
- } else if (node.format && NUMBER_FORMATS.has(node.format)) types.add("number");
1139
- else if (node.format && DATE_FORMATS.has(node.format)) types.add("date");
1140
- else types.add("unknown");
1563
+ async function init(input = {}) {
1564
+ const root = input.root ?? process.cwd();
1565
+ const created = [];
1566
+ const skipped = [];
1567
+ const renamed = [];
1568
+ const refused = [];
1569
+ const typed = input.locales?.flatMap((locale) => {
1570
+ if (isLocaleTag(locale)) return [locale];
1571
+ const near = suggestTag(locale);
1572
+ if (near) renamed.push({
1573
+ from: locale,
1574
+ to: near
1575
+ });
1576
+ else refused.push(locale);
1577
+ return near ? [near] : [];
1578
+ });
1579
+ const locales = typed && [...new Set(typed)];
1580
+ let sourceLocale = input.sourceLocale;
1581
+ if (sourceLocale !== void 0 && !isLocaleTag(sourceLocale)) {
1582
+ const near = suggestTag(sourceLocale);
1583
+ if (!near) throw new Error(`[verbaly] "${sourceLocale}" is not a locale tag: pass --source with one like en or pt-BR`);
1584
+ renamed.push({
1585
+ from: sourceLocale,
1586
+ to: near
1587
+ });
1588
+ sourceLocale = near;
1141
1589
  }
1142
- }
1143
- function renderParamType(types) {
1144
- if (types.has("unknown") || types.size === 0) return "unknown";
1145
- const members = /* @__PURE__ */ new Set();
1146
- if (types.has("number")) members.add("number");
1147
- if (types.has("string")) members.add("string");
1148
- if (types.has("date")) for (const m of [
1149
- "Date",
1150
- "number",
1151
- "string"
1152
- ]) members.add(m);
1153
- return [...members].join(" | ");
1154
- }
1155
- function generateDts(catalog, options = {}) {
1156
- const lines = [];
1157
- for (const [key, message] of Object.entries(catalog).sort(([a], [b]) => a.localeCompare(b))) {
1158
- const params = collectParams(message);
1159
- if (params.size === 0) lines.push(` ${JSON.stringify(key)}: never;`);
1590
+ const options = {
1591
+ ...input,
1592
+ locales,
1593
+ sourceLocale
1594
+ };
1595
+ const existing = findConfigFile(root);
1596
+ const typescript = existsSync(join(root, "tsconfig.json"));
1597
+ const configFile = existing ?? (typescript ? "verbaly.config.ts" : "verbaly.config.mjs");
1598
+ if (existing) skipped.push(existing);
1599
+ else {
1600
+ writeFileSync(join(root, configFile), configSource(options, typescript));
1601
+ created.push(configFile);
1602
+ }
1603
+ const fromFile = existing ? await loadConfigFile(root) : {};
1604
+ const scaffold = {
1605
+ dir: options.dir ?? fromFile.dir,
1606
+ sourceLocale: options.sourceLocale ?? fromFile.sourceLocale,
1607
+ locales: options.locales ?? fromFile.locales
1608
+ };
1609
+ const dir = join(root, scaffold.dir ?? "locales");
1610
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
1611
+ for (const locale of /* @__PURE__ */ new Set([scaffold.sourceLocale ?? "en", ...scaffold.locales ?? []])) {
1612
+ const file = join(dir, `${locale}.json`);
1613
+ const label = relative(root, file).replaceAll("\\", "/");
1614
+ if (existsSync(file)) skipped.push(label);
1160
1615
  else {
1161
- const fields = [...params.entries()].map(([name, types]) => `${JSON.stringify(name)}: ${renderParamType(types)}`).join("; ");
1162
- lines.push(` ${JSON.stringify(key)}: { ${fields} };`);
1616
+ writeFileSync(file, "{}\n");
1617
+ created.push(label);
1163
1618
  }
1164
1619
  }
1165
- return `// generated by verbaly: do not edit
1166
- declare module 'virtual:verbaly' {
1167
- export interface VerbalyMessages {
1168
- ${lines.join("\n")}
1169
- }
1170
- export type VerbalyKey = keyof VerbalyMessages & string;
1171
-
1172
- export type VerbalyKeyTree = VerbalyKey | { readonly [name: string]: VerbalyKeyTree };
1173
- export function defineKeys<const T extends VerbalyKeyTree>(keys: T): T;
1174
-
1175
- export const verbaly: import('verbaly').Verbaly<VerbalyKey>;
1176
-
1177
- export const sourceLocale: string;
1178
- export const locales: string[];
1179
- export const routing: import('verbaly').Routing;
1180
- export function localePath(
1181
- locale: string,
1182
- options?: { path?: string; base?: string },
1183
- ): string;
1184
- export function localeFromPath(options?: {
1185
- path?: string;
1186
- base?: string;
1187
- }): string | undefined;
1188
- export function loadMessages(locale: string): Promise<Record<string, string>>;${options.inlineCatalog ? "\n export function adoptPage(options?: {\n root?: ParentNode;\n path?: string;\n }): string | undefined;" : ""}
1189
- export function createInstance(
1190
- options?: import('verbaly').VerbalyOptions<VerbalyKey>,
1191
- ): import('verbaly').Verbaly<VerbalyKey>;
1192
- export function createRequestInstance(
1193
- locale: string,
1194
- ): Promise<import('verbaly').Verbaly<VerbalyKey>>;
1195
-
1196
- export function t<K extends VerbalyKey>(
1197
- key: K,
1198
- ...args: [VerbalyMessages[K]] extends [never] ? [] : [VerbalyMessages[K]]
1199
- ): string;
1200
- export function t(strings: TemplateStringsArray, ...values: unknown[]): string;
1201
- export namespace t {
1202
- export function id(
1203
- key: string,
1204
- ): (strings: TemplateStringsArray, ...values: unknown[]) => string;
1205
- }
1206
-
1207
- export function setLocale(locale: string): Promise<void>;
1208
- export function switchLocale(
1209
- locale: string,
1210
- options?: Omit<
1211
- import('verbaly').SwitchLocaleOptions,
1212
- 'routing' | 'supported' | 'sourceLocale'
1213
- >,
1214
- ): Promise<void>;
1215
- export function getLocale(): string;
1216
- export function subscribe(listener: () => void): () => void;
1620
+ const host = detectHost(root);
1621
+ const next = host ? [`pnpm add -D ${host.pkg}`, host.wire] : ["run \"verbaly extract\" after writing your first t`…` message"];
1622
+ return {
1623
+ created,
1624
+ skipped,
1625
+ host: host?.name,
1626
+ configFile,
1627
+ next,
1628
+ renamed,
1629
+ refused
1630
+ };
1217
1631
  }
1218
-
1219
- declare module 'virtual:verbaly/locale/*' {
1220
- const messages: Record<string, string>;
1221
- export default messages;
1632
+ //#endregion
1633
+ //#region src/state.ts
1634
+ const STATE_FILE = ".verbaly-state.json";
1635
+ const LEGACY_DRAFTS_FILE = ".verbaly-drafts.json";
1636
+ function statePath(cfg, file = STATE_FILE) {
1637
+ return join(cfg.dir, file);
1222
1638
  }
1223
- `;
1639
+ function loadState(cfg) {
1640
+ const current = readJson(statePath(cfg));
1641
+ if (current !== void 0 && !isObject(current)) throw corrupt(statePath(cfg));
1642
+ const legacy = readJson(statePath(cfg, LEGACY_DRAFTS_FILE));
1643
+ if (legacy !== void 0 && !isObject(legacy)) throw corrupt(statePath(cfg, LEGACY_DRAFTS_FILE));
1644
+ const state = isObject(current) ? {
1645
+ drafts: readDrafts(current.drafts),
1646
+ fingerprints: readFingerprints(current.fingerprints)
1647
+ } : {
1648
+ drafts: {},
1649
+ fingerprints: {}
1650
+ };
1651
+ if (legacy !== void 0) for (const [locale, keys] of Object.entries(readDrafts(legacy))) markDrafts(state.drafts, locale, keys);
1652
+ return state;
1224
1653
  }
1225
- function writeDts(cfg, catalog, file) {
1226
- const target = file === void 0 ? cfg.dts : file;
1227
- if (target === false) return;
1228
- file = target ?? join(cfg.root, "verbaly.d.ts");
1229
- const content = generateDts(catalog, { inlineCatalog: cfg.render.inlineCatalog === true });
1654
+ function readState(cfg) {
1230
1655
  try {
1231
- if (readFileSync(file, "utf8") === content) return;
1232
- } catch {}
1233
- mkdirSync(dirname(file), { recursive: true });
1234
- writeFileSync(file, content);
1235
- }
1236
- //#endregion
1237
- //#region src/bundle.ts
1238
- function isExcluded(key, prefixes) {
1239
- return prefixes.some((prefix) => key === prefix || key.startsWith(`${prefix}.`));
1656
+ return { state: loadState(cfg) };
1657
+ } catch (error) {
1658
+ return {
1659
+ state: {
1660
+ drafts: {},
1661
+ fingerprints: {}
1662
+ },
1663
+ problem: error.message.replace(/^\[verbaly\] /, "")
1664
+ };
1665
+ }
1240
1666
  }
1241
- function auditBundle(cfg, catalogs, registry) {
1242
- const prefixes = cfg.bundle.exclude ?? [];
1243
- if (prefixes.length === 0) return [];
1244
- const source = Object.keys(catalogs[cfg.sourceLocale] ?? {});
1245
- const used = registry.usedKeys();
1246
- const issues = [];
1247
- for (const prefix of prefixes) {
1248
- if (!source.some((key) => isExcluded(key, [prefix]))) {
1249
- issues.push({
1250
- prefix,
1251
- problem: `matches no key in ${cfg.sourceLocale}.json, so it excludes nothing`,
1252
- fix: "check the spelling against your catalog, or drop it from bundle.exclude"
1253
- });
1254
- continue;
1255
- }
1256
- const files = /* @__PURE__ */ new Set();
1257
- for (const [key, where] of used) if (isExcluded(key, [prefix])) for (const file of where) files.add(file);
1258
- if (files.size > 0) issues.push({
1259
- prefix,
1260
- problem: `is read by t() in ${counted(files.size, "file")}, where it resolves to the key itself`,
1261
- fix: "pre-render those pages with render, load the group with addMessages, or stop excluding it"
1262
- });
1667
+ function saveState(cfg, state) {
1668
+ const serialized = serializeState(state);
1669
+ const path = statePath(cfg);
1670
+ const legacy = statePath(cfg, LEGACY_DRAFTS_FILE);
1671
+ if (serialized === void 0) {
1672
+ rmSync(path, { force: true });
1673
+ rmSync(legacy, { force: true });
1674
+ return;
1263
1675
  }
1264
- return issues;
1676
+ let existing;
1677
+ try {
1678
+ existing = readFileSync(path, "utf8");
1679
+ } catch {
1680
+ mkdirSync(cfg.dir, { recursive: true });
1681
+ }
1682
+ if (existing !== serialized) writeFileSync(path, serialized);
1683
+ if (existsSync(legacy)) rmSync(legacy);
1265
1684
  }
1266
- function formatBundleIssue(issue) {
1267
- return `bundle.exclude "${issue.prefix}" ${issue.problem}`;
1685
+ function updateState(cfg, catalogs) {
1686
+ const next = refreshState(cfg, catalogs, loadState(cfg));
1687
+ saveState(cfg, next);
1688
+ return next;
1268
1689
  }
1269
- //#endregion
1270
- //#region src/registry.ts
1271
- var MessageRegistry = class {
1272
- files = /* @__PURE__ */ new Map();
1273
- update(file, analysis) {
1274
- this.files.set(file, analysis);
1275
- }
1276
- remove(file) {
1277
- this.files.delete(file);
1690
+ function refreshState(cfg, catalogs, previous) {
1691
+ const flat = flatCatalogs(catalogs);
1692
+ const source = flat[cfg.sourceLocale] ?? {};
1693
+ const shown = new Set(targetLocales(cfg).filter((locale) => Object.hasOwn(flat, locale) && existsSync(catalogPath(cfg, locale))));
1694
+ const drafts = {};
1695
+ for (const [locale, keys] of Object.entries(previous.drafts)) {
1696
+ if (!shown.has(locale)) {
1697
+ drafts[locale] = keys;
1698
+ continue;
1699
+ }
1700
+ const live = keys.filter((key) => own(flat[locale], key));
1701
+ if (live.length) drafts[locale] = live;
1278
1702
  }
1279
- messages() {
1280
- const out = /* @__PURE__ */ new Map();
1281
- for (const analysis of this.files.values()) for (const msg of analysis.tagged) if (!out.has(msg.key)) out.set(msg.key, msg);
1282
- return out;
1703
+ const fingerprints = {};
1704
+ for (const [locale, stamps] of Object.entries(previous.fingerprints)) if (!shown.has(locale)) fingerprints[locale] = stamps;
1705
+ for (const locale of shown) {
1706
+ const stamps = refreshStamps(source, flat[locale], previous.fingerprints[locale] ?? {});
1707
+ if (Object.keys(stamps).length) fingerprints[locale] = stamps;
1283
1708
  }
1284
- collisions() {
1285
- const seen = /* @__PURE__ */ new Map();
1286
- for (const analysis of this.files.values()) for (const msg of analysis.tagged) {
1287
- const found = seen.get(msg.key);
1288
- if (!found) seen.set(msg.key, {
1289
- key: msg.key,
1290
- kept: msg,
1291
- dropped: []
1292
- });
1293
- else if (msg.message !== found.kept.message && !found.dropped.some((other) => other.message === msg.message)) found.dropped.push(msg);
1709
+ return {
1710
+ drafts,
1711
+ fingerprints
1712
+ };
1713
+ }
1714
+ function refreshStamps(source, catalog, before) {
1715
+ const after = emptyCatalog();
1716
+ for (const key of /* @__PURE__ */ new Set([...Object.keys(before), ...Object.keys(source)])) {
1717
+ const translated = own(catalog, key);
1718
+ if (!translated) continue;
1719
+ const was = own(before, key);
1720
+ if (was !== void 0 && translationOf(was) === fingerprint(translated)) {
1721
+ after[key] = was;
1722
+ continue;
1294
1723
  }
1295
- return [...seen.values()].filter((entry) => entry.dropped.length > 0);
1724
+ const text = own(source, key);
1725
+ if (text && tracked(key, text)) after[key] = stamp(text, translated);
1726
+ else if (was !== void 0) after[key] = was;
1296
1727
  }
1297
- usedKeys(strict = false) {
1298
- const out = /* @__PURE__ */ new Map();
1299
- for (const analysis of this.files.values()) for (const used of analysis.usedKeys) {
1300
- if (strict && used.loose) continue;
1301
- const files = out.get(used.key) ?? [];
1302
- if (!files.includes(used.file)) files.push(used.file);
1303
- out.set(used.key, files);
1728
+ return after;
1729
+ }
1730
+ function recordTranslations(cfg, source, writes) {
1731
+ const state = loadState(cfg);
1732
+ for (const { locale, entries, draft } of writes) {
1733
+ if (entries.length === 0) continue;
1734
+ const stamps = state.fingerprints[locale] ??= emptyCatalog();
1735
+ for (const entry of entries) {
1736
+ const from = entry.source || own(source, entry.key);
1737
+ if (from && entry.text && tracked(entry.key, from)) stamps[entry.key] = stamp(from, entry.text);
1304
1738
  }
1305
- return out;
1306
- }
1307
- strayImports() {
1308
- return [...this.files.values()].flatMap((analysis) => analysis.strayImports);
1309
- }
1310
- missed() {
1311
- return [...this.files.values()].flatMap((analysis) => analysis.missed ?? []);
1312
- }
1313
- parseErrors() {
1314
- const out = [];
1315
- for (const [file, analysis] of this.files) if (analysis.parseError) out.push({
1316
- file,
1317
- message: analysis.parseError
1318
- });
1319
- return out;
1739
+ const keys = entries.map((entry) => entry.key);
1740
+ if (draft === true) markDrafts(state.drafts, locale, keys);
1741
+ else if (draft === false) clearDrafts(state.drafts, locale, keys);
1320
1742
  }
1321
- origins() {
1322
- const out = this.usedKeys();
1323
- for (const analysis of this.files.values()) for (const msg of analysis.tagged) {
1324
- const files = out.get(msg.key) ?? [];
1325
- if (!files.includes(msg.file)) files.push(msg.file);
1326
- out.set(msg.key, files);
1327
- }
1328
- return out;
1743
+ saveState(cfg, state);
1744
+ return state;
1745
+ }
1746
+ function effectiveDrafts(drafts, catalogs) {
1747
+ const out = {};
1748
+ for (const [locale, keys] of Object.entries(drafts)) {
1749
+ const catalog = catalogs[locale] ?? {};
1750
+ const live = keys.filter((key) => own(catalog, key));
1751
+ if (live.length) out[locale] = live;
1329
1752
  }
1330
- };
1331
- //#endregion
1332
- //#region src/analyze.ts
1333
- function parseErrorMessage(error) {
1334
- return error instanceof Error ? error.message : String(error);
1753
+ return out;
1335
1754
  }
1336
- const SKIP_KEYS = /* @__PURE__ */ new Set([
1337
- "loc",
1338
- "leadingComments",
1339
- "trailingComments",
1340
- "innerComments",
1341
- "extra"
1342
- ]);
1343
- const DEFAULT_T_NAMES = ["t"];
1344
- const JSX_FILE_RE = /\.(?:[cm]?jsx?|tsx)$/;
1345
- const DEFINE_KEYS = "defineKeys";
1346
- function analyze(code, file, options = {}) {
1347
- const names = new Set(options.tNames ?? DEFAULT_T_NAMES);
1348
- const ast = parse$1(code, {
1349
- sourceType: "module",
1350
- errorRecovery: true,
1351
- plugins: JSX_FILE_RE.test(file) ? ["typescript", "jsx"] : ["typescript"]
1352
- });
1353
- const tagged = [];
1354
- const usedKeys = [];
1355
- const strayImports = [];
1356
- const missed = [];
1357
- const renamed = renamedBindings(ast.program, names);
1358
- walk(ast.program, (node) => {
1359
- if (node.type === "ImportDeclaration") collectStrayImports(node, file, strayImports);
1360
- else if (node.type === "TaggedTemplateExpression") {
1361
- const tag = node.tag;
1362
- const explicit = explicitId(tag, names);
1363
- if (!explicit && !isTReference(tag, names)) {
1364
- const name = renamedTag(tag, renamed);
1365
- if (name) missed.push({
1366
- name,
1367
- file,
1368
- start: node.start
1369
- });
1370
- return;
1371
- }
1372
- const quasi = node.quasi;
1373
- const message = buildMessage(code, quasi, names);
1374
- if (!message) return;
1375
- tagged.push({
1376
- key: explicit ? explicit.key : stableKey(message.text),
1377
- message: message.text,
1378
- params: message.params,
1379
- start: node.start,
1380
- end: node.end,
1381
- tagStart: explicit ? explicit.refStart : tag.start,
1382
- tagEnd: explicit ? explicit.refEnd : tag.end,
1383
- file
1384
- });
1385
- } else if (node.type === "CallExpression") {
1386
- const callee = node.callee;
1387
- const args = node.arguments;
1388
- if (callee.type === "Identifier" && callee.name === DEFINE_KEYS) {
1389
- collectDeclaredKeys(args[0], file, usedKeys);
1390
- return;
1391
- }
1392
- if (!isTReference(callee, names)) {
1393
- const key = renamed.has(identifierName(callee)) ? staticString(args[0]) : void 0;
1394
- if (key !== void 0) usedKeys.push({
1395
- key,
1396
- file,
1397
- loose: true
1398
- });
1399
- return;
1400
- }
1401
- const key = staticString(args[0]);
1402
- if (key !== void 0) usedKeys.push(usedKey(key, file, args[0]));
1403
- } else if (node.type === "JSXElement") handleTrans(code, node, file, tagged, usedKeys, names);
1404
- });
1405
- return {
1406
- tagged,
1407
- usedKeys,
1408
- strayImports,
1409
- ...missed.length > 0 && { missed }
1410
- };
1755
+ function markDrafts(drafts, locale, keys) {
1756
+ if (!keys.length) return;
1757
+ drafts[locale] = [.../* @__PURE__ */ new Set([...drafts[locale] ?? [], ...keys])];
1411
1758
  }
1412
- function renamedBindings(program, names) {
1413
- const out = /* @__PURE__ */ new Set();
1414
- const add = (node) => {
1415
- const name = identifierName(node);
1416
- if (name && !names.has(name)) out.add(name);
1417
- };
1418
- walk(program, (node) => {
1419
- if (node.type === "ImportDeclaration") {
1420
- if (node.source.value !== "virtual:verbaly") return;
1421
- for (const spec of node.specifiers) if (spec.type === "ImportSpecifier" && identifierName(spec.imported) === "t") add(spec.local);
1422
- } else if (node.type === "VariableDeclarator") {
1423
- const id = node.id;
1424
- const init = node.init;
1425
- if (id.type === "Identifier" && init && handsOutT(init)) add(id);
1426
- if (id.type !== "ObjectPattern") return;
1427
- for (const property of id.properties) {
1428
- if (property.type !== "ObjectProperty" || property.computed) continue;
1429
- if (identifierName(property.key) === "t") add(property.value);
1430
- }
1431
- }
1432
- });
1433
- return out;
1759
+ function clearDrafts(drafts, locale, keys) {
1760
+ if (!drafts[locale]) return;
1761
+ if (!keys) {
1762
+ delete drafts[locale];
1763
+ return;
1764
+ }
1765
+ const drop = new Set(keys);
1766
+ drafts[locale] = drafts[locale].filter((key) => !drop.has(key));
1767
+ if (!drafts[locale].length) delete drafts[locale];
1434
1768
  }
1435
- function handsOutT(init) {
1436
- const call = init.type === "AwaitExpression" ? init.argument : init;
1437
- if (call.type !== "CallExpression") return false;
1438
- const callee = identifierName(call.callee);
1439
- return init.type === "AwaitExpression" ? callee === "getT" : callee === "useT";
1769
+ function fingerprint(text) {
1770
+ return stableKey(text);
1440
1771
  }
1441
- function identifierName(node) {
1442
- return node?.type === "Identifier" ? node.name : "";
1772
+ function tracked(key, text) {
1773
+ return stableKey(text) !== key;
1443
1774
  }
1444
- function renamedTag(tag, renamed) {
1445
- if (renamed.size === 0) return void 0;
1446
- const name = identifierName(tag);
1447
- if (renamed.has(name)) return name;
1448
- if (tag.type !== "CallExpression") return void 0;
1449
- const callee = tag.callee;
1450
- if (callee.type !== "MemberExpression" || callee.computed) return void 0;
1451
- if (identifierName(callee.property) !== "id") return void 0;
1452
- const object = identifierName(callee.object);
1453
- return renamed.has(object) ? object : void 0;
1775
+ function stamp(source, translated) {
1776
+ return `${fingerprint(source)}.${fingerprint(translated)}`;
1454
1777
  }
1455
- function collectDeclaredKeys(node, file, out) {
1456
- if (node?.type !== "ObjectExpression") return;
1457
- for (const property of node.properties) {
1458
- if (property.type !== "ObjectProperty") continue;
1459
- const value = property.value;
1460
- const key = staticString(value);
1461
- if (key !== void 0) {
1462
- if (key !== "") out.push(usedKey(key, file, value));
1463
- } else if (value.type === "ObjectExpression") collectDeclaredKeys(value, file, out);
1778
+ function outdatedTranslations(cfg, catalogs, fingerprints) {
1779
+ const source = catalogs[cfg.sourceLocale] ?? {};
1780
+ const out = [];
1781
+ for (const locale of targetLocales(cfg)) {
1782
+ const catalog = catalogs[locale] ?? {};
1783
+ for (const [key, was] of Object.entries(fingerprints[locale] ?? {})) {
1784
+ const text = own(source, key);
1785
+ const translated = own(catalog, key);
1786
+ if (!text || !translated) continue;
1787
+ if (translationOf(was) !== fingerprint(translated)) continue;
1788
+ if (sourceOf(was) !== fingerprint(text)) out.push({
1789
+ locale,
1790
+ key
1791
+ });
1792
+ }
1464
1793
  }
1794
+ return out.sort((a, b) => a.locale.localeCompare(b.locale) || a.key.localeCompare(b.key));
1465
1795
  }
1466
- function usedKey(key, file, node) {
1467
- return node?.type === "StringLiteral" ? {
1468
- key,
1469
- file
1470
- } : {
1471
- key,
1472
- file,
1473
- loose: true
1474
- };
1796
+ function acceptOutdated(cfg, catalogs, fingerprints, entries) {
1797
+ const source = catalogs[cfg.sourceLocale] ?? {};
1798
+ for (const { locale, key } of entries) {
1799
+ const text = own(source, key);
1800
+ const translated = own(catalogs[locale] ?? {}, key);
1801
+ if (!text || !translated) continue;
1802
+ (fingerprints[locale] ??= emptyCatalog())[key] = stamp(text, translated);
1803
+ }
1475
1804
  }
1476
- function staticString(node) {
1477
- if (!node) return void 0;
1478
- if (node.type === "StringLiteral") return node.value;
1479
- if (node.type === "TemplateLiteral" && node.expressions.length === 0) return cookedValue(node.quasis[0]);
1480
- if (node.type === "JSXExpressionContainer") return staticString(node.expression);
1805
+ function sourceOf(stamped) {
1806
+ return stamped.slice(0, stamped.indexOf("."));
1481
1807
  }
1482
- const VERBALY_PACKAGE = /^(?:verbaly|@verbaly\/[\w-]+)$/;
1483
- function collectStrayImports(node, file, out) {
1484
- const source = node.source;
1485
- if (typeof source.value !== "string" || !VERBALY_PACKAGE.test(source.value)) return;
1486
- for (const spec of node.specifiers) {
1487
- if (spec.type !== "ImportSpecifier") continue;
1488
- const imported = spec.imported;
1489
- if (imported.type !== "Identifier") continue;
1490
- const name = imported.name;
1491
- if (name === "t" || name === DEFINE_KEYS) out.push({
1492
- name,
1493
- source: source.value,
1494
- file
1495
- });
1808
+ function translationOf(stamped) {
1809
+ return stamped.slice(stamped.indexOf(".") + 1);
1810
+ }
1811
+ function flatCatalogs(catalogs) {
1812
+ const out = {};
1813
+ for (const [locale, catalog] of Object.entries(catalogs)) out[locale] = flatten(catalog);
1814
+ return out;
1815
+ }
1816
+ function serializeState(state) {
1817
+ const drafts = {};
1818
+ for (const locale of Object.keys(state.drafts).sort()) {
1819
+ const keys = [...new Set(state.drafts[locale])].sort();
1820
+ if (keys.length) drafts[locale] = keys;
1821
+ }
1822
+ const fingerprints = {};
1823
+ for (const locale of Object.keys(state.fingerprints).sort()) {
1824
+ const entries = state.fingerprints[locale] ?? {};
1825
+ const keys = Object.keys(entries).sort();
1826
+ if (!keys.length) continue;
1827
+ fingerprints[locale] = Object.fromEntries(keys.map((key) => [key, entries[key]]));
1496
1828
  }
1829
+ const out = {};
1830
+ if (Object.keys(drafts).length) out.drafts = drafts;
1831
+ if (Object.keys(fingerprints).length) out.fingerprints = fingerprints;
1832
+ if (!out.drafts && !out.fingerprints) return void 0;
1833
+ return JSON.stringify(out, null, 2) + "\n";
1497
1834
  }
1498
- function handleTrans(code, node, file, tagged, usedKeys, names) {
1499
- const opening = node.openingElement;
1500
- const nameNode = opening.name;
1501
- if (nameNode.type !== "JSXIdentifier" || nameNode.name !== "Trans") return;
1502
- const attrs = opening.attributes;
1503
- const idAttr = attrs.find((a) => a.type === "JSXAttribute" && a.name.name === "id");
1504
- const children = node.children;
1505
- const push = (key, built) => tagged.push({
1506
- key,
1507
- message: built.text,
1508
- params: built.params,
1509
- start: node.start,
1510
- end: node.end,
1511
- tagStart: nameNode.start,
1512
- tagEnd: nameNode.end,
1513
- file,
1514
- jsx: {
1515
- name: nameNode.name,
1516
- components: built.components
1517
- }
1518
- });
1519
- if (idAttr) {
1520
- const value = idAttr.value;
1521
- const id = staticString(value);
1522
- if (id === void 0) return;
1523
- if (value?.type === "StringLiteral" && attrs.length === 1 && children?.length) {
1524
- const built = buildTransMessage(code, children, names);
1525
- if (built?.text.trim()) {
1526
- push(id, built);
1527
- return;
1528
- }
1529
- }
1530
- usedKeys.push(usedKey(id, file, value));
1835
+ function readJson(path) {
1836
+ let content;
1837
+ try {
1838
+ content = readFileSync(path, "utf8");
1839
+ } catch {
1531
1840
  return;
1532
1841
  }
1533
- if (attrs.length > 0) return;
1534
- if (!children?.length) return;
1535
- const built = buildTransMessage(code, children, names);
1536
- if (!built || !built.text.trim()) return;
1537
- push(stableKey(built.text), built);
1842
+ try {
1843
+ return JSON.parse(content.charCodeAt(0) === 65279 ? content.slice(1) : content);
1844
+ } catch (error) {
1845
+ throw corrupt(path, error);
1846
+ }
1538
1847
  }
1539
- function explicitId(tag, names) {
1540
- if (tag.type !== "CallExpression") return void 0;
1541
- const callee = tag.callee;
1542
- if (callee.type !== "MemberExpression" || callee.computed) return void 0;
1543
- const prop = callee.property;
1544
- if (prop.type !== "Identifier" || prop.name !== "id") return void 0;
1545
- const obj = callee.object;
1546
- if (!isTReference(obj, names)) return void 0;
1547
- const args = tag.arguments;
1548
- const first = args[0];
1549
- if (args.length !== 1 || first?.type !== "StringLiteral") return void 0;
1550
- return {
1551
- key: first.value,
1552
- refStart: obj.start,
1553
- refEnd: obj.end
1554
- };
1848
+ function corrupt(path, cause) {
1849
+ return new Error(`[verbaly] ${path} is not valid JSON: restore it from git or fix it (deleting it approves every draft)`, { cause });
1555
1850
  }
1556
- function buildTransMessage(code, children, names) {
1557
- const params = [];
1558
- const components = [];
1559
- const takenParams = /* @__PURE__ */ new Map();
1560
- const takenTags = /* @__PURE__ */ new Map();
1561
- function walkChildren(nodes) {
1562
- let text = "";
1563
- for (const child of nodes) if (child.type === "JSXText") text += escapeText(cleanJsxText(child.value));
1564
- else if (child.type === "JSXExpressionContainer") {
1565
- const expr = child.expression;
1566
- if (expr.type === "JSXEmptyExpression") continue;
1567
- if (expr.type === "StringLiteral") {
1568
- text += escapeText(expr.value);
1569
- continue;
1570
- }
1571
- if (containsTaggedT(expr, names)) return void 0;
1572
- const source = code.slice(expr.start, expr.end);
1573
- const name = uniqueName(deriveName(expr, params.length), source, takenParams);
1574
- params.push({
1575
- name,
1576
- start: expr.start,
1577
- end: expr.end
1578
- });
1579
- text += `{${name}}`;
1580
- } else if (child.type === "JSXElement") {
1581
- const opening = child.openingElement;
1582
- const nameNode = opening.name;
1583
- if (nameNode.type !== "JSXIdentifier" || nameNode.name === "Trans") return void 0;
1584
- const source = selfClosedSource(code, opening);
1585
- const tag = uniqueName(nameNode.name.toLowerCase(), source, takenTags);
1586
- if (!components.some((c) => c.name === tag)) components.push({
1587
- name: tag,
1588
- source
1589
- });
1590
- if (!child.closingElement) text += `<${tag}/>`;
1591
- else {
1592
- const inner = walkChildren(child.children);
1593
- if (inner === void 0) return void 0;
1594
- text += `<${tag}>${inner}</${tag}>`;
1595
- }
1596
- } else return;
1597
- return text;
1598
- }
1599
- const text = walkChildren(children);
1600
- if (text === void 0) return void 0;
1601
- return {
1602
- text,
1603
- params,
1604
- components
1605
- };
1851
+ function isObject(value) {
1852
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1606
1853
  }
1607
- function cleanJsxText(raw) {
1608
- const lines = raw.split(/\r\n|[\r\n]/);
1609
- let out = "";
1610
- for (let i = 0; i < lines.length; i++) {
1611
- let line = lines[i].replace(/\t/g, " ");
1612
- if (i !== 0) line = line.replace(/^ +/, "");
1613
- if (i !== lines.length - 1) line = line.replace(/ +$/, "");
1614
- if (!line) continue;
1615
- if (out && i !== 0) out += " ";
1616
- out += line;
1854
+ function readDrafts(value) {
1855
+ const out = {};
1856
+ if (!isObject(value)) return out;
1857
+ for (const [locale, keys] of Object.entries(value)) if (Array.isArray(keys)) out[locale] = keys.filter((key) => typeof key === "string");
1858
+ return out;
1859
+ }
1860
+ function readFingerprints(value) {
1861
+ const out = {};
1862
+ if (!isObject(value)) return out;
1863
+ for (const [locale, entries] of Object.entries(value)) {
1864
+ if (!isObject(entries)) continue;
1865
+ const kept = emptyCatalog();
1866
+ for (const [key, stamped] of Object.entries(entries)) if (typeof stamped === "string" && stamped.includes(".")) kept[key] = stamped;
1867
+ out[locale] = kept;
1617
1868
  }
1618
1869
  return out;
1619
1870
  }
1620
- function selfClosedSource(code, opening) {
1621
- const src = code.slice(opening.start, opening.end);
1622
- return src.endsWith("/>") ? src : `${src.slice(0, -1).trimEnd()} />`;
1871
+ //#endregion
1872
+ //#region src/check.ts
1873
+ function gatePasses(result) {
1874
+ return result.missing.length === 0 && result.unknown.length === 0 && !result.broken.some((entry) => entry.severity === "error");
1623
1875
  }
1624
- function containsTaggedT(node, names) {
1625
- let found = false;
1626
- walk(node, (n) => {
1627
- if (n.type !== "TaggedTemplateExpression") return;
1628
- const tag = n.tag;
1629
- if (isTReference(tag, names) || explicitId(tag, names)) found = true;
1876
+ function check(cfg, catalogs, registry, fingerprints = {}) {
1877
+ const extracted = registry.messages();
1878
+ const flat = {};
1879
+ for (const locale of cfg.locales) flat[locale] = flatten(catalogs[locale] ?? {});
1880
+ const source = flat[cfg.sourceLocale] ?? {};
1881
+ const shipped = shippedCatalogs(cfg, flat, registry);
1882
+ const sourceText = shipped[cfg.sourceLocale];
1883
+ const used = registry.usedKeys();
1884
+ const unknown = [];
1885
+ for (const [key, files] of registry.usedKeys(true)) if (!(extracted.has(key) || cfg.locales.some((locale) => flat[locale]?.[key] !== void 0))) unknown.push({
1886
+ key,
1887
+ files
1630
1888
  });
1631
- return found;
1632
- }
1633
- function isTReference(node, names) {
1634
- if (node.type === "Identifier") return names.has(node.name);
1635
- if (node.type === "MemberExpression" && !node.computed) {
1636
- const prop = node.property;
1637
- return prop.type === "Identifier" && names.has(prop.name);
1889
+ const needed = /* @__PURE__ */ new Set([...extracted.keys(), ...Object.keys(source)]);
1890
+ const missing = [];
1891
+ for (const key of extracted.keys()) if (!source[key]) missing.push({
1892
+ locale: cfg.sourceLocale,
1893
+ key,
1894
+ source: extracted.get(key)?.message
1895
+ });
1896
+ for (const locale of cfg.locales) {
1897
+ if (locale === cfg.sourceLocale) continue;
1898
+ for (const key of needed) if (!flat[locale]?.[key]) missing.push({
1899
+ locale,
1900
+ key,
1901
+ source: source[key] ?? extracted.get(key)?.message
1902
+ });
1638
1903
  }
1639
- return false;
1640
- }
1641
- function buildMessage(code, quasi, names) {
1642
- const quasis = quasi.quasis;
1643
- const expressions = quasi.expressions;
1644
- const params = [];
1645
- const taken = /* @__PURE__ */ new Map();
1646
- let text = escapeText(cookedValue(quasis[0]));
1647
- for (let i = 0; i < expressions.length; i++) {
1648
- const expr = expressions[i];
1649
- if (!expr) return void 0;
1650
- if (containsTaggedT(expr, names)) return void 0;
1651
- const source = code.slice(expr.start, expr.end);
1652
- const name = uniqueName(deriveName(expr, i), source, taken);
1653
- params.push({
1654
- name,
1655
- start: expr.start,
1656
- end: expr.end
1904
+ const broken = [];
1905
+ const add = (locale, key, issues) => {
1906
+ for (const issue of issues) broken.push({
1907
+ locale,
1908
+ key,
1909
+ severity: issue.severity,
1910
+ issue: issue.message
1657
1911
  });
1658
- text += `{${name}}` + escapeText(cookedValue(quasis[i + 1]));
1912
+ };
1913
+ const divergent = [];
1914
+ for (const [key, entry] of extracted) {
1915
+ const written = source[key];
1916
+ if (written && written !== entry.message) divergent.push({
1917
+ key,
1918
+ catalog: written,
1919
+ code: siteOf(entry)
1920
+ });
1921
+ }
1922
+ for (const [key, text] of Object.entries(sourceText)) add(cfg.sourceLocale, key, validateMessage(text, cfg.sourceLocale));
1923
+ for (const locale of cfg.locales) {
1924
+ if (locale === cfg.sourceLocale) continue;
1925
+ for (const [key, translated] of Object.entries(flat[locale] ?? {})) {
1926
+ if (!translated) continue;
1927
+ add(locale, key, validateMessage(translated, locale));
1928
+ const text = sourceText[key];
1929
+ if (text) add(locale, key, validatePair(text, translated));
1930
+ }
1931
+ }
1932
+ const extra = [];
1933
+ for (const locale of cfg.locales) {
1934
+ if (locale === cfg.sourceLocale) continue;
1935
+ for (const key of Object.keys(flat[locale] ?? {})) {
1936
+ if (source[key] !== void 0 || extracted.has(key)) continue;
1937
+ extra.push({
1938
+ locale,
1939
+ key,
1940
+ files: used.get(key) ?? []
1941
+ });
1942
+ }
1659
1943
  }
1660
1944
  return {
1661
- text,
1662
- params
1945
+ ok: gatePasses({
1946
+ missing,
1947
+ unknown,
1948
+ broken
1949
+ }),
1950
+ missing,
1951
+ unknown,
1952
+ broken,
1953
+ extra,
1954
+ collisions: collisionEntries(registry),
1955
+ divergent,
1956
+ outdated: outdatedTranslations(cfg, shipped, fingerprints)
1663
1957
  };
1664
1958
  }
1665
- function cookedValue(element) {
1666
- if (!element) return "";
1667
- const value = element.value;
1668
- return value.cooked ?? value.raw;
1669
- }
1670
- function escapeText(text) {
1671
- return text.replace(/[{}]/g, (m) => m + m);
1672
- }
1673
- function deriveName(expr, index) {
1674
- if (expr.type === "Identifier") return expr.name;
1675
- if (expr.type === "MemberExpression" && !expr.computed) {
1676
- const prop = expr.property;
1677
- if (prop.type === "Identifier") return prop.name;
1959
+ function formatCheckResult(result, root) {
1960
+ const show = (file) => root ? relative(root, file).replaceAll("\\", "/") : file;
1961
+ const lines = [];
1962
+ if (result.missing.length > 0) {
1963
+ lines.push("missing translations:");
1964
+ for (const entry of result.missing) {
1965
+ const hint = entry.source ? `: "${truncate(entry.source, 40)}"` : "";
1966
+ lines.push(` [${entry.locale}] ${entry.key}${hint}`);
1967
+ }
1678
1968
  }
1679
- return `_${index}`;
1680
- }
1681
- function uniqueName(base, source, taken) {
1682
- let name = base;
1683
- let n = 2;
1684
- while (taken.has(name) && taken.get(name) !== source) {
1685
- name = `${base}${n}`;
1686
- n += 1;
1969
+ if (result.unknown.length > 0) {
1970
+ lines.push("unknown keys (not in any catalog):");
1971
+ for (const entry of result.unknown) lines.push(` ${entry.key} (used in ${entry.files.map(show).join(", ")})`);
1687
1972
  }
1688
- taken.set(name, source);
1689
- return name;
1690
- }
1691
- function walk(node, visit) {
1692
- visit(node);
1693
- for (const key in node) {
1694
- if (SKIP_KEYS.has(key)) continue;
1695
- const value = node[key];
1696
- if (Array.isArray(value)) {
1697
- for (const item of value) if (isNode(item)) walk(item, visit);
1698
- } else if (isNode(value)) walk(value, visit);
1973
+ const errors = result.broken.filter((entry) => entry.severity === "error");
1974
+ if (errors.length > 0) {
1975
+ lines.push("broken translations:");
1976
+ for (const entry of errors) lines.push(` [${entry.locale}] ${entry.key}: ${entry.issue}`);
1699
1977
  }
1978
+ return lines.join("\n");
1700
1979
  }
1701
- function isNode(value) {
1702
- return typeof value === "object" && value !== null && typeof value.type === "string";
1980
+ function checkNextSteps(result, cliReachable = true) {
1981
+ const steps = [];
1982
+ if (result.missing.length > 0) steps.push("missing: run `npx verbaly extract` to scaffold the keys, then fill them (or run `npx verbaly translate`)");
1983
+ if (result.unknown.length > 0) steps.push("unknown keys: the key used in the code is in no catalog, fix the key or run `npx verbaly extract`");
1984
+ if (result.broken.some((entry) => entry.severity === "error")) steps.push("broken: a translation has to keep the params, tags and plural cases of its source message");
1985
+ if (steps.length > 0 && !cliReachable) steps.push(`the verbaly command is not linked in this project: ${CLI_INSTALL_FIX}`);
1986
+ return steps.join("\n");
1703
1987
  }
1704
- //#endregion
1705
- //#region src/sfc.ts
1706
- const SFC_FILE_RE = /\.(?:svelte|vue|astro)$/;
1707
- function analyzeFile(code, file) {
1708
- if (SFC_FILE_RE.test(file)) return analyzeSfc(code, file);
1709
- try {
1710
- return analyze(code, file);
1711
- } catch (error) {
1712
- return {
1713
- tagged: [],
1714
- usedKeys: [],
1715
- strayImports: [],
1716
- parseError: parseErrorMessage(error)
1717
- };
1718
- }
1988
+ function formatCheckWarnings(result, root, options = {}) {
1989
+ const lines = result.broken.filter((entry) => entry.severity === "warning").map((entry) => ` [${entry.locale}] ${entry.key}: ${entry.issue}`);
1990
+ for (const entry of result.extra) lines.push(entry.files.length > 0 ? ` [${entry.locale}] ${entry.key}: only this translation has it, so the source language shows the key itself` : ` [${entry.locale}] ${entry.key}: only this translation has it, and no code reads it`);
1991
+ for (const entry of result.collisions) lines.push(` ${formatFinding({
1992
+ kind: "collision",
1993
+ ...entry
1994
+ }, root)}`);
1995
+ for (const { key, catalog, code } of result.divergent) lines.push(` ${key}: the source catalog says "${truncate(catalog, 40)}" and the code says "${truncate(code.message, 40)}" (${sourcePlace(code, root)}): the code wins, so edit the text there (extract writes it into the catalog)`);
1996
+ if (!options.outdatedFails) for (const entry of result.outdated) lines.push(` ${formatFinding({
1997
+ kind: "outdated",
1998
+ ...entry
1999
+ }, root)}`);
2000
+ return lines.join("\n");
1719
2001
  }
1720
- const SCRIPT_RE = /(<script\b[^>]*>)([\s\S]*?)(<\/script\s*>)/gi;
1721
- const STYLE_RE = /<style\b[^>]*>[\s\S]*?<\/style\s*>/gi;
1722
- const COMMENT_RE = /<!--[\s\S]*?-->/g;
1723
- const FRONTMATTER_RE = /^(\uFEFF?\s*---\r?\n)([\s\S]*?)\r?\n---(?=\r?\n|$)/;
1724
- const CANDIDATE_SVELTE = /(?<![\w$])\$?t(?=[`(]|\.id\()/g;
1725
- const CANDIDATE_VUE = /(?<![\w$])t(?=[`(]|\.id\()/g;
1726
- const MUSTACHE_RE = /\{\{[\s\S]*?\}\}/g;
1727
- const DIRECTIVE_RE = /\s(?:v-[\w-]+(?::[^\s=>/]+)?|[:@][^\s=>/]+)\s*=\s*("[^"]*"|'[^']*')/g;
1728
- function analyzeSfc(code, file) {
1729
- const svelte = file.endsWith(".svelte");
1730
- const options = svelte ? { tNames: ["t", "$t"] } : void 0;
1731
- const tagged = [];
1732
- const usedKeys = [];
1733
- const strayImports = [];
1734
- let parseError;
1735
- const block = (segment, offset) => {
1736
- parseError ??= segment.error;
1737
- merge(segment.analysis, offset, false);
1738
- };
1739
- const frontmatter = file.endsWith(".astro") ? FRONTMATTER_RE.exec(code) : null;
1740
- if (frontmatter?.[2]) block(analyzeSegment(frontmatter[2], file, options), frontmatter[1].length);
1741
- for (const match of code.matchAll(SCRIPT_RE)) {
1742
- const content = match[2];
1743
- if (!content) continue;
1744
- block(analyzeSegment(content, file, options), match.index + match[1].length);
1745
- }
1746
- const markup = blank(blank(blank(frontmatter ? " ".repeat(frontmatter[0].length) + code.slice(frontmatter[0].length) : code, SCRIPT_RE), STYLE_RE), COMMENT_RE);
1747
- const candidates = svelte ? CANDIDATE_SVELTE : CANDIDATE_VUE;
1748
- const ranges = file.endsWith(".vue") ? vueExpressionRanges(markup) : braceRanges(markup);
1749
- let range = 0;
1750
- let consumedTo = 0;
1751
- for (const match of markup.matchAll(candidates)) {
1752
- const start = match.index;
1753
- if (start < consumedTo) continue;
1754
- while (range < ranges.length && ranges[range][1] <= start) range += 1;
1755
- if (range >= ranges.length || start < ranges[range][0]) continue;
1756
- const end = expressionExtent(markup, start);
1757
- if (end === void 0) continue;
1758
- merge(analyzeSegment(code.slice(start, end), file, options).analysis, start, true);
1759
- consumedTo = end;
1760
- }
1761
- return {
1762
- tagged,
1763
- usedKeys,
1764
- strayImports,
1765
- ...parseError && { parseError }
1766
- };
1767
- function merge(analysis, offset, markupSegment) {
1768
- if (!analysis) return;
1769
- for (const msg of analysis.tagged) tagged.push({
1770
- ...msg,
1771
- start: msg.start + offset,
1772
- end: msg.end + offset,
1773
- tagStart: msg.tagStart + offset,
1774
- tagEnd: msg.tagEnd + offset,
1775
- params: msg.params.map((p) => ({
1776
- ...p,
1777
- start: p.start + offset,
1778
- end: p.end + offset
1779
- })),
1780
- ...markupSegment && { singleQuote: true }
2002
+ function githubCheckAnnotations(result, registry, cfg, options = {}) {
2003
+ const messages = registry.messages();
2004
+ const rel = (file) => escapeProperty(relative(cfg.root, file).replaceAll("\\", "/"));
2005
+ const at = (file, line) => `file=${rel(file)}${line ? `,line=${line}` : ""}`;
2006
+ const lines = [];
2007
+ const byKey = /* @__PURE__ */ new Map();
2008
+ for (const entry of result.missing) {
2009
+ const grouped = byKey.get(entry.key);
2010
+ if (grouped) grouped.locales.push(entry.locale);
2011
+ else byKey.set(entry.key, {
2012
+ ...entry,
2013
+ locales: [entry.locale]
1781
2014
  });
1782
- usedKeys.push(...analysis.usedKeys);
1783
- strayImports.push(...analysis.strayImports);
1784
2015
  }
1785
- }
1786
- function analyzeSegment(code, file, options) {
1787
- try {
1788
- return { analysis: analyze(code, file, options) };
1789
- } catch (error) {
1790
- return { error: parseErrorMessage(error) };
2016
+ for (const entry of byKey.values()) {
2017
+ const origin = messages.get(entry.key);
2018
+ const hint = entry.source ? `: "${truncate(entry.source, 60)}"` : "";
2019
+ const text = escapeData(`missing [${entry.locales.join(", ")}] ${entry.key}${hint}`);
2020
+ if (origin) lines.push(`::error ${at(origin.file, origin.line)}::${text}`);
2021
+ else lines.push(`::error::${text}`);
1791
2022
  }
1792
- }
1793
- function blank(source, re) {
1794
- return source.replace(re, (m) => " ".repeat(m.length));
1795
- }
1796
- function braceRanges(markup) {
1797
- const ranges = [];
1798
- let i = 0;
1799
- while (i < markup.length) {
1800
- if (markup[i] === "{") {
1801
- const end = balancedEnd(markup, i);
1802
- if (end !== void 0) {
1803
- ranges.push([i + 1, end - 1]);
1804
- i = end;
1805
- continue;
1806
- }
2023
+ for (const entry of result.unknown) {
2024
+ const text = escapeData(`unknown key "${entry.key}" (not in any catalog)`);
2025
+ const file = entry.files[0];
2026
+ lines.push(file ? `::error file=${rel(file)}::${text}` : `::error::${text}`);
2027
+ }
2028
+ for (const entry of result.broken) {
2029
+ const origin = messages.get(entry.key);
2030
+ const text = escapeData(`[${entry.locale}] ${entry.key}: ${entry.issue}`);
2031
+ const command = entry.severity === "error" ? "error" : "warning";
2032
+ if (!origin) {
2033
+ lines.push(`::${command}::${text}`);
2034
+ continue;
1807
2035
  }
1808
- i += 1;
2036
+ lines.push(`::${command} ${at(origin.file, origin.line)}::${text}`);
1809
2037
  }
1810
- return ranges;
1811
- }
1812
- function vueExpressionRanges(markup) {
1813
- const ranges = [];
1814
- for (const match of markup.matchAll(MUSTACHE_RE)) ranges.push([match.index + 2, match.index + match[0].length - 2]);
1815
- for (const match of markup.matchAll(DIRECTIVE_RE)) {
1816
- const valueStart = match.index + match[0].length - match[1].length + 1;
1817
- ranges.push([valueStart, valueStart + match[1].length - 2]);
2038
+ for (const entry of result.extra) {
2039
+ const text = escapeData(`[${entry.locale}] ${entry.key}: only this translation has it`);
2040
+ const file = entry.files[0];
2041
+ lines.push(file ? `::warning file=${rel(file)}::${text}` : `::warning::${text}`);
1818
2042
  }
1819
- return ranges.sort((a, b) => a[0] - b[0]);
1820
- }
1821
- function expressionExtent(code, start) {
1822
- let i = start;
1823
- if (code[i] === "$") i += 1;
1824
- i += 1;
1825
- if (code.startsWith(".id(", i)) {
1826
- const close = balancedEnd(code, i + 3);
1827
- if (close === void 0 || code[close] !== "`") return void 0;
1828
- return balancedEnd(code, close);
2043
+ for (const { key, sites } of result.collisions) {
2044
+ const texts = new Set(sites.map((place) => place.message)).size;
2045
+ const text = escapeData(`"${key}" has ${counted(texts, "text")}, and every place shows the first one`);
2046
+ for (const place of sites) lines.push(`::warning ${at(place.file, place.line)}::${text}`);
1829
2047
  }
1830
- if (code[i] === "`" || code[i] === "(") return balancedEnd(code, i);
2048
+ for (const { key, code } of result.divergent) {
2049
+ const text = escapeData(`"${key}": the source catalog has another text, the code's one ships`);
2050
+ lines.push(`::warning ${at(code.file, code.line)}::${text}`);
2051
+ }
2052
+ const outdated = options.outdatedFails ? "error" : "warning";
2053
+ for (const { locale, key } of result.outdated) {
2054
+ const text = escapeData(`[${locale}] ${key}: translated from an older source text`);
2055
+ lines.push(`::${outdated} file=${rel(catalogPath(cfg, locale))}::${text}`);
2056
+ }
2057
+ return lines;
1831
2058
  }
1832
- function balancedEnd(code, open) {
1833
- const stack = [];
1834
- let i = open;
1835
- while (i < code.length) {
1836
- const ch = code[i];
1837
- if (stack[stack.length - 1] === "`") {
1838
- if (ch === "\\") i += 1;
1839
- else if (ch === "`") stack.pop();
1840
- else if (ch === "$" && code[i + 1] === "{") {
1841
- stack.push("{");
1842
- i += 1;
1843
- }
1844
- } else if (ch === "'" || ch === "\"") i = stringEnd(code, i);
1845
- else if (ch === "`" || ch === "(" || ch === "{") stack.push(ch);
1846
- else if (ch === ")" || ch === "}") {
1847
- if (stack[stack.length - 1] !== (ch === ")" ? "(" : "{")) return void 0;
1848
- stack.pop();
2059
+ function escapeData(text) {
2060
+ return text.replaceAll("%", "%25").replaceAll("\r", "%0D").replaceAll("\n", "%0A");
2061
+ }
2062
+ function escapeProperty(text) {
2063
+ return escapeData(text).replaceAll(":", "%3A").replaceAll(",", "%2C");
2064
+ }
2065
+ //#endregion
2066
+ //#region src/bundle.ts
2067
+ function isExcluded(key, prefixes) {
2068
+ return prefixes.some((prefix) => key === prefix || key.startsWith(`${prefix}.`));
2069
+ }
2070
+ function auditBundle(cfg, catalogs, registry) {
2071
+ const prefixes = cfg.bundle.exclude ?? [];
2072
+ if (prefixes.length === 0) return [];
2073
+ const source = Object.keys(catalogs[cfg.sourceLocale] ?? {});
2074
+ const used = registry.usedKeys();
2075
+ const issues = [];
2076
+ for (const prefix of prefixes) {
2077
+ if (!source.some((key) => isExcluded(key, [prefix]))) {
2078
+ issues.push({
2079
+ prefix,
2080
+ problem: `matches no key in ${cfg.sourceLocale}.json, so it excludes nothing`,
2081
+ fix: "check the spelling against your catalog, or drop it from bundle.exclude"
2082
+ });
2083
+ continue;
1849
2084
  }
1850
- i += 1;
1851
- if (stack.length === 0) return i;
2085
+ const files = /* @__PURE__ */ new Set();
2086
+ for (const [key, where] of used) if (isExcluded(key, [prefix])) for (const file of where) files.add(file);
2087
+ if (files.size > 0) issues.push({
2088
+ prefix,
2089
+ problem: `is read by t() in ${counted(files.size, "file")}, where it resolves to the key itself`,
2090
+ fix: "pre-render those pages with render, load the group with addMessages, or stop excluding it"
2091
+ });
1852
2092
  }
2093
+ return issues;
1853
2094
  }
1854
- function stringEnd(code, start) {
1855
- const quote = code[start];
1856
- let i = start + 1;
1857
- while (i < code.length) if (code[i] === "\\") i += 2;
1858
- else if (code[i] === quote) return i;
1859
- else i += 1;
1860
- return code.length;
2095
+ function formatBundleIssue(issue) {
2096
+ return `bundle.exclude "${issue.prefix}" ${issue.problem}`;
1861
2097
  }
1862
2098
  //#endregion
1863
- //#region src/extract.ts
1864
- async function extractProject(cfg) {
1865
- const files = await glob(cfg.include, {
1866
- cwd: cfg.root,
1867
- ignore: cfg.exclude,
1868
- absolute: true
1869
- });
1870
- const registry = new MessageRegistry();
1871
- for (const file of files) registry.update(file, analyzeFile(readFileSync(file, "utf8"), file));
1872
- return registry;
1873
- }
1874
- async function collectOrigins(cfg, reuse) {
1875
- const registry = reuse ?? await extractProject(cfg);
1876
- const origins = Object.create(null);
1877
- for (const [key, files] of registry.origins()) origins[key] = files.map((file) => relative(cfg.root, file).replaceAll("\\", "/"));
1878
- return origins;
2099
+ //#region src/params.ts
2100
+ const NUMBER_FORMATS = /* @__PURE__ */ new Set([
2101
+ "number",
2102
+ "integer",
2103
+ "percent",
2104
+ "currency"
2105
+ ]);
2106
+ const DATE_FORMATS = /* @__PURE__ */ new Set(["date", "time"]);
2107
+ function collectParams(message) {
2108
+ const out = /* @__PURE__ */ new Map();
2109
+ visit(parse(message, parseIcu), out);
2110
+ return out;
1879
2111
  }
1880
- function syncCatalogs(cfg, catalogs, registry) {
1881
- const added = {};
1882
- const replaced = [];
1883
- const source = catalogs[cfg.sourceLocale] ??= emptyCatalog();
1884
- for (const [key, msg] of registry.messages()) {
1885
- const before = own(source, key);
1886
- if (before !== msg.message) {
1887
- if (before) replaced.push(key);
1888
- source[key] = msg.message;
1889
- (added[cfg.sourceLocale] ??= []).push(key);
1890
- }
1891
- }
1892
- const needed = Object.keys(source);
1893
- for (const locale of cfg.locales) {
1894
- if (locale === cfg.sourceLocale) continue;
1895
- const catalog = catalogs[locale] ??= emptyCatalog();
1896
- for (const key of needed) if (own(catalog, key) === void 0) {
1897
- catalog[key] = "";
1898
- (added[locale] ??= []).push(key);
1899
- }
2112
+ function visit(nodes, out) {
2113
+ for (const node of nodes) {
2114
+ if (node.kind !== "param") continue;
2115
+ const types = out.get(node.name) ?? /* @__PURE__ */ new Set();
2116
+ out.set(node.name, types);
2117
+ if (node.variants) {
2118
+ for (const [key, body] of node.variants) {
2119
+ if (PLURAL_CATEGORIES.has(key) || /^=\d+$/.test(key)) types.add("number");
2120
+ else if (key !== "other") types.add("string");
2121
+ visit(body, out);
2122
+ }
2123
+ if (types.size === 0) types.add("string");
2124
+ } else if (node.format && NUMBER_FORMATS.has(node.format)) types.add("number");
2125
+ else if (node.format && DATE_FORMATS.has(node.format)) types.add("date");
2126
+ else types.add("unknown");
1900
2127
  }
1901
- return {
1902
- added,
1903
- replaced
1904
- };
1905
2128
  }
1906
- function pruneCatalogs(cfg, catalogs, registry) {
1907
- const removed = {};
1908
- if (registry.parseErrors().length > 0) return removed;
1909
- const keep = /* @__PURE__ */ new Set([...registry.messages().keys(), ...registry.usedKeys().keys()]);
1910
- for (const locale of cfg.locales) {
1911
- const catalog = catalogs[locale];
1912
- if (!catalog) continue;
1913
- for (const key of Object.keys(catalog)) if (!keep.has(key)) {
1914
- delete catalog[key];
1915
- (removed[locale] ??= []).push(key);
2129
+ function renderParamType(types) {
2130
+ if (types.has("unknown") || types.size === 0) return "unknown";
2131
+ const members = /* @__PURE__ */ new Set();
2132
+ if (types.has("number")) members.add("number");
2133
+ if (types.has("string")) members.add("string");
2134
+ if (types.has("date")) for (const m of [
2135
+ "Date",
2136
+ "number",
2137
+ "string"
2138
+ ]) members.add(m);
2139
+ return [...members].join(" | ");
2140
+ }
2141
+ function generateDts(catalog, options = {}) {
2142
+ const lines = [];
2143
+ for (const [key, message] of Object.entries(catalog).sort(([a], [b]) => a.localeCompare(b))) {
2144
+ const params = collectParams(message);
2145
+ if (params.size === 0) lines.push(` ${JSON.stringify(key)}: never;`);
2146
+ else {
2147
+ const fields = [...params.entries()].map(([name, types]) => `${JSON.stringify(name)}: ${renderParamType(types)}`).join("; ");
2148
+ lines.push(` ${JSON.stringify(key)}: { ${fields} };`);
1916
2149
  }
1917
2150
  }
1918
- return removed;
2151
+ return `// generated by verbaly: do not edit
2152
+ declare module 'virtual:verbaly' {
2153
+ export interface VerbalyMessages {
2154
+ ${lines.join("\n")}
2155
+ }
2156
+ export type VerbalyKey = keyof VerbalyMessages & string;
2157
+
2158
+ export type VerbalyKeyTree = VerbalyKey | { readonly [name: string]: VerbalyKeyTree };
2159
+ export function defineKeys<const T extends VerbalyKeyTree>(keys: T): T;
2160
+
2161
+ export const verbaly: import('verbaly').Verbaly<VerbalyKey>;
2162
+
2163
+ export const sourceLocale: string;
2164
+ export const locales: string[];
2165
+ export const routing: import('verbaly').Routing;
2166
+ export function localePath(
2167
+ locale: string,
2168
+ options?: { path?: string; base?: string },
2169
+ ): string;
2170
+ export function localeFromPath(options?: {
2171
+ path?: string;
2172
+ base?: string;
2173
+ }): string | undefined;
2174
+ export function loadMessages(locale: string): Promise<Record<string, string>>;${options.inlineCatalog ? "\n export function adoptPage(options?: {\n root?: ParentNode;\n path?: string;\n }): string | undefined;" : ""}
2175
+ export function createInstance(
2176
+ options?: import('verbaly').VerbalyOptions<VerbalyKey>,
2177
+ ): import('verbaly').Verbaly<VerbalyKey>;
2178
+ export function createRequestInstance(
2179
+ locale: string,
2180
+ ): Promise<import('verbaly').Verbaly<VerbalyKey>>;
2181
+
2182
+ export function t<K extends VerbalyKey>(
2183
+ key: K,
2184
+ ...args: [VerbalyMessages[K]] extends [never] ? [] : [VerbalyMessages[K]]
2185
+ ): string;
2186
+ export function t(strings: TemplateStringsArray, ...values: unknown[]): string;
2187
+ export namespace t {
2188
+ export function id(
2189
+ key: string,
2190
+ ): (strings: TemplateStringsArray, ...values: unknown[]) => string;
2191
+ }
2192
+
2193
+ export function setLocale(locale: string): Promise<void>;
2194
+ export function switchLocale(
2195
+ locale: string,
2196
+ options?: Omit<
2197
+ import('verbaly').SwitchLocaleOptions,
2198
+ 'routing' | 'supported' | 'sourceLocale'
2199
+ >,
2200
+ ): Promise<void>;
2201
+ export function getLocale(): string;
2202
+ export function subscribe(listener: () => void): () => void;
1919
2203
  }
1920
- //#endregion
1921
- //#region src/drafts.ts
1922
- function loadDrafts(cfg) {
1923
- return loadState(cfg).drafts;
1924
- }
1925
- function saveDrafts(cfg, drafts) {
1926
- saveState(cfg, {
1927
- ...loadState(cfg),
1928
- drafts
1929
- });
2204
+
2205
+ declare module 'virtual:verbaly/locale/*' {
2206
+ const messages: Record<string, string>;
2207
+ export default messages;
1930
2208
  }
1931
- function markDrafts(drafts, locale, keys) {
1932
- if (!keys.length) return;
1933
- drafts[locale] = [.../* @__PURE__ */ new Set([...drafts[locale] ?? [], ...keys])];
2209
+ `;
1934
2210
  }
1935
- function clearDrafts(drafts, locale, keys) {
1936
- if (!drafts[locale]) return;
1937
- if (!keys) {
1938
- delete drafts[locale];
1939
- return;
1940
- }
1941
- const drop = new Set(keys);
1942
- drafts[locale] = drafts[locale].filter((key) => !drop.has(key));
1943
- if (!drafts[locale].length) delete drafts[locale];
2211
+ function writeDts(cfg, catalog, file) {
2212
+ const target = file === void 0 ? cfg.dts : file;
2213
+ if (target === false) return;
2214
+ file = target ?? join(cfg.root, "verbaly.d.ts");
2215
+ const content = generateDts(catalog, { inlineCatalog: cfg.render.inlineCatalog === true });
2216
+ try {
2217
+ if (readFileSync(file, "utf8") === content) return;
2218
+ } catch {}
2219
+ mkdirSync(dirname(file), { recursive: true });
2220
+ writeFileSync(file, content);
1944
2221
  }
1945
2222
  //#endregion
1946
2223
  //#region src/doctor.ts
@@ -2070,15 +2347,13 @@ async function doctor(cfg) {
2070
2347
  }
2071
2348
  const missed = registry.missed();
2072
2349
  if (missed.length > 0) {
2073
- const locate = createLocator();
2074
2350
  const first = missed[0];
2075
- const line = locate(first.file, first.start);
2076
- warn("sources", `a t under another name keeps ${counted(missed.length, "text")} out of extraction (${rel(first.file)}${line ? `:${line}` : ""}: ${first.name}\`…\`)`, "name it t (const t = useT()), the only name verbaly reads, or use t(key) with the key in the catalog");
2351
+ warn("sources", `a t under another name keeps ${counted(missed.length, "text")} out of extraction (${sourcePlace(first, cfg.root)}: ${first.name}\`…\`)`, "name it t (const t = useT()), the only name verbaly reads, or use t(key) with the key in the catalog");
2077
2352
  }
2078
2353
  const positional = [...registry.messages().values()].filter((msg) => msg.params.some((param) => /^_\d+$/.test(param.name)));
2079
2354
  if (positional.length > 0) {
2080
2355
  const first = positional[0];
2081
- warn("messages", `a translator gets a nameless value like {_0} in ${counted(positional.length, "message")} (${rel(first.file)}: "${first.message}")`, "put the value in a named variable first (const date = formatDate(d)), so the message says {date}");
2356
+ warn("messages", `a translator gets a nameless value like {_0} in ${counted(positional.length, "message")} (${sourcePlace(first, cfg.root)}: "${first.message}")`, "put the value in a named variable first (const date = formatDate(d)), so the message says {date}");
2082
2357
  }
2083
2358
  const escaped = [...registry.messages().values()].map((msg) => ({
2084
2359
  file: rel(msg.file),
@@ -2100,15 +2375,8 @@ async function doctor(cfg) {
2100
2375
  for (const issue of issues) warn("bundle", formatBundleIssue(issue), issue.fix);
2101
2376
  if (issues.length === 0) ok("bundle", `${counted(excluded.length, "group")} kept out of the client (${preview(excluded)})`);
2102
2377
  }
2103
- let state = {
2104
- drafts: {},
2105
- fingerprints: {}
2106
- };
2107
- try {
2108
- state = loadState(cfg);
2109
- } catch (error) {
2110
- warn("state", error.message.replace(/^\[verbaly\] /, ""), `delete ${STATE_FILE}: drafts and outdated tracking start again from the catalogs`);
2111
- }
2378
+ const { state, problem } = readState(cfg);
2379
+ if (problem) warn("state", problem, `restore ${STATE_FILE} from git: deleting it would mark every machine draft as reviewed`);
2112
2380
  if (catalogsHealthy) {
2113
2381
  const stale = Object.entries(state.drafts).flatMap(([locale, keys]) => {
2114
2382
  const live = new Set(effectiveDrafts({ [locale]: keys }, catalogs)[locale] ?? []);
@@ -2437,6 +2705,7 @@ function toPo(sourceLocale, locale, entries) {
2437
2705
  }
2438
2706
  function parsePo(content) {
2439
2707
  const entries = Object.create(null);
2708
+ const sources = Object.create(null);
2440
2709
  let locale;
2441
2710
  let msgctxt;
2442
2711
  let msgid;
@@ -2447,7 +2716,10 @@ function parsePo(content) {
2447
2716
  if (msgid === "" && msgctxt === void 0) {
2448
2717
  const lang = /^Language:[ \t]*(.+?)[ \t]*$/m.exec(msgstr ?? "")?.[1];
2449
2718
  if (lang) locale = lang;
2450
- } else if (msgctxt !== void 0 && msgid !== void 0) entries[msgctxt] = fuzzy ? "" : msgstr ?? "";
2719
+ } else if (msgctxt !== void 0 && msgid !== void 0) {
2720
+ entries[msgctxt] = fuzzy ? "" : msgstr ?? "";
2721
+ sources[msgctxt] = msgid;
2722
+ }
2451
2723
  msgctxt = msgid = msgstr = field = void 0;
2452
2724
  fuzzy = false;
2453
2725
  };
@@ -2487,7 +2759,8 @@ function parsePo(content) {
2487
2759
  finish();
2488
2760
  return {
2489
2761
  locale,
2490
- entries
2762
+ entries,
2763
+ sources
2491
2764
  };
2492
2765
  }
2493
2766
  function poString(text) {
@@ -2647,7 +2920,7 @@ function formatTranslateFailures(failed) {
2647
2920
  async function resolveProvider(cfg, model) {
2648
2921
  const configured = cfg.translate.provider;
2649
2922
  if (typeof configured === "function") return configured;
2650
- const { claudeProvider } = await import("./claude-BmD8W9uW.js");
2923
+ const { claudeProvider } = await import("./claude-DmnZ1cvR.js");
2651
2924
  return claudeProvider({ model: model ?? cfg.translate.model });
2652
2925
  }
2653
2926
  function structureMatches(source, translated) {
@@ -2751,7 +3024,8 @@ function importCatalogs(cfg, catalogs, files, options = {}) {
2751
3024
  skipped: {},
2752
3025
  unknown: {},
2753
3026
  unmatched: [],
2754
- mapped: []
3027
+ mapped: [],
3028
+ sources: {}
2755
3029
  };
2756
3030
  for (const file of files) {
2757
3031
  const parsed = parseExchangeFile(file, options.locale);
@@ -2795,6 +3069,8 @@ function importCatalogs(cfg, catalogs, files, options = {}) {
2795
3069
  }
2796
3070
  if (!options.dryRun) catalog[key] = text;
2797
3071
  (result.imported[locale] ??= []).push(key);
3072
+ const seen = parsed.sources[key];
3073
+ if (seen) (result.sources[locale] ??= {})[key] = seen;
2798
3074
  }
2799
3075
  }
2800
3076
  return result;
@@ -2807,18 +3083,20 @@ function parseExchangeFile(file, localeOverride) {
2807
3083
  if (!locale) throw new Error(`[verbaly] ${file} has no trgLang/target-language, pass --locale <id>.`);
2808
3084
  return {
2809
3085
  locale,
2810
- entries: parsed.entries
3086
+ entries: parsed.entries,
3087
+ sources: parsed.sources
2811
3088
  };
2812
3089
  }
2813
3090
  if (/\.csv$/i.test(file)) return {
2814
3091
  locale: localeOverride ?? basename(file).replace(/\.csv$/i, ""),
2815
- entries: parseCsv(content)
3092
+ ...parseCsv(content)
2816
3093
  };
2817
3094
  if (/\.po$/i.test(file)) {
2818
3095
  const parsed = parsePo(content);
2819
3096
  return {
2820
3097
  locale: localeOverride ?? parsed.locale ?? basename(file).replace(/\.po$/i, ""),
2821
- entries: parsed.entries
3098
+ entries: parsed.entries,
3099
+ sources: parsed.sources
2822
3100
  };
2823
3101
  }
2824
3102
  throw new Error(`[verbaly] ${file}: unsupported format, expected .xlf, .xliff, .csv or .po.`);
@@ -2854,15 +3132,19 @@ function newLocale(cfg, detected) {
2854
3132
  function parseXliff(content) {
2855
3133
  const locale = /\btrgLang\s*=\s*"([^"]+)"/.exec(content)?.[1] ?? /\btarget-language\s*=\s*"([^"]+)"/.exec(content)?.[1];
2856
3134
  const entries = Object.create(null);
3135
+ const sources = Object.create(null);
2857
3136
  for (const match of content.matchAll(/<(?:trans-)?unit\b([^>]*)>([\s\S]*?)<\/(?:trans-)?unit>/g)) {
2858
3137
  const id = /\bid\s*=\s*"([^"]*)"/.exec(match[1])?.[1];
2859
3138
  if (!id) continue;
2860
3139
  const target = /<target\b[^>]*>([\s\S]*?)<\/target>/.exec(match[2])?.[1];
2861
3140
  entries[unescapeXml(id)] = target === void 0 ? "" : inlineToMessage(stripCdata(target));
3141
+ const source = /<source\b[^>]*>([\s\S]*?)<\/source>/.exec(match[2])?.[1];
3142
+ if (source !== void 0) sources[unescapeXml(id)] = inlineToMessage(stripCdata(source));
2862
3143
  }
2863
3144
  return {
2864
3145
  locale,
2865
- entries
3146
+ entries,
3147
+ sources
2866
3148
  };
2867
3149
  }
2868
3150
  function stripCdata(text) {
@@ -2883,13 +3165,21 @@ function parseCsv(content) {
2883
3165
  const header = rows[0]?.map((cell) => cell.trim().toLowerCase()) ?? [];
2884
3166
  const keyCol = header.indexOf("key");
2885
3167
  const targetCol = header.indexOf("target");
3168
+ const sourceCol = header.indexOf("source");
2886
3169
  if (keyCol === -1 || targetCol === -1) throw new Error("[verbaly] CSV needs a header row with \"key\" and \"target\" columns.");
2887
3170
  const entries = Object.create(null);
3171
+ const sources = Object.create(null);
2888
3172
  for (const row of rows.slice(1)) {
2889
3173
  const key = row[keyCol];
2890
- if (key) entries[key] = row[targetCol] ?? "";
3174
+ if (!key) continue;
3175
+ entries[key] = row[targetCol] ?? "";
3176
+ const source = sourceCol === -1 ? void 0 : row[sourceCol];
3177
+ if (source) sources[key] = source;
2891
3178
  }
2892
- return entries;
3179
+ return {
3180
+ entries,
3181
+ sources
3182
+ };
2893
3183
  }
2894
3184
  function csvRows(content) {
2895
3185
  const rows = [];
@@ -3085,6 +3375,55 @@ function migrateCatalogs(cfg, options = {}) {
3085
3375
  };
3086
3376
  }
3087
3377
  //#endregion
3378
+ //#region src/project.ts
3379
+ async function syncProject(cfg, options = {}) {
3380
+ const registry = options.registry ?? await extractProject(cfg);
3381
+ const catalogs = options.catalogs ?? loadCatalogs(cfg);
3382
+ if (options.confirm) confirmFromDisk(cfg, catalogs, registry);
3383
+ const pruneBlocked = options.prune === true && registry.parseErrors().length > 0;
3384
+ const pruned = options.prune ? pruneCatalogs(cfg, catalogs, registry) : {};
3385
+ const { added, replaced } = syncCatalogs(cfg, catalogs, registry);
3386
+ const result = {
3387
+ registry,
3388
+ catalogs,
3389
+ added,
3390
+ replaced,
3391
+ pruned,
3392
+ pruneBlocked,
3393
+ findings: scanFindings(cfg, registry, replaced),
3394
+ written: {}
3395
+ };
3396
+ if (options.dryRun) return result;
3397
+ const changed = /* @__PURE__ */ new Set([...Object.keys(added), ...Object.keys(pruned)]);
3398
+ if (replaced.length > 0) changed.add(cfg.sourceLocale);
3399
+ for (const locale of cfg.locales) {
3400
+ if (options.write === "changed" && !changed.has(locale)) continue;
3401
+ result.written[locale] = writeCatalog(cfg, locale, catalogs[locale] ?? {});
3402
+ }
3403
+ writeDts(cfg, catalogs[cfg.sourceLocale] ?? {});
3404
+ try {
3405
+ result.state = updateState(cfg, catalogs);
3406
+ } catch (error) {
3407
+ result.stateProblem = error.message.replace(/^\[verbaly\] /, "");
3408
+ }
3409
+ return result;
3410
+ }
3411
+ function confirmFromDisk(cfg, catalogs, registry) {
3412
+ const source = catalogs[cfg.sourceLocale] ?? {};
3413
+ const stale = /* @__PURE__ */ new Set();
3414
+ for (const [key, msg] of registry.messages()) if (own(source, key) !== msg.message) stale.add(msg.file);
3415
+ for (const file of stale) {
3416
+ let code;
3417
+ try {
3418
+ code = readFileSync(file, "utf8");
3419
+ } catch {
3420
+ registry.remove(file);
3421
+ continue;
3422
+ }
3423
+ registry.update(file, analyzeFile(code, file));
3424
+ }
3425
+ }
3426
+ //#endregion
3088
3427
  //#region src/warn.ts
3089
3428
  const warned = /* @__PURE__ */ new Set();
3090
3429
  function warnOnce(message, dedupeKey = message) {
@@ -3543,7 +3882,9 @@ function status(cfg, catalogs, registry, drafts = {}, fingerprints = {}) {
3543
3882
  const source = flat[cfg.sourceLocale] ?? {};
3544
3883
  const needed = /* @__PURE__ */ new Set([...extracted.keys(), ...Object.keys(source)]);
3545
3884
  const live = effectiveDrafts(drafts, flat);
3546
- const outdated = outdatedTranslations(cfg, flat, fingerprints);
3885
+ const shipped = shippedCatalogs(cfg, flat, registry);
3886
+ const sourceText = shipped[cfg.sourceLocale];
3887
+ const outdated = outdatedTranslations(cfg, shipped, fingerprints);
3547
3888
  const locales = [];
3548
3889
  for (const locale of cfg.locales) {
3549
3890
  if (locale === cfg.sourceLocale) continue;
@@ -3553,7 +3894,7 @@ function status(cfg, catalogs, registry, drafts = {}, fingerprints = {}) {
3553
3894
  let broken = 0;
3554
3895
  for (const [key, text] of Object.entries(catalog)) {
3555
3896
  if (!text) continue;
3556
- const from = source[key] ?? extracted.get(key)?.message;
3897
+ const from = sourceText[key];
3557
3898
  if ([...validateMessage(text, locale), ...from ? validatePair(from, text) : []].some((issue) => issue.severity === "error")) broken += 1;
3558
3899
  }
3559
3900
  locales.push({
@@ -3751,7 +4092,7 @@ function wrapCode(code, file) {
3751
4092
  const s = new MagicString(code);
3752
4093
  const visited = /* @__PURE__ */ new Set();
3753
4094
  let changed = false;
3754
- walk(ast, (node) => {
4095
+ walk$1(ast, (node) => {
3755
4096
  if (node.type !== "JSXElement" && node.type !== "JSXFragment") return;
3756
4097
  if (visited.has(node)) return;
3757
4098
  processElement(node);
@@ -3880,7 +4221,7 @@ function wrapCode(code, file) {
3880
4221
  return text.length > 60 ? text.slice(0, 59) + "…" : text;
3881
4222
  }
3882
4223
  function markSubtree(node) {
3883
- walk(node, (n) => {
4224
+ walk$1(node, (n) => {
3884
4225
  if (n.type === "JSXElement" || n.type === "JSXFragment") visited.add(n);
3885
4226
  });
3886
4227
  }
@@ -3896,7 +4237,7 @@ function hasDirective(program, value) {
3896
4237
  }
3897
4238
  function declaresT(program) {
3898
4239
  let found = false;
3899
- walk(program, (node) => {
4240
+ walk$1(program, (node) => {
3900
4241
  if (found) return;
3901
4242
  if (node.type === "ImportDeclaration") {
3902
4243
  for (const spec of node.specifiers) if (isTName(spec.local?.name)) found = true;
@@ -3928,7 +4269,7 @@ function hasVerbalyAttr(opening) {
3928
4269
  }
3929
4270
  function usesT(node) {
3930
4271
  let found = false;
3931
- walk(node, (n) => {
4272
+ walk$1(node, (n) => {
3932
4273
  if (n.type === "TaggedTemplateExpression" && isTReference(n.tag, T_NAMES)) found = true;
3933
4274
  if (n.type === "CallExpression" && isTReference(n.callee, T_NAMES)) found = true;
3934
4275
  });
@@ -3936,7 +4277,7 @@ function usesT(node) {
3936
4277
  }
3937
4278
  function containsJsx(node) {
3938
4279
  let found = false;
3939
- walk(node, (n) => {
4280
+ walk$1(node, (n) => {
3940
4281
  if (n.type === "JSXElement" || n.type === "JSXFragment") found = true;
3941
4282
  });
3942
4283
  return found;
@@ -3966,7 +4307,7 @@ Usage:
3966
4307
  verbaly status translation coverage per locale, at a glance
3967
4308
  verbaly check verify translations are complete (CI)
3968
4309
  verbaly translate fill missing translations via a provider (default: claude)
3969
- verbaly review list translations awaiting review: machine drafts and outdated ones (--approve accepts them)
4310
+ verbaly review [keys…] list translations awaiting review: machine drafts and outdated ones (--approve accepts them)
3970
4311
  verbaly export write translator files (XLIFF 2.0, CSV, gettext PO) or mobile resources (Android, iOS)
3971
4312
  verbaly import <files…> fill catalogs back from translated XLIFF/CSV/PO files
3972
4313
  verbaly pseudo generate a pseudo-locale catalog for i18n QA (default: en-XA)
@@ -3984,7 +4325,7 @@ Options:
3984
4325
  --json machine-readable output (status)
3985
4326
  --drafts also fail on unreviewed machine translations (check)
3986
4327
  --outdated also fail on translations written for an older source text (check)
3987
- --approve mark listed drafts as reviewed (review)
4328
+ --approve accept what review lists, drafts and outdated, or only the keys given (review)
3988
4329
  --reporter <name> failure format: text (default) or github annotations (check)
3989
4330
  --model <id> model override for the claude provider (translate)
3990
4331
  --dry-run list what would happen, write nothing (translate, import, extract)
@@ -4094,30 +4435,28 @@ async function runCli(args = process.argv.slice(2)) {
4094
4435
  process.exitCode = 1;
4095
4436
  return;
4096
4437
  }
4438
+ const reporter = values.watch ? createDevReporter(cfg.root, (line) => console.warn(` ${line}`)) : void 0;
4097
4439
  async function runExtract() {
4098
- const registry = await extractProject(cfg);
4099
- const catalogs = loadCatalogs(cfg);
4100
- if (values.prune) {
4101
- const removed = pruneCatalogs(cfg, catalogs, registry);
4102
- const unread = registry.parseErrors().length;
4103
- if (unread > 0) console.warn(` prune skipped: an unparsed file may read any key (${counted(unread, "file")} below), so it waits until every file parses`);
4104
- for (const [locale, keys] of Object.entries(removed)) console.log(dryRun ? ` ${locale}: would prune ${keys.length}: ${keys.join(", ")}` : ` ${locale}: -${keys.length} pruned`);
4105
- }
4106
- const { added, replaced } = syncCatalogs(cfg, catalogs, registry);
4107
- if (!dryRun) {
4108
- for (const locale of cfg.locales) writeCatalog(cfg, locale, catalogs[locale] ?? {});
4109
- writeDts(cfg, catalogs[cfg.sourceLocale] ?? {});
4110
- updateState(cfg, catalogs);
4440
+ const result = await syncProject(cfg, {
4441
+ prune: values.prune,
4442
+ dryRun
4443
+ });
4444
+ if (result.pruneBlocked) {
4445
+ const unread = result.registry.parseErrors().length;
4446
+ console.warn(` prune skipped: an unparsed file may read any key (${counted(unread, "file")} below), so it waits until every file parses`);
4111
4447
  }
4112
- const total = registry.messages().size;
4448
+ for (const [locale, keys] of Object.entries(result.pruned)) console.log(dryRun ? ` ${locale}: would prune ${keys.length}: ${keys.join(", ")}` : ` ${locale}: -${keys.length} pruned`);
4449
+ const total = result.registry.messages().size;
4113
4450
  console.log(`[verbaly] ${counted(total, "message")} · locales: ${cfg.locales.join(", ")}${dryRun ? " (dry run, nothing written)" : ""}`);
4114
- for (const [locale, keys] of Object.entries(added)) console.log(` ${locale}: ${dryRun ? `would add ${keys.length}` : `+${keys.length}`}`);
4115
- reportReplaced(cfg, registry, replaced, dryRun);
4116
- for (const entry of collisionEntries(registry)) console.warn(formatCollision(entry, cfg.root));
4117
- reportParseErrors(cfg, registry);
4118
- reportEscapedSyntax(cfg, registry);
4119
- reportMissed(cfg, registry);
4120
- reportPositional(cfg, registry);
4451
+ for (const [locale, keys] of Object.entries(result.added)) console.log(` ${locale}: ${dryRun ? `would add ${keys.length}` : `+${keys.length}`}`);
4452
+ const warnings = result.findings.filter((finding) => {
4453
+ if (finding.kind !== "replaced") return true;
4454
+ console.log(` ${formatFinding(finding, cfg.root)}`);
4455
+ return false;
4456
+ });
4457
+ if (reporter) reporter.report("extract", warnings);
4458
+ else for (const finding of warnings) console.warn(` ${formatFinding(finding, cfg.root)}`);
4459
+ if (result.stateProblem) console.warn(` ${result.stateProblem}, so drafts and outdated translations were not updated`);
4121
4460
  }
4122
4461
  await runExtract();
4123
4462
  if (values.watch) {
@@ -4183,7 +4522,8 @@ async function runCli(args = process.argv.slice(2)) {
4183
4522
  }
4184
4523
  if (command === "status") {
4185
4524
  const registry = await extractProject(cfg);
4186
- const state = loadState(cfg);
4525
+ const { state, problem } = readState(cfg);
4526
+ if (problem) console.warn(`[verbaly] ${problem}, so drafts and outdated translations are not counted`);
4187
4527
  const result = status(cfg, loadCatalogs(cfg), registry, state.drafts, state.fingerprints);
4188
4528
  console.log(values.json ? JSON.stringify(result) : formatStatusResult(result));
4189
4529
  return;
@@ -4200,39 +4540,41 @@ async function runCli(args = process.argv.slice(2)) {
4200
4540
  const state = checkState(cfg, values.drafts === true || values.outdated === true);
4201
4541
  const result = check(cfg, catalogs, registry, state.fingerprints);
4202
4542
  const unreviewed = values.drafts ? effectiveDrafts(state.drafts, catalogs) : {};
4203
- const draftKeys = Object.entries(unreviewed);
4204
4543
  const outdated = values.outdated ? result.outdated : [];
4205
- if (reporter === "github") for (const line of githubCheckAnnotations(result, registry, cfg.root)) console.error(line);
4544
+ const gated = { outdatedFails: values.outdated === true };
4545
+ if (reporter === "github") for (const line of githubCheckAnnotations(result, registry, cfg, gated)) console.error(line);
4206
4546
  else {
4207
- const warnings = formatCheckWarnings(result, cfg.root);
4547
+ const warnings = formatCheckWarnings(result, cfg.root, gated);
4208
4548
  if (warnings) console.warn(`[verbaly] warnings (the gate still passes)\n${warnings}`);
4209
4549
  }
4210
- if (result.ok && draftKeys.length === 0 && outdated.length === 0) {
4550
+ const awaiting = [...Object.entries(unreviewed).map(([locale, keys]) => ` [${locale}] ${keys.length} unreviewed: ${keys.join(", ")}`), ...byLocale(outdated).map(([locale, keys]) => ` [${locale}] ${keys.length} outdated: ${keys.join(", ")}`)];
4551
+ if (result.ok && awaiting.length === 0) {
4211
4552
  console.log("[verbaly] all translations complete ✓");
4212
4553
  return;
4213
4554
  }
4214
- if (result.ok) {
4215
- for (const [locale, keys] of draftKeys) console.error(` [${locale}] ${keys.length} unreviewed: ${keys.join(", ")}`);
4216
- for (const [locale, keys] of byLocale(outdated)) console.error(` [${locale}] ${keys.length} outdated: ${keys.join(", ")}`);
4555
+ if (!result.ok) {
4556
+ const brokenCount = result.broken.filter((entry) => entry.severity === "error").length;
4557
+ const report = reporter === "github" ? `[verbaly] check failed: ${result.missing.length} missing, ${result.unknown.length} unknown, ${brokenCount} broken` : `[verbaly] check failed\n${formatCheckResult(result, cfg.root)}`;
4558
+ console.error(`${report}\n${checkNextSteps(result)}`);
4559
+ }
4560
+ if (awaiting.length > 0) {
4561
+ for (const line of awaiting) console.error(line);
4217
4562
  console.error("[verbaly] check failed: translations awaiting review (run verbaly review, then --approve what holds)");
4218
- process.exitCode = 1;
4219
- return;
4220
4563
  }
4221
- const brokenCount = result.broken.filter((entry) => entry.severity === "error").length;
4222
- const report = reporter === "github" ? `[verbaly] check failed: ${result.missing.length} missing, ${result.unknown.length} unknown, ${brokenCount} broken` : `[verbaly] check failed\n${formatCheckResult(result, cfg.root)}`;
4223
- console.error(`${report}\n${checkNextSteps(result)}`);
4224
4564
  process.exitCode = 1;
4225
4565
  return;
4226
4566
  }
4227
4567
  if (command === "translate") {
4228
- const catalogs = loadCatalogs(cfg);
4568
+ if (!values["dry-run"]) loadState(cfg);
4569
+ const registry = await extractProject(cfg);
4570
+ const catalogs = shippedCatalogs(cfg, loadCatalogs(cfg), registry, { newKeys: false });
4229
4571
  const result = await translateCatalogs(cfg, catalogs, await resolveProvider(cfg, values.model), {
4230
4572
  locales: csv(values.locales),
4231
4573
  batchSize: cfg.translate.batchSize,
4232
4574
  concurrency: cfg.translate.concurrency,
4233
4575
  retries: cfg.translate.retries,
4234
4576
  dryRun: values["dry-run"],
4235
- origins: values["dry-run"] ? void 0 : await collectOrigins(cfg),
4577
+ origins: values["dry-run"] ? void 0 : await collectOrigins(cfg, registry),
4236
4578
  onProgress: values["dry-run"] ? void 0 : reportProgress
4237
4579
  });
4238
4580
  if (values["dry-run"]) {
@@ -4244,15 +4586,24 @@ async function runCli(args = process.argv.slice(2)) {
4244
4586
  for (const [locale, keys] of entries) console.log(` ${locale}: ${keys.length} missing: ${keys.join(", ")}`);
4245
4587
  return;
4246
4588
  }
4247
- const drafts = loadDrafts(cfg);
4589
+ const source = catalogs[cfg.sourceLocale] ?? {};
4590
+ const writes = [];
4248
4591
  for (const [locale, keys] of Object.entries(result.translated)) {
4249
- const written = mergeTranslations(cfg, locale, catalogs[locale] ?? {}, keys);
4250
- markDrafts(drafts, locale, written);
4592
+ const catalog = catalogs[locale] ?? {};
4593
+ const written = mergeTranslations(cfg, locale, catalog, keys);
4594
+ writes.push({
4595
+ locale,
4596
+ draft: true,
4597
+ entries: written.map((key) => ({
4598
+ key,
4599
+ text: catalog[key]
4600
+ }))
4601
+ });
4251
4602
  console.log(` ${locale}: +${written.length} translated (draft)`);
4252
4603
  const kept = keys.length - written.length;
4253
4604
  if (kept > 0) console.log(` ${locale}: ${counted(kept, "message")} kept as written while this ran`);
4254
4605
  }
4255
- if (Object.keys(result.translated).length > 0) saveDrafts(cfg, drafts);
4606
+ if (writes.length > 0) recordTranslations(cfg, source, writes);
4256
4607
  for (const [locale, keys] of Object.entries(result.invalid)) console.warn(` ${locale}: ${keys.length} rejected (params/tags not preserved): ${keys.join(", ")}`);
4257
4608
  for (const line of formatTranslateFailures(result.failed)) console.error(line);
4258
4609
  if (result.failed.length > 0) process.exitCode = 1;
@@ -4260,40 +4611,48 @@ async function runCli(args = process.argv.slice(2)) {
4260
4611
  return;
4261
4612
  }
4262
4613
  if (command === "review") {
4614
+ const registry = await extractProject(cfg);
4263
4615
  const catalogs = loadCatalogs(cfg);
4616
+ const shipped = shippedCatalogs(cfg, catalogs, registry);
4264
4617
  const state = loadState(cfg);
4265
- const live = effectiveDrafts(state.drafts, catalogs);
4266
- const targets = values.locale ? { [values.locale]: live[values.locale] ?? [] } : live;
4267
- const entries = Object.entries(targets).filter(([, keys]) => keys.length);
4268
- const outdated = outdatedTranslations(cfg, catalogs, state.fingerprints).filter((entry) => !values.locale || entry.locale === values.locale);
4269
- if (entries.length === 0 && outdated.length === 0) {
4618
+ const only = new Set(positionals.slice(1));
4619
+ const wanted = ({ locale, key }) => (!values.locale || locale === values.locale) && (only.size === 0 || only.has(key));
4620
+ const drafts = Object.entries(effectiveDrafts(state.drafts, catalogs)).flatMap(([locale, keys]) => keys.map((key) => ({
4621
+ locale,
4622
+ key
4623
+ }))).filter(wanted);
4624
+ const outdated = outdatedTranslations(cfg, shipped, state.fingerprints).filter(wanted);
4625
+ if (drafts.length === 0 && outdated.length === 0) {
4270
4626
  console.log("[verbaly] nothing awaiting review ✓");
4271
4627
  return;
4272
4628
  }
4273
4629
  if (values.approve) {
4274
- let count = 0;
4275
- for (const [locale, keys] of entries) {
4630
+ for (const [locale, keys] of byLocale(drafts)) {
4276
4631
  clearDrafts(state.drafts, locale, keys);
4277
- count += keys.length;
4278
4632
  console.log(` ${locale}: ${keys.length} approved`);
4279
4633
  }
4280
- acceptOutdated(cfg, catalogs, state.fingerprints, outdated);
4281
- for (const [locale, keys] of byLocale(outdated)) {
4282
- console.log(` ${locale}: ${keys.length} kept for the new source text`);
4283
- count += keys.length;
4284
- }
4634
+ acceptOutdated(cfg, shipped, state.fingerprints, outdated);
4635
+ for (const [locale, keys] of byLocale(outdated)) console.log(` ${locale}: ${keys.length} kept for the new source text`);
4285
4636
  saveState(cfg, state);
4286
- console.log(`[verbaly] ${counted(count, "translation")} marked reviewed ✓`);
4637
+ const reviewed = new Set([...drafts, ...outdated].map(({ locale, key }) => `${locale}:${key}`));
4638
+ console.log(`[verbaly] ${counted(reviewed.size, "translation")} marked reviewed ✓`);
4287
4639
  return;
4288
4640
  }
4289
- if (entries.length > 0) {
4290
- const total = entries.reduce((sum, [, keys]) => sum + keys.length, 0);
4291
- console.log(`[verbaly] ${counted(total, "machine translation")} awaiting review (--approve to accept)`);
4292
- for (const [locale, keys] of entries) console.log(` ${locale}: ${keys.join(", ")}`);
4641
+ const source = shipped[cfg.sourceLocale] ?? {};
4642
+ const show = (locale, keys) => {
4643
+ console.log(` ${locale}:`);
4644
+ for (const key of keys) {
4645
+ const translated = catalogs[locale]?.[key] ?? "";
4646
+ console.log(` ${key}: "${truncate(source[key] ?? "", 60)}" → "${truncate(translated, 60)}"`);
4647
+ }
4648
+ };
4649
+ if (drafts.length > 0) {
4650
+ console.log(`[verbaly] ${counted(drafts.length, "machine translation")} awaiting review (--approve to accept)`);
4651
+ for (const [locale, keys] of byLocale(drafts)) show(locale, keys);
4293
4652
  }
4294
4653
  if (outdated.length > 0) {
4295
4654
  console.log(`[verbaly] ${counted(outdated.length, "translation")} written for an older source text (update them, or --approve keeps them)`);
4296
- for (const [locale, keys] of byLocale(outdated)) console.log(` ${locale}: ${keys.join(", ")}`);
4655
+ for (const [locale, keys] of byLocale(outdated)) show(locale, keys);
4297
4656
  }
4298
4657
  return;
4299
4658
  }
@@ -4315,12 +4674,13 @@ async function runCli(args = process.argv.slice(2)) {
4315
4674
  process.exitCode = 1;
4316
4675
  return;
4317
4676
  }
4318
- const result = exportCatalogs(cfg, loadCatalogs(cfg), {
4677
+ const registry = await extractProject(cfg);
4678
+ const result = exportCatalogs(cfg, shippedCatalogs(cfg, loadCatalogs(cfg), registry, { newKeys: false }), {
4319
4679
  locales: csv(values.locales),
4320
4680
  format,
4321
4681
  out: values.out,
4322
4682
  missing: values.missing,
4323
- origins: isMobileFormat(format) ? void 0 : await collectOrigins(cfg)
4683
+ origins: isMobileFormat(format) ? void 0 : await collectOrigins(cfg, registry)
4324
4684
  });
4325
4685
  if (result.files.length === 0) {
4326
4686
  console.log("[verbaly] no target locales to export (add locales to your config)");
@@ -4338,7 +4698,9 @@ async function runCli(args = process.argv.slice(2)) {
4338
4698
  process.exitCode = 1;
4339
4699
  return;
4340
4700
  }
4341
- const catalogs = loadCatalogs(cfg);
4701
+ if (!values["dry-run"]) loadState(cfg);
4702
+ const registry = await extractProject(cfg);
4703
+ const catalogs = shippedCatalogs(cfg, loadCatalogs(cfg), registry, { newKeys: false });
4342
4704
  const result = importCatalogs(cfg, catalogs, files, {
4343
4705
  locale: values.locale,
4344
4706
  overwrite: values.overwrite,
@@ -4355,19 +4717,27 @@ async function runCli(args = process.argv.slice(2)) {
4355
4717
  }
4356
4718
  process.exitCode = 1;
4357
4719
  }
4358
- const drafts = loadDrafts(cfg);
4359
- let draftsChanged = false;
4720
+ const writes = [];
4360
4721
  for (const [locale, keys] of Object.entries(result.imported)) {
4361
4722
  if (!values["dry-run"]) {
4362
- writeCatalog(cfg, locale, catalogs[locale] ?? {});
4363
- if (values.draft) markDrafts(drafts, locale, keys);
4364
- else clearDrafts(drafts, locale, keys);
4365
- draftsChanged = true;
4723
+ const catalog = catalogs[locale] ?? {};
4724
+ writeCatalog(cfg, locale, catalog);
4725
+ const seen = result.sources[locale] ?? {};
4726
+ const entries = keys.map((key) => ({
4727
+ key,
4728
+ text: catalog[key],
4729
+ source: seen[key]
4730
+ }));
4731
+ writes.push({
4732
+ locale,
4733
+ entries,
4734
+ draft: values.draft === true
4735
+ });
4366
4736
  }
4367
4737
  const verb = values["dry-run"] ? "would import" : "imported";
4368
4738
  console.log(` ${locale}: +${keys.length} ${verb}${values.draft ? " (draft)" : ""}`);
4369
4739
  }
4370
- if (draftsChanged) saveDrafts(cfg, drafts);
4740
+ if (writes.length > 0) recordTranslations(cfg, catalogs[cfg.sourceLocale] ?? {}, writes);
4371
4741
  for (const [locale, keys] of Object.entries(result.skipped)) console.log(` ${locale}: ${keys.length} already translated, kept (use --overwrite to replace)`);
4372
4742
  for (const [locale, keys] of Object.entries(result.rejected)) console.warn(` ${locale}: ${keys.length} rejected (params/tags not preserved): ${keys.join(", ")}`);
4373
4743
  for (const [locale, keys] of Object.entries(result.unknown)) console.warn(` ${locale}: ${counted(keys.length, "unknown key")} ignored (not in the source catalog): ${keys.join(", ")}`);
@@ -4412,67 +4782,20 @@ function formatCliError(error) {
4412
4782
  const message = error instanceof Error ? error.message : String(error);
4413
4783
  return message.startsWith("[verbaly]") ? message : `[verbaly] ${message}`;
4414
4784
  }
4415
- function reportParseErrors(cfg, registry) {
4416
- for (const { file, message } of registry.parseErrors()) {
4417
- const rel = relative(cfg.root, file).replaceAll("\\", "/");
4418
- console.warn(` ${rel}: could not be parsed (${message}), its messages were not extracted`);
4419
- }
4420
- }
4421
- function reportReplaced(cfg, registry, replaced, dryRun) {
4422
- if (replaced.length === 0) return;
4423
- const messages = registry.messages();
4424
- const locate = createLocator();
4425
- const verb = dryRun ? "would get" : "got";
4426
- for (const key of replaced) {
4427
- const msg = messages.get(key);
4428
- if (!msg) continue;
4429
- const line = locate(msg.file, msg.start);
4430
- const place = `${relative(cfg.root, msg.file).replaceAll("\\", "/")}${line ? `:${line}` : ""}`;
4431
- console.warn(` ${cfg.sourceLocale}: ${key} ${verb} the text written in ${place}, the code owns it: edit it there`);
4432
- }
4433
- }
4434
- function reportMissed(cfg, registry) {
4435
- const locate = createLocator();
4436
- for (const { name, file, start } of registry.missed()) {
4437
- const line = locate(file, start);
4438
- const place = `${relative(cfg.root, file).replaceAll("\\", "/")}${line ? `:${line}` : ""}`;
4439
- console.warn(` ${place}: ${name}\`…\` is never extracted, so it stays in the source language: name it t`);
4440
- }
4441
- }
4442
- function reportPositional(cfg, registry) {
4443
- for (const msg of registry.messages().values()) {
4444
- const nameless = msg.params.filter((param) => /^_\d+$/.test(param.name));
4445
- if (nameless.length === 0) continue;
4446
- const file = relative(cfg.root, msg.file).replaceAll("\\", "/");
4447
- const names = nameless.map((param) => `{${param.name}}`).join(", ");
4448
- console.warn(` ${file}: ${names} in "${msg.message}" reaches the translator without a name, put the value in a named variable first`);
4449
- }
4450
- }
4451
4785
  function checkState(cfg, gating) {
4452
- try {
4453
- return loadState(cfg);
4454
- } catch (error) {
4455
- if (gating) throw error;
4456
- console.warn(`${formatCliError(error)}, so outdated translations are not reported`);
4457
- return {
4458
- drafts: {},
4459
- fingerprints: {}
4460
- };
4461
- }
4786
+ if (gating) return loadState(cfg);
4787
+ const { state, problem } = readState(cfg);
4788
+ if (problem) console.warn(`[verbaly] ${problem}, so outdated translations are not reported`);
4789
+ return state;
4462
4790
  }
4463
4791
  function byLocale(entries) {
4464
4792
  const out = /* @__PURE__ */ new Map();
4465
- for (const { locale, key } of entries) out.set(locale, [...out.get(locale) ?? [], key]);
4466
- return [...out];
4467
- }
4468
- function reportEscapedSyntax(cfg, registry) {
4469
- for (const msg of registry.messages().values()) {
4470
- const slice = escapedSyntax(msg.message);
4471
- if (!slice) continue;
4472
- const file = relative(cfg.root, msg.file).replaceAll("\\", "/");
4473
- console.warn(` ${file}: ${slice} renders as literal text, a tagged template has no params`);
4474
- console.warn(" use t(key, params) for a plural or format block, or pass a ${…} value");
4793
+ for (const { locale, key } of entries) {
4794
+ const keys = out.get(locale);
4795
+ if (keys) keys.push(key);
4796
+ else out.set(locale, [key]);
4475
4797
  }
4798
+ return [...out];
4476
4799
  }
4477
4800
  const COMMON_FLAGS = /* @__PURE__ */ new Set([
4478
4801
  "root",
@@ -4538,6 +4861,6 @@ runCli().catch((error) => {
4538
4861
  process.exitCode = 1;
4539
4862
  });
4540
4863
  //#endregion
4541
- export { isModuleNotFound as n, counted as t };
4864
+ export { counted as n, isModuleNotFound as t };
4542
4865
 
4543
4866
  //# sourceMappingURL=cli.js.map