@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/index.js CHANGED
@@ -195,17 +195,6 @@ function formatBundleIssue(issue) {
195
195
  return `bundle.exclude "${issue.prefix}" ${issue.problem}`;
196
196
  }
197
197
  //#endregion
198
- //#region src/warn.ts
199
- const warned = /* @__PURE__ */ new Set();
200
- function warnOnce(message, dedupeKey = message) {
201
- if (warned.has(dedupeKey)) return;
202
- warned.add(dedupeKey);
203
- console.warn(`[verbaly] ${message}`);
204
- }
205
- function warnParseError(file, message) {
206
- warnOnce(`${file}: could not be parsed (${message}), its messages were not extracted`);
207
- }
208
- //#endregion
209
198
  //#region src/registry.ts
210
199
  var MessageRegistry = class {
211
200
  files = /* @__PURE__ */ new Map();
@@ -217,15 +206,21 @@ var MessageRegistry = class {
217
206
  }
218
207
  messages() {
219
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);
210
+ return out;
211
+ }
212
+ collisions() {
213
+ const seen = /* @__PURE__ */ new Map();
220
214
  for (const analysis of this.files.values()) for (const msg of analysis.tagged) {
221
- const existing = out.get(msg.key);
222
- if (existing) {
223
- if (existing.message !== msg.message) warnOnce(`key collision "${msg.key}": ${JSON.stringify(existing.message)} vs ${JSON.stringify(msg.message)}, second dropped`, `collision:${msg.key}`);
224
- continue;
225
- }
226
- out.set(msg.key, msg);
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);
227
222
  }
228
- return out;
223
+ return [...seen.values()].filter((entry) => entry.dropped.length > 0);
229
224
  }
