@verbaly/compiler 0.31.0 → 0.33.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,22 +1,96 @@
1
+ import { i as targetLocales, n as loadConfig, r as resolveConfig } from "./config-D8gkaunO.js";
2
+ import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
3
+ import { dirname, join, relative } from "node:path";
4
+ import { glob } from "tinyglobby";
1
5
  import { parse } from "@babel/parser";
2
6
  import { createHash } from "node:crypto";
3
- import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, watch, writeFileSync } from "node:fs";
4
- import { basename, dirname, join, relative, resolve } from "node:path";
5
7
  import { RICH_TAGS, createVerbaly, flatten, localeDirection, normalizeLink, parse as parse$1, parseTags, safeAttribute } from "verbaly";
6
- import { pathToFileURL } from "node:url";
7
8
  import picomatch from "picomatch";
8
9
  import MagicString from "magic-string";
9
- import { glob } from "tinyglobby";
10
- //#region \0rolldown/runtime.js
11
- var __defProp = Object.defineProperty;
12
- var __exportAll = (all, no_symbols) => {
13
- let target = {};
14
- for (var name in all) __defProp(target, name, {
15
- get: all[name],
16
- enumerable: true
17
- });
18
- if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
19
- return target;
10
+ //#region src/catalog.ts
11
+ function catalogPath(cfg, locale) {
12
+ return join(cfg.dir, `${locale}.json`);
13
+ }
14
+ function readCatalog(cfg, locale) {
15
+ let content;
16
+ try {
17
+ content = readFileSync(catalogPath(cfg, locale), "utf8");
18
+ } catch {
19
+ return {};
20
+ }
21
+ try {
22
+ return JSON.parse(content.replace(/^\uFEFF/, ""));
23
+ } catch (error) {
24
+ throw new Error(`[verbaly] ${catalogPath(cfg, locale)} is not valid JSON, fix or delete the file`, { cause: error });
25
+ }
26
+ }
27
+ function loadCatalogs(cfg) {
28
+ const catalogs = {};
29
+ for (const locale of cfg.locales) catalogs[locale] = readCatalog(cfg, locale);
30
+ return catalogs;
31
+ }
32
+ function serializeCatalog(catalog) {
33
+ const sorted = {};
34
+ for (const key of Object.keys(catalog).sort()) {
35
+ const value = catalog[key];
36
+ if (value !== void 0) sorted[key] = value;
37
+ }
38
+ return JSON.stringify(sorted, null, 2) + "\n";
39
+ }
40
+ function writeCatalog(cfg, locale, catalog) {
41
+ const serialized = serializeCatalog(catalog);
42
+ const path = catalogPath(cfg, locale);
43
+ try {
44
+ if (readFileSync(path, "utf8") === serialized) return serialized;
45
+ } catch {
46
+ mkdirSync(cfg.dir, { recursive: true });
47
+ }
48
+ writeFileSync(path, serialized);
49
+ return serialized;
50
+ }
51
+ //#endregion
52
+ //#region src/registry.ts
53
+ var MessageRegistry = class {
54
+ files = /* @__PURE__ */ new Map();
55
+ update(file, analysis) {
56
+ this.files.set(file, analysis);
57
+ }
58
+ remove(file) {
59
+ this.files.delete(file);
60
+ }
61
+ messages() {
62
+ const out = /* @__PURE__ */ new Map();
63
+ for (const analysis of this.files.values()) for (const msg of analysis.tagged) {
64
+ const existing = out.get(msg.key);
65
+ if (existing) {
66
+ if (existing.message !== msg.message) console.warn(`[verbaly] key collision "${msg.key}": ${JSON.stringify(existing.message)} vs ${JSON.stringify(msg.message)}, second dropped.`);
67
+ continue;
68
+ }
69
+ out.set(msg.key, msg);
70
+ }
71
+ return out;
72
+ }
73
+ usedKeys() {
74
+ const out = /* @__PURE__ */ new Map();
75
+ for (const analysis of this.files.values()) for (const used of analysis.usedKeys) {
76
+ const files = out.get(used.key) ?? [];
77
+ if (!files.includes(used.file)) files.push(used.file);
78
+ out.set(used.key, files);
79
+ }
80
+ return out;
81
+ }
82
+ strayImports() {
83
+ return [...this.files.values()].flatMap((analysis) => analysis.strayImports);
84
+ }
85
+ origins() {
86
+ const out = this.usedKeys();
87
+ for (const analysis of this.files.values()) for (const msg of analysis.tagged) {
88
+ const files = out.get(msg.key) ?? [];
89
+ if (!files.includes(msg.file)) files.push(msg.file);
90
+ out.set(msg.key, files);
91
+ }
92
+ return out;
93
+ }
20
94
  };
21
95
  //#endregion
22
96
  //#region src/key.ts
@@ -42,8 +116,10 @@ function analyze(code, file, options = {}) {
42
116
  });
43
117
  const tagged = [];
44
118
  const usedKeys = [];
