@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/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { a as loadConfigFile, i as loadConfig, n as findConfigFile, o as resolveConfig, s as targetLocales, t as counted } from "./text-M4XbWU6N.js";
1
+ import { a as loadConfig, c as targetLocales, n as truncate, o as loadConfigFile, r as findConfigFile, s as resolveConfig, t as counted } from "./text-SqXoYAIB.js";
2
2
  import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, rmSync, watch, writeFileSync } from "node:fs";
3
3
  import { dirname, join, relative } from "node:path";
4
4
  import { CATALOG_SCRIPT, LOCALE_STORAGE_KEY, RICH_TAGS, VOID_TAGS, alternateLinks, createVerbaly, flatten, localeDirection, normalizeLink, parse, parseIcu, parseTags, safeAttribute } from "verbaly";
@@ -206,25 +206,28 @@ var MessageRegistry = class {
206
206
  }
207
207
  messages() {
208
208
  const out = /* @__PURE__ */ new Map();
209
- for (const analysis of this.files.values()) for (const msg of analysis.tagged) if (!out.has(msg.key)) out.set(msg.key, msg);
209
+ for (const analysis of this.inOrder()) for (const msg of analysis.tagged) {
210
+ const held = out.get(msg.key);
211
+ if (!held || earlier(msg, held)) out.set(msg.key, msg);
212
+ }
210
213
  return out;
211
214
  }
