@verbaly/compiler 0.37.0 → 0.38.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/README.md CHANGED
@@ -148,7 +148,7 @@ The package exports two layers, and **nothing else is public**. Anything you can
148
148
  | Codegen | `generateDts` `writeDts` `generateRuntimeModule` `generateLocaleModule` · type `RuntimeModuleOptions` |
149
149
  | Bundler plumbing | `transformSource` `transformCode` `runBuildGate` `createSourceFilter` `isTransformTarget` `resolveVirtualId` `loadVirtualModule` `RESOLVED_VIRTUAL_ID` `LOCALE_MODULE_PREFIX` `SOURCE_FILE_RE` · types `PluginOptions` `TransformResult` |
150
150
  | The gate | `check` `formatCheckResult` `formatCheckWarnings` · types `CheckResult` `MissingEntry` `UnknownEntry` `BrokenEntry` `IssueSeverity` |
151
- | Coverage | `status` `formatStatusResult` · types `StatusResult` `LocaleStatus` |
151
+ | Coverage | `status` `formatStatusResult` `counted` · types `StatusResult` `LocaleStatus` |
152
152
  | Draft review | `loadDrafts` `saveDrafts` `markDrafts` `effectiveDrafts` · type `Drafts` |
153
153
  | Translation | `translateCatalogs` `resolveProvider` |
154
154
  | Static rendering | `renderSite` · types `RenderSiteOptions` `RenderSiteResult` |
package/dist/cli.js CHANGED
@@ -14,16 +14,37 @@ function catalogPath(cfg, locale) {
14
14
  return join(cfg.dir, `${locale}.json`);
15
15
  }
16
16
  function readCatalog(cfg, locale) {
17
+ const tree = readTree(cfg, locale);
18
+ const bad = badLeaf(tree);
19
+ if (bad) throw new Error(`[verbaly] ${catalogPath(cfg, locale)} has a non-string value at "${bad}", catalog values are text (groups of text are fine): fix the value`);
20
+ return flatten(tree);
21
+ }
22
+ function badLeaf(tree, prefix = "") {
23
+ for (const [key, value] of Object.entries(tree)) {
24
+ const path = prefix ? `${prefix}.${key}` : key;
25
+ if (typeof value === "string") continue;
26
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return path;
27
+ const bad = badLeaf(value, path);
28
+ if (bad) return bad;
29
+ }
30
+ }
31
+ function readTree(cfg, locale) {
17
32
  let content;
18
33
  try {
19
34
  content = readFileSync(catalogPath(cfg, locale), "utf8");
20
35
  } catch {
21
36
  return {};
22
37
  }
38
+ const parsed = parseTree(content);
39
+ if (parsed) return parsed;
40
+ throw new Error(`[verbaly] ${catalogPath(cfg, locale)} is not valid JSON, fix or delete the file`);
41
+ }
42
+ function parseTree(content) {
43
+ const body = content.charCodeAt(0) === 65279 ? content.slice(1) : content;
23
44
  try {
24
- return JSON.parse(content.replace(/^\uFEFF/, ""));
25
- } catch (error) {
26
- throw new Error(`[verbaly] ${catalogPath(cfg, locale)} is not valid JSON, fix or delete the file`, { cause: error });
45
+ return JSON.parse(body);
46
+ } catch {
47
+ return;
27
48
  }
28
49
  }