119
+ const strayImports = [];
45
120
  walk$1(ast.program, (node) => {
46
- if (node.type === "TaggedTemplateExpression") {
121
+ if (node.type === "ImportDeclaration") collectStrayImports(node, file, strayImports);
122
+ else if (node.type === "TaggedTemplateExpression") {
47
123
  const tag = node.tag;
48
124
  const explicit = explicitId(tag, names);
49
125
  if (!explicit && !isTReference(tag, names)) return;
@@ -72,9 +148,24 @@ function analyze(code, file, options = {}) {
72
148
  });
73
149
  return {
74
150
  tagged,
75
- usedKeys
151
+ usedKeys,
152
+ strayImports
76
153
  };
77
154
  }
155
+ const VERBALY_PACKAGE = /^(?:verbaly|@verbaly\/[\w-]+)$/;
156
+ function collectStrayImports(node, file, out) {
157
+ const source = node.source;
158
+ if (typeof source.value !== "string" || !VERBALY_PACKAGE.test(source.value)) return;
159
+ for (const spec of node.specifiers) {
160
+ if (spec.type !== "ImportSpecifier") continue;
161
+ const imported = spec.imported;
162
+ if (imported.type === "Identifier" && imported.name === "t") out.push({
163
+ name: "t",
164
+ source: source.value,
165
+ file
166
+ });
167
+ }
168
+ }
78
169
  function handleTrans(code, node, file, tagged, usedKeys, names) {
79
170
  const opening = node.openingElement;
80
171
  const nameNode = opening.name;
@@ -303,6 +394,7 @@ function analyzeSfc(code, file) {
303
394
  const options = svelte ? { tNames: ["t", "$t"] } : void 0;
304
395
  const tagged = [];
305
396
  const usedKeys = [];
397
+ const strayImports = [];
306
398
  const frontmatter = file.endsWith(".astro") ? FRONTMATTER_RE.exec(code) : null;
307
399
  if (frontmatter?.[2]) merge(analyzeSegment(frontmatter[2], file, options), frontmatter[1].length, false);
308
400
  for (const match of code.matchAll(SCRIPT_RE)) {
@@ -327,7 +419,8 @@ function analyzeSfc(code, file) {
327
419
  }
328
420
  return {
329
421
  tagged,
330
- usedKeys
422
+ usedKeys,
423
+ strayImports
331
424
  };
332
425
  function merge(analysis, offset, markupSegment) {
333
426
  if (!analysis) return;
@@ -345,6 +438,7 @@ function analyzeSfc(code, file) {
345
438
  ...markupSegment && { singleQuote: true }
346
439
  });
347
440
  usedKeys.push(...analysis.usedKeys);
441
+ strayImports.push(...analysis.strayImports);
348
442
  }
349
443
  }
350
444
  function analyzeSegment(code, file, options) {
@@ -424,46 +518,53 @@ function stringEnd(code, start) {
424
518
  return code.length;
425
519
  }
426
520
  //#endregion
427
- //#region src/catalog.ts
428
- function catalogPath(cfg, locale) {
429
- return join(cfg.dir, `${locale}.json`);
430
- }
431
- function readCatalog(cfg, locale) {
432
- let content;
433
- try {
434
- content = readFileSync(catalogPath(cfg, locale), "utf8");
435
- } catch {
436
- return {};
437
- }
438
- try {
439
- return JSON.parse(content.replace(/^\uFEFF/, ""));
440
- } catch (error) {
441
- throw new Error(`[verbaly] ${catalogPath(cfg, locale)} is not valid JSON, fix or delete the file`, { cause: error });
442
- }
521
+ //#region src/extract.ts
522
+ async function extractProject(cfg) {
523
+ const files = await glob(cfg.include, {
524
+ cwd: cfg.root,
525
+ ignore: cfg.exclude,
526
+ absolute: true
527
+ });
528
+ const registry = new MessageRegistry();
529
+ for (const file of files) registry.update(file, analyzeFile(readFileSync(file, "utf8"), file));
530
+ return registry;
443
531
  }
444
- function loadCatalogs(cfg) {
445
- const catalogs = {};
446
- for (const locale of cfg.locales) catalogs[locale] = readCatalog(cfg, locale);
447
- return catalogs;
532
+ async function collectOrigins(cfg) {
533
+ const registry = await extractProject(cfg);
534
+ const origins = {};
535
+ for (const [key, files] of registry.origins()) origins[key] = files.map((file) => relative(cfg.root, file).replaceAll("\\", "/"));
536
+ return origins;
448
537
  }
449
- function serializeCatalog(catalog) {
450
- const sorted = {};
451
- for (const key of Object.keys(catalog).sort()) {
452
- const value = catalog[key];
453
- if (value !== void 0) sorted[key] = value;
538
+ function syncCatalogs(cfg, catalogs, registry) {
539
+ const added = {};
540
+ const source = catalogs[cfg.sourceLocale] ??= {};
541
+ for (const [key, msg] of registry.messages()) if (source[key] !== msg.message) {
542
+ source[key] = msg.message;
543
+ (added[cfg.sourceLocale] ??= []).push(key);
454
544
  }
455
- return JSON.stringify(sorted, null, 2) + "\n";
545
+ const needed = Object.keys(source);
546
+ for (const locale of cfg.locales) {
547
+ if (locale === cfg.sourceLocale) continue;
548
+ const catalog = catalogs[locale] ??= {};
549
+ for (const key of needed) if (catalog[key] === void 0) {
550
+ catalog[key] = "";
551
+ (added[locale] ??= []).push(key);
552
+ }
553
+ }
554
+ return { added };
456
555
  }
457
- function writeCatalog(cfg, locale, catalog) {
458
- const serialized = serializeCatalog(catalog);
459
- const path = catalogPath(cfg, locale);
460
- try {
461
- if (readFileSync(path, "utf8") === serialized) return serialized;
462
- } catch {
463
- mkdirSync(cfg.dir, { recursive: true });
556
+ function pruneCatalogs(cfg, catalogs, registry) {
557
+ const keep = /* @__PURE__ */ new Set([...registry.messages().keys(), ...registry.usedKeys().keys()]);
558
+ const removed = {};
559
+ for (const locale of cfg.locales) {
560
+ const catalog = catalogs[locale];
561
+ if (!catalog) continue;
562
+ for (const key of Object.keys(catalog)) if (!keep.has(key)) {
563
+ delete catalog[key];
564
+ (removed[locale] ??= []).push(key);
565
+ }
464
566
  }
465
- writeFileSync(path, serialized);
466
- return serialized;
567
+ return removed;
467
568
  }
468
569
  //#endregion
469
570
  //#region src/validate.ts
@@ -624,193 +725,34 @@ function reachableCategories(locale, ordinal) {
624
725
  return out;
625
726
  }
626
727
  //#endregion
627
- //#region src/check.ts
628
- function gatePasses(result) {
629
- return result.missing.length === 0 && result.unknown.length === 0 && !result.broken.some((entry) => entry.severity === "error");
728
+ //#region src/params.ts
729
+ const NUMBER_FORMATS = /* @__PURE__ */ new Set([
730
+ "number",
731
+ "integer",
732
+ "percent",
733
+ "currency"
734
+ ]);
735
+ const DATE_FORMATS = /* @__PURE__ */ new Set(["date", "time"]);
736
+ function collectParams(message) {
737
+ const out = /* @__PURE__ */ new Map();
738
+ visit(parse$1(message), out);
739
+ return out;
630
740
  }
631
- function check(cfg, catalogs, registry) {
632
- const extracted = registry.messages();
633
- const flat = {};
634
- for (const locale of cfg.locales) flat[locale] = flatten(catalogs[locale] ?? {});
635
- const source = flat[cfg.sourceLocale] ?? {};
636
- const unknown = [];
637
- for (const [key, files] of registry.usedKeys()) if (!(extracted.has(key) || cfg.locales.some((locale) => flat[locale]?.[key] !== void 0))) unknown.push({
638
- key,
639
- files
640
- });
641
- const needed = /* @__PURE__ */ new Set([...extracted.keys(), ...Object.keys(source)]);
642
- const missing = [];
643
- for (const key of extracted.keys()) if (!source[key]) missing.push({
644
- locale: cfg.sourceLocale,
645
- key,
646
- source: extracted.get(key)?.message
647
- });
648
- for (const locale of cfg.locales) {
649
- if (locale === cfg.sourceLocale) continue;
650
- for (const key of needed) if (!flat[locale]?.[key]) missing.push({
651
- locale,
652
- key,
653
- source: source[key] ?? extracted.get(key)?.message
654
- });
655
- }
656
- const broken = [];
657
- const add = (locale, key, issues) => {
658
- for (const issue of issues) broken.push({
659
- locale,
660
- key,
661
- severity: issue.severity,
662
- issue: issue.message
663
- });
664
- };
665
- const sourceText = { ...source };
666
- for (const [key, entry] of extracted) if (!sourceText[key]) sourceText[key] = entry.message;
667
- for (const [key, text] of Object.entries(sourceText)) add(cfg.sourceLocale, key, validateMessage(text, cfg.sourceLocale));
668
- for (const locale of cfg.locales) {
669
- if (locale === cfg.sourceLocale) continue;
670
- for (const [key, translated] of Object.entries(flat[locale] ?? {})) {
671
- if (!translated) continue;
672
- add(locale, key, validateMessage(translated, locale));
673
- const text = sourceText[key];
674
- if (text) add(locale, key, validatePair(text, translated));
675
- }
676
- }
677
- return {
678
- ok: gatePasses({
679
- missing,
680
- unknown,
681
- broken
682
- }),
683
- missing,
684
- unknown,
685
- broken
686
- };
687
- }
688
- function formatCheckResult(result) {
689
- const lines = [];
690
- if (result.missing.length > 0) {
691
- lines.push("missing translations:");
692
- for (const entry of result.missing) {
693
- const hint = entry.source ? `: "${truncate(entry.source, 40)}"` : "";
694
- lines.push(` [${entry.locale}] ${entry.key}${hint}`);
695
- }
696
- }
697
- if (result.unknown.length > 0) {
698
- lines.push("unknown keys (not in any catalog):");
699
- for (const entry of result.unknown) lines.push(` ${entry.key} (used in ${entry.files.join(", ")})`);
700
- }
701
- const errors = result.broken.filter((entry) => entry.severity === "error");
702
- if (errors.length > 0) {
703
- lines.push("broken translations:");
704
- for (const entry of errors) lines.push(` [${entry.locale}] ${entry.key}: ${entry.issue}`);
705
- }
706
- return lines.join("\n");
707
- }
708
- function checkNextSteps(result) {
709
- const steps = [];
710
- if (result.missing.length > 0) steps.push("missing: run `npx verbaly extract` to scaffold the keys, then fill them (or run `npx verbaly translate`)");
711
- if (result.unknown.length > 0) steps.push("unknown keys: the key used in the code is in no catalog, fix the key or run `npx verbaly extract`");
712
- if (result.broken.some((entry) => entry.severity === "error")) steps.push("broken: a translation has to keep the params, tags and plural cases of its source message");
713
- return steps.join("\n");
714
- }
715
- function formatCheckWarnings(result) {
716
- return result.broken.filter((entry) => entry.severity === "warning").map((entry) => ` [${entry.locale}] ${entry.key}: ${entry.issue}`).join("\n");
717
- }
718
- function truncate(text, max) {
719
- return text.length > max ? text.slice(0, max - 1) + "…" : text;
720
- }
721
- function githubCheckAnnotations(result, registry, root) {
722
- const messages = registry.messages();
723
- const contents = /* @__PURE__ */ new Map();
724
- const readSource = (file) => {
725
- if (!contents.has(file)) try {
726
- contents.set(file, readFileSync(file, "utf8"));
727
- } catch {
728
- contents.set(file, void 0);
729
- }
730
- return contents.get(file);
731
- };
732
- const lines = [];
733
- const byKey = /* @__PURE__ */ new Map();
734
- for (const entry of result.missing) {
735
- const grouped = byKey.get(entry.key);
736
- if (grouped) grouped.locales.push(entry.locale);
737
- else byKey.set(entry.key, {
738
- ...entry,
739
- locales: [entry.locale]
740
- });
741
- }
742
- for (const entry of byKey.values()) {
743
- const origin = messages.get(entry.key);
744
- const hint = entry.source ? `: "${truncate(entry.source, 60)}"` : "";
745
- const text = escapeData(`missing [${entry.locales.join(", ")}] ${entry.key}${hint}`);
746
- if (origin) {
747
- const file = relative(root, origin.file).replaceAll("\\", "/");
748
- const content = readSource(origin.file);
749
- const line = content === void 0 ? void 0 : lineAt(content, origin.start);
750
- lines.push(`::error file=${escapeProperty(file)}${line ? `,line=${line}` : ""}::${text}`);
751
- } else lines.push(`::error::${text}`);
752
- }
753
- for (const entry of result.unknown) {
754
- const text = escapeData(`unknown key "${entry.key}" (not in any catalog)`);
755
- const file = entry.files[0];
756
- lines.push(file ? `::error file=${escapeProperty(relative(root, file).replaceAll("\\", "/"))}::${text}` : `::error::${text}`);
757
- }
758
- for (const entry of result.broken) {
759
- const origin = messages.get(entry.key);
760
- const text = escapeData(`[${entry.locale}] ${entry.key}: ${entry.issue}`);
761
- const command = entry.severity === "error" ? "error" : "warning";
762
- if (!origin) {
763
- lines.push(`::${command}::${text}`);
764
- continue;
765
- }
766
- const file = relative(root, origin.file).replaceAll("\\", "/");
767
- const content = readSource(origin.file);
768
- const line = content === void 0 ? void 0 : lineAt(content, origin.start);
769
- lines.push(`::${command} file=${escapeProperty(file)}${line ? `,line=${line}` : ""}::${text}`);
770
- }
771
- return lines;
772
- }
773
- function lineAt(content, offset) {
774
- let line = 1;
775
- const end = Math.min(offset, content.length);
776
- for (let i = 0; i < end; i++) if (content[i] === "\n") line += 1;
777
- return line;
778
- }
779
- function escapeData(text) {
780
- return text.replaceAll("%", "%25").replaceAll("\r", "%0D").replaceAll("\n", "%0A");
781
- }
782
- function escapeProperty(text) {
783
- return escapeData(text).replaceAll(":", "%3A").replaceAll(",", "%2C");
784
- }
785
- //#endregion
786
- //#region src/params.ts
787
- const NUMBER_FORMATS = /* @__PURE__ */ new Set([
788
- "number",
789
- "integer",
790
- "percent",
791
- "currency"
792
- ]);
793
- const DATE_FORMATS = /* @__PURE__ */ new Set(["date", "time"]);
794
- function collectParams(message) {
795
- const out = /* @__PURE__ */ new Map();
796
- visit(parse$1(message), out);
797
- return out;
798
- }
799
- function visit(nodes, out) {
800
- for (const node of nodes) {
801
- if (node.kind !== "param") continue;
802
- const types = out.get(node.name) ?? /* @__PURE__ */ new Set();
803
- out.set(node.name, types);
804
- if (node.variants) {
805
- for (const [key, body] of node.variants) {
806
- if (PLURAL_CATEGORIES.has(key) || /^=\d+$/.test(key)) types.add("number");
807
- else if (key !== "other") types.add("string");
808
- visit(body, out);
809
- }
810
- if (types.size === 0) types.add("string");
811
- } else if (node.format && NUMBER_FORMATS.has(node.format)) types.add("number");
812
- else if (node.format && DATE_FORMATS.has(node.format)) types.add("date");
813
- else types.add("unknown");
741
+ function visit(nodes, out) {
742
+ for (const node of nodes) {
743
+ if (node.kind !== "param") continue;
744
+ const types = out.get(node.name) ?? /* @__PURE__ */ new Set();
745
+ out.set(node.name, types);
746
+ if (node.variants) {
747
+ for (const [key, body] of node.variants) {
748
+ if (PLURAL_CATEGORIES.has(key) || /^=\d+$/.test(key)) types.add("number");
749
+ else if (key !== "other") types.add("string");
750
+ visit(body, out);
751
+ }
752
+ if (types.size === 0) types.add("string");
753
+ } else if (node.format && NUMBER_FORMATS.has(node.format)) types.add("number");
754
+ else if (node.format && DATE_FORMATS.has(node.format)) types.add("date");
755
+ else types.add("unknown");
814
756
  }
815
757
  }
816
758
  function renderParamType(types) {
@@ -825,9 +767,6 @@ function renderParamType(types) {
825
767
  ]) members.add(m);
826
768
  return [...members].join(" | ");
827
769
  }
828
- //#endregion
829
- //#region src/codegen.ts
830
- const VIRTUAL_ID = "virtual:verbaly";
831
770
  function generateRuntimeModule(cfg, options = {}) {
832
771
  const importPath = options.localeImport ?? ((locale) => `virtual:verbaly/locale/${locale}`);
833
772
  const others = cfg.locales.filter((locale) => locale !== cfg.sourceLocale);
@@ -951,194 +890,99 @@ function writeDts(cfg, catalog, file) {
951
890
  writeFileSync(file, content);
952
891
  }
953
892
  //#endregion
954
- //#region src/pseudo.ts
955
- const PSEUDO_LOCALE = "en-XA";
956
- const ACCENTS = {
957
- a: "á",
958
- b: "ƀ",
959
- c: "ç",
960
- d: "đ",
961
- e: "é",
962
- f: "ƒ",
963
- g: "ğ",
964
- h: "ĥ",
965
- i: "í",
966
- j: "ĵ",
967
- k: "ķ",
968
- l: "ĺ",
969
- m: "ɱ",
970
- n: "ñ",
971
- o: "ó",
972
- p: "þ",
973
- q: "ǫ",
974
- r: "ŕ",
975
- s: "š",
976
- t: "ţ",
977
- u: "ú",
978
- v: "ṽ",
979
- w: "ŵ",
980
- x: "ẋ",
981
- y: "ý",
982
- z: "ž",
983
- A: "Á",
984
- B: "Ɓ",
985
- C: "Ç",
986
- D: "Đ",
987
- E: "É",
988
- F: "Ƒ",
989
- G: "Ğ",
990
- H: "Ĥ",
991
- I: "Í",
992
- J: "Ĵ",
993
- K: "Ķ",
994
- L: "Ĺ",
995
- M: "Ḿ",
996
- N: "Ñ",
997
- O: "Ó",
998
- P: "Þ",
999
- Q: "Ǫ",
1000
- R: "Ŕ",
1001
- S: "Š",
1002
- T: "Ţ",
1003
- U: "Ú",
1004
- V: "Ṽ",
1005
- W: "Ŵ",
1006
- X: "Ẍ",
1007
- Y: "Ý",
1008
- Z: "Ž"
1009
- };
1010
- const TAG_AT = /<\/?[a-zA-Z][\w-]*\/?>/y;
1011
- function pseudoLocalize(message) {
1012
- let out = "";
1013
- let letters = 0;
1014
- let i = 0;
1015
- while (i < message.length) {
1016
- const two = message.slice(i, i + 2);
1017
- if (two === "{{" || two === "}}" || two === "||" || two === "##") {
1018
- out += two;
1019
- i += 2;
1020
- continue;
1021
- }
1022
- const ch = message[i];
1023
- if (ch === "{") {
1024
- const end = matchBrace$1(message, i);
1025
- out += message.slice(i, end);
1026
- i = end;
1027
- continue;
1028
- }
1029
- if (ch === "<") {
1030
- TAG_AT.lastIndex = i;
1031
- const m = TAG_AT.exec(message);
1032
- if (m) {
1033
- out += m[0];
1034
- i += m[0].length;
1035
- continue;
1036
- }
1037
- }
1038
- const mapped = ACCENTS[ch];
1039
- if (mapped) {
1040
- out += mapped;
1041
- letters += 1;
1042
- } else out += ch;
1043
- i += 1;
1044
- }
1045
- const pad = "~".repeat(Math.ceil(letters / 3));
1046
- return `⟦${out}${pad ? " " + pad : ""}⟧`;
893
+ //#region src/check.ts
894
+ function gatePasses(result) {
895
+ return result.missing.length === 0 && result.unknown.length === 0 && !result.broken.some((entry) => entry.severity === "error");
1047
896
  }
1048
- function matchBrace$1(message, start) {
1049
- let depth = 0;
1050
- for (let i = start; i < message.length; i++) {
1051
- const two = message.slice(i, i + 2);
1052
- if (two === "{{" || two === "}}") {
1053
- i += 1;
1054
- continue;
1055
- }
1056
- const ch = message[i];
1057
- if (ch === "{") depth += 1;
1058
- else if (ch === "}") {
1059
- depth -= 1;
1060
- if (depth === 0) return i + 1;
1061
- }
897
+ function check(cfg, catalogs, registry) {
898
+ const extracted = registry.messages();
899
+ const flat = {};
900
+ for (const locale of cfg.locales) flat[locale] = flatten(catalogs[locale] ?? {});
901
+ const source = flat[cfg.sourceLocale] ?? {};
902
+ const unknown = [];
903
+ for (const [key, files] of registry.usedKeys()) if (!(extracted.has(key) || cfg.locales.some((locale) => flat[locale]?.[key] !== void 0))) unknown.push({
904
+ key,
905
+ files
906
+ });
907
+ const needed = /* @__PURE__ */ new Set([...extracted.keys(), ...Object.keys(source)]);
908
+ const missing = [];
909
+ for (const key of extracted.keys()) if (!source[key]) missing.push({
910
+ locale: cfg.sourceLocale,
911
+ key,
912
+ source: extracted.get(key)?.message
913
+ });
914
+ for (const locale of cfg.locales) {
915
+ if (locale === cfg.sourceLocale) continue;
916
+ for (const key of needed) if (!flat[locale]?.[key]) missing.push({
917
+ locale,
918
+ key,
919
+ source: source[key] ?? extracted.get(key)?.message
920
+ });
1062
921
  }
1063
- return message.length;
1064
- }
1065
- function pseudoCatalogs(cfg, catalogs, locale = PSEUDO_LOCALE) {
1066
- const source = catalogs[cfg.sourceLocale] ?? {};
1067
- const target = {};
1068
- for (const [key, msg] of Object.entries(source)) target[key] = msg ? pseudoLocalize(msg) : "";
1069
- catalogs[locale] = target;
1070
- return Object.keys(target).filter((key) => target[key]);
1071
- }
1072
- //#endregion
1073
- //#region src/config.ts
1074
- function resolveConfig(config = {}) {
1075
- const root = resolve(config.root ?? process.cwd());
1076
- const dir = resolve(root, config.dir ?? "locales");
1077
- const sourceLocale = config.sourceLocale ?? "en";
1078
- const locales = /* @__PURE__ */ new Set([sourceLocale, ...config.locales ?? []]);
1079
- if (existsSync(dir)) {
1080
- for (const file of readdirSync(dir)) if (file.endsWith(".json") && !file.startsWith(".") && file !== `en-XA.json`) locales.add(file.slice(0, -5));
922
+ const broken = [];
923
+ const add = (locale, key, issues) => {
924
+ for (const issue of issues) broken.push({
925
+ locale,
926
+ key,
927
+ severity: issue.severity,
928
+ issue: issue.message
929
+ });
930
+ };
931
+ const sourceText = { ...source };
932
+ for (const [key, entry] of extracted) if (!sourceText[key]) sourceText[key] = entry.message;
933
+ for (const [key, text] of Object.entries(sourceText)) add(cfg.sourceLocale, key, validateMessage(text, cfg.sourceLocale));
934
+ for (const locale of cfg.locales) {
935
+ if (locale === cfg.sourceLocale) continue;
936
+ for (const [key, translated] of Object.entries(flat[locale] ?? {})) {
937
+ if (!translated) continue;
938
+ add(locale, key, validateMessage(translated, locale));
939
+ const text = sourceText[key];
940
+ if (text) add(locale, key, validatePair(text, translated));
941
+ }
1081
942
  }
1082
943
  return {
1083
- root,
1084
- dir,
1085
- sourceLocale,
1086
- locales: [...locales],
1087
- include: config.include ?? ["{src,app}/**/*.{js,jsx,ts,tsx,mjs,mts,svelte,vue,astro}"],
1088
- exclude: config.exclude ?? ["**/node_modules/**", "**/dist/**"],
1089
- dts: typeof config.dts === "string" ? resolve(root, config.dts) : config.dts,
1090
- translate: config.translate ?? {},
1091
- render: config.render ?? {}
944
+ ok: gatePasses({
945
+ missing,
946
+ unknown,
947
+ broken
948
+ }),
949
+ missing,
950
+ unknown,
951
+ broken
1092
952
  };
1093
953
  }
1094
- const CONFIG_FILES = [
1095
- "verbaly.config.js",
1096
- "verbaly.config.mjs",
1097
- "verbaly.config.ts",
1098
- "verbaly.config.mts",
1099
- "verbaly.config.json"
1100
- ];
1101
- function findConfigFile(root) {
1102
- return CONFIG_FILES.find((name) => existsSync(join(root, name)));
1103
- }
1104
- async function loadConfigFile(root) {
1105
- for (const name of ["verbaly.config.js", "verbaly.config.mjs"]) {
1106
- const path = join(root, name);
1107
- if (existsSync(path)) return (await import(pathToFileURL(path).href)).default ?? {};
1108
- }
1109
- for (const name of ["verbaly.config.ts", "verbaly.config.mts"]) {
1110
- const path = join(root, name);
1111
- if (existsSync(path)) return loadTsConfig(path);
1112
- }
1113
- const jsonPath = join(root, "verbaly.config.json");
1114
- if (existsSync(jsonPath)) return JSON.parse(readFileSync(jsonPath, "utf8"));
1115
- return {};
1116
- }
1117
- async function loadTsConfig(path) {
1118
- try {
1119
- const { bundleRequire } = await import("bundle-require");
1120
- const { mod } = await bundleRequire({ filepath: path });
1121
- return mod.default ?? {};
1122
- } catch (error) {
1123
- if (isModuleNotFound(error, "esbuild")) throw new Error(`[verbaly] ${path} needs esbuild: install it with pnpm add -D esbuild`, { cause: error });
1124
- throw error;
954
+ function formatCheckResult(result) {
955
+ const lines = [];
956
+ if (result.missing.length > 0) {
957
+ lines.push("missing translations:");
958
+ for (const entry of result.missing) {
959
+ const hint = entry.source ? `: "${truncate(entry.source, 40)}"` : "";
960
+ lines.push(` [${entry.locale}] ${entry.key}${hint}`);
961
+ }
1125
962
  }
963
+ if (result.unknown.length > 0) {
964
+ lines.push("unknown keys (not in any catalog):");
965
+ for (const entry of result.unknown) lines.push(` ${entry.key} (used in ${entry.files.join(", ")})`);
966
+ }
967
+ const errors = result.broken.filter((entry) => entry.severity === "error");
968
+ if (errors.length > 0) {
969
+ lines.push("broken translations:");
970
+ for (const entry of errors) lines.push(` [${entry.locale}] ${entry.key}: ${entry.issue}`);
971
+ }
972
+ return lines.join("\n");
1126
973
  }
1127
- function isModuleNotFound(error, name) {
1128
- return error instanceof Error && error.code === "ERR_MODULE_NOT_FOUND" && error.message.includes(name);
1129
- }
1130
- function targetLocales(cfg, override) {
1131
- return (override ?? cfg.locales).filter((locale) => locale !== cfg.sourceLocale && cfg.locales.includes(locale));
974
+ function checkNextSteps(result) {
975
+ const steps = [];
976
+ if (result.missing.length > 0) steps.push("missing: run `npx verbaly extract` to scaffold the keys, then fill them (or run `npx verbaly translate`)");
977
+ if (result.unknown.length > 0) steps.push("unknown keys: the key used in the code is in no catalog, fix the key or run `npx verbaly extract`");
978
+ if (result.broken.some((entry) => entry.severity === "error")) steps.push("broken: a translation has to keep the params, tags and plural cases of its source message");
979
+ return steps.join("\n");
1132
980
  }
1133
- async function loadConfig(root, overrides = {}) {
1134
- return resolveConfig({
1135
- ...await loadConfigFile(root),
1136
- ...definedOnly(overrides),
1137
- root
1138
- });
981
+ function formatCheckWarnings(result) {
982
+ return result.broken.filter((entry) => entry.severity === "warning").map((entry) => ` [${entry.locale}] ${entry.key}: ${entry.issue}`).join("\n");
1139
983
  }
1140
- function definedOnly(config) {
1141
- return Object.fromEntries(Object.entries(config).filter(([, value]) => value !== void 0));
984
+ function truncate(text, max) {
985
+ return text.length > max ? text.slice(0, max - 1) + "…" : text;
1142
986
  }
1143
987
  //#endregion
1144
988
  //#region src/transform.ts
@@ -1195,8 +1039,10 @@ function createSourceFilter(cfg) {
1195
1039
  function transformSource(code, id, registry) {
1196
1040
  const analysis = analyzeFile(code, id);
1197
1041
  registry.update(id, analysis);
1042
+ const messages = {};
1043
+ for (const msg of analysis.tagged) messages[msg.key] ??= msg.message;
1198
1044
  return {
1199
- analysis,
1045
+ messages,
1200
1046
  result: transformCode(code, id, analysis) ?? null
1201
1047
  };
1202
1048
  }
@@ -1210,324 +1056,6 @@ function runBuildGate(cfg, registry, failOnMissing) {
1210
1056
  throw new Error(`[verbaly] build blocked\n${formatCheckResult(result)}\n${checkNextSteps(result)}`);
1211
1057
  }
1212
1058
  //#endregion
1213
- //#region src/registry.ts
1214
- var MessageRegistry = class {
1215
- files = /* @__PURE__ */ new Map();
1216
- update(file, analysis) {
1217
- this.files.set(file, analysis);
1218
- }
1219
- remove(file) {
1220
- this.files.delete(file);
1221
- }
1222
- messages() {
1223
- const out = /* @__PURE__ */ new Map();
1224
- for (const analysis of this.files.values()) for (const msg of analysis.tagged) {
1225
- const existing = out.get(msg.key);
1226
- if (existing) {
1227
- if (existing.message !== msg.message) console.warn(`[verbaly] key collision "${msg.key}": ${JSON.stringify(existing.message)} vs ${JSON.stringify(msg.message)}, second dropped.`);
1228
- continue;
1229
- }
1230
- out.set(msg.key, msg);
1231
- }
1232
- return out;
1233
- }
1234
- usedKeys() {
1235
- const out = /* @__PURE__ */ new Map();
1236
- for (const analysis of this.files.values()) for (const used of analysis.usedKeys) {
1237
- const files = out.get(used.key) ?? [];
1238
- if (!files.includes(used.file)) files.push(used.file);
1239
- out.set(used.key, files);
1240
- }
1241
- return out;
1242
- }
1243
- origins() {
1244
- const out = this.usedKeys();
1245
- for (const analysis of this.files.values()) for (const msg of analysis.tagged) {
1246
- const files = out.get(msg.key) ?? [];
1247
- if (!files.includes(msg.file)) files.push(msg.file);
1248
- out.set(msg.key, files);
1249
- }
1250
- return out;
1251
- }
1252
- };
1253
- //#endregion
1254
- //#region src/extract.ts
1255
- async function extractProject(cfg) {
1256
- const files = await glob(cfg.include, {
1257
- cwd: cfg.root,
1258
- ignore: cfg.exclude,
1259
- absolute: true
1260
- });
1261
- const registry = new MessageRegistry();
1262
- for (const file of files) registry.update(file, analyzeFile(readFileSync(file, "utf8"), file));
1263
- return registry;
1264
- }
1265
- async function collectOrigins(cfg) {
1266
- const registry = await extractProject(cfg);
1267
- const origins = {};
1268
- for (const [key, files] of registry.origins()) origins[key] = files.map((file) => relative(cfg.root, file).replaceAll("\\", "/"));
1269
- return origins;
1270
- }
1271
- function syncCatalogs(cfg, catalogs, registry) {
1272
- const added = {};
1273
- const source = catalogs[cfg.sourceLocale] ??= {};
1274
- for (const [key, msg] of registry.messages()) if (source[key] !== msg.message) {
1275
- source[key] = msg.message;
1276
- (added[cfg.sourceLocale] ??= []).push(key);
1277
- }
1278
- const needed = Object.keys(source);
1279
- for (const locale of cfg.locales) {
1280
- if (locale === cfg.sourceLocale) continue;
1281
- const catalog = catalogs[locale] ??= {};
1282
- for (const key of needed) if (catalog[key] === void 0) {
1283
- catalog[key] = "";
1284
- (added[locale] ??= []).push(key);
1285
- }
1286
- }
1287
- return { added };
1288
- }
1289
- function pruneCatalogs(cfg, catalogs, registry) {
1290
- const keep = /* @__PURE__ */ new Set([...registry.messages().keys(), ...registry.usedKeys().keys()]);
1291
- const removed = {};
1292
- for (const locale of cfg.locales) {
1293
- const catalog = catalogs[locale];
1294
- if (!catalog) continue;
1295
- for (const key of Object.keys(catalog)) if (!keep.has(key)) {
1296
- delete catalog[key];
1297
- (removed[locale] ??= []).push(key);
1298
- }
1299
- }
1300
- return removed;
1301
- }
1302
- //#endregion
1303
- //#region src/init.ts
1304
- const HOSTS = [
1305
- {
1306
- name: "nuxt",
1307
- dep: "nuxt",
1308
- pkg: "@verbaly/nuxt",
1309
- wire: "add '@verbaly/nuxt' to the modules in nuxt.config"
1310
- },
1311
- {
1312
- name: "next",
1313
- dep: "next",
1314
- pkg: "@verbaly/next",
1315
- wire: "wrap the export of next.config with withVerbaly"
1316
- },
1317
- {
1318
- name: "sveltekit",
1319
- dep: "@sveltejs/kit",
1320
- pkg: "@verbaly/vite",
1321
- wire: "add verbaly() to the plugins in vite.config (per-request locale: @verbaly/sveltekit)"
1322
- },
1323
- {
1324
- name: "astro",
1325
- dep: "astro",
1326
- pkg: "@verbaly/astro",
1327
- wire: "add verbaly() to the integrations in astro.config"
1328
- },
1329
- {
1330
- name: "vite",
1331
- dep: "vite",
1332
- pkg: "@verbaly/vite",
1333
- wire: "add verbaly() to the plugins in vite.config"
1334
- },
1335
- {
1336
- name: "webpack",
1337
- dep: "webpack",
1338
- pkg: "@verbaly/unplugin",
1339
- wire: "add the verbaly webpack plugin to your build config"
1340
- },
1341
- {
1342
- name: "rspack",
1343
- dep: "@rspack/core",
1344
- pkg: "@verbaly/unplugin",
1345
- wire: "add the verbaly rspack plugin to your build config"
1346
- },
1347
- {
1348
- name: "rollup",
1349
- dep: "rollup",
1350
- pkg: "@verbaly/unplugin",
1351
- wire: "add the verbaly rollup plugin to your build config"
1352
- },
1353
- {
1354
- name: "esbuild",
1355
- dep: "esbuild",
1356
- pkg: "@verbaly/unplugin",
1357
- wire: "add the verbaly esbuild plugin to your build config"
1358
- }
1359
- ];
1360
- const WIRING_PACKAGES = [...new Set(HOSTS.map((host) => host.pkg))];
1361
- function readDependencies(root) {
1362
- const path = join(root, "package.json");
1363
- if (!existsSync(path)) return {};
1364
- try {
1365
- const pkg = JSON.parse(readFileSync(path, "utf8"));
1366
- return {
1367
- ...pkg.dependencies,
1368
- ...pkg.devDependencies
1369
- };
1370
- } catch {
1371
- return {};
1372
- }
1373
- }
1374
- function detectHost(root) {
1375
- const deps = readDependencies(root);
1376
- return HOSTS.find((host) => deps[host.dep]);
1377
- }
1378
- function configSource(options, typescript) {
1379
- const fields = [` sourceLocale: '${options.sourceLocale ?? "en"}',`];
1380
- if (options.locales?.length) fields.push(` locales: [${options.locales.map((l) => `'${l}'`).join(", ")}],`);
1381
- if (options.dir) fields.push(` dir: '${options.dir}',`);
1382
- const body = `export default {\n${fields.join("\n")}\n}`;
1383
- if (typescript) return `import type { VerbalyConfig } from '@verbaly/compiler';\n\n${body} satisfies VerbalyConfig;\n`;
1384
- return `/** @type {import('@verbaly/compiler').VerbalyConfig} */\n${body};\n`;
1385
- }
1386
- function init(options = {}) {
1387
- const root = options.root ?? process.cwd();
1388
- const created = [];
1389
- const skipped = [];
1390
- const existing = findConfigFile(root);
1391
- const typescript = existsSync(join(root, "tsconfig.json"));
1392
- const configFile = existing ?? (typescript ? "verbaly.config.ts" : "verbaly.config.mjs");
1393
- if (existing) skipped.push(existing);
1394
- else {
1395
- writeFileSync(join(root, configFile), configSource(options, typescript));
1396
- created.push(configFile);
1397
- }
1398
- const dir = join(root, options.dir ?? "locales");
1399
- if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
1400
- for (const locale of /* @__PURE__ */ new Set([options.sourceLocale ?? "en", ...options.locales ?? []])) {
1401
- const file = join(dir, `${locale}.json`);
1402
- const label = relative(root, file).replaceAll("\\", "/");
1403
- if (existsSync(file)) skipped.push(label);
1404
- else {
1405
- writeFileSync(file, "{}\n");
1406
- created.push(label);
1407
- }
1408
- }
1409
- const host = detectHost(root);
1410
- const next = host ? [`pnpm add -D ${host.pkg}`, host.wire] : ["run \"verbaly extract\" after writing your first t`…` message"];
1411
- return {
1412
- created,
1413
- skipped,
1414
- host: host?.name,
1415
- configFile,
1416
- next
1417
- };
1418
- }
1419
- //#endregion
1420
- //#region src/doctor.ts
1421
- const PREVIEW = 5;
1422
- async function doctor(cfg) {
1423
- const entries = [];
1424
- const ok = (name, message) => entries.push({
1425
- level: "ok",
1426
- check: name,
1427
- message
1428
- });
1429
- const warn = (name, message, fix) => entries.push({
1430
- level: "warn",
1431
- check: name,
1432
- message,
1433
- fix
1434
- });
1435
- const error = (name, message, fix) => entries.push({
1436
- level: "error",
1437
- check: name,
1438
- message,
1439
- fix
1440
- });
1441
- const rel = (path) => relative(cfg.root, path).replaceAll("\\", "/");
1442
- const configFile = findConfigFile(cfg.root);
1443
- if (configFile) ok("config", `${configFile} found`);
1444
- else warn("config", "no config file, running on defaults", "run `npx verbaly init`");
1445
- const catalogs = {};
1446
- let catalogsHealthy = true;
1447
- if (!existsSync(cfg.dir)) {
1448
- catalogsHealthy = false;
1449
- error("catalogs", `catalogs directory ${rel(cfg.dir)}/ does not exist`, "run `npx verbaly init` to scaffold it");
1450
- } else {
1451
- for (const locale of cfg.locales) {
1452
- const file = join(cfg.dir, `${locale}.json`);
1453
- if (!existsSync(file)) {
1454
- catalogsHealthy = false;
1455
- error(`locale ${locale}`, `${rel(file)} is missing`, "run `npx verbaly extract` to create it");
1456
- continue;
1457
- }
1458
- try {
1459
- const parsed = JSON.parse(readFileSync(file, "utf8"));
1460
- const bad = badLeaf(parsed);
1461
- if (bad) {
1462
- catalogsHealthy = false;
1463
- error(`locale ${locale}`, `${rel(file)} has a non-string value at "${bad}"`, "catalog values are text (groups of text are fine); fix the value");
1464
- } else catalogs[locale] = flatten(parsed);
1465
- } catch {
1466
- catalogsHealthy = false;
1467
- error(`locale ${locale}`, `${rel(file)} is not valid JSON`, "repair the file (or delete it and run `npx verbaly extract`)");
1468
- }
1469
- }
1470
- if (catalogsHealthy) ok("catalogs", `${cfg.locales.length} locales (${cfg.locales.join(", ")}) in ${rel(cfg.dir)}/`);
1471
- }
1472
- const source = catalogs[cfg.sourceLocale];
1473
- 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`");
1474
- const deps = readDependencies(cfg.root);
1475
- const host = detectHost(cfg.root);
1476
- const installed = WIRING_PACKAGES.find((pkg) => deps[pkg]);
1477
- if (!host) ok("plugin", "no bundler detected, the CLI flow (extract/check) applies");
1478
- else if (installed) ok("plugin", `${installed} installed for ${host.name}`);
1479
- else warn("plugin", `${host.name} detected but ${host.pkg} is not installed`, `pnpm add -D ${host.pkg} and ${host.wire}`);
1480
- const scanning = cfg.include.length > 0;
1481
- if (!scanning) ok("sources", "source scanning is off (include: []), the catalogs are the source of truth");
1482
- if (source && scanning && cfg.dts !== false) {
1483
- const dtsPath = cfg.dts ?? join(cfg.root, "verbaly.d.ts");
1484
- if (!existsSync(dtsPath)) warn("types", "verbaly.d.ts has not been generated", "run `npx verbaly extract`");
1485
- else if (readFileSync(dtsPath, "utf8") !== generateDts(source)) warn("types", "verbaly.d.ts is stale", "run `npx verbaly extract`");
1486
- else ok("types", "verbaly.d.ts is up to date");
1487
- }
1488
- const registry = await extractProject(cfg);
1489
- if (source && scanning) {
1490
- const extracted = registry.messages();
1491
- const used = registry.usedKeys();
1492
- const orphans = Object.keys(source).filter((key) => !extracted.has(key) && !used.has(key));
1493
- if (orphans.length > 0) warn("orphans", `${orphans.length} catalog ${orphans.length === 1 ? "key is" : "keys are"} no longer referenced (${preview(orphans)})`, "run `npx verbaly extract --prune` to drop them");
1494
- else ok("orphans", "no orphan keys");
1495
- }
1496
- if (catalogsHealthy) {
1497
- const result = check(cfg, catalogs, registry);
1498
- if (result.unknown.length > 0) error("keys", `${result.unknown.length} unknown ${result.unknown.length === 1 ? "key" : "keys"} used in code (${preview(result.unknown.map((u) => u.key))})`, "fix the key or add it to the catalogs (`npx verbaly check` for details)");
1499
- if (result.missing.length > 0) {
1500
- const locales = [...new Set(result.missing.map((m) => m.locale))];
1501
- warn("translations", `${result.missing.length} missing ${result.missing.length === 1 ? "translation" : "translations"} (${locales.join(", ")})`, "run `npx verbaly translate` or fill the catalogs (`npx verbaly check` for details)");
1502
- }
1503
- const broken = result.broken.filter((entry) => entry.severity === "error");
1504
- if (broken.length > 0) {
1505
- const locales = [...new Set(broken.map((b) => b.locale))];
1506
- error("translations", `${broken.length} broken ${broken.length === 1 ? "translation" : "translations"} (${locales.join(", ")}): present but not rendering what the source renders`, "run `npx verbaly check` to read what each one lost");
1507
- }
1508
- const warnings = result.broken.filter((entry) => entry.severity === "warning");
1509
- if (warnings.length > 0) warn("translations", `${warnings.length} structural ${warnings.length === 1 ? "warning" : "warnings"} (plural forms a language asks for)`, "run `npx verbaly check` to read them, they never fail the build");
1510
- if (result.ok) ok("translations", "all translations complete");
1511
- }
1512
- return {
1513
- ok: entries.every((entry) => entry.level !== "error"),
1514
- entries
1515
- };
1516
- }
1517
- function preview(keys) {
1518
- const head = keys.slice(0, PREVIEW).join(", ");
1519
- return keys.length > PREVIEW ? `${head}, …` : head;
1520
- }
1521
- function badLeaf(tree, prefix = "") {
1522
- for (const [key, value] of Object.entries(tree)) {
1523
- const path = prefix ? `${prefix}.${key}` : key;
1524
- if (typeof value === "string") continue;
1525
- if (value === null || typeof value !== "object" || Array.isArray(value)) return path;
1526
- const bad = badLeaf(value, path);
1527
- if (bad) return bad;
1528
- }
1529
- }
1530
- //#endregion
1531
1059
  //#region src/drafts.ts
1532
1060
  const DRAFTS_FILE = ".verbaly-drafts.json";
1533
1061
  function draftsPath(cfg) {
@@ -1552,386 +1080,80 @@ function serializeDrafts(drafts) {
1552
1080
  const keys = [...new Set(drafts[locale])].sort();
1553
1081
  if (keys.length) sorted[locale] = keys;
1554
1082
  }
1555
- return JSON.stringify(sorted, null, 2) + "\n";
1556
- }
1557
- function saveDrafts(cfg, drafts) {
1558
- const serialized = serializeDrafts(drafts);
1559
- const path = draftsPath(cfg);
1560
- try {
1561
- if (readFileSync(path, "utf8") === serialized) return;
1562
- } catch {
1563
- mkdirSync(cfg.dir, { recursive: true });
1564
- }
1565
- writeFileSync(path, serialized);
1566
- }
1567
- function markDrafts(drafts, locale, keys) {
1568
- if (!keys.length) return;
1569
- drafts[locale] = [.../* @__PURE__ */ new Set([...drafts[locale] ?? [], ...keys])];
1570
- }
1571
- function clearDrafts(drafts, locale, keys) {
1572
- if (!drafts[locale]) return;
1573
- if (!keys) {
1574
- delete drafts[locale];
1575
- return;
1576
- }
1577
- const drop = new Set(keys);
1578
- drafts[locale] = drafts[locale].filter((key) => !drop.has(key));
1579
- if (!drafts[locale].length) delete drafts[locale];
1580
- }
1581
- function effectiveDrafts(drafts, catalogs) {
1582
- const out = {};
1583
- for (const [locale, keys] of Object.entries(drafts)) {
1584
- const catalog = catalogs[locale] ?? {};
1585
- const live = keys.filter((key) => catalog[key]);
1586
- if (live.length) out[locale] = live;
1587
- }
1588
- return out;
1589
- }
1590
- //#endregion
1591
- //#region src/inline.ts
1592
- const OPEN_TAG = /^<([a-zA-Z][a-zA-Z0-9-]*)\s*(\/?)>/;
1593
- function messageToInline(text) {
1594
- return renderParts(parseParts(text, 0).parts, /* @__PURE__ */ new Map());
1595
- }
1596
- function inlineToMessage(xml) {
1597
- let out = "";
1598
- let text = "";
1599
- let i = 0;
1600
- const flush = () => {
1601
- out += unescapeXml(text);
1602
- text = "";
1603
- };
1604
- while (i < xml.length) {
1605
- if (xml[i] === "<") {
1606
- const slice = xml.slice(i);
1607
- const ph = /^<ph\b([^>]*?)\/\s*>/.exec(slice) ?? /^<ph\b([^>]*)>\s*<\/ph\s*>/.exec(slice);
1608
- if (ph) {
1609
- flush();
1610
- out += attr(ph[1], "disp") ?? `{${attr(ph[1], "id") ?? "ph"}}`;
1611
- i += ph[0].length;
1612
- continue;
1613
- }
1614
- const pc = /^<pc\b([^>]*)>/.exec(slice);
1615
- if (pc) {
1616
- const close = findPcClose(xml, i + pc[0].length);
1617
- if (close) {
1618
- flush();
1619
- const id = attr(pc[1], "id") ?? "pc";
1620
- out += attr(pc[1], "dispStart") ?? `<${id}>`;
1621
- out += inlineToMessage(xml.slice(i + pc[0].length, close.innerEnd));
1622
- out += attr(pc[1], "dispEnd") ?? `</${id}>`;
1623
- i = close.end;
1624
- continue;
1625
- }
1626
- }
1627
- }
1628
- text += xml[i];
1629
- i += 1;
1630
- }
1631
- flush();
1632
- return out;
1633
- }
1634
- function escapeXml(text) {
1635
- return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
1636
- }
1637
- function unescapeXml(text) {
1638
- return text.replace(/&(lt|gt|amp|quot|apos|#x?[0-9a-fA-F]+);/g, (_, entity) => {
1639
- if (entity === "lt") return "<";
1640
- if (entity === "gt") return ">";
1641
- if (entity === "amp") return "&";
1642
- if (entity === "quot") return "\"";
1643
- if (entity === "apos") return "'";
1644
- const code = entity.startsWith("#x") ? parseInt(entity.slice(2), 16) : parseInt(entity.slice(1), 10);
1645
- return String.fromCodePoint(code);
1646
- });
1647
- }
1648
- function parseParts(text, pos, closeTag) {
1649
- const parts = [];
1650
- let plain = "";
1651
- const flush = () => {
1652
- if (plain) parts.push({
1653
- kind: "text",
1654
- text: plain
1655
- });
1656
- plain = "";
1657
- };
1658
- let i = pos;
1659
- while (i < text.length) {
1660
- const pair = text[i] + (text[i + 1] ?? "");
1661
- if (pair === "{{" || pair === "}}") {
1662
- plain += pair;
1663
- i += 2;
1664
- continue;
1665
- }
1666
- if (text[i] === "{") {
1667
- const end = matchBrace(text, i);
1668
- if (end === -1) {
1669
- plain += "{";
1670
- i += 1;
1671
- continue;
1672
- }
1673
- const src = text.slice(i, end + 1);
1674
- if (hasTopLevelPipe(src)) plain += src;
1675
- else {
1676
- flush();
1677
- parts.push({
1678
- kind: "ph",
1679
- name: paramName(src),
1680
- src
1681
- });
1682
- }
1683
- i = end + 1;
1684
- continue;
1685
- }
1686
- if (text[i] === "<") {
1687
- if (closeTag && text.startsWith(`</${closeTag}>`, i)) {
1688
- flush();
1689
- return {
1690
- parts,
1691
- end: i + closeTag.length + 3,
1692
- closed: true
1693
- };
1694
- }
1695
- const open = OPEN_TAG.exec(text.slice(i));
1696
- if (open) {
1697
- const [openSrc, name, selfClose] = open;
1698
- if (selfClose) {
1699
- flush();
1700
- parts.push({
1701
- kind: "ph",
1702
- name: idSafe(name),
1703
- src: openSrc
1704
- });
1705
- i += openSrc.length;
1706
- continue;
1707
- }
1708
- const inner = parseParts(text, i + openSrc.length, name);
1709
- if (inner.closed) {
1710
- flush();
1711
- parts.push({
1712
- kind: "pc",
1713
- name: idSafe(name),
1714
- openSrc,
1715
- closeSrc: `</${name}>`,
1716
- children: inner.parts
1717
- });
1718
- i = inner.end;
1719
- continue;
1720
- }
1721
- }
1722
- plain += "<";
1723
- i += 1;
1724
- continue;
1725
- }
1726
- plain += text[i];
1727
- i += 1;
1728
- }
1729
- flush();
1730
- return {
1731
- parts,
1732
- end: i,
1733
- closed: false
1734
- };
1735
- }
1736
- function matchBrace(text, start) {
1737
- let depth = 0;
1738
- for (let i = start; i < text.length; i++) {
1739
- const pair = text[i] + (text[i + 1] ?? "");
1740
- if (pair === "{{" || pair === "}}") {
1741
- i += 1;
1742
- continue;
1743
- }
1744
- if (text[i] === "{") depth += 1;
1745
- else if (text[i] === "}") {
1746
- depth -= 1;
1747
- if (depth === 0) return i;
1748
- }
1749
- }
1750
- return -1;
1083
+ return JSON.stringify(sorted, null, 2) + "\n";
1751
1084
  }
1752
- function hasTopLevelPipe(src) {
1753
- let depth = 0;
1754
- for (let i = 0; i < src.length; i++) {
1755
- const pair = src[i] + (src[i + 1] ?? "");
1756
- if (pair === "{{" || pair === "}}" || pair === "||") {
1757
- i += 1;
1758
- continue;
1759
- }
1760
- if (src[i] === "{") depth += 1;
1761
- else if (src[i] === "}") depth -= 1;
1762
- else if (src[i] === "|" && depth === 1) return true;
1085
+ function saveDrafts(cfg, drafts) {
1086
+ const serialized = serializeDrafts(drafts);
1087
+ const path = draftsPath(cfg);
1088
+ try {
1089
+ if (readFileSync(path, "utf8") === serialized) return;
1090
+ } catch {
1091
+ mkdirSync(cfg.dir, { recursive: true });
1763
1092
  }
1764
- return false;
1765
- }
1766
- function paramName(src) {
1767
- const name = /^\{\s*([^{}|:\s]+)/.exec(src)?.[1];
1768
- return name ? idSafe(name) : "ph";
1093
+ writeFileSync(path, serialized);
1769
1094
  }
1770
- function idSafe(name) {
1771
- return name.replace(/[^a-zA-Z0-9._-]/g, "_") || "ph";
1095
+ function markDrafts(drafts, locale, keys) {
1096
+ if (!keys.length) return;
1097
+ drafts[locale] = [.../* @__PURE__ */ new Set([...drafts[locale] ?? [], ...keys])];
1772
1098
  }
1773
- function renderParts(parts, taken) {
1774
- let out = "";
1775
- for (const part of parts) if (part.kind === "text") out += escapeXml(part.text);
1776
- else if (part.kind === "ph") out += `<ph id="${uniqueId(part.name, taken)}" disp="${escapeXml(part.src)}"/>`;
1777
- else {
1778
- const id = uniqueId(part.name, taken);
1779
- out += `<pc id="${id}" dispStart="${escapeXml(part.openSrc)}" dispEnd="${escapeXml(part.closeSrc)}">`;
1780
- out += renderParts(part.children, taken);
1781
- out += "</pc>";
1099
+ function effectiveDrafts(drafts, catalogs) {
1100
+ const out = {};
1101
+ for (const [locale, keys] of Object.entries(drafts)) {
1102
+ const catalog = catalogs[locale] ?? {};
1103
+ const live = keys.filter((key) => catalog[key]);
1104
+ if (live.length) out[locale] = live;
1782
1105
  }
1783
1106
  return out;
1784
1107
  }
1785
- function uniqueId(name, taken) {
1786
- const count = taken.get(name) ?? 0;
1787
- taken.set(name, count + 1);
1788
- return count === 0 ? name : `${name}${count + 1}`;
1789
- }
1790
- function findPcClose(xml, from) {
1791
- const tags = /<pc\b[^>]*>|<\/pc\s*>/g;
1792
- tags.lastIndex = from;
1793
- let depth = 1;
1794
- for (let match = tags.exec(xml); match; match = tags.exec(xml)) {
1795
- depth += match[0].startsWith("</") ? -1 : 1;
1796
- if (depth === 0) return {
1797
- innerEnd: match.index,
1798
- end: tags.lastIndex
1799
- };
1800
- }
1801
- }
1802
- function attr(attrs, name) {
1803
- const value = new RegExp(`\\b${name}\\s*=\\s*"([^"]*)"`).exec(attrs)?.[1];
1804
- return value === void 0 ? void 0 : unescapeXml(value);
1805
- }
1806
- //#endregion
1807
- //#region src/mobile.ts
1808
- function androidValuesDir(locale, sourceLocale) {
1809
- if (locale === sourceLocale) return "values";
1810
- const parts = locale.split("-");
1811
- if (parts.length === 1) return `values-${locale}`;
1812
- if (parts.length === 2 && /^[a-zA-Z]{2}$/.test(parts[1])) return `values-${parts[0]}-r${parts[1].toUpperCase()}`;
1813
- return `values-b+${parts.join("+")}`;
1814
- }
1815
- function toAndroidXml(entries) {
1816
- const names = /* @__PURE__ */ new Map();
1817
- return [
1818
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>",
1819
- "<resources>",
1820
- ...entries.map(({ key, text }) => {
1821
- const name = androidName(key);
1822
- const clash = names.get(name);
1823
- if (clash !== void 0) throw new Error(`[verbaly] android-xml: keys "${clash}" and "${key}" both become resource name "${name}", rename one of them.`);
1824
- names.set(name, key);
1825
- return ` <string name="${name}">${androidText(text)}</string>`;
1826
- }),
1827
- "</resources>",
1828
- ""
1829
- ].join("\n");
1830
- }
1831
- function toIosStrings(entries) {
1832
- return [...entries.map(({ key, text }) => `"${iosText(key)}" = "${iosText(text)}";`), ""].join("\n");
1833
- }
1834
- function androidName(key) {
1835
- const name = key.replace(/[^A-Za-z0-9_]/g, "_");
1836
- return /^[0-9]/.test(name) ? `_${name}` : name;
1837
- }
1838
- function androidText(text) {
1839
- 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;");
1840
- return /^[@?]/.test(escaped) ? `\\${escaped}` : escaped;
1841
- }
1842
- function iosText(text) {
1843
- return text.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/\n/g, "\\n").replace(/\t/g, "\\t");
1844
- }
1845
1108
  //#endregion
1846
- //#region src/po.ts
1847
- function toPo(sourceLocale, locale, entries) {
1848
- return [
1849
- [
1850
- "msgid \"\"",
1851
- "msgstr \"\"",
1852
- `${poString("Project-Id-Version: verbaly\n")}`,
1853
- `${poString("MIME-Version: 1.0\n")}`,
1854
- `${poString("Content-Type: text/plain; charset=UTF-8\n")}`,
1855
- `${poString("Content-Transfer-Encoding: 8bit\n")}`,
1856
- `${poString(`Language: ${locale}\n`)}`,
1857
- `${poString(`X-Source-Language: ${sourceLocale}\n`)}`
1858
- ].join("\n"),
1859
- ...entries.map(({ key, source, target, location }) => [
1860
- ...location?.length ? [`#: ${location.join(" ")}`] : [],
1861
- `msgctxt ${poString(key)}`,
1862
- `msgid ${poString(source)}`,
1863
- `msgstr ${poString(target)}`
1864
- ].join("\n")),
1865
- ""
1866
- ].join("\n\n");
1867
- }
1868
- function parsePo(content) {
1869
- const entries = {};
1870
- let locale;
1871
- let msgctxt;
1872
- let msgid;
1873
- let msgstr;
1874
- let fuzzy = false;
1875
- let field;
1876
- const finish = () => {
1877
- if (msgid === "" && msgctxt === void 0) {
1878
- const lang = /^Language:[ \t]*(.+?)[ \t]*$/m.exec(msgstr ?? "")?.[1];
1879
- if (lang) locale = lang;
1880
- } else if (msgctxt !== void 0 && msgid !== void 0) entries[msgctxt] = fuzzy ? "" : msgstr ?? "";
1881
- msgctxt = msgid = msgstr = field = void 0;
1882
- fuzzy = false;
1883
- };
1884
- for (const raw of content.replace(/^\uFEFF/, "").split(/\r\n|[\r\n]/)) {
1885
- const line = raw.trim();
1886
- if (line === "") {
1887
- finish();
1888
- continue;
1889
- }
1890
- if (line.startsWith("#")) {
1891
- if (/^#,.*\bfuzzy\b/.test(line)) fuzzy = true;
1892
- continue;
1893
- }
1894
- const keyword = /^(msgctxt|msgid_plural|msgid|msgstr(?:\[\d+\])?)\s+(.*)$/.exec(line);
1895
- if (keyword) {
1896
- const [, name, rest] = keyword;
1897
- const value = poUnquote(rest);
1898
- if (value === void 0) continue;
1899
- if (name === "msgctxt") {
1900
- msgctxt = value;
1901
- field = "msgctxt";
1902
- } else if (name === "msgid") {
1903
- msgid = value;
1904
- field = "msgid";
1905
- } else if (name === "msgstr" || name === "msgstr[0]") {
1906
- msgstr = value;
1907
- field = "msgstr";
1908
- } else field = "other";
1909
- continue;
1109
+ //#region src/status.ts
1110
+ function status(cfg, catalogs, registry, drafts = {}) {
1111
+ const extracted = registry.messages();
1112
+ const flat = {};
1113
+ for (const locale of cfg.locales) flat[locale] = flatten(catalogs[locale] ?? {});
1114
+ const source = flat[cfg.sourceLocale] ?? {};
1115
+ const needed = /* @__PURE__ */ new Set([...extracted.keys(), ...Object.keys(source)]);
1116
+ const live = effectiveDrafts(drafts, flat);
1117
+ const locales = [];
1118
+ for (const locale of cfg.locales) {
1119
+ if (locale === cfg.sourceLocale) continue;
1120
+ const catalog = flat[locale] ?? {};
1121
+ let translated = 0;
1122
+ for (const key of needed) if (catalog[key]) translated += 1;
1123
+ let broken = 0;
1124
+ for (const [key, text] of Object.entries(catalog)) {
1125
+ if (!text) continue;
1126
+ const from = source[key] ?? extracted.get(key)?.message;
1127
+ if ([...validateMessage(text, locale), ...from ? validatePair(from, text) : []].some((issue) => issue.severity === "error")) broken += 1;
1910
1128
  }
1911
- const continuation = poUnquote(line);
1912
- if (continuation === void 0 || field === void 0 || field === "other") continue;
1913
- if (field === "msgctxt") msgctxt = (msgctxt ?? "") + continuation;
1914
- else if (field === "msgid") msgid = (msgid ?? "") + continuation;
1915
- else msgstr = (msgstr ?? "") + continuation;
1129
+ locales.push({
1130
+ locale,
1131
+ translated,
1132
+ total: needed.size,
1133
+ drafts: live[locale]?.length ?? 0,
1134
+ broken
1135
+ });
1916
1136
  }
1917
- finish();
1918
1137
  return {
1919
- locale,
1920
- entries
1138
+ messages: needed.size,
1139
+ source: cfg.sourceLocale,
1140
+ locales
1921
1141
  };
1922
1142
  }
1923
- function poString(text) {
1924
- return `"${text.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/\n/g, "\\n").replace(/\t/g, "\\t").replace(/\r/g, "\\r")}"`;
1925
- }
1926
- function poUnquote(text) {
1927
- const match = /^"((?:[^"\\]|\\.)*)"$/.exec(text);
1928
- if (!match) return void 0;
1929
- return match[1].replace(/\\(.)/g, (_, ch) => {
1930
- if (ch === "n") return "\n";
1931
- if (ch === "t") return " ";
1932
- if (ch === "r") return "\r";
1933
- return ch;
1934
- });
1143
+ function formatStatusResult(result) {
1144
+ const lines = [`[verbaly] ${result.messages} messages · source: ${result.source}`];
1145
+ if (result.locales.length === 0) {
1146
+ lines.push(" no target locales (add locales to your config)");
1147
+ return lines.join("\n");
1148
+ }
1149
+ for (const { locale, translated, total, drafts, broken } of result.locales) {
1150
+ const pct = total === 0 ? 100 : Math.floor(translated / total * 100);
1151
+ const mark = translated === total && broken === 0 ? " ✓" : "";
1152
+ const notes = [drafts > 0 ? `${drafts} unreviewed` : "", broken > 0 ? `${broken} broken` : ""].filter(Boolean);
1153
+ const note = notes.length > 0 ? `, ${notes.join(", ")}` : "";
1154
+ lines.push(` ${locale}: ${translated}/${total} translated (${pct}%${note})${mark}`);
1155
+ }
1156
+ return lines.join("\n");
1935
1157
  }
1936
1158
  //#endregion
1937
1159
  //#region src/translate.ts
@@ -1976,7 +1198,7 @@ async function translateCatalogs(cfg, catalogs, provider, options = {}) {
1976
1198
  async function resolveProvider(cfg, model) {
1977
1199
  const configured = cfg.translate.provider;
1978
1200
  if (typeof configured === "function") return configured;
1979
- const { claudeProvider } = await Promise.resolve().then(() => claude_exports);
1201
+ const { claudeProvider } = await import("./claude-CrAkiSVP.js");
1980
1202
  return claudeProvider({ model: model ?? cfg.translate.model });
1981
1203
  }
1982
1204
  function structureMatches(source, translated) {
@@ -1987,274 +1209,6 @@ function structureMatches(source, translated) {
1987
1209
  }
1988
1210
  }
1989
1211
  //#endregion
1990
- //#region src/exchange.ts
1991
- function isMobileFormat(format) {
1992
- return format === "android-xml" || format === "ios-strings";
1993
- }
1994
- function exportCatalogs(cfg, catalogs, options = {}) {
1995
- const format = options.format ?? "xliff";
1996
- const dir = resolve(cfg.root, options.out ?? "verbaly-export");
1997
- const source = catalogs[cfg.sourceLocale] ?? {};
1998
- const targets = targetLocales(cfg, options.locales);
1999
- if (isMobileFormat(format)) return exportMobile(cfg, catalogs, format, dir, source, targets);
2000
- const files = [];
2001
- mkdirSync(dir, { recursive: true });
2002
- for (const locale of targets) {
2003
- const catalog = catalogs[locale] ?? {};
2004
- const all = Object.keys(source).filter((key) => source[key]).sort().map((key) => ({
2005
- key,
2006
- source: source[key],
2007
- target: catalog[key] ?? "",
2008
- location: options.origins?.[key]
2009
- }));
2010
- const untranslated = all.filter((entry) => !entry.target);
2011
- const entries = options.missing ? untranslated : all;
2012
- const path = join(dir, `${locale}.${format === "xliff" ? "xlf" : format}`);
2013
- writeFileSync(path, format === "csv" ? toCsv(entries) : format === "po" ? toPo(cfg.sourceLocale, locale, entries) : toXliff(cfg.sourceLocale, locale, entries));
2014
- files.push({
2015
- locale,
2016
- path,
2017
- total: entries.length,
2018
- untranslated: untranslated.length
2019
- });
2020
- }
2021
- return {
2022
- format,
2023
- dir,
2024
- files
2025
- };
2026
- }
2027
- function exportMobile(cfg, catalogs, format, dir, source, targets) {
2028
- const keys = Object.keys(source).filter((key) => source[key]).sort();
2029
- const files = [];
2030
- for (const locale of [cfg.sourceLocale, ...targets]) {
2031
- const catalog = locale === cfg.sourceLocale ? source : catalogs[locale] ?? {};
2032
- const entries = keys.map((key) => ({
2033
- key,
2034
- text: catalog[key] ?? ""
2035
- })).filter((entry) => entry.text);
2036
- const path = join(dir, format === "android-xml" ? join(androidValuesDir(locale, cfg.sourceLocale), "strings.xml") : join(`${locale}.lproj`, "Localizable.strings"));
2037
- mkdirSync(dirname(path), { recursive: true });
2038
- writeFileSync(path, format === "android-xml" ? toAndroidXml(entries) : toIosStrings(entries));
2039
- files.push({
2040
- locale,
2041
- path,
2042
- total: entries.length,
2043
- untranslated: keys.length - entries.length
2044
- });
2045
- }
2046
- return {
2047
- format,
2048
- dir,
2049
- files
2050
- };
2051
- }
2052
- function importCatalogs(cfg, catalogs, files, options = {}) {
2053
- const source = catalogs[cfg.sourceLocale] ?? {};
2054
- const result = {
2055
- imported: {},
2056
- rejected: {},
2057
- skipped: {},
2058
- unknown: {}
2059
- };
2060
- for (const file of files) {
2061
- const parsed = parseExchangeFile(file, options.locale);
2062
- const locale = parsed.locale;
2063
- if (!/^[a-zA-Z]{2,3}([-_][a-zA-Z0-9]+)*$/.test(locale)) throw new Error(`[verbaly] ${file}: "${locale}" doesn't look like a locale, pass --locale <id>.`);
2064
- 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.`);
2065
- const catalog = catalogs[locale] ??= {};
2066
- for (const [key, text] of Object.entries(parsed.entries)) {
2067
- if (!text.trim()) continue;
2068
- if (!source[key]) {
2069
- (result.unknown[locale] ??= []).push(key);
2070
- continue;
2071
- }
2072
- if (catalog[key] && !options.overwrite) {
2073
- (result.skipped[locale] ??= []).push(key);
2074
- continue;
2075
- }
2076
- if (!structureMatches(source[key], text)) {
2077
- (result.rejected[locale] ??= []).push(key);
2078
- continue;
2079
- }
2080
- if (!options.dryRun) catalog[key] = text;
2081
- (result.imported[locale] ??= []).push(key);
2082
- }
2083
- }
2084
- return result;
2085
- }
2086
- function parseExchangeFile(file, localeOverride) {
2087
- const content = readFileSync(file, "utf8");
2088
- if (/\.(xlf|xliff)$/i.test(file)) {
2089
- const parsed = parseXliff(content);
2090
- const locale = localeOverride ?? parsed.locale;
2091
- if (!locale) throw new Error(`[verbaly] ${file} has no trgLang/target-language, pass --locale <id>.`);
2092
- return {
2093
- locale,
2094
- entries: parsed.entries
2095
- };
2096
- }
2097
- if (/\.csv$/i.test(file)) return {
2098
- locale: localeOverride ?? basename(file).replace(/\.csv$/i, ""),
2099
- entries: parseCsv(content)
2100
- };
2101
- if (/\.po$/i.test(file)) {
2102
- const parsed = parsePo(content);
2103
- return {
2104
- locale: localeOverride ?? parsed.locale ?? basename(file).replace(/\.po$/i, ""),
2105
- entries: parsed.entries
2106
- };
2107
- }
2108
- throw new Error(`[verbaly] ${file}: unsupported format, expected .xlf, .xliff, .csv or .po.`);
2109
- }
2110
- function toXliff(sourceLocale, locale, entries) {
2111
- const units = entries.map(({ key, source, target, location }) => [
2112
- ` <unit id="${escapeXml(key)}">`,
2113
- ...location?.length ? [
2114
- " <notes>",
2115
- ...location.map((file) => ` <note category="location">${escapeXml(file)}</note>`),
2116
- " </notes>"
2117
- ] : [],
2118
- ` <segment state="${target ? "translated" : "initial"}">`,
2119
- ` <source>${messageToInline(source)}</source>`,
2120
- ` <target>${messageToInline(target)}</target>`,
2121
- " </segment>",
2122
- " </unit>"
2123
- ].join("\n")).join("\n");
2124
- return [
2125
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>",
2126
- `<xliff xmlns="urn:oasis:names:tc:xliff:document:2.0" version="2.0" srcLang="${escapeXml(sourceLocale)}" trgLang="${escapeXml(locale)}">`,
2127
- ` <file id="verbaly" original="${escapeXml(`${locale}.json`)}">`,
2128
- units,
2129
- " </file>",
2130
- "</xliff>",
2131
- ""
2132
- ].join("\n");
2133
- }
2134
- function parseXliff(content) {
2135
- const locale = /\btrgLang\s*=\s*"([^"]+)"/.exec(content)?.[1] ?? /\btarget-language\s*=\s*"([^"]+)"/.exec(content)?.[1];
2136
- const entries = {};
2137
- for (const match of content.matchAll(/<(?:trans-)?unit\b([^>]*)>([\s\S]*?)<\/(?:trans-)?unit>/g)) {
2138
- const id = /\bid\s*=\s*"([^"]*)"/.exec(match[1])?.[1];
2139
- if (!id) continue;
2140
- const target = /<target\b[^>]*>([\s\S]*?)<\/target>/.exec(match[2])?.[1];
2141
- entries[unescapeXml(id)] = target === void 0 ? "" : inlineToMessage(stripCdata(target));
2142
- }
2143
- return {
2144
- locale,
2145
- entries
2146
- };
2147
- }
2148
- function stripCdata(text) {
2149
- return text.replace(/<!\[CDATA\[([\s\S]*?)\]\]>/g, "$1");
2150
- }
2151
- function toCsv(entries) {
2152
- return [
2153
- "key,source,target,location",
2154
- ...entries.map(({ key, source, target, location }) => `${csvField(key)},${csvField(source)},${csvField(target)},${csvField(location?.join("; ") ?? "")}`),
2155
- ""
2156
- ].join("\r\n");
2157
- }
2158
- function csvField(text) {
2159
- return /[",\r\n]/.test(text) ? `"${text.replace(/"/g, "\"\"")}"` : text;
2160
- }
2161
- function parseCsv(content) {
2162
- const rows = csvRows(content);
2163
- const header = rows[0]?.map((cell) => cell.trim().toLowerCase()) ?? [];
2164
- const keyCol = header.indexOf("key");
2165
- const targetCol = header.indexOf("target");
2166
- if (keyCol === -1 || targetCol === -1) throw new Error("[verbaly] CSV needs a header row with \"key\" and \"target\" columns.");
2167
- const entries = {};
2168
- for (const row of rows.slice(1)) {
2169
- const key = row[keyCol];
2170
- if (key) entries[key] = row[targetCol] ?? "";
2171
- }
2172
- return entries;
2173
- }
2174
- function csvRows(content) {
2175
- const rows = [];
2176
- let row = [];
2177
- let field = "";
2178
- let quoted = false;
2179
- for (let i = 0; i < content.length; i++) {
2180
- const char = content[i];
2181
- if (quoted) if (char === "\"") if (content[i + 1] === "\"") {
2182
- field += "\"";
2183
- i++;
2184
- } else quoted = false;
2185
- else field += char;
2186
- else if (char === "\"") quoted = true;
2187
- else if (char === ",") {
2188
- row.push(field);
2189
- field = "";
2190
- } else if (char === "\n" || char === "\r") {
2191
- if (char === "\r" && content[i + 1] === "\n") i++;
2192
- row.push(field);
2193
- field = "";
2194
- if (row.some((cell) => cell !== "")) rows.push(row);
2195
- row = [];
2196
- } else field += char;
2197
- }
2198
- row.push(field);
2199
- if (row.some((cell) => cell !== "")) rows.push(row);
2200
- return rows;
2201
- }
2202
- //#endregion
2203
- //#region src/providers/claude.ts
2204
- var claude_exports = /* @__PURE__ */ __exportAll({
2205
- batchFormat: () => batchFormat,
2206
- buildPrompt: () => buildPrompt,
2207
- claudeProvider: () => claudeProvider,
2208
- loadSdk: () => loadSdk
2209
- });
2210
- const DEFAULT_MODEL = "claude-sonnet-5";
2211
- const SYSTEM = `You translate UI strings for the Verbaly i18n library.
2212
- Rules:
2213
- - Translate only the human-readable text, naturally for the target locale.
2214
- - Preserve verbatim: placeholders like {name}, format specs like {price:currency/EUR}, variant blocks like {count | one: ... | other: # ...} (translate only the text inside each variant, keep keys and # as-is), ICU syntax, named tags like <em>...</em> and escapes {{ }} || ##.
2215
- - Keys are opaque identifiers: return exactly the same keys, never translate or rename them.`;
2216
- function claudeProvider(options = {}) {
2217
- return async (request) => {
2218
- const text = (await new (await (loadSdk()))(options.apiKey ? { apiKey: options.apiKey } : {}).messages.create({
2219
- model: options.model ?? DEFAULT_MODEL,
2220
- max_tokens: options.maxTokens ?? 16e3,
2221
- thinking: { type: "disabled" },
2222
- system: SYSTEM,
2223
- messages: [{
2224
- role: "user",
2225
- content: buildPrompt(request)
2226
- }],
2227
- output_config: { format: batchFormat(request) }
2228
- })).content.find((block) => block.type === "text")?.text ?? "{}";
2229
- return JSON.parse(text);
2230
- };
2231
- }
2232
- function buildPrompt(request) {
2233
- const origins = request.origins;
2234
- const context = origins && Object.keys(origins).length ? `\n\nWhere each string appears (context for tone and length, do not translate these paths):\n` + Object.entries(origins).map(([key, files]) => ` ${key}: ${files.join(", ")}`).join("\n") : "";
2235
- return `Translate each value from "${request.sourceLocale}" to "${request.targetLocale}". Return a JSON object with the same keys and translated values.\n\n` + JSON.stringify(request.messages, null, 2) + context;
2236
- }
2237
- function batchFormat(request) {
2238
- const keys = Object.keys(request.messages);
2239
- return {
2240
- type: "json_schema",
2241
- schema: {
2242
- type: "object",
2243
- properties: Object.fromEntries(keys.map((key) => [key, { type: "string" }])),
2244
- required: keys,
2245
- additionalProperties: false
2246
- }
2247
- };
2248
- }
2249
- async function loadSdk(load = () => import("@anthropic-ai/sdk")) {
2250
- try {
2251
- return (await load()).default;
2252
- } catch (error) {
2253
- if (isModuleNotFound(error, "@anthropic-ai/sdk")) throw new Error("[verbaly] the claude translate provider needs @anthropic-ai/sdk: install it as a dev dependency (e.g. `pnpm add -D @anthropic-ai/sdk` / `npm i -D @anthropic-ai/sdk`) and set ANTHROPIC_API_KEY", { cause: error });
2254
- throw error;
2255
- }
2256
- }
2257
- //#endregion
2258
1212
  //#region src/render.ts
2259
1213
  const HREFLANG_OPEN = "<!--verbaly:hreflang-->";
2260
1214
  const HREFLANG_CLOSE = "<!--/verbaly:hreflang-->";
@@ -2526,309 +1480,6 @@ function decodeEntities(text) {
2526
1480
  return text.replace(/&quot;/g, "\"").replace(/&#39;/g, "'").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&");
2527
1481
  }
2528
1482
  //#endregion
2529
- //#region src/status.ts
2530
- function status(cfg, catalogs, registry, drafts = {}) {
2531
- const extracted = registry.messages();
2532
- const flat = {};
2533
- for (const locale of cfg.locales) flat[locale] = flatten(catalogs[locale] ?? {});
2534
- const source = flat[cfg.sourceLocale] ?? {};
2535
- const needed = /* @__PURE__ */ new Set([...extracted.keys(), ...Object.keys(source)]);
2536
- const live = effectiveDrafts(drafts, flat);
2537
- const locales = [];
2538
- for (const locale of cfg.locales) {
2539
- if (locale === cfg.sourceLocale) continue;
2540
- const catalog = flat[locale] ?? {};
2541
- let translated = 0;
2542
- for (const key of needed) if (catalog[key]) translated += 1;
2543
- let broken = 0;
2544
- for (const [key, text] of Object.entries(catalog)) {
2545
- if (!text) continue;
2546
- const from = source[key] ?? extracted.get(key)?.message;
2547
- if ([...validateMessage(text, locale), ...from ? validatePair(from, text) : []].some((issue) => issue.severity === "error")) broken += 1;
2548
- }
2549
- locales.push({
2550
- locale,
2551
- translated,
2552
- total: needed.size,
2553
- drafts: live[locale]?.length ?? 0,
2554
- broken
2555
- });
2556
- }
2557
- return {
2558
- messages: needed.size,
2559
- source: cfg.sourceLocale,
2560
- locales
2561
- };
2562
- }
2563
- function formatStatusResult(result) {
2564
- const lines = [`[verbaly] ${result.messages} messages · source: ${result.source}`];
2565
- if (result.locales.length === 0) {
2566
- lines.push(" no target locales (add locales to your config)");
2567
- return lines.join("\n");
2568
- }
2569
- for (const { locale, translated, total, drafts, broken } of result.locales) {
2570
- const pct = total === 0 ? 100 : Math.floor(translated / total * 100);
2571
- const mark = translated === total && broken === 0 ? " ✓" : "";
2572
- const notes = [drafts > 0 ? `${drafts} unreviewed` : "", broken > 0 ? `${broken} broken` : ""].filter(Boolean);
2573
- const note = notes.length > 0 ? `, ${notes.join(", ")}` : "";
2574
- lines.push(` ${locale}: ${translated}/${total} translated (${pct}%${note})${mark}`);
2575
- }
2576
- return lines.join("\n");
2577
- }
2578
- //#endregion
2579
- //#region src/watch.ts
2580
- function watchProject(cfg, run, options = {}) {
2581
- const catalogDir = relative(cfg.root, cfg.dir).replaceAll("\\", "/");
2582
- let timer;
2583
- let running = false;
2584
- let queued = false;
2585
- async function refresh() {
2586
- if (running) {
2587
- queued = true;
2588
- return;
2589
- }
2590
- running = true;
2591
- try {
2592
- await run();
2593
- } catch (error) {
2594
- console.warn("[verbaly] watch run failed:", error);
2595
- } finally {
2596
- running = false;
2597
- if (queued) {
2598
- queued = false;
2599
- schedule();
2600
- }
2601
- }
2602
- }
2603
- function schedule() {
2604
- clearTimeout(timer);
2605
- timer = setTimeout(() => void refresh(), options.debounce ?? 150);
2606
- }
2607
- const watcher = watch(cfg.root, { recursive: true }, (_event, filename) => {
2608
- if (!filename) return;
2609
- const file = filename.replaceAll("\\", "/");
2610
- if (file.includes("node_modules/") || file.endsWith(".d.ts")) return;
2611
- if (catalogDir && file.startsWith(`${catalogDir}/`)) return;
2612
- if (SOURCE_FILE_RE.test(file)) schedule();
2613
- });
2614
- return () => {
2615
- clearTimeout(timer);
2616
- watcher.close();
2617
- };
2618
- }
2619
- //#endregion
2620
- //#region src/wrap.ts
2621
- const WRAP_ATTRS = /* @__PURE__ */ new Set([
2622
- "title",
2623
- "alt",
2624
- "placeholder",
2625
- "aria-label"
2626
- ]);
2627
- const T_NAMES = /* @__PURE__ */ new Set(["t"]);
2628
- const LETTER = /\p{L}/u;
2629
- async function wrapProject(cfg, options = {}) {
2630
- const files = (await glob(cfg.include, {
2631
- cwd: cfg.root,
2632
- ignore: cfg.exclude,
2633
- absolute: true
2634
- })).filter((file) => /\.[jt]sx$/.test(file));
2635
- const result = {
2636
- files: files.length,
2637
- changed: [],
2638
- wrapped: [],
2639
- skipped: []
2640
- };
2641
- for (const file of files) {
2642
- const code = readFileSync(file, "utf8");
2643
- const label = relative(cfg.root, file).replaceAll("\\", "/");
2644
- const out = wrapCode(code, label);
2645
- result.wrapped.push(...out.wrapped);
2646
- result.skipped.push(...out.skipped);
2647
- if (out.code !== void 0) {
2648
- result.changed.push(label);
2649
- if (options.write) writeFileSync(file, out.code);
2650
- }
2651
- }
2652
- return result;
2653
- }
2654
- function wrapCode(code, file) {
2655
- const wrapped = [];
2656
- const skipped = [];
2657
- let ast;
2658
- try {
2659
- ast = parse(code, {
2660
- sourceType: "module",
2661
- errorRecovery: true,
2662
- plugins: ["typescript", "jsx"]
2663
- }).program;
2664
- } catch {
2665
- return {
2666
- wrapped,
2667
- skipped
2668
- };
2669
- }
2670
- const s = new MagicString(code);
2671
- const visited = /* @__PURE__ */ new Set();
2672
- let changed = false;
2673
- walk$1(ast, (node) => {
2674
- if (node.type !== "JSXElement" && node.type !== "JSXFragment") return;
2675
- if (visited.has(node)) return;
2676
- processElement(node);
2677
- });
2678
- return changed ? {
2679
- code: s.toString(),
2680
- wrapped,
2681
- skipped
2682
- } : {
2683
- wrapped,
2684
- skipped
2685
- };
2686
- function processElement(node) {
2687
- visited.add(node);
2688
- if (node.type === "JSXElement") {
2689
- const opening = node.openingElement;
2690
- const name = opening.name;
2691
- if (name.type === "JSXIdentifier" && name.name === "Trans") return markSubtree(node);
2692
- if (hasVerbalyAttr(opening)) return markSubtree(node);
2693
- wrapAttributes(opening);
2694
- }
2695
- const children = node.children ?? [];
2696
- const hasElementChild = children.some((c) => c.type === "JSXElement" || c.type === "JSXFragment");
2697
- const hasText = children.some((c) => c.type === "JSXText" && LETTER.test(c.value) || c.type === "JSXExpressionContainer" && c.expression.type === "StringLiteral" && LETTER.test(c.expression.value));
2698
- if (hasElementChild && hasText) {
2699
- skip(node, snippet(children), "mixed text and markup: wrap by hand or use <Trans>");
2700
- return markSubtree(node);
2701
- }
2702
- if (hasText) {
2703
- wrapSegment(node, children);
2704
- return markSubtree(node);
2705
- }
2706
- for (const child of children) if (child.type === "JSXElement" || child.type === "JSXFragment") processElement(child);
2707
- }
2708
- function wrapSegment(parent, children) {
2709
- const meaningful = children.filter((c) => c.type === "JSXText" && c.value.trim() !== "" || c.type === "JSXExpressionContainer" && c.expression.type !== "JSXEmptyExpression");
2710
- if (meaningful.length === 0) return;
2711
- const first = meaningful[0];
2712
- const last = meaningful[meaningful.length - 1];
2713
- let template = "";
2714
- let report = "";
2715
- for (let i = children.indexOf(first); i <= children.indexOf(last); i++) {
2716
- const child = children[i];
2717
- if (child.type === "JSXText") {
2718
- let value = cleanJsxText(child.value);
2719
- if (child === first) value = value.trimStart();
2720
- if (child === last) value = value.trimEnd();
2721
- template += escapeTemplate(value);
2722
- report += value;
2723
- } else if (child.type === "JSXExpressionContainer") {
2724
- const expr = child.expression;
2725
- if (expr.type === "JSXEmptyExpression") continue;
2726
- if (usesT(expr)) {
2727
- skip(parent, snippet(children), "already uses t: finish it by hand");
2728
- return;
2729
- }
2730
- if (containsJsx(expr)) {
2731
- skip(parent, snippet(children), "an expression renders markup: wrap by hand or use <Trans>");
2732
- markSubtree(child);
2733
- return;
2734
- }
2735
- if (expr.type === "StringLiteral") {
2736
- template += escapeTemplate(expr.value);
2737
- report += expr.value;
2738
- } else {
2739
- const source = code.slice(expr.start, expr.end);
2740
- template += "${" + source + "}";
2741
- report += "${" + source + "}";
2742
- }
2743
- } else return;
2744
- }
2745
- if (!LETTER.test(report)) return;
2746
- const start = first.type === "JSXText" ? first.start + leadingWs(first.value) : first.start;
2747
- const end = last.type === "JSXText" ? last.end - trailingWs(last.value) : last.end;
2748
- s.overwrite(start, end, "{t`" + template + "`}");
2749
- changed = true;
2750
- wrapped.push({
2751
- file,
2752
- line: line(first),
2753
- text: report,
2754
- kind: "text"
2755
- });
2756
- }
2757
- function wrapAttributes(opening) {
2758
- for (const attr of opening.attributes) {
2759
- if (attr.type !== "JSXAttribute") continue;
2760
- const name = attr.name;
2761
- if (name.type !== "JSXIdentifier" || !WRAP_ATTRS.has(name.name)) continue;
2762
- const value = attr.value;
2763
- if (value?.type !== "StringLiteral") continue;
2764
- const raw = value.value;
2765
- if (!LETTER.test(raw)) continue;
2766
- s.overwrite(value.start, value.end, "{t`" + escapeTemplate(raw) + "`}");
2767
- changed = true;
2768
- wrapped.push({
2769
- file,
2770
- line: line(value),
2771
- text: raw,
2772
- kind: "attribute",
2773
- attribute: name.name
2774
- });
2775
- }
2776
- }
2777
- function skip(node, text, reason) {
2778
- skipped.push({
2779
- file,
2780
- line: line(node),
2781
- text,
2782
- reason
2783
- });
2784
- }
2785
- function snippet(children) {
2786
- const start = children[0]?.start ?? 0;
2787
- const end = children[children.length - 1]?.end ?? start;
2788
- const text = code.slice(start, end).replace(/\s+/g, " ").trim();
2789
- return text.length > 60 ? text.slice(0, 59) + "…" : text;
2790
- }
2791
- function markSubtree(node) {
2792
- walk$1(node, (n) => {
2793
- if (n.type === "JSXElement" || n.type === "JSXFragment") visited.add(n);
2794
- });
2795
- }
2796
- }
2797
- function hasVerbalyAttr(opening) {
2798
- return opening.attributes.some((attr) => {
2799
- if (attr.type !== "JSXAttribute") return false;
2800
- const name = attr.name;
2801
- return name.type === "JSXIdentifier" && name.name.startsWith("data-verbaly");
2802
- });
2803
- }
2804
- function usesT(node) {
2805
- let found = false;
2806
- walk$1(node, (n) => {
2807
- if (n.type === "TaggedTemplateExpression" && isTReference(n.tag, T_NAMES)) found = true;
2808
- if (n.type === "CallExpression" && isTReference(n.callee, T_NAMES)) found = true;
2809
- });
2810
- return found;
2811
- }
2812
- function containsJsx(node) {
2813
- let found = false;
2814
- walk$1(node, (n) => {
2815
- if (n.type === "JSXElement" || n.type === "JSXFragment") found = true;
2816
- });
2817
- return found;
2818
- }
2819
- function escapeTemplate(text) {
2820
- return text.replace(/[\\`]/g, "\\$&").replace(/\$\{/g, "\\${");
2821
- }
2822
- function leadingWs(text) {
2823
- return text.length - text.trimStart().length;
2824
- }
2825
- function trailingWs(text) {
2826
- return text.length - text.trimEnd().length;
2827
- }
2828
- function line(node) {
2829
- return node.loc?.start?.line ?? 1;
2830
- }
2831
- //#endregion
2832
- export { DRAFTS_FILE, LOCALE_MODULE_PREFIX, MessageRegistry, PLURAL_CATEGORIES, PSEUDO_LOCALE, RESOLVED_VIRTUAL_ID, SFC_FILE_RE, SOURCE_FILE_RE, VIRTUAL_ID, WIRING_PACKAGES, analyze, analyzeFile, analyzeSfc, catalogPath, check, checkNextSteps, claudeProvider, clearDrafts, collectOrigins, collectParams, createSourceFilter, detectHost, doctor, effectiveDrafts, exportCatalogs, extractProject, findConfigFile, formatCheckResult, formatCheckWarnings, formatStatusResult, gatePasses, generateDts, generateLocaleModule, generateRuntimeModule, githubCheckAnnotations, importCatalogs, init, isMobileFormat, isTransformTarget, loadCatalogs, loadConfig, loadConfigFile, loadDrafts, loadVirtualModule, markDrafts, parseExchangeFile, pruneCatalogs, pseudoCatalogs, pseudoLocalize, readCatalog, readDependencies, renderHtml, renderParamType, renderSite, resolveConfig, resolveProvider, resolveVirtualId, runBuildGate, saveDrafts, serializeCatalog, stableKey, status, structureMatches, syncCatalogs, targetLocales, transformCode, transformSource, translateCatalogs, validateMessage, validatePair, watchProject, wrapCode, wrapProject, writeCatalog, writeDts };
1483
+ export { LOCALE_MODULE_PREFIX, MessageRegistry, RESOLVED_VIRTUAL_ID, SOURCE_FILE_RE, check, collectOrigins, createSourceFilter, effectiveDrafts, extractProject, formatCheckResult, formatCheckWarnings, formatStatusResult, generateDts, generateLocaleModule, generateRuntimeModule, isTransformTarget, loadCatalogs, loadConfig, loadDrafts, loadVirtualModule, markDrafts, pruneCatalogs, renderSite, resolveConfig, resolveProvider, resolveVirtualId, runBuildGate, saveDrafts, stableKey, status, syncCatalogs, transformCode, transformSource, translateCatalogs, writeCatalog, writeDts };
2833
1484
 
2834
1485
  //# sourceMappingURL=index.js.map