@verbaly/compiler 0.11.0 → 0.12.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/cli.js CHANGED
@@ -1,145 +1,151 @@
1
1
  #!/usr/bin/env node
2
-
3
- // src/cli.ts
4
- import { parseArgs as parseArgs2 } from "util";
5
-
6
- // src/catalog.ts
7
- import { mkdirSync, readFileSync, writeFileSync } from "fs";
8
- import { join } from "path";
2
+ import { parseArgs } from "node:util";
3
+ import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
4
+ import { dirname, join, relative, resolve } from "node:path";
5
+ import { RICH_TAGS, createVerbaly, parse, parseTags, safeHref } from "verbaly";
6
+ import { pathToFileURL } from "node:url";
7
+ import { glob } from "tinyglobby";
8
+ import { parse as parse$1 } from "@babel/parser";
9
+ import { createHash } from "node:crypto";
10
+ import MagicString from "magic-string";
11
+ //#region src/catalog.ts
9
12
  function catalogPath(cfg, locale) {
10
- return join(cfg.dir, `${locale}.json`);
13
+ return join(cfg.dir, `${locale}.json`);
11
14
  }
12
15
  function readCatalog(cfg, locale) {
13
- try {
14
- return JSON.parse(readFileSync(catalogPath(cfg, locale), "utf8"));
15
- } catch {
16
- return {};
17
- }
16
+ try {
17
+ return JSON.parse(readFileSync(catalogPath(cfg, locale), "utf8"));
18
+ } catch {
19
+ return {};
20
+ }
18
21
  }
19
22
  function loadCatalogs(cfg) {
20
- const catalogs = {};
21
- for (const locale of cfg.locales) catalogs[locale] = readCatalog(cfg, locale);
22
- return catalogs;
23
+ const catalogs = {};
24
+ for (const locale of cfg.locales) catalogs[locale] = readCatalog(cfg, locale);
25
+ return catalogs;
23
26
  }
24
27
  function serializeCatalog(catalog) {
25
- const sorted = {};
26
- for (const key of Object.keys(catalog).sort()) {
27
- const value = catalog[key];
28
- if (value !== void 0) sorted[key] = value;
29
- }
30
- return JSON.stringify(sorted, null, 2) + "\n";
28
+ const sorted = {};
29
+ for (const key of Object.keys(catalog).sort()) {
30
+ const value = catalog[key];
31
+ if (value !== void 0) sorted[key] = value;
32
+ }
33
+ return JSON.stringify(sorted, null, 2) + "\n";
31
34
  }
32
35
  function writeCatalog(cfg, locale, catalog) {
33
- const serialized = serializeCatalog(catalog);
34
- mkdirSync(cfg.dir, { recursive: true });
35
- writeFileSync(catalogPath(cfg, locale), serialized);
36
- return serialized;
36
+ const serialized = serializeCatalog(catalog);
37
+ mkdirSync(cfg.dir, { recursive: true });
38
+ writeFileSync(catalogPath(cfg, locale), serialized);
39
+ return serialized;
37
40
  }
38
-
39
- // src/check.ts
41
+ //#endregion
42
+ //#region src/check.ts
40
43
  function check(cfg, catalogs, registry) {
41
- const source = catalogs[cfg.sourceLocale] ?? {};
42
- const extracted = registry.messages();
43
- const unknown = [];
44
- for (const [key, files] of registry.usedKeys()) {
45
- const known = extracted.has(key) || cfg.locales.some((locale) => catalogs[locale]?.[key] !== void 0);
46
- if (!known) unknown.push({ key, files });
47
- }
48
- const needed = /* @__PURE__ */ new Set([...extracted.keys(), ...Object.keys(source)]);
49
- const missing = [];
50
- for (const key of extracted.keys()) {
51
- if (!source[key]) {
52
- missing.push({ locale: cfg.sourceLocale, key, source: extracted.get(key)?.message });
53
- }
54
- }
55
- for (const locale of cfg.locales) {
56
- if (locale === cfg.sourceLocale) continue;
57
- for (const key of needed) {
58
- if (!catalogs[locale]?.[key]) {
59
- missing.push({ locale, key, source: source[key] ?? extracted.get(key)?.message });
60
- }
61
- }
62
- }
63
- return { ok: missing.length === 0 && unknown.length === 0, missing, unknown };
44
+ const source = catalogs[cfg.sourceLocale] ?? {};
45
+ const extracted = registry.messages();
46
+ const unknown = [];
47
+ for (const [key, files] of registry.usedKeys()) if (!(extracted.has(key) || cfg.locales.some((locale) => catalogs[locale]?.[key] !== void 0))) unknown.push({
48
+ key,
49
+ files
50
+ });
51
+ const needed = /* @__PURE__ */ new Set([...extracted.keys(), ...Object.keys(source)]);
52
+ const missing = [];
53
+ for (const key of extracted.keys()) if (!source[key]) missing.push({
54
+ locale: cfg.sourceLocale,
55
+ key,
56
+ source: extracted.get(key)?.message
57
+ });
58
+ for (const locale of cfg.locales) {
59
+ if (locale === cfg.sourceLocale) continue;
60
+ for (const key of needed) if (!catalogs[locale]?.[key]) missing.push({
61
+ locale,
62
+ key,
63
+ source: source[key] ?? extracted.get(key)?.message
64
+ });
65
+ }
66
+ return {
67
+ ok: missing.length === 0 && unknown.length === 0,
68
+ missing,
69
+ unknown
70
+ };
64
71
  }
65
72
  function formatCheckResult(result) {
66
- const lines = [];
67
- if (result.missing.length > 0) {
68
- lines.push("missing translations:");
69
- for (const entry of result.missing) {
70
- const hint = entry.source ? ` \u2014 "${truncate(entry.source, 40)}"` : "";
71
- lines.push(` [${entry.locale}] ${entry.key}${hint}`);
72
- }
73
- }
74
- if (result.unknown.length > 0) {
75
- lines.push("unknown keys (not in any catalog):");
76
- for (const entry of result.unknown) {
77
- lines.push(` ${entry.key} \u2014 used in ${entry.files.join(", ")}`);
78
- }
79
- }
80
- return lines.join("\n");
73
+ const lines = [];
74
+ if (result.missing.length > 0) {
75
+ lines.push("missing translations:");
76
+ for (const entry of result.missing) {
77
+ const hint = entry.source ? ` "${truncate(entry.source, 40)}"` : "";
78
+ lines.push(` [${entry.locale}] ${entry.key}${hint}`);
79
+ }
80
+ }
81
+ if (result.unknown.length > 0) {
82
+ lines.push("unknown keys (not in any catalog):");
83
+ for (const entry of result.unknown) lines.push(` ${entry.key} — used in ${entry.files.join(", ")}`);
84
+ }
85
+ return lines.join("\n");
81
86
  }
82
87
  function truncate(text, max) {
83
- return text.length > max ? text.slice(0, max - 1) + "\u2026" : text;
88
+ return text.length > max ? text.slice(0, max - 1) + "" : text;
84
89
  }
85
-
86
- // src/codegen.ts
87
- import { writeFileSync as writeFileSync2 } from "fs";
88
- import { join as join2 } from "path";
89
-
90
- // src/params.ts
91
- import { parse } from "verbaly";
92
- var PLURAL_KEYS = /* @__PURE__ */ new Set(["zero", "one", "two", "few", "many"]);
93
- var NUMBER_FORMATS = /* @__PURE__ */ new Set(["number", "integer", "percent", "currency"]);
94
- var DATE_FORMATS = /* @__PURE__ */ new Set(["date", "time"]);
90
+ //#endregion
91
+ //#region src/params.ts
92
+ const PLURAL_KEYS = /* @__PURE__ */ new Set([
93
+ "zero",
94
+ "one",
95
+ "two",
96
+ "few",
97
+ "many"
98
+ ]);
99
+ const NUMBER_FORMATS = /* @__PURE__ */ new Set([
100
+ "number",
101
+ "integer",
102
+ "percent",
103
+ "currency"
104
+ ]);
105
+ const DATE_FORMATS = /* @__PURE__ */ new Set(["date", "time"]);
95
106
  function collectParams(message) {
96
- const out = /* @__PURE__ */ new Map();
97
- visit(parse(message), out);
98
- return out;
107
+ const out = /* @__PURE__ */ new Map();
108
+ visit(parse(message), out);
109
+ return out;
99
110
  }
100
111
  function visit(nodes, out) {
101
- for (const node of nodes) {
102
- if (node.kind !== "param") continue;
103
- const types = out.get(node.name) ?? /* @__PURE__ */ new Set();
104
- out.set(node.name, types);
105
- if (node.variants) {
106
- for (const [key, body] of node.variants) {
107
- if (PLURAL_KEYS.has(key) || /^=\d+$/.test(key)) types.add("number");
108
- else if (key !== "other") types.add("string");
109
- visit(body, out);
110
- }
111
- if (types.size === 0) types.add("string");
112
- } else if (node.format && NUMBER_FORMATS.has(node.format)) {
113
- types.add("number");
114
- } else if (node.format && DATE_FORMATS.has(node.format)) {
115
- types.add("date");
116
- } else {
117
- types.add("unknown");
118
- }
119
- }
112
+ for (const node of nodes) {
113
+ if (node.kind !== "param") continue;
114
+ const types = out.get(node.name) ?? /* @__PURE__ */ new Set();
115
+ out.set(node.name, types);
116
+ if (node.variants) {
117
+ for (const [key, body] of node.variants) {
118
+ if (PLURAL_KEYS.has(key) || /^=\d+$/.test(key)) types.add("number");
119
+ else if (key !== "other") types.add("string");
120
+ visit(body, out);
121
+ }
122
+ if (types.size === 0) types.add("string");
123
+ } else if (node.format && NUMBER_FORMATS.has(node.format)) types.add("number");
124
+ else if (node.format && DATE_FORMATS.has(node.format)) types.add("date");
125
+ else types.add("unknown");
126
+ }
120
127
  }
121
128
  function renderParamType(types) {
122
- if (types.has("unknown") || types.size === 0) return "unknown";
123
- const parts = [];
124
- if (types.has("number")) parts.push("number");
125
- if (types.has("string")) parts.push("string");
126
- if (types.has("date")) parts.push("Date | number | string");
127
- return parts.join(" | ");
129
+ if (types.has("unknown") || types.size === 0) return "unknown";
130
+ const parts = [];
131
+ if (types.has("number")) parts.push("number");
132
+ if (types.has("string")) parts.push("string");
133
+ if (types.has("date")) parts.push("Date | number | string");
134
+ return parts.join(" | ");
128
135
  }
