@verbaly/compiler 0.66.0 → 0.67.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
@@ -4,9 +4,9 @@ import { parseArgs } from "node:util";
4
4
  import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, rmSync, watch, writeFileSync } from "node:fs";
5
5
  import { CATALOG_SCRIPT, LOCALE_STORAGE_KEY, RICH_TAGS, VOID_TAGS, alternateLinks, createVerbaly, flatten, localeDirection, normalizeLink, parse, parseIcu, parseTags, safeAttribute } from "verbaly";
6
6
  import { pathToFileURL } from "node:url";
7
+ import { createHash } from "node:crypto";
7
8
  import { glob } from "tinyglobby";
8
9
  import { parse as parse$1 } from "@babel/parser";
9
- import { createHash } from "node:crypto";
10
10
  import MagicString from "magic-string";
11
11
  import picomatch from "picomatch";
12
12
  //#region src/catalog.ts
@@ -521,6 +521,213 @@ async function init(input = {}) {
521
521
  };
522
522
  }
523
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
+ };
542
+ }
543
+ //#endregion
544
+ //#region src/key.ts
545
+ function stableKey(message) {
546
+ return createHash("sha256").update(message).digest("base64url").slice(0, 8);
547
+ }
548
+ //#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));
559
+ return {
560
+ drafts: readDrafts(current.drafts),
561
+ fingerprints: readFingerprints(current.fingerprints)
562
+ };
563
+ }
564
+ const legacy = readJson(statePath(cfg, LEGACY_DRAFTS_FILE));
565
+ if (legacy === void 0) return {
566
+ drafts: {},
567
+ fingerprints: {}
568
+ };
569
+ if (!isObject(legacy)) throw corrupt(statePath(cfg, LEGACY_DRAFTS_FILE));
570
+ return {
571
+ drafts: readDrafts(legacy),
572
+ fingerprints: {}
573
+ };
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;
583
+ }
584
+ let existing;
585
+ try {
586
+ existing = readFileSync(path, "utf8");
587
+ } catch {
588
+ mkdirSync(cfg.dir, { recursive: true });
589
+ }
590
+ if (existing !== serialized) writeFileSync(path, serialized);
591
+ if (existsSync(legacy)) rmSync(legacy);
592
+ }
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)
598
+ };
599
+ saveState(cfg, next);
600
+ return next;
601
+ }
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;
608
+ }
609
+ return out;
610
+ }
611
+ function fingerprint(text) {
612
+ return stableKey(text);
613
+ }
614
+ function tracked(key, text) {
615
+ return stableKey(text) !== key;
616
+ }
617
+ function stamp(source, translated) {
618
+ return `${fingerprint(source)}.${fingerprint(translated)}`;
619
+ }
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);
632
+ }
633
+ if (Object.keys(after).length) out[locale] = after;
634
+ }
635
+ return out;
636
+ }
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
+ }
652
+ }
653
+ return out.sort((a, b) => a.locale.localeCompare(b.locale) || a.key.localeCompare(b.key));
654
+ }
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);
662
+ }
663
+ }
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]]));
682
+ }
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
+ }
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
+ }
701
+ }
702
+ function corrupt(path, cause) {
703
+ return new Error(`[verbaly] ${path} is not valid JSON, fix or delete the file`, { cause });
704
+ }
705
+ function isObject(value) {
706
+ return typeof value === "object" && value !== null && !Array.isArray(value);
707
+ }
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;
713
+ }
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;
722
+ }
723
+ return out;
724
+ }
725
+ //#endregion
726
+ //#region src/text.ts
727
+ function counted(count, noun, many = `${noun}s`) {
728
+ return `${count} ${count === 1 ? noun : many}`;
729
+ }
730
+ //#endregion
524
731
  //#region src/validate.ts
525
732
  const read = (message) => parse(message, parseIcu);
526
733
  const PLURAL_CATEGORIES = /* @__PURE__ */ new Set([
@@ -688,8 +895,14 @@ function reachableCategories(locale, ordinal) {
688
895
  function gatePasses(result) {
689
896
  return result.missing.length === 0 && result.unknown.length === 0 && !result.broken.some((entry) => entry.severity === "error");
690
897
  }
691
- function check(cfg, catalogs, registry) {
898
+ function check(cfg, catalogs, registry, fingerprints = {}) {
692
899
  const extracted = registry.messages();
900
+ const locate = createLocator();
901
+ const site = (msg) => ({
902
+ file: msg.file,
903
+ line: locate(msg.file, msg.start),
904
+ message: msg.message
905
+ });
693
906
  const flat = {};
694
907
  for (const locale of cfg.locales) flat[locale] = flatten(catalogs[locale] ?? {});
695
908
  const source = flat[cfg.sourceLocale] ?? {};
@@ -724,7 +937,16 @@ function check(cfg, catalogs, registry) {
724
937
  });
725
938
  };
726
939
  const sourceText = Object.assign(emptyCatalog(), source);
727
- for (const [key, entry] of extracted) if (!sourceText[key]) sourceText[key] = entry.message;
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)
947
+ });
948
+ sourceText[key] = entry.message;
949
+ }
728
950
  for (const [key, text] of Object.entries(sourceText)) add(cfg.sourceLocale, key, validateMessage(text, cfg.sourceLocale));
