@verbaly/compiler 0.69.1 → 0.71.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 findConfigFile, c as loadConfigFile, d as WIRING_PACKAGES, f as detectHost, i as SOURCE_EXTENSIONS, l as resolveConfig, m as readDependencies, n as counted, p as installCommand, r as truncate, s as loadConfig, t as byCodeUnit, u as targetLocales } from "./text-Bh96y7ik.js";
1
+ import { a as findConfigFile, c as loadConfigFile, d as WIRING_PACKAGES, f as detectHost, i as SOURCE_EXTENSIONS, l as resolveConfig, m as readDependencies, n as counted, p as installCommand, r as truncate, s as loadConfig, t as byCodeUnit, u as targetLocales } from "./text-dwjJ8ZDb.js";
2
2
  import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, rmSync, watch, writeFileSync } from "node:fs";
3
3
  import { dirname, join, relative, resolve, sep } 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";
@@ -356,7 +356,10 @@ function analyzeScript(code, file, options = {}) {
356
356
  return;
357
357
  }
358
358
  const key = staticString(args[0]);
359
- if (key !== void 0) usedKeys.push(usedKey(key, file, args[0]));
359
+ if (key !== void 0) usedKeys.push({
360
+ key,
361
+ file
362
+ });
360
363
  } else if (node.type === "JSXElement") handleTrans(code, node, file, tagged, usedKeys, names);
361
364
  });
362
365
  const renamed = bindings.renamed(options.renamed);