129
-
130
- // src/codegen.ts
136
+ //#endregion
137
+ //#region src/codegen.ts
131
138
  function generateDts(entries) {
132
- const lines = [];
133
- for (const [key, message] of [...entries.entries()].sort(([a], [b]) => a.localeCompare(b))) {
134
- const params = collectParams(message);
135
- if (params.size === 0) {
136
- lines.push(` ${JSON.stringify(key)}: never;`);
137
- } else {
138
- const fields = [...params.entries()].map(([name, types]) => `${JSON.stringify(name)}: ${renderParamType(types)}`).join("; ");
139
- lines.push(` ${JSON.stringify(key)}: { ${fields} };`);
140
- }
141
- }
142
- return `// generated by verbaly \u2014 do not edit
139
+ const lines = [];
140
+ for (const [key, message] of [...entries.entries()].sort(([a], [b]) => a.localeCompare(b))) {
141
+ const params = collectParams(message);
142
+ if (params.size === 0) lines.push(` ${JSON.stringify(key)}: never;`);
143
+ else {
144
+ const fields = [...params.entries()].map(([name, types]) => `${JSON.stringify(name)}: ${renderParamType(types)}`).join("; ");
145
+ lines.push(` ${JSON.stringify(key)}: { ${fields} };`);
146
+ }
147
+ }
148
+ return `// generated by verbaly — do not edit
143
149
  declare module 'virtual:verbaly' {
144
150
  export interface VerbalyMessages {
145
151
  ${lines.join("\n")}
@@ -171,830 +177,870 @@ declare module 'virtual:verbaly/locale/*' {
171
177
  `;
172
178
  }
173
179
  function writeDts(cfg, entries) {
174
- writeFileSync2(join2(cfg.root, "verbaly.d.ts"), generateDts(entries));
180
+ writeFileSync(join(cfg.root, "verbaly.d.ts"), generateDts(entries));
175
181
  }
176
-
177
- // src/config.ts
178
- import { existsSync, readFileSync as readFileSync2, readdirSync } from "fs";
179
- import { join as join3, resolve } from "path";
180
- import { pathToFileURL } from "url";
182
+ //#endregion
183
+ //#region src/config.ts
181
184
  function resolveConfig(config = {}) {
182
- const root = resolve(config.root ?? process.cwd());
183
- const dir = resolve(root, config.dir ?? "locales");
184
- const sourceLocale = config.sourceLocale ?? "en";
185
- const locales = /* @__PURE__ */ new Set([sourceLocale, ...config.locales ?? []]);
186
- if (existsSync(dir)) {
187
- for (const file of readdirSync(dir)) {
188
- if (file.endsWith(".json")) locales.add(file.slice(0, -5));
189
- }
190
- }
191
- return {
192
- root,
193
- dir,
194
- sourceLocale,
195
- locales: [...locales],
196
- include: config.include ?? ["src/**/*.{js,jsx,ts,tsx,mjs,mts}"],
197
- exclude: config.exclude ?? ["**/node_modules/**", "**/dist/**"],
198
- translate: config.translate ?? {},
199
- render: config.render ?? {}
200
- };
185
+ const root = resolve(config.root ?? process.cwd());
186
+ const dir = resolve(root, config.dir ?? "locales");
187
+ const sourceLocale = config.sourceLocale ?? "en";
188
+ const locales = /* @__PURE__ */ new Set([sourceLocale, ...config.locales ?? []]);
189
+ if (existsSync(dir)) {
190
+ for (const file of readdirSync(dir)) if (file.endsWith(".json")) locales.add(file.slice(0, -5));
191
+ }
192
+ return {
193
+ root,
194
+ dir,
195
+ sourceLocale,
196
+ locales: [...locales],
197
+ include: config.include ?? ["src/**/*.{js,jsx,ts,tsx,mjs,mts}"],
198
+ exclude: config.exclude ?? ["**/node_modules/**", "**/dist/**"],
199
+ translate: config.translate ?? {},
200
+ render: config.render ?? {}
201
+ };
201
202
  }
202
203
  async function loadConfigFile(root) {
203
- for (const name of ["verbaly.config.js", "verbaly.config.mjs"]) {
204
- const path = join3(root, name);
205
- if (existsSync(path)) {
206
- const mod = await import(pathToFileURL(path).href);
207
- return mod.default ?? {};
208
- }
209
- }
210
- for (const name of ["verbaly.config.ts", "verbaly.config.mts"]) {
211
- const path = join3(root, name);
212
- if (existsSync(path)) return loadTsConfig(path);
213
- }
214
- const jsonPath = join3(root, "verbaly.config.json");
215
- if (existsSync(jsonPath)) {
216
- return JSON.parse(readFileSync2(jsonPath, "utf8"));
217
- }
218
- return {};
204
+ for (const name of ["verbaly.config.js", "verbaly.config.mjs"]) {
205
+ const path = join(root, name);
206
+ if (existsSync(path)) return (await import(pathToFileURL(path).href)).default ?? {};
207
+ }
208
+ for (const name of ["verbaly.config.ts", "verbaly.config.mts"]) {
209
+ const path = join(root, name);
210
+ if (existsSync(path)) return loadTsConfig(path);
211
+ }
212
+ const jsonPath = join(root, "verbaly.config.json");
213
+ if (existsSync(jsonPath)) return JSON.parse(readFileSync(jsonPath, "utf8"));
214
+ return {};
219
215
  }
220
216
  async function loadTsConfig(path) {
221
- try {
222
- const { bundleRequire } = await import("bundle-require");
223
- const { mod } = await bundleRequire({ filepath: path });
224
- return mod.default ?? {};
225
- } catch (error) {
226
- if (isModuleNotFound(error, "esbuild")) {
227
- throw new Error(`[verbaly] ${path} needs esbuild \u2014 install it: pnpm add -D esbuild`, {
228
- cause: error
229
- });
230
- }
231
- throw error;
232
- }
217
+ try {
218
+ const { bundleRequire } = await import("bundle-require");
219
+ const { mod } = await bundleRequire({ filepath: path });
220
+ return mod.default ?? {};
221
+ } catch (error) {
222
+ if (isModuleNotFound(error, "esbuild")) throw new Error(`[verbaly] ${path} needs esbuild — install it: pnpm add -D esbuild`, { cause: error });
223
+ throw error;
224
+ }
233
225
  }
234
226
  function isModuleNotFound(error, name) {
235
- return error instanceof Error && error.code === "ERR_MODULE_NOT_FOUND" && error.message.includes(name);
227
+ return error instanceof Error && error.code === "ERR_MODULE_NOT_FOUND" && error.message.includes(name);
236
228
  }
237
229
  async function loadConfig(root, overrides = {}) {
238
- const fileConfig = await loadConfigFile(root);
239
- return resolveConfig({ ...fileConfig, ...definedOnly(overrides), root });
230
+ return resolveConfig({
231
+ ...await loadConfigFile(root),
232
+ ...definedOnly(overrides),
233
+ root
234
+ });
240
235
  }
241
236
  function definedOnly(config) {
242
- return Object.fromEntries(
243
- Object.entries(config).filter(([, value]) => value !== void 0)
244
- );
237
+ return Object.fromEntries(Object.entries(config).filter(([, value]) => value !== void 0));
245
238
  }
246
-
247
- // src/extract.ts
248
- import { readFileSync as readFileSync3 } from "fs";
249
- import { glob } from "tinyglobby";
250
-
251
- // src/analyze.ts
252
- import { parse as parse2 } from "@babel/parser";
253
-
254
- // src/key.ts
255
- import { createHash } from "crypto";
239
+ //#endregion
240
+ //#region src/key.ts
256
241
  function stableKey(message) {
257
- return createHash("sha256").update(message).digest("base64url").slice(0, 8);
242
+ return createHash("sha256").update(message).digest("base64url").slice(0, 8);
258
243
  }
259
-
260
- // src/analyze.ts
261
- var SKIP_KEYS = /* @__PURE__ */ new Set(["loc", "leadingComments", "trailingComments", "innerComments", "extra"]);
244
+ //#endregion
245
+ //#region src/analyze.ts
246
+ const SKIP_KEYS = /* @__PURE__ */ new Set([
247
+ "loc",
248
+ "leadingComments",
249
+ "trailingComments",
250
+ "innerComments",
251
+ "extra"
252
+ ]);
262
253
  function analyze(code, file) {
263
- const jsx = /\.[jt]sx$/.test(file);
264
- const ast = parse2(code, {
265
- sourceType: "module",
266
- errorRecovery: true,
267
- plugins: jsx ? ["typescript", "jsx"] : ["typescript"]
268
- });
269
- const tagged = [];
270
- const usedKeys = [];
271
- walk(ast.program, (node) => {
272
- if (node.type === "TaggedTemplateExpression") {
273
- const tag = node.tag;
274
- const explicit = explicitId(tag);
275
- if (!explicit && !isTReference(tag)) return;
276
- const quasi = node.quasi;
277
- const message = buildMessage(code, quasi);
278
- if (!message) return;
279
- tagged.push({
280
- key: explicit ? explicit.key : stableKey(message.text),
281
- message: message.text,
282
- params: message.params,
283
- start: node.start,
284
- end: node.end,
285
- tagStart: explicit ? explicit.refStart : tag.start,
286
- tagEnd: explicit ? explicit.refEnd : tag.end,
287
- file
288
- });
289
- } else if (node.type === "CallExpression") {
290
- const callee = node.callee;
291
- if (!isTReference(callee)) return;
292
- const args = node.arguments;
293
- const first = args[0];
294
- if (first?.type === "StringLiteral") {
295
- usedKeys.push({ key: first.value, file });
296
- }
297
- } else if (node.type === "JSXElement") {
298
- handleTrans(code, node, file, tagged, usedKeys);
299
- }
300
- });
301
- return { tagged, usedKeys };
254
+ const ast = parse$1(code, {
255
+ sourceType: "module",
256
+ errorRecovery: true,
257
+ plugins: /\.[jt]sx$/.test(file) ? ["typescript", "jsx"] : ["typescript"]
258
+ });
259
+ const tagged = [];
260
+ const usedKeys = [];
261
+ walk(ast.program, (node) => {
262
+ if (node.type === "TaggedTemplateExpression") {
263
+ const tag = node.tag;
264
+ const explicit = explicitId(tag);
265
+ if (!explicit && !isTReference(tag)) return;
266
+ const quasi = node.quasi;
267
+ const message = buildMessage(code, quasi);
268
+ if (!message) return;
269
+ tagged.push({
270
+ key: explicit ? explicit.key : stableKey(message.text),
271
+ message: message.text,
272
+ params: message.params,
273
+ start: node.start,
274
+ end: node.end,
275
+ tagStart: explicit ? explicit.refStart : tag.start,
276
+ tagEnd: explicit ? explicit.refEnd : tag.end,
277
+ file
278
+ });
279
+ } else if (node.type === "CallExpression") {
280
+ const callee = node.callee;
281
+ if (!isTReference(callee)) return;
282
+ const first = node.arguments[0];
283
+ if (first?.type === "StringLiteral") usedKeys.push({
284
+ key: first.value,
285
+ file
286
+ });
287
+ } else if (node.type === "JSXElement") handleTrans(code, node, file, tagged, usedKeys);
288
+ });
289
+ return {
290
+ tagged,
291
+ usedKeys
292
+ };
302
293
  }
303
294
  function handleTrans(code, node, file, tagged, usedKeys) {
304
- const opening = node.openingElement;
305
- const nameNode = opening.name;
306
- if (nameNode.type !== "JSXIdentifier" || nameNode.name !== "Trans") return;
307
- const attrs = opening.attributes;
308
- const idAttr = attrs.find((a) => a.type === "JSXAttribute" && a.name.name === "id");
309
- const children = node.children;
310
- if (idAttr) {
311
- const value = idAttr.value;
312
- if (value?.type !== "StringLiteral") return;
313
- const id = value.value;
314
- if (attrs.length === 1 && children?.length) {
315
- const built2 = buildTransMessage(code, children);
316
- if (built2?.text.trim()) {
317
- tagged.push({
318
- key: id,
319
- message: built2.text,
320
- params: built2.params,
321
- start: node.start,
322
- end: node.end,
323
- tagStart: nameNode.start,
324
- tagEnd: nameNode.end,
325
- file,
326
- jsx: { name: nameNode.name, components: built2.components }
327
- });
328
- return;
329
- }
330
- }
331
- usedKeys.push({ key: id, file });
332
- return;
333
- }
334
- if (attrs.length > 0) return;
335
- if (!children?.length) return;
336
- const built = buildTransMessage(code, children);
337
- if (!built || !built.text.trim()) return;
338
- tagged.push({
339
- key: stableKey(built.text),
340
- message: built.text,
341
- params: built.params,
342
- start: node.start,
343
- end: node.end,
344
- tagStart: nameNode.start,
345
- tagEnd: nameNode.end,
346
- file,
347
- jsx: { name: nameNode.name, components: built.components }
348
- });
295
+ const opening = node.openingElement;
296
+ const nameNode = opening.name;
297
+ if (nameNode.type !== "JSXIdentifier" || nameNode.name !== "Trans") return;
298
+ const attrs = opening.attributes;
299
+ const idAttr = attrs.find((a) => a.type === "JSXAttribute" && a.name.name === "id");
300
+ const children = node.children;
301
+ if (idAttr) {
302
+ const value = idAttr.value;
303
+ if (value?.type !== "StringLiteral") return;
304
+ const id = value.value;
305
+ if (attrs.length === 1 && children?.length) {
306
+ const built = buildTransMessage(code, children);
307
+ if (built?.text.trim()) {
308
+ tagged.push({
309
+ key: id,
310
+ message: built.text,
311
+ params: built.params,
312
+ start: node.start,
313
+ end: node.end,
314
+ tagStart: nameNode.start,
315
+ tagEnd: nameNode.end,
316
+ file,
317
+ jsx: {
318
+ name: nameNode.name,
319
+ components: built.components
320
+ }
321
+ });
322
+ return;
323
+ }
324
+ }
325
+ usedKeys.push({
326
+ key: id,
327
+ file
328
+ });
329
+ return;
330
+ }
331
+ if (attrs.length > 0) return;
332
+ if (!children?.length) return;
333
+ const built = buildTransMessage(code, children);
334
+ if (!built || !built.text.trim()) return;
335
+ tagged.push({
336
+ key: stableKey(built.text),
337
+ message: built.text,
338
+ params: built.params,
339
+ start: node.start,
340
+ end: node.end,
341
+ tagStart: nameNode.start,
342
+ tagEnd: nameNode.end,
343
+ file,
344
+ jsx: {
345
+ name: nameNode.name,
346
+ components: built.components
347
+ }
348
+ });
349
349
  }
350
350
  function explicitId(tag) {
351
- if (tag.type !== "CallExpression") return void 0;
352
- const callee = tag.callee;
353
- if (callee.type !== "MemberExpression" || callee.computed) return void 0;
354
- const prop = callee.property;
355
- if (prop.type !== "Identifier" || prop.name !== "id") return void 0;
356
- const obj = callee.object;
357
- if (!isTReference(obj)) return void 0;
358
- const args = tag.arguments;
359
- const first = args[0];
360
- if (args.length !== 1 || first?.type !== "StringLiteral") return void 0;
361
- return { key: first.value, refStart: obj.start, refEnd: obj.end };
351
+ if (tag.type !== "CallExpression") return void 0;
352
+ const callee = tag.callee;
353
+ if (callee.type !== "MemberExpression" || callee.computed) return void 0;
354
+ const prop = callee.property;
355
+ if (prop.type !== "Identifier" || prop.name !== "id") return void 0;
356
+ const obj = callee.object;
357
+ if (!isTReference(obj)) return void 0;
358
+ const args = tag.arguments;
359
+ const first = args[0];
360
+ if (args.length !== 1 || first?.type !== "StringLiteral") return void 0;
361
+ return {
362
+ key: first.value,
363
+ refStart: obj.start,
364
+ refEnd: obj.end
365
+ };
362
366
  }
363
367
  function buildTransMessage(code, children) {
364
- const params = [];
365
- const components = [];
366
- const takenParams = /* @__PURE__ */ new Map();
367
- const takenTags = /* @__PURE__ */ new Map();
368
- function walkChildren(nodes) {
369
- let text2 = "";
370
- for (const child of nodes) {
371
- if (child.type === "JSXText") {
372
- text2 += escapeText(cleanJsxText(child.value));
373
- } else if (child.type === "JSXExpressionContainer") {
374
- const expr = child.expression;
375
- if (expr.type === "JSXEmptyExpression") continue;
376
- if (expr.type === "StringLiteral") {
377
- text2 += escapeText(expr.value);
378
- continue;
379
- }
380
- if (expr.type === "TaggedTemplateExpression") return void 0;
381
- const source = code.slice(expr.start, expr.end);
382
- const name = uniqueName(deriveName(expr, params.length), source, takenParams);
383
- params.push({ name, start: expr.start, end: expr.end });
384
- text2 += `{${name}}`;
385
- } else if (child.type === "JSXElement") {
386
- const opening = child.openingElement;
387
- const nameNode = opening.name;
388
- if (nameNode.type !== "JSXIdentifier" || nameNode.name === "Trans") return void 0;
389
- const source = selfClosedSource(code, opening);
390
- const tag = uniqueName(nameNode.name.toLowerCase(), source, takenTags);
391
- if (!components.some((c) => c.name === tag)) components.push({ name: tag, source });
392
- if (!child.closingElement) {
393
- text2 += `<${tag}/>`;
394
- } else {
395
- const inner = walkChildren(child.children);
396
- if (inner === void 0) return void 0;
397
- text2 += `<${tag}>${inner}</${tag}>`;
398
- }
399
- } else {
400
- return void 0;
401
- }
402
- }
403
- return text2;
404
- }
405
- const text = walkChildren(children);
406
- if (text === void 0) return void 0;
407
- return { text, params, components };
368
+ const params = [];
369
+ const components = [];
370
+ const takenParams = /* @__PURE__ */ new Map();
371
+ const takenTags = /* @__PURE__ */ new Map();
372
+ function walkChildren(nodes) {
373
+ let text = "";
374
+ for (const child of nodes) if (child.type === "JSXText") text += escapeText(cleanJsxText(child.value));
375
+ else if (child.type === "JSXExpressionContainer") {
376
+ const expr = child.expression;
377
+ if (expr.type === "JSXEmptyExpression") continue;
378
+ if (expr.type === "StringLiteral") {
379
+ text += escapeText(expr.value);
380
+ continue;
381
+ }
382
+ if (expr.type === "TaggedTemplateExpression") return void 0;
383
+ const source = code.slice(expr.start, expr.end);
384
+ const name = uniqueName(deriveName(expr, params.length), source, takenParams);
385
+ params.push({
386
+ name,
387
+ start: expr.start,
388
+ end: expr.end
389
+ });
390
+ text += `{${name}}`;
391
+ } else if (child.type === "JSXElement") {
392
+ const opening = child.openingElement;
393
+ const nameNode = opening.name;
394
+ if (nameNode.type !== "JSXIdentifier" || nameNode.name === "Trans") return void 0;
395
+ const source = selfClosedSource(code, opening);
396
+ const tag = uniqueName(nameNode.name.toLowerCase(), source, takenTags);
397
+ if (!components.some((c) => c.name === tag)) components.push({
398
+ name: tag,
399
+ source
400
+ });
401
+ if (!child.closingElement) text += `<${tag}/>`;
402
+ else {
403
+ const inner = walkChildren(child.children);
404
+ if (inner === void 0) return void 0;
405
+ text += `<${tag}>${inner}</${tag}>`;
406
+ }
407
+ } else return;
408
+ return text;
409
+ }
410
+ const text = walkChildren(children);
411
+ if (text === void 0) return void 0;
412
+ return {
413
+ text,
414
+ params,
415
+ components
416
+ };
408
417
  }
409
418
  function cleanJsxText(raw) {
410
- const lines = raw.split(/\r\n|[\r\n]/);
411
- let out = "";
412
- for (let i = 0; i < lines.length; i++) {
413
- let line = lines[i].replace(/\t/g, " ");
414
- if (i !== 0) line = line.replace(/^ +/, "");
415
- if (i !== lines.length - 1) line = line.replace(/ +$/, "");
416
- if (!line) continue;
417
- if (out && i !== 0) out += " ";
418
- out += line;
419
- }
420
- return out;
419
+ const lines = raw.split(/\r\n|[\r\n]/);
420
+ let out = "";
421
+ for (let i = 0; i < lines.length; i++) {
422
+ let line = lines[i].replace(/\t/g, " ");
423
+ if (i !== 0) line = line.replace(/^ +/, "");
424
+ if (i !== lines.length - 1) line = line.replace(/ +$/, "");
425
+ if (!line) continue;
426
+ if (out && i !== 0) out += " ";
427
+ out += line;
428
+ }
429
+ return out;
421
430
  }
422
431
  function selfClosedSource(code, opening) {
423
- const src = code.slice(opening.start, opening.end);
424
- return src.endsWith("/>") ? src : `${src.slice(0, -1).trimEnd()} />`;
432
+ const src = code.slice(opening.start, opening.end);
433
+ return src.endsWith("/>") ? src : `${src.slice(0, -1).trimEnd()} />`;
425
434
  }
426
435
  function isTReference(node) {
427
- if (node.type === "Identifier") return node.name === "t";
428
- if (node.type === "MemberExpression" && !node.computed) {
429
- const prop = node.property;
430
- return prop.type === "Identifier" && prop.name === "t";
431
- }
432
- return false;
436
+ if (node.type === "Identifier") return node.name === "t";
437
+ if (node.type === "MemberExpression" && !node.computed) {
438
+ const prop = node.property;
439
+ return prop.type === "Identifier" && prop.name === "t";
440
+ }
441
+ return false;
433
442
  }
434
443
  function buildMessage(code, quasi) {
435
- const quasis = quasi.quasis;
436
- const expressions = quasi.expressions;
437
- const params = [];
438
- const taken = /* @__PURE__ */ new Map();
439
- let text = escapeText(cookedValue(quasis[0]));
440
- for (let i = 0; i < expressions.length; i++) {
441
- const expr = expressions[i];
442
- if (!expr) return void 0;
443
- const source = code.slice(expr.start, expr.end);
444
- const name = uniqueName(deriveName(expr, i), source, taken);
445
- params.push({ name, start: expr.start, end: expr.end });
446
- text += `{${name}}` + escapeText(cookedValue(quasis[i + 1]));
447
- }
448
- return { text, params };
444
+ const quasis = quasi.quasis;
445
+ const expressions = quasi.expressions;
446
+ const params = [];
447
+ const taken = /* @__PURE__ */ new Map();
448
+ let text = escapeText(cookedValue(quasis[0]));
449
+ for (let i = 0; i < expressions.length; i++) {
450
+ const expr = expressions[i];
451
+ if (!expr) return void 0;
452
+ const source = code.slice(expr.start, expr.end);
453
+ const name = uniqueName(deriveName(expr, i), source, taken);
454
+ params.push({
455
+ name,
456
+ start: expr.start,
457
+ end: expr.end
458
+ });
459
+ text += `{${name}}` + escapeText(cookedValue(quasis[i + 1]));
460
+ }
461
+ return {
462
+ text,
463
+ params
464
+ };
449
465
  }
450
466
  function cookedValue(element) {
451
- if (!element) return "";
452
- const value = element.value;
453
- return value.cooked ?? value.raw;
467
+ if (!element) return "";
468
+ const value = element.value;
469
+ return value.cooked ?? value.raw;
454
470
  }
455
471
  function escapeText(text) {
456
- return text.replace(/[{}]/g, (m) => m + m);
472
+ return text.replace(/[{}]/g, (m) => m + m);
457
473
  }
458
474
  function deriveName(expr, index) {
459
- if (expr.type === "Identifier") return expr.name;
460
- if (expr.type === "MemberExpression" && !expr.computed) {
461
- const prop = expr.property;
462
- if (prop.type === "Identifier") return prop.name;
463
- }
464
- return `_${index}`;
475
+ if (expr.type === "Identifier") return expr.name;
476
+ if (expr.type === "MemberExpression" && !expr.computed) {
477
+ const prop = expr.property;
478
+ if (prop.type === "Identifier") return prop.name;
479
+ }
480
+ return `_${index}`;
465
481
  }
466
482
  function uniqueName(base, source, taken) {
467
- let name = base;
468
- let n = 2;
469
- while (taken.has(name) && taken.get(name) !== source) {
470
- name = `${base}${n}`;
471
- n += 1;
472
- }
473
- taken.set(name, source);
474
- return name;
483
+ let name = base;
484
+ let n = 2;
485
+ while (taken.has(name) && taken.get(name) !== source) {
486
+ name = `${base}${n}`;
487
+ n += 1;
488
+ }
489
+ taken.set(name, source);
490
+ return name;
475
491
  }
476
- function walk(node, visit2) {
477
- visit2(node);
478
- for (const [key, value] of Object.entries(node)) {
479
- if (SKIP_KEYS.has(key)) continue;
480
- if (Array.isArray(value)) {
481
- for (const item of value) {
482
- if (isNode(item)) walk(item, visit2);
483
- }
484
- } else if (isNode(value)) {
485
- walk(value, visit2);
486
- }
487
- }
492
+ function walk(node, visit) {
493
+ visit(node);
494
+ for (const [key, value] of Object.entries(node)) {
495
+ if (SKIP_KEYS.has(key)) continue;
496
+ if (Array.isArray(value)) {
497
+ for (const item of value) if (isNode(item)) walk(item, visit);
498
+ } else if (isNode(value)) walk(value, visit);
499
+ }
488
500
  }
489
501
  function isNode(value) {
490
- return typeof value === "object" && value !== null && typeof value.type === "string";
502
+ return typeof value === "object" && value !== null && typeof value.type === "string";
491
503
  }
492
-
493
- // src/registry.ts
504
+ //#endregion
505
+ //#region src/registry.ts
494
506
  var MessageRegistry = class {
495
- files = /* @__PURE__ */ new Map();
496
- update(file, analysis) {
497
- this.files.set(file, analysis);
498
- }
499
- remove(file) {
500
- this.files.delete(file);
501
- }
502
- messages() {
503
- const out = /* @__PURE__ */ new Map();
504
- for (const analysis of this.files.values()) {
505
- for (const msg of analysis.tagged) {
506
- const existing = out.get(msg.key);
507
- if (existing) {
508
- if (existing.message !== msg.message) {
509
- console.warn(
510
- `[verbaly] key collision "${msg.key}": ${JSON.stringify(existing.message)} vs ${JSON.stringify(msg.message)} \u2014 second dropped.`
511
- );
512
- }
513
- continue;
514
- }
515
- out.set(msg.key, msg);
516
- }
517
- }
518
- return out;
519
- }
520
- usedKeys() {
521
- const out = /* @__PURE__ */ new Map();
522
- for (const analysis of this.files.values()) {
523
- for (const used of analysis.usedKeys) {
524
- const files = out.get(used.key) ?? [];
525
- if (!files.includes(used.file)) files.push(used.file);
526
- out.set(used.key, files);
527
- }
528
- }
529
- return out;
530
- }
507
+ files = /* @__PURE__ */ new Map();
508
+ update(file, analysis) {
509
+ this.files.set(file, analysis);
510
+ }
511
+ remove(file) {
512
+ this.files.delete(file);
513
+ }
514
+ messages() {
515
+ const out = /* @__PURE__ */ new Map();
516
+ for (const analysis of this.files.values()) for (const msg of analysis.tagged) {
517
+ const existing = out.get(msg.key);
518
+ if (existing) {
519
+ if (existing.message !== msg.message) console.warn(`[verbaly] key collision "${msg.key}": ${JSON.stringify(existing.message)} vs ${JSON.stringify(msg.message)} — second dropped.`);
520
+ continue;
521
+ }
522
+ out.set(msg.key, msg);
523
+ }
524
+ return out;
525
+ }
526
+ usedKeys() {
527
+ const out = /* @__PURE__ */ new Map();
528
+ for (const analysis of this.files.values()) for (const used of analysis.usedKeys) {
529
+ const files = out.get(used.key) ?? [];
530
+ if (!files.includes(used.file)) files.push(used.file);
531
+ out.set(used.key, files);
532
+ }
533
+ return out;
534
+ }
531
535
  };
532
-
533
- // src/extract.ts
536
+ //#endregion
537
+ //#region src/extract.ts
534
538
  async function extractProject(cfg) {
535
- const files = await glob(cfg.include, {
536
- cwd: cfg.root,
537
- ignore: cfg.exclude,
538
- absolute: true
539
- });
540
- const registry = new MessageRegistry();
541
- for (const file of files) {
542
- registry.update(file, analyze(readFileSync3(file, "utf8"), file));
543
- }
544
- return registry;
539
+ const files = await glob(cfg.include, {
540
+ cwd: cfg.root,
541
+ ignore: cfg.exclude,
542
+ absolute: true
543
+ });
544
+ const registry = new MessageRegistry();
545
+ for (const file of files) registry.update(file, analyze(readFileSync(file, "utf8"), file));
546
+ return registry;
545
547
  }
546
548
  function syncCatalogs(cfg, catalogs, registry) {
547
- const added = {};
548
- const source = catalogs[cfg.sourceLocale] ??= {};
549
- for (const [key, msg] of registry.messages()) {
550
- if (source[key] !== msg.message) {
551
- source[key] = msg.message;
552
- (added[cfg.sourceLocale] ??= []).push(key);
553
- }
554
- }
555
- const needed = Object.keys(source);
556
- for (const locale of cfg.locales) {
557
- if (locale === cfg.sourceLocale) continue;
558
- const catalog = catalogs[locale] ??= {};
559
- for (const key of needed) {
560
- if (catalog[key] === void 0) {
561
- catalog[key] = "";
562
- (added[locale] ??= []).push(key);
563
- }
564
- }
565
- }
566
- return { added };
549
+ const added = {};
550
+ const source = catalogs[cfg.sourceLocale] ??= {};
551
+ for (const [key, msg] of registry.messages()) if (source[key] !== msg.message) {
552
+ source[key] = msg.message;
553
+ (added[cfg.sourceLocale] ??= []).push(key);
554
+ }
555
+ const needed = Object.keys(source);
556
+ for (const locale of cfg.locales) {
557
+ if (locale === cfg.sourceLocale) continue;
558
+ const catalog = catalogs[locale] ??= {};
559
+ for (const key of needed) if (catalog[key] === void 0) {
560
+ catalog[key] = "";
561
+ (added[locale] ??= []).push(key);
562
+ }
563
+ }
564
+ return { added };
567
565
  }
568
566
  function pruneCatalogs(cfg, catalogs, registry) {
569
- const keep = /* @__PURE__ */ new Set([...registry.messages().keys(), ...registry.usedKeys().keys()]);
570
- const removed = {};
571
- for (const locale of cfg.locales) {
572
- const catalog = catalogs[locale];
573
- if (!catalog) continue;
574
- for (const key of Object.keys(catalog)) {
575
- if (!keep.has(key)) {
576
- delete catalog[key];
577
- (removed[locale] ??= []).push(key);
578
- }
579
- }
580
- }
581
- return removed;
567
+ const keep = /* @__PURE__ */ new Set([...registry.messages().keys(), ...registry.usedKeys().keys()]);
568
+ const removed = {};
569
+ for (const locale of cfg.locales) {
570
+ const catalog = catalogs[locale];
571
+ if (!catalog) continue;
572
+ for (const key of Object.keys(catalog)) if (!keep.has(key)) {
573
+ delete catalog[key];
574
+ (removed[locale] ??= []).push(key);
575
+ }
576
+ }
577
+ return removed;
582
578
  }
583
-
584
- // src/pseudo.ts
585
- var PSEUDO_LOCALE = "en-XA";
586
- var ACCENTS = {
587
- a: "\xE1",
588
- b: "\u0180",
589
- c: "\xE7",
590
- d: "\u0111",
591
- e: "\xE9",
592
- f: "\u0192",
593
- g: "\u011F",
594
- h: "\u0125",
595
- i: "\xED",
596
- j: "\u0135",
597
- k: "\u0137",
598
- l: "\u013A",
599
- m: "\u0271",
600
- n: "\xF1",
601
- o: "\xF3",
602
- p: "\xFE",
603
- q: "\u01EB",
604
- r: "\u0155",
605
- s: "\u0161",
606
- t: "\u0163",
607
- u: "\xFA",
608
- v: "\u1E7D",
609
- w: "\u0175",
610
- x: "\u1E8B",
611
- y: "\xFD",
612
- z: "\u017E",
613
- A: "\xC1",
614
- B: "\u0181",
615
- C: "\xC7",
616
- D: "\u0110",
617
- E: "\xC9",
618
- F: "\u0191",
619
- G: "\u011E",
620
- H: "\u0124",
621
- I: "\xCD",
622
- J: "\u0134",
623
- K: "\u0136",
624
- L: "\u0139",
625
- M: "\u1E3E",
626
- N: "\xD1",
627
- O: "\xD3",
628
- P: "\xDE",
629
- Q: "\u01EA",
630
- R: "\u0154",
631
- S: "\u0160",
632
- T: "\u0162",
633
- U: "\xDA",
634
- V: "\u1E7C",
635
- W: "\u0174",
636
- X: "\u1E8C",
637
- Y: "\xDD",
638
- Z: "\u017D"
579
+ //#endregion
580
+ //#region src/init.ts
581
+ const CONFIG_NAMES = [
582
+ "verbaly.config.js",
583
+ "verbaly.config.mjs",
584
+ "verbaly.config.ts",
585
+ "verbaly.config.mts",
586
+ "verbaly.config.json"
587
+ ];
588
+ const BUNDLERS = [
589
+ "vite",
590
+ "webpack",
591
+ "rollup",
592
+ "rspack",
593
+ "esbuild"
594
+ ];
595
+ function detectBundler(root) {
596
+ const path = join(root, "package.json");
597
+ if (!existsSync(path)) return void 0;
598
+ try {
599
+ const pkg = JSON.parse(readFileSync(path, "utf8"));
600
+ const deps = {
601
+ ...pkg.dependencies,
602
+ ...pkg.devDependencies
603
+ };
604
+ return BUNDLERS.find((name) => deps[name]);
605
+ } catch {
606
+ return;
607
+ }
608
+ }
609
+ function configSource(options, typescript) {
610
+ const fields = [` sourceLocale: '${options.sourceLocale ?? "en"}',`];
611
+ if (options.locales?.length) fields.push(` locales: [${options.locales.map((l) => `'${l}'`).join(", ")}],`);
612
+ if (options.dir) fields.push(` dir: '${options.dir}',`);
613
+ const body = `export default {\n${fields.join("\n")}\n}`;
614
+ if (typescript) return `import type { VerbalyConfig } from '@verbaly/compiler';\n\n${body} satisfies VerbalyConfig;\n`;
615
+ return `/** @type {import('@verbaly/compiler').VerbalyConfig} */\n${body};\n`;
616
+ }
617
+ function init(options = {}) {
618
+ const root = options.root ?? process.cwd();
619
+ const created = [];
620
+ const skipped = [];
621
+ const existing = CONFIG_NAMES.find((name) => existsSync(join(root, name)));
622
+ const typescript = existsSync(join(root, "tsconfig.json"));
623
+ const configFile = existing ?? (typescript ? "verbaly.config.ts" : "verbaly.config.mjs");
624
+ if (existing) skipped.push(existing);
625
+ else {
626
+ writeFileSync(join(root, configFile), configSource(options, typescript));
627
+ created.push(configFile);
628
+ }
629
+ const dir = join(root, options.dir ?? "locales");
630
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
631
+ for (const locale of /* @__PURE__ */ new Set([options.sourceLocale ?? "en", ...options.locales ?? []])) {
632
+ const file = join(dir, `${locale}.json`);
633
+ const label = relative(root, file).replaceAll("\\", "/");
634
+ if (existsSync(file)) skipped.push(label);
635
+ else {
636
+ writeFileSync(file, "{}\n");
637
+ created.push(label);
638
+ }
639
+ }
640
+ const bundler = detectBundler(root);
641
+ const next = [];
642
+ if (bundler === "vite") next.push("install the plugin: pnpm add -D @verbaly/vite", "add verbaly() to the plugins in vite.config");
643
+ else if (bundler) next.push("install the plugin: pnpm add -D @verbaly/unplugin", `add the verbaly ${bundler} plugin to your build config`);
644
+ else next.push("run \"verbaly extract\" after writing your first t`…` message");
645
+ return {
646
+ created,
647
+ skipped,
648
+ bundler,
649
+ configFile,
650
+ next
651
+ };
652
+ }
653
+ //#endregion
654
+ //#region src/pseudo.ts
655
+ const PSEUDO_LOCALE = "en-XA";
656
+ const ACCENTS = {
657
+ a: "á",
658
+ b: "ƀ",
659
+ c: "ç",
660
+ d: "đ",
661
+ e: "é",
662
+ f: "ƒ",
663
+ g: "ğ",
664
+ h: "ĥ",
665
+ i: "í",
666
+ j: "ĵ",
667
+ k: "ķ",
668
+ l: "ĺ",
669
+ m: "ɱ",
670
+ n: "ñ",
671
+ o: "ó",
672
+ p: "þ",
673
+ q: "ǫ",
674
+ r: "ŕ",
675
+ s: "š",
676
+ t: "ţ",
677
+ u: "ú",
678
+ v: "ṽ",
679
+ w: "ŵ",
680
+ x: "ẋ",
681
+ y: "ý",
682
+ z: "ž",
683
+ A: "Á",
684
+ B: "Ɓ",
685
+ C: "Ç",
686
+ D: "Đ",
687
+ E: "É",
688
+ F: "Ƒ",
689
+ G: "Ğ",
690
+ H: "Ĥ",
691
+ I: "Í",
692
+ J: "Ĵ",
693
+ K: "Ķ",
694
+ L: "Ĺ",
695
+ M: "Ḿ",
696
+ N: "Ñ",
697
+ O: "Ó",
698
+ P: "Þ",
699
+ Q: "Ǫ",
700
+ R: "Ŕ",
701
+ S: "Š",
702
+ T: "Ţ",
703
+ U: "Ú",
704
+ V: "Ṽ",
705
+ W: "Ŵ",
706
+ X: "Ẍ",
707
+ Y: "Ý",
708
+ Z: "Ž"
639
709
  };
640
- var TAG_AT = /<\/?[a-zA-Z][\w-]*\/?>/y;
710
+ const TAG_AT = /<\/?[a-zA-Z][\w-]*\/?>/y;
641
711
  function pseudoLocalize(message) {
642
- let out = "";
643
- let letters = 0;
644
- let i = 0;
645
- while (i < message.length) {
646
- const two = message.slice(i, i + 2);
647
- if (two === "{{" || two === "}}" || two === "||" || two === "##") {
648
- out += two;
649
- i += 2;
650
- continue;
651
- }
652
- const ch = message[i];
653
- if (ch === "{") {
654
- const end = matchBrace(message, i);
655
- out += message.slice(i, end);
656
- i = end;
657
- continue;
658
- }
659
- if (ch === "<") {
660
- TAG_AT.lastIndex = i;
661
- const m = TAG_AT.exec(message);
662
- if (m) {
663
- out += m[0];
664
- i += m[0].length;
665
- continue;
666
- }
667
- }
668
- const mapped = ACCENTS[ch];
669
- if (mapped) {
670
- out += mapped;
671
- letters += 1;
672
- } else {
673
- out += ch;
674
- }
675
- i += 1;
676
- }
677
- const pad = "~".repeat(Math.ceil(letters / 3));
678
- return `\u27E6${out}${pad ? " " + pad : ""}\u27E7`;
712
+ let out = "";
713
+ let letters = 0;
714
+ let i = 0;
715
+ while (i < message.length) {
716
+ const two = message.slice(i, i + 2);
717
+ if (two === "{{" || two === "}}" || two === "||" || two === "##") {
718
+ out += two;
719
+ i += 2;
720
+ continue;
721
+ }
722
+ const ch = message[i];
723
+ if (ch === "{") {
724
+ const end = matchBrace(message, i);
725
+ out += message.slice(i, end);
726
+ i = end;
727
+ continue;
728
+ }
729
+ if (ch === "<") {
730
+ TAG_AT.lastIndex = i;
731
+ const m = TAG_AT.exec(message);
732
+ if (m) {
733
+ out += m[0];
734
+ i += m[0].length;
735
+ continue;
736
+ }
737
+ }
738
+ const mapped = ACCENTS[ch];
739
+ if (mapped) {
740
+ out += mapped;
741
+ letters += 1;
742
+ } else out += ch;
743
+ i += 1;
744
+ }
745
+ const pad = "~".repeat(Math.ceil(letters / 3));
746
+ return `⟦${out}${pad ? " " + pad : ""}⟧`;
679
747
  }
680
748
  function matchBrace(message, start) {
681
- let depth = 0;
682
- for (let i = start; i < message.length; i++) {
683
- const two = message.slice(i, i + 2);
684
- if (two === "{{" || two === "}}") {
685
- i += 1;
686
- continue;
687
- }
688
- const ch = message[i];
689
- if (ch === "{") depth += 1;
690
- else if (ch === "}") {
691
- depth -= 1;
692
- if (depth === 0) return i + 1;
693
- }
694
- }
695
- return message.length;
749
+ let depth = 0;
750
+ for (let i = start; i < message.length; i++) {
751
+ const two = message.slice(i, i + 2);
752
+ if (two === "{{" || two === "}}") {
753
+ i += 1;
754
+ continue;
755
+ }
756
+ const ch = message[i];
757
+ if (ch === "{") depth += 1;
758
+ else if (ch === "}") {
759
+ depth -= 1;
760
+ if (depth === 0) return i + 1;
761
+ }
762
+ }
763
+ return message.length;
696
764
  }
697
765
  function pseudoCatalogs(cfg, catalogs, locale = PSEUDO_LOCALE) {
698
- const source = catalogs[cfg.sourceLocale] ?? {};
699
- const target = {};
700
- for (const [key, msg] of Object.entries(source)) {
701
- target[key] = msg ? pseudoLocalize(msg) : "";
702
- }
703
- catalogs[locale] = target;
704
- return Object.keys(target).filter((key) => target[key]);
766
+ const source = catalogs[cfg.sourceLocale] ?? {};
767
+ const target = {};
768
+ for (const [key, msg] of Object.entries(source)) target[key] = msg ? pseudoLocalize(msg) : "";
769
+ catalogs[locale] = target;
770
+ return Object.keys(target).filter((key) => target[key]);
705
771
  }
706
-
707
- // src/render.ts
708
- import { mkdirSync as mkdirSync2, readFileSync as readFileSync4, writeFileSync as writeFileSync3 } from "fs";
709
- import { dirname, join as join4, relative } from "path";
710
- import MagicString from "magic-string";
711
- import { glob as glob2 } from "tinyglobby";
712
- import {
713
- createVerbaly,
714
- parseTags,
715
- RICH_TAGS,
716
- safeHref
717
- } from "verbaly";
718
- var VOID_TAGS = /* @__PURE__ */ new Set([
719
- "area",
720
- "base",
721
- "br",
722
- "col",
723
- "embed",
724
- "hr",
725
- "img",
726
- "input",
727
- "link",
728
- "meta",
729
- "param",
730
- "source",
731
- "track",
732
- "wbr"
772
+ //#endregion
773
+ //#region src/render.ts
774
+ const VOID_TAGS = /* @__PURE__ */ new Set([
775
+ "area",
776
+ "base",
777
+ "br",
778
+ "col",
779
+ "embed",
780
+ "hr",
781
+ "img",
782
+ "input",
783
+ "link",
784
+ "meta",
785
+ "param",
786
+ "source",
787
+ "track",
788
+ "wbr"
733
789
  ]);
734
- var START_TAG = /<([a-zA-Z][a-zA-Z0-9-]*)((?:"[^"]*"|'[^']*'|[^"'>])*)>/g;
735
- var ATTR = /([^\s=/"'<>]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+)))?/g;
790
+ const START_TAG = /<([a-zA-Z][a-zA-Z0-9-]*)((?:"[^"]*"|'[^']*'|[^"'>])*)>/g;
791
+ const ATTR = /([^\s=/"'<>]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+)))?/g;
736
792
  function renderHtml(html, options) {
737
- const attr = options.attribute ?? "data-verbaly";
738
- const argsAttr = `${attr}-args`;
739
- const attrsAttr = `${attr}-attr`;
740
- const richAttr = `${attr}-rich`;
741
- const linksAttr = `${attr}-links`;
742
- const richTags = new Set(options.richTags ?? RICH_TAGS);
743
- const globalLinks = options.richLinks;
744
- const sourceLocale = options.sourceLocale ?? "en";
745
- const messages = {};
746
- for (const [locale, catalog] of Object.entries(options.catalogs)) {
747
- const clean = {};
748
- for (const [key, msg] of Object.entries(catalog)) if (msg) clean[key] = msg;
749
- messages[locale] = clean;
750
- }
751
- const v = createVerbaly({ locale: options.locale, fallback: sourceLocale, messages });
752
- const t = v.t;
753
- const ms = new MagicString(html);
754
- const missing = /* @__PURE__ */ new Set();
755
- const skip = protectedRanges(html);
756
- const inSkip = (index) => skip.some(([from, to]) => index >= from && index < to);
757
- START_TAG.lastIndex = 0;
758
- let m;
759
- while ((m = START_TAG.exec(html)) !== null) {
760
- if (inSkip(m.index)) continue;
761
- const [full, rawName, attrChunk] = m;
762
- const tagName = rawName.toLowerCase();
763
- const openEnd = m.index + full.length;
764
- const chunkStart = m.index + 1 + rawName.length;
765
- if (tagName === "html" && options.setLang !== false) {
766
- setAttribute(ms, html, chunkStart, openEnd, attrChunk, "lang", options.locale);
767
- continue;
768
- }
769
- const attrs = parseAttrs(attrChunk);
770
- const key = attrs.get(attr);
771
- const attrMapRaw = attrs.get(attrsAttr);
772
- if (key === void 0 && attrMapRaw === void 0) continue;
773
- const args = parseArgs(attrs.get(argsAttr));
774
- if (key) {
775
- if (!v.has(key)) {
776
- missing.add(key);
777
- } else if (!VOID_TAGS.has(tagName) && !attrChunk.trimEnd().endsWith("/")) {
778
- const close = findClose(html, tagName, openEnd, inSkip);
779
- if (close) {
780
- const text = t(key, args);
781
- const own = parseArgs(attrs.get(linksAttr));
782
- const links = own ? globalLinks ? { ...globalLinks, ...own } : own : globalLinks;
783
- const content = attrs.has(richAttr) ? richToHtml(parseTags(text), richTags, links) : escapeHtml(text);
784
- if (html.slice(openEnd, close.contentEnd) !== content) {
785
- if (openEnd === close.contentEnd) ms.appendLeft(openEnd, content);
786
- else ms.overwrite(openEnd, close.contentEnd, content);
787
- }
788
- }
789
- }
790
- }
791
- if (attrMapRaw !== void 0) {
792
- const map = parseArgs(attrMapRaw);
793
- if (map) {
794
- for (const [name, attrKey] of Object.entries(map)) {
795
- if (typeof attrKey !== "string" || name.toLowerCase().startsWith("on")) continue;
796
- if (!v.has(attrKey)) {
797
- missing.add(attrKey);
798
- continue;
799
- }
800
- setAttribute(ms, html, chunkStart, openEnd, attrChunk, name, t(attrKey, args));
801
- }
802
- }
803
- }
804
- }
805
- return { html: ms.toString(), missing: [...missing] };
793
+ const attr = options.attribute ?? "data-verbaly";
794
+ const argsAttr = `${attr}-args`;
795
+ const attrsAttr = `${attr}-attr`;
796
+ const richAttr = `${attr}-rich`;
797
+ const linksAttr = `${attr}-links`;
798
+ const richTags = new Set(options.richTags ?? RICH_TAGS);
799
+ const globalLinks = options.richLinks;
800
+ const sourceLocale = options.sourceLocale ?? "en";
801
+ const messages = {};
802
+ for (const [locale, catalog] of Object.entries(options.catalogs)) {
803
+ const clean = {};
804
+ for (const [key, msg] of Object.entries(catalog)) if (msg) clean[key] = msg;
805
+ messages[locale] = clean;
806
+ }
807
+ const v = createVerbaly({
808
+ locale: options.locale,
809
+ fallback: sourceLocale,
810
+ messages
811
+ });
812
+ const t = v.t;
813
+ const ms = new MagicString(html);
814
+ const missing = /* @__PURE__ */ new Set();
815
+ const skip = protectedRanges(html);
816
+ const inSkip = (index) => skip.some(([from, to]) => index >= from && index < to);
817
+ START_TAG.lastIndex = 0;
818
+ let m;
819
+ while ((m = START_TAG.exec(html)) !== null) {
820
+ if (inSkip(m.index)) continue;
821
+ const [full, rawName, attrChunk] = m;
822
+ const tagName = rawName.toLowerCase();
823
+ const openEnd = m.index + full.length;
824
+ const chunkStart = m.index + 1 + rawName.length;
825
+ if (tagName === "html" && options.setLang !== false) {
826
+ setAttribute(ms, html, chunkStart, openEnd, attrChunk, "lang", options.locale);
827
+ continue;
828
+ }
829
+ const attrs = parseAttrs(attrChunk);
830
+ const key = attrs.get(attr);
831
+ const attrMapRaw = attrs.get(attrsAttr);
832
+ if (key === void 0 && attrMapRaw === void 0) continue;
833
+ const args = parseArgs$1(attrs.get(argsAttr));
834
+ if (key) {
835
+ if (!v.has(key)) missing.add(key);
836
+ else if (!VOID_TAGS.has(tagName) && !attrChunk.trimEnd().endsWith("/")) {
837
+ const close = findClose(html, tagName, openEnd, inSkip);
838
+ if (close) {
839
+ const text = t(key, args);
840
+ const own = parseArgs$1(attrs.get(linksAttr));
841
+ const links = own ? globalLinks ? {
842
+ ...globalLinks,
843
+ ...own
844
+ } : own : globalLinks;
845
+ const content = attrs.has(richAttr) ? richToHtml(parseTags(text), richTags, links) : escapeHtml(text);
846
+ if (html.slice(openEnd, close.contentEnd) !== content) if (openEnd === close.contentEnd) ms.appendLeft(openEnd, content);
847
+ else ms.overwrite(openEnd, close.contentEnd, content);
848
+ }
849
+ }
850
+ }
851
+ if (attrMapRaw !== void 0) {
852
+ const map = parseArgs$1(attrMapRaw);
853
+ if (map) for (const [name, attrKey] of Object.entries(map)) {
854
+ if (typeof attrKey !== "string" || name.toLowerCase().startsWith("on")) continue;
855
+ if (!v.has(attrKey)) {
856
+ missing.add(attrKey);
857
+ continue;
858
+ }
859
+ setAttribute(ms, html, chunkStart, openEnd, attrChunk, name, t(attrKey, args));
860
+ }
861
+ }
862
+ }
863
+ return {
864
+ html: ms.toString(),
865
+ missing: [...missing]
866
+ };
806
867
  }
807
868
  async function renderSite(cfg, options = {}) {
808
- const site = join4(cfg.root, options.site ?? "dist");
809
- const locales = options.locales ?? cfg.locales;
810
- const catalogs = loadCatalogs(cfg);
811
- const files = await glob2("**/*.html", {
812
- cwd: site,
813
- absolute: true,
814
- ignore: locales.map((locale) => `${locale}/**`)
815
- });
816
- const missing = {};
817
- for (const file of files) {
818
- const html = readFileSync4(file, "utf8");
819
- const rel = relative(site, file);
820
- for (const locale of locales) {
821
- const result = renderHtml(html, {
822
- locale,
823
- catalogs,
824
- sourceLocale: cfg.sourceLocale,
825
- attribute: options.attribute,
826
- richTags: options.richTags,
827
- richLinks: options.richLinks ?? cfg.render.links
828
- });
829
- for (const key of result.missing) {
830
- const list = missing[locale] ??= [];
831
- if (!list.includes(key)) list.push(key);
832
- }
833
- const out = locale === cfg.sourceLocale ? file : join4(site, locale, rel);
834
- mkdirSync2(dirname(out), { recursive: true });
835
- writeFileSync3(out, result.html);
836
- }
837
- }
838
- return { files: files.length, locales: [...locales], missing };
869
+ const site = join(cfg.root, options.site ?? "dist");
870
+ const locales = options.locales ?? cfg.locales;
871
+ const catalogs = loadCatalogs(cfg);
872
+ const files = await glob("**/*.html", {
873
+ cwd: site,
874
+ absolute: true,
875
+ ignore: locales.map((locale) => `${locale}/**`)
876
+ });
877
+ const missing = {};
878
+ for (const file of files) {
879
+ const html = readFileSync(file, "utf8");
880
+ const rel = relative(site, file);
881
+ for (const locale of locales) {
882
+ const result = renderHtml(html, {
883
+ locale,
884
+ catalogs,
885
+ sourceLocale: cfg.sourceLocale,
886
+ attribute: options.attribute,
887
+ richTags: options.richTags,
888
+ richLinks: options.richLinks ?? cfg.render.links
889
+ });
890
+ for (const key of result.missing) {
891
+ const list = missing[locale] ??= [];
892
+ if (!list.includes(key)) list.push(key);
893
+ }
894
+ const out = locale === cfg.sourceLocale ? file : join(site, locale, rel);
895
+ mkdirSync(dirname(out), { recursive: true });
896
+ writeFileSync(out, result.html);
897
+ }
898
+ }
899
+ return {
900
+ files: files.length,
901
+ locales: [...locales],
902
+ missing
903
+ };
839
904
  }
840
905
  function parseAttrs(chunk) {
841
- const attrs = /* @__PURE__ */ new Map();
842
- ATTR.lastIndex = 0;
843
- let m;
844
- while ((m = ATTR.exec(chunk)) !== null) {
845
- attrs.set(m[1].toLowerCase(), m[2] ?? m[3] ?? m[4] ?? "");
846
- }
847
- return attrs;
906
+ const attrs = /* @__PURE__ */ new Map();
907
+ ATTR.lastIndex = 0;
908
+ let m;
909
+ while ((m = ATTR.exec(chunk)) !== null) attrs.set(m[1].toLowerCase(), m[2] ?? m[3] ?? m[4] ?? "");
910
+ return attrs;
848
911
  }
849
- function parseArgs(raw) {
850
- if (!raw) return void 0;
851
- try {
852
- return JSON.parse(decodeEntities(raw));
853
- } catch {
854
- console.warn(`[verbaly] invalid args JSON: ${raw}`);
855
- return void 0;
856
- }
912
+ function parseArgs$1(raw) {
913
+ if (!raw) return void 0;
914
+ try {
915
+ return JSON.parse(decodeEntities(raw));
916
+ } catch {
917
+ console.warn(`[verbaly] invalid args JSON: ${raw}`);
918
+ return;
919
+ }
857
920
  }
858
921
  function protectedRanges(html) {
859
- const ranges = [];
860
- const re = /<!--[\s\S]*?-->|<script\b[\s\S]*?<\/script\s*>|<style\b[\s\S]*?<\/style\s*>/gi;
861
- let m;
862
- while ((m = re.exec(html)) !== null) {
863
- const openEnd = m[0].startsWith("<!--") ? m.index : html.indexOf(">", m.index) + 1;
864
- ranges.push([openEnd, m.index + m[0].length]);
865
- }
866
- return ranges;
922
+ const ranges = [];
923
+ const re = /<!--[\s\S]*?-->|<script\b[\s\S]*?<\/script\s*>|<style\b[\s\S]*?<\/style\s*>/gi;
924
+ let m;
925
+ while ((m = re.exec(html)) !== null) {
926
+ const openEnd = m[0].startsWith("<!--") ? m.index : html.indexOf(">", m.index) + 1;
927
+ ranges.push([openEnd, m.index + m[0].length]);
928
+ }
929
+ return ranges;
867
930
  }
868
931
  function findClose(html, tagName, from, inSkip) {
869
- const re = new RegExp(
870
- `<${tagName}(?=[\\s/>])(?:"[^"]*"|'[^']*'|[^"'>])*>|</${tagName}\\s*>`,
871
- "gi"
872
- );
873
- re.lastIndex = from;
874
- let depth = 1;
875
- let m;
876
- while ((m = re.exec(html)) !== null) {
877
- if (inSkip(m.index)) continue;
878
- if (m[0][1] === "/") {
879
- depth -= 1;
880
- if (depth === 0) return { contentEnd: m.index };
881
- } else if (!m[0].endsWith("/>")) {
882
- depth += 1;
883
- }
884
- }
885
- return null;
932
+ const re = new RegExp(`<${tagName}(?=[\\s/>])(?:"[^"]*"|'[^']*'|[^"'>])*>|</${tagName}\\s*>`, "gi");
933
+ re.lastIndex = from;
934
+ let depth = 1;
935
+ let m;
936
+ while ((m = re.exec(html)) !== null) {
937
+ if (inSkip(m.index)) continue;
938
+ if (m[0][1] === "/") {
939
+ depth -= 1;
940
+ if (depth === 0) return { contentEnd: m.index };
941
+ } else if (!m[0].endsWith("/>")) depth += 1;
942
+ }
943
+ return null;
886
944
  }
887
945
  function setAttribute(ms, html, chunkStart, openEnd, attrChunk, name, value) {
888
- const escaped = escapeAttr(value);
889
- const existing = new RegExp(`(\\s${name}\\s*=\\s*)("[^"]*"|'[^']*'|[^\\s>]+)`, "i").exec(
890
- attrChunk
891
- );
892
- if (existing) {
893
- const valueStart = chunkStart + existing.index + existing[1].length;
894
- const valueEnd = valueStart + existing[2].length;
895
- if (html.slice(valueStart, valueEnd) !== `"${escaped}"`) {
896
- ms.overwrite(valueStart, valueEnd, `"${escaped}"`);
897
- }
898
- return;
899
- }
900
- const selfClosing = html.slice(openEnd - 2, openEnd) === "/>";
901
- const insertAt = openEnd - (selfClosing ? 2 : 1);
902
- ms.appendLeft(insertAt, ` ${name}="${escaped}"`);
946
+ const escaped = escapeAttr(value);
947
+ const existing = new RegExp(`(\\s${name}\\s*=\\s*)("[^"]*"|'[^']*'|[^\\s>]+)`, "i").exec(attrChunk);
948
+ if (existing) {
949
+ const valueStart = chunkStart + existing.index + existing[1].length;
950
+ const valueEnd = valueStart + existing[2].length;
951
+ if (html.slice(valueStart, valueEnd) !== `"${escaped}"`) ms.overwrite(valueStart, valueEnd, `"${escaped}"`);
952
+ return;
953
+ }
954
+ const insertAt = openEnd - (html.slice(openEnd - 2, openEnd) === "/>" ? 2 : 1);
955
+ ms.appendLeft(insertAt, ` ${name}="${escaped}"`);
903
956
  }
904
957
  function richToHtml(nodes, allowed, links) {
905
- let out = "";
906
- for (const node of nodes) {
907
- if (typeof node === "string") {
908
- out += escapeHtml(node);
909
- } else if (links?.[node.name] !== void 0) {
910
- const link = links[node.name];
911
- const { href, target, rel } = typeof link === "string" ? { href: link } : link;
912
- const safe = safeHref(href);
913
- let attrs = safe !== void 0 ? ` href="${escapeAttr(safe)}"` : "";
914
- if (target) attrs += ` target="${escapeAttr(target)}"`;
915
- if (rel) attrs += ` rel="${escapeAttr(rel)}"`;
916
- out += `<a${attrs}>${richToHtml(node.children, allowed, links)}</a>`;
917
- } else if (allowed.has(node.name)) {
918
- out += `<${node.name}>${richToHtml(node.children, allowed, links)}</${node.name}>`;
919
- } else {
920
- out += richToHtml(node.children, allowed, links);
921
- }
922
- }
923
- return out;
958
+ let out = "";
959
+ for (const node of nodes) if (typeof node === "string") out += escapeHtml(node);
960
+ else if (links?.[node.name] !== void 0) {
961
+ const link = links[node.name];
962
+ const { href, target, rel } = typeof link === "string" ? { href: link } : link;
963
+ const safe = safeHref(href);
964
+ let attrs = safe !== void 0 ? ` href="${escapeAttr(safe)}"` : "";
965
+ if (target) attrs += ` target="${escapeAttr(target)}"`;
966
+ if (rel) attrs += ` rel="${escapeAttr(rel)}"`;
967
+ out += `<a${attrs}>${richToHtml(node.children, allowed, links)}</a>`;
968
+ } else if (allowed.has(node.name)) out += `<${node.name}>${richToHtml(node.children, allowed, links)}</${node.name}>`;
969
+ else out += richToHtml(node.children, allowed, links);
970
+ return out;
924
971
  }
925
972
  function escapeHtml(text) {
926
- return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
973
+ return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
927
974
  }
928
975
  function escapeAttr(text) {
929
- return escapeHtml(text).replace(/"/g, "&quot;");
976
+ return escapeHtml(text).replace(/"/g, "&quot;");
930
977
  }
931
978
  function decodeEntities(text) {
932
- return text.replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&");
979
+ return text.replace(/&quot;/g, "\"").replace(/&#39;/g, "'").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&");
933
980
  }
934
-
935
- // src/translate.ts
981
+ //#endregion
982
+ //#region src/translate.ts
936
983
  async function translateCatalogs(cfg, catalogs, provider, options = {}) {
937
- const batchSize = options.batchSize ?? 20;
938
- const targets = (options.locales ?? cfg.locales).filter(
939
- (locale) => locale !== cfg.sourceLocale && cfg.locales.includes(locale)
940
- );
941
- const source = catalogs[cfg.sourceLocale] ?? {};
942
- const result = { translated: {}, invalid: {}, pending: {} };
943
- for (const locale of targets) {
944
- const catalog = catalogs[locale] ??= {};
945
- const missing = Object.keys(source).filter((key) => source[key] && !catalog[key]);
946
- if (missing.length === 0) continue;
947
- if (options.dryRun) {
948
- result.pending[locale] = missing;
949
- continue;
950
- }
951
- for (let i = 0; i < missing.length; i += batchSize) {
952
- const keys = missing.slice(i, i + batchSize);
953
- const messages = Object.fromEntries(keys.map((key) => [key, source[key]]));
954
- const out = await provider({
955
- sourceLocale: cfg.sourceLocale,
956
- targetLocale: locale,
957
- messages
958
- });
959
- for (const key of keys) {
960
- const text = out[key];
961
- if (typeof text === "string" && text.trim() && structureMatches(source[key], text)) {
962
- catalog[key] = text;
963
- (result.translated[locale] ??= []).push(key);
964
- } else {
965
- (result.invalid[locale] ??= []).push(key);
966
- }
967
- }
968
- }
969
- }
970
- return result;
984
+ const batchSize = options.batchSize ?? 20;
985
+ const targets = (options.locales ?? cfg.locales).filter((locale) => locale !== cfg.sourceLocale && cfg.locales.includes(locale));
986
+ const source = catalogs[cfg.sourceLocale] ?? {};
987
+ const result = {
988
+ translated: {},
989
+ invalid: {},
990
+ pending: {}
991
+ };
992
+ for (const locale of targets) {
993
+ const catalog = catalogs[locale] ??= {};
994
+ const missing = Object.keys(source).filter((key) => source[key] && !catalog[key]);
995
+ if (missing.length === 0) continue;
996
+ if (options.dryRun) {
997
+ result.pending[locale] = missing;
998
+ continue;
999
+ }
1000
+ for (let i = 0; i < missing.length; i += batchSize) {
1001
+ const keys = missing.slice(i, i + batchSize);
1002
+ const messages = Object.fromEntries(keys.map((key) => [key, source[key]]));
1003
+ const out = await provider({
1004
+ sourceLocale: cfg.sourceLocale,
1005
+ targetLocale: locale,
1006
+ messages
1007
+ });
1008
+ for (const key of keys) {
1009
+ const text = out[key];
1010
+ if (typeof text === "string" && text.trim() && structureMatches(source[key], text)) {
1011
+ catalog[key] = text;
1012
+ (result.translated[locale] ??= []).push(key);
1013
+ } else (result.invalid[locale] ??= []).push(key);
1014
+ }
1015
+ }
1016
+ }
1017
+ return result;
971
1018
  }
972
1019
  function structureMatches(source, translated) {
973
- return sameMembers(paramNames(source), paramNames(translated)) && sameMembers(tagTokens(source), tagTokens(translated));
1020
+ return sameMembers(paramNames(source), paramNames(translated)) && sameMembers(tagTokens(source), tagTokens(translated));
974
1021
  }
975
1022
  function paramNames(message) {
976
- try {
977
- return [...collectParams(message).keys()].sort();
978
- } catch {
979
- return ["\0invalid"];
980
- }
1023
+ try {
1024
+ return [...collectParams(message).keys()].sort();
1025
+ } catch {
1026
+ return ["\0invalid"];
1027
+ }
981
1028
  }
982
- var TAG = /<(\/?)([a-zA-Z][\w-]*)(\/?)>/g;
1029
+ const TAG = /<(\/?)([a-zA-Z][\w-]*)(\/?)>/g;
983
1030
  function tagTokens(message) {
984
- const out = [];
985
- for (const match of message.matchAll(TAG)) {
986
- out.push(`${match[1]}${match[2]}${match[3]}`);
987
- }
988
- return out.sort();
1031
+ const out = [];
1032
+ for (const match of message.matchAll(TAG)) out.push(`${match[1]}${match[2]}${match[3]}`);
1033
+ return out.sort();
989
1034
  }
990
1035
  function sameMembers(a, b) {
991
- return a.length === b.length && a.every((value, i) => value === b[i]);
1036
+ return a.length === b.length && a.every((value, i) => value === b[i]);
992
1037
  }
993
-
994
- // src/cli.ts
995
- var HELP = `verbaly \u2014 i18n compiler
1038
+ //#endregion
1039
+ //#region src/cli.ts
1040
+ const HELP = `verbaly i18n compiler
996
1041
 
997
1042
  Usage:
1043
+ verbaly init scaffold config + locale catalogs (detects your bundler)
998
1044
  verbaly extract scan sources, update catalogs and types
999
1045
  verbaly check verify translations are complete (CI)
1000
1046
  verbaly translate fill missing translations via a provider (default: claude)
@@ -1016,131 +1062,129 @@ Config file: verbaly.config.{js,mjs,ts,mts,json} at root (flags win).
1016
1062
  The claude provider needs @anthropic-ai/sdk installed and ANTHROPIC_API_KEY set.
1017
1063
  `;
1018
1064
  async function main() {
1019
- const { positionals, values } = parseArgs2({
1020
- allowPositionals: true,
1021
- options: {
1022
- root: { type: "string" },
1023
- dir: { type: "string" },
1024
- source: { type: "string" },
1025
- locales: { type: "string" },
1026
- prune: { type: "boolean" },
1027
- model: { type: "string" },
1028
- locale: { type: "string" },
1029
- site: { type: "string" },
1030
- "dry-run": { type: "boolean" },
1031
- help: { type: "boolean", short: "h" }
1032
- }
1033
- });
1034
- const command = positionals[0];
1035
- if (values.help || !command) {
1036
- console.log(HELP);
1037
- process.exitCode = command ? 0 : 1;
1038
- return;
1039
- }
1040
- const cfg = await loadConfig(values.root ?? process.cwd(), {
1041
- dir: values.dir,
1042
- sourceLocale: values.source,
1043
- locales: values.locales?.split(",")
1044
- });
1045
- if (command === "extract") {
1046
- const registry = await extractProject(cfg);
1047
- const catalogs = loadCatalogs(cfg);
1048
- if (values.prune) {
1049
- const removed = pruneCatalogs(cfg, catalogs, registry);
1050
- for (const [locale, keys] of Object.entries(removed)) {
1051
- console.log(` ${locale}: -${keys.length} pruned`);
1052
- }
1053
- }
1054
- const { added } = syncCatalogs(cfg, catalogs, registry);
1055
- for (const locale of cfg.locales) {
1056
- writeCatalog(cfg, locale, catalogs[locale] ?? {});
1057
- }
1058
- writeDts(cfg, new Map(Object.entries(catalogs[cfg.sourceLocale] ?? {})));
1059
- const total = registry.messages().size;
1060
- console.log(`[verbaly] ${total} messages \xB7 locales: ${cfg.locales.join(", ")}`);
1061
- for (const [locale, keys] of Object.entries(added)) {
1062
- console.log(` ${locale}: +${keys.length}`);
1063
- }
1064
- return;
1065
- }
1066
- if (command === "check") {
1067
- const registry = await extractProject(cfg);
1068
- const result = check(cfg, loadCatalogs(cfg), registry);
1069
- if (result.ok) {
1070
- console.log("[verbaly] all translations complete \u2713");
1071
- return;
1072
- }
1073
- console.error(`[verbaly] check failed
1074
- ${formatCheckResult(result)}`);
1075
- process.exitCode = 1;
1076
- return;
1077
- }
1078
- if (command === "translate") {
1079
- const catalogs = loadCatalogs(cfg);
1080
- const provider = await resolveProvider(cfg, values.model);
1081
- const result = await translateCatalogs(cfg, catalogs, provider, {
1082
- locales: values.locales?.split(","),
1083
- batchSize: cfg.translate.batchSize,
1084
- dryRun: values["dry-run"]
1085
- });
1086
- if (values["dry-run"]) {
1087
- const entries = Object.entries(result.pending);
1088
- if (entries.length === 0) {
1089
- console.log("[verbaly] nothing to translate \u2713");
1090
- return;
1091
- }
1092
- for (const [locale, keys] of entries) {
1093
- console.log(` ${locale}: ${keys.length} missing \u2014 ${keys.join(", ")}`);
1094
- }
1095
- return;
1096
- }
1097
- for (const locale of Object.keys(result.translated)) {
1098
- writeCatalog(cfg, locale, catalogs[locale] ?? {});
1099
- console.log(` ${locale}: +${result.translated[locale].length} translated`);
1100
- }
1101
- for (const [locale, keys] of Object.entries(result.invalid)) {
1102
- console.warn(
1103
- ` ${locale}: ${keys.length} rejected (params/tags not preserved): ${keys.join(", ")}`
1104
- );
1105
- }
1106
- if (Object.keys(result.translated).length === 0 && Object.keys(result.invalid).length === 0) {
1107
- console.log("[verbaly] nothing to translate \u2713");
1108
- }
1109
- return;
1110
- }
1111
- if (command === "render") {
1112
- const result = await renderSite(cfg, {
1113
- site: values.site,
1114
- locales: values.locales?.split(",")
1115
- });
1116
- console.log(
1117
- `[verbaly] ${result.files} pages \xD7 ${result.locales.length} locales (${result.locales.join(", ")})`
1118
- );
1119
- for (const [locale, keys] of Object.entries(result.missing)) {
1120
- console.warn(` ${locale}: ${keys.length} keys not pre-filled \u2014 ${keys.join(", ")}`);
1121
- }
1122
- return;
1123
- }
1124
- if (command === "pseudo") {
1125
- const catalogs = loadCatalogs(cfg);
1126
- const locale = values.locale ?? PSEUDO_LOCALE;
1127
- const keys = pseudoCatalogs(cfg, catalogs, locale);
1128
- writeCatalog(cfg, locale, catalogs[locale] ?? {});
1129
- console.log(`[verbaly] ${keys.length} messages pseudo-localized \u2192 ${locale}`);
1130
- return;
1131
- }
1132
- console.error(`[verbaly] unknown command "${command}"
1133
- ${HELP}`);
1134
- process.exitCode = 1;
1065
+ const { positionals, values } = parseArgs({
1066
+ allowPositionals: true,
1067
+ options: {
1068
+ root: { type: "string" },
1069
+ dir: { type: "string" },
1070
+ source: { type: "string" },
1071
+ locales: { type: "string" },
1072
+ prune: { type: "boolean" },
1073
+ model: { type: "string" },
1074
+ locale: { type: "string" },
1075
+ site: { type: "string" },
1076
+ "dry-run": { type: "boolean" },
1077
+ help: {
1078
+ type: "boolean",
1079
+ short: "h"
1080
+ }
1081
+ }
1082
+ });
1083
+ const command = positionals[0];
1084
+ if (values.help || !command) {
1085
+ console.log(HELP);
1086
+ process.exitCode = command ? 0 : 1;
1087
+ return;
1088
+ }
1089
+ if (command === "init") {
1090
+ const result = init({
1091
+ root: values.root,
1092
+ dir: values.dir,
1093
+ sourceLocale: values.source,
1094
+ locales: values.locales?.split(",")
1095
+ });
1096
+ if (result.created.length) console.log(`[verbaly] created: ${result.created.join(", ")}`);
1097
+ if (result.skipped.length) console.log(` kept (already there): ${result.skipped.join(", ")}`);
1098
+ if (result.bundler) console.log(` detected bundler: ${result.bundler}`);
1099
+ console.log([" next steps:", ...result.next.map((step, i) => ` ${i + 1}. ${step}`)].join("\n"));
1100
+ return;
1101
+ }
1102
+ const cfg = await loadConfig(values.root ?? process.cwd(), {
1103
+ dir: values.dir,
1104
+ sourceLocale: values.source,
1105
+ locales: values.locales?.split(",")
1106
+ });
1107
+ if (command === "extract") {
1108
+ const registry = await extractProject(cfg);
1109
+ const catalogs = loadCatalogs(cfg);
1110
+ if (values.prune) {
1111
+ const removed = pruneCatalogs(cfg, catalogs, registry);
1112
+ for (const [locale, keys] of Object.entries(removed)) console.log(` ${locale}: -${keys.length} pruned`);
1113
+ }
1114
+ const { added } = syncCatalogs(cfg, catalogs, registry);
1115
+ for (const locale of cfg.locales) writeCatalog(cfg, locale, catalogs[locale] ?? {});
1116
+ writeDts(cfg, new Map(Object.entries(catalogs[cfg.sourceLocale] ?? {})));
1117
+ const total = registry.messages().size;
1118
+ console.log(`[verbaly] ${total} messages · locales: ${cfg.locales.join(", ")}`);
1119
+ for (const [locale, keys] of Object.entries(added)) console.log(` ${locale}: +${keys.length}`);
1120
+ return;
1121
+ }
1122
+ if (command === "check") {
1123
+ const registry = await extractProject(cfg);
1124
+ const result = check(cfg, loadCatalogs(cfg), registry);
1125
+ if (result.ok) {
1126
+ console.log("[verbaly] all translations complete ✓");
1127
+ return;
1128
+ }
1129
+ console.error(`[verbaly] check failed\n${formatCheckResult(result)}`);
1130
+ process.exitCode = 1;
1131
+ return;
1132
+ }
1133
+ if (command === "translate") {
1134
+ const catalogs = loadCatalogs(cfg);
1135
+ const result = await translateCatalogs(cfg, catalogs, await resolveProvider(cfg, values.model), {
1136
+ locales: values.locales?.split(","),
1137
+ batchSize: cfg.translate.batchSize,
1138
+ dryRun: values["dry-run"]
1139
+ });
1140
+ if (values["dry-run"]) {
1141
+ const entries = Object.entries(result.pending);
1142
+ if (entries.length === 0) {
1143
+ console.log("[verbaly] nothing to translate ✓");
1144
+ return;
1145
+ }
1146
+ for (const [locale, keys] of entries) console.log(` ${locale}: ${keys.length} missing — ${keys.join(", ")}`);
1147
+ return;
1148
+ }
1149
+ for (const locale of Object.keys(result.translated)) {
1150
+ writeCatalog(cfg, locale, catalogs[locale] ?? {});
1151
+ console.log(` ${locale}: +${result.translated[locale].length} translated`);
1152
+ }
1153
+ for (const [locale, keys] of Object.entries(result.invalid)) console.warn(` ${locale}: ${keys.length} rejected (params/tags not preserved): ${keys.join(", ")}`);
1154
+ if (Object.keys(result.translated).length === 0 && Object.keys(result.invalid).length === 0) console.log("[verbaly] nothing to translate ✓");
1155
+ return;
1156
+ }
1157
+ if (command === "render") {
1158
+ const result = await renderSite(cfg, {
1159
+ site: values.site,
1160
+ locales: values.locales?.split(",")
1161
+ });
1162
+ console.log(`[verbaly] ${result.files} pages × ${result.locales.length} locales (${result.locales.join(", ")})`);
1163
+ for (const [locale, keys] of Object.entries(result.missing)) console.warn(` ${locale}: ${keys.length} keys not pre-filled — ${keys.join(", ")}`);
1164
+ return;
1165
+ }
1166
+ if (command === "pseudo") {
1167
+ const catalogs = loadCatalogs(cfg);
1168
+ const locale = values.locale ?? "en-XA";
1169
+ const keys = pseudoCatalogs(cfg, catalogs, locale);
1170
+ writeCatalog(cfg, locale, catalogs[locale] ?? {});
1171
+ console.log(`[verbaly] ${keys.length} messages pseudo-localized → ${locale}`);
1172
+ return;
1173
+ }
1174
+ console.error(`[verbaly] unknown command "${command}"\n${HELP}`);
1175
+ process.exitCode = 1;
1135
1176
  }
1136
1177
  async function resolveProvider(cfg, model) {
1137
- const configured = cfg.translate.provider;
1138
- if (typeof configured === "function") return configured;
1139
- const { claudeProvider } = await import("./claude-XSRCRBAQ.js");
1140
- return claudeProvider({ model: model ?? cfg.translate.model });
1178
+ const configured = cfg.translate.provider;
1179
+ if (typeof configured === "function") return configured;
1180
+ const { claudeProvider } = await import("./claude-BhP-eK5E.js");
1181
+ return claudeProvider({ model: model ?? cfg.translate.model });
1141
1182
  }
1142
1183
  main().catch((error) => {
1143
- console.error("[verbaly]", error instanceof Error ? error.message : error);
1144
- process.exitCode = 1;
1184
+ console.error("[verbaly]", error instanceof Error ? error.message : error);
1185
+ process.exitCode = 1;
1145
1186
  });
1187
+ //#endregion
1188
+ export {};
1189
+
1146
1190
  //# sourceMappingURL=cli.js.map