729
951
  for (const locale of cfg.locales) {
730
952
  if (locale === cfg.sourceLocale) continue;
@@ -747,6 +969,8 @@ function check(cfg, catalogs, registry) {
747
969
  });
748
970
  }
749
971
  }
972
+ const collisions = collisionEntries(registry, locate);
973
+ const outdated = outdatedTranslations(cfg, flat, fingerprints);
750
974
  return {
751
975
  ok: gatePasses({
752
976
  missing,
@@ -756,7 +980,10 @@ function check(cfg, catalogs, registry) {
756
980
  missing,
757
981
  unknown,
758
982
  broken,
759
- extra
983
+ extra,
984
+ collisions,
985
+ divergent,
986
+ outdated
760
987
  };
761
988
  }
762
989
  function formatCheckResult(result, root) {
@@ -788,9 +1015,33 @@ function checkNextSteps(result, cliReachable = true) {
788
1015
  if (steps.length > 0 && !cliReachable) steps.push(`the verbaly command is not linked in this project: ${CLI_INSTALL_FIX}`);
789
1016
  return steps.join("\n");
790
1017
  }
791
- function formatCheckWarnings(result) {
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
+ }));
1027
+ }
1028
+ function sourcePlace(at, root) {
1029
+ const file = root ? relative(root, at.file).replaceAll("\\", "/") : at.file;
1030
+ return at.line ? `${file}:${at.line}` : file;
1031
+ }
1032
+ function quoted(at, root) {
1033
+ return `"${truncate(at.message, 40)}" (${sourcePlace(at, root)})`;
1034
+ }
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`;
1038
+ }
1039
+ function formatCheckWarnings(result, root) {
792
1040
  const lines = result.broken.filter((entry) => entry.severity === "warning").map((entry) => ` [${entry.locale}] ${entry.key}: ${entry.issue}`);
793
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\``);
794
1045
  return lines.join("\n");
795
1046
  }
796
1047
  function truncate(text, max) {
@@ -798,15 +1049,9 @@ function truncate(text, max) {
798
1049
  }
799
1050
  function githubCheckAnnotations(result, registry, root) {
800
1051
  const messages = registry.messages();
801
- const contents = /* @__PURE__ */ new Map();
802
- const readSource = (file) => {
803
- if (!contents.has(file)) try {
804
- contents.set(file, readFileSync(file, "utf8"));
805
- } catch {
806
- contents.set(file, void 0);
807
- }
808
- return contents.get(file);
809
- };
1052
+ const locate = createLocator();
1053
+ const rel = (file) => escapeProperty(relative(root, file).replaceAll("\\", "/"));
1054
+ const at = (file, line) => `file=${rel(file)}${line ? `,line=${line}` : ""}`;
810
1055
  const lines = [];
811
1056
  const byKey = /* @__PURE__ */ new Map();
812
1057
  for (const entry of result.missing) {
@@ -821,17 +1066,13 @@ function githubCheckAnnotations(result, registry, root) {
821
1066
  const origin = messages.get(entry.key);
822
1067
  const hint = entry.source ? `: "${truncate(entry.source, 60)}"` : "";
823
1068
  const text = escapeData(`missing [${entry.locales.join(", ")}] ${entry.key}${hint}`);
824
- if (origin) {
825
- const file = relative(root, origin.file).replaceAll("\\", "/");
826
- const content = readSource(origin.file);
827
- const line = content === void 0 ? void 0 : lineAt(content, origin.start);
828
- lines.push(`::error file=${escapeProperty(file)}${line ? `,line=${line}` : ""}::${text}`);
829
- } else lines.push(`::error::${text}`);
1069
+ if (origin) lines.push(`::error ${at(origin.file, locate(origin.file, origin.start))}::${text}`);
1070
+ else lines.push(`::error::${text}`);
830
1071
  }
831
1072
  for (const entry of result.unknown) {
832
1073
  const text = escapeData(`unknown key "${entry.key}" (not in any catalog)`);
833
1074
  const file = entry.files[0];
834
- lines.push(file ? `::error file=${escapeProperty(relative(root, file).replaceAll("\\", "/"))}::${text}` : `::error::${text}`);
1075
+ lines.push(file ? `::error file=${rel(file)}::${text}` : `::error::${text}`);
835
1076
  }
836
1077
  for (const entry of result.broken) {
837
1078
  const origin = messages.get(entry.key);
@@ -841,24 +1082,27 @@ function githubCheckAnnotations(result, registry, root) {
841
1082
  lines.push(`::${command}::${text}`);
842
1083
  continue;
843
1084
  }
844
- const file = relative(root, origin.file).replaceAll("\\", "/");
845
- const content = readSource(origin.file);
846
- const line = content === void 0 ? void 0 : lineAt(content, origin.start);
847
- lines.push(`::${command} file=${escapeProperty(file)}${line ? `,line=${line}` : ""}::${text}`);
1085
+ lines.push(`::${command} ${at(origin.file, locate(origin.file, origin.start))}::${text}`);
848
1086
  }
849
1087
  for (const entry of result.extra) {
850
1088
  const text = escapeData(`[${entry.locale}] ${entry.key}: only this translation has it`);
851
1089
  const file = entry.files[0];
852
- lines.push(file ? `::warning file=${escapeProperty(relative(root, file).replaceAll("\\", "/"))}::${text}` : `::warning::${text}`);
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}`);
1099
+ }
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}`);
853
1103
  }
854
1104
  return lines;
855
1105
  }