212
215
  collisions() {
213
- const seen = /* @__PURE__ */ new Map();
214
- for (const analysis of this.files.values()) for (const msg of analysis.tagged) {
215
- const found = seen.get(msg.key);
216
- if (!found) seen.set(msg.key, {
217
- key: msg.key,
218
- kept: msg,
219
- dropped: []
220
- });
221
- else if (msg.message !== found.kept.message && !found.dropped.some((other) => other.message === msg.message)) found.dropped.push(msg);
216
+ const winners = this.messages();
217
+ const dropped = /* @__PURE__ */ new Map();
218
+ for (const analysis of this.inOrder()) for (const msg of analysis.tagged) {
219
+ if (msg.message === winners.get(msg.key).message) continue;
220
+ dropped.set(msg.key, [...dropped.get(msg.key) ?? [], msg]);
222
221
  }
223
- return [...seen.values()].filter((entry) => entry.dropped.length > 0);
222
+ return [...dropped].map(([key, others]) => ({
223
+ key,
224
+ kept: winners.get(key),
225
+ dropped: others.sort((a, b) => earlier(a, b) ? -1 : 1)
226
+ }));
224
227
  }
225
228
  usedKeys(strict = false) {
226
229
  const out = /* @__PURE__ */ new Map();
227
- for (const analysis of this.files.values()) for (const used of analysis.usedKeys) {
230
+ for (const analysis of this.inOrder()) for (const used of analysis.usedKeys) {
228
231
  if (strict && used.loose) continue;
229
232
  const files = out.get(used.key) ?? [];
230
233
  if (!files.includes(used.file)) files.push(used.file);
@@ -233,29 +236,38 @@ var MessageRegistry = class {
233
236
  return out;
234
237
  }
235
238
  strayImports() {
236
- return [...this.files.values()].flatMap((analysis) => analysis.strayImports);
239
+ return this.inOrder().flatMap((analysis) => analysis.strayImports);
237
240
  }
238
241
  missed() {
239
- return [...this.files.values()].flatMap((analysis) => analysis.missed ?? []);
242
+ return this.inOrder().flatMap((analysis) => analysis.missed);
240
243
  }
241
244
  parseErrors() {
242
245
  const out = [];
243
- for (const [file, analysis] of this.files) if (analysis.parseError) out.push({
244
- file,
245
- message: analysis.parseError
246
- });
246
+ for (const file of [...this.files.keys()].sort()) {
247
+ const { parseError } = this.files.get(file);
248
+ if (parseError) out.push({
249
+ file,
250
+ message: parseError
251
+ });
252
+ }
247
253
  return out;
248
254
  }
249
255
  origins() {
250
256
  const out = this.usedKeys();
251
- for (const analysis of this.files.values()) for (const msg of analysis.tagged) {
257
+ for (const analysis of this.inOrder()) for (const msg of analysis.tagged) {
252
258
  const files = out.get(msg.key) ?? [];
253
259
  if (!files.includes(msg.file)) files.push(msg.file);
254
260
  out.set(msg.key, files);
255
261
  }
256
262
  return out;
257
263
  }
264
+ inOrder() {
265
+ return [...this.files.keys()].sort().map((file) => this.files.get(file));
266
+ }
258
267
  };
268
+ function earlier(a, b) {
269
+ return a.file === b.file ? a.start < b.start : a.file < b.file;
270
+ }
259
271
  //#endregion
260
272
  //#region src/key.ts
261
273
  function stableKey(message) {
@@ -277,6 +289,9 @@ const DEFAULT_T_NAMES = ["t"];
277
289
  const JSX_FILE_RE = /\.(?:[cm]?jsx?|tsx)$/;
278
290
  const DEFINE_KEYS = "defineKeys";
279
291
  function analyze(code, file, options = {}) {
292
+ return analyzeScript(code, file, options).analysis;
293
+ }
294
+ function analyzeScript(code, file, options = {}) {
280
295
  const names = new Set(options.tNames ?? DEFAULT_T_NAMES);
281
296
  const ast = parse$1(code, {
282
297
  sourceType: "module",
@@ -286,19 +301,20 @@ function analyze(code, file, options = {}) {
286
301
  const tagged = [];
287
302
  const usedKeys = [];
288
303
  const strayImports = [];
289
- const missed = [];
290
- const renamed = renamedBindings(ast.program, names);
304
+ const bindings = new Bindings(names);
305
+ const candidates = [];
291
306
  walk$1(ast.program, (node) => {
292
- if (node.type === "ImportDeclaration") collectStrayImports(node, file, strayImports);
307
+ if (node.type === "ImportDeclaration") {
308
+ collectStrayImports(node, file, strayImports);
309
+ bindings.addImport(node);
310
+ } else if (node.type === "VariableDeclarator") bindings.addDeclarator(node);
293
311
  else if (node.type === "TaggedTemplateExpression") {
294
312
  const tag = node.tag;
295
313
  const explicit = explicitId(tag, names);
296
314
  if (!explicit && !isTReference(tag, names)) {
297
- const name = renamedTag(tag, renamed);
298
- if (name) missed.push({
299
- name,
300
- file,
301
- start: node.start
315
+ candidates.push({
316
+ kind: "tag",
317
+ node
302
318
  });
303
319
  return;
304
320
  }
@@ -311,6 +327,7 @@ function analyze(code, file, options = {}) {
311
327
  params: message.params,
312
328
  start: node.start,
313
329
  end: node.end,
330
+ line: lineOf(node),
314
331
  tagStart: explicit ? explicit.refStart : tag.start,
315
332
  tagEnd: explicit ? explicit.refEnd : tag.end,
316
333
  file
@@ -323,11 +340,11 @@ function analyze(code, file, options = {}) {
323
340
  return;
324
341
  }
325
342
  if (!isTReference(callee, names)) {
326
- const key = renamed.has(identifierName(callee)) ? staticString(args[0]) : void 0;
327
- if (key !== void 0) usedKeys.push({
328
- key,
329
- file,
330
- loose: true
343
+ const key = callee.type === "Identifier" ? staticString(args[0]) : void 0;
344
+ if (key !== void 0) candidates.push({
345
+ kind: "call",
346
+ name: callee.name,
347
+ key
331
348
  });
332
349
  return;
333
350
  }
@@ -335,41 +352,136 @@ function analyze(code, file, options = {}) {
335
352
  if (key !== void 0) usedKeys.push(usedKey(key, file, args[0]));
336
353
  } else if (node.type === "JSXElement") handleTrans(code, node, file, tagged, usedKeys, names);
337
354
  });
355
+ const renamed = bindings.renamed(options.renamed);
356
+ const missed = [];
357
+ for (const candidate of candidates) {
358
+ if (candidate.kind === "call") {
359
+ if (renamed.has(candidate.name)) usedKeys.push({
360
+ key: candidate.key,
361
+ file,
362
+ loose: true
363
+ });
364
+ continue;
365
+ }
366
+ const { node } = candidate;
367
+ const name = renamedTag(node.tag, renamed);
368
+ if (!name) continue;
369
+ missed.push({
370
+ name,
371
+ file,
372
+ start: node.start,
373
+ line: lineOf(node)
374
+ });
375
+ const key = missedKey(code, node, names);
376
+ if (key !== void 0) usedKeys.push({
377
+ key,
378
+ file,
379
+ loose: true
380
+ });
381
+ }
338
382
  return {
339
- tagged,
340
- usedKeys,
341
- strayImports,
342
- ...missed.length > 0 && { missed }
383
+ analysis: {
384
+ tagged,
385
+ usedKeys,
386
+ strayImports,
387
+ missed
388
+ },
389
+ renamed: [...renamed]
343
390
  };
344
391
  }
345
- function renamedBindings(program, names) {
346
- const out = /* @__PURE__ */ new Set();
347
- const add = (node) => {
348
- const name = identifierName(node);
349
- if (name && !names.has(name)) out.add(name);
350
- };
351
- walk$1(program, (node) => {
352
- if (node.type === "ImportDeclaration") {
353
- if (node.source.value !== "virtual:verbaly") return;
354
- for (const spec of node.specifiers) if (spec.type === "ImportSpecifier" && identifierName(spec.imported) === "t") add(spec.local);
355
- } else if (node.type === "VariableDeclarator") {
356
- const id = node.id;
357
- const init = node.init;
358
- if (id.type === "Identifier" && init && handsOutT(init)) add(id);
359
- if (id.type !== "ObjectPattern") return;
360
- for (const property of id.properties) {
361
- if (property.type !== "ObjectProperty" || property.computed) continue;
362
- if (identifierName(property.key) === "t") add(property.value);
363
- }
392
+ function lineOf(node) {
393
+ return node.loc?.start.line ?? 1;
394
+ }
395
+ const VERBALY_SOURCE = /^(?:verbaly|virtual:verbaly|@verbaly\/[\w-]+(?:\/[\w-]+)*)$/;
396
+ const T_FACTORIES = /* @__PURE__ */ new Map([["useT", "call"], ["getT", "await"]]);
397
+ const INSTANCE_FACTORIES = /* @__PURE__ */ new Set(["useVerbaly", "getVerbaly"]);
398
+ var Bindings = class {
399
+ names;
400
+ imports = /* @__PURE__ */ new Map();
401
+ direct = /* @__PURE__ */ new Set();
402
+ declared = [];
403
+ destructured = [];
404
+ constructor(names) {
405
+ this.names = names;
406
+ }
407
+ addImport(node) {
408
+ const source = node.source.value;
409
+ if (typeof source !== "string") return;
410
+ for (const spec of node.specifiers) {
411
+ const local = identifierName(spec.local);
412
+ if (!local) continue;
413
+ const imported = spec.type === "ImportSpecifier" ? importedName(spec.imported) : spec.type;
414
+ this.imports.set(local, {
415
+ source,
416
+ imported
417
+ });
418
+ if (source === "virtual:verbaly" && imported === "t") this.direct.add(local);
364
419
  }
365
- });
366
- return out;
367
- }
368
- function handsOutT(init) {
369
- const call = init.type === "AwaitExpression" ? init.argument : init;
370
- if (call.type !== "CallExpression") return false;
371
- const callee = identifierName(call.callee);
372
- return init.type === "AwaitExpression" ? callee === "getT" : callee === "useT";
420
+ }
421
+ addDeclarator(node) {
422
+ const id = node.id;
423
+ const init = node.init;
424
+ if (!init) return;
425
+ if (id.type === "Identifier") {
426
+ this.declared.push({
427
+ name: id.name,
428
+ init
429
+ });
430
+ return;
431
+ }
432
+ if (id.type !== "ObjectPattern") return;
433
+ for (const property of id.properties) {
434
+ if (property.type !== "ObjectProperty" || property.computed) continue;
435
+ if (identifierName(property.key) !== "t") continue;
436
+ const value = property.value;
437
+ const name = identifierName(value.type === "AssignmentPattern" ? value.left : value);
438
+ if (name) this.destructured.push({
439
+ name,
440
+ init
441
+ });
442
+ }
443
+ }
444
+ renamed(seed = []) {
445
+ const out = new Set(seed);
446
+ const add = (name) => {
447
+ if (this.names.has(name)) return;
448
+ out.add(name);
449
+ if (this.names.has("$t")) out.add(`$${name}`);
450
+ };
451
+ for (const name of this.direct) add(name);
452
+ for (const { name, init } of this.declared) if (this.handsOutT(init)) add(name);
453
+ for (const { name, init } of this.destructured) if (this.carriesT(init)) add(name);
454
+ return out;
455
+ }
456
+ handsOutT(init) {
457
+ const awaited = init.type === "AwaitExpression";
458
+ const call = awaited ? init.argument : init;
459
+ if (call.type !== "CallExpression") return false;
460
+ const origin = this.origin(identifierName(call.callee));
461
+ if (origin.verbaly === false) return false;
462
+ const how = T_FACTORIES.get(origin.imported);
463
+ return how !== void 0 && how === "await" === awaited;
464
+ }
465
+ carriesT(init) {
466
+ const inner = init.type === "AwaitExpression" ? init.argument : init;
467
+ const name = identifierName(inner.type === "CallExpression" ? inner.callee : inner);
468
+ if (!name) return false;
469
+ return this.origin(name).verbaly ?? INSTANCE_FACTORIES.has(name);
470
+ }
471
+ origin(local) {
472
+ const found = this.imports.get(local);
473
+ if (!found) return {
474
+ verbaly: void 0,
475
+ imported: local
476
+ };
477
+ return {
478
+ verbaly: VERBALY_SOURCE.test(found.source),
479
+ imported: found.imported
480
+ };
481
+ }
482
+ };
483
+ function importedName(node) {
484
+ return node.type === "StringLiteral" ? node.value : identifierName(node);
373
485
  }
374
486
  function identifierName(node) {
375
487
  return node?.type === "Identifier" ? node.name : "";
@@ -385,6 +497,16 @@ function renamedTag(tag, renamed) {
385
497
  const object = identifierName(callee.object);
386
498
  return renamed.has(object) ? object : void 0;
387
499
  }
500
+ function missedKey(code, node, names) {
501
+ const tag = node.tag;
502
+ if (tag.type === "CallExpression") {
503
+ const args = tag.arguments;
504
+ const first = args[0];
505
+ return args.length === 1 && first?.type === "StringLiteral" ? first.value : void 0;
506
+ }
507
+ const message = buildMessage(code, node.quasi, names);
508
+ return message ? stableKey(message.text) : void 0;
509
+ }
388
510
  function collectDeclaredKeys(node, file, out) {
389
511
  if (node?.type !== "ObjectExpression") return;
390
512
  for (const property of node.properties) {
@@ -441,6 +563,7 @@ function handleTrans(code, node, file, tagged, usedKeys, names) {
441
563
  params: built.params,
442
564
  start: node.start,
443
565
  end: node.end,
566
+ line: lineOf(node),
444
567
  tagStart: nameNode.start,
445
568
  tagEnd: nameNode.end,
446
569
  file,
@@ -646,6 +769,7 @@ function analyzeFile(code, file) {
646
769
  tagged: [],
647
770
  usedKeys: [],
648
771
  strayImports: [],
772
+ missed: [],
649
773
  parseError: parseErrorMessage(error)
650
774
  };
651
775
  }
@@ -654,55 +778,63 @@ const SCRIPT_RE = /(<script\b[^>]*>)([\s\S]*?)(<\/script\s*>)/gi;
654
778
  const STYLE_RE = /<style\b[^>]*>[\s\S]*?<\/style\s*>/gi;
655
779
  const COMMENT_RE = /<!--[\s\S]*?-->/g;
656
780
  const FRONTMATTER_RE = /^(\uFEFF?\s*---\r?\n)([\s\S]*?)\r?\n---(?=\r?\n|$)/;
657
- const CANDIDATE_SVELTE = /(?<![\w$])\$?t(?=[`(]|\.id\()/g;
658
- const CANDIDATE_VUE = /(?<![\w$])t(?=[`(]|\.id\()/g;
659
781
  const MUSTACHE_RE = /\{\{[\s\S]*?\}\}/g;
660
782
  const DIRECTIVE_RE = /\s(?:v-[\w-]+(?::[^\s=>/]+)?|[:@][^\s=>/]+)\s*=\s*("[^"]*"|'[^']*')/g;
661
783
  function analyzeSfc(code, file) {
662
784
  const svelte = file.endsWith(".svelte");
663
- const options = svelte ? { tNames: ["t", "$t"] } : void 0;
785
+ const tNames = svelte ? ["t", "$t"] : ["t"];
664
786
  const tagged = [];
665
787
  const usedKeys = [];
666
788
  const strayImports = [];
789
+ const missed = [];
790
+ const renamed = /* @__PURE__ */ new Set();
791
+ const lineAt = lineCounter(code);
667
792
  let parseError;
668
- const block = (segment, offset) => {
793
+ const block = (content, offset) => {
794
+ const segment = analyzeSegment(content, file, { tNames });
669
795
  parseError ??= segment.error;
796
+ for (const name of segment.renamed) renamed.add(name);
670
797
  merge(segment.analysis, offset, false);
671
798
  };
672
799
  const frontmatter = file.endsWith(".astro") ? FRONTMATTER_RE.exec(code) : null;
673
- if (frontmatter?.[2]) block(analyzeSegment(frontmatter[2], file, options), frontmatter[1].length);
800
+ if (frontmatter?.[2]) block(frontmatter[2], frontmatter[1].length);
674
801
  for (const match of code.matchAll(SCRIPT_RE)) {
675
802
  const content = match[2];
676
- if (!content) continue;
677
- block(analyzeSegment(content, file, options), match.index + match[1].length);
803
+ if (content) block(content, match.index + match[1].length);
678
804
  }
679
805
  const markup = blank(blank(blank(frontmatter ? " ".repeat(frontmatter[0].length) + code.slice(frontmatter[0].length) : code, SCRIPT_RE), STYLE_RE), COMMENT_RE);
680
- const candidates = svelte ? CANDIDATE_SVELTE : CANDIDATE_VUE;
806
+ const markupOptions = {
807
+ tNames,
808
+ renamed: [...renamed]
809
+ };
681
810
  const ranges = file.endsWith(".vue") ? vueExpressionRanges(markup) : braceRanges(markup);
682
811
  let range = 0;
683
812
  let consumedTo = 0;
684
- for (const match of markup.matchAll(candidates)) {
813
+ for (const match of markup.matchAll(candidatePattern(svelte, renamed))) {
685
814
  const start = match.index;
686
815
  if (start < consumedTo) continue;
687
816
  while (range < ranges.length && ranges[range][1] <= start) range += 1;
688
817
  if (range >= ranges.length || start < ranges[range][0]) continue;
689
- const end = expressionExtent(markup, start);
818
+ const end = expressionExtent(markup, start, match[0].length);
690
819
  if (end === void 0) continue;
691
- merge(analyzeSegment(code.slice(start, end), file, options).analysis, start, true);
820
+ merge(analyzeSegment(code.slice(start, end), file, markupOptions).analysis, start, true);
692
821
  consumedTo = end;
693
822
  }
694
823
  return {
695
824
  tagged,
696
825
  usedKeys,
697
826
  strayImports,
827
+ missed,
698
828
  ...parseError && { parseError }
699
829
  };
700
830
  function merge(analysis, offset, markupSegment) {
701
831
  if (!analysis) return;
832
+ const lines = lineAt(offset) - 1;
702
833
  for (const msg of analysis.tagged) tagged.push({
703
834
  ...msg,
704
835
  start: msg.start + offset,
705
836
  end: msg.end + offset,
837
+ line: msg.line + lines,
706
838
  tagStart: msg.tagStart + offset,
707
839
  tagEnd: msg.tagEnd + offset,
708
840
  params: msg.params.map((p) => ({
@@ -712,15 +844,41 @@ function analyzeSfc(code, file) {
712
844
  })),
713
845
  ...markupSegment && { singleQuote: true }
714
846
  });
847
+ for (const call of analysis.missed) missed.push({
848
+ ...call,
849
+ start: call.start + offset,
850
+ line: call.line + lines
851
+ });
715
852
  usedKeys.push(...analysis.usedKeys);
716
853
  strayImports.push(...analysis.strayImports);
717
854
  }
718
855
  }
856
+ function candidatePattern(svelte, renamed) {
857
+ const names = [.../* @__PURE__ */ new Set(["t", ...[...renamed].map((name) => name.replace(/^\$/, ""))])].map((name) => name.replace(/[$]/g, "\\$")).join("|");
858
+ return new RegExp(`(?<![\\w$])${svelte ? "\\$?" : ""}(?:${names})(?=[\`(]|\\.id\\()`, "g");
859
+ }
860
+ function lineCounter(code) {
861
+ const breaks = [];
862
+ for (let i = code.indexOf("\n"); i !== -1; i = code.indexOf("\n", i + 1)) breaks.push(i);
863
+ return (offset) => {
864
+ let low = 0;
865
+ let high = breaks.length;
866
+ while (low < high) {
867
+ const mid = low + high >> 1;
868
+ if (breaks[mid] < offset) low = mid + 1;
869
+ else high = mid;
870
+ }
871
+ return low + 1;
872
+ };
873
+ }
719
874
  function analyzeSegment(code, file, options) {
720
875
  try {
721
- return { analysis: analyze(code, file, options) };
876
+ return analyzeScript(code, file, options);
722
877
  } catch (error) {
723
- return { error: parseErrorMessage(error) };
878
+ return {
879
+ renamed: [],
880
+ error: parseErrorMessage(error)
881
+ };
724
882
  }
725
883
  }
726
884
  function blank(source, re) {
@@ -751,10 +909,8 @@ function vueExpressionRanges(markup) {
751
909
  }
752
910
  return ranges.sort((a, b) => a[0] - b[0]);
753
911
  }
754
- function expressionExtent(code, start) {
755
- let i = start;
756
- if (code[i] === "$") i += 1;
757
- i += 1;
912
+ function expressionExtent(code, start, nameLength) {
913
+ const i = start + nameLength;
758
914
  if (code.startsWith(".id(", i)) {
759
915
  const close = balancedEnd(code, i + 3);
760
916
  if (close === void 0 || code[close] !== "`") return void 0;
@@ -801,7 +957,7 @@ async function extractProject(cfg) {
801
957
  absolute: true
802
958
  });
803
959
  const registry = new MessageRegistry();
804
- for (const file of files) registry.update(file, analyzeFile(readFileSync(file, "utf8"), file));
960
+ for (const file of files.sort()) registry.update(file, analyzeFile(readFileSync(file, "utf8"), file));
805
961
  return registry;
806
962
  }
807
963
  async function collectOrigins(cfg, reuse) {
@@ -816,11 +972,13 @@ function syncCatalogs(cfg, catalogs, registry) {
816
972
  const source = catalogs[cfg.sourceLocale] ??= emptyCatalog();
817
973
  for (const [key, msg] of registry.messages()) {
818
974
  const before = own(source, key);
819
- if (before !== msg.message) {
820
- if (before) replaced.push(key);
821
- source[key] = msg.message;
822
- (added[cfg.sourceLocale] ??= []).push(key);
823
- }
975
+ if (before === msg.message) continue;
976
+ source[key] = msg.message;
977
+ if (before) replaced.push({
978
+ key,
979
+ before
980
+ });
981
+ else (added[cfg.sourceLocale] ??= []).push(key);
824
982
  }
825
983
  const needed = Object.keys(source);
826
984
  for (const locale of cfg.locales) {
@@ -836,6 +994,14 @@ function syncCatalogs(cfg, catalogs, registry) {
836
994
  replaced
837
995
  };
838
996
  }
997
+ function shippedCatalogs(cfg, catalogs, registry, options = {}) {
998
+ const source = Object.assign(emptyCatalog(), flatten(catalogs[cfg.sourceLocale] ?? {}));
999
+ for (const [key, msg] of registry.messages()) if (options.newKeys !== false || own(source, key) !== void 0) source[key] = msg.message;
1000
+ return {
1001
+ ...catalogs,
1002
+ [cfg.sourceLocale]: source
1003
+ };
1004
+ }
839
1005
  function pruneCatalogs(cfg, catalogs, registry) {
840
1006
  const removed = {};
841
1007
  if (registry.parseErrors().length > 0) return removed;
@@ -1246,6 +1412,401 @@ function writeDts(cfg, catalog, file) {
1246
1412
  writeFileSync(file, content);
1247
1413
  }
1248
1414
  //#endregion
1415
+ //#region src/findings.ts
1416
+ function siteOf(msg) {
1417
+ return {
1418
+ file: msg.file,
1419
+ line: msg.line,
1420
+ message: msg.message
1421
+ };
1422
+ }
1423
+ function collisionEntries(registry) {
1424
+ return registry.collisions().map(({ key, kept, dropped }) => ({
1425
+ key,
1426
+ sites: [kept, ...dropped].map(siteOf)
1427
+ }));
1428
+ }
1429
+ function scanFindings(cfg, registry, replaced = []) {
1430
+ const messages = registry.messages();
1431
+ const out = [];
1432
+ for (const { key, before } of replaced) {
1433
+ const msg = messages.get(key);
1434
+ if (msg) out.push({
1435
+ kind: "replaced",
1436
+ locale: cfg.sourceLocale,
1437
+ key,
1438
+ before,
1439
+ site: siteOf(msg)
1440
+ });
1441
+ }
1442
+ for (const entry of collisionEntries(registry)) out.push({
1443
+ kind: "collision",
1444
+ ...entry
1445
+ });
1446
+ for (const { name, file, line } of registry.missed()) out.push({
1447
+ kind: "renamed",
1448
+ name,
1449
+ file,
1450
+ line
1451
+ });
1452
+ for (const msg of messages.values()) {
1453
+ const params = msg.params.map((param) => param.name).filter((name) => /^_\d+$/.test(name));
1454
+ if (params.length > 0) out.push({
1455
+ kind: "positional",
1456
+ params,
1457
+ site: siteOf(msg)
1458
+ });
1459
+ const slice = escapedSyntax(msg.message);
1460
+ if (slice) out.push({
1461
+ kind: "escaped",
1462
+ slice,
1463
+ site: siteOf(msg)
1464
+ });
1465
+ }
1466
+ for (const { file, message } of registry.parseErrors()) out.push({
1467
+ kind: "unparsed",
1468
+ file,
1469
+ message
1470
+ });
1471
+ return out;
1472
+ }
1473
+ function sourcePlace(at, root) {
1474
+ const file = root ? relative(root, at.file).replaceAll("\\", "/") : at.file;
1475
+ return at.line ? `${file}:${at.line}` : file;
1476
+ }
1477
+ function quoted(at, root) {
1478
+ return `"${truncate(at.message, 40)}" (${sourcePlace(at, root)})`;
1479
+ }
1480
+ function formatCollision({ key, sites }, root) {
1481
+ const [kept, ...others] = sites;
1482
+ const texts = new Set(sites.map((at) => at.message)).size;
1483
+ 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`;
1484
+ }
1485
+ function formatFinding(finding, root) {
1486
+ switch (finding.kind) {
1487
+ case "collision": return formatCollision(finding, root);
1488
+ case "replaced": {
1489
+ const place = sourcePlace(finding.site, root);
1490
+ 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)}"`;
1491
+ }
1492
+ case "renamed": return `${sourcePlace(finding, root)}: ${finding.name}\`…\` is never extracted, so it stays in the source language: name it t`;
1493
+ case "positional": {
1494
+ const names = finding.params.map((name) => `{${name}}`).join(", ");
1495
+ 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`;
1496
+ }
1497
+ 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)`;
1498
+ case "unparsed": return `${sourcePlace(finding, root)}: could not be parsed (${finding.message}), its messages were not extracted`;
1499
+ case "outdated": return `[${finding.locale}] ${finding.key}: translated from an older source text, update it or keep it with \`npx verbaly review --approve\``;
1500
+ }
1501
+ }
1502
+ function findingId(finding) {
1503
+ switch (finding.kind) {
1504
+ case "collision":
1505
+ case "replaced": return `${finding.kind}:${finding.key}`;
1506
+ case "outdated": return `outdated:${finding.locale}:${finding.key}`;
1507
+ case "renamed": return `renamed:${finding.file}:${finding.name}`;
1508
+ case "positional": return `positional:${finding.site.file}:${finding.params.join(",")}`;
1509
+ case "escaped": return `escaped:${finding.site.file}:${finding.slice}`;
1510
+ case "unparsed": return `unparsed:${finding.file}`;
1511
+ }
1512
+ }
1513
+ function createDevReporter(root, print = (line) => console.warn(`[verbaly] ${line}`), cap = 5) {
1514
+ const shown = /* @__PURE__ */ new Map();
1515
+ return { report(channel, findings) {
1516
+ const before = shown.get(channel) ?? /* @__PURE__ */ new Set();
1517
+ const now = /* @__PURE__ */ new Set();
1518
+ const fresh = [];
1519
+ for (const finding of findings) {
1520
+ const id = findingId(finding);
1521
+ if (now.has(id)) continue;
1522
+ now.add(id);
1523
+ if (!before.has(id)) fresh.push(finding);
1524
+ }
1525
+ shown.set(channel, now);
1526
+ for (const finding of fresh.slice(0, cap)) print(formatFinding(finding, root));
1527
+ if (fresh.length > cap) print(`and ${fresh.length - cap} more: \`npx verbaly doctor\` names them`);
1528
+ } };
1529
+ }
1530
+ //#endregion
1531
+ //#region src/state.ts
1532
+ const STATE_FILE = ".verbaly-state.json";
1533
+ const LEGACY_DRAFTS_FILE = ".verbaly-drafts.json";
1534
+ function statePath(cfg, file = STATE_FILE) {
1535
+ return join(cfg.dir, file);
1536
+ }
1537
+ function loadState(cfg) {
1538
+ const current = readJson(statePath(cfg));
1539
+ if (current !== void 0 && !isObject(current)) throw corrupt(statePath(cfg));
1540
+ const legacy = readJson(statePath(cfg, LEGACY_DRAFTS_FILE));
1541
+ if (legacy !== void 0 && !isObject(legacy)) throw corrupt(statePath(cfg, LEGACY_DRAFTS_FILE));
1542
+ const state = isObject(current) ? {
1543
+ drafts: readDrafts(current.drafts),
1544
+ fingerprints: readFingerprints(current.fingerprints)
1545
+ } : {
1546
+ drafts: {},
1547
+ fingerprints: {}
1548
+ };
1549
+ if (legacy !== void 0) for (const [locale, keys] of Object.entries(readDrafts(legacy))) markDrafts(state.drafts, locale, keys);
1550
+ return state;
1551
+ }
1552
+ function readState(cfg) {
1553
+ try {
1554
+ return { state: loadState(cfg) };
1555
+ } catch (error) {
1556
+ return {
1557
+ state: {
1558
+ drafts: {},
1559
+ fingerprints: {}
1560
+ },
1561
+ problem: error.message.replace(/^\[verbaly\] /, "")
1562
+ };
1563
+ }
1564
+ }
1565
+ function saveState(cfg, state) {
1566
+ const serialized = serializeState(state);
1567
+ const path = statePath(cfg);
1568
+ const legacy = statePath(cfg, LEGACY_DRAFTS_FILE);
1569
+ if (serialized === void 0) {
1570
+ rmSync(path, { force: true });
1571
+ rmSync(legacy, { force: true });
1572
+ return;
1573
+ }
1574
+ let existing;
1575
+ try {
1576
+ existing = readFileSync(path, "utf8");
1577
+ } catch {
1578
+ mkdirSync(cfg.dir, { recursive: true });
1579
+ }
1580
+ if (existing !== serialized) writeFileSync(path, serialized);
1581
+ if (existsSync(legacy)) rmSync(legacy);
1582
+ }
1583
+ function updateState(cfg, catalogs) {
1584
+ const next = refreshState(cfg, catalogs, loadState(cfg));
1585
+ saveState(cfg, next);
1586
+ return next;
1587
+ }
1588
+ function refreshState(cfg, catalogs, previous) {
1589
+ const flat = flatCatalogs(catalogs);
1590
+ const source = flat[cfg.sourceLocale] ?? {};
1591
+ const shown = new Set(targetLocales(cfg).filter((locale) => Object.hasOwn(flat, locale) && existsSync(catalogPath(cfg, locale))));
1592
+ const drafts = {};
1593
+ for (const [locale, keys] of Object.entries(previous.drafts)) {
1594
+ if (!shown.has(locale)) {
1595
+ drafts[locale] = keys;
1596
+ continue;
1597
+ }
1598
+ const live = keys.filter((key) => own(flat[locale], key));
1599
+ if (live.length) drafts[locale] = live;
1600
+ }
1601
+ const fingerprints = {};
1602
+ for (const [locale, stamps] of Object.entries(previous.fingerprints)) if (!shown.has(locale)) fingerprints[locale] = stamps;
1603
+ for (const locale of shown) {
1604
+ const stamps = refreshStamps(source, flat[locale], previous.fingerprints[locale] ?? {});
1605
+ if (Object.keys(stamps).length) fingerprints[locale] = stamps;
1606
+ }
1607
+ return {
1608
+ drafts,
1609
+ fingerprints
1610
+ };
1611
+ }
1612
+ function refreshStamps(source, catalog, before) {
1613
+ const after = emptyCatalog();
1614
+ for (const key of /* @__PURE__ */ new Set([...Object.keys(before), ...Object.keys(source)])) {
1615
+ const translated = own(catalog, key);
1616
+ if (!translated) continue;
1617
+ const was = own(before, key);
1618
+ if (was !== void 0 && translationOf(was) === fingerprint(translated)) {
1619
+ after[key] = was;
1620
+ continue;
1621
+ }
1622
+ const text = own(source, key);
1623
+ if (text && tracked(key, text)) after[key] = stamp(text, translated);
1624
+ else if (was !== void 0) after[key] = was;
1625
+ }
1626
+ return after;
1627
+ }
1628
+ function recordTranslations(cfg, source, writes) {
1629
+ const state = loadState(cfg);
1630
+ for (const { locale, entries, draft } of writes) {
1631
+ if (entries.length === 0) continue;
1632
+ const stamps = state.fingerprints[locale] ??= emptyCatalog();
1633
+ for (const entry of entries) {
1634
+ const from = entry.source || own(source, entry.key);
1635
+ if (from && entry.text && tracked(entry.key, from)) stamps[entry.key] = stamp(from, entry.text);
1636
+ }
1637
+ const keys = entries.map((entry) => entry.key);
1638
+ if (draft === true) markDrafts(state.drafts, locale, keys);
1639
+ else if (draft === false) clearDrafts(state.drafts, locale, keys);
1640
+ }
1641
+ saveState(cfg, state);
1642
+ return state;
1643
+ }
1644
+ function effectiveDrafts(drafts, catalogs) {
1645
+ const out = {};
1646
+ for (const [locale, keys] of Object.entries(drafts)) {
1647
+ const catalog = catalogs[locale] ?? {};
1648
+ const live = keys.filter((key) => own(catalog, key));
1649
+ if (live.length) out[locale] = live;
1650
+ }
1651
+ return out;
1652
+ }
1653
+ function markDrafts(drafts, locale, keys) {
1654
+ if (!keys.length) return;
1655
+ drafts[locale] = [.../* @__PURE__ */ new Set([...drafts[locale] ?? [], ...keys])];
1656
+ }
1657
+ function clearDrafts(drafts, locale, keys) {
1658
+ if (!drafts[locale]) return;
1659
+ if (!keys) {
1660
+ delete drafts[locale];
1661
+ return;
1662
+ }
1663
+ const drop = new Set(keys);
1664
+ drafts[locale] = drafts[locale].filter((key) => !drop.has(key));
1665
+ if (!drafts[locale].length) delete drafts[locale];
1666
+ }
1667
+ function fingerprint(text) {
1668
+ return stableKey(text);
1669
+ }
1670
+ function tracked(key, text) {
1671
+ return stableKey(text) !== key;
1672
+ }
1673
+ function stamp(source, translated) {
1674
+ return `${fingerprint(source)}.${fingerprint(translated)}`;
1675
+ }
1676
+ function outdatedTranslations(cfg, catalogs, fingerprints) {
1677
+ const source = catalogs[cfg.sourceLocale] ?? {};
1678
+ const out = [];
1679
+ for (const locale of targetLocales(cfg)) {
1680
+ const catalog = catalogs[locale] ?? {};
1681
+ for (const [key, was] of Object.entries(fingerprints[locale] ?? {})) {
1682
+ const text = own(source, key);
1683
+ const translated = own(catalog, key);
1684
+ if (!text || !translated) continue;
1685
+ if (translationOf(was) !== fingerprint(translated)) continue;
1686
+ if (sourceOf(was) !== fingerprint(text)) out.push({
1687
+ locale,
1688
+ key
1689
+ });
1690
+ }
1691
+ }
1692
+ return out.sort((a, b) => a.locale.localeCompare(b.locale) || a.key.localeCompare(b.key));
1693
+ }
1694
+ function sourceOf(stamped) {
1695
+ return stamped.slice(0, stamped.indexOf("."));
1696
+ }
1697
+ function translationOf(stamped) {
1698
+ return stamped.slice(stamped.indexOf(".") + 1);
1699
+ }
1700
+ function flatCatalogs(catalogs) {
1701
+ const out = {};
1702
+ for (const [locale, catalog] of Object.entries(catalogs)) out[locale] = flatten(catalog);
1703
+ return out;
1704
+ }
1705
+ function serializeState(state) {
1706
+ const drafts = {};
1707
+ for (const locale of Object.keys(state.drafts).sort()) {
1708
+ const keys = [...new Set(state.drafts[locale])].sort();
1709
+ if (keys.length) drafts[locale] = keys;
1710
+ }
1711
+ const fingerprints = {};
1712
+ for (const locale of Object.keys(state.fingerprints).sort()) {
1713
+ const entries = state.fingerprints[locale] ?? {};
1714
+ const keys = Object.keys(entries).sort();
1715
+ if (!keys.length) continue;
1716
+ fingerprints[locale] = Object.fromEntries(keys.map((key) => [key, entries[key]]));
1717
+ }
1718
+ const out = {};
1719
+ if (Object.keys(drafts).length) out.drafts = drafts;
1720
+ if (Object.keys(fingerprints).length) out.fingerprints = fingerprints;
1721
+ if (!out.drafts && !out.fingerprints) return void 0;
1722
+ return JSON.stringify(out, null, 2) + "\n";
1723
+ }
1724
+ function readJson(path) {
1725
+ let content;
1726
+ try {
1727
+ content = readFileSync(path, "utf8");
1728
+ } catch {
1729
+ return;
1730
+ }
1731
+ try {
1732
+ return JSON.parse(content.charCodeAt(0) === 65279 ? content.slice(1) : content);
1733
+ } catch (error) {
1734
+ throw corrupt(path, error);
1735
+ }
1736
+ }
1737
+ function corrupt(path, cause) {
1738
+ return new Error(`[verbaly] ${path} is not valid JSON: restore it from git or fix it (deleting it approves every draft)`, { cause });
1739
+ }
1740
+ function isObject(value) {
1741
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1742
+ }
1743
+ function readDrafts(value) {
1744
+ const out = {};
1745
+ if (!isObject(value)) return out;
1746
+ for (const [locale, keys] of Object.entries(value)) if (Array.isArray(keys)) out[locale] = keys.filter((key) => typeof key === "string");
1747
+ return out;
1748
+ }
1749
+ function readFingerprints(value) {
1750
+ const out = {};
1751
+ if (!isObject(value)) return out;
1752
+ for (const [locale, entries] of Object.entries(value)) {
1753
+ if (!isObject(entries)) continue;
1754
+ const kept = emptyCatalog();
1755
+ for (const [key, stamped] of Object.entries(entries)) if (typeof stamped === "string" && stamped.includes(".")) kept[key] = stamped;
1756
+ out[locale] = kept;
1757
+ }
1758
+ return out;
1759
+ }
1760
+ //#endregion
1761
+ //#region src/project.ts
1762
+ async function syncProject(cfg, options = {}) {
1763
+ const registry = options.registry ?? await extractProject(cfg);
1764
+ const catalogs = options.catalogs ?? loadCatalogs(cfg);
1765
+ if (options.confirm) confirmFromDisk(cfg, catalogs, registry);
1766
+ const pruneBlocked = options.prune === true && registry.parseErrors().length > 0;
1767
+ const pruned = options.prune ? pruneCatalogs(cfg, catalogs, registry) : {};
1768
+ const { added, replaced } = syncCatalogs(cfg, catalogs, registry);
1769
+ const result = {
1770
+ registry,
1771
+ catalogs,
1772
+ added,
1773
+ replaced,
1774
+ pruned,
1775
+ pruneBlocked,
1776
+ findings: scanFindings(cfg, registry, replaced),
1777
+ written: {}
1778
+ };
1779
+ if (options.dryRun) return result;
1780
+ const changed = /* @__PURE__ */ new Set([...Object.keys(added), ...Object.keys(pruned)]);
1781
+ if (replaced.length > 0) changed.add(cfg.sourceLocale);
1782
+ for (const locale of cfg.locales) {
1783
+ if (options.write === "changed" && !changed.has(locale)) continue;
1784
+ result.written[locale] = writeCatalog(cfg, locale, catalogs[locale] ?? {});
1785
+ }
1786
+ writeDts(cfg, catalogs[cfg.sourceLocale] ?? {});
1787
+ try {
1788
+ result.state = updateState(cfg, catalogs);
1789
+ } catch (error) {
1790
+ result.stateProblem = error.message.replace(/^\[verbaly\] /, "");
1791
+ }
1792
+ return result;
1793
+ }
1794
+ function confirmFromDisk(cfg, catalogs, registry) {
1795
+ const source = catalogs[cfg.sourceLocale] ?? {};
1796
+ const stale = /* @__PURE__ */ new Set();
1797
+ for (const [key, msg] of registry.messages()) if (own(source, key) !== msg.message) stale.add(msg.file);
1798
+ for (const file of stale) {
1799
+ let code;
1800
+ try {
1801
+ code = readFileSync(file, "utf8");
1802
+ } catch {
1803
+ registry.remove(file);
1804
+ continue;
1805
+ }
1806
+ registry.update(file, analyzeFile(code, file));
1807
+ }
1808
+ }
1809
+ //#endregion
1249
1810
  //#region src/tag.ts
1250
1811
  function isLocaleTag(tag) {
1251
1812
  try {
@@ -1418,194 +1979,6 @@ async function init(input = {}) {
1418
1979
  };
1419
1980
  }
1420
1981
  //#endregion
1421
- //#region src/location.ts
1422
- function lineAt(content, offset) {
1423
- let line = 1;
1424
- const end = Math.min(offset, content.length);
1425
- for (let i = 0; i < end; i++) if (content[i] === "\n") line += 1;
1426
- return line;
1427
- }
1428
- function createLocator() {
1429
- const contents = /* @__PURE__ */ new Map();
1430
- return (file, offset) => {
1431
- if (!contents.has(file)) try {
1432
- contents.set(file, readFileSync(file, "utf8"));
1433
- } catch {
1434
- contents.set(file, void 0);
1435
- }
1436
- const content = contents.get(file);
1437
- return content === void 0 ? void 0 : lineAt(content, offset);
1438
- };
1439
- }
1440
- //#endregion
1441
- //#region src/state.ts
1442
- const STATE_FILE = ".verbaly-state.json";
1443
- const LEGACY_DRAFTS_FILE = ".verbaly-drafts.json";
1444
- function statePath(cfg, file = STATE_FILE) {
1445
- return join(cfg.dir, file);
1446
- }
1447
- function loadState(cfg) {
1448
- const current = readJson(statePath(cfg));
1449
- if (current !== void 0) {
1450
- if (!isObject(current)) throw corrupt(statePath(cfg));
1451
- return {
1452
- drafts: readDrafts(current.drafts),
1453
- fingerprints: readFingerprints(current.fingerprints)
1454
- };
1455
- }
1456
- const legacy = readJson(statePath(cfg, LEGACY_DRAFTS_FILE));
1457
- if (legacy === void 0) return {
1458
- drafts: {},
1459
- fingerprints: {}
1460
- };
1461
- if (!isObject(legacy)) throw corrupt(statePath(cfg, LEGACY_DRAFTS_FILE));
1462
- return {
1463
- drafts: readDrafts(legacy),
1464
- fingerprints: {}
1465
- };
1466
- }
1467
- function saveState(cfg, state) {
1468
- const serialized = serializeState(state);
1469
- const path = statePath(cfg);
1470
- const legacy = statePath(cfg, LEGACY_DRAFTS_FILE);
1471
- if (serialized === void 0) {
1472
- rmSync(path, { force: true });
1473
- rmSync(legacy, { force: true });
1474
- return;
1475
- }
1476
- let existing;
1477
- try {
1478
- existing = readFileSync(path, "utf8");
1479
- } catch {
1480
- mkdirSync(cfg.dir, { recursive: true });
1481
- }
1482
- if (existing !== serialized) writeFileSync(path, serialized);
1483
- if (existsSync(legacy)) rmSync(legacy);
1484
- }
1485
- function updateState(cfg, catalogs) {
1486
- const state = loadState(cfg);
1487
- const next = {
1488
- drafts: effectiveDrafts(state.drafts, catalogs),
1489
- fingerprints: refreshFingerprints(cfg, catalogs, state.fingerprints)
1490
- };
1491
- saveState(cfg, next);
1492
- return next;
1493
- }
1494
- function effectiveDrafts(drafts, catalogs) {
1495
- const out = {};
1496
- for (const [locale, keys] of Object.entries(drafts)) {
1497
- const catalog = catalogs[locale] ?? {};
1498
- const live = keys.filter((key) => own(catalog, key));
1499
- if (live.length) out[locale] = live;
1500
- }
1501
- return out;
1502
- }
1503
- function fingerprint(text) {
1504
- return stableKey(text);
1505
- }
1506
- function tracked(key, text) {
1507
- return stableKey(text) !== key;
1508
- }
1509
- function stamp(source, translated) {
1510
- return `${fingerprint(source)}.${fingerprint(translated)}`;
1511
- }
1512
- function refreshFingerprints(cfg, catalogs, previous) {
1513
- const source = catalogs[cfg.sourceLocale] ?? {};
1514
- const out = {};
1515
- for (const locale of targetLocales(cfg)) {
1516
- const catalog = catalogs[locale] ?? {};
1517
- const before = previous[locale] ?? {};
1518
- const after = emptyCatalog();
1519
- for (const [key, text] of Object.entries(source)) {
1520
- const translated = own(catalog, key);
1521
- if (!text || !translated || !tracked(key, text)) continue;
1522
- const was = own(before, key);
1523
- after[key] = was !== void 0 && translationOf(was) === fingerprint(translated) ? was : stamp(text, translated);
1524
- }
1525
- if (Object.keys(after).length) out[locale] = after;
1526
- }
1527
- return out;
1528
- }
1529
- function outdatedTranslations(cfg, catalogs, fingerprints) {
1530
- const source = catalogs[cfg.sourceLocale] ?? {};
1531
- const out = [];
1532
- for (const locale of targetLocales(cfg)) {
1533
- const catalog = catalogs[locale] ?? {};
1534
- for (const [key, was] of Object.entries(fingerprints[locale] ?? {})) {
1535
- const text = own(source, key);
1536
- const translated = own(catalog, key);
1537
- if (!text || !translated) continue;
1538
- if (translationOf(was) !== fingerprint(translated)) continue;
1539
- if (sourceOf(was) !== fingerprint(text)) out.push({
1540
- locale,
1541
- key
1542
- });
1543
- }
1544
- }
1545
- return out.sort((a, b) => a.locale.localeCompare(b.locale) || a.key.localeCompare(b.key));
1546
- }
1547
- function sourceOf(stamped) {
1548
- return stamped.slice(0, stamped.indexOf("."));
1549
- }
1550
- function translationOf(stamped) {
1551
- return stamped.slice(stamped.indexOf(".") + 1);
1552
- }
1553
- function serializeState(state) {
1554
- const drafts = {};
1555
- for (const locale of Object.keys(state.drafts).sort()) {
1556
- const keys = [...new Set(state.drafts[locale])].sort();
1557
- if (keys.length) drafts[locale] = keys;
1558
- }
1559
- const fingerprints = {};
1560
- for (const locale of Object.keys(state.fingerprints).sort()) {
1561
- const entries = state.fingerprints[locale] ?? {};
1562
- const keys = Object.keys(entries).sort();
1563
- if (!keys.length) continue;
1564
- fingerprints[locale] = Object.fromEntries(keys.map((key) => [key, entries[key]]));
1565
- }
1566
- const out = {};
1567
- if (Object.keys(drafts).length) out.drafts = drafts;
1568
- if (Object.keys(fingerprints).length) out.fingerprints = fingerprints;
1569
- if (!out.drafts && !out.fingerprints) return void 0;
1570
- return JSON.stringify(out, null, 2) + "\n";
1571
- }
1572
- function readJson(path) {
1573
- let content;
1574
- try {
1575
- content = readFileSync(path, "utf8");
1576
- } catch {
1577
- return;
1578
- }
1579
- try {
1580
- return JSON.parse(content.charCodeAt(0) === 65279 ? content.slice(1) : content);
1581
- } catch (error) {
1582
- throw corrupt(path, error);
1583
- }
1584
- }
1585
- function corrupt(path, cause) {
1586
- return new Error(`[verbaly] ${path} is not valid JSON, fix or delete the file`, { cause });
1587
- }
1588
- function isObject(value) {
1589
- return typeof value === "object" && value !== null && !Array.isArray(value);
1590
- }
1591
- function readDrafts(value) {
1592
- const out = {};
1593
- if (!isObject(value)) return out;
1594
- for (const [locale, keys] of Object.entries(value)) if (Array.isArray(keys)) out[locale] = keys.filter((key) => typeof key === "string");
1595
- return out;
1596
- }
1597
- function readFingerprints(value) {
1598
- const out = {};
1599
- if (!isObject(value)) return out;
1600
- for (const [locale, entries] of Object.entries(value)) {
1601
- if (!isObject(entries)) continue;
1602
- const kept = emptyCatalog();
1603
- for (const [key, stamped] of Object.entries(entries)) if (typeof stamped === "string" && stamped.includes(".")) kept[key] = stamped;
1604
- out[locale] = kept;
1605
- }
1606
- return out;
1607
- }
1608
- //#endregion
1609
1982
  //#region src/check.ts
1610
1983
  function gatePasses(result) {
1611
1984
  return result.missing.length === 0 && result.unknown.length === 0 && !result.broken.some((entry) => entry.severity === "error");
@@ -1615,15 +1988,11 @@ function warningCount(result) {
1615
1988
  }
1616
1989
  function check(cfg, catalogs, registry, fingerprints = {}) {
1617
1990
  const extracted = registry.messages();
1618
- const locate = createLocator();
1619
- const site = (msg) => ({
1620
- file: msg.file,
1621
- line: locate(msg.file, msg.start),
1622
- message: msg.message
1623
- });
1624
1991
  const flat = {};
1625
1992
  for (const locale of cfg.locales) flat[locale] = flatten(catalogs[locale] ?? {});
1626
1993
  const source = flat[cfg.sourceLocale] ?? {};
1994
+ const shipped = shippedCatalogs(cfg, flat, registry);
1995
+ const sourceText = shipped[cfg.sourceLocale];
1627
1996
  const used = registry.usedKeys();
1628
1997
  const unknown = [];
1629
1998
  for (const [key, files] of registry.usedKeys(true)) if (!(extracted.has(key) || cfg.locales.some((locale) => flat[locale]?.[key] !== void 0))) unknown.push({
@@ -1654,16 +2023,14 @@ function check(cfg, catalogs, registry, fingerprints = {}) {
1654
2023
  issue: issue.message
1655
2024
  });
1656
2025
  };
1657
- const sourceText = Object.assign(emptyCatalog(), source);
1658
2026
  const divergent = [];
1659
2027
  for (const [key, entry] of extracted) {
1660
- const written = sourceText[key];
2028
+ const written = source[key];
1661
2029
  if (written && written !== entry.message) divergent.push({
1662
2030
  key,
1663
2031
  catalog: written,
1664
- code: site(entry)
2032
+ code: siteOf(entry)
1665
2033
  });
1666
- sourceText[key] = entry.message;
1667
2034
  }
1668
2035
  for (const [key, text] of Object.entries(sourceText)) add(cfg.sourceLocale, key, validateMessage(text, cfg.sourceLocale));
1669
2036
  for (const locale of cfg.locales) {
@@ -1687,8 +2054,6 @@ function check(cfg, catalogs, registry, fingerprints = {}) {
1687
2054
  });
1688
2055
  }
1689
2056
  }
1690
- const collisions = collisionEntries(registry, locate);
1691
- const outdated = outdatedTranslations(cfg, flat, fingerprints);
1692
2057
  return {
1693
2058
  ok: gatePasses({
1694
2059
  missing,
@@ -1699,9 +2064,9 @@ function check(cfg, catalogs, registry, fingerprints = {}) {
1699
2064
  unknown,
1700
2065
  broken,
1701
2066
  extra,
1702
- collisions,
2067
+ collisions: collisionEntries(registry),
1703
2068
  divergent,
1704
- outdated
2069
+ outdated: outdatedTranslations(cfg, shipped, fingerprints)
1705
2070
  };
1706
2071
  }
1707
2072
  function formatCheckResult(result, root) {
@@ -1733,38 +2098,20 @@ function checkNextSteps(result, cliReachable = true) {
1733
2098
  if (steps.length > 0 && !cliReachable) steps.push(`the verbaly command is not linked in this project: ${CLI_INSTALL_FIX}`);
1734
2099
  return steps.join("\n");
1735
2100
  }
1736
- function collisionEntries(registry, locate = createLocator()) {
1737
- return registry.collisions().map(({ key, kept, dropped }) => ({
1738
- key,
1739
- sites: [kept, ...dropped].map((msg) => ({
1740
- file: msg.file,
1741
- line: locate(msg.file, msg.start),
1742
- message: msg.message
1743
- }))
1744
- }));
1745
- }
1746
- function sourcePlace(at, root) {
1747
- const file = root ? relative(root, at.file).replaceAll("\\", "/") : at.file;
1748
- return at.line ? `${file}:${at.line}` : file;
1749
- }
1750
- function quoted(at, root) {
1751
- return `"${truncate(at.message, 40)}" (${sourcePlace(at, root)})`;
1752
- }
1753
- function formatCollision({ key, sites }, root) {
1754
- const [kept, ...others] = sites;
1755
- 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`;
1756
- }
1757
- function formatCheckWarnings(result, root) {
2101
+ function formatCheckWarnings(result, root, options = {}) {
1758
2102
  const lines = result.broken.filter((entry) => entry.severity === "warning").map((entry) => ` [${entry.locale}] ${entry.key}: ${entry.issue}`);
1759
2103
  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`);
1760
- for (const entry of result.collisions) lines.push(formatCollision(entry, root));
1761
- 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)`);
1762
- 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\``);
2104
+ for (const entry of result.collisions) lines.push(` ${formatFinding({
2105
+ kind: "collision",
2106
+ ...entry
2107
+ }, root)}`);
2108
+ 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)`);
2109
+ if (!options.outdatedFails) for (const entry of result.outdated) lines.push(` ${formatFinding({
2110
+ kind: "outdated",
2111
+ ...entry
2112
+ }, root)}`);
1763
2113
  return lines.join("\n");
1764
2114
  }
1765
- function truncate(text, max) {
1766
- return text.length > max ? text.slice(0, max - 1) + "…" : text;
1767
- }
1768
2115
  //#endregion
1769
2116
  //#region src/warn.ts
1770
2117
  const warned = /* @__PURE__ */ new Set();
@@ -1860,12 +2207,9 @@ function runBuildGate(cfg, registry, failOnMissing) {
1860
2207
  throw new Error(`[verbaly] build blocked\n${formatCheckResult(result, cfg.root)}\n${checkNextSteps(result, cliReachable(cfg.root))}`);
1861
2208
  }
1862
2209
  function buildFingerprints(cfg) {
1863
- try {
1864
- return loadState(cfg).fingerprints;
1865
- } catch (error) {
1866
- warnOnce(`${error.message.replace(/^\[verbaly\] /, "")}, so outdated translations are not reported`, "gate:state");
1867
- return {};
1868
- }
2210
+ const { state, problem } = readState(cfg);
2211
+ if (problem) warnOnce(`${problem}, so outdated translations are not reported`, "gate:state");
2212
+ return state.fingerprints;
1869
2213
  }
1870
2214
  //#endregion
1871
2215
  //#region src/drafts.ts
@@ -1878,20 +2222,6 @@ function saveDrafts(cfg, drafts) {
1878
2222
  drafts
1879
2223
  });
1880
2224
  }
1881
- function markDrafts(drafts, locale, keys) {
1882
- if (!keys.length) return;
1883
- drafts[locale] = [.../* @__PURE__ */ new Set([...drafts[locale] ?? [], ...keys])];
1884
- }
1885
- function clearDrafts(drafts, locale, keys) {
1886
- if (!drafts[locale]) return;
1887
- if (!keys) {
1888
- delete drafts[locale];
1889
- return;
1890
- }
1891
- const drop = new Set(keys);
1892
- drafts[locale] = drafts[locale].filter((key) => !drop.has(key));
1893
- if (!drafts[locale].length) delete drafts[locale];
1894
- }
1895
2225
  //#endregion
1896
2226
  //#region src/status.ts
1897
2227
  function status(cfg, catalogs, registry, drafts = {}, fingerprints = {}) {
@@ -1901,7 +2231,9 @@ function status(cfg, catalogs, registry, drafts = {}, fingerprints = {}) {
1901
2231
  const source = flat[cfg.sourceLocale] ?? {};
1902
2232
  const needed = /* @__PURE__ */ new Set([...extracted.keys(), ...Object.keys(source)]);
1903
2233
  const live = effectiveDrafts(drafts, flat);
1904
- const outdated = outdatedTranslations(cfg, flat, fingerprints);
2234
+ const shipped = shippedCatalogs(cfg, flat, registry);
2235
+ const sourceText = shipped[cfg.sourceLocale];
2236
+ const outdated = outdatedTranslations(cfg, shipped, fingerprints);
1905
2237
  const locales = [];
1906
2238
  for (const locale of cfg.locales) {
1907
2239
  if (locale === cfg.sourceLocale) continue;
@@ -1911,7 +2243,7 @@ function status(cfg, catalogs, registry, drafts = {}, fingerprints = {}) {
1911
2243
  let broken = 0;
1912
2244
  for (const [key, text] of Object.entries(catalog)) {
1913
2245
  if (!text) continue;
1914
- const from = source[key] ?? extracted.get(key)?.message;
2246
+ const from = sourceText[key];
1915
2247
  if ([...validateMessage(text, locale), ...from ? validatePair(from, text) : []].some((issue) => issue.severity === "error")) broken += 1;
1916
2248
  }
1917
2249
  locales.push({
@@ -2076,15 +2408,13 @@ async function doctor(cfg) {
2076
2408
  }
2077
2409
  const missed = registry.missed();
2078
2410
  if (missed.length > 0) {
2079
- const locate = createLocator();
2080
2411
  const first = missed[0];
2081
- const line = locate(first.file, first.start);
2082
- 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");
2412
+ 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");
2083
2413
  }
2084
2414
  const positional = [...registry.messages().values()].filter((msg) => msg.params.some((param) => /^_\d+$/.test(param.name)));
2085
2415
  if (positional.length > 0) {
2086
2416
  const first = positional[0];
2087
- 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}");
2417
+ 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}");
2088
2418
  }
2089
2419
  const escaped = [...registry.messages().values()].map((msg) => ({
2090
2420
  file: rel(msg.file),
@@ -2106,15 +2436,8 @@ async function doctor(cfg) {
2106
2436
  for (const issue of issues) warn("bundle", formatBundleIssue(issue), issue.fix);
2107
2437
  if (issues.length === 0) ok("bundle", `${counted(excluded.length, "group")} kept out of the client (${preview(excluded)})`);
2108
2438
  }
2109
- let state = {
2110
- drafts: {},
2111
- fingerprints: {}
2112
- };
2113
- try {
2114
- state = loadState(cfg);
2115
- } catch (error) {
2116
- warn("state", error.message.replace(/^\[verbaly\] /, ""), `delete ${STATE_FILE}: drafts and outdated tracking start again from the catalogs`);
2117
- }
2439
+ const { state, problem } = readState(cfg);
2440
+ if (problem) warn("state", problem, `restore ${STATE_FILE} from git: deleting it would mark every machine draft as reviewed`);
2118
2441
  if (catalogsHealthy) {
2119
2442
  const stale = Object.entries(state.drafts).flatMap(([locale, keys]) => {
2120
2443
  const live = new Set(effectiveDrafts({ [locale]: keys }, catalogs)[locale] ?? []);
@@ -2295,7 +2618,9 @@ function mergeTranslations(cfg, locale, translated, keys) {
2295
2618
  function writeDrafts(cfg, locale, entries, options = {}) {
2296
2619
  const targets = targetLocales(cfg);
2297
2620
  if (!targets.includes(locale)) throw new Error(`[verbaly] "${locale}" is not a language this project translates into (${targets.join(", ") || "none yet"})`);
2298
- const source = readCatalog(cfg, cfg.sourceLocale);
2621
+ loadState(cfg);
2622
+ const catalogs = { [cfg.sourceLocale]: readCatalog(cfg, cfg.sourceLocale) };
2623
+ const source = options.registry ? shippedCatalogs(cfg, catalogs, options.registry, { newKeys: false })[cfg.sourceLocale] : catalogs[cfg.sourceLocale];
2299
2624
  const current = readCatalog(cfg, locale);
2300
2625
  const result = {
2301
2626
  written: [],
@@ -2315,9 +2640,14 @@ function writeDrafts(cfg, locale, entries, options = {}) {
2315
2640
  }
2316
2641
  if (result.written.length > 0) {
2317
2642
  writeCatalog(cfg, locale, current);
2318
- const drafts = loadDrafts(cfg);
2319
- markDrafts(drafts, locale, result.written);
2320
- saveDrafts(cfg, drafts);
2643
+ recordTranslations(cfg, source, [{
2644
+ locale,
2645
+ entries: result.written.map((key) => ({
2646
+ key,
2647
+ text: current[key]
2648
+ })),
2649
+ draft: true
2650
+ }]);
2321
2651
  }
2322
2652
  return result;
2323
2653
  }
@@ -2336,7 +2666,7 @@ function formatTranslateFailures(failed) {
2336
2666
  async function resolveProvider(cfg, model) {
2337
2667
  const configured = cfg.translate.provider;
2338
2668
  if (typeof configured === "function") return configured;
2339
- const { claudeProvider } = await import("./claude-D-j-ZiYH.js");
2669
+ const { claudeProvider } = await import("./claude-BFIWiu_4.js");
2340
2670
  return claudeProvider({ model: model ?? cfg.translate.model });
2341
2671
  }
2342
2672
  function structureMatches(source, translated) {
@@ -3138,6 +3468,6 @@ function formatCliError(error) {
3138
3468
  return message.startsWith("[verbaly]") ? message : `[verbaly] ${message}`;
3139
3469
  }
3140
3470
  //#endregion
3141
- export { LOCALE_MODULE_PREFIX, MessageRegistry, RESOLVED_VIRTUAL_ID, SOURCE_FILE_RE, STATE_FILE, check, clearDrafts, clientCatalogs, collectOrigins, collisionEntries, counted, createSourceFilter, doctor, effectiveDrafts, extractProject, formatCheckResult, formatCheckWarnings, formatCliError, formatCollision, formatDoctorEntry, formatRenderWarnings, formatStatusResult, formatTranslateFailures, generateDts, generateLocaleModule, generateRuntimeModule, init, isTransformTarget, loadCatalogs, loadConfig, loadDrafts, loadState, loadVirtualModule, markDrafts, mergeTranslations, needsIcu, needsRelative, outdatedTranslations, parseCatalog, pruneCatalogs, readCatalog, renderSite, resolveConfig, resolveProvider, resolveVirtualId, runBuildGate, saveDrafts, stableKey, status, syncCatalogs, targetLocales, transformCode, transformSource, translateCatalogs, updateState, validateMessage, validatePair, watchTree, wrapProject, writeCatalog, writeDrafts, writeDts };
3471
+ export { LOCALE_MODULE_PREFIX, MessageRegistry, RESOLVED_VIRTUAL_ID, SOURCE_FILE_RE, STATE_FILE, check, clearDrafts, clientCatalogs, collectOrigins, collisionEntries, counted, createDevReporter, createSourceFilter, doctor, effectiveDrafts, extractProject, formatCheckResult, formatCheckWarnings, formatCliError, formatCollision, formatDoctorEntry, formatFinding, formatRenderWarnings, formatStatusResult, formatTranslateFailures, generateDts, generateLocaleModule, generateRuntimeModule, init, isTransformTarget, loadCatalogs, loadConfig, loadDrafts, loadState, loadVirtualModule, markDrafts, mergeTranslations, needsIcu, needsRelative, outdatedTranslations, parseCatalog, pruneCatalogs, readCatalog, readState, recordTranslations, renderSite, resolveConfig, resolveProvider, resolveVirtualId, runBuildGate, saveDrafts, shippedCatalogs, stableKey, status, syncCatalogs, syncProject, targetLocales, transformCode, transformSource, translateCatalogs, updateState, validateMessage, validatePair, watchTree, wrapProject, writeCatalog, writeDrafts, writeDts };
3142
3472
 
3143
3473
  //# sourceMappingURL=index.js.map