@verbaly/compiler 0.36.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/dist/index.d.ts CHANGED
@@ -228,6 +228,9 @@ interface StatusResult {
228
228
  declare function status(cfg: ResolvedConfig, catalogs: Catalogs, registry: MessageRegistry, drafts?: Drafts): StatusResult;
229
229
  declare function formatStatusResult(result: StatusResult): string;
230
230
  //#endregion
231
+ //#region src/text.d.ts
232
+ declare function counted(count: number, noun: string, many?: string): string;
233
+ //#endregion
231
234
  //#region src/render.d.ts
232
235
  interface RenderSiteOptions {
233
236
  site?: string;
@@ -249,5 +252,5 @@ interface RenderSiteResult {
249
252
  }
250
253
  declare function renderSite(cfg: ResolvedConfig, options?: RenderSiteOptions): Promise<RenderSiteResult>;
251
254
  //#endregion
252
- export { type BrokenEntry, type Catalog, type Catalogs, type CheckResult, type Drafts, type IssueSeverity, LOCALE_MODULE_PREFIX, type LocaleStatus, MessageRegistry, type MissingEntry, type PluginOptions, RESOLVED_VIRTUAL_ID, type RedirectConfig, type RenderConfig, type RenderSiteOptions, type RenderSiteResult, type ResolvedConfig, type RuntimeModuleOptions, SOURCE_FILE_RE, type StatusResult, type SyncResult, type TransformResult, type TranslateConfig, type TranslateOptions, type TranslateProvider, type TranslateRequest, type TranslateResult, type UnknownEntry, type VerbalyConfig, 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 };
255
+ export { type BrokenEntry, type Catalog, type Catalogs, type CheckResult, type Drafts, type IssueSeverity, LOCALE_MODULE_PREFIX, type LocaleStatus, MessageRegistry, type MissingEntry, type PluginOptions, RESOLVED_VIRTUAL_ID, type RedirectConfig, type RenderConfig, type RenderSiteOptions, type RenderSiteResult, type ResolvedConfig, type RuntimeModuleOptions, SOURCE_FILE_RE, type StatusResult, type SyncResult, type TransformResult, type TranslateConfig, type TranslateOptions, type TranslateProvider, type TranslateRequest, type TranslateResult, type UnknownEntry, type VerbalyConfig, check, collectOrigins, counted, 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 };
253
256
  //# sourceMappingURL=index.d.ts.map
package/dist/index.js CHANGED
@@ -1,10 +1,10 @@
1
1
  import { i as targetLocales, n as loadConfig, r as resolveConfig } from "./config-D8gkaunO.js";
2
2
  import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
3
3
  import { dirname, join, relative } from "node:path";
4
+ import { LOCALE_STORAGE_KEY, RICH_TAGS, VOID_TAGS, createVerbaly, flatten, localeDirection, normalizeLink, parse, parseTags, safeAttribute } from "verbaly";
4
5
  import { glob } from "tinyglobby";
5
- import { parse } from "@babel/parser";
6
+ import { parse as parse$1 } from "@babel/parser";
6
7
  import { createHash } from "node:crypto";
7
- import { LOCALE_STORAGE_KEY, RICH_TAGS, VOID_TAGS, createVerbaly, flatten, localeDirection, normalizeLink, parse as parse$1, parseTags, safeAttribute } from "verbaly";
8
8
  import picomatch from "picomatch";
9
9
  import MagicString from "magic-string";
10
10
  //#region src/catalog.ts
@@ -12,16 +12,37 @@ function catalogPath(cfg, locale) {
12
12
  return join(cfg.dir, `${locale}.json`);
13
13
  }
14
14
  function readCatalog(cfg, locale) {
15
+ const tree = readTree(cfg, locale);
16
+ const bad = badLeaf(tree);
17
+ 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`);
18
+ return flatten(tree);
19
+ }
20
+ function badLeaf(tree, prefix = "") {
21
+ for (const [key, value] of Object.entries(tree)) {
22
+ const path = prefix ? `${prefix}.${key}` : key;
23
+ if (typeof value === "string") continue;
24
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return path;
25
+ const bad = badLeaf(value, path);
26
+ if (bad) return bad;
27
+ }
28
+ }
29
+ function readTree(cfg, locale) {
15
30
  let content;
16
31
  try {
17
32
  content = readFileSync(catalogPath(cfg, locale), "utf8");
18
33
  } catch {
19
34
  return {};
20
35
  }
36
+ const parsed = parseTree(content);
37
+ if (parsed) return parsed;
38
+ throw new Error(`[verbaly] ${catalogPath(cfg, locale)} is not valid JSON, fix or delete the file`);
39
+ }
40
+ function parseTree(content) {
41
+ const body = content.charCodeAt(0) === 65279 ? content.slice(1) : content;
21
42
  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 });
43
+ return JSON.parse(body);
44
+ } catch {
45
+ return;
25
46
  }
26
47
  }
27
48
  function loadCatalogs(cfg) {
@@ -29,25 +50,68 @@ function loadCatalogs(cfg) {
29
50
  for (const locale of cfg.locales) catalogs[locale] = readCatalog(cfg, locale);
30
51
  return catalogs;
31
52
  }
32
- function serializeCatalog(catalog) {
53
+ function isNested(tree) {
54
+ return Object.values(tree).some((value) => typeof value === "object" && value !== null);
55
+ }
56
+ function nest(catalog) {
57
+ const tree = {};
58
+ for (const [key, message] of Object.entries(catalog).sort(([a], [b]) => a < b ? -1 : 1)) {
59
+ const parts = key.split(".");
60
+ const leaf = parts[parts.length - 1];
61
+ let node = parts.length > 1 ? tree : void 0;
62
+ for (let i = 0; node && i < parts.length - 1; i++) {
63
+ const next = node[parts[i]] ??= {};
64
+ node = typeof next === "object" && next !== null ? next : void 0;
65
+ }
66
+ if (node && typeof node[leaf] !== "object") node[leaf] = message;
67
+ else tree[key] = message;
68
+ }
69
+ return tree;
70
+ }
71
+ function sortTree(tree) {
33
72
  const sorted = {};
34
- for (const key of Object.keys(catalog).sort()) {
35
- const value = catalog[key];
36
- if (value !== void 0) sorted[key] = value;
73
+ for (const key of Object.keys(tree).sort()) {
74
+ const value = tree[key];
75
+ if (typeof value === "string") sorted[key] = value;
76
+ else if (value !== void 0) sorted[key] = sortTree(value);
37
77
  }
38
- return JSON.stringify(sorted, null, 2) + "\n";
78
+ return sorted;
79
+ }
80
+ function serializeCatalog(catalog, nested = false) {
81
+ return JSON.stringify(sortTree(nested ? nest(catalog) : catalog), null, 2) + "\n";
39
82
  }
40
83
  function writeCatalog(cfg, locale, catalog) {
41
- const serialized = serializeCatalog(catalog);
42
84
  const path = catalogPath(cfg, locale);
85
+ let existing;
43
86
  try {
44
- if (readFileSync(path, "utf8") === serialized) return serialized;
87
+ existing = readFileSync(path, "utf8");
45
88
  } catch {
46
89
  mkdirSync(cfg.dir, { recursive: true });
47
90
  }
91
+ const serialized = serializeCatalog(catalog, wantsNesting(cfg, locale, existing));
92
+ if (existing === serialized) return serialized;
48
93
  writeFileSync(path, serialized);
49
94
  return serialized;
50
95
  }
96
+ function wantsNesting(cfg, locale, existing) {
97
+ if (existing !== void 0) {
98
+ const tree = parseTree(existing);
99
+ return tree !== void 0 && isNested(tree);
100
+ }
101
+ if (locale === cfg.sourceLocale) return false;
102
+ return isNested(readTree(cfg, cfg.sourceLocale));
103
+ }
104
+ //#endregion
105
+ //#region src/warn.ts
106
+ const warned = /* @__PURE__ */ new Set();
107
+ function warnOnce(message, dedupeKey = message) {
108
+ if (warned.has(dedupeKey)) return;
109
+ warned.add(dedupeKey);
110
+ console.warn(`[verbaly] ${message}`);
111
+ }
112
+ function warnParseError(file, message) {
113
+ warnOnce(`${file}: could not be parsed (${message}), its messages were not extracted`);
114
+ }
51
115
  //#endregion
52
116
  //#region src/registry.ts
53
117
  var MessageRegistry = class {
@@ -63,7 +127,7 @@ var MessageRegistry = class {
63
127
  for (const analysis of this.files.values()) for (const msg of analysis.tagged) {
64
128
  const existing = out.get(msg.key);
65
129
  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.`);
130
+ if (existing.message !== msg.message) warnOnce(`key collision "${msg.key}": ${JSON.stringify(existing.message)} vs ${JSON.stringify(msg.message)}, second dropped`, `collision:${msg.key}`);
67
131
  continue;
68
132
  }
69
133
  out.set(msg.key, msg);
@@ -121,7 +185,7 @@ const DEFAULT_T_NAMES = ["t"];
121
185
  const JSX_FILE_RE = /\.(?:[cm]?jsx?|tsx)$/;
122
186
  function analyze(code, file, options = {}) {
123
187
  const names = new Set(options.tNames ?? DEFAULT_T_NAMES);
124
- const ast = parse(code, {
188
+ const ast = parse$1(code, {
125
189
  sourceType: "module",
126
190
  errorRecovery: true,
127
191
  plugins: JSX_FILE_RE.test(file) ? ["typescript", "jsx"] : ["typescript"]
@@ -606,7 +670,7 @@ const PLURAL_CATEGORIES = /* @__PURE__ */ new Set([
606
670
  const EXACT = /^=\d+$/;
607
671
  function shapes(message) {
608
672
  const out = /* @__PURE__ */ new Map();
609
- walk(parse$1(message), out);
673
+ walk(parse(message), out);
610
674
  return out;
611
675
  }
612
676
  function walk(nodes, out) {
@@ -623,7 +687,7 @@ function walk(nodes, out) {
623
687
  }
624
688
  function paramNames(message) {
625
689
  const names = /* @__PURE__ */ new Set();
626
- collect(parse$1(message), names);
690
+ collect(parse(message), names);
627
691
  return [...names].sort();
628
692
  }
629
693
  function collect(nodes, out) {
@@ -763,7 +827,7 @@ const NUMBER_FORMATS = /* @__PURE__ */ new Set([
763
827
  const DATE_FORMATS = /* @__PURE__ */ new Set(["date", "time"]);
764
828
  function collectParams(message) {
765
829
  const out = /* @__PURE__ */ new Map();
766
- visit(parse$1(message), out);
830
+ visit(parse(message), out);
767
831
  return out;
768
832
  }
769
833
  function visit(nodes, out) {
@@ -1013,15 +1077,6 @@ function truncate(text, max) {
1013
1077
  return text.length > max ? text.slice(0, max - 1) + "…" : text;
1014
1078
  }
1015
1079
  //#endregion
1016
- //#region src/warn.ts
1017
- const warned = /* @__PURE__ */ new Set();
1018
- function warnParseError(file, message) {
1019
- const line = `[verbaly] ${file}: could not be parsed (${message}), its messages were not extracted`;
1020
- if (warned.has(line)) return;
1021
- warned.add(line);
1022
- console.warn(line);
1023
- }
1024
- //#endregion
1025
1080
  //#region src/transform.ts
1026
1081
  function quote(text, single) {
1027
1082
  if (!single) return JSON.stringify(text);
@@ -1146,6 +1201,11 @@ function effectiveDrafts(drafts, catalogs) {
1146
1201
  return out;
1147
1202
  }
1148
1203
  //#endregion
1204
+ //#region src/text.ts
1205
+ function counted(count, noun, many = `${noun}s`) {
1206
+ return `${count} ${count === 1 ? noun : many}`;
1207
+ }
1208
+ //#endregion
1149
1209
  //#region src/status.ts
1150
1210
  function status(cfg, catalogs, registry, drafts = {}) {
1151
1211
  const extracted = registry.messages();
@@ -1181,7 +1241,7 @@ function status(cfg, catalogs, registry, drafts = {}) {
1181
1241
  };
1182
1242
  }
1183
1243
  function formatStatusResult(result) {
1184
- const lines = [`[verbaly] ${result.messages} messages · source: ${result.source}`];
1244
+ const lines = [`[verbaly] ${counted(result.messages, "message")} · source: ${result.source}`];
1185
1245
  if (result.locales.length === 0) {
1186
1246
  lines.push(" no target locales (add locales to your config)");
1187
1247
  return lines.join("\n");
@@ -1250,6 +1310,13 @@ function structureMatches(source, translated) {
1250
1310
  }
1251
1311
  //#endregion
1252
1312
  //#region src/render.ts
1313
+ function localeInstance(catalogs, locale, sourceLocale) {
1314
+ return createVerbaly({
1315
+ locale,
1316
+ fallback: sourceLocale,
1317
+ messages: catalogs
1318
+ });
1319
+ }
1253
1320
  const HREFLANG_OPEN = "<!--verbaly:hreflang-->";
1254
1321
  const HREFLANG_CLOSE = "<!--/verbaly:hreflang-->";
1255
1322
  const REDIRECT_OPEN = "<!--verbaly:redirect-->";
@@ -1266,11 +1333,7 @@ function renderHtml(html, options) {
1266
1333
  const richTags = new Set(options.richTags ?? RICH_TAGS);
1267
1334
  const globalLinks = options.richLinks;
1268
1335
  const sourceLocale = options.sourceLocale ?? "en";
1269
- const v = createVerbaly({
1270
- locale: options.locale,
1271
- fallback: sourceLocale,
1272
- messages: options.catalogs
1273
- });
1336
+ const v = options.instance ?? localeInstance(options.catalogs, options.locale, sourceLocale);
1274
1337
  const t = v.t;
1275
1338
  const ms = new MagicString(html);
1276
1339
  const missing = /* @__PURE__ */ new Set();
@@ -1325,8 +1388,10 @@ function renderHtml(html, options) {
1325
1388
  ...own
1326
1389
  } : own : globalLinks;
1327
1390
  const content = attrs.has(richAttr) ? richToHtml(parseTags(text), richTags, links) : escapeHtml(text);
1328
- if (html.slice(openEnd, close.contentEnd) !== content) if (openEnd === close.contentEnd) ms.appendLeft(openEnd, content);
1329
- else ms.overwrite(openEnd, close.contentEnd, content);
1391
+ if (html.slice(openEnd, close.contentEnd) !== content) {
1392
+ if (openEnd === close.contentEnd) ms.appendLeft(openEnd, content);
1393
+ else ms.overwrite(openEnd, close.contentEnd, content);
1394
+ }
1330
1395
  filled.push([openEnd, close.contentEnd]);
1331
1396
  }
1332
1397
  }
@@ -1437,6 +1502,7 @@ async function renderSite(cfg, options = {}) {
1437
1502
  storageKey: redirect.storageKey
1438
1503
  };
1439
1504
  const catalogs = loadCatalogs(cfg);
1505
+ const instances = new Map(locales.map((locale) => [locale, localeInstance(catalogs, locale, cfg.sourceLocale)]));
1440
1506
  if (clean) {
1441
1507
  for (const locale of locales) if (locale !== cfg.sourceLocale) rmSync(join(site, locale), {
1442
1508
  recursive: true,
@@ -1463,7 +1529,7 @@ async function renderSite(cfg, options = {}) {
1463
1529
  for (const locale of locales) {
1464
1530
  const result = renderHtml(html, {
1465
1531
  locale,
1466
- catalogs,
1532
+ instance: instances.get(locale),
1467
1533
  sourceLocale: cfg.sourceLocale,
1468
1534
  attribute,
1469
1535
  richTags: options.richTags,
@@ -1592,6 +1658,6 @@ function decodeEntities(text) {
1592
1658
  return text.replace(/&quot;/g, "\"").replace(/&#39;/g, "'").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&");
1593
1659
  }
1594
1660
  //#endregion
1595
- 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 };
1661
+ export { LOCALE_MODULE_PREFIX, MessageRegistry, RESOLVED_VIRTUAL_ID, SOURCE_FILE_RE, check, collectOrigins, counted, 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 };
1596
1662
 
1597
1663
  //# sourceMappingURL=index.js.map