@verbaly/compiler 0.71.0 → 0.72.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
@@ -211,7 +211,9 @@ export declare function loadConfig(root: string, overrides?: VerbalyConfig): Pro
211
211
  export declare function clientCatalogs(cfg: ResolvedConfig, catalogs: Catalogs): Catalogs;
212
212
  //#endregion
213
213
  //#region src/extract.d.ts
214
- export declare function extractProject(cfg: ResolvedConfig): Promise<MessageRegistry>;
214
+ export declare function extractProject(cfg: ResolvedConfig, options?: {
215
+ keepSource?: boolean;
216
+ }): Promise<MessageRegistry>;
215
217
  export declare function collectOrigins(cfg: ResolvedConfig, reuse?: MessageRegistry): Promise<Record<string, string[]>>;
216
218
  interface ReplacedText {
217
219
  key: string;
@@ -243,6 +245,7 @@ interface OutdatedEntry {
243
245
  interface StateRead {
244
246
  state: State;
245
247
  problem?: string;
248
+ conflict?: true;
246
249
  }
247
250
  interface WrittenTranslation {
248
251
  key: string;
@@ -257,6 +260,7 @@ interface TranslationWrite {
257
260
  interface LockEntry {
258
261
  file: string;
259
262
  from?: string;
263
+ merged?: true;
260
264
  }
261
265
  export declare function loadState(cfg: ResolvedConfig): State;
262
266
  export declare function readState(cfg: ResolvedConfig): StateRead;
@@ -391,7 +395,7 @@ export declare function resolveVirtualId(id: string): string | undefined;
391
395
  export declare function loadVirtualModule(id: string, cfg: ResolvedConfig, catalogs: Catalogs): string | undefined;
392
396
  export declare function isTransformTarget(id: string): boolean;
393
397
  export declare function createSourceFilter(cfg: ResolvedConfig): (id: string) => boolean;
394
- export declare function transformSource(code: string, id: string, registry: MessageRegistry): {
398
+ export declare function transformSource(code: string, id: string, registry: MessageRegistry, scan?: MessageRegistry): {
395
399
  messages: Catalog;
396
400
  result: TransformResult | null;
397
401
  };
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-dwjJ8ZDb.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-BMBWE8tL.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";
@@ -954,16 +954,34 @@ function stringEnd(code, start) {
954
954
  }
955
955
  //#endregion
956
956
  //#region src/extract.ts
957
- async function extractProject(cfg) {
957
+ const kept = /* @__PURE__ */ new WeakMap();
958
+ async function extractProject(cfg, options = {}) {
958
959
  const files = await glob(cfg.include, {
959
960
  cwd: cfg.root,
960
961
  ignore: cfg.exclude,
961
962
  absolute: true
962
963
  });
963
964
  const registry = new MessageRegistry();
964
- for (const file of files.sort()) registry.update(file, analyzeFile(readFileSync(file, "utf8"), file));
965
+ const read = options.keepSource ? /* @__PURE__ */ new Map() : null;
966
+ for (const file of files.sort()) {
967
+ const code = readFileSync(file, "utf8");
968
+ const analysis = analyzeFile(code, file);
969
+ registry.update(file, analysis);
970
+ read?.set(file.replaceAll("\\", "/"), {
971
+ code,
972
+ analysis
973
+ });
974
+ }
975
+ if (read) kept.set(registry, read);
965
976
  return registry;
966
977
  }
978
+ function scannedAnalysis(scan, file, code) {
979
+ const read = kept.get(scan);
980
+ const key = file.replaceAll("\\", "/");
981
+ const entry = read?.get(key);
982
+ read?.delete(key);
983
+ return entry?.code === code ? entry.analysis : void 0;
984
+ }
967
985
  async function collectOrigins(cfg, reuse) {
968
986
  const registry = reuse ?? await extractProject(cfg);
969
987
  const origins = Object.create(null);
@@ -1060,15 +1078,20 @@ function collect(nodes, out) {
1060
1078
  if (node.variants) for (const [, body] of node.variants) collect(body, out);
1061
1079
  }
1062
1080
  }
1063
- const TAG = /<(\/?)([a-zA-Z][\w-]*)(\/?)>/g;
1081
+ const TAG = /<(\/?)([a-zA-Z][\w-]*)\s*(\/?)>/g;
1082
+ const BREAK = /^(?:br|wbr)$/;
1064
1083
  function markupNames(message) {
1065
1084
  const out = /* @__PURE__ */ new Set();
1066
- for (const match of message.matchAll(TAG)) if (match[1] || match[3]) out.add(match[2]);
1085
+ for (const match of message.matchAll(TAG)) if (match[1] || match[3] || BREAK.test(match[2])) out.add(match[2]);
1067
1086
  return out;
1068
1087
  }
1069
1088
  function tagTokens(message, markup) {
1070
1089
  const out = [];
1071
- for (const match of message.matchAll(TAG)) if (markup.has(match[2])) out.push(`${match[1]}${match[2]}${match[3]}`);
1090
+ for (const [, closing, name, selfClose] of message.matchAll(TAG)) {
1091
+ if (!markup.has(name)) continue;
1092
+ if (!BREAK.test(name)) out.push(`${closing}${name}${selfClose}`);
1093
+ else if (!closing) out.push(`${name}/`);
1094
+ }
1072
1095
  return out.sort();
1073
1096
  }
1074
1097
  function surplus(a, b) {
@@ -1637,6 +1660,7 @@ function formatFinding(finding, root) {
1637
1660
  case "outdated": return `[${finding.locale}] ${finding.key}: translated from an older source text, update it or keep it with \`npx verbaly review --approve\``;
1638
1661
  case "lock": {
1639
1662
  const lock = sourcePlace(finding, root);
1663
+ if (finding.merged) return `${lock} had a merge conflict and now holds both sides, drafts and stamps included: add it to the commit that resolves the merge`;
1640
1664
  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
1665
  }
1642
1666
  }
@@ -1650,7 +1674,7 @@ function findingId(finding) {
1650
1674
  case "positional": return `positional:${finding.site.file}:${finding.params.join(",")}`;
1651
1675
  case "escaped": return `escaped:${finding.site.file}:${finding.slice}`;
1652
1676
  case "unparsed": return `unparsed:${finding.file}`;
1653
- case "lock": return `lock:${finding.file}`;
1677
+ case "lock": return `lock:${finding.merged ? "merged:" : ""}${finding.file}`;
1654
1678
  }
1655
1679
  }
1656
1680
  function createDevReporter(root, print = (line) => console.warn(`[verbaly] ${line}`), cap = 5) {
@@ -1677,6 +1701,7 @@ const LOCK_VERSION = 1;
1677
1701
  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
1702
  const LEGACY_STATE_FILE = ".verbaly-state.json";
1679
1703
  const LEGACY_DRAFTS_FILE = ".verbaly-drafts.json";
1704
+ const resolved = /* @__PURE__ */ new Set();
1680
1705
  function statePath(cfg) {
1681
1706
  return join(cfg.root, STATE_FILE);
1682
1707
  }
@@ -1684,31 +1709,51 @@ function legacyPaths(cfg) {
1684
1709
  return [join(cfg.dir, LEGACY_STATE_FILE), join(cfg.dir, LEGACY_DRAFTS_FILE)];
1685
1710
  }
1686
1711
  function loadState(cfg) {
1687
- const lock = readObject(statePath(cfg));
1688
- if (lock) checkVersion(statePath(cfg), lock.version);
1689
- const [legacyState, legacyDrafts] = legacyPaths(cfg).map(readObject);
1712
+ const lock = readSides(statePath(cfg)) ?? [];
1713
+ for (const side of lock) checkVersion(statePath(cfg), side.version);
1714
+ const [legacyState = [], legacyDrafts = []] = legacyPaths(cfg).map((path) => readSides(path) ?? []);
1690
1715
  const state = {
1691
1716
  drafts: {},
1692
1717
  fingerprints: {}
1693
1718
  };
1694
- for (const source of [lock, legacyState]) {
1695
- if (!source) continue;
1719
+ const kept = lock.length > 1 ? keptStamp(cfg) : void 0;
1720
+ [...lock, ...legacyState].forEach((source, index) => {
1696
1721
  for (const [locale, keys] of Object.entries(readDrafts(source.drafts))) markDrafts(state.drafts, locale, keys);
1697
1722
  for (const [locale, stamps] of Object.entries(readFingerprints(source.fingerprints))) {
1698
1723
  const into = state.fingerprints[locale] ??= emptyCatalog();
1699
- for (const [key, stamped] of Object.entries(stamps)) if (own(into, key) === void 0) into[key] = stamped;
1724
+ for (const [key, stamped] of Object.entries(stamps)) {
1725
+ const held = own(into, key);
1726
+ if (held === void 0) into[key] = stamped;
1727
+ else if (index < lock.length && held !== stamped && kept?.(locale, key, stamped)) into[key] = stamped;
1728
+ }
1700
1729
  }
1701
1730
  const migrated = readMigrated(source.migrated);
1702
1731
  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);
1732
+ });
1733
+ for (const side of legacyDrafts) for (const [locale, keys] of Object.entries(readDrafts(side))) markDrafts(state.drafts, locale, keys);
1705
1734
  return state;
1706
1735
  }
1736
+ function keptStamp(cfg) {
1737
+ const read = /* @__PURE__ */ new Map();
1738
+ return (locale, key, stamped) => {
1739
+ if (!read.has(locale)) try {
1740
+ read.set(locale, readCatalog(cfg, locale));
1741
+ } catch {
1742
+ read.set(locale, void 0);
1743
+ }
1744
+ const translated = own(read.get(locale) ?? {}, key);
1745
+ return translated !== void 0 && translationOf(stamped) === fingerprint(translated);
1746
+ };
1747
+ }
1707
1748
  function stateFile(cfg) {
1708
1749
  return [statePath(cfg), ...legacyPaths(cfg)].find((path) => existsSync(path));
1709
1750
  }
1710
1751
  function lockNews(cfg, before) {
1711
1752
  const lock = statePath(cfg);
1753
+ if (resolved.delete(lock)) return {
1754
+ file: lock,
1755
+ merged: true
1756
+ };
1712
1757
  if (before === lock || !existsSync(lock)) return void 0;
1713
1758
  return before ? {
1714
1759
  file: lock,
@@ -1719,15 +1764,20 @@ function checkVersion(path, version) {
1719
1764
  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
1765
  }
1721
1766
  function readState(cfg) {
1767
+ const marked = (readText(statePath(cfg))?.split(/\r?\n/) ?? []).some((line) => CONFLICT.start.test(line)) ? { conflict: true } : {};
1722
1768
  try {
1723
- return { state: loadState(cfg) };
1769
+ return {
1770
+ state: loadState(cfg),
1771
+ ...marked
1772
+ };
1724
1773
  } catch (error) {
1725
1774
  return {
1726
1775
  state: {
1727
1776
  drafts: {},
1728
1777
  fingerprints: {}
1729
1778
  },
1730
- problem: error.message.replace(/^\[verbaly\] /, "")
1779
+ problem: error.message.replace(/^\[verbaly\] /, ""),
1780
+ ...marked
1731
1781
  };
1732
1782
  }
1733
1783
  }
@@ -1742,7 +1792,10 @@ function saveState(cfg, state) {
1742
1792
  const existing = readText(path);
1743
1793
  if (existing === void 0) mkdirSync(cfg.root, { recursive: true });
1744
1794
  const serialized = withLineEndings(fresh, existing ?? legacy.map(readText).find((text) => text !== void 0));
1745
- if (existing !== serialized) writeFileSync(path, serialized);
1795
+ if (existing !== serialized) {
1796
+ if (existing !== void 0 && conflictSides(existing)) resolved.add(path);
1797
+ writeFileSync(path, serialized);
1798
+ }
1746
1799
  for (const file of legacy) rmSync(file, { force: true });
1747
1800
  }
1748
1801
  function readText(path) {
@@ -1899,20 +1952,47 @@ function serializeState(state) {
1899
1952
  if (migrated.length) out.migrated = migrated;
1900
1953
  return JSON.stringify(out, null, 2) + "\n";
1901
1954
  }
1902
- function readObject(path) {
1955
+ function readSides(path) {
1903
1956
  const content = readText(path);
1904
1957
  if (content === void 0) return void 0;
1958
+ const body = content.charCodeAt(0) === 65279 ? content.slice(1) : content;
1959
+ const sides = conflictSides(body);
1960
+ return (sides ?? [body]).map((text) => parseObject(path, text, sides !== void 0));
1961
+ }
1962
+ function parseObject(path, text, conflicted) {
1905
1963
  let value;
1906
1964
  try {
1907
- value = JSON.parse(content.charCodeAt(0) === 65279 ? content.slice(1) : content);
1965
+ value = JSON.parse(text);
1908
1966
  } catch (error) {
1909
- throw corrupt(path, error);
1967
+ throw corrupt(path, conflicted, error);
1910
1968
  }
1911
- if (!isObject(value)) throw corrupt(path);
1969
+ if (!isObject(value)) throw corrupt(path, conflicted);
1912
1970
  return value;
1913
1971
  }
1914
- function corrupt(path, cause) {
1915
- return new Error(`[verbaly] ${path} is not valid JSON: restore it from git or fix it (deleting it approves every draft)`, { cause });
1972
+ const CONFLICT = {
1973
+ start: /^<{7}(?: |$)/,
1974
+ base: /^\|{7}(?: |$)/,
1975
+ split: /^={7}$/,
1976
+ end: /^>{7}(?: |$)/
1977
+ };
1978
+ function conflictSides(text) {
1979
+ const lines = text.split(/\r?\n/);
1980
+ if (!lines.some((line) => CONFLICT.start.test(line))) return void 0;
1981
+ const ours = [];
1982
+ const theirs = [];
1983
+ let at = "both";
1984
+ for (const line of lines) if (at === "both" && CONFLICT.start.test(line)) at = "ours";
1985
+ else if (at === "ours" && CONFLICT.base.test(line)) at = "base";
1986
+ else if ((at === "ours" || at === "base") && CONFLICT.split.test(line)) at = "theirs";
1987
+ else if (at === "theirs" && CONFLICT.end.test(line)) at = "both";
1988
+ else if (at !== "base") {
1989
+ if (at !== "theirs") ours.push(line);
1990
+ if (at !== "ours") theirs.push(line);
1991
+ }
1992
+ return at === "both" ? [ours.join("\n"), theirs.join("\n")] : void 0;
1993
+ }
1994
+ function corrupt(path, conflicted, cause) {
1995
+ return new Error(conflicted ? `[verbaly] ${path} has a merge conflict Verbaly cannot read: resolve it by hand and keep the entries of both sides (dropping a side, or the file, approves its drafts)` : `[verbaly] ${path} is not valid JSON: restore it from git or fix it (deleting it approves every draft)`, { cause });
1916
1996
  }
1917
1997
  function isObject(value) {
1918
1998
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -2385,8 +2465,8 @@ function createSourceFilter(cfg) {
2385
2465
  return !rel.startsWith("..") && matches(rel);
2386
2466
  };
2387
2467
  }
2388
- function transformSource(code, id, registry) {
2389
- const analysis = analyzeFile(code, id);
2468
+ function transformSource(code, id, registry, scan) {
2469
+ const analysis = (scan && scannedAnalysis(scan, id, code)) ?? analyzeFile(code, id);
2390
2470
  registry.update(id, analysis);
2391
2471
  if (analysis.parseError) warnParseError(id, analysis.parseError);
2392
2472
  const messages = emptyCatalog();
@@ -2744,8 +2824,9 @@ async function doctor(cfg) {
2744
2824
  for (const issue of issues) warn("bundle", formatBundleIssue(issue), issue.fix);
2745
2825
  if (issues.length === 0) ok("bundle", `${counted(excluded.length, "group")} kept out of the client (${preview(excluded)})`);
2746
2826
  }
2747
- const { state, problem } = readState(cfg);
2748
- if (problem) warn("state", problem, `restore ${STATE_FILE} from git: deleting it would mark every machine draft as reviewed`);
2827
+ const { state, problem, conflict } = readState(cfg);
2828
+ if (problem) warn("state", problem, conflict ? "resolve it by hand, keeping the entries of both sides: taking one side approves the drafts of the other" : `restore ${STATE_FILE} from git: deleting it would mark every machine draft as reviewed`);
2829
+ else if (conflict) warn("state", `${STATE_FILE} has a merge conflict, and both sides were read`, "run `npx verbaly extract`, which writes both sides into it, then commit it");
2749
2830
  if (catalogsHealthy) {
2750
2831
  const stale = Object.entries(state.drafts).flatMap(([locale, keys]) => {
2751
2832
  const live = new Set(effectiveDrafts({ [locale]: keys }, catalogs)[locale] ?? []);
@@ -2974,7 +3055,7 @@ function formatTranslateFailures(failed) {
2974
3055
  async function resolveProvider(cfg, model) {
2975
3056
  const configured = cfg.translate.provider;
2976
3057
  if (typeof configured === "function") return configured;
2977
- const { claudeProvider } = await import("./claude-CusgBHrv.js");
3058
+ const { claudeProvider } = await import("./claude-Baoc6pYL.js");
2978
3059
  return claudeProvider({ model: model ?? cfg.translate.model });
2979
3060
  }
2980
3061
  function structureMatches(source, translated) {