856
- function lineAt(content, offset) {
857
- let line = 1;
858
- const end = Math.min(offset, content.length);
859
- for (let i = 0; i < end; i++) if (content[i] === "\n") line += 1;
860
- return line;
861
- }
862
1106
  function escapeData(text) {
863
1107
  return text.replaceAll("%", "%25").replaceAll("\r", "%0D").replaceAll("\n", "%0A");
864
1108
  }
@@ -990,11 +1234,6 @@ function writeDts(cfg, catalog, file) {
990
1234
  writeFileSync(file, content);
991
1235
  }
992
1236
  //#endregion
993
- //#region src/text.ts
994
- function counted(count, noun, many = `${noun}s`) {
995
- return `${count} ${count === 1 ? noun : many}`;
996
- }
997
- //#endregion
998
1237
  //#region src/bundle.ts
999
1238
  function isExcluded(key, prefixes) {
1000
1239
  return prefixes.some((prefix) => key === prefix || key.startsWith(`${prefix}.`));
@@ -1028,14 +1267,6 @@ function formatBundleIssue(issue) {
1028
1267
  return `bundle.exclude "${issue.prefix}" ${issue.problem}`;
1029
1268
  }
1030
1269
  //#endregion
1031
- //#region src/warn.ts
1032
- const warned = /* @__PURE__ */ new Set();
1033
- function warnOnce(message, dedupeKey = message) {
1034
- if (warned.has(dedupeKey)) return;
1035
- warned.add(dedupeKey);
1036
- console.warn(`[verbaly] ${message}`);
1037
- }
1038
- //#endregion
1039
1270
  //#region src/registry.ts
1040
1271
  var MessageRegistry = class {
1041
1272
  files = /* @__PURE__ */ new Map();
@@ -1047,15 +1278,21 @@ var MessageRegistry = class {
1047
1278
  }
1048
1279
  messages() {
1049
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;
1283
+ }
1284
+ collisions() {
1285
+ const seen = /* @__PURE__ */ new Map();
1050
1286
  for (const analysis of this.files.values()) for (const msg of analysis.tagged) {
1051
- const existing = out.get(msg.key);
1052
- if (existing) {
1053
- if (existing.message !== msg.message) warnOnce(`key collision "${msg.key}": ${JSON.stringify(existing.message)} vs ${JSON.stringify(msg.message)}, second dropped`, `collision:${msg.key}`);
1054
- continue;
1055
- }
1056
- out.set(msg.key, msg);
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);
1057
1294
  }
1058
- return out;
1295
+ return [...seen.values()].filter((entry) => entry.dropped.length > 0);
1059
1296
  }
1060
1297
  usedKeys(strict = false) {
1061
1298
  const out = /* @__PURE__ */ new Map();
@@ -1070,6 +1307,9 @@ var MessageRegistry = class {
1070
1307
  strayImports() {
1071
1308
  return [...this.files.values()].flatMap((analysis) => analysis.strayImports);
1072
1309
  }
1310
+ missed() {
1311
+ return [...this.files.values()].flatMap((analysis) => analysis.missed ?? []);
1312
+ }
1073
1313
  parseErrors() {
1074
1314
  const out = [];
1075
1315
  for (const [file, analysis] of this.files) if (analysis.parseError) out.push({
@@ -1089,11 +1329,6 @@ var MessageRegistry = class {
1089
1329
  }
1090
1330
  };
1091
1331
  //#endregion
1092
- //#region src/key.ts
1093
- function stableKey(message) {
1094
- return createHash("sha256").update(message).digest("base64url").slice(0, 8);
1095
- }
1096
- //#endregion
1097
1332
  //#region src/analyze.ts
1098
1333
  function parseErrorMessage(error) {
1099
1334
  return error instanceof Error ? error.message : String(error);
@@ -1118,12 +1353,22 @@ function analyze(code, file, options = {}) {
1118
1353
  const tagged = [];
1119
1354
  const usedKeys = [];
1120
1355
  const strayImports = [];
1356
+ const missed = [];
1357
+ const renamed = renamedBindings(ast.program, names);
1121
1358
  walk(ast.program, (node) => {
1122
1359
  if (node.type === "ImportDeclaration") collectStrayImports(node, file, strayImports);
1123
1360
  else if (node.type === "TaggedTemplateExpression") {
1124
1361
  const tag = node.tag;
1125
1362
  const explicit = explicitId(tag, names);
1126
- if (!explicit && !isTReference(tag, names)) return;
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
+ }
1127
1372
  const quasi = node.quasi;
1128
1373
  const message = buildMessage(code, quasi, names);
1129
1374
  if (!message) return;
@@ -1144,7 +1389,15 @@ function analyze(code, file, options = {}) {
1144
1389
  collectDeclaredKeys(args[0], file, usedKeys);
1145
1390
  return;
1146
1391
  }
1147
- if (!isTReference(callee, names)) return;
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
+ }
1148
1401
  const key = staticString(args[0]);
1149
1402
  if (key !== void 0) usedKeys.push(usedKey(key, file, args[0]));
1150
1403
  } else if (node.type === "JSXElement") handleTrans(code, node, file, tagged, usedKeys, names);
@@ -1152,8 +1405,52 @@ function analyze(code, file, options = {}) {
1152
1405
  return {
1153
1406
  tagged,
1154
1407
  usedKeys,
1155
- strayImports
1408
+ strayImports,
1409
+ ...missed.length > 0 && { missed }
1410
+ };
1411
+ }
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);
1156
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;
1434
+ }
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";
1440
+ }
1441
+ function identifierName(node) {
1442
+ return node?.type === "Identifier" ? node.name : "";
1443
+ }
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;
1157
1454
  }
1158
1455
  function collectDeclaredKeys(node, file, out) {
1159
1456
  if (node?.type !== "ObjectExpression") return;
@@ -1582,10 +1879,15 @@ async function collectOrigins(cfg, reuse) {
1582
1879
  }
1583
1880
  function syncCatalogs(cfg, catalogs, registry) {
1584
1881
  const added = {};
1882
+ const replaced = [];
1585
1883
  const source = catalogs[cfg.sourceLocale] ??= emptyCatalog();
1586
- for (const [key, msg] of registry.messages()) if (own(source, key) !== msg.message) {
1587
- source[key] = msg.message;
1588
- (added[cfg.sourceLocale] ??= []).push(key);
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
+ }
1589
1891
  }
1590
1892
  const needed = Object.keys(source);
1591
1893
  for (const locale of cfg.locales) {
@@ -1596,7 +1898,10 @@ function syncCatalogs(cfg, catalogs, registry) {
1596
1898
  (added[locale] ??= []).push(key);
1597
1899
  }
1598
1900
  }
1599
- return { added };
1901
+ return {
1902
+ added,
1903
+ replaced
1904
+ };
1600
1905
  }
1601
1906
  function pruneCatalogs(cfg, catalogs, registry) {
1602
1907
  const removed = {};
@@ -1613,6 +1918,31 @@ function pruneCatalogs(cfg, catalogs, registry) {
1613
1918
  return removed;
1614
1919
  }
1615
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
+ });
1930
+ }
1931
+ function markDrafts(drafts, locale, keys) {
1932
+ if (!keys.length) return;
1933
+ drafts[locale] = [.../* @__PURE__ */ new Set([...drafts[locale] ?? [], ...keys])];
1934
+ }
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];
1944
+ }
1945
+ //#endregion
1616
1946
  //#region src/doctor.ts