@@ -365,8 +368,7 @@ function analyzeScript(code, file, options = {}) {
365
368
  if (candidate.kind === "call") {
366
369
  if (renamed.has(candidate.name)) usedKeys.push({
367
370
  key: candidate.key,
368
- file,
369
- loose: true
371
+ file
370
372
  });
371
373
  continue;
372
374
  }
@@ -508,8 +510,7 @@ function missedKey(code, node, names) {
508
510
  const tag = node.tag;
509
511
  if (tag.type === "CallExpression") {
510
512
  const args = tag.arguments;
511
- const first = args[0];
512
- return args.length === 1 && first?.type === "StringLiteral" ? first.value : void 0;
513
+ return args.length === 1 ? staticString(args[0]) : void 0;
513
514
  }
514
515
  const message = buildMessage(code, node.quasi, names);
515
516
  return message ? stableKey(message.text) : void 0;
@@ -521,20 +522,13 @@ function collectDeclaredKeys(node, file, out) {
521
522
  const value = property.value;
522
523
  const key = staticString(value);
523
524
  if (key !== void 0) {
524
- if (key !== "") out.push(usedKey(key, file, value));
525
+ if (key !== "") out.push({
526
+ key,
527
+ file
528
+ });
525
529
  } else if (value.type === "ObjectExpression") collectDeclaredKeys(value, file, out);
526
530
  }
527
531
  }
528
- function usedKey(key, file, node) {
529
- return node?.type === "StringLiteral" ? {
530
- key,
531
- file
532
- } : {
533
- key,
534
- file,
535
- loose: true
536
- };
537
- }
538
532
  function staticString(node) {
539
533
  if (!node) return void 0;
540
534
  if (node.type === "StringLiteral") return node.value;
@@ -583,14 +577,17 @@ function handleTrans(code, node, file, tagged, usedKeys, names) {
583
577
  const value = idAttr.value;
584
578
  const id = staticString(value);
585
579
  if (id === void 0) return;
586
- if (value?.type === "StringLiteral" && attrs.length === 1 && children?.length) {
580
+ if (attrs.length === 1 && children?.length) {
587
581
  const built = buildTransMessage(code, children, names);
588
582
  if (built?.text.trim()) {
589
583
  push(id, built);
590
584
  return;
591
585
  }
592
586
  }
593
- usedKeys.push(usedKey(id, file, value));
587
+ usedKeys.push({
588
+ key: id,
589
+ file
590
+ });
594
591
  return;
595
592
  }
596
593
  if (attrs.length > 0) return;
@@ -608,10 +605,10 @@ function explicitId(tag, names) {
608
605
  const obj = callee.object;
609
606
  if (!isTReference(obj, names)) return void 0;
610
607
  const args = tag.arguments;
611
- const first = args[0];
612
- if (args.length !== 1 || first?.type !== "StringLiteral") return void 0;
608
+ const key = args.length === 1 ? staticString(args[0]) : void 0;
609
+ if (key === void 0) return void 0;
613
610
  return {
614
- key: first.value,
611
+ key,
615
612
  refStart: obj.start,
616
613
  refEnd: obj.end
617
614
  };
@@ -1389,6 +1386,9 @@ export async function createRequestInstance(locale) {
1389
1386
 
1390
1387
  const v = createInstance();
1391
1388
 
1389
+ // a hook with no provider above it (a test, a story) reads this one; a server never registers it
1390
+ if (typeof document !== 'undefined') globalThis[Symbol.for('verbaly.app')] = v;
1391
+
1392
1392
  export const verbaly = v;
1393
1393
  export const t = v.t;
1394
1394
 
@@ -1421,6 +1421,9 @@ function generateDts(catalog, options = {}) {
1421
1421
  }
1422
1422
  }
1423
1423
  return `${DTS_HEADER}
1424
+ // biome-ignore-all lint: generated by verbaly
1425
+ // biome-ignore-all format: generated by verbaly
1426
+ // prettier-ignore
1424
1427
  declare module 'virtual:verbaly' {
1425
1428
  export interface VerbalyMessages {
1426
1429
  ${lines.join("\n")}
@@ -1450,28 +1453,28 @@ ${lines.join("\n")}
1450
1453
  ): import('verbaly').Verbaly;
1451
1454
  export function createRequestInstance(locale: string): Promise<import('verbaly').Verbaly>;
1452
1455
 
1453
- // a key written as a literal must exist; string, or a template with a part from data, is data
1454
- export function t<K extends VerbalyKey | TemplateStringsArray | (string & {})>(
1455
- first: K extends TemplateStringsArray
1456
- ? K
1457
- : {} extends Record<K & string, 1>
1456
+ // a literal key must exist; a string, a template with data in it or a union of keys is data
1457
+ export const t: {
1458
+ <K extends VerbalyKey | TemplateStringsArray | (string & {})>(
1459
+ first: K extends TemplateStringsArray
1458
1460
  ? K
1459
- : K extends VerbalyKey ? K : VerbalyKey,
1460
- ...rest: [K] extends [never]
1461
- ? [params?: import('verbaly').Params]
1462
- : K extends TemplateStringsArray
1463
- ? unknown[]
1464
1461
  : {} extends Record<K & string, 1>
1465
- ? [params?: import('verbaly').Params]
1466
- : K extends VerbalyKey
1467
- ? [VerbalyMessages[K]] extends [never] ? [] : [VerbalyMessages[K]]
1468
- : unknown[]
1469
- ): string;
1470
- export namespace t {
1471
- export function id(
1472
- key: string,
1473
- ): (strings: TemplateStringsArray, ...values: unknown[]) => string;
1474
- }
1462
+ ? K
1463
+ : K extends VerbalyKey ? K : VerbalyKey,
1464
+ ...rest: [K] extends [never]
1465
+ ? [params?: import('verbaly').Params]
1466
+ : [K] extends [(K extends unknown ? (key: K) => void : never) extends (key: infer One) => void ? One : never]
1467
+ ? K extends TemplateStringsArray
1468
+ ? unknown[]
1469
+ : {} extends Record<K & string, 1>
1470
+ ? [params?: import('verbaly').Params]
1471
+ : K extends VerbalyKey
1472
+ ? [VerbalyMessages[K]] extends [never] ? [] : [VerbalyMessages[K]]
1473
+ : unknown[]
1474
+ : [params?: import('verbaly').Params]
1475
+ ): string;
1476
+ id(key: string): (strings: TemplateStringsArray, ...values: unknown[]) => string;
1477
+ };
1475
1478
 
1476
1479
  export function setLocale(locale: string): Promise<void>;
1477
1480
  export function switchLocale(
@@ -1493,6 +1496,7 @@ ${lines.join("\n")}
1493
1496
  }
1494
1497
  }
1495
1498
 
1499
+ // prettier-ignore
1496
1500
  declare module 'virtual:verbaly/locale/*' {
1497
1501
  const messages: Record<string, string>;
1498
1502
  export default messages;
@@ -1631,6 +1635,10 @@ function formatFinding(finding, root) {
1631
1635
  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)`;
1632
1636
  case "unparsed": return `${sourcePlace(finding, root)}: could not be parsed (${finding.message}), its messages were not extracted`;
1633
1637
  case "outdated": return `[${finding.locale}] ${finding.key}: translated from an older source text, update it or keep it with \`npx verbaly review --approve\``;
1638
+ case "lock": {
1639
+ const lock = sourcePlace(finding, root);
1640
+ return finding.from ? `${sourcePlace({ file: finding.from }, root)} moved to ${lock}, next to your config: commit both changes` : `${lock} now keeps the source text each translation was made for and which ones are drafts: commit it with your catalogs`;
1641
+ }
1634
1642
  }
1635
1643
  }
1636
1644
  function findingId(finding) {
@@ -1642,6 +1650,7 @@ function findingId(finding) {
1642
1650
  case "positional": return `positional:${finding.site.file}:${finding.params.join(",")}`;
1643
1651
  case "escaped": return `escaped:${finding.site.file}:${finding.slice}`;
1644
1652
  case "unparsed": return `unparsed:${finding.file}`;
1653
+ case "lock": return `lock:${finding.file}`;
1645
1654
  }
1646
1655
  }
1647
1656
  function createDevReporter(root, print = (line) => console.warn(`[verbaly] ${line}`), cap = 5) {
@@ -1663,26 +1672,52 @@ function createDevReporter(root, print = (line) => console.warn(`[verbaly] ${lin
1663
1672
  }
1664
1673
  //#endregion
1665
1674
  //#region src/state.ts
1666
- const STATE_FILE = ".verbaly-state.json";
1675
+ const STATE_FILE = "verbaly.lock";
1676
+ const LOCK_VERSION = 1;
1677
+ const README = "Written by Verbaly: the source text each translation was made for, which ones are drafts, and which languages migrate converted. Commit it with your catalogs and never edit it: deleting it marks every draft as reviewed.";
1678
+ const LEGACY_STATE_FILE = ".verbaly-state.json";
1667
1679
  const LEGACY_DRAFTS_FILE = ".verbaly-drafts.json";
1668
- function statePath(cfg, file = STATE_FILE) {
1669
- return join(cfg.dir, file);
1680
+ function statePath(cfg) {
1681
+ return join(cfg.root, STATE_FILE);
1682
+ }
1683
+ function legacyPaths(cfg) {
1684
+ return [join(cfg.dir, LEGACY_STATE_FILE), join(cfg.dir, LEGACY_DRAFTS_FILE)];
1670
1685
  }
1671
1686
  function loadState(cfg) {
1672
- const current = readJson(statePath(cfg));
1673
- if (current !== void 0 && !isObject(current)) throw corrupt(statePath(cfg));
1674
- const legacy = readJson(statePath(cfg, LEGACY_DRAFTS_FILE));
1675
- if (legacy !== void 0 && !isObject(legacy)) throw corrupt(statePath(cfg, LEGACY_DRAFTS_FILE));
1676
- const state = isObject(current) ? {
1677
- drafts: readDrafts(current.drafts),
1678
- fingerprints: readFingerprints(current.fingerprints)
1679
- } : {
1687
+ const lock = readObject(statePath(cfg));
1688
+ if (lock) checkVersion(statePath(cfg), lock.version);
1689
+ const [legacyState, legacyDrafts] = legacyPaths(cfg).map(readObject);
1690
+ const state = {
1680
1691
  drafts: {},
1681
1692
  fingerprints: {}
1682
1693
  };
1683
- if (legacy !== void 0) for (const [locale, keys] of Object.entries(readDrafts(legacy))) markDrafts(state.drafts, locale, keys);
1694
+ for (const source of [lock, legacyState]) {
1695
+ if (!source) continue;
1696
+ for (const [locale, keys] of Object.entries(readDrafts(source.drafts))) markDrafts(state.drafts, locale, keys);
1697
+ for (const [locale, stamps] of Object.entries(readFingerprints(source.fingerprints))) {
1698
+ const into = state.fingerprints[locale] ??= emptyCatalog();
1699
+ for (const [key, stamped] of Object.entries(stamps)) if (own(into, key) === void 0) into[key] = stamped;
1700
+ }
1701
+ const migrated = readMigrated(source.migrated);
1702
+ if (migrated) state.migrated = [.../* @__PURE__ */ new Set([...state.migrated ?? [], ...migrated])];
1703
+ }
1704
+ if (legacyDrafts) for (const [locale, keys] of Object.entries(readDrafts(legacyDrafts))) markDrafts(state.drafts, locale, keys);
1684
1705
  return state;
1685
1706
  }
1707
+ function stateFile(cfg) {
1708
+ return [statePath(cfg), ...legacyPaths(cfg)].find((path) => existsSync(path));
1709
+ }
1710
+ function lockNews(cfg, before) {
1711
+ const lock = statePath(cfg);
1712
+ if (before === lock || !existsSync(lock)) return void 0;
1713
+ return before ? {
1714
+ file: lock,
1715
+ from: before
1716
+ } : { file: lock };
1717
+ }
1718
+ function checkVersion(path, version) {
1719
+ if (typeof version === "number" && version > LOCK_VERSION) throw new Error(`[verbaly] ${path} was written by a newer Verbaly (format ${version}): update @verbaly/compiler to read it`);
1720
+ }
1686
1721
  function readState(cfg) {
1687
1722
  try {
1688
1723
  return { state: loadState(cfg) };
@@ -1699,21 +1734,23 @@ function readState(cfg) {
1699
1734
  function saveState(cfg, state) {
1700
1735
  const fresh = serializeState(state);
1701
1736
  const path = statePath(cfg);
1702
- const legacy = statePath(cfg, LEGACY_DRAFTS_FILE);
1737
+ const legacy = legacyPaths(cfg);
1703
1738
  if (fresh === void 0) {
1704
- rmSync(path, { force: true });
1705
- rmSync(legacy, { force: true });
1739
+ for (const file of [path, ...legacy]) rmSync(file, { force: true });
1706
1740
  return;
1707
1741
  }
1708
- let existing;
1742
+ const existing = readText(path);
1743
+ if (existing === void 0) mkdirSync(cfg.root, { recursive: true });
1744
+ const serialized = withLineEndings(fresh, existing ?? legacy.map(readText).find((text) => text !== void 0));
1745
+ if (existing !== serialized) writeFileSync(path, serialized);
1746
+ for (const file of legacy) rmSync(file, { force: true });
1747
+ }
1748
+ function readText(path) {
1709
1749
  try {
1710
- existing = readFileSync(path, "utf8");
1750
+ return readFileSync(path, "utf8");
1711
1751
  } catch {
1712
- mkdirSync(cfg.dir, { recursive: true });
1752
+ return;
1713
1753
  }
1714
- const serialized = withLineEndings(fresh, existing);
1715
- if (existing !== serialized) writeFileSync(path, serialized);
1716
- if (existsSync(legacy)) rmSync(legacy);
1717
1754
  }
1718
1755
  function updateState(cfg, catalogs) {
1719
1756
  const next = refreshState(cfg, catalogs, loadState(cfg));
@@ -1741,7 +1778,8 @@ function refreshState(cfg, catalogs, previous) {
1741
1778
  }
1742
1779
  return {
1743
1780
  drafts,
1744
- fingerprints
1781
+ fingerprints,
1782
+ migrated: previous.migrated
1745
1783
  };
1746
1784
  }
1747
1785
  function refreshStamps(source, catalog, before) {
@@ -1850,24 +1888,28 @@ function serializeState(state) {
1850
1888
  if (!keys.length) continue;
1851
1889
  fingerprints[locale] = Object.fromEntries(keys.map((key) => [key, entries[key]]));
1852
1890
  }
1853
- const out = {};
1891
+ const migrated = [...new Set(state.migrated ?? [])].sort();
1892
+ if (!Object.keys(drafts).length && !Object.keys(fingerprints).length && !migrated.length) return;
1893
+ const out = {
1894
+ _readme: README,
1895
+ version: LOCK_VERSION
1896
+ };
1854
1897
  if (Object.keys(drafts).length) out.drafts = drafts;
1855
1898
  if (Object.keys(fingerprints).length) out.fingerprints = fingerprints;
1856
- if (!out.drafts && !out.fingerprints) return void 0;
1899
+ if (migrated.length) out.migrated = migrated;
1857
1900
  return JSON.stringify(out, null, 2) + "\n";
1858
1901
  }
1859
- function readJson(path) {
1860
- let content;
1861
- try {
1862
- content = readFileSync(path, "utf8");
1863
- } catch {
1864
- return;
1865
- }
1902
+ function readObject(path) {
1903
+ const content = readText(path);
1904
+ if (content === void 0) return void 0;
1905
+ let value;
1866
1906
  try {
1867
- return JSON.parse(content.charCodeAt(0) === 65279 ? content.slice(1) : content);
1907
+ value = JSON.parse(content.charCodeAt(0) === 65279 ? content.slice(1) : content);
1868
1908
  } catch (error) {
1869
1909
  throw corrupt(path, error);
1870
1910
  }
1911
+ if (!isObject(value)) throw corrupt(path);
1912
+ return value;
1871
1913
  }
1872
1914
  function corrupt(path, cause) {
1873
1915
  return new Error(`[verbaly] ${path} is not valid JSON: restore it from git or fix it (deleting it approves every draft)`, { cause });
@@ -1881,6 +1923,11 @@ function readDrafts(value) {
1881
1923
  for (const [locale, keys] of Object.entries(value)) if (Array.isArray(keys)) out[locale] = keys.filter((key) => typeof key === "string");
1882
1924
  return out;
1883
1925
  }
1926
+ function readMigrated(value) {
1927
+ if (!Array.isArray(value)) return void 0;
1928
+ const locales = value.filter((locale) => typeof locale === "string");
1929
+ return locales.length ? locales : void 0;
1930
+ }
1884
1931
  function readFingerprints(value) {
1885
1932
  const out = {};
1886
1933
  if (!isObject(value)) return out;
@@ -1919,11 +1966,17 @@ async function syncProject(cfg, options = {}) {
1919
1966
  result.written[locale] = writeCatalog(cfg, locale, catalogs[locale] ?? {});
1920
1967
  }
1921
1968
  writeDts(cfg, catalogs[cfg.sourceLocale] ?? {});
1969
+ const before = stateFile(cfg);
1922
1970
  try {
1923
1971
  result.state = updateState(cfg, catalogs);
1924
1972
  } catch (error) {
1925
1973
  result.stateProblem = error.message.replace(/^\[verbaly\] /, "");
1926
1974
  }
1975
+ const news = lockNews(cfg, before);
1976
+ if (news) result.findings.push({
1977
+ kind: "lock",
1978
+ ...news
1979
+ });
1927
1980
  return result;
1928
1981
  }
1929
1982
  function confirmFromDisk(cfg, catalogs, registry) {
@@ -1942,6 +1995,42 @@ function confirmFromDisk(cfg, catalogs, registry) {
1942
1995
  }
1943
1996
  }
1944
1997
  //#endregion
1998
+ //#region src/migrate.ts
1999
+ const KNOWN = [
2000
+ "i18next",
2001
+ "react-i18next",
2002
+ "vue-i18n",
2003
+ "react-intl",
2004
+ "next-intl",
2005
+ "svelte-i18n"
2006
+ ];
2007
+ function detectLibraries(root) {
2008
+ const path = join(root, "package.json");
2009
+ if (!existsSync(path)) return [];
2010
+ let manifest;
2011
+ try {
2012
+ manifest = JSON.parse(readFileSync(path, "utf8"));
2013
+ } catch {
2014
+ return [];
2015
+ }
2016
+ const deps = {
2017
+ ...manifest.dependencies,
2018
+ ...manifest.devDependencies
2019
+ };
2020
+ return KNOWN.filter((name) => deps[name] !== void 0);
2021
+ }
2022
+ const PLAIN = /\{\{\s*([A-Za-z_$][\w$]*)\s*\}\}/g;
2023
+ new RegExp(/\{\{[^{}]*\}\}/.source, "g");
2024
+ new RegExp(`^${PLAIN.source}$`);
2025
+ new RegExp(`^(.*)_(${[...[
2026
+ "zero",
2027
+ "one",
2028
+ "two",
2029
+ "few",
2030
+ "many",
2031
+ "other"
2032
+ ], "plural"].join("|")})$`);
2033
+ //#endregion
1945
2034
  //#region src/tag.ts
1946
2035
  function isLocaleTag(tag) {
1947
2036
  try {
@@ -1957,6 +2046,27 @@ function suggestTag(tag) {
1957
2046
  }
1958
2047
  //#endregion
1959
2048
  //#region src/init.ts
2049
+ const CATALOG_DIRS = [
2050
+ "locales",
2051
+ "src/locales",
2052
+ "src/i18n/locales",
2053
+ "src/i18n",
2054
+ "i18n",
2055
+ "lang",
2056
+ "src/lang",
2057
+ "translations",
2058
+ "src/translations",
2059
+ "messages"
2060
+ ];
2061
+ function existingCatalogs(root) {
2062
+ return CATALOG_DIRS.find((dir) => {
2063
+ try {
2064
+ return readdirSync(join(root, dir)).some((file) => file.endsWith(".json") && isLocaleTag(file.slice(0, -5)));
2065
+ } catch {
2066
+ return false;
2067
+ }
2068
+ });
2069
+ }
1960
2070
  function cliReachable(root) {
1961
2071
  const bin = join(root, "node_modules", ".bin");
1962
2072
  return existsSync(join(bin, "verbaly")) || existsSync(join(bin, "verbaly.CMD"));
@@ -2005,14 +2115,19 @@ async function init(input = {}) {
2005
2115
  const existing = findConfigFile(root);
2006
2116
  const typescript = existsSync(join(root, "tsconfig.json"));
2007
2117
  const configFile = existing ?? (typescript ? "verbaly.config.ts" : "verbaly.config.mjs");
2118
+ const found = existing || options.dir ? void 0 : existingCatalogs(root);
2008
2119
  if (existing) skipped.push(existing);
2009
2120
  else {
2010
- writeFileSync(join(root, configFile), configSource(options, typescript));
2121
+ const dir = found === "locales" ? void 0 : found;
2122
+ writeFileSync(join(root, configFile), configSource({
2123
+ ...options,
2124
+ dir: options.dir ?? dir
2125
+ }, typescript));
2011
2126
  created.push(configFile);
2012
2127
  }
2013
2128
  const fromFile = existing ? await loadConfigFile(root) : {};
2014
2129
  const scaffold = {
2015
- dir: options.dir ?? fromFile.dir,
2130
+ dir: options.dir ?? fromFile.dir ?? found,
2016
2131
  sourceLocale: options.sourceLocale ?? fromFile.sourceLocale,
2017
2132
  locales: options.locales ?? fromFile.locales
2018
2133
  };
@@ -2028,7 +2143,11 @@ async function init(input = {}) {
2028
2143
  }
2029
2144
  }
2030
2145
  const host = detectHost(root);
2031
- const next = host ? [installCommand(root, host.install), host.wire] : ["run \"verbaly extract\" after writing your first t`…` message"];
2146
+ const deps = readDependencies(root);
2147
+ const missing = host?.install.filter((pkg) => !deps[pkg]) ?? [];
2148
+ const next = host ? [...missing.length ? [installCommand(root, missing)] : [], host.wire] : ["run \"verbaly extract\" after writing your first t`…` message"];
2149
+ const others = detectLibraries(root);
2150
+ if (found && others.length) next.push(`port the ${others.join(" and ")} catalogs: npx verbaly migrate reports, --write applies`);
2032
2151
  return {
2033
2152
  created,
2034
2153
  skipped,
@@ -2036,16 +2155,17 @@ async function init(input = {}) {
2036
2155
  configFile,
2037
2156
  next,
2038
2157
  renamed,
2039
- refused
2158
+ refused,
2159
+ found
2040
2160
  };
2041
2161
  }
2042
2162
  //#endregion
2043
2163
  //#region src/check.ts
2044
2164
  function gatePasses(result) {
2045
- return result.missing.length === 0 && result.unknown.length === 0 && !result.broken.some((entry) => entry.severity === "error");
2165
+ return result.missing.length === 0 && result.unknown.length === 0 && result.collisions.length === 0 && !result.broken.some((entry) => entry.severity === "error");
2046
2166
  }
2047
2167
  function warningCount(result) {
2048
- return result.broken.filter((entry) => entry.severity === "warning").length + result.extra.length + result.collisions.length + result.divergent.length + result.outdated.length;
2168
+ return result.broken.filter((entry) => entry.severity === "warning").length + result.extra.length + result.divergent.length + result.outdated.length;
2049
2169
  }
2050
2170
  function check(cfg, catalogs, registry, fingerprints = {}) {
2051
2171
  const extracted = registry.messages();
@@ -2115,17 +2235,19 @@ function check(cfg, catalogs, registry, fingerprints = {}) {
2115
2235
  });
2116
2236
  }
2117
2237
  }
2238
+ const collisions = collisionEntries(registry);
2118
2239
  return {
2119
2240
  ok: gatePasses({
2120
2241
  missing,
2121
2242
  unknown,
2122
- broken
2243
+ broken,
2244
+ collisions
2123
2245
  }),
2124
2246
  missing,
2125
2247
  unknown,
2126
2248
  broken,
2127
2249
  extra,
2128
- collisions: collisionEntries(registry),
2250
+ collisions,
2129
2251
  divergent,
2130
2252
  outdated: outdatedTranslations(cfg, shipped, fingerprints)
2131
2253
  };
@@ -2149,23 +2271,54 @@ function formatCheckResult(result, root) {
2149
2271
  lines.push("broken translations:");
2150
2272
  for (const entry of errors) lines.push(` [${entry.locale}] ${entry.key}: ${entry.issue}`);
2151
2273
  }
2274
+ if (result.collisions.length > 0) {
2275
+ lines.push("keys written with more than one text:");
2276
+ for (const entry of result.collisions) lines.push(` ${formatCollision(entry, root)}`);
2277
+ }
2152
2278
  return lines.join("\n");
2153
2279
  }
2280
+ function formatBuildReport(result, sourceLocale, root, cap = 5) {
2281
+ const show = (file) => root ? relative(root, file).replaceAll("\\", "/") : file;
2282
+ const lines = [];
2283
+ const list = (entries, line) => {
2284
+ for (const entry of entries.slice(0, cap)) lines.push(` ${line(entry)}`);
2285
+ if (entries.length > cap) lines.push(` and ${entries.length - cap} more`);
2286
+ };
2287
+ const broken = result.broken.filter((entry) => entry.severity === "error");
2288
+ if (broken.length > 0) {
2289
+ lines.push(`✗ the build goes on with ${counted(broken.length, "broken translation")}, each rendering differently from its source:`);
2290
+ list(broken, (entry) => `[${entry.locale}] ${entry.key}: ${entry.issue}`);
2291
+ }
2292
+ if (result.collisions.length > 0) {
2293
+ lines.push(`✗ the build goes on with ${counted(result.collisions.length, "key")} written with more than one text:`);
2294
+ list(result.collisions, (entry) => formatCollision(entry, root));
2295
+ }
2296
+ const quoted = (entry) => entry.source ? `: "${truncate(entry.source, 40)}"` : "";
2297
+ const untranslated = result.missing.filter((entry) => entry.locale !== sourceLocale);
2298
+ if (untranslated.length > 0) {
2299
+ lines.push(`⚠ the build goes on without ${counted(untranslated.length, "translation")}, shown in ${sourceLocale} instead:`);
2300
+ list(untranslated, (entry) => `[${entry.locale}] ${entry.key}${quoted(entry)}`);
2301
+ }
2302
+ if (result.unknown.length > 0) {
2303
+ lines.push(`⚠ the build goes on with ${counted(result.unknown.length, "key")} no catalog has, so the key itself shows:`);
2304
+ list(result.unknown, (entry) => `${entry.key} (used in ${entry.files.map(show).join(", ")})`);
2305
+ }
2306
+ const unsynced = result.missing.filter((entry) => entry.locale === sourceLocale);
2307
+ if (unsynced.length > 0) lines.push(`⚠ the build goes on with ${counted(unsynced.length, "text")} the ${sourceLocale} catalog does not have yet, taken from the code`);
2308
+ return lines;
2309
+ }
2154
2310
  function checkNextSteps(result, cliReachable = true) {
2155
2311
  const steps = [];
2156
2312
  if (result.missing.length > 0) steps.push("missing: run `npx verbaly extract` to scaffold the keys, then fill them (or run `npx verbaly translate`)");
2157
2313
  if (result.unknown.length > 0) steps.push("unknown keys: the key used in the code is in no catalog, fix the key or run `npx verbaly extract`");
2158
2314
  if (result.broken.some((entry) => entry.severity === "error")) steps.push("broken: a translation has to keep the params, tags and plural cases of its source message");
2315
+ if (result.collisions.length > 0) steps.push("collisions: give each text its own key in t.id(…), or write the same text in every place");
2159
2316
  if (steps.length > 0 && !cliReachable) steps.push(`the verbaly command is not linked in this project: ${CLI_INSTALL_FIX}`);
2160
2317
  return steps.join("\n");
2161
2318
  }
2162
2319
  function formatCheckWarnings(result, root, options = {}) {
2163
2320
  const lines = result.broken.filter((entry) => entry.severity === "warning").map((entry) => ` [${entry.locale}] ${entry.key}: ${entry.issue}`);
2164
2321
  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`);
2165
- for (const entry of result.collisions) lines.push(` ${formatFinding({
2166
- kind: "collision",
2167
- ...entry
2168
- }, root)}`);
2169
2322
  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)`);
2170
2323
  if (!options.outdatedFails) for (const entry of result.outdated) lines.push(` ${formatFinding({
2171
2324
  kind: "outdated",
@@ -2247,14 +2400,40 @@ function runBuildGate(cfg, registry, failOnMissing) {
2247
2400
  const catalogs = loadCatalogs(cfg);
2248
2401
  for (const issue of auditBundle(cfg, catalogs, registry)) warnOnce(`${formatBundleIssue(issue)}\n fix: ${issue.fix}`, `bundle:${issue.prefix}`);
2249
2402
  const found = check(cfg, catalogs, registry, buildFingerprints(cfg));
2403
+ if (failOnMissing === true && !gatePasses(found)) throw new Error(`[verbaly] build blocked\n${formatCheckResult(found, cfg.root)}\n${checkNextSteps(found, cliReachable(cfg.root))}`);
2404
+ reportGate(cfg, found);
2250
2405
  const warnings = warningCount(found);
2251
2406
  if (warnings > 0) warnOnce(`check has ${counted(warnings, "warning")}, and the build still passes: run \`npx verbaly check\` to read them`, "gate:warnings");
2252
- const result = failOnMissing === false ? {
2407
+ }
2408
+ const reported = /* @__PURE__ */ new Map();
2409
+ function reportGate(cfg, found) {
2410
+ const before = reported.get(cfg.root) ?? /* @__PURE__ */ new Set();
2411
+ const now = /* @__PURE__ */ new Set();
2412
+ const fresh = (entries, id) => entries.filter((entry) => {
2413
+ const key = id(entry);
2414
+ now.add(key);
2415
+ return !before.has(key);
2416
+ });
2417
+ const report = {
2418
+ broken: fresh(found.broken.filter((entry) => entry.severity === "error"), (entry) => `broken:${entry.locale}:${entry.key}:${entry.issue}`),
2419
+ missing: fresh(found.missing, (entry) => `missing:${entry.locale}:${entry.key}`),
2420
+ unknown: fresh(found.unknown, (entry) => `unknown:${entry.key}`),
2421
+ collisions: fresh(found.collisions, (entry) => `collision:${entry.key}`)
2422
+ };
2423
+ reported.set(cfg.root, now);
2424
+ const lines = formatBuildReport(report, cfg.sourceLocale, cfg.root);
2425
+ if (lines.length === 0) return;
2426
+ const steps = checkNextSteps({
2253
2427
  ...found,
2254
- missing: []
2255
- } : found;
2256
- if (gatePasses(result)) return;
2257
- throw new Error(`[verbaly] build blocked\n${formatCheckResult(result, cfg.root)}\n${checkNextSteps(result, cliReachable(cfg.root))}`);
2428
+ ...report
2429
+ }, cliReachable(cfg.root));
2430
+ const block = [
2431
+ ...lines.map((line) => line.startsWith(" ") ? line : `[verbaly] ${line}`),
2432
+ "[verbaly] to fix them:",
2433
+ ...steps.split("\n").map((step) => ` ${step}`),
2434
+ "[verbaly] `npx verbaly check` lists every one, and in your CI it stops a release on them"
2435
+ ];
2436
+ console.warn(block.join("\n"));
2258
2437
  }
2259
2438
  function buildFingerprints(cfg) {
2260
2439
  const { state, problem } = readState(cfg);
@@ -2414,6 +2593,11 @@ function formatDoctorEntry(entry) {
2414
2593
  return entry.fix ? `${head}
2415
2594
  fix: ${entry.fix}` : head;
2416
2595
  }
2596
+ function formatDoctorHealth(result) {
2597
+ if (!result.ok) return "problems found";
2598
+ const warnings = result.entries.filter((entry) => entry.level === "warn").length;
2599
+ return warnings > 0 ? `setup works, with ${counted(warnings, "warning")} to read` : "setup looks healthy";
2600
+ }
2417
2601
  async function doctor(cfg) {
2418
2602
  const entries = [];
2419
2603
  const ok = (name, message) => entries.push({
@@ -2589,7 +2773,7 @@ async function doctor(cfg) {
2589
2773
  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");
2590
2774
  if (result.collisions.length > 0) {
2591
2775
  const first = result.collisions[0];
2592
- 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)");
2776
+ error("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)");
2593
2777
  }
2594
2778
  if (result.divergent.length > 0) {
2595
2779
  const first = result.divergent[0];
@@ -2790,7 +2974,7 @@ function formatTranslateFailures(failed) {
2790
2974
  async function resolveProvider(cfg, model) {
2791
2975
  const configured = cfg.translate.provider;
2792
2976
  if (typeof configured === "function") return configured;
2793
- const { claudeProvider } = await import("./claude-mvcniUPN.js");
2977
+ const { claudeProvider } = await import("./claude-CusgBHrv.js");
2794
2978
  return claudeProvider({ model: model ?? cfg.translate.model });
2795
2979
  }
2796
2980
  function structureMatches(source, translated) {
@@ -3592,6 +3776,6 @@ function formatCliError(error) {
3592
3776
  return message.startsWith("[verbaly]") ? message : `[verbaly] ${message}`;
3593
3777
  }
3594
3778
  //#endregion
3595
- 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, reportOutsideInclude, resolveConfig, resolveProvider, resolveVirtualId, runBuildGate, saveDrafts, shippedCatalogs, stableKey, status, syncCatalogs, syncProject, targetLocales, transformCode, transformSource, translateCatalogs, updateState, validateMessage, validatePair, watchTree, wrapProject, writeCatalog, writeDrafts, writeDts };
3779
+ 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, formatDoctorHealth, 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, reportOutsideInclude, resolveConfig, resolveProvider, resolveVirtualId, runBuildGate, saveDrafts, shippedCatalogs, stableKey, status, syncCatalogs, syncProject, targetLocales, transformCode, transformSource, translateCatalogs, updateState, validateMessage, validatePair, watchTree, wrapProject, writeCatalog, writeDrafts, writeDts };
3596
3780
 
3597
3781
  //# sourceMappingURL=index.js.map