@verbaly/compiler 0.70.0 → 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.d.ts CHANGED
@@ -228,7 +228,7 @@ export declare function shippedCatalogs(cfg: ResolvedConfig, catalogs: Catalogs,
228
228
  export declare function pruneCatalogs(cfg: ResolvedConfig, catalogs: Catalogs, registry: MessageRegistry): Record<string, string[]>;
229
229
  //#endregion
230
230
  //#region src/state.d.ts
231
- export declare const STATE_FILE = ".verbaly-state.json";
231
+ export declare const STATE_FILE = "verbaly.lock";
232
232
  type Drafts = Record<string, string[]>;
233
233
  type Fingerprints = Record<string, Record<string, string>>;
234
234
  interface State {
@@ -254,6 +254,10 @@ interface TranslationWrite {
254
254
  entries: WrittenTranslation[];
255
255
  draft?: boolean;
256
256
  }
257
+ interface LockEntry {
258
+ file: string;
259
+ from?: string;
260
+ }
257
261
  export declare function loadState(cfg: ResolvedConfig): State;
258
262
  export declare function readState(cfg: ResolvedConfig): StateRead;
259
263
  export declare function updateState(cfg: ResolvedConfig, catalogs: Catalogs): State;
@@ -311,7 +315,9 @@ type Finding = ({
311
315
  kind: 'unparsed';
312
316
  } & UnparsedEntry) | ({
313
317
  kind: 'outdated';
314
- } & OutdatedEntry);
318
+ } & OutdatedEntry) | ({
319
+ kind: 'lock';
320
+ } & LockEntry);
315
321
  export declare function collisionEntries(registry: MessageRegistry): CollisionEntry[];
316
322
  export declare function formatCollision({ key, sites }: CollisionEntry, root?: string): string;
317
323
  export declare function formatFinding(finding: Finding, root?: string): string;
package/dist/index.js CHANGED
@@ -1635,6 +1635,10 @@ function formatFinding(finding, root) {
1635
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)`;
1636
1636
  case "unparsed": return `${sourcePlace(finding, root)}: could not be parsed (${finding.message}), its messages were not extracted`;
1637
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
+ }
1638
1642
  }
1639
1643
  }
1640
1644
  function findingId(finding) {
@@ -1646,6 +1650,7 @@ function findingId(finding) {
1646
1650
  case "positional": return `positional:${finding.site.file}:${finding.params.join(",")}`;
1647
1651
  case "escaped": return `escaped:${finding.site.file}:${finding.slice}`;
1648
1652
  case "unparsed": return `unparsed:${finding.file}`;
1653
+ case "lock": return `lock:${finding.file}`;
1649
1654
  }
1650
1655
  }
1651
1656
  function createDevReporter(root, print = (line) => console.warn(`[verbaly] ${line}`), cap = 5) {
@@ -1667,27 +1672,52 @@ function createDevReporter(root, print = (line) => console.warn(`[verbaly] ${lin
1667
1672
  }
1668
1673
  //#endregion
1669
1674
  //#region src/state.ts
1670
- 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";
1671
1679
  const LEGACY_DRAFTS_FILE = ".verbaly-drafts.json";
1672
- function statePath(cfg, file = STATE_FILE) {
1673
- 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)];
1674
1685
  }