1617
1947
  const PREVIEW = 5;
1618
1948
  function readRoutingChoice(root, configFile) {
@@ -1738,6 +2068,18 @@ async function doctor(cfg) {
1738
2068
  const files = [...new Set(stray.map((entry) => rel(entry.file)))];
1739
2069
  error("imports", `t is imported from a verbaly package, which never exports it, in ${counted(files.length, "file")} (${preview(files)})`, "t comes from your instance (React: const t = useT()) or from virtual:verbaly");
1740
2070
  }
2071
+ const missed = registry.missed();
2072
+ if (missed.length > 0) {
2073
+ const locate = createLocator();
2074
+ 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");
2077
+ }
2078
+ const positional = [...registry.messages().values()].filter((msg) => msg.params.some((param) => /^_\d+$/.test(param.name)));
2079
+ if (positional.length > 0) {
2080
+ 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}");
2082
+ }
1741
2083
  const escaped = [...registry.messages().values()].map((msg) => ({
1742
2084
  file: rel(msg.file),
1743
2085
  slice: escapedSyntax(msg.message)
@@ -1758,8 +2100,24 @@ async function doctor(cfg) {
1758
2100
  for (const issue of issues) warn("bundle", formatBundleIssue(issue), issue.fix);
1759
2101
  if (issues.length === 0) ok("bundle", `${counted(excluded.length, "group")} kept out of the client (${preview(excluded)})`);
1760
2102
  }
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
+ }
2112
+ if (catalogsHealthy) {
2113
+ const stale = Object.entries(state.drafts).flatMap(([locale, keys]) => {
2114
+ const live = new Set(effectiveDrafts({ [locale]: keys }, catalogs)[locale] ?? []);
2115
+ return keys.filter((key) => !live.has(key)).map((key) => `${locale}: ${key}`);
2116
+ });
2117
+ if (stale.length > 0) warn("drafts", `${STATE_FILE} lists ${counted(stale.length, "draft")} whose translation is gone (${preview(stale)})`, "run `npx verbaly extract`, which drops them");
2118
+ }
1761
2119
  if (catalogsHealthy) {
1762
- const result = check(cfg, catalogs, registry);
2120
+ const result = check(cfg, catalogs, registry, state.fingerprints);
1763
2121
  if (result.unknown.length > 0) error("keys", `${counted(result.unknown.length, "unknown key")} used in code (${preview(result.unknown.map((u) => u.key))})`, "fix the key or add it to the catalogs (`npx verbaly check` for details)");
1764
2122
  if (result.missing.length > 0) {
1765
2123
  const locales = [...new Set(result.missing.map((m) => m.locale))];
@@ -1776,6 +2134,18 @@ async function doctor(cfg) {
1776
2134
  }
1777
2135
  const warnings = result.broken.filter((entry) => entry.severity === "warning");
1778
2136
  if (warnings.length > 0) warn("translations", `${counted(warnings.length, "structural warning")} (plural forms a language asks for)`, "run `npx verbaly check` to read them, they never fail the build");
2137
+ if (result.collisions.length > 0) {
2138
+ const first = result.collisions[0];
2139
+ warn("keys", `${counted(result.collisions.length, "key")} written with more than one text, and every place shows the first (${first.key}: ${first.sites.map((at) => sourcePlace(at, cfg.root)).join(", ")})`, "give each text its own key (`npx verbaly check` lists every place)");
2140
+ }
2141
+ if (result.divergent.length > 0) {
2142
+ const first = result.divergent[0];
2143
+ warn("source texts", `the code and ${cfg.sourceLocale}.json disagree on ${counted(result.divergent.length, "text")}, and the code's text ships (${first.key}, ${sourcePlace(first.code, cfg.root)})`, "edit those texts in the code; `npx verbaly extract` writes them into the catalog");
2144
+ }
2145
+ if (result.outdated.length > 0) {
2146
+ const shown = result.outdated.map((entry) => `${entry.locale}: ${entry.key}`);
2147
+ warn("outdated", `${counted(result.outdated.length, "translation")} written for an older source text (${preview(shown)})`, "update them, or keep them with `npx verbaly review --approve`");
2148
+ }
1779
2149
  if (result.ok) ok("translations", "all translations complete");
1780
2150
  }
1781
2151
  return {
@@ -1788,66 +2158,6 @@ function preview(keys) {
1788
2158
  return keys.length > PREVIEW ? `${head}, …` : head;
1789
2159
  }
1790
2160
  //#endregion
1791
- //#region src/drafts.ts
1792
- const DRAFTS_FILE = ".verbaly-drafts.json";
1793
- function draftsPath(cfg) {
1794
- return join(cfg.dir, DRAFTS_FILE);
1795
- }
1796
- function loadDrafts(cfg) {
1797
- let content;
1798
- try {
1799
- content = readFileSync(draftsPath(cfg), "utf8");
1800
- } catch {
1801
- return {};
1802
- }
1803
- try {
1804
- return JSON.parse(content.replace(/^\uFEFF/, ""));
1805
- } catch (error) {
1806
- throw new Error(`[verbaly] ${draftsPath(cfg)} is not valid JSON, fix or delete the file`, { cause: error });
1807
- }
1808
- }
1809
- function serializeDrafts(drafts) {
1810
- const sorted = {};
1811
- for (const locale of Object.keys(drafts).sort()) {
1812
- const keys = [...new Set(drafts[locale])].sort();
1813
- if (keys.length) sorted[locale] = keys;
1814
- }
1815
- return JSON.stringify(sorted, null, 2) + "\n";
1816
- }
1817
- function saveDrafts(cfg, drafts) {
1818
- const serialized = serializeDrafts(drafts);
1819
- const path = draftsPath(cfg);
1820
- try {
1821
- if (readFileSync(path, "utf8") === serialized) return;
1822
- } catch {
1823
- mkdirSync(cfg.dir, { recursive: true });
1824
- }
1825
- writeFileSync(path, serialized);
1826
- }
1827
- function markDrafts(drafts, locale, keys) {
1828
- if (!keys.length) return;
1829
- drafts[locale] = [.../* @__PURE__ */ new Set([...drafts[locale] ?? [], ...keys])];
1830
- }
1831
- function clearDrafts(drafts, locale, keys) {
1832
- if (!drafts[locale]) return;
1833
- if (!keys) {
1834
- delete drafts[locale];
1835
- return;
1836
- }
1837
- const drop = new Set(keys);
1838
- drafts[locale] = drafts[locale].filter((key) => !drop.has(key));
1839
- if (!drafts[locale].length) delete drafts[locale];
1840
- }
1841
- function effectiveDrafts(drafts, catalogs) {
1842
- const out = {};
1843
- for (const [locale, keys] of Object.entries(drafts)) {
1844
- const catalog = catalogs[locale] ?? {};
1845
- const live = keys.filter((key) => own(catalog, key));
1846
- if (live.length) out[locale] = live;
1847
- }
1848
- return out;
1849
- }
1850
- //#endregion
1851
2161
  //#region src/inline.ts
1852
2162
  const OPEN_TAG = /^<([a-zA-Z][a-zA-Z0-9-]*)\s*(\/?)>/;
1853
2163
  function messageToInline(text) {
@@ -2775,6 +3085,14 @@ function migrateCatalogs(cfg, options = {}) {
2775
3085
  };
2776
3086
  }
2777
3087
  //#endregion
3088
+ //#region src/warn.ts
3089
+ const warned = /* @__PURE__ */ new Set();
3090
+ function warnOnce(message, dedupeKey = message) {
3091
+ if (warned.has(dedupeKey)) return;
3092
+ warned.add(dedupeKey);
3093
+ console.warn(`[verbaly] ${message}`);
3094
+ }
3095
+ //#endregion
2778
3096
  //#region src/render.ts
2779
3097
  function localeInstance(catalogs, locale, sourceLocale) {
2780
3098
  return createVerbaly({
@@ -3218,13 +3536,14 @@ function decodeEntities(text) {
3218
3536
  }
3219
3537
  //#endregion
3220
3538
  //#region src/status.ts
3221
- function status(cfg, catalogs, registry, drafts = {}) {
3539
+ function status(cfg, catalogs, registry, drafts = {}, fingerprints = {}) {
3222
3540
  const extracted = registry.messages();
3223
3541
  const flat = {};
3224
3542
  for (const locale of cfg.locales) flat[locale] = flatten(catalogs[locale] ?? {});
3225
3543
  const source = flat[cfg.sourceLocale] ?? {};
3226
3544
  const needed = /* @__PURE__ */ new Set([...extracted.keys(), ...Object.keys(source)]);
3227
3545
  const live = effectiveDrafts(drafts, flat);
3546
+ const outdated = outdatedTranslations(cfg, flat, fingerprints);
3228
3547
  const locales = [];
3229
3548
  for (const locale of cfg.locales) {
3230
3549
  if (locale === cfg.sourceLocale) continue;
@@ -3242,7 +3561,8 @@ function status(cfg, catalogs, registry, drafts = {}) {
3242
3561
  translated,
3243
3562
  total: needed.size,
3244
3563
  drafts: live[locale]?.length ?? 0,
3245
- broken
3564
+ broken,
3565
+ outdated: outdated.filter((entry) => entry.locale === locale).length
3246
3566
  });
3247
3567
  }
3248
3568
  return {
@@ -3257,10 +3577,14 @@ function formatStatusResult(result) {
3257
3577
  lines.push(" no target locales (add locales to your config)");
3258
3578
  return lines.join("\n");
3259
3579
  }
3260
- for (const { locale, translated, total, drafts, broken } of result.locales) {
3580
+ for (const { locale, translated, total, drafts, broken, outdated } of result.locales) {
3261
3581
  const pct = total === 0 ? 100 : Math.floor(translated / total * 100);
3262
- const mark = translated === total && broken === 0 ? " ✓" : "";
3263
- const notes = [drafts > 0 ? `${drafts} unreviewed` : "", broken > 0 ? `${broken} broken` : ""].filter(Boolean);
3582
+ const mark = translated === total && broken === 0 && outdated === 0 ? " ✓" : "";
3583
+ const notes = [
3584
+ drafts > 0 ? `${drafts} unreviewed` : "",
3585
+ broken > 0 ? `${broken} broken` : "",
3586
+ outdated > 0 ? `${outdated} outdated` : ""
3587
+ ].filter(Boolean);
3264
3588
  const note = notes.length > 0 ? `, ${notes.join(", ")}` : "";
3265
3589
  lines.push(` ${locale}: ${translated}/${total} translated (${pct}%${note})${mark}`);
3266
3590
  }
@@ -3642,7 +3966,7 @@ Usage:
3642
3966
  verbaly status translation coverage per locale, at a glance
3643
3967
  verbaly check verify translations are complete (CI)
3644
3968
  verbaly translate fill missing translations via a provider (default: claude)
3645
- verbaly review list machine translations awaiting review (--approve marks them reviewed)
3969
+ verbaly review list translations awaiting review: machine drafts and outdated ones (--approve accepts them)
3646
3970
  verbaly export write translator files (XLIFF 2.0, CSV, gettext PO) or mobile resources (Android, iOS)
3647
3971
  verbaly import <files…> fill catalogs back from translated XLIFF/CSV/PO files
3648
3972
  verbaly pseudo generate a pseudo-locale catalog for i18n QA (default: en-XA)
@@ -3659,6 +3983,7 @@ Options:
3659
3983
  --plurals also merge _one/_other into one message with variants (migrate)
3660
3984
  --json machine-readable output (status)
3661
3985
  --drafts also fail on unreviewed machine translations (check)
3986
+ --outdated also fail on translations written for an older source text (check)
3662
3987
  --approve mark listed drafts as reviewed (review)
3663
3988
  --reporter <name> failure format: text (default) or github annotations (check)
3664
3989
  --model <id> model override for the claude provider (translate)
@@ -3667,6 +3992,7 @@ Options:
3667
3992
  --out <path> export directory (export, default: verbaly-export)
3668
3993
  --missing export only untranslated entries (export)
3669
3994
  --overwrite replace existing translations on import (import)
3995
+ --draft mark what the files bring as drafts a person still has to review (import)
3670
3996
  --locale <id> pseudo-locale id (pseudo) / one locale only (review, import)
3671
3997
  --site <path> built site directory (render, default: dist)
3672
3998
  --attribute <name> base data attribute (render, default: data-verbaly)
@@ -3693,6 +4019,8 @@ async function runCli(args = process.argv.slice(2)) {
3693
4019
  write: { type: "boolean" },
3694
4020
  json: { type: "boolean" },
3695
4021
  drafts: { type: "boolean" },
4022
+ outdated: { type: "boolean" },
4023
+ draft: { type: "boolean" },
3696
4024
  approve: { type: "boolean" },
3697
4025
  reporter: { type: "string" },
3698
4026
  model: { type: "string" },
@@ -3775,16 +4103,21 @@ async function runCli(args = process.argv.slice(2)) {
3775
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`);
3776
4104
  for (const [locale, keys] of Object.entries(removed)) console.log(dryRun ? ` ${locale}: would prune ${keys.length}: ${keys.join(", ")}` : ` ${locale}: -${keys.length} pruned`);
3777
4105
  }
3778
- const { added } = syncCatalogs(cfg, catalogs, registry);
4106
+ const { added, replaced } = syncCatalogs(cfg, catalogs, registry);
3779
4107
  if (!dryRun) {
3780
4108
  for (const locale of cfg.locales) writeCatalog(cfg, locale, catalogs[locale] ?? {});
3781
4109
  writeDts(cfg, catalogs[cfg.sourceLocale] ?? {});
4110
+ updateState(cfg, catalogs);
3782
4111
  }
3783
4112
  const total = registry.messages().size;
3784
4113
  console.log(`[verbaly] ${counted(total, "message")} · locales: ${cfg.locales.join(", ")}${dryRun ? " (dry run, nothing written)" : ""}`);
3785
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));
3786
4117
  reportParseErrors(cfg, registry);
3787
4118
  reportEscapedSyntax(cfg, registry);
4119
+ reportMissed(cfg, registry);
4120
+ reportPositional(cfg, registry);
3788
4121
  }
3789
4122
  await runExtract();
3790
4123
  if (values.watch) {
@@ -3850,7 +4183,8 @@ async function runCli(args = process.argv.slice(2)) {
3850
4183
  }
3851
4184
  if (command === "status") {
3852
4185
  const registry = await extractProject(cfg);
3853
- const result = status(cfg, loadCatalogs(cfg), registry, loadDrafts(cfg));
4186
+ const state = loadState(cfg);
4187
+ const result = status(cfg, loadCatalogs(cfg), registry, state.drafts, state.fingerprints);
3854
4188
  console.log(values.json ? JSON.stringify(result) : formatStatusResult(result));
3855
4189
  return;
3856
4190
  }
@@ -3863,21 +4197,24 @@ async function runCli(args = process.argv.slice(2)) {
3863
4197
  }
3864
4198
  const registry = await extractProject(cfg);
3865
4199
  const catalogs = loadCatalogs(cfg);
3866
- const result = check(cfg, catalogs, registry);
3867
- const unreviewed = values.drafts ? effectiveDrafts(loadDrafts(cfg), catalogs) : {};
4200
+ const state = checkState(cfg, values.drafts === true || values.outdated === true);
4201
+ const result = check(cfg, catalogs, registry, state.fingerprints);
4202
+ const unreviewed = values.drafts ? effectiveDrafts(state.drafts, catalogs) : {};
3868
4203
  const draftKeys = Object.entries(unreviewed);
4204
+ const outdated = values.outdated ? result.outdated : [];
3869
4205
  if (reporter === "github") for (const line of githubCheckAnnotations(result, registry, cfg.root)) console.error(line);
3870
4206
  else {
3871
- const warnings = formatCheckWarnings(result);
4207
+ const warnings = formatCheckWarnings(result, cfg.root);
3872
4208
  if (warnings) console.warn(`[verbaly] warnings (the gate still passes)\n${warnings}`);
3873
4209
  }
3874
- if (result.ok && draftKeys.length === 0) {
4210
+ if (result.ok && draftKeys.length === 0 && outdated.length === 0) {
3875
4211
  console.log("[verbaly] all translations complete ✓");
3876
4212
  return;
3877
4213
  }
3878
- if (result.ok && draftKeys.length > 0) {
4214
+ if (result.ok) {
3879
4215
  for (const [locale, keys] of draftKeys) console.error(` [${locale}] ${keys.length} unreviewed: ${keys.join(", ")}`);
3880
- console.error("[verbaly] check failed: machine translations awaiting review (run verbaly review --approve)");
4216
+ for (const [locale, keys] of byLocale(outdated)) console.error(` [${locale}] ${keys.length} outdated: ${keys.join(", ")}`);
4217
+ console.error("[verbaly] check failed: translations awaiting review (run verbaly review, then --approve what holds)");
3881
4218
  process.exitCode = 1;
3882
4219
  return;
3883
4220
  }
@@ -3924,28 +4261,40 @@ async function runCli(args = process.argv.slice(2)) {
3924
4261
  }
3925
4262
  if (command === "review") {
3926
4263
  const catalogs = loadCatalogs(cfg);
3927
- const drafts = loadDrafts(cfg);
3928
- const live = effectiveDrafts(drafts, catalogs);
4264
+ const state = loadState(cfg);
4265
+ const live = effectiveDrafts(state.drafts, catalogs);
3929
4266
  const targets = values.locale ? { [values.locale]: live[values.locale] ?? [] } : live;
3930
4267
  const entries = Object.entries(targets).filter(([, keys]) => keys.length);
3931
- if (entries.length === 0) {
3932
- console.log("[verbaly] no machine translations awaiting review ✓");
4268
+ const outdated = outdatedTranslations(cfg, catalogs, state.fingerprints).filter((entry) => !values.locale || entry.locale === values.locale);
4269
+ if (entries.length === 0 && outdated.length === 0) {
4270
+ console.log("[verbaly] nothing awaiting review ✓");
3933
4271
  return;
3934
4272
  }
3935
4273
  if (values.approve) {
3936
4274
  let count = 0;
3937
4275
  for (const [locale, keys] of entries) {
3938
- clearDrafts(drafts, locale, keys);
4276
+ clearDrafts(state.drafts, locale, keys);
3939
4277
  count += keys.length;
3940
4278
  console.log(` ${locale}: ${keys.length} approved`);
3941
4279
  }
3942
- saveDrafts(cfg, drafts);
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
+ }
4285
+ saveState(cfg, state);
3943
4286
  console.log(`[verbaly] ${counted(count, "translation")} marked reviewed ✓`);
3944
4287
  return;
3945
4288
  }
3946
- const total = entries.reduce((sum, [, keys]) => sum + keys.length, 0);
3947
- console.log(`[verbaly] ${counted(total, "machine translation")} awaiting review (--approve to accept)`);
3948
- for (const [locale, keys] of entries) console.log(` ${locale}: ${keys.join(", ")}`);
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(", ")}`);
4293
+ }
4294
+ if (outdated.length > 0) {
4295
+ 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(", ")}`);
4297
+ }
3949
4298
  return;
3950
4299
  }
3951
4300
  if (command === "export") {
@@ -4011,11 +4360,12 @@ async function runCli(args = process.argv.slice(2)) {
4011
4360
  for (const [locale, keys] of Object.entries(result.imported)) {
4012
4361
  if (!values["dry-run"]) {
4013
4362
  writeCatalog(cfg, locale, catalogs[locale] ?? {});
4014
- clearDrafts(drafts, locale, keys);
4363
+ if (values.draft) markDrafts(drafts, locale, keys);
4364
+ else clearDrafts(drafts, locale, keys);
4015
4365
  draftsChanged = true;
4016
4366
  }
4017
4367
  const verb = values["dry-run"] ? "would import" : "imported";
4018
- console.log(` ${locale}: +${keys.length} ${verb}`);
4368
+ console.log(` ${locale}: +${keys.length} ${verb}${values.draft ? " (draft)" : ""}`);
4019
4369
  }
4020
4370
  if (draftsChanged) saveDrafts(cfg, drafts);
4021
4371
  for (const [locale, keys] of Object.entries(result.skipped)) console.log(` ${locale}: ${keys.length} already translated, kept (use --overwrite to replace)`);
@@ -4068,6 +4418,53 @@ function reportParseErrors(cfg, registry) {
4068
4418
  console.warn(` ${rel}: could not be parsed (${message}), its messages were not extracted`);
4069
4419
  }
4070
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
+ 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
+ }
4462
+ }
4463
+ function byLocale(entries) {
4464
+ const out = /* @__PURE__ */ new Map();
4465
+ for (const { locale, key } of entries) out.set(locale, [...out.get(locale) ?? [], key]);
4466
+ return [...out];
4467
+ }
4071
4468
  function reportEscapedSyntax(cfg, registry) {
4072
4469
  for (const msg of registry.messages().values()) {
4073
4470
  const slice = escapedSyntax(msg.message);
@@ -4095,7 +4492,11 @@ const COMMAND_FLAGS = {
4095
4492
  wrap: ["write"],
4096
4493
  migrate: ["write", "plurals"],
4097
4494
  status: ["json"],
4098
- check: ["reporter", "drafts"],
4495
+ check: [
4496
+ "reporter",
4497
+ "drafts",
4498
+ "outdated"
4499
+ ],
4099
4500
  translate: ["model", "dry-run"],
4100
4501
  review: ["approve", "locale"],
4101
4502
  export: [
@@ -4106,7 +4507,8 @@ const COMMAND_FLAGS = {
4106
4507
  import: [
4107
4508
  "locale",
4108
4509
  "overwrite",
4109
- "dry-run"
4510
+ "dry-run",
4511
+ "draft"
4110
4512
  ],
4111
4513
  pseudo: ["locale"],
4112
4514
  render: [