29
50
  function loadCatalogs(cfg) {
@@ -31,25 +52,57 @@ function loadCatalogs(cfg) {
31
52
  for (const locale of cfg.locales) catalogs[locale] = readCatalog(cfg, locale);
32
53
  return catalogs;
33
54
  }
34
- function serializeCatalog(catalog) {
55
+ function isNested(tree) {
56
+ return Object.values(tree).some((value) => typeof value === "object" && value !== null);
57
+ }
58
+ function nest(catalog) {
59
+ const tree = {};
60
+ for (const [key, message] of Object.entries(catalog).sort(([a], [b]) => a < b ? -1 : 1)) {
61
+ const parts = key.split(".");
62
+ const leaf = parts[parts.length - 1];
63
+ let node = parts.length > 1 ? tree : void 0;
64
+ for (let i = 0; node && i < parts.length - 1; i++) {
65
+ const next = node[parts[i]] ??= {};
66
+ node = typeof next === "object" && next !== null ? next : void 0;
67
+ }
68
+ if (node && typeof node[leaf] !== "object") node[leaf] = message;
69
+ else tree[key] = message;
70
+ }
71
+ return tree;
72
+ }
73
+ function sortTree(tree) {
35
74
  const sorted = {};
36
- for (const key of Object.keys(catalog).sort()) {
37
- const value = catalog[key];
38
- if (value !== void 0) sorted[key] = value;
75
+ for (const key of Object.keys(tree).sort()) {
76
+ const value = tree[key];
77
+ if (typeof value === "string") sorted[key] = value;
78
+ else if (value !== void 0) sorted[key] = sortTree(value);
39
79
  }
40
- return JSON.stringify(sorted, null, 2) + "\n";
80
+ return sorted;
81
+ }
82
+ function serializeCatalog(catalog, nested = false) {
83
+ return JSON.stringify(sortTree(nested ? nest(catalog) : catalog), null, 2) + "\n";
41
84
  }
42
85
  function writeCatalog(cfg, locale, catalog) {
43
- const serialized = serializeCatalog(catalog);
44
86
  const path = catalogPath(cfg, locale);
87
+ let existing;
45
88
  try {
46
- if (readFileSync(path, "utf8") === serialized) return serialized;
89
+ existing = readFileSync(path, "utf8");
47
90
  } catch {
48
91
  mkdirSync(cfg.dir, { recursive: true });
49
92
  }
93
+ const serialized = serializeCatalog(catalog, wantsNesting(cfg, locale, existing));
94
+ if (existing === serialized) return serialized;
50
95
  writeFileSync(path, serialized);
51
96
  return serialized;
52
97
  }
98
+ function wantsNesting(cfg, locale, existing) {
99
+ if (existing !== void 0) {
100
+ const tree = parseTree(existing);
101
+ return tree !== void 0 && isNested(tree);
102
+ }
103
+ if (locale === cfg.sourceLocale) return false;
104
+ return isNested(readTree(cfg, cfg.sourceLocale));
105
+ }
53
106
  //#endregion
54
107
  //#region src/validate.ts
55
108
  const PLURAL_CATEGORIES = /* @__PURE__ */ new Set([
@@ -665,6 +718,14 @@ function definedOnly(config) {
665
718
  return Object.fromEntries(Object.entries(config).filter(([, value]) => value !== void 0));
666
719
  }
667
720
  //#endregion
721
+ //#region src/warn.ts
722
+ const warned = /* @__PURE__ */ new Set();
723
+ function warnOnce(message, dedupeKey = message) {
724
+ if (warned.has(dedupeKey)) return;
725
+ warned.add(dedupeKey);
726
+ console.warn(`[verbaly] ${message}`);
727
+ }
728
+ //#endregion
668
729
  //#region src/registry.ts
669
730
  var MessageRegistry = class {
670
731
  files = /* @__PURE__ */ new Map();
@@ -679,7 +740,7 @@ var MessageRegistry = class {
679
740
  for (const analysis of this.files.values()) for (const msg of analysis.tagged) {
680
741
  const existing = out.get(msg.key);
681
742
  if (existing) {
682
- if (existing.message !== msg.message) console.warn(`[verbaly] key collision "${msg.key}": ${JSON.stringify(existing.message)} vs ${JSON.stringify(msg.message)}, second dropped.`);
743
+ if (existing.message !== msg.message) warnOnce(`key collision "${msg.key}": ${JSON.stringify(existing.message)} vs ${JSON.stringify(msg.message)}, second dropped`, `collision:${msg.key}`);
683
744
  continue;
684
745
  }
685
746
  out.set(msg.key, msg);
@@ -1328,6 +1389,11 @@ function init(options = {}) {
1328
1389
  };
1329
1390
  }
1330
1391
  //#endregion
1392
+ //#region src/text.ts
1393
+ function counted(count, noun, many = `${noun}s`) {
1394
+ return `${count} ${count === 1 ? noun : many}`;
1395
+ }
1396
+ //#endregion
1331
1397
  //#region src/doctor.ts
1332
1398
  const PREVIEW = 5;
1333
1399
  async function doctor(cfg) {
@@ -1378,7 +1444,7 @@ async function doctor(cfg) {
1378
1444
  error(`locale ${locale}`, `${rel(file)} is not valid JSON`, "repair the file (or delete it and run `npx verbaly extract`)");
1379
1445
  }
1380
1446
  }
1381
- if (catalogsHealthy) ok("catalogs", `${cfg.locales.length} locales (${cfg.locales.join(", ")}) in ${rel(cfg.dir)}/`);
1447
+ if (catalogsHealthy) ok("catalogs", `${counted(cfg.locales.length, "locale")} (${cfg.locales.join(", ")}) in ${rel(cfg.dir)}/`);
1382
1448
  }
1383
1449
  const source = catalogs[cfg.sourceLocale];
1384
1450
  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`");
@@ -1447,15 +1513,6 @@ function preview(keys) {
1447
1513
  const head = keys.slice(0, PREVIEW).join(", ");
1448
1514
  return keys.length > PREVIEW ? `${head}, …` : head;
1449
1515
  }
1450
- function badLeaf(tree, prefix = "") {
1451
- for (const [key, value] of Object.entries(tree)) {
1452
- const path = prefix ? `${prefix}.${key}` : key;
1453
- if (typeof value === "string") continue;
1454
- if (value === null || typeof value !== "object" || Array.isArray(value)) return path;
1455
- const bad = badLeaf(value, path);
1456
- if (bad) return bad;
1457
- }
1458
- }
1459
1516
  //#endregion
1460
1517
  //#region src/drafts.ts
1461
1518
  const DRAFTS_FILE = ".verbaly-drafts.json";
@@ -1939,7 +1996,8 @@ function exportCatalogs(cfg, catalogs, options = {}) {
1939
1996
  const untranslated = all.filter((entry) => !entry.target);
1940
1997
  const entries = options.missing ? untranslated : all;
1941
1998
  const path = join(dir, `${locale}.${format === "xliff" ? "xlf" : format}`);
1942
- writeFileSync(path, format === "csv" ? toCsv(entries) : format === "po" ? toPo(cfg.sourceLocale, locale, entries) : toXliff(cfg.sourceLocale, locale, entries));
1999
+ const content = format === "csv" ? toCsv(entries) : format === "po" ? toPo(cfg.sourceLocale, locale, entries) : toXliff(cfg.sourceLocale, locale, entries);
2000
+ writeFileSync(path, content);
1943
2001
  files.push({
1944
2002
  locale,
1945
2003
  path,
@@ -1962,7 +2020,8 @@ function exportMobile(cfg, catalogs, format, dir, source, targets) {
1962
2020
  key,
1963
2021
  text: catalog[key] ?? ""
1964
2022
  })).filter((entry) => entry.text);
1965
- const path = join(dir, format === "android-xml" ? join(androidValuesDir(locale, cfg.sourceLocale), "strings.xml") : join(`${locale}.lproj`, "Localizable.strings"));
2023
+ const relative = format === "android-xml" ? join(androidValuesDir(locale, cfg.sourceLocale), "strings.xml") : join(`${locale}.lproj`, "Localizable.strings");
2024
+ const path = join(dir, relative);
1966
2025
  mkdirSync(dirname(path), { recursive: true });
1967
2026
  writeFileSync(path, format === "android-xml" ? toAndroidXml(entries) : toIosStrings(entries));
1968
2027
  files.push({
@@ -2107,12 +2166,14 @@ function csvRows(content) {
2107
2166
  let quoted = false;
2108
2167
  for (let i = 0; i < content.length; i++) {
2109
2168
  const char = content[i];
2110
- if (quoted) if (char === "\"") if (content[i + 1] === "\"") {
2111
- field += "\"";
2112
- i++;
2113
- } else quoted = false;
2114
- else field += char;
2115
- else if (char === "\"") quoted = true;
2169
+ if (quoted) {
2170
+ if (char === "\"") {
2171
+ if (content[i + 1] === "\"") {
2172
+ field += "\"";
2173
+ i++;
2174
+ } else quoted = false;
2175
+ } else field += char;
2176
+ } else if (char === "\"") quoted = true;
2116
2177
  else if (char === ",") {
2117
2178
  row.push(field);
2118
2179
  field = "";
@@ -2130,6 +2191,13 @@ function csvRows(content) {
2130
2191
  }
2131
2192
  //#endregion
2132
2193
  //#region src/render.ts
2194
+ function localeInstance(catalogs, locale, sourceLocale) {
2195
+ return createVerbaly({
2196
+ locale,
2197
+ fallback: sourceLocale,
2198
+ messages: catalogs
2199
+ });
2200
+ }
2133
2201
  const HREFLANG_OPEN = "<!--verbaly:hreflang-->";
2134
2202
  const HREFLANG_CLOSE = "<!--/verbaly:hreflang-->";
2135
2203
  const REDIRECT_OPEN = "<!--verbaly:redirect-->";
@@ -2146,11 +2214,7 @@ function renderHtml(html, options) {
2146
2214
  const richTags = new Set(options.richTags ?? RICH_TAGS);
2147
2215
  const globalLinks = options.richLinks;
2148
2216
  const sourceLocale = options.sourceLocale ?? "en";
2149
- const v = createVerbaly({
2150
- locale: options.locale,
2151
- fallback: sourceLocale,
2152
- messages: options.catalogs
2153
- });
2217
+ const v = options.instance ?? localeInstance(options.catalogs, options.locale, sourceLocale);
2154
2218
  const t = v.t;
2155
2219
  const ms = new MagicString(html);
2156
2220
  const missing = /* @__PURE__ */ new Set();
@@ -2205,8 +2269,10 @@ function renderHtml(html, options) {
2205
2269
  ...own
2206
2270
  } : own : globalLinks;
2207
2271
  const content = attrs.has(richAttr) ? richToHtml(parseTags(text), richTags, links) : escapeHtml(text);
2208
- if (html.slice(openEnd, close.contentEnd) !== content) if (openEnd === close.contentEnd) ms.appendLeft(openEnd, content);
2209
- else ms.overwrite(openEnd, close.contentEnd, content);
2272
+ if (html.slice(openEnd, close.contentEnd) !== content) {
2273
+ if (openEnd === close.contentEnd) ms.appendLeft(openEnd, content);
2274
+ else ms.overwrite(openEnd, close.contentEnd, content);
2275
+ }
2210
2276
  filled.push([openEnd, close.contentEnd]);
2211
2277
  }
2212
2278
  }
@@ -2317,6 +2383,7 @@ async function renderSite(cfg, options = {}) {
2317
2383
  storageKey: redirect.storageKey
2318
2384
  };
2319
2385
  const catalogs = loadCatalogs(cfg);
2386
+ const instances = new Map(locales.map((locale) => [locale, localeInstance(catalogs, locale, cfg.sourceLocale)]));
2320
2387
  if (clean) {
2321
2388
  for (const locale of locales) if (locale !== cfg.sourceLocale) rmSync(join(site, locale), {
2322
2389
  recursive: true,
@@ -2343,7 +2410,7 @@ async function renderSite(cfg, options = {}) {
2343
2410
  for (const locale of locales) {
2344
2411
  const result = renderHtml(html, {
2345
2412
  locale,
2346
- catalogs,
2413
+ instance: instances.get(locale),
2347
2414
  sourceLocale: cfg.sourceLocale,
2348
2415
  attribute,
2349
2416
  richTags: options.richTags,
@@ -2507,7 +2574,7 @@ function status(cfg, catalogs, registry, drafts = {}) {
2507
2574
  };
2508
2575
  }
2509
2576
  function formatStatusResult(result) {
2510
- const lines = [`[verbaly] ${result.messages} messages · source: ${result.source}`];
2577
+ const lines = [`[verbaly] ${counted(result.messages, "message")} · source: ${result.source}`];
2511
2578
  if (result.locales.length === 0) {
2512
2579
  lines.push(" no target locales (add locales to your config)");
2513
2580
  return lines.join("\n");
@@ -2891,7 +2958,7 @@ async function runCli(args = process.argv.slice(2)) {
2891
2958
  warn: "⚠",
2892
2959
  error: "✗"
2893
2960
  };
2894
- console.log(`[verbaly] doctor: ${plural(result.entries.length, "check")}`);
2961
+ console.log(`[verbaly] doctor: ${counted(result.entries.length, "check")}`);
2895
2962
  for (const entry of result.entries) {
2896
2963
  const line = ` ${icon[entry.level]} ${entry.check}: ${entry.message}`;
2897
2964
  if (entry.level === "error") console.error(line);
@@ -2926,7 +2993,7 @@ async function runCli(args = process.argv.slice(2)) {
2926
2993
  if (cfg.dts !== false) writeDts(cfg, catalogs[cfg.sourceLocale] ?? {}, cfg.dts);
2927
2994
  }
2928
2995
  const total = registry.messages().size;
2929
- console.log(`[verbaly] ${plural(total, "message")} · locales: ${cfg.locales.join(", ")}${dryRun ? " (dry run, nothing written)" : ""}`);
2996
+ console.log(`[verbaly] ${counted(total, "message")} · locales: ${cfg.locales.join(", ")}${dryRun ? " (dry run, nothing written)" : ""}`);
2930
2997
  for (const [locale, keys] of Object.entries(added)) console.log(` ${locale}: ${dryRun ? `would add ${keys.length}` : `+${keys.length}`}`);
2931
2998
  reportParseErrors(cfg, registry);
2932
2999
  reportEscapedSyntax(cfg, registry);
@@ -2941,12 +3008,12 @@ async function runCli(args = process.argv.slice(2)) {
2941
3008
  if (command === "wrap") {
2942
3009
  const result = await wrapProject(cfg, { write: values.write });
2943
3010
  if (result.wrapped.length === 0 && result.skipped.length === 0) {
2944
- console.log(`[verbaly] nothing to wrap (${plural(result.files, "file")} scanned) ✓`);
3011
+ console.log(`[verbaly] nothing to wrap (${counted(result.files, "file")} scanned) ✓`);
2945
3012
  return;
2946
3013
  }
2947
3014
  const verb = values.write ? "wrapped" : "would wrap";
2948
3015
  const note = values.write ? "" : " (report only, use --write to apply)";
2949
- console.log(`[verbaly] ${verb} ${plural(result.wrapped.length, "text")} in ${plural(result.changed.length, "file")}${note}`);
3016
+ console.log(`[verbaly] ${verb} ${counted(result.wrapped.length, "text")} in ${counted(result.changed.length, "file")}${note}`);
2950
3017
  for (const entry of result.wrapped) {
2951
3018
  const attr = entry.kind === "attribute" ? `${entry.attribute} → ` : "";
2952
3019
  console.log(` ${entry.file}:${entry.line} ${attr}"${entry.text}"`);
@@ -3043,11 +3110,11 @@ async function runCli(args = process.argv.slice(2)) {
3043
3110
  console.log(` ${locale}: ${keys.length} approved`);
3044
3111
  }
3045
3112
  saveDrafts(cfg, drafts);
3046
- console.log(`[verbaly] ${count} translations marked reviewed ✓`);
3113
+ console.log(`[verbaly] ${counted(count, "translation")} marked reviewed ✓`);
3047
3114
  return;
3048
3115
  }
3049
3116
  const total = entries.reduce((sum, [, keys]) => sum + keys.length, 0);
3050
- console.log(`[verbaly] ${total} machine translations awaiting review (--approve to accept)`);
3117
+ console.log(`[verbaly] ${counted(total, "machine translation")} awaiting review (--approve to accept)`);
3051
3118
  for (const [locale, keys] of entries) console.log(` ${locale}: ${keys.join(", ")}`);
3052
3119
  return;
3053
3120
  }
@@ -3081,8 +3148,8 @@ async function runCli(args = process.argv.slice(2)) {
3081
3148
  return;
3082
3149
  }
3083
3150
  const note = isMobileFormat(result.format) ? "untranslated skipped" : "untranslated";
3084
- console.log(`[verbaly] exported ${result.files.length} locales (${result.format}) → ${result.dir}`);
3085
- for (const file of result.files) console.log(` ${file.locale}: ${file.total} messages (${file.untranslated} ${note}) → ${file.path}`);
3151
+ console.log(`[verbaly] exported ${counted(result.files.length, "locale")} (${result.format}) → ${result.dir}`);
3152
+ for (const file of result.files) console.log(` ${file.locale}: ${counted(file.total, "message")} (${file.untranslated} ${note}) → ${file.path}`);
3086
3153
  return;
3087
3154
  }
3088
3155
  if (command === "import") {
@@ -3112,7 +3179,7 @@ async function runCli(args = process.argv.slice(2)) {
3112
3179
  if (draftsChanged) saveDrafts(cfg, drafts);
3113
3180
  for (const [locale, keys] of Object.entries(result.skipped)) console.log(` ${locale}: ${keys.length} already translated, kept (use --overwrite to replace)`);
3114
3181
  for (const [locale, keys] of Object.entries(result.rejected)) console.warn(` ${locale}: ${keys.length} rejected (params/tags not preserved): ${keys.join(", ")}`);
3115
- for (const [locale, keys] of Object.entries(result.unknown)) console.warn(` ${locale}: ${keys.length} unknown keys ignored (not in the source catalog): ${keys.join(", ")}`);
3182
+ for (const [locale, keys] of Object.entries(result.unknown)) console.warn(` ${locale}: ${counted(keys.length, "unknown key")} ignored (not in the source catalog): ${keys.join(", ")}`);
3116
3183
  if (Object.keys(result.imported).length === 0) console.log("[verbaly] nothing to import ✓");
3117
3184
  return;
3118
3185
  }
@@ -3127,8 +3194,8 @@ async function runCli(args = process.argv.slice(2)) {
3127
3194
  redirect: values.redirect,
3128
3195
  clean: values.clean
3129
3196
  });
3130
- console.log(`[verbaly] ${plural(result.files, "page")} × ${plural(result.locales.length, "locale")} (${result.locales.join(", ")})`);
3131
- for (const [locale, keys] of Object.entries(result.missing)) console.warn(` ${locale}: ${plural(keys.length, "key")} not pre-filled: ${keys.join(", ")}`);
3197
+ console.log(`[verbaly] ${counted(result.files, "page")} × ${counted(result.locales.length, "locale")} (${result.locales.join(", ")})`);
3198
+ for (const [locale, keys] of Object.entries(result.missing)) console.warn(` ${locale}: ${counted(keys.length, "key")} not pre-filled: ${keys.join(", ")}`);
3132
3199
  return;
3133
3200
  }
3134
3201
  if (command === "pseudo") {
@@ -3136,7 +3203,7 @@ async function runCli(args = process.argv.slice(2)) {
3136
3203
  const locale = values.locale ?? "en-XA";
3137
3204
  const keys = pseudoCatalogs(cfg, catalogs, locale);
3138
3205
  writeCatalog(cfg, locale, catalogs[locale] ?? {});
3139
- console.log(`[verbaly] ${plural(keys.length, "message")} pseudo-localized → ${locale}`);
3206
+ console.log(`[verbaly] ${counted(keys.length, "message")} pseudo-localized → ${locale}`);
3140
3207
  return;
3141
3208
  }
3142
3209
  console.error(`[verbaly] unknown command "${command}"\n${HELP}`);
@@ -3146,9 +3213,6 @@ function formatCliError(error) {
3146
3213
  const message = error instanceof Error ? error.message : String(error);
3147
3214
  return message.startsWith("[verbaly]") ? message : `[verbaly] ${message}`;
3148
3215
  }
3149
- function plural(count, noun) {
3150
- return `${count} ${noun}${count === 1 ? "" : "s"}`;
3151
- }
3152
3216
  function reportParseErrors(cfg, registry) {
3153
3217
  for (const { file, message } of registry.parseErrors()) {
3154
3218
  const rel = relative(cfg.root, file).replaceAll("\\", "/");