230
225
  usedKeys(strict = false) {
231
226
  const out = /* @__PURE__ */ new Map();
@@ -240,6 +235,9 @@ var MessageRegistry = class {
240
235
  strayImports() {
241
236
  return [...this.files.values()].flatMap((analysis) => analysis.strayImports);
242
237
  }
238
+ missed() {
239
+ return [...this.files.values()].flatMap((analysis) => analysis.missed ?? []);
240
+ }
243
241
  parseErrors() {
244
242
  const out = [];
245
243
  for (const [file, analysis] of this.files) if (analysis.parseError) out.push({
@@ -288,12 +286,22 @@ function analyze(code, file, options = {}) {
288
286
  const tagged = [];
289
287
  const usedKeys = [];
290
288
  const strayImports = [];
289
+ const missed = [];
290
+ const renamed = renamedBindings(ast.program, names);
291
291
  walk$1(ast.program, (node) => {
292
292
  if (node.type === "ImportDeclaration") collectStrayImports(node, file, strayImports);
293
293
  else if (node.type === "TaggedTemplateExpression") {
294
294
  const tag = node.tag;
295
295
  const explicit = explicitId(tag, names);
296
- if (!explicit && !isTReference(tag, names)) return;
296
+ if (!explicit && !isTReference(tag, names)) {
297
+ const name = renamedTag(tag, renamed);
298
+ if (name) missed.push({
299
+ name,
300
+ file,
301
+ start: node.start
302
+ });
303
+ return;
304
+ }
297
305
  const quasi = node.quasi;
298
306
  const message = buildMessage(code, quasi, names);
299
307
  if (!message) return;
@@ -314,7 +322,15 @@ function analyze(code, file, options = {}) {
314
322
  collectDeclaredKeys(args[0], file, usedKeys);
315
323
  return;
316
324
  }
317
- if (!isTReference(callee, names)) return;
325
+ 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
331
+ });
332
+ return;
333
+ }
318
334
  const key = staticString(args[0]);
319
335
  if (key !== void 0) usedKeys.push(usedKey(key, file, args[0]));
320
336
  } else if (node.type === "JSXElement") handleTrans(code, node, file, tagged, usedKeys, names);
@@ -322,9 +338,53 @@ function analyze(code, file, options = {}) {
322
338
  return {
323
339
  tagged,
324
340
  usedKeys,
325
- strayImports
341
+ strayImports,
342
+ ...missed.length > 0 && { missed }
326
343
  };
327
344
  }
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
+ }
364
+ }
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";
373
+ }
374
+ function identifierName(node) {
375
+ return node?.type === "Identifier" ? node.name : "";
376
+ }
377
+ function renamedTag(tag, renamed) {
378
+ if (renamed.size === 0) return void 0;
379
+ const name = identifierName(tag);
380
+ if (renamed.has(name)) return name;
381
+ if (tag.type !== "CallExpression") return void 0;
382
+ const callee = tag.callee;
383
+ if (callee.type !== "MemberExpression" || callee.computed) return void 0;
384
+ if (identifierName(callee.property) !== "id") return void 0;
385
+ const object = identifierName(callee.object);
386
+ return renamed.has(object) ? object : void 0;
387
+ }
328
388
  function collectDeclaredKeys(node, file, out) {
329
389
  if (node?.type !== "ObjectExpression") return;
330
390
  for (const property of node.properties) {
@@ -752,10 +812,15 @@ async function collectOrigins(cfg, reuse) {
752
812
  }
753
813
  function syncCatalogs(cfg, catalogs, registry) {
754
814
  const added = {};
815
+ const replaced = [];
755
816
  const source = catalogs[cfg.sourceLocale] ??= emptyCatalog();
756
- for (const [key, msg] of registry.messages()) if (own(source, key) !== msg.message) {
757
- source[key] = msg.message;
758
- (added[cfg.sourceLocale] ??= []).push(key);
817
+ for (const [key, msg] of registry.messages()) {
818
+ 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
+ }
759
824
  }
760
825
  const needed = Object.keys(source);
761
826
  for (const locale of cfg.locales) {
@@ -766,7 +831,10 @@ function syncCatalogs(cfg, catalogs, registry) {
766
831
  (added[locale] ??= []).push(key);
767
832
  }
768
833
  }
769
- return { added };
834
+ return {
835
+ added,
836
+ replaced
837
+ };
770
838
  }
771
839
  function pruneCatalogs(cfg, catalogs, registry) {
772
840
  const removed = {};
@@ -1350,12 +1418,209 @@ async function init(input = {}) {
1350
1418
  };
1351
1419
  }
1352
1420
  //#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
1353
1609
  //#region src/check.ts
1354
1610
  function gatePasses(result) {
1355
1611
  return result.missing.length === 0 && result.unknown.length === 0 && !result.broken.some((entry) => entry.severity === "error");
1356
1612
  }
1357
- function check(cfg, catalogs, registry) {
1613
+ function warningCount(result) {
1614
+ return result.broken.filter((entry) => entry.severity === "warning").length + result.extra.length + result.collisions.length + result.divergent.length + result.outdated.length;
1615
+ }
1616
+ function check(cfg, catalogs, registry, fingerprints = {}) {
1358
1617
  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
+ });
1359
1624
  const flat = {};
1360
1625
  for (const locale of cfg.locales) flat[locale] = flatten(catalogs[locale] ?? {});
1361
1626
  const source = flat[cfg.sourceLocale] ?? {};
@@ -1390,7 +1655,16 @@ function check(cfg, catalogs, registry) {
1390
1655
  });
1391
1656
  };
1392
1657
  const sourceText = Object.assign(emptyCatalog(), source);
1393
- for (const [key, entry] of extracted) if (!sourceText[key]) sourceText[key] = entry.message;
1658
+ const divergent = [];
1659
+ for (const [key, entry] of extracted) {
1660
+ const written = sourceText[key];
1661
+ if (written && written !== entry.message) divergent.push({
1662
+ key,
1663
+ catalog: written,
1664
+ code: site(entry)
1665
+ });
1666
+ sourceText[key] = entry.message;
1667
+ }
1394
1668
  for (const [key, text] of Object.entries(sourceText)) add(cfg.sourceLocale, key, validateMessage(text, cfg.sourceLocale));
1395
1669
  for (const locale of cfg.locales) {
1396
1670
  if (locale === cfg.sourceLocale) continue;
@@ -1413,6 +1687,8 @@ function check(cfg, catalogs, registry) {
1413
1687
  });
1414
1688
  }
1415
1689
  }