1675
1686
  function loadState(cfg) {
1676
- const current = readJson(statePath(cfg));
1677
- if (current !== void 0 && !isObject(current)) throw corrupt(statePath(cfg));
1678
- const legacy = readJson(statePath(cfg, LEGACY_DRAFTS_FILE));
1679
- if (legacy !== void 0 && !isObject(legacy)) throw corrupt(statePath(cfg, LEGACY_DRAFTS_FILE));
1680
- const state = isObject(current) ? {
1681
- drafts: readDrafts(current.drafts),
1682
- fingerprints: readFingerprints(current.fingerprints),
1683
- migrated: readMigrated(current.migrated)
1684
- } : {
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 = {
1685
1691
  drafts: {},
1686
1692
  fingerprints: {}
1687
1693
  };
1688
- 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);
1689
1705
  return state;
1690
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
+ }
1691
1721
  function readState(cfg) {
1692
1722
  try {
1693
1723
  return { state: loadState(cfg) };
@@ -1704,21 +1734,23 @@ function readState(cfg) {
1704
1734
  function saveState(cfg, state) {
1705
1735
  const fresh = serializeState(state);
1706
1736
  const path = statePath(cfg);
1707
- const legacy = statePath(cfg, LEGACY_DRAFTS_FILE);
1737
+ const legacy = legacyPaths(cfg);
1708
1738
  if (fresh === void 0) {
1709
- rmSync(path, { force: true });
1710
- rmSync(legacy, { force: true });
1739
+ for (const file of [path, ...legacy]) rmSync(file, { force: true });
1711
1740
  return;
1712
1741
  }
1713
- 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) {
1714
1749
  try {
1715
- existing = readFileSync(path, "utf8");
1750
+ return readFileSync(path, "utf8");
1716
1751
  } catch {
1717
- mkdirSync(cfg.dir, { recursive: true });
1752
+ return;
1718
1753
  }
1719
- const serialized = withLineEndings(fresh, existing);
1720
- if (existing !== serialized) writeFileSync(path, serialized);
1721
- if (existsSync(legacy)) rmSync(legacy);
1722
1754
  }
1723
1755
  function updateState(cfg, catalogs) {
1724
1756
  const next = refreshState(cfg, catalogs, loadState(cfg));
@@ -1857,25 +1889,27 @@ function serializeState(state) {
1857
1889
  fingerprints[locale] = Object.fromEntries(keys.map((key) => [key, entries[key]]));
1858
1890
  }
1859
1891
  const migrated = [...new Set(state.migrated ?? [])].sort();
1860
- const out = {};
1892
+ if (!Object.keys(drafts).length && !Object.keys(fingerprints).length && !migrated.length) return;
1893
+ const out = {
1894
+ _readme: README,
1895
+ version: LOCK_VERSION
1896
+ };
1861
1897
  if (Object.keys(drafts).length) out.drafts = drafts;
1862
1898
  if (Object.keys(fingerprints).length) out.fingerprints = fingerprints;
1863
1899
  if (migrated.length) out.migrated = migrated;
1864
- if (!out.drafts && !out.fingerprints && !out.migrated) return void 0;
1865
1900
  return JSON.stringify(out, null, 2) + "\n";
1866
1901
  }
1867
- function readJson(path) {
1868
- let content;
1869
- try {
1870
- content = readFileSync(path, "utf8");
1871
- } catch {
1872
- return;
1873
- }
1902
+ function readObject(path) {
1903
+ const content = readText(path);
1904
+ if (content === void 0) return void 0;
1905
+ let value;
1874
1906
  try {
1875
- return JSON.parse(content.charCodeAt(0) === 65279 ? content.slice(1) : content);
1907
+ value = JSON.parse(content.charCodeAt(0) === 65279 ? content.slice(1) : content);
1876
1908
  } catch (error) {
1877
1909
  throw corrupt(path, error);
1878
1910
  }
1911
+ if (!isObject(value)) throw corrupt(path);
1912
+ return value;
1879
1913
  }
1880
1914
  function corrupt(path, cause) {
1881
1915
  return new Error(`[verbaly] ${path} is not valid JSON: restore it from git or fix it (deleting it approves every draft)`, { cause });
@@ -1932,11 +1966,17 @@ async function syncProject(cfg, options = {}) {
1932
1966
  result.written[locale] = writeCatalog(cfg, locale, catalogs[locale] ?? {});
1933
1967
  }
1934
1968
  writeDts(cfg, catalogs[cfg.sourceLocale] ?? {});
1969
+ const before = stateFile(cfg);
1935
1970
  try {
1936
1971
  result.state = updateState(cfg, catalogs);
1937
1972
  } catch (error) {
1938
1973
  result.stateProblem = error.message.replace(/^\[verbaly\] /, "");
1939
1974
  }
1975
+ const news = lockNews(cfg, before);
1976
+ if (news) result.findings.push({
1977
+ kind: "lock",
1978
+ ...news
1979
+ });
1940
1980
  return result;
1941
1981
  }
1942
1982
  function confirmFromDisk(cfg, catalogs, registry) {
@@ -2122,10 +2162,10 @@ async function init(input = {}) {
2122
2162
  //#endregion
2123
2163
  //#region src/check.ts
2124
2164
  function gatePasses(result) {
2125
- 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");
2126
2166
  }
2127
2167
  function warningCount(result) {
2128
- 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;
2129
2169
  }
2130
2170
  function check(cfg, catalogs, registry, fingerprints = {}) {
2131
2171
  const extracted = registry.messages();
@@ -2195,17 +2235,19 @@ function check(cfg, catalogs, registry, fingerprints = {}) {
2195
2235
  });
2196
2236
  }
2197
2237
  }
2238
+ const collisions = collisionEntries(registry);
2198
2239
  return {
2199
2240
  ok: gatePasses({
2200
2241
  missing,
2201
2242
  unknown,
2202
- broken
2243
+ broken,
2244
+ collisions
2203
2245
  }),
2204
2246
  missing,
2205
2247
  unknown,
2206
2248
  broken,
2207
2249
  extra,
2208
- collisions: collisionEntries(registry),
2250
+ collisions,
2209
2251
  divergent,
2210
2252
  outdated: outdatedTranslations(cfg, shipped, fingerprints)
2211
2253
  };
@@ -2229,6 +2271,10 @@ function formatCheckResult(result, root) {
2229
2271
  lines.push("broken translations:");
2230
2272
  for (const entry of errors) lines.push(` [${entry.locale}] ${entry.key}: ${entry.issue}`);
2231
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
+ }
2232
2278
  return lines.join("\n");
2233
2279
  }
2234
2280
  function formatBuildReport(result, sourceLocale, root, cap = 5) {
@@ -2243,6 +2289,10 @@ function formatBuildReport(result, sourceLocale, root, cap = 5) {
2243
2289
  lines.push(`✗ the build goes on with ${counted(broken.length, "broken translation")}, each rendering differently from its source:`);
2244
2290
  list(broken, (entry) => `[${entry.locale}] ${entry.key}: ${entry.issue}`);
2245
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
+ }
2246
2296
  const quoted = (entry) => entry.source ? `: "${truncate(entry.source, 40)}"` : "";
2247
2297
  const untranslated = result.missing.filter((entry) => entry.locale !== sourceLocale);
2248
2298
  if (untranslated.length > 0) {
@@ -2262,16 +2312,13 @@ function checkNextSteps(result, cliReachable = true) {
2262
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`)");
2263
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`");
2264
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");
2265
2316
  if (steps.length > 0 && !cliReachable) steps.push(`the verbaly command is not linked in this project: ${CLI_INSTALL_FIX}`);
2266
2317
  return steps.join("\n");
2267
2318
  }
2268
2319
  function formatCheckWarnings(result, root, options = {}) {
2269
2320
  const lines = result.broken.filter((entry) => entry.severity === "warning").map((entry) => ` [${entry.locale}] ${entry.key}: ${entry.issue}`);
2270
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`);
2271
- for (const entry of result.collisions) lines.push(` ${formatFinding({
2272
- kind: "collision",
2273
- ...entry
2274
- }, root)}`);
2275
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)`);
2276
2323
  if (!options.outdatedFails) for (const entry of result.outdated) lines.push(` ${formatFinding({
2277
2324
  kind: "outdated",
@@ -2370,7 +2417,8 @@ function reportGate(cfg, found) {
2370
2417
  const report = {
2371
2418
  broken: fresh(found.broken.filter((entry) => entry.severity === "error"), (entry) => `broken:${entry.locale}:${entry.key}:${entry.issue}`),
2372
2419
  missing: fresh(found.missing, (entry) => `missing:${entry.locale}:${entry.key}`),
2373
- unknown: fresh(found.unknown, (entry) => `unknown:${entry.key}`)
2420
+ unknown: fresh(found.unknown, (entry) => `unknown:${entry.key}`),
2421
+ collisions: fresh(found.collisions, (entry) => `collision:${entry.key}`)
2374
2422
  };
2375
2423
  reported.set(cfg.root, now);
2376
2424
  const lines = formatBuildReport(report, cfg.sourceLocale, cfg.root);
@@ -2725,7 +2773,7 @@ async function doctor(cfg) {
2725
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");
2726
2774
  if (result.collisions.length > 0) {
2727
2775
  const first = result.collisions[0];
2728
- 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)");
2729
2777
  }
2730
2778
  if (result.divergent.length > 0) {
2731
2779
  const first = result.divergent[0];