@verbaly/compiler 0.82.0 → 0.84.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.
@@ -3,6 +3,7 @@ import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSy
3
3
  import { basename, dirname, join, relative, resolve, sep } from "node:path";
4
4
  import { pathToFileURL } from "node:url";
5
5
  import { CATALOG_SCRIPT, LOCALE_STORAGE_KEY, RICH_TAGS, VOID_TAGS, alternateLinks, createVerbaly, flatten, localeDirection, normalizeLink, parse, parseIcu, parseTags, safeAttribute } from "verbaly";
6
+ import { readFile } from "node:fs/promises";
6
7
  import { glob } from "tinyglobby";
7
8
  import { parse as parse$1 } from "@babel/parser";
8
9
  import { createHash } from "node:crypto";
@@ -10,6 +11,34 @@ import { applyEdits, modify, parse as parse$2 } from "jsonc-parser";
10
11
  import picomatch from "picomatch";
11
12
  import MagicString from "magic-string";
12
13
  import { parseArgs as parseArgs$1 } from "node:util";
14
+ // src/util/path.ts
15
+ function slashed(path) {
16
+ return path.replaceAll("\\", "/");
17
+ }
18
+ function relativePath(root, file) {
19
+ return slashed(relative(root, file));
20
+ }
21
+ // src/util/text.ts
22
+ function counted(count, noun, many = `${noun}s`) {
23
+ return `${count} ${count === 1 ? noun : many}`;
24
+ }
25
+ function truncate(text, max) {
26
+ return text.length > max ? text.slice(0, max - 1) + "…" : text;
27
+ }
28
+ function trimTrailingSlashes(text) {
29
+ let end = text.length;
30
+ while (end > 0 && text.charCodeAt(end - 1) === 47) end -= 1;
31
+ return text.slice(0, end);
32
+ }
33
+ function singleQuoted(text) {
34
+ return `'${text.replace(/[\\']/g, "\\$&")}'`;
35
+ }
36
+ function byCodeUnit(a, b) {
37
+ return a < b ? -1 : a > b ? 1 : 0;
38
+ }
39
+ function stripBom(text) {
40
+ return text.charCodeAt(0) === 65279 ? text.slice(1) : text;
41
+ }
13
42
  // src/config/host.ts