1690
+ const collisions = collisionEntries(registry, locate);
1691
+ const outdated = outdatedTranslations(cfg, flat, fingerprints);
1416
1692
  return {
1417
1693
  ok: gatePasses({
1418
1694
  missing,
@@ -1422,7 +1698,10 @@ function check(cfg, catalogs, registry) {
1422
1698
  missing,
1423
1699
  unknown,
1424
1700
  broken,
1425
- extra
1701
+ extra,
1702
+ collisions,
1703
+ divergent,
1704
+ outdated
1426
1705
  };
1427
1706
  }
1428
1707
  function formatCheckResult(result, root) {
@@ -1454,15 +1733,50 @@ function checkNextSteps(result, cliReachable = true) {
1454
1733
  if (steps.length > 0 && !cliReachable) steps.push(`the verbaly command is not linked in this project: ${CLI_INSTALL_FIX}`);
1455
1734
  return steps.join("\n");
1456
1735
  }
1457
- function formatCheckWarnings(result) {
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) {
1458
1758
  const lines = result.broken.filter((entry) => entry.severity === "warning").map((entry) => ` [${entry.locale}] ${entry.key}: ${entry.issue}`);
1459
1759
  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\``);
1460
1763
  return lines.join("\n");
1461
1764
  }
1462
1765
  function truncate(text, max) {
1463
1766
  return text.length > max ? text.slice(0, max - 1) + "…" : text;
1464
1767
  }
1465
1768
  //#endregion
1769
+ //#region src/warn.ts
1770
+ const warned = /* @__PURE__ */ new Set();
1771
+ function warnOnce(message, dedupeKey = message) {
1772
+ if (warned.has(dedupeKey)) return;
1773
+ warned.add(dedupeKey);
1774
+ console.warn(`[verbaly] ${message}`);
1775
+ }
1776
+ function warnParseError(file, message) {
1777
+ warnOnce(`${file}: could not be parsed (${message}), its messages were not extracted`);
1778
+ }
1779
+ //#endregion
1466
1780
  //#region src/transform.ts
1467
1781
  function quote(text, single) {
1468
1782
  if (!single) return JSON.stringify(text);
@@ -1535,8 +1849,8 @@ function transformSource(code, id, registry) {
1535
1849
  function runBuildGate(cfg, registry, failOnMissing) {
1536
1850
  const catalogs = loadCatalogs(cfg);
1537
1851
  for (const issue of auditBundle(cfg, catalogs, registry)) warnOnce(`${formatBundleIssue(issue)}\n fix: ${issue.fix}`, `bundle:${issue.prefix}`);
1538
- const found = check(cfg, catalogs, registry);
1539
- const warnings = found.broken.filter((entry) => entry.severity === "warning").length + found.extra.length;
1852
+ const found = check(cfg, catalogs, registry, buildFingerprints(cfg));
1853
+ const warnings = warningCount(found);
1540
1854
  if (warnings > 0) warnOnce(`check has ${counted(warnings, "warning")}, and the build still passes: run \`npx verbaly check\` to read them`, "gate:warnings");
1541
1855
  const result = failOnMissing === false ? {
1542
1856
  ...found,
@@ -1545,42 +1859,24 @@ function runBuildGate(cfg, registry, failOnMissing) {
1545
1859
  if (gatePasses(result)) return;
1546
1860
  throw new Error(`[verbaly] build blocked\n${formatCheckResult(result, cfg.root)}\n${checkNextSteps(result, cliReachable(cfg.root))}`);
1547
1861
  }
1548
- //#endregion
1549
- //#region src/drafts.ts
1550
- const DRAFTS_FILE = ".verbaly-drafts.json";
1551
- function draftsPath(cfg) {
1552
- return join(cfg.dir, DRAFTS_FILE);
1553
- }
1554
- function loadDrafts(cfg) {
1555
- let content;
1556
- try {
1557
- content = readFileSync(draftsPath(cfg), "utf8");
1558
- } catch {
1559
- return {};
1560
- }
1862
+ function buildFingerprints(cfg) {
1561
1863
  try {
1562
- return JSON.parse(content.replace(/^\uFEFF/, ""));
1864
+ return loadState(cfg).fingerprints;
1563
1865
  } catch (error) {
1564
- throw new Error(`[verbaly] ${draftsPath(cfg)} is not valid JSON, fix or delete the file`, { cause: error });
1866
+ warnOnce(`${error.message.replace(/^\[verbaly\] /, "")}, so outdated translations are not reported`, "gate:state");
1867
+ return {};
1565
1868
  }
1566
1869
  }
1567
- function serializeDrafts(drafts) {
1568
- const sorted = {};
1569
- for (const locale of Object.keys(drafts).sort()) {
1570
- const keys = [...new Set(drafts[locale])].sort();
1571
- if (keys.length) sorted[locale] = keys;
1572
- }
1573
- return JSON.stringify(sorted, null, 2) + "\n";
1870
+ //#endregion
1871
+ //#region src/drafts.ts
1872
+ function loadDrafts(cfg) {
1873
+ return loadState(cfg).drafts;
1574
1874
  }
1575
1875
  function saveDrafts(cfg, drafts) {
1576
- const serialized = serializeDrafts(drafts);
1577
- const path = draftsPath(cfg);
1578
- try {
1579
- if (readFileSync(path, "utf8") === serialized) return;
1580
- } catch {
1581
- mkdirSync(cfg.dir, { recursive: true });
1582
- }
1583
- writeFileSync(path, serialized);
1876
+ saveState(cfg, {
1877
+ ...loadState(cfg),
1878
+ drafts
1879
+ });
1584
1880
  }
1585
1881
  function markDrafts(drafts, locale, keys) {
1586
1882
  if (!keys.length) return;
@@ -1596,24 +1892,16 @@ function clearDrafts(drafts, locale, keys) {
1596
1892
  drafts[locale] = drafts[locale].filter((key) => !drop.has(key));
1597
1893
  if (!drafts[locale].length) delete drafts[locale];
1598
1894
  }
1599
- function effectiveDrafts(drafts, catalogs) {
1600
- const out = {};
1601
- for (const [locale, keys] of Object.entries(drafts)) {
1602
- const catalog = catalogs[locale] ?? {};
1603
- const live = keys.filter((key) => own(catalog, key));
1604
- if (live.length) out[locale] = live;
1605
- }
1606
- return out;
1607
- }
1608
1895
  //#endregion
1609
1896
  //#region src/status.ts
1610
- function status(cfg, catalogs, registry, drafts = {}) {
1897
+ function status(cfg, catalogs, registry, drafts = {}, fingerprints = {}) {
1611
1898
  const extracted = registry.messages();
1612
1899
  const flat = {};
1613
1900
  for (const locale of cfg.locales) flat[locale] = flatten(catalogs[locale] ?? {});
1614
1901
  const source = flat[cfg.sourceLocale] ?? {};
1615
1902
  const needed = /* @__PURE__ */ new Set([...extracted.keys(), ...Object.keys(source)]);
1616
1903
  const live = effectiveDrafts(drafts, flat);
1904
+ const outdated = outdatedTranslations(cfg, flat, fingerprints);
1617
1905
  const locales = [];
1618
1906
  for (const locale of cfg.locales) {
1619
1907
  if (locale === cfg.sourceLocale) continue;
@@ -1631,7 +1919,8 @@ function status(cfg, catalogs, registry, drafts = {}) {
1631
1919
  translated,
1632
1920
  total: needed.size,
1633
1921
  drafts: live[locale]?.length ?? 0,
1634
- broken
1922
+ broken,
1923
+ outdated: outdated.filter((entry) => entry.locale === locale).length
1635
1924
  });
1636
1925
  }
1637
1926
  return {
@@ -1646,10 +1935,14 @@ function formatStatusResult(result) {
1646
1935
  lines.push(" no target locales (add locales to your config)");
1647
1936
  return lines.join("\n");
1648
1937
  }
1649
- for (const { locale, translated, total, drafts, broken } of result.locales) {
1938
+ for (const { locale, translated, total, drafts, broken, outdated } of result.locales) {
1650
1939
  const pct = total === 0 ? 100 : Math.floor(translated / total * 100);
1651
- const mark = translated === total && broken === 0 ? " ✓" : "";
1652
- const notes = [drafts > 0 ? `${drafts} unreviewed` : "", broken > 0 ? `${broken} broken` : ""].filter(Boolean);
1940
+ const mark = translated === total && broken === 0 && outdated === 0 ? " ✓" : "";
1941
+ const notes = [
1942
+ drafts > 0 ? `${drafts} unreviewed` : "",
1943
+ broken > 0 ? `${broken} broken` : "",
1944
+ outdated > 0 ? `${outdated} outdated` : ""
1945
+ ].filter(Boolean);
1653
1946
  const note = notes.length > 0 ? `, ${notes.join(", ")}` : "";
1654
1947
  lines.push(` ${locale}: ${translated}/${total} translated (${pct}%${note})${mark}`);
1655
1948
  }
@@ -1781,6 +2074,18 @@ async function doctor(cfg) {
1781
2074
  const files = [...new Set(stray.map((entry) => rel(entry.file)))];
1782
2075
  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");
1783
2076
  }
2077
+ const missed = registry.missed();
2078
+ if (missed.length > 0) {
2079
+ const locate = createLocator();
2080
+ 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");
2083
+ }
2084
+ const positional = [...registry.messages().values()].filter((msg) => msg.params.some((param) => /^_\d+$/.test(param.name)));
2085
+ if (positional.length > 0) {
2086
+ 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}");
2088
+ }
1784
2089
  const escaped = [...registry.messages().values()].map((msg) => ({
1785
2090
  file: rel(msg.file),
1786
2091
  slice: escapedSyntax(msg.message)
@@ -1801,8 +2106,24 @@ async function doctor(cfg) {
1801
2106
  for (const issue of issues) warn("bundle", formatBundleIssue(issue), issue.fix);
1802
2107
  if (issues.length === 0) ok("bundle", `${counted(excluded.length, "group")} kept out of the client (${preview(excluded)})`);
1803
2108
  }
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
+ }
2118
+ if (catalogsHealthy) {
2119
+ const stale = Object.entries(state.drafts).flatMap(([locale, keys]) => {
2120
+ const live = new Set(effectiveDrafts({ [locale]: keys }, catalogs)[locale] ?? []);
2121
+ return keys.filter((key) => !live.has(key)).map((key) => `${locale}: ${key}`);
2122
+ });
2123
+ 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");
2124
+ }
1804
2125
  if (catalogsHealthy) {
1805
- const result = check(cfg, catalogs, registry);
2126
+ const result = check(cfg, catalogs, registry, state.fingerprints);
1806
2127
  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)");
1807
2128
  if (result.missing.length > 0) {
1808
2129
  const locales = [...new Set(result.missing.map((m) => m.locale))];
@@ -1819,6 +2140,18 @@ async function doctor(cfg) {
1819
2140
  }
1820
2141
  const warnings = result.broken.filter((entry) => entry.severity === "warning");
1821
2142
  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");
2143
+ if (result.collisions.length > 0) {
2144
+ const first = result.collisions[0];
2145
+ 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)");
2146
+ }
2147
+ if (result.divergent.length > 0) {
2148
+ const first = result.divergent[0];
2149
+ 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");
2150
+ }
2151
+ if (result.outdated.length > 0) {
2152
+ const shown = result.outdated.map((entry) => `${entry.locale}: ${entry.key}`);
2153
+ 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`");
2154
+ }
1822
2155
  if (result.ok) ok("translations", "all translations complete");
1823
2156
  }
1824
2157
  return {
@@ -1959,6 +2292,35 @@ function mergeTranslations(cfg, locale, translated, keys) {
1959
2292
  if (written.length > 0) writeCatalog(cfg, locale, current);
1960
2293
  return written;
1961
2294
  }
2295
+ function writeDrafts(cfg, locale, entries, options = {}) {
2296
+ const targets = targetLocales(cfg);
2297
+ 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);
2299
+ const current = readCatalog(cfg, locale);
2300
+ const result = {
2301
+ written: [],
2302
+ kept: [],
2303
+ invalid: [],
2304
+ unknown: []
2305
+ };
2306
+ for (const { key, text } of entries) {
2307
+ const from = own(source, key);
2308
+ if (!from) result.unknown.push(key);
2309
+ else if (!text.trim() || !structureMatches(from, text)) result.invalid.push(key);
2310
+ else if (own(current, key) && !options.overwrite) result.kept.push(key);
2311
+ else {
2312
+ current[key] = text;
2313
+ result.written.push(key);
2314
+ }
2315
+ }
2316
+ if (result.written.length > 0) {
2317
+ writeCatalog(cfg, locale, current);
2318
+ const drafts = loadDrafts(cfg);
2319
+ markDrafts(drafts, locale, result.written);
2320
+ saveDrafts(cfg, drafts);
2321
+ }
2322
+ return result;
2323
+ }
1962
2324
  function formatTranslateFailures(failed) {
1963
2325
  const grouped = [];
1964
2326
  for (const entry of failed) {
@@ -2776,6 +3138,6 @@ function formatCliError(error) {
2776
3138
  return message.startsWith("[verbaly]") ? message : `[verbaly] ${message}`;
2777
3139
  }
2778
3140
  //#endregion
2779
- export { DRAFTS_FILE, LOCALE_MODULE_PREFIX, MessageRegistry, RESOLVED_VIRTUAL_ID, SOURCE_FILE_RE, check, clearDrafts, clientCatalogs, collectOrigins, counted, createSourceFilter, doctor, effectiveDrafts, extractProject, formatCheckResult, formatCheckWarnings, formatCliError, formatDoctorEntry, formatRenderWarnings, formatStatusResult, formatTranslateFailures, generateDts, generateLocaleModule, generateRuntimeModule, init, isTransformTarget, loadCatalogs, loadConfig, loadDrafts, loadVirtualModule, markDrafts, mergeTranslations, needsIcu, needsRelative, parseCatalog, pruneCatalogs, readCatalog, renderSite, resolveConfig, resolveProvider, resolveVirtualId, runBuildGate, saveDrafts, stableKey, status, syncCatalogs, targetLocales, transformCode, transformSource, translateCatalogs, validateMessage, validatePair, watchTree, wrapProject, writeCatalog, writeDts };
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 };
2780
3142
 
2781
3143
  //# sourceMappingURL=index.js.map