14
43
  const HOSTS = [
15
44
  {
@@ -95,19 +124,21 @@ const HOSTS = [
95
124
  }
96
125
  ];
97
126
  const WIRING_PACKAGES = [...new Set(HOSTS.map((host) => host.pkg))];
98
- function readDependencies(root) {
99
- const path = join(root, "package.json");
100
- if (!existsSync(path)) return {};
127
+ function readManifest(root) {
101
128
  try {
102
- const pkg = JSON.parse(readFileSync(path, "utf8"));
103
- return {
104
- ...pkg.dependencies,
105
- ...pkg.devDependencies
106
- };
129
+ const manifest = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
130
+ return typeof manifest === "object" && manifest !== null ? manifest : void 0;
107
131
  } catch {
108
- return {};
132
+ return;
109
133
  }
110
134
  }
135
+ function readDependencies(root) {
136
+ const manifest = readManifest(root);
137
+ return {
138
+ ...manifest?.dependencies,
139
+ ...manifest?.devDependencies
140
+ };
141
+ }
111
142
  const ADAPTERS = [
112
143
  ["@verbaly/react", [
113
144
  "react",
@@ -153,11 +184,9 @@ const LOCKFILES = [
153
184
  ["package-lock.json", "npm"]
154
185
  ];
155
186
  function packageManager(root) {
156
- try {
157
- const declared = JSON.parse(readFileSync(join(root, "package.json"), "utf8")).packageManager;
158
- const name = typeof declared === "string" ? declared.split("@")[0] : void 0;
159
- if (name === "pnpm" || name === "npm" || name === "yarn" || name === "bun") return name;
160
- } catch {}
187
+ const declared = readManifest(root)?.packageManager;
188
+ const name = typeof declared === "string" ? declared.split("@")[0] : void 0;
189
+ if (name === "pnpm" || name === "npm" || name === "yarn" || name === "bun") return name;
161
190
  for (let dir = root;; dir = dirname(dir)) {
162
191
  const found = LOCKFILES.find(([file]) => existsSync(join(dir, file)));
163
192
  if (found) return found[1];
@@ -199,7 +228,8 @@ function warnParseError(file, message) {
199
228
  warnOnce(`${file}: could not be parsed (${message}), its messages were not extracted`);
200
229
  }
201
230
  // src/config/config.ts
202
- const SOURCE_EXTENSIONS = "{js,jsx,ts,tsx,mjs,mts,svelte,vue,astro}";
231
+ const SOURCE_EXTENSIONS = "{js,jsx,ts,tsx,mjs,mts,cjs,cts,svelte,vue,astro}";
232
+ const SOURCE_FILE_RE = /\.(?:[cm]?[jt]sx?|svelte|vue|astro)$/;
203
233
  const PSEUDO_LOCALE = "en-XA";
204
234
  function resolveConfig(config = {}) {
205
235
  const root = resolve(config.root ?? process.cwd());
@@ -219,10 +249,11 @@ function resolveConfig(config = {}) {
219
249
  sourceLocale,
220
250
  localesDeclared,
221
251
  routing: config.routing ?? (config.render ? "prefix-except-source" : "no-prefix"),
252
+ routingDeclared: config.routing !== void 0,
222
253
  icu: config.icu,
223
254
  relative: config.relative,
224
255
  locales: [...locales],
225
- include: config.include ?? [`{src,app}/**/*.{js,jsx,ts,tsx,mjs,mts,svelte,vue,astro}`],
256
+ include: config.include ?? [`{src,app}/**/*.{js,jsx,ts,tsx,mjs,mts,cjs,cts,svelte,vue,astro}`],
226
257
  exclude: config.exclude ?? ["**/node_modules/**", "**/dist/**"],
227
258
  dts: typeof config.dts === "string" ? resolve(root, config.dts) : config.dts === false ? false : defaultTypesPath(root, host),
228
259
  translate: config.translate ?? {},
@@ -243,27 +274,19 @@ function findConfigFile(root) {
243
274
  return CONFIG_FILES.find((name) => existsSync(join(root, name)));
244
275
  }
245
276
  async function loadConfigFile(root) {
246
- for (const name of ["verbaly.config.js", "verbaly.config.mjs"]) {
247
- const path = join(root, name);
248
- if (existsSync(path)) {
249
- const url = `${pathToFileURL(path).href}?mtime=${statSync(path).mtimeMs}`;
250
- const cache = createRequire(import.meta.url).cache;
251
- delete cache[realpathSync(path)];
252
- delete cache[resolve(path)];
253
- return (await import(url)).default ?? {};
254
- }
255
- }
256
- for (const name of ["verbaly.config.ts", "verbaly.config.mts"]) {
257
- const path = join(root, name);
258
- if (existsSync(path)) return loadTsConfig(path);
259
- }
260
- const jsonPath = join(root, "verbaly.config.json");
261
- if (existsSync(jsonPath)) return readJsonConfig(jsonPath);
262
- return {};
277
+ const name = findConfigFile(root);
278
+ if (!name) return {};
279
+ const path = join(root, name);
280
+ if (name.endsWith(".json")) return readJsonConfig(path);
281
+ if (name.endsWith("ts")) return loadTsConfig(path);
282
+ const url = `${pathToFileURL(path).href}?mtime=${statSync(path).mtimeMs}`;
283
+ const cache = createRequire(import.meta.url).cache;
284
+ delete cache[realpathSync(path)];
285
+ delete cache[resolve(path)];
286
+ return (await import(url)).default ?? {};
263
287
  }
264
288
  function readJsonConfig(path) {
265
- const content = readFileSync(path, "utf8");
266
- const body = content.charCodeAt(0) === 65279 ? content.slice(1) : content;
289
+ const body = stripBom(readFileSync(path, "utf8"));
267
290
  try {
268
291
  return JSON.parse(body);
269
292
  } catch (error) {
@@ -282,8 +305,17 @@ async function loadTsConfig(path) {
282
305
  function isModuleNotFound(error, name) {
283
306
  return error instanceof Error && error.code === "ERR_MODULE_NOT_FOUND" && error.message.includes(name);
284
307
  }
308
+ function strangerLocales(cfg, said, named) {
309
+ const unknown = named.filter((locale) => !cfg.locales.includes(locale));
310
+ if (unknown.length === 0) return void 0;
311
+ const dir = relativePath(cfg.root, cfg.dir);
312
+ const start = cfg.localesDeclared ? `add ${unknown.join(", ")} to locales in your verbaly config` : `create ${unknown.map((locale) => `${dir}/${locale}.json`).join(", ")} holding {}`;
313
+ return `[verbaly] ${said} names ${unknown.map((locale) => `"${locale}"`).join(", ")}, and this project has ${cfg.locales.join(", ")}\n fix: check the spelling, or ${start} to start a new language`;
314
+ }
285
315
  function targetLocales(cfg, override) {
286
- return (override ?? cfg.locales).filter((locale) => locale !== cfg.sourceLocale && cfg.locales.includes(locale));
316
+ const typo = override && strangerLocales(cfg, "locales", override);
317
+ if (typo) throw new Error(typo);
318
+ return (override ?? cfg.locales).filter((locale) => locale !== cfg.sourceLocale);
287
319
  }
288
320
  async function loadConfig(root, overrides = {}, from = {}) {
289
321
  const fileConfig = await loadConfigFile(root);
@@ -380,16 +412,20 @@ function parseCatalog(content) {
380
412
  return tree === void 0 ? void 0 : flatten(tree);
381
413
  }
382
414
  function parseTree(content) {
383
- const body = content.charCodeAt(0) === 65279 ? content.slice(1) : content;
415
+ const body = stripBom(content);
416
+ if (body.trim() === "") return {};
384
417
  try {
385
418
  return JSON.parse(body);
386
419
  } catch {
387
420
  return;
388
421
  }
389
422
  }
390
- function isTree(value) {
423
+ function isRecord(value) {
391
424
  return typeof value === "object" && value !== null && !Array.isArray(value);
392
425
  }
426
+ function isTree(value) {
427
+ return isRecord(value);
428
+ }
393
429
  function loadCatalogs(cfg) {
394
430
  const catalogs = emptyCatalog();
395
431
  for (const locale of cfg.locales) catalogs[locale] = readCatalog(cfg, locale);
@@ -412,7 +448,7 @@ function pathsOf(tree, prefix = [], out = /* @__PURE__ */ new Map()) {
412
448
  function nest(catalog, shape) {
413
449
  const tree = group();
414
450
  const written = shape ? pathsOf(shape) : void 0;
415
- for (const [key, message] of Object.entries(catalog).sort(([a], [b]) => a < b ? -1 : 1)) {
451
+ for (const [key, message] of Object.entries(catalog).sort(([a], [b]) => byCodeUnit(a, b))) {
416
452
  const parts = written?.get(key) ?? key.split(".");
417
453
  const leaf = parts[parts.length - 1];
418
454
  let node = parts.length > 1 ? tree : void 0;
@@ -477,7 +513,8 @@ function writeCatalog(cfg, locale, catalog) {
477
513
  return serialized;
478
514
  }
479
515
  function shapeFor(cfg, locale, existing, previous) {
480
- if (existing !== void 0) return previous;
516
+ const blank = previous !== void 0 && Object.keys(previous).length === 0;
517
+ if (existing !== void 0 && !blank) return previous;
481
518
  return locale === cfg.sourceLocale ? void 0 : readTree(cfg, cfg.sourceLocale);
482
519
  }
483
520
  const ICU_ARG = /(^|[^{])\{\s*[a-zA-Z0-9_]+\s*,\s*(?:plural|selectordinal|select|number|date|time)\b/;
@@ -500,24 +537,6 @@ function someLeaf(tree, pattern) {
500
537
  } else if (isTree(value) && someLeaf(value, pattern)) return true;
501
538
  return false;
502
539
  }
503
- // src/util/text.ts
504
- function counted(count, noun, many = `${noun}s`) {
505
- return `${count} ${count === 1 ? noun : many}`;
506
- }
507
- function truncate(text, max) {
508
- return text.length > max ? text.slice(0, max - 1) + "…" : text;
509
- }
510
- function trimTrailingSlashes(text) {
511
- let end = text.length;
512
- while (end > 0 && text.charCodeAt(end - 1) === 47) end -= 1;
513
- return text.slice(0, end);
514
- }
515
- function singleQuoted(text) {
516
- return `'${text.replace(/[\\']/g, "\\$&")}'`;
517
- }
518
- function byCodeUnit(a, b) {
519
- return a < b ? -1 : a > b ? 1 : 0;
520
- }
521
540
  // src/emit/bundle.ts
522
541
  function isExcluded(key, prefixes) {
523
542
  return prefixes.some((prefix) => key === prefix || key.startsWith(`${prefix}.`));
@@ -796,7 +815,7 @@ function loadsAtRuntime(node) {
796
815
  return specifiers.some((spec) => spec.importKind !== "type" && spec.exportKind !== "type");
797
816
  }
798
817
  function lineOf(node) {
799
- return node.loc?.start.line ?? 1;
818
+ return node.loc?.start?.line ?? 1;
800
819
  }
801
820
  const OTHER_I18N = /^(?:react-i18next|next-i18next|next-translate|ttag|@lingui\/[\w-]+)(?:\/.*)?$/;
802
821
  const TRANS = "Trans";
@@ -864,7 +883,7 @@ var Bindings = class {
864
883
  }
865
884
  foreign(name, at) {
866
885
  let theirs = this.other(name);
867
- let reach = Infinity;
886
+ let reach = 1e400;
868
887
  for (const { name: bound, init, scope } of [...this.declared, ...this.destructured]) {
869
888
  if (bound !== name || at < scope.start || at >= scope.end) continue;
870
889
  if (scope.end - scope.start >= reach) continue;
@@ -924,19 +943,25 @@ function renamedTag(tag, renamed) {
924
943
  if (renamed.size === 0) return void 0;
925
944
  const name = identifierName(tag);
926
945
  if (renamed.has(name)) return name;
946
+ const call = idCall(tag);
947
+ if (!call) return void 0;
948
+ const object = identifierName(call.object);
949
+ return renamed.has(object) ? object : void 0;
950
+ }
951
+ function idCall(tag) {
927
952
  if (tag.type !== "CallExpression") return void 0;
928
953
  const callee = tag.callee;
929
954
  if (callee.type !== "MemberExpression" || callee.computed) return void 0;
930
955
  if (identifierName(callee.property) !== "id") return void 0;
931
- const object = identifierName(callee.object);
932
- return renamed.has(object) ? object : void 0;
956
+ const args = tag.arguments;
957
+ return {
958
+ object: callee.object,
959
+ key: args.length === 1 ? staticString(args[0]) : void 0
960
+ };
933
961
  }
934
962
  function missedKey(code, node, names) {
935
963
  const tag = node.tag;
936
- if (tag.type === "CallExpression") {
937
- const args = tag.arguments;
938
- return args.length === 1 ? staticString(args[0]) : void 0;
939
- }
964
+ if (tag.type === "CallExpression") return idCall(tag)?.key;
940
965
  const message = buildMessage(code, node.quasi, names);
941
966
  return message ? stableKey(message.text) : void 0;
942
967
  }
@@ -1021,20 +1046,12 @@ function handleTrans(code, node, file, tagged, usedKeys, names) {
1021
1046
  push(stableKey(built.text), built);
1022
1047
  }
1023
1048
  function explicitId(tag, names) {
1024
- if (tag.type !== "CallExpression") return void 0;
1025
- const callee = tag.callee;
1026
- if (callee.type !== "MemberExpression" || callee.computed) return void 0;
1027
- const prop = callee.property;
1028
- if (prop.type !== "Identifier" || prop.name !== "id") return void 0;
1029
- const obj = callee.object;
1030
- if (!isTReference(obj, names)) return void 0;
1031
- const args = tag.arguments;
1032
- const key = args.length === 1 ? staticString(args[0]) : void 0;
1033
- if (key === void 0) return void 0;
1049
+ const call = idCall(tag);
1050
+ if (!call || !isTReference(call.object, names) || call.key === void 0) return void 0;
1034
1051
  return {
1035
- key,
1036
- refStart: obj.start,
1037
- refEnd: obj.end
1052
+ key: call.key,
1053
+ refStart: call.object.start,
1054
+ refEnd: call.object.end
1038
1055
  };
1039
1056
  }
1040
1057
  function buildTransMessage(code, children, names) {
@@ -1490,6 +1507,17 @@ function stringEnd(code, start) {
1490
1507
  }
1491
1508
  // src/scan/extract.ts
1492
1509
  const kept = /* @__PURE__ */ new WeakMap();
1510
+ async function readSources(files, each, platform = process.platform) {
1511
+ if (platform !== "win32") {
1512
+ for (const file of files) each(file, readFileSync(file, "utf8"));
1513
+ return;
1514
+ }
1515
+ for (let at = 0; at < files.length; at += 64) {
1516
+ const window = files.slice(at, at + 64);
1517
+ const read = await Promise.all(window.map(async (file) => [file, await readFile(file, "utf8")]));
1518
+ for (const [file, code] of read) each(file, code);
1519
+ }
1520
+ }
1493
1521
  async function extractProject(cfg, options = {}) {
1494
1522
  const files = await glob(cfg.include, {
1495
1523
  cwd: cfg.root,
@@ -1498,31 +1526,31 @@ async function extractProject(cfg, options = {}) {
1498
1526
  });
1499
1527
  const registry = new MessageRegistry();
1500
1528
  const read = options.keepSource ? /* @__PURE__ */ new Map() : null;
1501
- for (const file of files.sort()) {
1502
- const code = readFileSync(file, "utf8");
1529
+ await readSources(files.sort(), (file, code) => {
1503
1530
  const analysis = analyzeFile(code, file);
1504
1531
  registry.update(file, analysis);
1505
- read?.set(file.replaceAll("\\", "/"), {
1532
+ read?.set(slashed(file), {
1506
1533
  code,
1507
1534
  analysis
1508
1535
  });
1509
- }
1536
+ });
1510
1537
  if (read) kept.set(registry, read);
1511
1538
  return registry;
1512
1539
  }
1513
1540
  function scannedAnalysis(scan, file, code) {
1514
1541
  const read = kept.get(scan);
1515
- const key = file.replaceAll("\\", "/");
1542
+ const key = slashed(file);
1516
1543
  const entry = read?.get(key);
1517
1544
  read?.delete(key);
1518
1545
  return entry?.code === code ? entry.analysis : void 0;
1519
1546
  }
1520
1547
  async function collectOrigins(cfg, reuse) {
1521
1548
  const registry = reuse ?? await extractProject(cfg);
1522
- const origins = Object.create(null);
1523
- for (const [key, files] of registry.origins()) origins[key] = files.map((file) => relative(cfg.root, file).replaceAll("\\", "/"));
1549
+ const origins = emptyCatalog();
1550
+ for (const [key, files] of registry.origins()) origins[key] = files.map((file) => relativePath(cfg.root, file));
1524
1551
  return origins;
1525
1552
  }
1553
+ // src/scan/sync.ts
1526
1554
  function syncCatalogs(cfg, catalogs, registry) {
1527
1555
  const added = emptyCatalog();
1528
1556
  const replaced = [];
@@ -1583,12 +1611,14 @@ function read(message) {
1583
1611
  return tree;
1584
1612
  }
1585
1613
  function gatePass(run) {
1586
- reading = /* @__PURE__ */ new Map();
1614
+ const outer = reading;
1615
+ const pass = /* @__PURE__ */ new Map();
1616
+ reading = pass;
1587
1617
  try {
1588
1618
  return run();
1589
1619
  } finally {
1590
- remembered = reading;
1591
- reading = void 0;
1620
+ remembered = pass;
1621
+ reading = outer;
1592
1622
  }
1593
1623
  }
1594
1624
  const PLURAL_CATEGORIES = /* @__PURE__ */ new Set([
@@ -1701,7 +1731,7 @@ function validateMessage(message, locale) {
1701
1731
  const missing = reachableCategories(locale, shape.ordinal).filter((category) => category !== "other" && !shape.selectors.includes(category));
1702
1732
  if (missing.length > 0) issues.push({
1703
1733
  severity: "warning",
1704
- message: `${locale} also needs the ${list(missing)} plural ${missing.length > 1 ? "forms" : "form"} for {${name}}`
1734
+ message: `${locale} needs ${counted(missing.length, "more plural form")} for {${name}}: ${list(missing)}`
1705
1735
  });
1706
1736
  }
1707
1737
  return issues;
@@ -1712,22 +1742,22 @@ function validatePair(source, translated) {
1712
1742
  const newParams = surplus(paramNames(translated), paramNames(source));
1713
1743
  if (lostParams.length > 0) issues.push({
1714
1744
  severity: "error",
1715
- message: `${list(lostParams.map((name) => `{${name}}`))} ${lostParams.length > 1 ? "are" : "is"} missing, so ${lostParams.length > 1 ? "their values never reach" : "its value never reaches"} the text`
1745
+ message: `the translation lost ${list(lostParams.map((name) => `{${name}}`))}, so the value never reaches the text`
1716
1746
  });
1717
1747
  if (newParams.length > 0) issues.push({
1718
1748
  severity: "error",
1719
- message: `${list(newParams.map((name) => `{${name}}`))} ${newParams.length > 1 ? "are" : "is"} not in the source message, so ${newParams.length > 1 ? "they render" : "it renders"} as literal text`
1749
+ message: `the translation adds ${list(newParams.map((name) => `{${name}}`))}, not in the source message, so the braces render as literal text`
1720
1750
  });
1721
1751
  const markup = /* @__PURE__ */ new Set([...markupNames(source), ...markupNames(translated)]);
1722
1752
  const lostTags = tagReport(surplus(tagTokens(source, markup), tagTokens(translated, markup)));
1723
1753
  const newTags = tagReport(surplus(tagTokens(translated, markup), tagTokens(source, markup)));
1724
1754
  if (lostTags.length > 0) issues.push({
1725
1755
  severity: "error",
1726
- message: `${list(lostTags)} ${lostTags.length > 1 ? "are" : "is"} missing from the translation`
1756
+ message: `the translation lost ${list(lostTags)}`
1727
1757
  });
1728
1758
  if (newTags.length > 0) issues.push({
1729
1759
  severity: "error",
1730
- message: `${list(newTags)} ${newTags.length > 1 ? "are" : "is"} not in the source message`
1760
+ message: `the translation adds ${list(newTags)}, not in the source message`
1731
1761
  });
1732
1762
  const target = shapes(translated);
1733
1763
  for (const [name, shape] of shapes(source)) {
@@ -1746,7 +1776,7 @@ function validatePair(source, translated) {
1746
1776
  const lostExact = shape.selectors.filter((key) => EXACT.test(key)).filter((key) => !other.selectors.includes(key));
1747
1777
  if (lostExact.length > 0) issues.push({
1748
1778
  severity: "warning",
1749
- message: `the ${list(lostExact)} ${lostExact.length > 1 ? "cases" : "case"} for {${name}} ${lostExact.length > 1 ? "are" : "is"} missing, so ${lostExact.length > 1 ? "those counts" : "that count"} falls back to "other"`
1779
+ message: `the translation lost ${counted(lostExact.length, "exact case")} for {${name}} (${list(lostExact)}), so "other" renders instead`
1750
1780
  });
1751
1781
  }
1752
1782
  return issues;
@@ -1781,6 +1811,13 @@ function reachableCategories(locale, ordinal) {
1781
1811
  reachable.set(cacheKey, out);
1782
1812
  return out;
1783
1813
  }
1814
+ function structureMatches(source, translated) {
1815
+ try {
1816
+ return ![...validateMessage(translated), ...validatePair(source, translated)].some((issue) => issue.severity === "error");
1817
+ } catch {
1818
+ return false;
1819
+ }
1820
+ }
1784
1821
  // src/emit/params.ts
1785
1822
  const NUMBER_FORMATS = /* @__PURE__ */ new Set([
1786
1823
  "number",
@@ -1860,7 +1897,7 @@ function formatting(text) {
1860
1897
  function typesIncluded(root, file) {
1861
1898
  const read = readTsconfig(root);
1862
1899
  if (typeof read === "string") return read;
1863
- const entry = relative(root, file).replaceAll("\\", "/");
1900
+ const entry = relativePath(root, file);
1864
1901
  const { include, files } = read.json;
1865
1902
  if (covered(include, entry) || covered(files, entry)) return "present";
1866
1903
  return "missing";
@@ -1868,7 +1905,7 @@ function typesIncluded(root, file) {
1868
1905
  function includeTypes(root, file) {
1869
1906
  const read = readTsconfig(root);
1870
1907
  if (typeof read === "string") return read;
1871
- const entry = relative(root, file).replaceAll("\\", "/");
1908
+ const entry = relativePath(root, file);
1872
1909
  const { include, files } = read.json;
1873
1910
  if (covered(include, entry) || covered(files, entry)) return "present";
1874
1911
  const options = { formattingOptions: formatting(read.text) };
@@ -2145,7 +2182,7 @@ function writeDts(cfg, catalog, file) {
2145
2182
  const ignore = join(cfg.root, ".verbaly", ".gitignore");
2146
2183
  if (!existsSync(ignore)) writeFileSync(ignore, "*\n");
2147
2184
  const state = includeTypes(cfg.root, target);
2148
- const entry = relative(cfg.root, target).replaceAll("\\", "/");
2185
+ const entry = relativePath(cfg.root, target);
2149
2186
  if (state === "added") warnOnce(`added "${entry}" to the include of tsconfig.json, so TypeScript reads the types`);
2150
2187
  else if (state === "unreadable") warnOnce(`tsconfig.json could not be read, so add "${entry}" to its include yourself`);
2151
2188
  }
@@ -2165,9 +2202,9 @@ function removeRootDts(cfg, target) {
2165
2202
  }
2166
2203
  if (head !== "// generated by verbaly: do not edit") return;
2167
2204
  rmSync(old);
2168
- warnOnce(`the types live in ${relative(cfg.root, target).replaceAll("\\", "/")} now, so the verbaly.d.ts Verbaly wrote at the root was removed`);
2205
+ warnOnce(`the types live in ${relativePath(cfg.root, target)} now, so the verbaly.d.ts Verbaly wrote at the root was removed`);
2169
2206
  }
2170
- // src/catalog/state.ts
2207
+ // src/catalog/lock.ts
2171
2208
  const STATE_FILE = "verbaly.lock";
2172
2209
  const LOCK_VERSION = 1;
2173
2210
  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.";
@@ -2278,77 +2315,6 @@ function readText(path) {
2278
2315
  return;
2279
2316
  }
2280
2317
  }
2281
- function updateState(cfg, catalogs) {
2282
- const next = refreshState(cfg, catalogs, loadState(cfg));
2283
- saveState(cfg, next);
2284
- return next;
2285
- }
2286
- function refreshState(cfg, catalogs, previous) {
2287
- const flat = flatCatalogs(catalogs);
2288
- const source = flat[cfg.sourceLocale] ?? {};
2289
- const shown = new Set(targetLocales(cfg).filter((locale) => Object.hasOwn(flat, locale) && existsSync(catalogPath(cfg, locale))));
2290
- const drafts = emptyCatalog();
2291
- for (const [locale, keys] of Object.entries(previous.drafts)) {
2292
- if (!shown.has(locale)) {
2293
- drafts[locale] = keys;
2294
- continue;
2295
- }
2296
- const live = keys.filter((key) => own(flat[locale], key));
2297
- if (live.length) drafts[locale] = live;
2298
- }
2299
- const fingerprints = emptyCatalog();
2300
- for (const [locale, stamps] of Object.entries(previous.fingerprints)) if (!shown.has(locale)) fingerprints[locale] = stamps;
2301
- for (const locale of shown) {
2302
- const stamps = refreshStamps(source, flat[locale], previous.fingerprints[locale] ?? {});
2303
- if (Object.keys(stamps).length) fingerprints[locale] = stamps;
2304
- }
2305
- return {
2306
- drafts,
2307
- fingerprints,
2308
- migrated: previous.migrated
2309
- };
2310
- }
2311
- function refreshStamps(source, catalog, before) {
2312
- const after = emptyCatalog();
2313
- for (const key of /* @__PURE__ */ new Set([...Object.keys(before), ...Object.keys(source)])) {
2314
- const translated = own(catalog, key);
2315
- if (!translated) continue;
2316
- const was = own(before, key);
2317
- if (was !== void 0 && translationOf(was) === fingerprint(translated)) {
2318
- after[key] = was;
2319
- continue;
2320
- }
2321
- const text = own(source, key);
2322
- if (text && tracked(key, text)) after[key] = stamp(text, translated);
2323
- else if (was !== void 0) after[key] = was;
2324
- }
2325
- return after;
2326
- }
2327
- function recordTranslations(cfg, source, writes) {
2328
- const state = loadState(cfg);
2329
- for (const { locale, entries, draft } of writes) {
2330
- if (entries.length === 0) continue;
2331
- const stamps = state.fingerprints[locale] ??= emptyCatalog();
2332
- for (const entry of entries) {
2333
- const from = entry.source || own(source, entry.key);
2334
- if (from && entry.text && tracked(entry.key, from)) stamps[entry.key] = stamp(from, entry.text);
2335
- }
2336
- const keys = entries.map((entry) => entry.key);
2337
- if (draft === true) markDrafts(state.drafts, locale, keys);
2338
- else if (draft === false) clearDrafts(state.drafts, locale, keys);
2339
- }
2340
- saveState(cfg, state);
2341
- return state;
2342
- }
2343
- function effectiveDrafts(drafts, catalogs) {
2344
- const out = emptyCatalog();
2345
- for (const [locale, keys] of Object.entries(drafts)) {
2346
- const catalog = catalogs[locale] ?? {};
2347
- const live = keys.filter((key) => own(catalog, key));
2348
- if (live.length) out[locale] = live;
2349
- }
2350
- return out;
2351
- }
2352
2318
  function markDrafts(drafts, locale, keys) {
2353
2319
  if (!keys.length) return;
2354
2320
  drafts[locale] = [.../* @__PURE__ */ new Set([...drafts[locale] ?? [], ...keys])];
@@ -2366,50 +2332,15 @@ function clearDrafts(drafts, locale, keys) {
2366
2332
  function fingerprint(text) {
2367
2333
  return stableKey(text);
2368
2334
  }
2369
- function tracked(key, text) {
2370
- return stableKey(text) !== key;
2371
- }
2372
2335
  function stamp(source, translated) {
2373
2336
  return `${fingerprint(source)}.${fingerprint(translated)}`;
2374
2337
  }
2375
- function outdatedTranslations(cfg, catalogs, fingerprints) {
2376
- const source = catalogs[cfg.sourceLocale] ?? {};
2377
- const out = [];
2378
- for (const locale of targetLocales(cfg)) {
2379
- const catalog = catalogs[locale] ?? {};
2380
- for (const [key, was] of Object.entries(fingerprints[locale] ?? {})) {
2381
- const text = own(source, key);
2382
- const translated = own(catalog, key);
2383
- if (!text || !translated) continue;
2384
- if (translationOf(was) !== fingerprint(translated)) continue;
2385
- if (sourceOf(was) !== fingerprint(text)) out.push({
2386
- locale,
2387
- key
2388
- });
2389
- }
2390
- }
2391
- return out.sort((a, b) => byCodeUnit(a.locale, b.locale) || byCodeUnit(a.key, b.key));
2392
- }
2393
- function acceptOutdated(cfg, catalogs, fingerprints, entries) {
2394
- const source = catalogs[cfg.sourceLocale] ?? {};
2395
- for (const { locale, key } of entries) {
2396
- const text = own(source, key);
2397
- const translated = own(catalogs[locale] ?? {}, key);
2398
- if (!text || !translated) continue;
2399
- (fingerprints[locale] ??= emptyCatalog())[key] = stamp(text, translated);
2400
- }
2401
- }
2402
2338
  function sourceOf(stamped) {
2403
2339
  return stamped.slice(0, stamped.indexOf("."));
2404
2340
  }
2405
2341
  function translationOf(stamped) {
2406
2342
  return stamped.slice(stamped.indexOf(".") + 1);
2407
2343
  }
2408
- function flatCatalogs(catalogs) {
2409
- const out = emptyCatalog();
2410
- for (const [locale, catalog] of Object.entries(catalogs)) out[locale] = flatten(catalog);
2411
- return out;
2412
- }
2413
2344
  function serializeState(state) {
2414
2345
  const drafts = emptyCatalog();
2415
2346
  for (const locale of Object.keys(state.drafts).sort()) {
@@ -2437,7 +2368,7 @@ function serializeState(state) {
2437
2368
  function readSides(path) {
2438
2369
  const content = readText(path);
2439
2370
  if (content === void 0) return void 0;
2440
- const body = content.charCodeAt(0) === 65279 ? content.slice(1) : content;
2371
+ const body = stripBom(content);
2441
2372
  const sides = conflictSides(body);
2442
2373
  return (sides ?? [body]).map((text) => parseObject(path, text, sides !== void 0));
2443
2374
  }
@@ -2448,7 +2379,7 @@ function parseObject(path, text, conflicted) {
2448
2379
  } catch (error) {
2449
2380
  throw corrupt(path, conflicted, error);
2450
2381
  }
2451
- if (!isObject(value)) throw corrupt(path, conflicted);
2382
+ if (!isRecord(value)) throw corrupt(path, conflicted);
2452
2383
  return value;
2453
2384
  }
2454
2385
  const CONFLICT = {
@@ -2476,12 +2407,9 @@ function conflictSides(text) {
2476
2407
  function corrupt(path, conflicted, cause) {
2477
2408
  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 });
2478
2409
  }
2479
- function isObject(value) {
2480
- return typeof value === "object" && value !== null && !Array.isArray(value);
2481
- }
2482
2410
  function readDrafts(value) {
2483
2411
  const out = emptyCatalog();
2484
- if (!isObject(value)) return out;
2412
+ if (!isRecord(value)) return out;
2485
2413
  for (const [locale, keys] of Object.entries(value)) if (Array.isArray(keys)) out[locale] = keys.filter((key) => typeof key === "string");
2486
2414
  return out;
2487
2415
  }
@@ -2492,33 +2420,140 @@ function readMigrated(value) {
2492
2420
  }
2493
2421
  function readFingerprints(value) {
2494
2422
  const out = emptyCatalog();
2495
- if (!isObject(value)) return out;
2423
+ if (!isRecord(value)) return out;
2496
2424
  for (const [locale, entries] of Object.entries(value)) {
2497
- if (!isObject(entries)) continue;
2425
+ if (!isRecord(entries)) continue;
2498
2426
  const kept = emptyCatalog();
2499
2427
  for (const [key, stamped] of Object.entries(entries)) if (typeof stamped === "string" && stamped.includes(".")) kept[key] = stamped;
2500
2428
  out[locale] = kept;
2501
2429
  }
2502
2430
  return out;
2503
2431
  }
2504
- // src/gate/findings.ts
2505
- function siteOf(msg) {
2432
+ // src/catalog/state.ts
2433
+ function updateState(cfg, catalogs) {
2434
+ const next = refreshState(cfg, catalogs, loadState(cfg));
2435
+ saveState(cfg, next);
2436
+ return next;
2437
+ }
2438
+ function refreshState(cfg, catalogs, previous) {
2439
+ const flat = flatCatalogs(catalogs);
2440
+ const source = flat[cfg.sourceLocale] ?? {};
2441
+ const shown = new Set(targetLocales(cfg).filter((locale) => Object.hasOwn(flat, locale) && existsSync(catalogPath(cfg, locale))));
2442
+ const drafts = emptyCatalog();
2443
+ for (const [locale, keys] of Object.entries(previous.drafts)) {
2444
+ if (!shown.has(locale)) {
2445
+ drafts[locale] = keys;
2446
+ continue;
2447
+ }
2448
+ const live = keys.filter((key) => own(flat[locale], key));
2449
+ if (live.length) drafts[locale] = live;
2450
+ }
2451
+ const fingerprints = emptyCatalog();
2452
+ for (const [locale, stamps] of Object.entries(previous.fingerprints)) if (!shown.has(locale)) fingerprints[locale] = stamps;
2453
+ for (const locale of shown) {
2454
+ const stamps = refreshStamps(source, flat[locale], previous.fingerprints[locale] ?? {});
2455
+ if (Object.keys(stamps).length) fingerprints[locale] = stamps;
2456
+ }
2506
2457
  return {
2507
- file: msg.file,
2508
- line: msg.line,
2509
- message: msg.message
2458
+ drafts,
2459
+ fingerprints,
2460
+ migrated: previous.migrated
2510
2461
  };
2511
2462
  }
2512
- function collisionEntries(registry) {
2513
- return registry.collisions().map(({ key, kept, dropped }) => ({
2514
- key,
2515
- sites: [kept, ...dropped].map(siteOf)
2516
- }));
2463
+ function refreshStamps(source, catalog, before) {
2464
+ const after = emptyCatalog();
2465
+ for (const key of /* @__PURE__ */ new Set([...Object.keys(before), ...Object.keys(source)])) {
2466
+ const translated = own(catalog, key);
2467
+ if (!translated) continue;
2468
+ const was = own(before, key);
2469
+ if (was !== void 0 && translationOf(was) === fingerprint(translated)) {
2470
+ after[key] = was;
2471
+ continue;
2472
+ }
2473
+ const text = own(source, key);
2474
+ if (text && tracked(key, text)) after[key] = stamp(text, translated);
2475
+ else if (was !== void 0) after[key] = was;
2476
+ }
2477
+ return after;
2517
2478
  }
2518
- function scanFindings(cfg, registry, replaced = []) {
2519
- const messages = registry.messages();
2520
- const out = [];
2521
- for (const { key, before } of replaced) {
2479
+ function recordTranslations(cfg, source, writes) {
2480
+ const state = loadState(cfg);
2481
+ for (const { locale, entries, draft } of writes) {
2482
+ if (entries.length === 0) continue;
2483
+ const stamps = state.fingerprints[locale] ??= emptyCatalog();
2484
+ for (const entry of entries) {
2485
+ const from = entry.source || own(source, entry.key);
2486
+ if (from && entry.text && tracked(entry.key, from)) stamps[entry.key] = stamp(from, entry.text);
2487
+ }
2488
+ const keys = entries.map((entry) => entry.key);
2489
+ if (draft === true) markDrafts(state.drafts, locale, keys);
2490
+ else if (draft === false) clearDrafts(state.drafts, locale, keys);
2491
+ }
2492
+ saveState(cfg, state);
2493
+ return state;
2494
+ }
2495
+ function effectiveDrafts(drafts, catalogs) {
2496
+ const out = emptyCatalog();
2497
+ for (const [locale, keys] of Object.entries(drafts)) {
2498
+ const catalog = catalogs[locale] ?? {};
2499
+ const live = keys.filter((key) => own(catalog, key));
2500
+ if (live.length) out[locale] = live;
2501
+ }
2502
+ return out;
2503
+ }
2504
+ function tracked(key, text) {
2505
+ return stableKey(text) !== key;
2506
+ }
2507
+ function outdatedTranslations(cfg, catalogs, fingerprints) {
2508
+ const source = catalogs[cfg.sourceLocale] ?? {};
2509
+ const out = [];
2510
+ for (const locale of targetLocales(cfg)) {
2511
+ const catalog = catalogs[locale] ?? {};
2512
+ for (const [key, was] of Object.entries(fingerprints[locale] ?? {})) {
2513
+ const text = own(source, key);
2514
+ const translated = own(catalog, key);
2515
+ if (!text || !translated) continue;
2516
+ if (translationOf(was) !== fingerprint(translated)) continue;
2517
+ if (sourceOf(was) !== fingerprint(text)) out.push({
2518
+ locale,
2519
+ key
2520
+ });
2521
+ }
2522
+ }
2523
+ return out.sort((a, b) => byCodeUnit(a.locale, b.locale) || byCodeUnit(a.key, b.key));
2524
+ }
2525
+ function acceptOutdated(cfg, catalogs, fingerprints, entries) {
2526
+ const source = catalogs[cfg.sourceLocale] ?? {};
2527
+ for (const { locale, key } of entries) {
2528
+ const text = own(source, key);
2529
+ const translated = own(catalogs[locale] ?? {}, key);
2530
+ if (!text || !translated) continue;
2531
+ (fingerprints[locale] ??= emptyCatalog())[key] = stamp(text, translated);
2532
+ }
2533
+ }
2534
+ function flatCatalogs(catalogs) {
2535
+ const out = emptyCatalog();
2536
+ for (const [locale, catalog] of Object.entries(catalogs)) out[locale] = flatten(catalog);
2537
+ return out;
2538
+ }
2539
+ // src/gate/findings.ts
2540
+ function siteOf(msg) {
2541
+ return {
2542
+ file: msg.file,
2543
+ line: msg.line,
2544
+ message: msg.message
2545
+ };
2546
+ }
2547
+ function collisionEntries(registry) {
2548
+ return registry.collisions().map(({ key, kept, dropped }) => ({
2549
+ key,
2550
+ sites: [kept, ...dropped].map(siteOf)
2551
+ }));
2552
+ }
2553
+ function scanFindings(cfg, registry, replaced = []) {
2554
+ const messages = registry.messages();
2555
+ const out = [];
2556
+ for (const { key, before } of replaced) {
2522
2557
  const msg = messages.get(key);
2523
2558
  if (msg) out.push({
2524
2559
  kind: "replaced",
@@ -2560,7 +2595,7 @@ function scanFindings(cfg, registry, replaced = []) {
2560
2595
  return out;
2561
2596
  }
2562
2597
  function sourcePlace(at, root) {
2563
- const file = root ? relative(root, at.file).replaceAll("\\", "/") : at.file;
2598
+ const file = root ? relativePath(root, at.file) : at.file;
2564
2599
  return at.line ? `${file}:${at.line}` : file;
2565
2600
  }
2566
2601
  function quoted(at, root) {
@@ -2661,7 +2696,7 @@ async function syncProject(cfg, options = {}) {
2661
2696
  const result = {
2662
2697
  registry,
2663
2698
  catalogs,
2664
- messages: Object.keys(catalogs[cfg.sourceLocale] ?? {}).length,
2699
+ messages: Object.keys(catalogs[cfg.sourceLocale] ?? emptyCatalog()).length,
2665
2700
  inCode: registry.messages().size,
2666
2701
  added,
2667
2702
  replaced,
@@ -2675,9 +2710,9 @@ async function syncProject(cfg, options = {}) {
2675
2710
  if (replaced.length > 0) changed.add(cfg.sourceLocale);
2676
2711
  for (const locale of cfg.locales) {
2677
2712
  if (options.write === "changed" && !changed.has(locale)) continue;
2678
- result.written[locale] = writeCatalog(cfg, locale, catalogs[locale] ?? {});
2713
+ result.written[locale] = writeCatalog(cfg, locale, catalogs[locale] ?? emptyCatalog());
2679
2714
  }
2680
- writeDts(cfg, catalogs[cfg.sourceLocale] ?? {});
2715
+ writeDts(cfg, catalogs[cfg.sourceLocale] ?? emptyCatalog());
2681
2716
  const before = stateFile(cfg);
2682
2717
  try {
2683
2718
  result.state = updateState(cfg, catalogs);
@@ -2692,7 +2727,7 @@ async function syncProject(cfg, options = {}) {
2692
2727
  return result;
2693
2728
  }
2694
2729
  function confirmFromDisk(cfg, catalogs, registry) {
2695
- const source = catalogs[cfg.sourceLocale] ?? {};
2730
+ const source = catalogs[cfg.sourceLocale] ?? emptyCatalog();
2696
2731
  const stale = /* @__PURE__ */ new Set();
2697
2732
  for (const [key, msg] of registry.messages()) if (own(source, key) !== msg.message) stale.add(msg.file);
2698
2733
  for (const file of stale) {
@@ -2749,7 +2784,7 @@ async function translateCatalogs(cfg, catalogs, provider, options = {}) {
2749
2784
  const retries = Math.max(0, options.retries ?? 2);
2750
2785
  const retryDelay = options.retryDelay ?? 500;
2751
2786
  const targets = targetLocales(cfg, options.locales);
2752
- const source = catalogs[cfg.sourceLocale] ?? {};
2787
+ const source = catalogs[cfg.sourceLocale] ?? emptyCatalog();
2753
2788
  const result = {
2754
2789
  translated: emptyCatalog(),
2755
2790
  invalid: emptyCatalog(),
@@ -2826,7 +2861,7 @@ function mergeTranslations(cfg, locale, translated, keys) {
2826
2861
  const current = readCatalog(cfg, locale);
2827
2862
  const written = [];
2828
2863
  for (const key of keys) {
2829
- const text = translated[key];
2864
+ const text = own(translated, key);
2830
2865
  if (!source[key] || current[key] || !text) continue;
2831
2866
  current[key] = text;
2832
2867
  written.push(key);
@@ -2835,10 +2870,12 @@ function mergeTranslations(cfg, locale, translated, keys) {
2835
2870
  return written;
2836
2871
  }
2837
2872
  function writeDrafts(cfg, locale, entries, options = {}) {
2838
- const targets = targetLocales(cfg);
2839
- if (!targets.includes(locale)) throw new Error(`[verbaly] "${locale}" is not a language this project translates into (${targets.join(", ") || "none yet"})`);
2873
+ const typo = strangerLocales(cfg, "locale", [locale]);
2874
+ if (typo) throw new Error(typo);
2875
+ if (locale === cfg.sourceLocale) throw new Error(`[verbaly] "${locale}" is not a language this project translates into (${targetLocales(cfg).join(", ") || "none yet"})`);
2840
2876
  loadState(cfg);
2841
- const catalogs = { [cfg.sourceLocale]: readCatalog(cfg, cfg.sourceLocale) };
2877
+ const catalogs = emptyCatalog();
2878
+ catalogs[cfg.sourceLocale] = readCatalog(cfg, cfg.sourceLocale);
2842
2879
  const source = options.registry ? shippedCatalogs(cfg, catalogs, options.registry, { newKeys: false })[cfg.sourceLocale] : catalogs[cfg.sourceLocale];
2843
2880
  const current = readCatalog(cfg, locale);
2844
2881
  const result = {
@@ -2889,16 +2926,9 @@ function formatTranslateFailures(failed) {
2889
2926
  async function resolveProvider(cfg, model) {
2890
2927
  const configured = cfg.translate.provider;
2891
2928
  if (typeof configured === "function") return configured;
2892
- const { claudeProvider } = await import("./claude-D31sQLmS.js");
2929
+ const { claudeProvider } = await import("./claude-BSLi4_54.js");
2893
2930
  return claudeProvider({ model: model ?? cfg.translate.model });
2894
2931
  }
2895
- function structureMatches(source, translated) {
2896
- try {
2897
- return ![...validateMessage(translated), ...validatePair(source, translated)].some((issue) => issue.severity === "error");
2898
- } catch {
2899
- return false;
2900
- }
2901
- }
2902
2932
  function progressOf(job) {
2903
2933
  return {
2904
2934
  locale: job.locale,
@@ -2921,6 +2951,7 @@ function glossaryFor(cfg, locale, messages) {
2921
2951
  }
2922
2952
  // src/project/translate.ts
2923
2953
  async function translateProject(cfg, options = {}) {
2954
+ if (options.locales) targetLocales(cfg, options.locales);
2924
2955
  const dryRun = options.dryRun === true;
2925
2956
  if (!dryRun) loadState(cfg);
2926
2957
  const registry = await extractProject(cfg);
@@ -2970,7 +3001,7 @@ function gatePasses(result) {
2970
3001
  return result.missing.length === 0 && result.unknown.length === 0 && result.collisions.length === 0 && !result.broken.some((entry) => entry.severity === "error");
2971
3002
  }
2972
3003
  function relativeCheck(root, result) {
2973
- const rel = (file) => relative(root, file).replaceAll("\\", "/");
3004
+ const rel = (file) => relativePath(root, file);
2974
3005
  return {
2975
3006
  ...result,
2976
3007
  unknown: result.unknown.map((entry) => ({
@@ -3003,13 +3034,25 @@ function warningCount(result) {
3003
3034
  function check(cfg, catalogs, registry, fingerprints = emptyCatalog()) {
3004
3035
  return gatePass(() => checkPass(cfg, catalogs, registry, fingerprints));
3005
3036
  }
3006
- function checkPass(cfg, catalogs, registry, fingerprints) {
3007
- const extracted = registry.messages();
3037
+ function gateViews(cfg, catalogs, registry) {
3008
3038
  const flat = emptyCatalog();
3009
3039
  for (const locale of cfg.locales) flat[locale] = flatView(catalogs[locale] ?? {});
3010
3040
  const source = flat[cfg.sourceLocale] ?? {};
3011
3041
  const shipped = shippedCatalogs(cfg, flat, registry);
3012
- const sourceText = shipped[cfg.sourceLocale];
3042
+ return {
3043
+ flat,
3044
+ source,
3045
+ shipped,
3046
+ sourceText: shipped[cfg.sourceLocale]
3047
+ };
3048
+ }
3049
+ function translationIssues(locale, translated, text) {
3050
+ const issues = validateMessage(translated, locale);
3051
+ return text ? [...issues, ...validatePair(text, translated)] : issues;
3052
+ }
3053
+ function checkPass(cfg, catalogs, registry, fingerprints) {
3054
+ const extracted = registry.messages();
3055
+ const { flat, source, shipped, sourceText } = gateViews(cfg, catalogs, registry);
3013
3056
  const used = registry.usedKeys();
3014
3057
  const unknown = [];
3015
3058
  for (const [key, files] of registry.usedKeys(true)) if (!(extracted.has(key) || cfg.locales.some((locale) => flat[locale]?.[key] !== void 0))) unknown.push({
@@ -3054,9 +3097,7 @@ function checkPass(cfg, catalogs, registry, fingerprints) {
3054
3097
  if (locale === cfg.sourceLocale) continue;
3055
3098
  for (const [key, translated] of Object.entries(flat[locale] ?? {})) {
3056
3099
  if (!translated) continue;
3057
- add(locale, key, validateMessage(translated, locale));
3058
- const text = sourceText[key];
3059
- if (text) add(locale, key, validatePair(text, translated));
3100
+ add(locale, key, translationIssues(locale, translated, sourceText[key]));
3060
3101
  }
3061
3102
  }
3062
3103
  const extra = [];
@@ -3088,8 +3129,9 @@ function checkPass(cfg, catalogs, registry, fingerprints) {
3088
3129
  outdated: outdatedTranslations(cfg, shipped, fingerprints)
3089
3130
  };
3090
3131
  }
3132
+ // src/gate/report.ts
3091
3133
  function formatCheckResult(result, root) {
3092
- const show = (file) => root ? relative(root, file).replaceAll("\\", "/") : file;
3134
+ const show = (file) => root ? relativePath(root, file) : file;
3093
3135
  const lines = [];
3094
3136
  if (result.missing.length > 0) {
3095
3137
  lines.push("missing translations:");
@@ -3114,7 +3156,7 @@ function formatCheckResult(result, root) {
3114
3156
  return lines.join("\n");
3115
3157
  }
3116
3158
  function formatBuildReport(result, sourceLocale, root, cap = 5) {
3117
- const show = (file) => root ? relative(root, file).replaceAll("\\", "/") : file;
3159
+ const show = (file) => root ? relativePath(root, file) : file;
3118
3160
  const lines = [];
3119
3161
  const list = (entries, line) => {
3120
3162
  for (const entry of entries.slice(0, cap)) lines.push(` ${line(entry)}`);
@@ -3164,7 +3206,7 @@ function formatCheckWarnings(result, root, options = {}) {
3164
3206
  }
3165
3207
  function githubCheckAnnotations(result, registry, cfg, options = {}) {
3166
3208
  const messages = registry.messages();
3167
- const rel = (file) => escapeProperty(relative(cfg.root, file).replaceAll("\\", "/"));
3209
+ const rel = (file) => escapeProperty(relativePath(cfg.root, file));
3168
3210
  const at = (file, line) => `file=${rel(file)}${line ? `,line=${line}` : ""}`;
3169
3211
  const lines = [];
3170
3212
  const byKey = /* @__PURE__ */ new Map();
@@ -3225,148 +3267,6 @@ function escapeData(text) {
3225
3267
  function escapeProperty(text) {
3226
3268
  return escapeData(text).replaceAll(":", "%3A").replaceAll(",", "%2C");
3227
3269
  }
3228
- // src/scan/transform.ts
3229
- function quote(text, single) {
3230
- return single ? singleQuoted(text) : JSON.stringify(text);
3231
- }
3232
- function transformCode(code, file, analysis, options = {}) {
3233
- const own = analysis ?? analyzeFile(code, file);
3234
- if (!analysis && own.parseError) warnParseError(file, own.parseError);
3235
- const { tagged } = own;
3236
- const appAt = options.appImport && !own.appImported ? own.adapterImport : void 0;
3237
- if (tagged.length === 0 && appAt === void 0) return null;
3238
- const s = new MagicString(code);
3239
- if (appAt !== void 0) s.appendLeft(appAt, `import '${APP_ID}'; `);
3240
- for (const msg of tagged) {
3241
- const seen = /* @__PURE__ */ new Set();
3242
- const entries = msg.params.filter((p) => !seen.has(p.name) && seen.add(p.name));
3243
- const pairs = entries.map((p) => `${quote(p.name, msg.singleQuote)}: ${code.slice(p.start, p.end)}`).join(", ");
3244
- if (msg.jsx) {
3245
- const values = entries.length ? ` values={{ ${pairs} }}` : "";
3246
- const components = msg.jsx.components.length ? ` components={{ ${msg.jsx.components.map((c) => `${JSON.stringify(c.name)}: ${c.source}`).join(", ")} }}` : "";
3247
- const quoted = JSON.stringify(msg.key);
3248
- const id = quoted === `"${msg.key}"` ? quoted : `{${quoted}}`;
3249
- s.overwrite(msg.start, msg.end, `<${msg.jsx.name} id=${id}${values}${components} />`);
3250
- continue;
3251
- }
3252
- const tagSource = code.slice(msg.tagStart, msg.tagEnd);
3253
- const args = entries.length ? `, { ${pairs} }` : "";
3254
- s.overwrite(msg.start, msg.end, `${tagSource}(${quote(msg.key, msg.singleQuote)}${args})`);
3255
- }
3256
- return {
3257
- code: s.toString(),
3258
- map: s.generateMap({ hires: true })
3259
- };
3260
- }
3261
- // src/emit/plugin.ts
3262
- const RESOLVED_VIRTUAL_ID = "\0" + VIRTUAL_ID;
3263
- const LOCALE_MODULE_PREFIX = `${RESOLVED_VIRTUAL_ID}/locale/`;
3264
- const SOURCE_FILE_RE = /\.(?:[cm]?[jt]sx?|svelte|vue|astro)$/;
3265
- function resolveVirtualId(id) {
3266
- if (isAppModule(id)) return RESOLVED_VIRTUAL_ID;
3267
- if (id.startsWith("@verbaly/app/locale/")) return LOCALE_MODULE_PREFIX + id.slice(20);
3268
- if (id.startsWith(`virtual:verbaly/`)) return "\0" + id;
3269
- }
3270
- function clientModules(cfg, catalogs, options = {}) {
3271
- const client = clientCatalogs(cfg, catalogs);
3272
- return {
3273
- runtime: () => generateRuntimeModule(cfg, {
3274
- ...options,
3275
- icu: cfg.icu ?? needsIcu(client),
3276
- relative: cfg.relative ?? needsRelative(client),
3277
- inlineCatalog: cfg.render.inlineCatalog === true
3278
- }),
3279
- locale: (locale) => generateLocaleModule(own(client, locale) ?? {})
3280
- };
3281
- }
3282
- function loadVirtualModule(id, cfg, catalogs) {
3283
- if (id === RESOLVED_VIRTUAL_ID) return clientModules(cfg, catalogs).runtime();
3284
- if (id.startsWith(LOCALE_MODULE_PREFIX)) return clientModules(cfg, catalogs).locale(id.slice(LOCALE_MODULE_PREFIX.length));
3285
- }
3286
- function isTransformTarget(id) {
3287
- return SOURCE_FILE_RE.test(id) && !id.includes("node_modules") && !id.startsWith("\0");
3288
- }
3289
- function createSourceFilter(cfg) {
3290
- if (cfg.include.length === 0) return () => false;
3291
- const matches = picomatch(cfg.include, { ignore: cfg.exclude });
3292
- return (id) => {
3293
- const rel = relative(cfg.root, id).replaceAll("\\", "/");
3294
- return !rel.startsWith("..") && matches(rel);
3295
- };
3296
- }
3297
- function transformSource(code, id, registry, scan) {
3298
- const analysis = (scan && scannedAnalysis(scan, id, code)) ?? analyzeFile(code, id);
3299
- registry.update(id, analysis);
3300
- if (analysis.parseError) warnParseError(id, analysis.parseError);
3301
- const messages = emptyCatalog();
3302
- for (const msg of analysis.tagged) messages[msg.key] ??= msg.message;
3303
- return {
3304
- messages,
3305
- result: transformCode(code, id, analysis, { appImport: true }) ?? null
3306
- };
3307
- }
3308
- function writeBuildTypes(cfg, catalogs) {
3309
- try {
3310
- writeDts(cfg, catalogs[cfg.sourceLocale] ?? {});
3311
- } catch (error) {
3312
- const code = error?.code;
3313
- if (typeof code !== "string") throw error;
3314
- warnOnce(`could not write the types to ${cfg.dts === false ? "" : relative(cfg.root, cfg.dts).replaceAll("\\", "/")} (${code}): run \`npx verbaly typegen\` where the project can be written`, `types:${cfg.root}`);
3315
- }
3316
- }
3317
- function runBuildGate(cfg, registry, failOnMissing) {
3318
- const catalogs = loadCatalogs(cfg);
3319
- for (const issue of auditBundle(cfg, catalogs, registry)) warnOnce(`${formatBundleIssue(issue)}\n fix: ${issue.fix}`, `bundle:${issue.prefix}`);
3320
- const found = check(cfg, catalogs, registry, buildFingerprints(cfg));
3321
- if (failOnMissing === true && !gatePasses(found)) throw new Error(`[verbaly] build blocked\n${formatCheckResult(found, cfg.root)}\n${checkNextSteps(found, cliReachable(cfg.root))}`);
3322
- reportGate(cfg, found);
3323
- const warnings = warningCount(found);
3324
- if (warnings > 0) {
3325
- const once = onceMoved(cfg.root);
3326
- const read = once ? `\`npx verbaly check\` reads them${once}` : "run `npx verbaly check` to read them";
3327
- warnOnce(`check has ${counted(warnings, "warning")}, and the build still passes: ${read}`, "gate:warnings");
3328
- }
3329
- }
3330
- function onceMoved(root) {
3331
- const moved = pluginOnlyOptions(root);
3332
- if (!moved) return "";
3333
- return ` once ${moved} ${moved.includes(" and ") ? "move" : "moves"} to verbaly.config`;
3334
- }
3335
- const reported = /* @__PURE__ */ new Map();
3336
- function reportGate(cfg, found) {
3337
- const before = reported.get(cfg.root) ?? /* @__PURE__ */ new Set();
3338
- const now = /* @__PURE__ */ new Set();
3339
- const fresh = (entries, id) => entries.filter((entry) => {
3340
- const key = id(entry);
3341
- now.add(key);
3342
- return !before.has(key);
3343
- });
3344
- const report = {
3345
- broken: fresh(found.broken.filter((entry) => entry.severity === "error"), (entry) => `broken:${entry.locale}:${entry.key}:${entry.issue}`),
3346
- missing: fresh(found.missing, (entry) => `missing:${entry.locale}:${entry.key}`),
3347
- unknown: fresh(found.unknown, (entry) => `unknown:${entry.key}`),
3348
- collisions: fresh(found.collisions, (entry) => `collision:${entry.key}`)
3349
- };
3350
- reported.set(cfg.root, now);
3351
- const lines = formatBuildReport(report, cfg.sourceLocale, cfg.root);
3352
- if (lines.length === 0) return;
3353
- const steps = checkNextSteps({
3354
- ...found,
3355
- ...report
3356
- }, cliReachable(cfg.root));
3357
- const block = [
3358
- ...lines.map((line) => line.startsWith(" ") ? line : `[verbaly] ${line}`),
3359
- "[verbaly] to fix them:",
3360
- ...steps.split("\n").map((step) => ` ${step}`),
3361
- `[verbaly] \`npx verbaly check\` lists every one${onceMoved(cfg.root)}, and in your CI it stops a release on them`
3362
- ];
3363
- console.warn(block.join("\n"));
3364
- }
3365
- function buildFingerprints(cfg) {
3366
- const { state, problem } = readState(cfg);
3367
- if (problem) warnOnce(`${problem}, so outdated translations are not reported`, "gate:state");
3368
- return state.fingerprints;
3369
- }
3370
3270
  // src/scan/scope.ts
3371
3271
  const TAGGED_HINT = /(?<![\w$.])\$?t(?:\.id\s*\([^)]*\))?\s*`/;
3372
3272
  const NOT_SOURCE = [
@@ -3377,7 +3277,7 @@ const NOT_SOURCE = [
3377
3277
  "**/coverage/**"
3378
3278
  ];
3379
3279
  function relativeId(cfg, id) {
3380
- return relative(cfg.root, id).replaceAll("\\", "/");
3280
+ return relativePath(cfg.root, id);
3381
3281
  }
3382
3282
  function suggestedPattern(rel) {
3383
3283
  const slash = rel.indexOf("/");
@@ -3436,13 +3336,9 @@ async function filesOutsideInclude(cfg) {
3436
3336
  // src/gate/status.ts
3437
3337
  function status(cfg, catalogs, registry, drafts = emptyCatalog(), fingerprints = emptyCatalog()) {
3438
3338
  const extracted = registry.messages();
3439
- const flat = emptyCatalog();
3440
- for (const locale of cfg.locales) flat[locale] = flatView(catalogs[locale] ?? {});
3441
- const source = flat[cfg.sourceLocale] ?? {};
3339
+ const { flat, source, shipped, sourceText } = gateViews(cfg, catalogs, registry);
3442
3340
  const needed = /* @__PURE__ */ new Set([...extracted.keys(), ...Object.keys(source)]);
3443
3341
  const live = effectiveDrafts(drafts, flat);
3444
- const shipped = shippedCatalogs(cfg, flat, registry);
3445
- const sourceText = shipped[cfg.sourceLocale];
3446
3342
  const outdated = outdatedTranslations(cfg, shipped, fingerprints);
3447
3343
  const locales = [];
3448
3344
  for (const locale of cfg.locales) {
@@ -3453,8 +3349,7 @@ function status(cfg, catalogs, registry, drafts = emptyCatalog(), fingerprints =
3453
3349
  let broken = 0;
3454
3350
  for (const [key, text] of Object.entries(catalog)) {
3455
3351
  if (!text) continue;
3456
- const from = sourceText[key];
3457
- if ([...validateMessage(text, locale), ...from ? validatePair(from, text) : []].some((issue) => issue.severity === "error")) broken += 1;
3352
+ if (translationIssues(locale, text, sourceText[key]).some((issue) => issue.severity === "error")) broken += 1;
3458
3353
  }
3459
3354
  locales.push({
3460
3355
  locale,
@@ -3562,7 +3457,7 @@ async function checkCommand(cfg, values) {
3562
3457
  }
3563
3458
  const registry = await extractProject(cfg);
3564
3459
  const catalogs = loadCatalogs(cfg);
3565
- const state = checkState(cfg, values.drafts === true || values.outdated === true);
3460
+ const state = checkState$1(cfg, values.drafts === true || values.outdated === true);
3566
3461
  const result = check(cfg, catalogs, registry, state.fingerprints);
3567
3462
  const unreviewed = values.drafts ? effectiveDrafts(state.drafts, catalogs) : {};
3568
3463
  const outdated = values.outdated ? result.outdated : [];
@@ -3588,7 +3483,7 @@ async function checkCommand(cfg, values) {
3588
3483
  }
3589
3484
  process.exitCode = 1;
3590
3485
  }
3591
- function checkState(cfg, gating) {
3486
+ function checkState$1(cfg, gating) {
3592
3487
  if (gating) return loadState(cfg);
3593
3488
  const { state, problem } = readState(cfg);
3594
3489
  if (problem) console.warn(`[verbaly] ${problem}, so outdated translations are not reported`);
@@ -3614,13 +3509,6 @@ function projectLocale(tag, locales) {
3614
3509
  }
3615
3510
  // src/project/doctor.ts
3616
3511
  const PREVIEW = 5;
3617
- function readRoutingChoice(root, configFile) {
3618
- try {
3619
- return /\brouting["']?\s*[:=]/.test(readFileSync(join(root, configFile), "utf8"));
3620
- } catch {
3621
- return false;
3622
- }
3623
- }
3624
3512
  function readAstroRouting(root, source) {
3625
3513
  for (const file of [
3626
3514
  "astro.config.mjs",
@@ -3666,31 +3554,63 @@ function formatDoctorHealth(result) {
3666
3554
  const warnings = result.entries.filter((entry) => entry.level === "warn").length;
3667
3555
  return warnings > 0 ? `setup works, with ${counted(warnings, "warning")} to read` : "setup looks healthy";
3668
3556
  }
3669
- async function doctor(cfg) {
3557
+ function createReport(cfg) {
3670
3558
  const entries = [];
3671
- const ok = (name, message) => entries.push({
3672
- level: "ok",
3673
- check: name,
3674
- message
3675
- });
3676
- const warn = (name, message, fix) => entries.push({
3677
- level: "warn",
3678
- check: name,
3679
- message,
3680
- fix
3681
- });
3682
- const error = (name, message, fix) => entries.push({
3683
- level: "error",
3684
- check: name,
3685
- message,
3686
- fix
3687
- });
3688
- const rel = (path) => relative(cfg.root, path).replaceAll("\\", "/");
3559
+ return {
3560
+ entries,
3561
+ ok: (name, message) => void entries.push({
3562
+ level: "ok",
3563
+ check: name,
3564
+ message
3565
+ }),
3566
+ warn: (name, message, fix) => void entries.push({
3567
+ level: "warn",
3568
+ check: name,
3569
+ message,
3570
+ fix
3571
+ }),
3572
+ error: (name, message, fix) => void entries.push({
3573
+ level: "error",
3574
+ check: name,
3575
+ message,
3576
+ fix
3577
+ }),
3578
+ rel: (path) => relativePath(cfg.root, path)
3579
+ };
3580
+ }
3581
+ async function doctor(cfg) {
3582
+ const report = createReport(cfg);
3583
+ const { ok } = report;
3584
+ const configFile = checkSetup(report, cfg);
3585
+ const { catalogs, catalogsHealthy, source } = checkCatalogs(report, cfg);
3586
+ checkRouting(report, cfg, configFile);
3587
+ const host = checkPlugin(report, cfg);
3588
+ const scanning = cfg.include.length > 0;
3589
+ if (!scanning) ok("sources", "source scanning is off (include: []), the catalogs are the source of truth");
3590
+ const registry = await extractProject(cfg);
3591
+ const messages = registry.messages();
3592
+ if (source && scanning) checkTypes(report, cfg, host, catalogs, registry, source);
3593
+ if (scanning) await checkSources(report, cfg, registry, messages);
3594
+ if (source && scanning) checkOrphans(report, source, registry, messages);
3595
+ if (catalogsHealthy) checkBundle(report, cfg, catalogs, registry);
3596
+ const state = checkState(report, cfg, catalogs, catalogsHealthy);
3597
+ if (catalogsHealthy) mirrorGate(report, cfg, catalogs, registry, state, scanning);
3598
+ return {
3599
+ ok: report.entries.every((entry) => entry.level !== "error"),
3600
+ entries: report.entries
3601
+ };
3602
+ }
3603
+ function checkSetup(report, cfg) {
3604
+ const { ok, warn } = report;
3689
3605
  const configFile = findConfigFile(cfg.root);
3690
3606
  if (configFile) ok("config", `${configFile} found`);
3691
3607
  else warn("config", "no config file, running on defaults", "run `npx verbaly init`");
3692
3608
  if (cliReachable(cfg.root)) ok("cli", "the verbaly command is available in this project");
3693
3609
  else warn("cli", "the verbaly command is not linked in node_modules/.bin", CLI_INSTALL_FIX);
3610
+ return configFile;
3611
+ }
3612
+ function checkCatalogs(report, cfg) {
3613
+ const { ok, warn, error, rel } = report;
3694
3614
  const catalogs = emptyCatalog();
3695
3615
  let catalogsHealthy = true;
3696
3616
  if (!existsSync(cfg.dir)) {
@@ -3734,11 +3654,19 @@ async function doctor(cfg) {
3734
3654
  }
3735
3655
  const source = catalogs[cfg.sourceLocale];
3736
3656
  if (source && Object.keys(source).length === 0) warn("source", `source catalog ${cfg.sourceLocale}.json is empty`, "write your first t`…` message and run `npx verbaly extract`");
3737
- const mirrors = cfg.render.site !== void 0 || Object.keys(cfg.render).length > 0;
3657
+ return {
3658
+ catalogs,
3659
+ catalogsHealthy,
3660
+ source
3661
+ };
3662
+ }
3663
+ function checkRouting(report, cfg, configFile) {
3664
+ const { ok, warn } = report;
3665
+ const mirrors = Object.keys(cfg.render).length > 0;
3738
3666
  if (cfg.routing === "no-prefix" && mirrors) warn("routing", "routing is \"no-prefix\" but a render section is configured, and render writes one url tree per locale", "drop the render section, or set routing to \"prefix-except-source\" so the helpers agree with the urls");
3739
3667
  else if (cfg.routing === "prefix-all" && mirrors) warn("routing", `routing is "prefix-all" but render keeps ${cfg.sourceLocale} at the root, so its links point at a /${cfg.sourceLocale}/ tree nobody wrote`, "set routing to \"prefix-except-source\", the url tree render writes");
3740
3668
  else {
3741
- const named = configFile ? readRoutingChoice(cfg.root, configFile) : false;
3669
+ const named = configFile !== void 0 && cfg.routingDeclared;
3742
3670
  const astro = cfg.host === "astro" && cfg.routing === "no-prefix" ? readAstroRouting(cfg.root, cfg.sourceLocale) : void 0;
3743
3671
  if (astro && named) warn("routing", `routing is "no-prefix" in ${configFile}, but @verbaly/astro uses ${astro.mode}: Astro's i18n in ${astro.file} puts the language in the url`, `remove routing from ${configFile}, or remove i18n from ${astro.file}`);
3744
3672
  else if (astro) {
@@ -3749,77 +3677,86 @@ async function doctor(cfg) {
3749
3677
  ok("routing", `${cfg.routing}${how}: ${ROUTING_SAYS[cfg.routing]}`);
3750
3678
  }
3751
3679
  }
3680
+ }
3681
+ function checkPlugin(report, cfg) {
3682
+ const { ok, warn } = report;
3752
3683
  const deps = readDependencies(cfg.root);
3753
3684
  const host = detectHost(cfg.root);
3754
3685
  const installed = WIRING_PACKAGES.find((pkg) => deps[pkg]);
3755
3686
  if (!host) ok("plugin", "no framework or bundler detected, the CLI flow (extract/check) applies");
3756
3687
  else if (installed) ok("plugin", `${installed} installed for ${host.name}`);
3757
3688
  else warn("plugin", `${host.name} detected but ${host.pkg} is not installed`, `${installCommand(cfg.root, host.install)}, then ${host.wire}`);
3758
- const scanning = cfg.include.length > 0;
3759
- if (!scanning) ok("sources", "source scanning is off (include: []), the catalogs are the source of truth");
3760
- const registry = await extractProject(cfg);
3761
- if (source && scanning && cfg.dts !== false) {
3762
- const dtsPath = cfg.dts;
3763
- const shown = rel(dtsPath);
3764
- const regenerate = host?.name === "astro" ? "run `npx astro sync`, which writes the types and links them" : host?.name === "nuxt" ? "run `npx nuxi prepare`, which writes the types and links them" : "run `npx verbaly typegen`";
3765
- const expected = generateDts(shippedCatalogs(cfg, catalogs, registry)[cfg.sourceLocale] ?? source, projectDtsOptions(cfg));
3766
- if (!existsSync(dtsPath)) warn("types", `${shown} has not been generated`, regenerate);
3767
- else if (readFileSync(dtsPath, "utf8").replace(/\r\n/g, "\n") !== expected) warn("types", `${shown} is stale`, "run `npx verbaly typegen`");
3768
- else ok("types", `${shown} is up to date`);
3769
- if (dtsPath.startsWith(join(cfg.root, ".verbaly"))) {
3770
- const state = typesIncluded(cfg.root, dtsPath);
3771
- if (state === "missing" || state === "unreadable") warn("types", state === "missing" ? `tsconfig.json does not include ${shown}, so TypeScript never reads the types` : `tsconfig.json could not be read, so it may not include ${shown}`, `run \`npx verbaly typegen\`, which adds the line, or add "${shown}" to include`);
3772
- }
3773
- const old = join(cfg.root, "verbaly.d.ts");
3774
- if (dtsPath !== old && existsSync(old) && readFileSync(old, "utf8").startsWith("// generated by verbaly: do not edit")) warn("types", `the verbaly.d.ts Verbaly wrote at the root is still there next to ${shown}, and they declare the same module twice`, "run `npx verbaly typegen`, which removes it");
3775
- }
3776
- if (scanning) {
3777
- const unreadable = registry.parseErrors();
3778
- if (unreadable.length > 0) {
3779
- const first = unreadable[0];
3780
- warn("sources", `could not parse ${counted(unreadable.length, "file")}, so the messages inside are not extracted (${rel(first.file)}: ${first.message})`, "fix the syntax error, or exclude the file in your config if it is not source");
3781
- }
3782
- const outside = await filesOutsideInclude(cfg);
3783
- if (outside.length > 0) {
3784
- const files = outside.map((entry) => rel(entry.file));
3785
- const patterns = [...new Set(outside.map((entry) => `"${entry.pattern}"`))];
3786
- warn("sources", `t\`…\` is written in ${counted(outside.length, "file")} outside include, and those texts are never extracted or translated (${preview(files)})`, `add ${patterns.join(" and ")} to include in your verbaly config, or the files to exclude if they are not app code`);
3787
- }
3788
- const stray = registry.strayImports();
3789
- if (stray.length > 0) {
3790
- const files = [...new Set(stray.map((entry) => rel(entry.file)))];
3791
- 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 verbaly/app");
3792
- }
3793
- const missed = registry.missed();
3794
- if (missed.length > 0) {
3795
- const first = missed[0];
3796
- warn("sources", `a t under another name keeps ${counted(missed.length, "text")} out of extraction (${sourcePlace(first, cfg.root)}: ${first.name}\`…\`)`, "name it t (const t = useT()), the only name verbaly reads, or use t(key) with the key in the catalog");
3797
- }
3798
- const positional = [...registry.messages().values()].filter((msg) => msg.params.some((param) => /^_\d+$/.test(param.name)));
3799
- if (positional.length > 0) {
3800
- const first = positional[0];
3801
- warn("messages", `a translator gets a nameless value like {_0} in ${counted(positional.length, "message")} (${sourcePlace(first, cfg.root)}: "${first.message}")`, "put the value in a named variable first (const date = formatDate(d)), so the message says {date}");
3802
- }
3803
- const escaped = [...registry.messages().values()].map((msg) => ({
3804
- file: rel(msg.file),
3805
- slice: escapedSyntax(msg.message)
3806
- })).filter((entry) => entry.slice !== void 0);
3807
- if (escaped.length > 0) warn("messages", `a block ships as literal text in ${counted(escaped.length, "extracted message")} (${escaped[0].file}: ${shownSlice(escaped[0].slice)})`, `in a tagged template, write ${inlineBlock(escaped[0].slice)}`);
3808
- }
3809
- if (source && scanning) {
3810
- const extracted = registry.messages();
3811
- const used = registry.usedKeys();
3812
- const orphans = Object.keys(source).filter((key) => !extracted.has(key) && !used.has(key));
3813
- const unread = registry.parseErrors().length > 0;
3814
- if (orphans.length > 0) warn("orphans", `${counted(orphans.length, "catalog key")} no longer referenced in code (${preview(orphans)})`, unread ? "fix the files that do not parse first, they may use these, and `npx verbaly extract --prune` leaves every key alone until then" : "run `npx verbaly extract --prune` to drop them");
3815
- else ok("orphans", "no orphan keys");
3689
+ return host;
3690
+ }
3691
+ function checkTypes(report, cfg, host, catalogs, registry, source) {
3692
+ const { ok, warn, rel } = report;
3693
+ if (cfg.dts === false) return;
3694
+ const dtsPath = cfg.dts;
3695
+ const shown = rel(dtsPath);
3696
+ const regenerate = host?.name === "astro" ? "run `npx astro sync`, which writes the types and links them" : host?.name === "nuxt" ? "run `npx nuxi prepare`, which writes the types and links them" : "run `npx verbaly typegen`";
3697
+ const expected = generateDts(shippedCatalogs(cfg, catalogs, registry)[cfg.sourceLocale] ?? source, projectDtsOptions(cfg));
3698
+ if (!existsSync(dtsPath)) warn("types", `${shown} has not been generated`, regenerate);
3699
+ else if (readFileSync(dtsPath, "utf8").replace(/\r\n/g, "\n") !== expected) warn("types", `${shown} is stale`, "run `npx verbaly typegen`");
3700
+ else ok("types", `${shown} is up to date`);
3701
+ if (dtsPath.startsWith(join(cfg.root, ".verbaly"))) {
3702
+ const state = typesIncluded(cfg.root, dtsPath);
3703
+ if (state === "missing" || state === "unreadable") warn("types", state === "missing" ? `tsconfig.json does not include ${shown}, so TypeScript never reads the types` : `tsconfig.json could not be read, so it may not include ${shown}`, `run \`npx verbaly typegen\`, which adds the line, or add "${shown}" to include`);
3816
3704
  }
3705
+ const old = join(cfg.root, "verbaly.d.ts");
3706
+ if (dtsPath !== old && existsSync(old) && readFileSync(old, "utf8").startsWith("// generated by verbaly: do not edit")) warn("types", `the verbaly.d.ts Verbaly wrote at the root is still there next to ${shown}, and they declare the same module twice`, "run `npx verbaly typegen`, which removes it");
3707
+ }
3708
+ async function checkSources(report, cfg, registry, messages) {
3709
+ const { warn, error, rel } = report;
3710
+ const unreadable = registry.parseErrors();
3711
+ if (unreadable.length > 0) {
3712
+ const first = unreadable[0];
3713
+ warn("sources", `could not parse ${counted(unreadable.length, "file")}, so the messages inside are not extracted (${rel(first.file)}: ${first.message})`, "fix the syntax error, or exclude the file in your config if it is not source");
3714
+ }
3715
+ const outside = await filesOutsideInclude(cfg);
3716
+ if (outside.length > 0) {
3717
+ const files = outside.map((entry) => rel(entry.file));
3718
+ const patterns = [...new Set(outside.map((entry) => `"${entry.pattern}"`))];
3719
+ warn("sources", `t\`…\` is written in ${counted(outside.length, "file")} outside include, and those texts are never extracted or translated (${preview(files)})`, `add ${patterns.join(" and ")} to include in your verbaly config, or the files to exclude if they are not app code`);
3720
+ }
3721
+ const stray = registry.strayImports();
3722
+ if (stray.length > 0) {
3723
+ const files = [...new Set(stray.map((entry) => rel(entry.file)))];
3724
+ 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 verbaly/app");
3725
+ }
3726
+ const missed = registry.missed();
3727
+ if (missed.length > 0) {
3728
+ const first = missed[0];
3729
+ warn("sources", `a t under another name keeps ${counted(missed.length, "text")} out of extraction (${sourcePlace(first, cfg.root)}: ${first.name}\`…\`)`, "name it t (const t = useT()), the only name verbaly reads, or use t(key) with the key in the catalog");
3730
+ }
3731
+ const positional = [...messages.values()].filter((msg) => msg.params.some((param) => /^_\d+$/.test(param.name)));
3732
+ if (positional.length > 0) {
3733
+ const first = positional[0];
3734
+ warn("messages", `a translator gets a nameless value like {_0} in ${counted(positional.length, "message")} (${sourcePlace(first, cfg.root)}: "${first.message}")`, "put the value in a named variable first (const date = formatDate(d)), so the message says {date}");
3735
+ }
3736
+ const escaped = [...messages.values()].map((msg) => ({
3737
+ file: rel(msg.file),
3738
+ slice: escapedSyntax(msg.message)
3739
+ })).filter((entry) => entry.slice !== void 0);
3740
+ if (escaped.length > 0) warn("messages", `a block ships as literal text in ${counted(escaped.length, "extracted message")} (${escaped[0].file}: ${shownSlice(escaped[0].slice)})`, `in a tagged template, write ${inlineBlock(escaped[0].slice)}`);
3741
+ }
3742
+ function checkOrphans(report, source, registry, extracted) {
3743
+ const { ok, warn } = report;
3744
+ const used = registry.usedKeys();
3745
+ const orphans = Object.keys(source).filter((key) => !extracted.has(key) && !used.has(key));
3746
+ const unread = registry.parseErrors().length > 0;
3747
+ if (orphans.length > 0) warn("orphans", `${counted(orphans.length, "catalog key")} no longer referenced in code (${preview(orphans)})`, unread ? "fix the files that do not parse first, they may use these, and `npx verbaly extract --prune` leaves every key alone until then" : "run `npx verbaly extract --prune` to drop them");
3748
+ else ok("orphans", "no orphan keys");
3749
+ }
3750
+ function checkBundle(report, cfg, catalogs, registry) {
3751
+ const { ok, warn } = report;
3817
3752
  const excluded = cfg.bundle.exclude ?? [];
3818
- if (excluded.length > 0 && catalogsHealthy) {
3819
- const issues = auditBundle(cfg, catalogs, registry);
3820
- for (const issue of issues) warn("bundle", formatBundleIssue(issue), issue.fix);
3821
- if (issues.length === 0) ok("bundle", `${counted(excluded.length, "group")} kept out of the client (${preview(excluded)})`);
3822
- }
3753
+ if (excluded.length === 0) return;
3754
+ const issues = auditBundle(cfg, catalogs, registry);
3755
+ for (const issue of issues) warn("bundle", formatBundleIssue(issue), issue.fix);
3756
+ if (issues.length === 0) ok("bundle", `${counted(excluded.length, "group")} kept out of the client (${preview(excluded)})`);
3757
+ }
3758
+ function checkState(report, cfg, catalogs, catalogsHealthy) {
3759
+ const { warn } = report;
3823
3760
  const { state, problem, conflict } = readState(cfg);
3824
3761
  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`);
3825
3762
  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");
@@ -3830,42 +3767,40 @@ async function doctor(cfg) {
3830
3767
  });
3831
3768
  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");
3832
3769
  }
3833
- if (catalogsHealthy) {
3834
- const result = check(cfg, catalogs, registry, state.fingerprints);
3835
- 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)");
3836
- if (result.missing.length > 0) {
3837
- const locales = [...new Set(result.missing.map((m) => m.locale))];
3838
- warn("translations", `${counted(result.missing.length, "missing translation")} (${locales.join(", ")})`, "run `npx verbaly translate` or fill the catalogs (`npx verbaly check` for details)");
3839
- }
3840
- const broken = result.broken.filter((entry) => entry.severity === "error");
3841
- if (broken.length > 0) {
3842
- const locales = [...new Set(broken.map((b) => b.locale))];
3843
- error("translations", `${counted(broken.length, "broken translation")} (${locales.join(", ")}): present but not rendering what the source renders`, "run `npx verbaly check` to read what each one lost");
3844
- }
3845
- if (result.extra.length > 0) {
3846
- const shown = result.extra.map((entry) => `${entry.locale}: ${entry.key}`);
3847
- warn("extras", `a translation has ${counted(result.extra.length, "key")} the source catalog does not (${preview(shown)})`, scanning ? "add them to the source catalog if your code uses them, or run `npx verbaly extract --prune` to drop the rest" : "add them to the source catalog if your code uses them, or delete them from the translations");
3848
- }
3849
- const warnings = result.broken.filter((entry) => entry.severity === "warning");
3850
- 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");
3851
- if (result.collisions.length > 0) {
3852
- const first = result.collisions[0];
3853
- 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)");
3854
- }
3855
- if (result.divergent.length > 0) {
3856
- const first = result.divergent[0];
3857
- 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");
3858
- }
3859
- if (result.outdated.length > 0) {
3860
- const shown = result.outdated.map((entry) => `${entry.locale}: ${entry.key}`);
3861
- 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`");
3862
- }
3863
- if (result.ok) ok("translations", "all translations complete");
3770
+ return state;
3771
+ }
3772
+ function mirrorGate(report, cfg, catalogs, registry, state, scanning) {
3773
+ const { ok, warn, error } = report;
3774
+ const result = check(cfg, catalogs, registry, state.fingerprints);
3775
+ 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)");
3776
+ if (result.missing.length > 0) {
3777
+ const locales = [...new Set(result.missing.map((m) => m.locale))];
3778
+ warn("translations", `${counted(result.missing.length, "missing translation")} (${locales.join(", ")})`, "run `npx verbaly translate` or fill the catalogs (`npx verbaly check` for details)");
3864
3779
  }
3865
- return {
3866
- ok: entries.every((entry) => entry.level !== "error"),
3867
- entries
3868
- };
3780
+ const broken = result.broken.filter((entry) => entry.severity === "error");
3781
+ if (broken.length > 0) {
3782
+ const locales = [...new Set(broken.map((b) => b.locale))];
3783
+ error("translations", `${counted(broken.length, "broken translation")} (${locales.join(", ")}): present but not rendering what the source renders`, "run `npx verbaly check` to read what each one lost");
3784
+ }
3785
+ if (result.extra.length > 0) {
3786
+ const shown = result.extra.map((entry) => `${entry.locale}: ${entry.key}`);
3787
+ warn("extras", `a translation has ${counted(result.extra.length, "key")} the source catalog does not (${preview(shown)})`, scanning ? "add them to the source catalog if your code uses them, or run `npx verbaly extract --prune` to drop the rest" : "add them to the source catalog if your code uses them, or delete them from the translations");
3788
+ }
3789
+ const warnings = result.broken.filter((entry) => entry.severity === "warning");
3790
+ 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");
3791
+ if (result.collisions.length > 0) {
3792
+ const first = result.collisions[0];
3793
+ 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)");
3794
+ }
3795
+ if (result.divergent.length > 0) {
3796
+ const first = result.divergent[0];
3797
+ 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");
3798
+ }
3799
+ if (result.outdated.length > 0) {
3800
+ const shown = result.outdated.map((entry) => `${entry.locale}: ${entry.key}`);
3801
+ 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`");
3802
+ }
3803
+ if (result.ok) ok("translations", "all translations complete");
3869
3804
  }
3870
3805
  function preview(keys) {
3871
3806
  const head = keys.slice(0, PREVIEW).join(", ");
@@ -3887,41 +3822,244 @@ async function doctorCommand(cfg) {
3887
3822
  process.exitCode = 1;
3888
3823
  }
3889
3824
  }
3890
- // src/util/markup.ts
3891
- const NAME$1 = `[^\\s=/"'<>]+`;
3892
- const ATTRIBUTE = new RegExp(`(${NAME$1})(?:\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s>]+)))?`, "g");
3893
- const ATTRIBUTE_NAME = new RegExp(`^${NAME$1}$`);
3894
- const TAG_REST = `(?:"[^"]*"|'[^']*'|[^"'>])*`;
3895
- function isAttributeName(name) {
3896
- return ATTRIBUTE_NAME.test(name);
3825
+ // src/exchange/mobile.ts
3826
+ function androidValuesDir(locale, sourceLocale) {
3827
+ if (locale === sourceLocale) return "values";
3828
+ const parts = locale.split("-");
3829
+ if (parts.length === 1) return `values-${locale}`;
3830
+ if (parts.length === 2 && /^[a-zA-Z]{2}$/.test(parts[1])) return `values-${parts[0]}-r${parts[1].toUpperCase()}`;
3831
+ return `values-b+${parts.join("+")}`;
3897
3832
  }
3898
- function readAttributes(chunk, lowerCase = false) {
3899
- const attributes = /* @__PURE__ */ new Map();
3900
- ATTRIBUTE.lastIndex = 0;
3901
- let match;
3902
- while ((match = ATTRIBUTE.exec(chunk)) !== null) {
3903
- const name = lowerCase ? match[1].toLowerCase() : match[1];
3904
- if (attributes.has(name)) continue;
3905
- const quoted = match[2] ?? match[3];
3906
- const value = quoted ?? match[4] ?? "";
3907
- const end = match.index + match[0].length;
3908
- const written = quoted !== void 0 ? value.length + 2 : value.length;
3909
- attributes.set(name, {
3910
- value,
3911
- start: end - written,
3912
- end
3913
- });
3914
- }
3915
- return attributes;
3833
+ function toAndroidXml(entries) {
3834
+ const names = /* @__PURE__ */ new Map();
3835
+ return [
3836
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>",
3837
+ "<resources>",
3838
+ ...entries.map(({ key, text }) => {
3839
+ const name = androidName(key);
3840
+ const clash = names.get(name);
3841
+ if (clash !== void 0) throw new Error(`[verbaly] android-xml: keys "${clash}" and "${key}" both become resource name "${name}", rename one of them`);
3842
+ names.set(name, key);
3843
+ return ` <string name="${name}">${androidText(text)}</string>`;
3844
+ }),
3845
+ "</resources>",
3846
+ ""
3847
+ ].join("\n");
3916
3848
  }
3917
- const ENTITY = /&(?:(lt|gt|amp|quot|apos)|#(\d+)|#[xX]([0-9a-fA-F]+));/g;
3918
- const NAMED = {
3919
- lt: "<",
3920
- gt: ">",
3921
- amp: "&",
3922
- quot: "\"",
3923
- apos: "'"
3924
- };
3849
+ function toIosStrings(entries) {
3850
+ return [...entries.map(({ key, text }) => `"${iosText(key)}" = "${iosText(text)}";`), ""].join("\n");
3851
+ }
3852
+ function androidName(key) {
3853
+ const name = key.replace(/[^A-Za-z0-9_]/g, "_");
3854
+ return /^[0-9]/.test(name) ? `_${name}` : name;
3855
+ }
3856
+ function androidText(text) {
3857
+ const escaped = text.replace(/\\/g, "\\\\").replace(/'/g, "\\'").replace(/"/g, "\\\"").replace(/\n/g, "\\n").replace(/\t/g, "\\t").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
3858
+ return /^[@?]/.test(escaped) ? `\\${escaped}` : escaped;
3859
+ }
3860
+ function iosText(text) {
3861
+ return text.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/\n/g, "\\n").replace(/\t/g, "\\t");
3862
+ }
3863
+ // src/exchange/csv.ts
3864
+ function toCsv(entries) {
3865
+ return [
3866
+ "key,source,target,location",
3867
+ ...entries.map(({ key, source, target, location }) => `${csvField(key)},${csvField(source)},${csvField(target)},${csvField(location?.join("; ") ?? "")}`),
3868
+ ""
3869
+ ].join("\r\n");
3870
+ }
3871
+ function csvField(text) {
3872
+ return /[",\r\n]/.test(text) ? `"${text.replace(/"/g, "\"\"")}"` : text;
3873
+ }
3874
+ function parseCsv(content) {
3875
+ const rows = csvRows(content, csvSeparator(content));
3876
+ const header = rows[0]?.map((cell) => cell.trim().toLowerCase()) ?? [];
3877
+ const keyCol = header.indexOf("key");
3878
+ const targetCol = header.indexOf("target");
3879
+ const sourceCol = header.indexOf("source");
3880
+ if (keyCol === -1 || targetCol === -1) throw new Error("[verbaly] CSV needs a header row with \"key\" and \"target\" columns");
3881
+ const entries = emptyCatalog();
3882
+ const sources = emptyCatalog();
3883
+ for (const row of rows.slice(1)) {
3884
+ const key = row[keyCol];
3885
+ if (!key) continue;
3886
+ entries[key] = row[targetCol] ?? "";
3887
+ const source = sourceCol === -1 ? void 0 : row[sourceCol];
3888
+ if (source) sources[key] = source;
3889
+ }
3890
+ return {
3891
+ entries,
3892
+ sources
3893
+ };
3894
+ }
3895
+ function csvSeparator(content) {
3896
+ let quoted = false;
3897
+ const seen = /* @__PURE__ */ new Set();
3898
+ for (const char of content) if (char === "\"") quoted = !quoted;
3899
+ else if (!quoted && (char === "\n" || char === "\r")) break;
3900
+ else if (!quoted) seen.add(char);
3901
+ return seen.has(",") ? "," : seen.has(";") ? ";" : seen.has(" ") ? " " : ",";
3902
+ }
3903
+ function csvRows(content, separator) {
3904
+ const rows = [];
3905
+ let row = [];
3906
+ let field = "";
3907
+ let quoted = false;
3908
+ for (let i = 0; i < content.length; i++) {
3909
+ const char = content[i];
3910
+ if (quoted) {
3911
+ if (char === "\"") {
3912
+ if (content[i + 1] === "\"") {
3913
+ field += "\"";
3914
+ i++;
3915
+ } else quoted = false;
3916
+ } else field += char;
3917
+ } else if (char === "\"") quoted = true;
3918
+ else if (char === separator) {
3919
+ row.push(field);
3920
+ field = "";
3921
+ } else if (char === "\n" || char === "\r") {
3922
+ if (char === "\r" && content[i + 1] === "\n") i++;
3923
+ row.push(field);
3924
+ field = "";
3925
+ if (row.some((cell) => cell !== "")) rows.push(row);
3926
+ row = [];
3927
+ } else field += char;
3928
+ }
3929
+ row.push(field);
3930
+ if (row.some((cell) => cell !== "")) rows.push(row);
3931
+ return rows;
3932
+ }
3933
+ // src/exchange/po.ts
3934
+ function toPo(sourceLocale, locale, entries) {
3935
+ return [
3936
+ [
3937
+ "msgid \"\"",
3938
+ "msgstr \"\"",
3939
+ `${poString("Project-Id-Version: verbaly\n")}`,
3940
+ `${poString("MIME-Version: 1.0\n")}`,
3941
+ `${poString("Content-Type: text/plain; charset=UTF-8\n")}`,
3942
+ `${poString("Content-Transfer-Encoding: 8bit\n")}`,
3943
+ `${poString(`Language: ${locale}\n`)}`,
3944
+ `${poString(`X-Source-Language: ${sourceLocale}\n`)}`
3945
+ ].join("\n"),
3946
+ ...entries.map(({ key, source, target, location }) => [
3947
+ ...location?.length ? [`#: ${location.join(" ")}`] : [],
3948
+ `msgctxt ${poString(key)}`,
3949
+ `msgid ${poString(source)}`,
3950
+ `msgstr ${poString(target)}`
3951
+ ].join("\n")),
3952
+ ""
3953
+ ].join("\n\n");
3954
+ }
3955
+ function parsePo(content) {
3956
+ const entries = emptyCatalog();
3957
+ const sources = emptyCatalog();
3958
+ let locale;
3959
+ let msgctxt;
3960
+ let msgid;
3961
+ let msgstr;
3962
+ let fuzzy = false;
3963
+ let field;
3964
+ const finish = () => {
3965
+ if (msgid === "" && msgctxt === void 0) {
3966
+ const lang = /^Language:[ \t]*(.+?)[ \t]*$/m.exec(msgstr ?? "")?.[1];
3967
+ if (lang) locale = lang;
3968
+ } else if (msgctxt !== void 0 && msgid !== void 0) {
3969
+ entries[msgctxt] = fuzzy ? "" : msgstr ?? "";
3970
+ sources[msgctxt] = msgid;
3971
+ }
3972
+ msgctxt = msgid = msgstr = field = void 0;
3973
+ fuzzy = false;
3974
+ };
3975
+ for (const raw of stripBom(content).split(/\r\n|[\r\n]/)) {
3976
+ const line = raw.trim();
3977
+ if (line === "") {
3978
+ finish();
3979
+ continue;
3980
+ }
3981
+ if (line.startsWith("#")) {
3982
+ if (/^#,.*\bfuzzy\b/.test(line)) fuzzy = true;
3983
+ continue;
3984
+ }
3985
+ const keyword = /^(msgctxt|msgid_plural|msgid|msgstr(?:\[\d+\])?)\s+(.*)$/.exec(line);
3986
+ if (keyword) {
3987
+ const [, name, rest] = keyword;
3988
+ const value = poUnquote(rest);
3989
+ if (value === void 0) continue;
3990
+ if (name === "msgctxt") {
3991
+ msgctxt = value;
3992
+ field = "msgctxt";
3993
+ } else if (name === "msgid") {
3994
+ msgid = value;
3995
+ field = "msgid";
3996
+ } else if (name === "msgstr" || name === "msgstr[0]") {
3997
+ msgstr = value;
3998
+ field = "msgstr";
3999
+ } else field = "other";
4000
+ continue;
4001
+ }
4002
+ const continuation = poUnquote(line);
4003
+ if (continuation === void 0 || field === void 0 || field === "other") continue;
4004
+ if (field === "msgctxt") msgctxt = (msgctxt ?? "") + continuation;
4005
+ else if (field === "msgid") msgid = (msgid ?? "") + continuation;
4006
+ else msgstr = (msgstr ?? "") + continuation;
4007
+ }
4008
+ finish();
4009
+ return {
4010
+ locale,
4011
+ entries,
4012
+ sources
4013
+ };
4014
+ }
4015
+ function poString(text) {
4016
+ return `"${text.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/\n/g, "\\n").replace(/\t/g, "\\t").replace(/\r/g, "\\r")}"`;
4017
+ }
4018
+ function poUnquote(text) {
4019
+ const match = /^"((?:[^"\\]|\\.)*)"$/.exec(text);
4020
+ if (!match) return void 0;
4021
+ return match[1].replace(/\\(.)/g, (_, ch) => {
4022
+ if (ch === "n") return "\n";
4023
+ if (ch === "t") return " ";
4024
+ if (ch === "r") return "\r";
4025
+ return ch;
4026
+ });
4027
+ }
4028
+ // src/util/markup.ts
4029
+ const NAME$1 = `[^\\s=/"'<>]+`;
4030
+ const ATTRIBUTE = new RegExp(`(${NAME$1})(?:\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s>]+)))?`, "g");
4031
+ const ATTRIBUTE_NAME = new RegExp(`^${NAME$1}$`);
4032
+ const TAG_REST = `(?:"[^"]*"|'[^']*'|[^"'>])*`;
4033
+ function isAttributeName(name) {
4034
+ return ATTRIBUTE_NAME.test(name);
4035
+ }
4036
+ function readAttributes(chunk, lowerCase = false) {
4037
+ const attributes = /* @__PURE__ */ new Map();
4038
+ ATTRIBUTE.lastIndex = 0;
4039
+ let match;
4040
+ while ((match = ATTRIBUTE.exec(chunk)) !== null) {
4041
+ const name = lowerCase ? match[1].toLowerCase() : match[1];
4042
+ if (attributes.has(name)) continue;
4043
+ const quoted = match[2] ?? match[3];
4044
+ const value = quoted ?? match[4] ?? "";
4045
+ const end = match.index + match[0].length;
4046
+ const written = quoted !== void 0 ? value.length + 2 : value.length;
4047
+ attributes.set(name, {
4048
+ value,
4049
+ start: end - written,
4050
+ end
4051
+ });
4052
+ }
4053
+ return attributes;
4054
+ }
4055
+ const ENTITY = /&(?:(lt|gt|amp|quot|apos)|#(\d+)|#[xX]([0-9a-fA-F]+));/g;
4056
+ const NAMED = {
4057
+ lt: "<",
4058
+ gt: ">",
4059
+ amp: "&",
4060
+ quot: "\"",
4061
+ apos: "'"
4062
+ };
3925
4063
  function decodeEntities(text) {
3926
4064
  return text.replace(ENTITY, (whole, name, decimal, hex) => {
3927
4065
  if (name) return NAMED[name];
@@ -4159,138 +4297,59 @@ function attr(attrs, name) {
4159
4297
  const value = attrs.get(name)?.value;
4160
4298
  return value === void 0 ? void 0 : decodeEntities(value);
4161
4299
  }
4162
- // src/exchange/mobile.ts
4163
- function androidValuesDir(locale, sourceLocale) {
4164
- if (locale === sourceLocale) return "values";
4165
- const parts = locale.split("-");
4166
- if (parts.length === 1) return `values-${locale}`;
4167
- if (parts.length === 2 && /^[a-zA-Z]{2}$/.test(parts[1])) return `values-${parts[0]}-r${parts[1].toUpperCase()}`;
4168
- return `values-b+${parts.join("+")}`;
4169
- }
4170
- function toAndroidXml(entries) {
4171
- const names = /* @__PURE__ */ new Map();
4300
+ // src/exchange/xliff.ts
4301
+ function toXliff(sourceLocale, locale, entries) {
4302
+ const units = entries.map(({ key, source, target, location }) => [
4303
+ ` <unit id="${escapeXml(key)}">`,
4304
+ ...location?.length ? [
4305
+ " <notes>",
4306
+ ...location.map((file) => ` <note category="location">${escapeXml(file)}</note>`),
4307
+ " </notes>"
4308
+ ] : [],
4309
+ ` <segment state="${target ? "translated" : "initial"}">`,
4310
+ ` <source>${messageToInline(source)}</source>`,
4311
+ ` <target>${messageToInline(target)}</target>`,
4312
+ " </segment>",
4313
+ " </unit>"
4314
+ ].join("\n")).join("\n");
4172
4315
  return [
4173
4316
  "<?xml version=\"1.0\" encoding=\"UTF-8\"?>",
4174
- "<resources>",
4175
- ...entries.map(({ key, text }) => {
4176
- const name = androidName(key);
4177
- const clash = names.get(name);
4178
- if (clash !== void 0) throw new Error(`[verbaly] android-xml: keys "${clash}" and "${key}" both become resource name "${name}", rename one of them.`);
4179
- names.set(name, key);
4180
- return ` <string name="${name}">${androidText(text)}</string>`;
4181
- }),
4182
- "</resources>",
4317
+ `<xliff xmlns="urn:oasis:names:tc:xliff:document:2.0" version="2.0" srcLang="${escapeXml(sourceLocale)}" trgLang="${escapeXml(locale)}">`,
4318
+ ` <file id="verbaly" original="${escapeXml(`${locale}.json`)}">`,
4319
+ units,
4320
+ " </file>",
4321
+ "</xliff>",
4183
4322
  ""
4184
4323
  ].join("\n");
4185
4324
  }
4186
- function toIosStrings(entries) {
4187
- return [...entries.map(({ key, text }) => `"${iosText(key)}" = "${iosText(text)}";`), ""].join("\n");
4188
- }
4189
- function androidName(key) {
4190
- const name = key.replace(/[^A-Za-z0-9_]/g, "_");
4191
- return /^[0-9]/.test(name) ? `_${name}` : name;
4192
- }
4193
- function androidText(text) {
4194
- const escaped = text.replace(/\\/g, "\\\\").replace(/'/g, "\\'").replace(/"/g, "\\\"").replace(/\n/g, "\\n").replace(/\t/g, "\\t").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
4195
- return /^[@?]/.test(escaped) ? `\\${escaped}` : escaped;
4196
- }
4197
- function iosText(text) {
4198
- return text.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/\n/g, "\\n").replace(/\t/g, "\\t");
4199
- }
4200
- // src/exchange/po.ts
4201
- function toPo(sourceLocale, locale, entries) {
4202
- return [
4203
- [
4204
- "msgid \"\"",
4205
- "msgstr \"\"",
4206
- `${poString("Project-Id-Version: verbaly\n")}`,
4207
- `${poString("MIME-Version: 1.0\n")}`,
4208
- `${poString("Content-Type: text/plain; charset=UTF-8\n")}`,
4209
- `${poString("Content-Transfer-Encoding: 8bit\n")}`,
4210
- `${poString(`Language: ${locale}\n`)}`,
4211
- `${poString(`X-Source-Language: ${sourceLocale}\n`)}`
4212
- ].join("\n"),
4213
- ...entries.map(({ key, source, target, location }) => [
4214
- ...location?.length ? [`#: ${location.join(" ")}`] : [],
4215
- `msgctxt ${poString(key)}`,
4216
- `msgid ${poString(source)}`,
4217
- `msgstr ${poString(target)}`
4218
- ].join("\n")),
4219
- ""
4220
- ].join("\n\n");
4325
+ const UNIT = `<(?:trans-)?unit\\b(${TAG_REST})>([\\s\\S]*?)</(?:trans-)?unit>`;
4326
+ const TARGET = new RegExp(`<target\\b${TAG_REST}>([\\s\\S]*?)</target>`);
4327
+ const SOURCE = new RegExp(`<source\\b${TAG_REST}>([\\s\\S]*?)</source>`);
4328
+ function tagAttribute(content, tag, name) {
4329
+ const open = new RegExp(`<${tag}\\b(${TAG_REST})>`).exec(content);
4330
+ return open && readAttributes(open[1]).get(name)?.value || void 0;
4221
4331
  }
4222
- function parsePo(content) {
4223
- const entries = Object.create(null);
4224
- const sources = Object.create(null);
4225
- let locale;
4226
- let msgctxt;
4227
- let msgid;
4228
- let msgstr;
4229
- let fuzzy = false;
4230
- let field;
4231
- const finish = () => {
4232
- if (msgid === "" && msgctxt === void 0) {
4233
- const lang = /^Language:[ \t]*(.+?)[ \t]*$/m.exec(msgstr ?? "")?.[1];
4234
- if (lang) locale = lang;
4235
- } else if (msgctxt !== void 0 && msgid !== void 0) {
4236
- entries[msgctxt] = fuzzy ? "" : msgstr ?? "";
4237
- sources[msgctxt] = msgid;
4238
- }
4239
- msgctxt = msgid = msgstr = field = void 0;
4240
- fuzzy = false;
4241
- };
4242
- for (const raw of content.replace(/^\uFEFF/, "").split(/\r\n|[\r\n]/)) {
4243
- const line = raw.trim();
4244
- if (line === "") {
4245
- finish();
4246
- continue;
4247
- }
4248
- if (line.startsWith("#")) {
4249
- if (/^#,.*\bfuzzy\b/.test(line)) fuzzy = true;
4250
- continue;
4251
- }
4252
- const keyword = /^(msgctxt|msgid_plural|msgid|msgstr(?:\[\d+\])?)\s+(.*)$/.exec(line);
4253
- if (keyword) {
4254
- const [, name, rest] = keyword;
4255
- const value = poUnquote(rest);
4256
- if (value === void 0) continue;
4257
- if (name === "msgctxt") {
4258
- msgctxt = value;
4259
- field = "msgctxt";
4260
- } else if (name === "msgid") {
4261
- msgid = value;
4262
- field = "msgid";
4263
- } else if (name === "msgstr" || name === "msgstr[0]") {
4264
- msgstr = value;
4265
- field = "msgstr";
4266
- } else field = "other";
4267
- continue;
4268
- }
4269
- const continuation = poUnquote(line);
4270
- if (continuation === void 0 || field === void 0 || field === "other") continue;
4271
- if (field === "msgctxt") msgctxt = (msgctxt ?? "") + continuation;
4272
- else if (field === "msgid") msgid = (msgid ?? "") + continuation;
4273
- else msgstr = (msgstr ?? "") + continuation;
4332
+ function parseXliff(content) {
4333
+ const head = (name) => tagAttribute(content, "xliff", name) ?? tagAttribute(content, "file", name);
4334
+ const locale = head("trgLang") ?? head("target-language");
4335
+ const entries = emptyCatalog();
4336
+ const sources = emptyCatalog();
4337
+ for (const match of content.matchAll(new RegExp(UNIT, "g"))) {
4338
+ const id = readAttributes(match[1]).get("id")?.value;
4339
+ if (!id) continue;
4340
+ const target = TARGET.exec(match[2])?.[1];
4341
+ entries[decodeEntities(id)] = target === void 0 ? "" : inlineToMessage(stripCdata(target));
4342
+ const source = SOURCE.exec(match[2])?.[1];
4343
+ if (source !== void 0) sources[decodeEntities(id)] = inlineToMessage(stripCdata(source));
4274
4344
  }
4275
- finish();
4276
4345
  return {
4277
4346
  locale,
4278
4347
  entries,
4279
4348
  sources
4280
4349
  };
4281
4350
  }
4282
- function poString(text) {
4283
- return `"${text.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/\n/g, "\\n").replace(/\t/g, "\\t").replace(/\r/g, "\\r")}"`;
4284
- }
4285
- function poUnquote(text) {
4286
- const match = /^"((?:[^"\\]|\\.)*)"$/.exec(text);
4287
- if (!match) return void 0;
4288
- return match[1].replace(/\\(.)/g, (_, ch) => {
4289
- if (ch === "n") return "\n";
4290
- if (ch === "t") return " ";
4291
- if (ch === "r") return "\r";
4292
- return ch;
4293
- });
4351
+ function stripCdata(text) {
4352
+ return text.replace(/<!\[CDATA\[([\s\S]*?)\]\]>/g, "$1");
4294
4353
  }
4295
4354
  // src/exchange/exchange.ts
4296
4355
  function isMobileFormat(format) {
@@ -4299,7 +4358,7 @@ function isMobileFormat(format) {
4299
4358
  function exportCatalogs(cfg, catalogs, options = {}) {
4300
4359
  const format = options.format ?? "xliff";
4301
4360
  const dir = resolve(cfg.root, options.out ?? "verbaly-export");
4302
- const source = catalogs[cfg.sourceLocale] ?? {};
4361
+ const source = catalogs[cfg.sourceLocale] ?? emptyCatalog();
4303
4362
  const targets = targetLocales(cfg, options.locales);
4304
4363
  if (isMobileFormat(format)) return exportMobile(cfg, catalogs, format, dir, source, targets);
4305
4364
  const files = [];
@@ -4307,7 +4366,7 @@ function exportCatalogs(cfg, catalogs, options = {}) {
4307
4366
  mkdirSync(dir, { recursive: true });
4308
4367
  for (const locale of targets) {
4309
4368
  const catalog = catalogs[locale] ?? emptyCatalog();
4310
- const all = Object.keys(source).filter((key) => source[key]).sort().map((key) => ({
4369
+ const all = translatable(source).map((key) => ({
4311
4370
  key,
4312
4371
  source: source[key],
4313
4372
  target: own(catalog, key) ?? "",
@@ -4331,11 +4390,14 @@ function exportCatalogs(cfg, catalogs, options = {}) {
4331
4390
  files
4332
4391
  };
4333
4392
  }
4393
+ function translatable(source) {
4394
+ return Object.keys(source).filter((key) => source[key]).sort();
4395
+ }
4334
4396
  function exportMobile(cfg, catalogs, format, dir, source, targets) {
4335
- const keys = Object.keys(source).filter((key) => source[key]).sort();
4397
+ const keys = translatable(source);
4336
4398
  const files = [];
4337
4399
  for (const locale of [cfg.sourceLocale, ...targets]) {
4338
- const catalog = locale === cfg.sourceLocale ? source : catalogs[locale] ?? {};
4400
+ const catalog = locale === cfg.sourceLocale ? source : catalogs[locale] ?? emptyCatalog();
4339
4401
  const entries = keys.map((key) => ({
4340
4402
  key,
4341
4403
  text: own(catalog, key) ?? ""
@@ -4358,7 +4420,7 @@ function exportMobile(cfg, catalogs, format, dir, source, targets) {
4358
4420
  };
4359
4421
  }
4360
4422
  function importCatalogs(cfg, catalogs, files, options = {}) {
4361
- const source = catalogs[cfg.sourceLocale] ?? {};
4423
+ const source = catalogs[cfg.sourceLocale] ?? emptyCatalog();
4362
4424
  const result = {
4363
4425
  imported: emptyCatalog(),
4364
4426
  rejected: emptyCatalog(),
@@ -4371,9 +4433,9 @@ function importCatalogs(cfg, catalogs, files, options = {}) {
4371
4433
  for (const file of files) {
4372
4434
  const parsed = parseExchangeFile(file, options.locale);
4373
4435
  const detected = parsed.locale;
4374
- if (!/^[a-zA-Z]{2,3}([-_][a-zA-Z0-9]+)*$/.test(detected)) throw new Error(`[verbaly] ${file}: "${detected}" doesn't look like a locale, pass --locale <id>.`);
4436
+ if (!/^[a-zA-Z]{2,3}([-_][a-zA-Z0-9]+)*$/.test(detected)) throw new Error(`[verbaly] ${file}: "${detected}" doesn't look like a locale, pass --locale <id>`);
4375
4437
  const locale = projectLocale(detected, cfg.locales) ?? newLocale(cfg, detected);
4376
- if (locale === cfg.sourceLocale) throw new Error(`[verbaly] ${file} targets the source locale "${locale}": import fills translations, not the source. Pass --locale if the detection is wrong.`);
4438
+ if (locale === cfg.sourceLocale) throw new Error(`[verbaly] ${file} targets the source locale "${locale}": import fills translations, not the source, so pass --locale if the detection is wrong`);
4377
4439
  if (locale === void 0) {
4378
4440
  const near = isLocaleTag(detected) ? detected : suggestTag(detected);
4379
4441
  result.unmatched.push(near ? {
@@ -4415,158 +4477,36 @@ function importCatalogs(cfg, catalogs, files, options = {}) {
4415
4477
  }
4416
4478
  }
4417
4479
  return result;
4418
- }
4419
- function parseExchangeFile(file, localeOverride) {
4420
- const content = readFileSync(file, "utf8");
4421
- if (/\.(xlf|xliff)$/i.test(file)) {
4422
- const parsed = parseXliff(content);
4423
- const locale = localeOverride ?? parsed.locale;
4424
- if (!locale) throw new Error(`[verbaly] ${file} has no trgLang/target-language, pass --locale <id>.`);
4425
- return {
4426
- locale,
4427
- entries: parsed.entries,
4428
- sources: parsed.sources
4429
- };
4430
- }
4431
- if (/\.csv$/i.test(file)) return {
4432
- locale: localeOverride ?? basename(file).replace(/\.csv$/i, ""),
4433
- ...parseCsv(content)
4434
- };
4435
- if (/\.po$/i.test(file)) {
4436
- const parsed = parsePo(content);
4437
- return {
4438
- locale: localeOverride ?? parsed.locale ?? basename(file).replace(/\.po$/i, ""),
4439
- entries: parsed.entries,
4440
- sources: parsed.sources
4441
- };
4442
- }
4443
- throw new Error(`[verbaly] ${file}: unsupported format, expected .xlf, .xliff, .csv or .po.`);
4444
- }
4445
- function toXliff(sourceLocale, locale, entries) {
4446
- const units = entries.map(({ key, source, target, location }) => [
4447
- ` <unit id="${escapeXml(key)}">`,
4448
- ...location?.length ? [
4449
- " <notes>",
4450
- ...location.map((file) => ` <note category="location">${escapeXml(file)}</note>`),
4451
- " </notes>"
4452
- ] : [],
4453
- ` <segment state="${target ? "translated" : "initial"}">`,
4454
- ` <source>${messageToInline(source)}</source>`,
4455
- ` <target>${messageToInline(target)}</target>`,
4456
- " </segment>",
4457
- " </unit>"
4458
- ].join("\n")).join("\n");
4459
- return [
4460
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>",
4461
- `<xliff xmlns="urn:oasis:names:tc:xliff:document:2.0" version="2.0" srcLang="${escapeXml(sourceLocale)}" trgLang="${escapeXml(locale)}">`,
4462
- ` <file id="verbaly" original="${escapeXml(`${locale}.json`)}">`,
4463
- units,
4464
- " </file>",
4465
- "</xliff>",
4466
- ""
4467
- ].join("\n");
4468
- }
4469
- function newLocale(cfg, detected) {
4470
- if (cfg.localesDeclared) return void 0;
4471
- return isLocaleTag(detected) ? detected : suggestTag(detected);
4472
- }
4473
- const UNIT = `<(?:trans-)?unit\\b(${TAG_REST})>([\\s\\S]*?)</(?:trans-)?unit>`;
4474
- const TARGET = new RegExp(`<target\\b${TAG_REST}>([\\s\\S]*?)</target>`);
4475
- const SOURCE = new RegExp(`<source\\b${TAG_REST}>([\\s\\S]*?)</source>`);
4476
- function tagAttribute(content, tag, name) {
4477
- const open = new RegExp(`<${tag}\\b(${TAG_REST})>`).exec(content);
4478
- return open && readAttributes(open[1]).get(name)?.value || void 0;
4479
- }
4480
- function parseXliff(content) {
4481
- const head = (name) => tagAttribute(content, "xliff", name) ?? tagAttribute(content, "file", name);
4482
- const locale = head("trgLang") ?? head("target-language");
4483
- const entries = Object.create(null);
4484
- const sources = Object.create(null);
4485
- for (const match of content.matchAll(new RegExp(UNIT, "g"))) {
4486
- const id = readAttributes(match[1]).get("id")?.value;
4487
- if (!id) continue;
4488
- const target = TARGET.exec(match[2])?.[1];
4489
- entries[decodeEntities(id)] = target === void 0 ? "" : inlineToMessage(stripCdata(target));
4490
- const source = SOURCE.exec(match[2])?.[1];
4491
- if (source !== void 0) sources[decodeEntities(id)] = inlineToMessage(stripCdata(source));
4492
- }
4493
- return {
4494
- locale,
4495
- entries,
4496
- sources
4497
- };
4498
- }
4499
- function stripCdata(text) {
4500
- return text.replace(/<!\[CDATA\[([\s\S]*?)\]\]>/g, "$1");
4501
- }
4502
- function toCsv(entries) {
4503
- return [
4504
- "key,source,target,location",
4505
- ...entries.map(({ key, source, target, location }) => `${csvField(key)},${csvField(source)},${csvField(target)},${csvField(location?.join("; ") ?? "")}`),
4506
- ""
4507
- ].join("\r\n");
4508
- }
4509
- function csvField(text) {
4510
- return /[",\r\n]/.test(text) ? `"${text.replace(/"/g, "\"\"")}"` : text;
4511
- }
4512
- function parseCsv(content) {
4513
- const rows = csvRows(content, csvSeparator(content));
4514
- const header = rows[0]?.map((cell) => cell.trim().toLowerCase()) ?? [];
4515
- const keyCol = header.indexOf("key");
4516
- const targetCol = header.indexOf("target");
4517
- const sourceCol = header.indexOf("source");
4518
- if (keyCol === -1 || targetCol === -1) throw new Error("[verbaly] CSV needs a header row with \"key\" and \"target\" columns.");
4519
- const entries = Object.create(null);
4520
- const sources = Object.create(null);
4521
- for (const row of rows.slice(1)) {
4522
- const key = row[keyCol];
4523
- if (!key) continue;
4524
- entries[key] = row[targetCol] ?? "";
4525
- const source = sourceCol === -1 ? void 0 : row[sourceCol];
4526
- if (source) sources[key] = source;
4480
+ }
4481
+ function parseExchangeFile(file, localeOverride) {
4482
+ const content = readFileSync(file, "utf8");
4483
+ if (/\.(xlf|xliff)$/i.test(file)) {
4484
+ const parsed = parseXliff(content);
4485
+ const locale = localeOverride ?? parsed.locale;
4486
+ if (!locale) throw new Error(`[verbaly] ${file} has no trgLang/target-language, pass --locale <id>`);
4487
+ return {
4488
+ locale,
4489
+ entries: parsed.entries,
4490
+ sources: parsed.sources
4491
+ };
4527
4492
  }
4528
- return {
4529
- entries,
4530
- sources
4493
+ if (/\.csv$/i.test(file)) return {
4494
+ locale: localeOverride ?? basename(file).replace(/\.csv$/i, ""),
4495
+ ...parseCsv(content)
4531
4496
  };
4532
- }
4533
- function csvSeparator(content) {
4534
- let quoted = false;
4535
- const seen = /* @__PURE__ */ new Set();
4536
- for (const char of content) if (char === "\"") quoted = !quoted;
4537
- else if (!quoted && (char === "\n" || char === "\r")) break;
4538
- else if (!quoted) seen.add(char);
4539
- return seen.has(",") ? "," : seen.has(";") ? ";" : seen.has(" ") ? " " : ",";
4540
- }
4541
- function csvRows(content, separator) {
4542
- const rows = [];
4543
- let row = [];
4544
- let field = "";
4545
- let quoted = false;
4546
- for (let i = 0; i < content.length; i++) {
4547
- const char = content[i];
4548
- if (quoted) {
4549
- if (char === "\"") {
4550
- if (content[i + 1] === "\"") {
4551
- field += "\"";
4552
- i++;
4553
- } else quoted = false;
4554
- } else field += char;
4555
- } else if (char === "\"") quoted = true;
4556
- else if (char === separator) {
4557
- row.push(field);
4558
- field = "";
4559
- } else if (char === "\n" || char === "\r") {
4560
- if (char === "\r" && content[i + 1] === "\n") i++;
4561
- row.push(field);
4562
- field = "";
4563
- if (row.some((cell) => cell !== "")) rows.push(row);
4564
- row = [];
4565
- } else field += char;
4497
+ if (/\.po$/i.test(file)) {
4498
+ const parsed = parsePo(content);
4499
+ return {
4500
+ locale: localeOverride ?? parsed.locale ?? basename(file).replace(/\.po$/i, ""),
4501
+ entries: parsed.entries,
4502
+ sources: parsed.sources
4503
+ };
4566
4504
  }
4567
- row.push(field);
4568
- if (row.some((cell) => cell !== "")) rows.push(row);
4569
- return rows;
4505
+ throw new Error(`[verbaly] ${file}: unsupported format, expected .xlf, .xliff, .csv or .po`);
4506
+ }
4507
+ function newLocale(cfg, detected) {
4508
+ if (cfg.localesDeclared) return void 0;
4509
+ return isLocaleTag(detected) ? detected : suggestTag(detected);
4570
4510
  }
4571
4511
  // src/cli/commands/export.ts
4572
4512
  async function exportCommand(cfg, values) {
@@ -4650,7 +4590,7 @@ function watchTree(root, options, onFile) {
4650
4590
  };
4651
4591
  }
4652
4592
  function watchProject(cfg, run, options = {}) {
4653
- const catalogDir = relative(cfg.root, cfg.dir).replaceAll("\\", "/");
4593
+ const catalogDir = relativePath(cfg.root, cfg.dir);
4654
4594
  let timer;
4655
4595
  let running = false;
4656
4596
  let queued = false;
@@ -4678,7 +4618,7 @@ function watchProject(cfg, run, options = {}) {
4678
4618
  }
4679
4619
  const close = watchTree(cfg.root, {}, (filename) => {
4680
4620
  if (!filename) return;
4681
- const file = filename.replaceAll("\\", "/");
4621
+ const file = slashed(filename);
4682
4622
  if (file.includes("node_modules/") || file.endsWith(".d.ts")) return;
4683
4623
  if (catalogDir && file.startsWith(`${catalogDir}/`)) return;
4684
4624
  if (SOURCE_FILE_RE.test(file)) schedule();
@@ -4790,18 +4730,7 @@ const KNOWN = [
4790
4730
  "svelte-i18n"
4791
4731
  ];
4792
4732
  function detectLibraries(root) {
4793
- const path = join(root, "package.json");
4794
- if (!existsSync(path)) return [];
4795
- let manifest;
4796
- try {
4797
- manifest = JSON.parse(readFileSync(path, "utf8"));
4798
- } catch {
4799
- return [];
4800
- }
4801
- const deps = {
4802
- ...manifest.dependencies,
4803
- ...manifest.devDependencies
4804
- };
4733
+ const deps = readDependencies(root);
4805
4734
  return KNOWN.filter((name) => deps[name] !== void 0);
4806
4735
  }
4807
4736
  const PLAIN = /\{\{\s*([A-Za-z_$][\w$]*)\s*\}\}/g;
@@ -5090,7 +5019,7 @@ async function init(input = {}) {
5090
5019
  if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
5091
5020
  for (const locale of /* @__PURE__ */ new Set([scaffold.sourceLocale ?? "en", ...scaffold.locales ?? []])) {
5092
5021
  const file = join(dir, `${locale}.json`);
5093
- const label = relative(root, file).replaceAll("\\", "/");
5022
+ const label = relativePath(root, file);
5094
5023
  if (existsSync(file)) skipped.push(label);
5095
5024
  else {
5096
5025
  writeFileSync(file, "{}\n");
@@ -5422,7 +5351,7 @@ function renderHtml(html, options) {
5422
5351
  };
5423
5352
  }
5424
5353
  function pageSlice(v, locale, used) {
5425
- const slice = Object.create(null);
5354
+ const slice = emptyCatalog();
5426
5355
  for (const key of used) {
5427
5356
  const found = v.inspect(key);
5428
5357
  slice[key] = found?.from === locale ? found.source : "";
@@ -5440,7 +5369,7 @@ function linkFor(links, name) {
5440
5369
  return links && Object.hasOwn(links, name) ? links[name] : void 0;
5441
5370
  }
5442
5371
  function usedLinks(nodes, links) {
5443
- const out = {};
5372
+ const out = emptyCatalog();
5444
5373
  const walk = (list) => {
5445
5374
  for (const node of list) {
5446
5375
  if (typeof node === "string") continue;
@@ -5454,7 +5383,7 @@ function usedLinks(nodes, links) {
5454
5383
  }
5455
5384
  function mirroredLinks(links, mirror) {
5456
5385
  if (!links) return links;
5457
- const out = {};
5386
+ const out = emptyCatalog();
5458
5387
  for (const [name, link] of Object.entries(links)) {
5459
5388
  const inside = mirroredHref(typeof link === "string" ? link : link.href, mirror);
5460
5389
  if (inside === void 0) out[name] = link;
@@ -5501,51 +5430,114 @@ function redirectScript(options) {
5501
5430
  `N=${options.trailingSlash === "never" ? 1 : 0}`
5502
5431
  ].join(",")};${REDIRECT_BODY};<\/script>`;
5503
5432
  }
5504
- function injectRedirect(ms, html, options) {
5505
- const block = `${REDIRECT_OPEN}${redirectScript(options)}${REDIRECT_CLOSE}`;
5506
- const from = html.indexOf(REDIRECT_OPEN);
5507
- if (from !== -1) {
5508
- const to = html.indexOf(REDIRECT_CLOSE, from);
5509
- if (to !== -1) {
5510
- const end = to + 24;
5511
- if (html.slice(from, end) !== block) ms.overwrite(from, end, block);
5512
- return;
5513
- }
5433
+ const HEAD_OPEN = /<head\b(?:"[^"]*"|'[^']*'|[^"'>])*>/i;
5434
+ const HEAD_CLOSE = /<\/head\s*>/i;
5435
+ function betweenMarkers(ms, html, [open, close], content, where) {
5436
+ const block = `${open}${content}${close}`;
5437
+ const from = html.indexOf(open);
5438
+ const to = from === -1 ? -1 : html.indexOf(close, from);
5439
+ if (to !== -1) {
5440
+ const end = to + close.length;
5441
+ if (html.slice(from, end) !== block) ms.overwrite(from, end, block);
5442
+ return;
5514
5443
  }
5515
- const head = /<head\b(?:"[^"]*"|'[^']*'|[^"'>])*>/i.exec(html);
5516
- if (head) ms.appendRight(head.index + head[0].length, block);
5444
+ const head = (where === "first" ? HEAD_OPEN : HEAD_CLOSE).exec(html);
5445
+ if (!head) return;
5446
+ if (where === "first") ms.appendRight(head.index + head[0].length, block);
5447
+ else ms.appendLeft(head.index, block);
5448
+ }
5449
+ function injectRedirect(ms, html, options) {
5450
+ betweenMarkers(ms, html, [REDIRECT_OPEN, REDIRECT_CLOSE], redirectScript(options), "first");
5517
5451
  }
5518
5452
  function injectAlternates(ms, html, alternates) {
5519
5453
  const links = alternates.map((a) => `<link rel="alternate" hreflang="${escapeAttr(a.hreflang)}" href="${escapeAttr(a.href)}">`).join("");
5520
- const block = `${HREFLANG_OPEN}${links}${HREFLANG_CLOSE}`;
5521
- const from = html.indexOf(HREFLANG_OPEN);
5522
- if (from !== -1) {
5523
- const to = html.indexOf(HREFLANG_CLOSE, from);
5524
- if (to !== -1) {
5525
- const end = to + 24;
5526
- if (html.slice(from, end) !== block) ms.overwrite(from, end, block);
5527
- return;
5528
- }
5529
- }
5530
- const head = /<\/head\s*>/i.exec(html);
5531
- if (head) ms.appendLeft(head.index, block);
5454
+ betweenMarkers(ms, html, [HREFLANG_OPEN, HREFLANG_CLOSE], links, "last");
5532
5455
  }
5533
5456
  function injectCatalog(ms, html, messages) {
5534
5457
  const json = JSON.stringify(messages).replace(/<\//g, "<\\/").replace(/<!--/g, "\\u003c!--");
5535
5458
  const tag = `<script ${CATALOG_SCRIPT} type="application/json">${json}<\/script>`;
5536
- const block = `${CATALOG_OPEN}${tag}${CATALOG_CLOSE}`;
5537
- const from = html.indexOf(CATALOG_OPEN);
5538
- if (from !== -1) {
5539
- const to = html.indexOf(CATALOG_CLOSE, from);
5540
- if (to !== -1) {
5541
- const end = to + 23;
5542
- if (html.slice(from, end) !== block) ms.overwrite(from, end, block);
5543
- return;
5544
- }
5459
+ betweenMarkers(ms, html, [CATALOG_OPEN, CATALOG_CLOSE], tag, "last");
5460
+ }
5461
+ function parseArgs(raw, attribute) {
5462
+ if (!raw) return void 0;
5463
+ try {
5464
+ return JSON.parse(decodeEntities(raw));
5465
+ } catch {
5466
+ warnOnce(`invalid JSON in ${attribute}: ${raw}`, `${attribute}:${raw}`);
5467
+ return;
5468
+ }
5469
+ }
5470
+ const OPAQUE_BLOCKS = [
5471
+ {
5472
+ open: "<!--",
5473
+ close: /(?<=<!--)-?>|--!?>/g
5474
+ },
5475
+ {
5476
+ open: /<script\b/gi,
5477
+ close: /<\/script(?=[\t\n\f\r />])/gi,
5478
+ closeTag: true
5479
+ },
5480
+ {
5481
+ open: /<style\b/gi,
5482
+ close: /<\/style(?=[\t\n\f\r />])/gi,
5483
+ closeTag: true
5484
+ }
5485
+ ];
5486
+ function protectedRanges(html) {
5487
+ return blocks(html, OPAQUE_BLOCKS).map(({ start, end }) => {
5488
+ return [html.startsWith("<!--", start) ? start : html.indexOf(">", start) + 1, end];
5489
+ });
5490
+ }
5491
+ function findClose(html, tagName, from, inSkip) {
5492
+ const re = new RegExp(`<${tagName}(?=[\\s/>])(?:"[^"]*"|'[^']*'|[^"'>])*>|</${tagName}\\s*>`, "gi");
5493
+ re.lastIndex = from;
5494
+ let depth = 1;
5495
+ let m;
5496
+ while ((m = re.exec(html)) !== null) {
5497
+ if (inSkip(m.index)) continue;
5498
+ if (m[0][1] === "/") {
5499
+ depth -= 1;
5500
+ if (depth === 0) return { contentEnd: m.index };
5501
+ } else if (!m[0].endsWith("/>")) depth += 1;
5502
+ }
5503
+ return null;
5504
+ }
5505
+ function setAttribute(ms, html, chunkStart, openEnd, attrs, name, value) {
5506
+ const written = `"${escapeAttr(value)}"`;
5507
+ const existing = attrs.get(name.toLowerCase());
5508
+ if (existing) {
5509
+ const from = chunkStart + existing.start;
5510
+ const to = chunkStart + existing.end;
5511
+ if (from === to) ms.appendLeft(from, `=${written}`);
5512
+ else if (html.slice(from, to) !== written) ms.overwrite(from, to, written);
5513
+ return;
5514
+ }
5515
+ const insertAt = openEnd - (html.slice(openEnd - 2, openEnd) === "/>" ? 2 : 1);
5516
+ ms.appendLeft(insertAt, ` ${name}=${written}`);
5517
+ }
5518
+ function richToHtml(nodes, allowed, links) {
5519
+ let out = "";
5520
+ for (const node of nodes) {
5521
+ const link = typeof node === "string" ? void 0 : linkFor(links, node.name);
5522
+ if (typeof node === "string") out += escapeHtml(node);
5523
+ else if (link !== void 0) {
5524
+ const { href, target, rel } = normalizeLink(link);
5525
+ let attrs = href !== void 0 ? ` href="${escapeAttr(href)}"` : "";
5526
+ if (target) attrs += ` target="${escapeAttr(target)}"`;
5527
+ if (rel) attrs += ` rel="${escapeAttr(rel)}"`;
5528
+ out += `<a${attrs}>${richToHtml(node.children, allowed, links)}</a>`;
5529
+ } else if (allowed.has(node.name)) out += VOID.has(node.name) ? `<${node.name}>` : `<${node.name}>${richToHtml(node.children, allowed, links)}</${node.name}>`;
5530
+ else out += richToHtml(node.children, allowed, links);
5545
5531
  }
5546
- const head = /<\/head\s*>/i.exec(html);
5547
- if (head) ms.appendLeft(head.index, block);
5532
+ return out;
5533
+ }
5534
+ function escapeHtml(text) {
5535
+ return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
5548
5536
  }
5537
+ function escapeAttr(text) {
5538
+ return escapeHtml(text).replace(/"/g, "&quot;");
5539
+ }
5540
+ // src/emit/site.ts
5549
5541
  const TITLE_TAG = /<title\b([^>]*)>/i;
5550
5542
  const REFRESH_META = /<meta\b[^>]*http-equiv\s*=\s*["']?refresh/i;
5551
5543
  const NOINDEX_META = /<meta\b[^>]*name\s*=\s*["']?robots["']?[^>]*content\s*=\s*["'][^"']*noindex/i;
@@ -5592,13 +5584,13 @@ async function renderSite(cfg, options = {}) {
5592
5584
  absolute: true,
5593
5585
  ignore: locales.map((locale) => `${locale}/**`)
5594
5586
  });
5595
- const pages = new Set(files.map((file) => publicPath(relative(site, file).replace(/\\/g, "/"))));
5596
- const missing = emptyCatalog();
5587
+ const pages = new Set(files.map((file) => publicPath(relativePath(site, file))));
5588
+ const unfilled = emptyCatalog();
5597
5589
  const untranslatedHead = [];
5598
5590
  const urls = [];
5599
5591
  for (const file of files) {
5600
5592
  const html = readFileSync(file, "utf8");
5601
- const rel = relative(site, file).replace(/\\/g, "/");
5593
+ const rel = relativePath(site, file);
5602
5594
  if (locales.length > 1 && !headIsBound(html, attribute ?? "data-verbaly")) untranslatedHead.push(rel);
5603
5595
  const alternates = wantHreflang ? pageAlternates(baseUrl, rel, locales, cfg.sourceLocale, cfg.trailingSlash) : [];
5604
5596
  if (wantHreflang && isIndexable(html) && !excluded(rel)) urls.push({
@@ -5624,27 +5616,37 @@ async function renderSite(cfg, options = {}) {
5624
5616
  redirect: routed && locale === cfg.sourceLocale ? script : void 0,
5625
5617
  inlineCatalog: cfg.render.inlineCatalog === true
5626
5618
  });
5627
- for (const key of result.missing) {
5628
- const list = missing[locale] ??= [];
5629
- if (!list.includes(key)) list.push(key);
5630
- }
5619
+ for (const key of result.missing) (unfilled[locale] ??= /* @__PURE__ */ new Set()).add(key);
5631
5620
  const out = locale === cfg.sourceLocale ? file : join(site, locale, rel);
5632
5621
  mkdirSync(dirname(out), { recursive: true });
5633
5622
  writeFileSync(out, result.html);
5634
5623
  }
5635
5624
  }
5636
5625
  if (wantSitemap && urls.length) writeFileSync(join(site, typeof sitemap === "string" ? sitemap : "sitemap-i18n.xml"), buildSitemap(urls));
5637
- return {
5626
+ const missing = emptyCatalog();
5627
+ for (const [locale, keys] of Object.entries(unfilled)) missing[locale] = [...keys];
5628
+ const result = {
5638
5629
  files: files.length,
5639
5630
  locales: [...locales],
5640
5631
  missing,
5641
5632
  untranslatedHead
5642
5633
  };
5634
+ const own = join(site, cfg.sourceLocale);
5635
+ const left = (await glob("**/*.html", { cwd: own })).length;
5636
+ if (left > 0) result.sourceFolder = {
5637
+ folder: relativePath(cfg.root, own),
5638
+ pages: left
5639
+ };
5640
+ return result;
5643
5641
  }
5644
5642
  function formatRenderWarnings(result, sourceLocale) {
5645
5643
  const lines = [];
5646
5644
  for (const [locale, keys] of Object.entries(result.missing)) lines.push(` ${locale}: ${counted(keys.length, "key")} not pre-filled: ${keys.join(", ")}`);
5647
5645
  if (result.untranslatedHead.length > 0) lines.push(` ${counted(result.untranslatedHead.length, "page")} of ${result.files} ship the same <title> in every locale (${result.untranslatedHead[0]}), so search results read in ${sourceLocale}`, ` fix: bind the head too, <title data-verbaly="key"> and a meta through data-verbaly-attr`);
5646
+ if (result.sourceFolder) {
5647
+ const { folder, pages } = result.sourceFolder;
5648
+ lines.push(` ${folder}/ is named like your source locale, so render does not mirror it (${counted(pages, "page")})`, ` fix: rename the folder if those pages are content, or delete it if an older run left it`);
5649
+ }
5648
5650
  return lines;
5649
5651
  }
5650
5652
  function pagePath(rel) {
@@ -5663,89 +5665,10 @@ function pageAlternates(baseUrl, rel, locales, sourceLocale, trailingSlash) {
5663
5665
  }
5664
5666
  function buildSitemap(urls) {
5665
5667
  return `<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml">${urls.flatMap(({ alternates }) => {
5666
- const alts = alternates.map((a) => `<xhtml:link rel="alternate" hreflang="${a.hreflang}" href="${escapeAttr(a.href)}"/>`).join("");
5668
+ const alts = alternates.map((a) => `<xhtml:link rel="alternate" hreflang="${escapeAttr(a.hreflang)}" href="${escapeAttr(a.href)}"/>`).join("");
5667
5669
  return alternates.filter((a) => a.hreflang !== "x-default").map((self) => `<url><loc>${escapeAttr(self.href)}</loc>${alts}</url>`);
5668
5670
  }).join("")}</urlset>\n`;
5669
5671
  }
5670
- function parseArgs(raw, attribute) {
5671
- if (!raw) return void 0;
5672
- try {
5673
- return JSON.parse(decodeEntities(raw));
5674
- } catch {
5675
- warnOnce(`invalid JSON in ${attribute}: ${raw}`, `${attribute}:${raw}`);
5676
- return;
5677
- }
5678
- }
5679
- const OPAQUE_BLOCKS = [
5680
- {
5681
- open: "<!--",
5682
- close: /(?<=<!--)-?>|--!?>/g
5683
- },
5684
- {
5685
- open: /<script\b/gi,
5686
- close: /<\/script(?=[\t\n\f\r />])/gi,
5687
- closeTag: true
5688
- },
5689
- {
5690
- open: /<style\b/gi,
5691
- close: /<\/style(?=[\t\n\f\r />])/gi,
5692
- closeTag: true
5693
- }
5694
- ];
5695
- function protectedRanges(html) {
5696
- return blocks(html, OPAQUE_BLOCKS).map(({ start, end }) => {
5697
- return [html.startsWith("<!--", start) ? start : html.indexOf(">", start) + 1, end];
5698
- });
5699
- }
5700
- function findClose(html, tagName, from, inSkip) {
5701
- const re = new RegExp(`<${tagName}(?=[\\s/>])(?:"[^"]*"|'[^']*'|[^"'>])*>|</${tagName}\\s*>`, "gi");
5702
- re.lastIndex = from;
5703
- let depth = 1;
5704
- let m;
5705
- while ((m = re.exec(html)) !== null) {
5706
- if (inSkip(m.index)) continue;
5707
- if (m[0][1] === "/") {
5708
- depth -= 1;
5709
- if (depth === 0) return { contentEnd: m.index };
5710
- } else if (!m[0].endsWith("/>")) depth += 1;
5711
- }
5712
- return null;
5713
- }
5714
- function setAttribute(ms, html, chunkStart, openEnd, attrs, name, value) {
5715
- const written = `"${escapeAttr(value)}"`;
5716
- const existing = attrs.get(name.toLowerCase());
5717
- if (existing) {
5718
- const from = chunkStart + existing.start;
5719
- const to = chunkStart + existing.end;
5720
- if (from === to) ms.appendLeft(from, `=${written}`);
5721
- else if (html.slice(from, to) !== written) ms.overwrite(from, to, written);
5722
- return;
5723
- }
5724
- const insertAt = openEnd - (html.slice(openEnd - 2, openEnd) === "/>" ? 2 : 1);
5725
- ms.appendLeft(insertAt, ` ${name}=${written}`);
5726
- }
5727
- function richToHtml(nodes, allowed, links) {
5728
- let out = "";
5729
- for (const node of nodes) {
5730
- const link = typeof node === "string" ? void 0 : linkFor(links, node.name);
5731
- if (typeof node === "string") out += escapeHtml(node);
5732
- else if (link !== void 0) {
5733
- const { href, target, rel } = normalizeLink(link);
5734
- let attrs = href !== void 0 ? ` href="${escapeAttr(href)}"` : "";
5735
- if (target) attrs += ` target="${escapeAttr(target)}"`;
5736
- if (rel) attrs += ` rel="${escapeAttr(rel)}"`;
5737
- out += `<a${attrs}>${richToHtml(node.children, allowed, links)}</a>`;
5738
- } else if (allowed.has(node.name)) out += VOID.has(node.name) ? `<${node.name}>` : `<${node.name}>${richToHtml(node.children, allowed, links)}</${node.name}>`;
5739
- else out += richToHtml(node.children, allowed, links);
5740
- }
5741
- return out;
5742
- }
5743
- function escapeHtml(text) {
5744
- return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
5745
- }
5746
- function escapeAttr(text) {
5747
- return escapeHtml(text).replace(/"/g, "&quot;");
5748
- }
5749
5672
  // src/cli/commands/render.ts
5750
5673
  async function renderCommand(cfg, values) {
5751
5674
  const result = await renderSite(cfg, {
@@ -5864,7 +5787,7 @@ async function typegenCommand(cfg) {
5864
5787
  console.log("[verbaly] no types written: dts is false in your verbaly config");
5865
5788
  return;
5866
5789
  }
5867
- const where = relative(cfg.root, written.file).replaceAll("\\", "/");
5790
+ const where = relativePath(cfg.root, written.file);
5868
5791
  const how = written.changed ? "written to" : "up to date in";
5869
5792
  console.log(`[verbaly] types ${how} ${where} (${counted(Object.keys(source).length, "message")})`);
5870
5793
  }
@@ -5913,7 +5836,7 @@ async function wrapProject(cfg, options = {}) {
5913
5836
  const adapters = () => found ??= jsxAdapters(cfg.root);
5914
5837
  for (const file of files) {
5915
5838
  const code = readFileSync(file, "utf8");
5916
- const label = relative(cfg.root, file).replaceAll("\\", "/");
5839
+ const label = relativePath(cfg.root, file);
5917
5840
  const out = wrapCode(code, label);
5918
5841
  result.wrapped.push(...out.wrapped);
5919
5842
  result.skipped.push(...out.skipped);
@@ -6051,7 +5974,7 @@ function wrapCode(code, file) {
6051
5974
  write(start, end, template);
6052
5975
  wrapped.push({
6053
5976
  file,
6054
- line: line(first),
5977
+ line: lineOf(first),
6055
5978
  text: report,
6056
5979
  kind: "text"
6057
5980
  });
@@ -6068,7 +5991,7 @@ function wrapCode(code, file) {
6068
5991
  write(value.start, value.end, escapeTemplate(raw));
6069
5992
  wrapped.push({
6070
5993
  file,
6071
- line: line(value),
5994
+ line: lineOf(value),
6072
5995
  text: raw,
6073
5996
  kind: "attribute",
6074
5997
  attribute: name.name
@@ -6078,7 +6001,7 @@ function wrapCode(code, file) {
6078
6001
  function skip(node, text, reason) {
6079
6002
  skipped.push({
6080
6003
  file,
6081
- line: line(node),
6004
+ line: lineOf(node),
6082
6005
  text,
6083
6006
  reason
6084
6007
  });
@@ -6146,7 +6069,7 @@ function tReaches(scopes, position) {
6146
6069
  for (const scope of scopes) {
6147
6070
  if (position < scope.start || position >= scope.end) continue;
6148
6071
  const size = scope.end - scope.start;
6149
- const best = nearest ? nearest.end - nearest.start : Infinity;
6072
+ const best = nearest ? nearest.end - nearest.start : 1e400;
6150
6073
  if (size < best || size === best && scope.bound) nearest = scope;
6151
6074
  }
6152
6075
  return nearest?.bound ?? false;
@@ -6200,9 +6123,6 @@ function leadingWs(text) {
6200
6123
  function trailingWs(text) {
6201
6124
  return text.length - text.trimEnd().length;
6202
6125
  }
6203
- function line(node) {
6204
- return node.loc?.start?.line ?? 1;
6205
- }
6206
6126
  function formatWrapResult(result, write) {
6207
6127
  const blocked = new Set(result.blocked.map((entry) => entry.file));
6208
6128
  const done = result.changed.filter((file) => !blocked.has(file));
@@ -6334,7 +6254,7 @@ async function runCli(args = process.argv.slice(2)) {
6334
6254
  const narrowed = csv(values.locales);
6335
6255
  if (narrowed || command === "review" && values.locale) {
6336
6256
  const whole = await loadConfig(root, project);
6337
- const typo = narrowed ? strangers(whole, "locales", narrowed) : strangers(whole, "locale", [values.locale]);
6257
+ const typo = narrowed ? strangerLocales(whole, "--locales", narrowed) : strangerLocales(whole, "--locale", [values.locale]);
6338
6258
  if (typo) {
6339
6259
  console.error(typo);
6340
6260
  process.exitCode = 1;
@@ -6347,13 +6267,6 @@ async function runCli(args = process.argv.slice(2)) {
6347
6267
  });
6348
6268
  return COMMANDS[command](cfg, values, positionals);
6349
6269
  }
6350
- function strangers(cfg, flag, named) {
6351
- const unknown = named.filter((locale) => !cfg.locales.includes(locale));
6352
- if (unknown.length === 0) return void 0;
6353
- const dir = relative(cfg.root, cfg.dir).replaceAll("\\", "/");
6354
- const start = cfg.localesDeclared ? `add ${unknown.join(", ")} to locales in your verbaly config` : `create ${unknown.map((locale) => `${dir}/${locale}.json`).join(", ")} holding {}`;
6355
- return `[verbaly] --${flag} names ${unknown.map((locale) => `"${locale}"`).join(", ")}, and this project has ${cfg.locales.join(", ")}\n fix: check the spelling, or ${start} to start a new language`;
6356
- }
6357
6270
  function formatCliError(error) {
6358
6271
  const message = error instanceof Error ? error.message : String(error);
6359
6272
  return message.startsWith("[verbaly]") ? message : `[verbaly] ${message}`;
@@ -6415,4 +6328,4 @@ function rejectStrayFlags(command, values) {
6415
6328
  process.exitCode = 1;
6416
6329
  return true;
6417
6330
  }
6418
- export { generateLocaleModule as $, relativeCheck as A, formatCollision as B, runBuildGate as C, resolveConfig as Ct, check as D, transformCode as E, translateCatalogs as F, loadState as G, STATE_FILE as H, writeDrafts as I, readState as J, markDrafts as K, syncProject as L, formatTranslateFailures as M, mergeTranslations as N, formatCheckResult as O, resolveProvider as P, generateDts as Q, collisionEntries as R, resolveVirtualId as S, loadConfig as St, writeBuildTypes as T, clearDrafts as U, formatFinding as V, effectiveDrafts as W, saveState as X, recordTranslations as Y, updateState as Z, SOURCE_FILE_RE as _, needsRelative as _t, formatRenderWarnings as a, extractProject as at, isTransformTarget as b, writeCatalog as bt, watchTree as c, syncCatalogs as ct, formatDoctorHealth as d, LOCALE_IMPORT as dt, generateRuntimeModule as et, formatStatusResult as f, MessageRegistry as ft, RESOLVED_VIRTUAL_ID as g, needsIcu as gt, LOCALE_MODULE_PREFIX as h, loadCatalogs as ht, wrapProject as i, collectOrigins as it, translateProject as j, formatCheckWarnings as k, doctor as l, stableKey as lt, reportOutsideInclude as m, counted as mt, runCli as n, validateMessage as nt, renderSite as o, pruneCatalogs as ot, status as p, clientCatalogs as pt, outdatedTranslations as q, formatWrapResult as r, validatePair as rt, init as s, shippedCatalogs as st, formatCliError as t, writeDts as tt, formatDoctorEntry as u, APP_ID as ut, clientModules as v, parseCatalog as vt, transformSource as w, targetLocales as wt, loadVirtualModule as x, isModuleNotFound as xt, createSourceFilter as y, readCatalog as yt, createDevReporter as z };
6331
+ export { collectOrigins as $, collisionEntries as A, singleQuoted as At, loadState as B, translateProject as C, pluginOnlyOptions as Ct, translateCatalogs as D, warnParseError as Dt, resolveProvider as E, warnOnce as Et, outdatedTranslations as F, generateLocaleModule as G, readState as H, recordTranslations as I, validateMessage as J, generateRuntimeModule as K, updateState as L, formatCollision as M, formatFinding as N, writeDrafts as O, cliReachable as Ot, effectiveDrafts as P, syncCatalogs as Q, STATE_FILE as R, warningCount as S, loadConfig as St, mergeTranslations as T, targetLocales as Tt, saveState as U, markDrafts as V, generateDts as W, pruneCatalogs as X, validatePair as Y, shippedCatalogs as Z, formatCheckResult as _, parseCatalog as _t, formatRenderWarnings as a, LOCALE_IMPORT as at, gatePasses as b, SOURCE_FILE_RE as bt, watchTree as c, MessageRegistry as ct, formatDoctorHealth as d, formatBundleIssue as dt, extractProject as et, formatStatusResult as f, emptyCatalog as ft, formatBuildReport as g, own as gt, checkNextSteps as h, needsRelative as ht, wrapProject as i, APP_ID as it, createDevReporter as j, relativePath as jt, syncProject as k, counted as kt, doctor as l, auditBundle as lt, reportOutsideInclude as m, needsIcu as mt, runCli as n, analyzeFile as nt, renderSite as o, VIRTUAL_ID as ot, status as p, loadCatalogs as pt, writeDts as q, formatWrapResult as r, stableKey as rt, init as s, isAppModule as st, formatCliError as t, scannedAnalysis as tt, formatDoctorEntry as u, clientCatalogs as ut, formatCheckWarnings as v, readCatalog as vt, formatTranslateFailures as w, resolveConfig as wt, relativeCheck as x, isModuleNotFound as xt, check as y, writeCatalog as yt, clearDrafts as z };