@verbaly/compiler 0.74.0 → 0.76.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,3960 +1,14 @@
1
- import { a as findConfigFile, c as loadConfigFile, d as WIRING_PACKAGES, f as detectHost, i as SOURCE_EXTENSIONS, l as resolveConfig, m as readDependencies, n as counted, p as installCommand, r as truncate, s as loadConfig, t as byCodeUnit, u as targetLocales } from "./text-BMBWE8tL.js";
2
- import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, rmSync, watch, writeFileSync } from "node:fs";
3
- import { dirname, join, relative, resolve, sep } from "node:path";
4
- import { CATALOG_SCRIPT, LOCALE_STORAGE_KEY, RICH_TAGS, VOID_TAGS, alternateLinks, createVerbaly, flatten, localeDirection, normalizeLink, parse, parseIcu, parseTags, safeAttribute } from "verbaly";
5
- import { glob } from "tinyglobby";
6
- import { parse as parse$1 } from "@babel/parser";
7
- import { createHash } from "node:crypto";
8
- import { applyEdits, modify, parse as parse$2 } from "jsonc-parser";
9
- import picomatch from "picomatch";
10
- import MagicString from "magic-string";
11
- //#region src/eol.ts
12
- function withLineEndings(text, existing) {
13
- const first = existing?.indexOf("\n") ?? -1;
14
- return first > 0 && existing[first - 1] === "\r" ? text.replace(/\r?\n/g, "\r\n") : text;
15
- }
16
- //#endregion
17
- //#region src/catalog.ts
18
- function emptyCatalog() {
19
- return Object.create(null);
20
- }
21
- function own(catalog, key) {
22
- return Object.hasOwn(catalog, key) ? catalog[key] : void 0;
23
- }
24
- function catalogPath(cfg, locale) {
25
- return join(cfg.dir, `${locale}.json`);
26
- }
27
- function readCatalog(cfg, locale) {
28
- const tree = readTree(cfg, locale);
29
- const bad = badLeaf(tree);
30
- 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`);
31
- return flatten(tree);
32
- }
33
- function badLeaf(tree, prefix = "") {
34
- for (const [key, value] of Object.entries(tree)) {
35
- const path = prefix ? `${prefix}.${key}` : key;
36
- if (typeof value === "string") continue;
37
- if (value === null || typeof value !== "object" || Array.isArray(value)) return path;
38
- const bad = badLeaf(value, path);
39
- if (bad) return bad;
40
- }
41
- }
42
- function readTree(cfg, locale) {
43
- let content;
44
- try {
45
- content = readFileSync(catalogPath(cfg, locale), "utf8");
46
- } catch {
47
- return {};
48
- }
49
- const parsed = parseTree(content);
50
- if (parsed === void 0) throw new Error(`[verbaly] ${catalogPath(cfg, locale)} is not valid JSON, fix or delete the file`);
51
- if (!isTree(parsed)) throw new Error(`[verbaly] ${catalogPath(cfg, locale)} is not a JSON object of messages, fix or delete the file`);
52
- return parsed;
53
- }
54
- function parseCatalog(content) {
55
- const tree = parseTree(content);
56
- return tree === void 0 ? void 0 : flatten(tree);
57
- }
58
- function parseTree(content) {
59
- const body = content.charCodeAt(0) === 65279 ? content.slice(1) : content;
60
- try {
61
- return JSON.parse(body);
62
- } catch {
63
- return;
64
- }
65
- }
66
- function isTree(value) {
67
- return typeof value === "object" && value !== null && !Array.isArray(value);
68
- }
69
- function loadCatalogs(cfg) {
70
- const catalogs = {};
71
- for (const locale of cfg.locales) catalogs[locale] = readCatalog(cfg, locale);
72
- return catalogs;
73
- }
74
- function isNested(tree) {
75
- return Object.values(tree).some((value) => typeof value === "object" && value !== null);
76
- }
77
- function group() {
78
- return Object.create(null);
79
- }
80
- function nest(catalog) {
81
- const tree = group();
82
- for (const [key, message] of Object.entries(catalog).sort(([a], [b]) => a < b ? -1 : 1)) {
83
- const parts = key.split(".");
84
- const leaf = parts[parts.length - 1];
85
- let node = parts.length > 1 ? tree : void 0;
86
- for (let i = 0; node && i < parts.length - 1; i++) {
87
- const next = node[parts[i]] ??= group();
88
- node = typeof next === "object" && next !== null ? next : void 0;
89
- }
90
- if (node && typeof node[leaf] !== "object") node[leaf] = message;
91
- else tree[key] = message;
92
- }
93
- return tree;
94
- }
95
- function sortTree(tree) {
96
- const sorted = group();
97
- for (const key of Object.keys(tree).sort()) {
98
- const value = tree[key];
99
- if (typeof value === "string") sorted[key] = value;
100
- else if (value !== void 0) sorted[key] = sortTree(value);
101
- }
102
- return sorted;
103
- }
104
- function isSorted(keys) {
105
- for (let i = 1; i < keys.length; i++) if (keys[i - 1] > keys[i]) return false;
106
- return true;
107
- }
108
- function orderLike(tree, previous) {
109
- const had = Object.keys(previous);
110
- if (isSorted(had)) return sortTree(tree);
111
- const out = group();
112
- const take = (key) => {
113
- const value = tree[key];
114
- if (typeof value === "string") {
115
- out[key] = value;
116
- return;
117
- }
118
- if (value === void 0) return;
119
- const before = previous[key];
120
- out[key] = typeof before === "object" && before !== null ? orderLike(value, before) : sortTree(value);
121
- };
122
- for (const key of had) if (Object.hasOwn(tree, key)) take(key);
123
- for (const key of Object.keys(tree).sort()) if (!Object.hasOwn(previous, key)) take(key);
124
- return out;
125
- }
126
- function serializeCatalog(catalog, nested = false, previous) {
127
- const tree = nested ? nest(catalog) : catalog;
128
- return JSON.stringify(previous ? orderLike(tree, previous) : sortTree(tree), null, 2) + "\n";
129
- }
130
- function writeCatalog(cfg, locale, catalog) {
131
- const path = catalogPath(cfg, locale);
132
- let existing;
133
- try {
134
- existing = readFileSync(path, "utf8");
135
- } catch {
136
- mkdirSync(cfg.dir, { recursive: true });
137
- }
138
- const parsed = existing === void 0 ? void 0 : parseTree(existing);
139
- const previous = isTree(parsed) ? parsed : void 0;
140
- const serialized = withLineEndings(serializeCatalog(catalog, wantsNesting(cfg, locale, existing, previous), previous), existing);
141
- if (existing === serialized) return serialized;
142
- writeFileSync(path, serialized);
143
- return serialized;
144
- }
145
- function wantsNesting(cfg, locale, existing, previous) {
146
- if (existing !== void 0) return previous !== void 0 && isNested(previous);
147
- if (locale === cfg.sourceLocale) return false;
148
- return isNested(readTree(cfg, cfg.sourceLocale));
149
- }
150
- const ICU_ARG = /(^|[^{])\{\s*[a-zA-Z0-9_]+\s*,\s*(?:plural|selectordinal|select|number|date|time)\b/;
151
- function needsIcu(catalogs) {
152
- for (const catalog of Object.values(catalogs)) for (const message of Object.values(flatten(catalog))) if (ICU_ARG.test(message)) return true;
153
- return false;
154
- }
155
- const RELATIVE_ARG = /\{[^{}]*:\s*relative\b/;
156
- function needsRelative(catalogs) {
157
- for (const catalog of Object.values(catalogs)) for (const message of Object.values(flatten(catalog))) if (RELATIVE_ARG.test(message)) return true;
158
- return false;
159
- }
160
- //#endregion
161
- //#region src/bundle.ts
162
- function isExcluded(key, prefixes) {
163
- return prefixes.some((prefix) => key === prefix || key.startsWith(`${prefix}.`));
164
- }
165
- function clientCatalogs(cfg, catalogs) {
166
- const prefixes = cfg.bundle.exclude ?? [];
167
- if (prefixes.length === 0) return catalogs;
168
- const out = {};
169
- for (const [locale, catalog] of Object.entries(catalogs)) {
170
- const kept = emptyCatalog();
171
- for (const [key, message] of Object.entries(catalog)) if (!isExcluded(key, prefixes)) kept[key] = message;
172
- out[locale] = kept;
173
- }
174
- return out;
175
- }
176
- function auditBundle(cfg, catalogs, registry) {
177
- const prefixes = cfg.bundle.exclude ?? [];
178
- if (prefixes.length === 0) return [];
179
- const source = Object.keys(catalogs[cfg.sourceLocale] ?? {});
180
- const used = registry.usedKeys();
181
- const issues = [];
182
- for (const prefix of prefixes) {
183
- if (!source.some((key) => isExcluded(key, [prefix]))) {
184
- issues.push({
185
- prefix,
186
- problem: `matches no key in ${cfg.sourceLocale}.json, so it excludes nothing`,
187
- fix: "check the spelling against your catalog, or drop it from bundle.exclude"
188
- });
189
- continue;
190
- }
191
- const files = /* @__PURE__ */ new Set();
192
- for (const [key, where] of used) if (isExcluded(key, [prefix])) for (const file of where) files.add(file);
193
- if (files.size > 0) issues.push({
194
- prefix,
195
- problem: `is read by t() in ${counted(files.size, "file")}, where it resolves to the key itself`,
196
- fix: "pre-render those pages with render, load the group with addMessages, or stop excluding it"
197
- });
198
- }
199
- return issues;
200
- }
201
- function formatBundleIssue(issue) {
202
- return `bundle.exclude "${issue.prefix}" ${issue.problem}`;
203
- }
204
- //#endregion
205
- //#region src/registry.ts
206
- var MessageRegistry = class {
207
- files = /* @__PURE__ */ new Map();
208
- update(file, analysis) {
209
- this.files.set(file, analysis);
210
- }
211
- remove(file) {
212
- this.files.delete(file);
213
- }
214
- messages() {
215
- const out = /* @__PURE__ */ new Map();
216
- for (const analysis of this.inOrder()) for (const msg of analysis.tagged) {
217
- const held = out.get(msg.key);
218
- if (!held || earlier(msg, held)) out.set(msg.key, msg);
219
- }
220
- return out;
221
- }
222
- collisions() {
223
- const winners = this.messages();
224
- const dropped = /* @__PURE__ */ new Map();
225
- for (const analysis of this.inOrder()) for (const msg of analysis.tagged) {
226
- if (msg.message === winners.get(msg.key).message) continue;
227
- dropped.set(msg.key, [...dropped.get(msg.key) ?? [], msg]);
228
- }
229
- return [...dropped].map(([key, others]) => ({
230
- key,
231
- kept: winners.get(key),
232
- dropped: others.sort((a, b) => earlier(a, b) ? -1 : 1)
233
- }));
234
- }
235
- usedKeys(strict = false) {
236
- const out = /* @__PURE__ */ new Map();
237
- for (const analysis of this.inOrder()) for (const used of analysis.usedKeys) {
238
- if (strict && used.loose) continue;
239
- const files = out.get(used.key) ?? [];
240
- if (!files.includes(used.file)) files.push(used.file);
241
- out.set(used.key, files);
242
- }
243
- return out;
244
- }
245
- strayImports() {
246
- return this.inOrder().flatMap((analysis) => analysis.strayImports);
247
- }
248
- missed() {
249
- return this.inOrder().flatMap((analysis) => analysis.missed);
250
- }
251
- parseErrors() {
252
- const out = [];
253
- for (const file of [...this.files.keys()].sort()) {
254
- const { parseError } = this.files.get(file);
255
- if (parseError) out.push({
256
- file,
257
- message: parseError
258
- });
259
- }
260
- return out;
261
- }
262
- origins() {
263
- const out = this.usedKeys();
264
- for (const analysis of this.inOrder()) for (const msg of analysis.tagged) {
265
- const files = out.get(msg.key) ?? [];
266
- if (!files.includes(msg.file)) files.push(msg.file);
267
- out.set(msg.key, files);
268
- }
269
- return out;
270
- }
271
- inOrder() {
272
- return [...this.files.keys()].sort().map((file) => this.files.get(file));
273
- }
274
- };
275
- function earlier(a, b) {
276
- return a.file === b.file ? a.start < b.start : a.file < b.file;
277
- }
278
- //#endregion
279
- //#region src/key.ts
280
- function stableKey(message) {
281
- return createHash("sha256").update(message).digest("base64url").slice(0, 8);
282
- }
283
- //#endregion
284
- //#region src/analyze.ts
285
- function parseErrorMessage(error) {
286
- return error instanceof Error ? error.message : String(error);
287
- }
288
- const SKIP_KEYS = /* @__PURE__ */ new Set([
289
- "loc",
290
- "leadingComments",
291
- "trailingComments",
292
- "innerComments",
293
- "extra"
294
- ]);
295
- const DEFAULT_T_NAMES = ["t"];
296
- const JSX_FILE_RE = /\.(?:[cm]?jsx?|tsx)$/;
297
- const DEFINE_KEYS = "defineKeys";
298
- function analyze(code, file, options = {}) {
299
- return analyzeScript(code, file, options).analysis;
300
- }
301
- function analyzeScript(code, file, options = {}) {
302
- const names = new Set(options.tNames ?? DEFAULT_T_NAMES);
303
- const ast = parse$1(code, {
304
- sourceType: "module",
305
- errorRecovery: true,
306
- plugins: JSX_FILE_RE.test(file) ? ["typescript", "jsx"] : ["typescript"]
307
- });
308
- const tagged = [];
309
- const usedKeys = [];
310
- const strayImports = [];
311
- const bindings = new Bindings(names);
312
- const candidates = [];
313
- walk$1(ast.program, (node) => {
314
- if (node.type === "ImportDeclaration") {
315
- collectStrayImports(node, file, strayImports);
316
- bindings.addImport(node);
317
- } else if (node.type === "VariableDeclarator") bindings.addDeclarator(node);
318
- else if (node.type === "TaggedTemplateExpression") {
319
- const tag = node.tag;
320
- const explicit = explicitId(tag, names);
321
- if (!explicit && !isTReference(tag, names)) {
322
- candidates.push({
323
- kind: "tag",
324
- node
325
- });
326
- return;
327
- }
328
- const quasi = node.quasi;
329
- const message = buildMessage(code, quasi, names);
330
- if (!message) return;
331
- tagged.push({
332
- key: explicit ? explicit.key : stableKey(message.text),
333
- message: message.text,
334
- params: message.params,
335
- start: node.start,
336
- end: node.end,
337
- line: lineOf(node),
338
- tagStart: explicit ? explicit.refStart : tag.start,
339
- tagEnd: explicit ? explicit.refEnd : tag.end,
340
- file
341
- });
342
- } else if (node.type === "CallExpression") {
343
- const callee = node.callee;
344
- const args = node.arguments;
345
- if (callee.type === "Identifier" && callee.name === DEFINE_KEYS) {
346
- collectDeclaredKeys(args[0], file, usedKeys);
347
- return;
348
- }
349
- if (!isTReference(callee, names)) {
350
- const key = callee.type === "Identifier" ? staticString(args[0]) : void 0;
351
- if (key !== void 0) candidates.push({
352
- kind: "call",
353
- name: callee.name,
354
- key
355
- });
356
- return;
357
- }
358
- const key = staticString(args[0]);
359
- if (key !== void 0) usedKeys.push({
360
- key,
361
- file
362
- });
363
- } else if (node.type === "JSXElement") handleTrans(code, node, file, tagged, usedKeys, names);
364
- });
365
- const renamed = bindings.renamed(options.renamed);
366
- const missed = [];
367
- for (const candidate of candidates) {
368
- if (candidate.kind === "call") {
369
- if (renamed.has(candidate.name)) usedKeys.push({
370
- key: candidate.key,
371
- file
372
- });
373
- continue;
374
- }
375
- const { node } = candidate;
376
- const name = renamedTag(node.tag, renamed);
377
- if (!name) continue;
378
- missed.push({
379
- name,
380
- file,
381
- start: node.start,
382
- line: lineOf(node)
383
- });
384
- const key = missedKey(code, node, names);
385
- if (key !== void 0) usedKeys.push({
386
- key,
387
- file,
388
- loose: true
389
- });
390
- }
391
- return {
392
- analysis: {
393
- tagged,
394
- usedKeys,
395
- strayImports,
396
- missed
397
- },
398
- renamed: [...renamed]
399
- };
400
- }
401
- function lineOf(node) {
402
- return node.loc?.start.line ?? 1;
403
- }
404
- const VERBALY_SOURCE = /^(?:verbaly|virtual:verbaly|@verbaly\/[\w-]+(?:\/[\w-]+)*)$/;
405
- const T_FACTORIES = /* @__PURE__ */ new Map([["useT", "call"], ["getT", "await"]]);
406
- const INSTANCE_FACTORIES = /* @__PURE__ */ new Set(["useVerbaly", "getVerbaly"]);
407
- var Bindings = class {
408
- names;
409
- imports = /* @__PURE__ */ new Map();
410
- direct = /* @__PURE__ */ new Set();
411
- declared = [];
412
- destructured = [];
413
- constructor(names) {
414
- this.names = names;
415
- }
416
- addImport(node) {
417
- const source = node.source.value;
418
- if (typeof source !== "string") return;
419
- for (const spec of node.specifiers) {
420
- const local = identifierName(spec.local);
421
- if (!local) continue;
422
- const imported = spec.type === "ImportSpecifier" ? importedName(spec.imported) : spec.type;
423
- this.imports.set(local, {
424
- source,
425
- imported
426
- });
427
- if (source === "virtual:verbaly" && imported === "t") this.direct.add(local);
428
- }
429
- }
430
- addDeclarator(node) {
431
- const id = node.id;
432
- const init = node.init;
433
- if (!init) return;
434
- if (id.type === "Identifier") {
435
- this.declared.push({
436
- name: id.name,
437
- init
438
- });
439
- return;
440
- }
441
- if (id.type !== "ObjectPattern") return;
442
- for (const property of id.properties) {
443
- if (property.type !== "ObjectProperty" || property.computed) continue;
444
- if (identifierName(property.key) !== "t") continue;
445
- const value = property.value;
446
- const name = identifierName(value.type === "AssignmentPattern" ? value.left : value);
447
- if (name) this.destructured.push({
448
- name,
449
- init
450
- });
451
- }
452
- }
453
- renamed(seed = []) {
454
- const out = new Set(seed);
455
- const add = (name) => {
456
- if (this.names.has(name)) return;
457
- out.add(name);
458
- if (this.names.has("$t")) out.add(`$${name}`);
459
- };
460
- for (const name of this.direct) add(name);
461
- for (const { name, init } of this.declared) if (this.handsOutT(init)) add(name);
462
- for (const { name, init } of this.destructured) if (this.carriesT(init)) add(name);
463
- return out;
464
- }
465
- handsOutT(init) {
466
- const awaited = init.type === "AwaitExpression";
467
- const call = awaited ? init.argument : init;
468
- if (call.type !== "CallExpression") return false;
469
- const origin = this.origin(identifierName(call.callee));
470
- if (origin.verbaly === false) return false;
471
- const how = T_FACTORIES.get(origin.imported);
472
- return how !== void 0 && how === "await" === awaited;
473
- }
474
- carriesT(init) {
475
- const inner = init.type === "AwaitExpression" ? init.argument : init;
476
- const name = identifierName(inner.type === "CallExpression" ? inner.callee : inner);
477
- if (!name) return false;
478
- return this.origin(name).verbaly ?? INSTANCE_FACTORIES.has(name);
479
- }
480
- origin(local) {
481
- const found = this.imports.get(local);
482
- if (!found) return {
483
- verbaly: void 0,
484
- imported: local
485
- };
486
- return {
487
- verbaly: VERBALY_SOURCE.test(found.source),
488
- imported: found.imported
489
- };
490
- }
491
- };
492
- function importedName(node) {
493
- return node.type === "StringLiteral" ? node.value : identifierName(node);
494
- }
495
- function identifierName(node) {
496
- return node?.type === "Identifier" ? node.name : "";
497
- }
498
- function renamedTag(tag, renamed) {
499
- if (renamed.size === 0) return void 0;
500
- const name = identifierName(tag);
501
- if (renamed.has(name)) return name;
502
- if (tag.type !== "CallExpression") return void 0;
503
- const callee = tag.callee;
504
- if (callee.type !== "MemberExpression" || callee.computed) return void 0;
505
- if (identifierName(callee.property) !== "id") return void 0;
506
- const object = identifierName(callee.object);
507
- return renamed.has(object) ? object : void 0;
508
- }
509
- function missedKey(code, node, names) {
510
- const tag = node.tag;
511
- if (tag.type === "CallExpression") {
512
- const args = tag.arguments;
513
- return args.length === 1 ? staticString(args[0]) : void 0;
514
- }
515
- const message = buildMessage(code, node.quasi, names);
516
- return message ? stableKey(message.text) : void 0;
517
- }
518
- function collectDeclaredKeys(node, file, out) {
519
- if (node?.type !== "ObjectExpression") return;
520
- for (const property of node.properties) {
521
- if (property.type !== "ObjectProperty") continue;
522
- const value = property.value;
523
- const key = staticString(value);
524
- if (key !== void 0) {
525
- if (key !== "") out.push({
526
- key,
527
- file
528
- });
529
- } else if (value.type === "ObjectExpression") collectDeclaredKeys(value, file, out);
530
- }
531
- }
532
- function staticString(node) {
533
- if (!node) return void 0;
534
- if (node.type === "StringLiteral") return node.value;
535
- if (node.type === "TemplateLiteral" && node.expressions.length === 0) return cookedValue(node.quasis[0]);
536
- if (node.type === "JSXExpressionContainer") return staticString(node.expression);
537
- }
538
- const VERBALY_PACKAGE = /^(?:verbaly|@verbaly\/[\w-]+)$/;
539
- function collectStrayImports(node, file, out) {
540
- const source = node.source;
541
- if (typeof source.value !== "string" || !VERBALY_PACKAGE.test(source.value)) return;
542
- for (const spec of node.specifiers) {
543
- if (spec.type !== "ImportSpecifier") continue;
544
- const imported = spec.imported;
545
- if (imported.type !== "Identifier") continue;
546
- const name = imported.name;
547
- if (name === "t" || name === DEFINE_KEYS) out.push({
548
- name,
549
- source: source.value,
550
- file
551
- });
552
- }
553
- }
554
- function handleTrans(code, node, file, tagged, usedKeys, names) {
555
- const opening = node.openingElement;
556
- const nameNode = opening.name;
557
- if (nameNode.type !== "JSXIdentifier" || nameNode.name !== "Trans") return;
558
- const attrs = opening.attributes;
559
- const idAttr = attrs.find((a) => a.type === "JSXAttribute" && a.name.name === "id");
560
- const children = node.children;
561
- const push = (key, built) => tagged.push({
562
- key,
563
- message: built.text,
564
- params: built.params,
565
- start: node.start,
566
- end: node.end,
567
- line: lineOf(node),
568
- tagStart: nameNode.start,
569
- tagEnd: nameNode.end,
570
- file,
571
- jsx: {
572
- name: nameNode.name,
573
- components: built.components
574
- }
575
- });
576
- if (idAttr) {
577
- const value = idAttr.value;
578
- const id = staticString(value);
579
- if (id === void 0) return;
580
- if (attrs.length === 1 && children?.length) {
581
- const built = buildTransMessage(code, children, names);
582
- if (built?.text.trim()) {
583
- push(id, built);
584
- return;
585
- }
586
- }
587
- usedKeys.push({
588
- key: id,
589
- file
590
- });
591
- return;
592
- }
593
- if (attrs.length > 0) return;
594
- if (!children?.length) return;
595
- const built = buildTransMessage(code, children, names);
596
- if (!built || !built.text.trim()) return;
597
- push(stableKey(built.text), built);
598
- }
599
- function explicitId(tag, names) {
600
- if (tag.type !== "CallExpression") return void 0;
601
- const callee = tag.callee;
602
- if (callee.type !== "MemberExpression" || callee.computed) return void 0;
603
- const prop = callee.property;
604
- if (prop.type !== "Identifier" || prop.name !== "id") return void 0;
605
- const obj = callee.object;
606
- if (!isTReference(obj, names)) return void 0;
607
- const args = tag.arguments;
608
- const key = args.length === 1 ? staticString(args[0]) : void 0;
609
- if (key === void 0) return void 0;
610
- return {
611
- key,
612
- refStart: obj.start,
613
- refEnd: obj.end
614
- };
615
- }
616
- function buildTransMessage(code, children, names) {
617
- const params = [];
618
- const components = [];
619
- const takenParams = /* @__PURE__ */ new Map();
620
- const takenTags = /* @__PURE__ */ new Map();
621
- function walkChildren(nodes) {
622
- let text = "";
623
- for (const child of nodes) if (child.type === "JSXText") text += escapeText(cleanJsxText(child.value));
624
- else if (child.type === "JSXExpressionContainer") {
625
- const expr = child.expression;
626
- if (expr.type === "JSXEmptyExpression") continue;
627
- if (expr.type === "StringLiteral") {
628
- text += escapeText(expr.value);
629
- continue;
630
- }
631
- if (containsTaggedT(expr, names)) return void 0;
632
- const source = code.slice(expr.start, expr.end);
633
- const name = uniqueName(deriveName(expr, params.length), source, takenParams);
634
- params.push({
635
- name,
636
- start: expr.start,
637
- end: expr.end
638
- });
639
- text += `{${name}}`;
640
- } else if (child.type === "JSXElement") {
641
- const opening = child.openingElement;
642
- const nameNode = opening.name;
643
- if (nameNode.type !== "JSXIdentifier" || nameNode.name === "Trans") return void 0;
644
- const source = selfClosedSource(code, opening);
645
- const tag = uniqueName(nameNode.name.toLowerCase(), source, takenTags);
646
- if (!components.some((c) => c.name === tag)) components.push({
647
- name: tag,
648
- source
649
- });
650
- if (!child.closingElement) text += `<${tag}/>`;
651
- else {
652
- const inner = walkChildren(child.children);
653
- if (inner === void 0) return void 0;
654
- text += `<${tag}>${inner}</${tag}>`;
655
- }
656
- } else return;
657
- return text;
658
- }
659
- const text = walkChildren(children);
660
- if (text === void 0) return void 0;
661
- return {
662
- text,
663
- params,
664
- components
665
- };
666
- }
667
- function cleanJsxText(raw) {
668
- const lines = raw.split(/\r\n|[\r\n]/);
669
- let out = "";
670
- for (let i = 0; i < lines.length; i++) {
671
- let line = lines[i].replace(/\t/g, " ");
672
- if (i !== 0) line = line.replace(/^ +/, "");
673
- if (i !== lines.length - 1) line = line.replace(/ +$/, "");
674
- if (!line) continue;
675
- if (out && i !== 0) out += " ";
676
- out += line;
677
- }
678
- return out;
679
- }
680
- function selfClosedSource(code, opening) {
681
- const src = code.slice(opening.start, opening.end);
682
- return src.endsWith("/>") ? src : `${src.slice(0, -1).trimEnd()} />`;
683
- }
684
- function containsTaggedT(node, names) {
685
- let found = false;
686
- walk$1(node, (n) => {
687
- if (n.type !== "TaggedTemplateExpression") return;
688
- const tag = n.tag;
689
- if (isTReference(tag, names) || explicitId(tag, names)) found = true;
690
- });
691
- return found;
692
- }
693
- function isTReference(node, names) {
694
- if (node.type === "Identifier") return names.has(node.name);
695
- if (node.type === "MemberExpression" && !node.computed) {
696
- const prop = node.property;
697
- return prop.type === "Identifier" && names.has(prop.name);
698
- }
699
- return false;
700
- }
701
- const BLOCK_TAIL = /^(?:\s*\|\s*[^\s|{}:]+\s*:|:[A-Za-z_][\w-]*)/;
702
- function buildMessage(code, quasi, names) {
703
- const quasis = quasi.quasis;
704
- const expressions = quasi.expressions;
705
- const texts = quasis.map(cookedValue);
706
- const params = [];
707
- const taken = /* @__PURE__ */ new Map();
708
- const tokens = [];
709
- for (let i = 0; i < texts.length; i++) {
710
- const chunk = texts[i];
711
- const head = i < expressions.length && chunk.endsWith("{") && BLOCK_TAIL.test(texts[i + 1]);
712
- for (const char of head ? chunk.slice(0, -1) : chunk) tokens.push(char);
713
- if (i === expressions.length) break;
714
- const expr = expressions[i];
715
- if (!expr) return void 0;
716
- if (containsTaggedT(expr, names)) return void 0;
717
- const source = code.slice(expr.start, expr.end);
718
- const name = uniqueName(deriveName(expr, i), source, taken);
719
- params.push({
720
- name,
721
- start: expr.start,
722
- end: expr.end
723
- });
724
- tokens.push({
725
- name,
726
- head
727
- });
728
- }
729
- let text = "";
730
- for (let k = 0; k < tokens.length; k++) {
731
- const token = tokens[k];
732
- if (typeof token === "string") text += token === "{" || token === "}" ? token + token : token;
733
- else if (!token.head) text += `{${token.name}}`;
734
- else {
735
- const end = blockEnd(tokens, k, false) ?? blockEnd(tokens, k, true);
736
- if (end === void 0) return {
737
- text: texts.map((chunk, i) => escapeText(chunk) + (params[i] ? `{${params[i].name}}` : "")).join(""),
738
- params
739
- };
740
- for (let m = k; m <= end; m++) text += tokenText(tokens[m]);
741
- k = end;
742
- }
743
- }
744
- return {
745
- text,
746
- params
747
- };
748
- }
749
- function tokenText(token) {
750
- if (typeof token === "string") return token;
751
- return token.head ? `{${token.name}` : `{${token.name}}`;
752
- }
753
- function blockEnd(tokens, start, pairs) {
754
- let depth = 0;
755
- for (let k = start; k < tokens.length; k++) {
756
- const token = tokens[k];
757
- if (typeof token !== "string") {
758
- if (token.head) depth += 1;
759
- } else if (token === "{" || token === "}") {
760
- if (tokens[k + 1] === token && (token === "{" || !(pairs && depth > 1))) k += 1;
761
- else {
762
- depth += token === "{" ? 1 : -1;
763
- if (depth === 0) return k;
764
- }
765
- }
766
- }
767
- }
768
- function cookedValue(element) {
769
- if (!element) return "";
770
- const value = element.value;
771
- return value.cooked ?? value.raw;
772
- }
773
- function escapeText(text) {
774
- return text.replace(/[{}]/g, (m) => m + m);
775
- }
776
- function deriveName(expr, index) {
777
- if (expr.type === "Identifier") return expr.name;
778
- if (expr.type === "MemberExpression" && !expr.computed) {
779
- const prop = expr.property;
780
- if (prop.type === "Identifier") return prop.name;
781
- }
782
- return `_${index}`;
783
- }
784
- function uniqueName(base, source, taken) {
785
- let name = base;
786
- let n = 2;
787
- while (taken.has(name) && taken.get(name) !== source) {
788
- name = `${base}${n}`;
789
- n += 1;
790
- }
791
- taken.set(name, source);
792
- return name;
793
- }
794
- function walk$1(node, visit) {
795
- visit(node);
796
- for (const key in node) {
797
- if (SKIP_KEYS.has(key)) continue;
798
- const value = node[key];
799
- if (Array.isArray(value)) {
800
- for (const item of value) if (isNode(item)) walk$1(item, visit);
801
- } else if (isNode(value)) walk$1(value, visit);
802
- }
803
- }
804
- function isNode(value) {
805
- return typeof value === "object" && value !== null && typeof value.type === "string";
806
- }
807
- //#endregion
808
- //#region src/sfc.ts
809
- const SFC_FILE_RE = /\.(?:svelte|vue|astro)$/;
810
- function analyzeFile(code, file) {
811
- if (SFC_FILE_RE.test(file)) return analyzeSfc(code, file);
812
- try {
813
- return analyze(code, file);
814
- } catch (error) {
815
- return {
816
- tagged: [],
817
- usedKeys: [],
818
- strayImports: [],
819
- missed: [],
820
- parseError: parseErrorMessage(error)
821
- };
822
- }
823
- }
824
- const SCRIPT_RE = /(<script\b[^>]*>)([\s\S]*?)(<\/script\s*>)/gi;
825
- const STYLE_RE = /<style\b[^>]*>[\s\S]*?<\/style\s*>/gi;
826
- const COMMENT_RE = /<!--[\s\S]*?-->/g;
827
- const FRONTMATTER_RE = /^(\uFEFF?\s*---\r?\n)([\s\S]*?)\r?\n---(?=\r?\n|$)/;
828
- const MUSTACHE_RE = /\{\{[\s\S]*?\}\}/g;
829
- const DIRECTIVE_RE = /\s(?:v-[\w-]+(?::[^\s=>/]+)?|[:@][^\s=>/]+)\s*=\s*("[^"]*"|'[^']*')/g;
830
- function analyzeSfc(code, file) {
831
- const svelte = file.endsWith(".svelte");
832
- const tNames = svelte ? ["t", "$t"] : ["t"];
833
- const tagged = [];
834
- const usedKeys = [];
835
- const strayImports = [];
836
- const missed = [];
837
- const renamed = /* @__PURE__ */ new Set();
838
- const lineAt = lineCounter(code);
839
- let parseError;
840
- const block = (content, offset) => {
841
- const segment = analyzeSegment(content, file, { tNames });
842
- parseError ??= segment.error;
843
- for (const name of segment.renamed) renamed.add(name);
844
- merge(segment.analysis, offset, false);
845
- };
846
- const frontmatter = file.endsWith(".astro") ? FRONTMATTER_RE.exec(code) : null;
847
- if (frontmatter?.[2]) block(frontmatter[2], frontmatter[1].length);
848
- for (const match of code.matchAll(SCRIPT_RE)) {
849
- const content = match[2];
850
- if (content) block(content, match.index + match[1].length);
851
- }
852
- const markup = blank(blank(blank(frontmatter ? " ".repeat(frontmatter[0].length) + code.slice(frontmatter[0].length) : code, SCRIPT_RE), STYLE_RE), COMMENT_RE);
853
- const markupOptions = {
854
- tNames,
855
- renamed: [...renamed]
856
- };
857
- const ranges = file.endsWith(".vue") ? vueExpressionRanges(markup) : braceRanges(markup);
858
- let range = 0;
859
- let consumedTo = 0;
860
- for (const match of markup.matchAll(candidatePattern(svelte, renamed))) {
861
- const start = match.index;
862
- if (start < consumedTo) continue;
863
- while (range < ranges.length && ranges[range][1] <= start) range += 1;
864
- if (range >= ranges.length || start < ranges[range][0]) continue;
865
- const end = expressionExtent(markup, start, match[0].length);
866
- if (end === void 0) continue;
867
- merge(analyzeSegment(code.slice(start, end), file, markupOptions).analysis, start, true);
868
- consumedTo = end;
869
- }
870
- return {
871
- tagged,
872
- usedKeys,
873
- strayImports,
874
- missed,
875
- ...parseError && { parseError }
876
- };
877
- function merge(analysis, offset, markupSegment) {
878
- if (!analysis) return;
879
- const lines = lineAt(offset) - 1;
880
- for (const msg of analysis.tagged) tagged.push({
881
- ...msg,
882
- start: msg.start + offset,
883
- end: msg.end + offset,
884
- line: msg.line + lines,
885
- tagStart: msg.tagStart + offset,
886
- tagEnd: msg.tagEnd + offset,
887
- params: msg.params.map((p) => ({
888
- ...p,
889
- start: p.start + offset,
890
- end: p.end + offset
891
- })),
892
- ...markupSegment && { singleQuote: true }
893
- });
894
- for (const call of analysis.missed) missed.push({
895
- ...call,
896
- start: call.start + offset,
897
- line: call.line + lines
898
- });
899
- usedKeys.push(...analysis.usedKeys);
900
- strayImports.push(...analysis.strayImports);
901
- }
902
- }
903
- function candidatePattern(svelte, renamed) {
904
- const names = [.../* @__PURE__ */ new Set(["t", ...[...renamed].map((name) => name.replace(/^\$/, ""))])].map((name) => name.replace(/[$]/g, "\\$")).join("|");
905
- return new RegExp(`(?<![\\w$])${svelte ? "\\$?" : ""}(?:${names})(?=[\`(]|\\.id\\()`, "g");
906
- }
907
- function lineCounter(code) {
908
- const breaks = [];
909
- for (let i = code.indexOf("\n"); i !== -1; i = code.indexOf("\n", i + 1)) breaks.push(i);
910
- return (offset) => {
911
- let low = 0;
912
- let high = breaks.length;
913
- while (low < high) {
914
- const mid = low + high >> 1;
915
- if (breaks[mid] < offset) low = mid + 1;
916
- else high = mid;
917
- }
918
- return low + 1;
919
- };
920
- }
921
- function analyzeSegment(code, file, options) {
922
- try {
923
- return analyzeScript(code, file, options);
924
- } catch (error) {
925
- return {
926
- renamed: [],
927
- error: parseErrorMessage(error)
928
- };
929
- }
930
- }
931
- function blank(source, re) {
932
- return source.replace(re, (m) => " ".repeat(m.length));
933
- }
934
- function braceRanges(markup) {
935
- const ranges = [];
936
- let i = 0;
937
- while (i < markup.length) {
938
- if (markup[i] === "{") {
939
- const end = balancedEnd(markup, i);
940
- if (end !== void 0) {
941
- ranges.push([i + 1, end - 1]);
942
- i = end;
943
- continue;
944
- }
945
- }
946
- i += 1;
947
- }
948
- return ranges;
949
- }
950
- function vueExpressionRanges(markup) {
951
- const ranges = [];
952
- for (const match of markup.matchAll(MUSTACHE_RE)) ranges.push([match.index + 2, match.index + match[0].length - 2]);
953
- for (const match of markup.matchAll(DIRECTIVE_RE)) {
954
- const valueStart = match.index + match[0].length - match[1].length + 1;
955
- ranges.push([valueStart, valueStart + match[1].length - 2]);
956
- }
957
- return ranges.sort((a, b) => a[0] - b[0]);
958
- }
959
- function expressionExtent(code, start, nameLength) {
960
- const i = start + nameLength;
961
- if (code.startsWith(".id(", i)) {
962
- const close = balancedEnd(code, i + 3);
963
- if (close === void 0 || code[close] !== "`") return void 0;
964
- return balancedEnd(code, close);
965
- }
966
- if (code[i] === "`" || code[i] === "(") return balancedEnd(code, i);
967
- }
968
- function balancedEnd(code, open) {
969
- const stack = [];
970
- let i = open;
971
- while (i < code.length) {
972
- const ch = code[i];
973
- if (stack[stack.length - 1] === "`") {
974
- if (ch === "\\") i += 1;
975
- else if (ch === "`") stack.pop();
976
- else if (ch === "$" && code[i + 1] === "{") {
977
- stack.push("{");
978
- i += 1;
979
- }
980
- } else if (ch === "'" || ch === "\"") i = stringEnd(code, i);
981
- else if (ch === "`" || ch === "(" || ch === "{") stack.push(ch);
982
- else if (ch === ")" || ch === "}") {
983
- if (stack[stack.length - 1] !== (ch === ")" ? "(" : "{")) return void 0;
984
- stack.pop();
985
- }
986
- i += 1;
987
- if (stack.length === 0) return i;
988
- }
989
- }
990
- function stringEnd(code, start) {
991
- const quote = code[start];
992
- let i = start + 1;
993
- while (i < code.length) if (code[i] === "\\") i += 2;
994
- else if (code[i] === quote) return i;
995
- else i += 1;
996
- return code.length;
997
- }
998
- //#endregion
999
- //#region src/extract.ts
1000
- const kept = /* @__PURE__ */ new WeakMap();
1001
- async function extractProject(cfg, options = {}) {
1002
- const files = await glob(cfg.include, {
1003
- cwd: cfg.root,
1004
- ignore: cfg.exclude,
1005
- absolute: true
1006
- });
1007
- const registry = new MessageRegistry();
1008
- const read = options.keepSource ? /* @__PURE__ */ new Map() : null;
1009
- for (const file of files.sort()) {
1010
- const code = readFileSync(file, "utf8");
1011
- const analysis = analyzeFile(code, file);
1012
- registry.update(file, analysis);
1013
- read?.set(file.replaceAll("\\", "/"), {
1014
- code,
1015
- analysis
1016
- });
1017
- }
1018
- if (read) kept.set(registry, read);
1019
- return registry;
1020
- }
1021
- function scannedAnalysis(scan, file, code) {
1022
- const read = kept.get(scan);
1023
- const key = file.replaceAll("\\", "/");
1024
- const entry = read?.get(key);
1025
- read?.delete(key);
1026
- return entry?.code === code ? entry.analysis : void 0;
1027
- }
1028
- async function collectOrigins(cfg, reuse) {
1029
- const registry = reuse ?? await extractProject(cfg);
1030
- const origins = Object.create(null);
1031
- for (const [key, files] of registry.origins()) origins[key] = files.map((file) => relative(cfg.root, file).replaceAll("\\", "/"));
1032
- return origins;
1033
- }
1034
- function syncCatalogs(cfg, catalogs, registry) {
1035
- const added = {};
1036
- const replaced = [];
1037
- const source = catalogs[cfg.sourceLocale] ??= emptyCatalog();
1038
- for (const [key, msg] of registry.messages()) {
1039
- const before = own(source, key);
1040
- if (before === msg.message) continue;
1041
- source[key] = msg.message;
1042
- if (before) replaced.push({
1043
- key,
1044
- before
1045
- });
1046
- else (added[cfg.sourceLocale] ??= []).push(key);
1047
- }
1048
- const needed = Object.keys(source);
1049
- for (const locale of cfg.locales) {
1050
- if (locale === cfg.sourceLocale) continue;
1051
- const catalog = catalogs[locale] ??= emptyCatalog();
1052
- for (const key of needed) if (own(catalog, key) === void 0) {
1053
- catalog[key] = "";
1054
- (added[locale] ??= []).push(key);
1055
- }
1056
- }
1057
- return {
1058
- added,
1059
- replaced
1060
- };
1061
- }
1062
- function shippedCatalogs(cfg, catalogs, registry, options = {}) {
1063
- const source = Object.assign(emptyCatalog(), flatten(catalogs[cfg.sourceLocale] ?? {}));
1064
- for (const [key, msg] of registry.messages()) if (options.newKeys !== false || own(source, key) !== void 0) source[key] = msg.message;
1065
- return {
1066
- ...catalogs,
1067
- [cfg.sourceLocale]: source
1068
- };
1069
- }
1070
- function pruneCatalogs(cfg, catalogs, registry) {
1071
- const removed = {};
1072
- if (registry.parseErrors().length > 0) return removed;
1073
- const keep = /* @__PURE__ */ new Set([...registry.messages().keys(), ...registry.usedKeys().keys()]);
1074
- for (const locale of cfg.locales) {
1075
- const catalog = catalogs[locale];
1076
- if (!catalog) continue;
1077
- for (const key of Object.keys(catalog)) if (!keep.has(key)) {
1078
- delete catalog[key];
1079
- (removed[locale] ??= []).push(key);
1080
- }
1081
- }
1082
- return removed;
1083
- }
1084
- //#endregion
1085
- //#region src/validate.ts
1086
- let remembered = /* @__PURE__ */ new Map();
1087
- let reading;
1088
- function read(message) {
1089
- if (!reading) return parse(message, parseIcu);
1090
- let tree = reading.get(message);
1091
- if (!tree) {
1092
- tree = remembered.get(message) ?? parse(message, parseIcu);
1093
- reading.set(message, tree);
1094
- }
1095
- return tree;
1096
- }
1097
- function gatePass(run) {
1098
- reading = /* @__PURE__ */ new Map();
1099
- try {
1100
- return run();
1101
- } finally {
1102
- remembered = reading;
1103
- reading = void 0;
1104
- }
1105
- }
1106
- const PLURAL_CATEGORIES = /* @__PURE__ */ new Set([
1107
- "zero",
1108
- "one",
1109
- "two",
1110
- "few",
1111
- "many"
1112
- ]);
1113
- const EXACT = /^=\d+$/;
1114
- function shapes(message) {
1115
- const out = /* @__PURE__ */ new Map();
1116
- walk(read(message), out);
1117
- return out;
1118
- }
1119
- function walk(nodes, out) {
1120
- for (const node of nodes) {
1121
- if (node.kind !== "param" || !node.variants) continue;
1122
- const selectors = node.variants.map(([key]) => key);
1123
- if (!out.has(node.name)) out.set(node.name, {
1124
- selectors,
1125
- plural: selectors.some((key) => PLURAL_CATEGORIES.has(key)),
1126
- ordinal: node.ordinal === true
1127
- });
1128
- for (const [, body] of node.variants) walk(body, out);
1129
- }
1130
- }
1131
- function paramNames(message) {
1132
- const names = /* @__PURE__ */ new Set();
1133
- collect(read(message), names);
1134
- return [...names].sort();
1135
- }
1136
- function collect(nodes, out) {
1137
- for (const node of nodes) {
1138
- if (node.kind !== "param") continue;
1139
- out.add(node.name);
1140
- if (node.variants) for (const [, body] of node.variants) collect(body, out);
1141
- }
1142
- }
1143
- const TAG = /<(\/?)([a-zA-Z][\w-]*)\s*(\/?)>/g;
1144
- const BREAK = /^(?:br|wbr)$/;
1145
- function markupNames(message) {
1146
- const out = /* @__PURE__ */ new Set();
1147
- for (const match of message.matchAll(TAG)) if (match[1] || match[3] || BREAK.test(match[2])) out.add(match[2]);
1148
- return out;
1149
- }
1150
- function tagTokens(message, markup) {
1151
- const out = [];
1152
- for (const [, closing, name, selfClose] of message.matchAll(TAG)) {
1153
- if (!markup.has(name)) continue;
1154
- if (!BREAK.test(name)) out.push(`${closing}${name}${selfClose}`);
1155
- else if (!closing) out.push(`${name}/`);
1156
- }
1157
- return out.sort();
1158
- }
1159
- function surplus(a, b) {
1160
- const rest = [...b];
1161
- const out = [];
1162
- for (const item of a) {
1163
- const at = rest.indexOf(item);
1164
- if (at < 0) out.push(item);
1165
- else rest.splice(at, 1);
1166
- }
1167
- return out;
1168
- }
1169
- function list(items) {
1170
- return items.length > 1 ? `${items.slice(0, -1).join(", ")} and ${items[items.length - 1]}` : items[0];
1171
- }
1172
- const ESCAPED_SYNTAX = /(?<!\{)\{\{\s*([\w.]+)(\s*[|:][^{}]*)\}\}/;
1173
- const ESCAPED_ICU = /(?<!\{)\{\{\s*([\w.]+)\s*,\s*(plural|selectordinal|select|number|date|time)\b/;
1174
- const ICU_SLICE = /^\{\{([\w.]+), (\w+), …\}\}$/;
1175
- const ESCAPED_OPEN = /(?<!\{)\{\{\{([\w.]+)\}(\s*\|\s*[^\s|{}:]+\s*:|:[A-Za-z_][\w-]*)/;
1176
- function escapedSyntax(message) {
1177
- const icu = ESCAPED_ICU.exec(message);
1178
- if (icu) return `{{${icu[1]}, ${icu[2]}, …}}`;
1179
- const open = ESCAPED_OPEN.exec(message);
1180
- if (open) return `{\${${open[1]}}${open[2]}…`;
1181
- return ESCAPED_SYNTAX.exec(message)?.[0];
1182
- }
1183
- function shownSlice(slice) {
1184
- return slice.startsWith("{{") ? slice.slice(1, -1) : slice;
1185
- }
1186
- function inlineBlock(slice) {
1187
- if (slice.startsWith("{${")) return "the same block with its closing }";
1188
- const icu = ICU_SLICE.exec(slice);
1189
- if (icu) {
1190
- const [, name = "", type = ""] = icu;
1191
- if (type === "plural") return `{\${${name}} | one: … | other: …}`;
1192
- if (type === "select") return `{\${${name}} | …: … | other: …}`;
1193
- if (type === "selectordinal") return "t(key, params), with the ICU message in the catalog";
1194
- return `{\${${name}}:${type}}`;
1195
- }
1196
- const match = ESCAPED_SYNTAX.exec(slice);
1197
- if (!match) return slice;
1198
- const [, name = "", tail = ""] = match;
1199
- return `{\${${name}}${tail.trimStart().startsWith(":") ? `:${tail.trimStart().slice(1).trimStart()}` : tail}}`;
1200
- }
1201
- function validateMessage(message, locale) {
1202
- const issues = [];
1203
- for (const [name, shape] of shapes(message)) {
1204
- if (!shape.plural) continue;
1205
- if (!shape.selectors.includes("other")) {
1206
- issues.push({
1207
- severity: "error",
1208
- message: `the plural block for {${name}} has no "other" case, so any count it does not list renders empty`
1209
- });
1210
- continue;
1211
- }
1212
- if (!locale) continue;
1213
- const missing = reachableCategories(locale, shape.ordinal).filter((category) => category !== "other" && !shape.selectors.includes(category));
1214
- if (missing.length > 0) issues.push({
1215
- severity: "warning",
1216
- message: `${locale} also needs the ${list(missing)} plural ${missing.length > 1 ? "forms" : "form"} for {${name}}`
1217
- });
1218
- }
1219
- return issues;
1220
- }
1221
- function validatePair(source, translated) {
1222
- const issues = [];
1223
- const lostParams = surplus(paramNames(source), paramNames(translated));
1224
- const newParams = surplus(paramNames(translated), paramNames(source));
1225
- if (lostParams.length > 0) issues.push({
1226
- severity: "error",
1227
- message: `${list(lostParams.map((name) => `{${name}}`))} ${lostParams.length > 1 ? "are" : "is"} missing, so ${lostParams.length > 1 ? "their values never reach" : "its value never reaches"} the text`
1228
- });
1229
- if (newParams.length > 0) issues.push({
1230
- severity: "error",
1231
- message: `${list(newParams.map((name) => `{${name}}`))} ${newParams.length > 1 ? "are" : "is"} not in the source message, so ${newParams.length > 1 ? "they render" : "it renders"} as literal text`
1232
- });
1233
- const markup = /* @__PURE__ */ new Set([...markupNames(source), ...markupNames(translated)]);
1234
- const lostTags = tagReport(surplus(tagTokens(source, markup), tagTokens(translated, markup)));
1235
- const newTags = tagReport(surplus(tagTokens(translated, markup), tagTokens(source, markup)));
1236
- if (lostTags.length > 0) issues.push({
1237
- severity: "error",
1238
- message: `${list(lostTags)} ${lostTags.length > 1 ? "are" : "is"} missing from the translation`
1239
- });
1240
- if (newTags.length > 0) issues.push({
1241
- severity: "error",
1242
- message: `${list(newTags)} ${newTags.length > 1 ? "are" : "is"} not in the source message`
1243
- });
1244
- const target = shapes(translated);
1245
- for (const [name, shape] of shapes(source)) {
1246
- const other = target.get(name);
1247
- if (!other) {
1248
- issues.push({
1249
- severity: "error",
1250
- message: `the ${shape.plural ? "plural" : "select"} block for {${name}} was flattened into plain text`
1251
- });
1252
- continue;
1253
- }
1254
- if (shape.selectors.includes("other") && !other.selectors.includes("other") && !other.plural) issues.push({
1255
- severity: "error",
1256
- message: `the "other" case for {${name}} is missing, so unlisted values render empty`
1257
- });
1258
- const lostExact = shape.selectors.filter((key) => EXACT.test(key)).filter((key) => !other.selectors.includes(key));
1259
- if (lostExact.length > 0) issues.push({
1260
- severity: "warning",
1261
- message: `the ${list(lostExact)} ${lostExact.length > 1 ? "cases" : "case"} for {${name}} ${lostExact.length > 1 ? "are" : "is"} missing, so ${lostExact.length > 1 ? "those counts" : "that count"} falls back to "other"`
1262
- });
1263
- }
1264
- return issues;
1265
- }
1266
- function tagReport(tokens) {
1267
- const out = [];
1268
- const seen = /* @__PURE__ */ new Set();
1269
- for (const token of tokens) {
1270
- const name = token.replaceAll("/", "");
1271
- if (seen.has(name)) continue;
1272
- seen.add(name);
1273
- out.push(token.endsWith("/") ? `<${name}/>` : `<${name}>`);
1274
- }
1275
- return out;
1276
- }
1277
- const COUNT_PROBE = 200;
1278
- const reachable = /* @__PURE__ */ new Map();
1279
- function reachableCategories(locale, ordinal) {
1280
- const type = ordinal ? "ordinal" : "cardinal";
1281
- const cacheKey = `${locale}\u0000${type}`;
1282
- const hit = reachable.get(cacheKey);
1283
- if (hit) return hit;
1284
- let out;
1285
- try {
1286
- const rules = new Intl.PluralRules(locale.replace(/_/g, "-"), { type });
1287
- const seen = /* @__PURE__ */ new Set();
1288
- for (let n = 0; n <= COUNT_PROBE; n++) seen.add(rules.select(n));
1289
- out = [...seen];
1290
- } catch {
1291
- out = [];
1292
- }
1293
- reachable.set(cacheKey, out);
1294
- return out;
1295
- }
1296
- //#endregion
1297
- //#region src/params.ts
1298
- const NUMBER_FORMATS = /* @__PURE__ */ new Set([
1299
- "number",
1300
- "integer",
1301
- "percent",
1302
- "currency"
1303
- ]);
1304
- const DATE_FORMATS = /* @__PURE__ */ new Set(["date", "time"]);
1305
- function collectParams(message) {
1306
- const out = /* @__PURE__ */ new Map();
1307
- visit(parse(message, parseIcu), out);
1308
- return out;
1309
- }
1310
- function visit(nodes, out) {
1311
- for (const node of nodes) {
1312
- if (node.kind !== "param") continue;
1313
- const types = out.get(node.name) ?? /* @__PURE__ */ new Set();
1314
- out.set(node.name, types);
1315
- if (node.variants) {
1316
- for (const [key, body] of node.variants) {
1317
- if (PLURAL_CATEGORIES.has(key) || /^=\d+$/.test(key)) types.add("number");
1318
- else if (key !== "other") types.add("string");
1319
- visit(body, out);
1320
- }
1321
- if (types.size === 0) types.add("string");
1322
- } else if (node.format && NUMBER_FORMATS.has(node.format)) types.add("number");
1323
- else if (node.format && DATE_FORMATS.has(node.format)) types.add("date");
1324
- else types.add("unknown");
1325
- }
1326
- }
1327
- function renderParamType(types) {
1328
- if (types.has("unknown") || types.size === 0) return "unknown";
1329
- const members = /* @__PURE__ */ new Set();
1330
- if (types.has("number")) members.add("number");
1331
- if (types.has("string")) members.add("string");
1332
- if (types.has("date")) for (const m of [
1333
- "Date",
1334
- "number",
1335
- "string"
1336
- ]) members.add(m);
1337
- return [...members].join(" | ");
1338
- }
1339
- //#endregion
1340
- //#region src/tsconfig.ts
1341
- function readTsconfig(root) {
1342
- const path = join(root, "tsconfig.json");
1343
- let text;
1344
- try {
1345
- text = readFileSync(path, "utf8");
1346
- } catch {
1347
- return "no-tsconfig";
1348
- }
1349
- const errors = [];
1350
- const json = parse$2(text, errors, { allowTrailingComma: true });
1351
- if (errors.length > 0 || typeof json !== "object" || json === null || Array.isArray(json)) return "unreadable";
1352
- return {
1353
- path,
1354
- text,
1355
- json
1356
- };
1357
- }
1358
- function covered(list, entry) {
1359
- if (!Array.isArray(list)) return false;
1360
- return list.some((item) => {
1361
- if (typeof item !== "string") return false;
1362
- const pattern = item.replace(/^\.\//, "").replace(/\/+$/, "");
1363
- return picomatch(pattern)(entry) || picomatch(`${pattern}/**/*`)(entry);
1364
- });
1365
- }
1366
- function formatting(text) {
1367
- const indent = /\n([ \t]+)\S/.exec(text)?.[1] ?? " ";
1368
- return {
1369
- insertSpaces: !indent.startsWith(" "),
1370
- tabSize: indent.startsWith(" ") ? 1 : indent.length,
1371
- eol: text.includes("\r\n") ? "\r\n" : "\n"
1372
- };
1373
- }
1374
- function typesIncluded(root, file) {
1375
- const read = readTsconfig(root);
1376
- if (typeof read === "string") return read;
1377
- const entry = relative(root, file).replaceAll("\\", "/");
1378
- const { include, files } = read.json;
1379
- if (covered(include, entry) || covered(files, entry)) return "present";
1380
- return "missing";
1381
- }
1382
- function includeTypes(root, file) {
1383
- const read = readTsconfig(root);
1384
- if (typeof read === "string") return read;
1385
- const entry = relative(root, file).replaceAll("\\", "/");
1386
- const { include, files } = read.json;
1387
- if (covered(include, entry) || covered(files, entry)) return "present";
1388
- const options = { formattingOptions: formatting(read.text) };
1389
- const edits = Array.isArray(include) ? modify(read.text, ["include", -1], entry, {
1390
- ...options,
1391
- isArrayInsertion: true
1392
- }) : Array.isArray(files) && include === void 0 ? modify(read.text, ["files", -1], entry, {
1393
- ...options,
1394
- isArrayInsertion: true
1395
- }) : modify(read.text, ["include"], ["**/*", entry], options);
1396
- writeFileSync(read.path, applyEdits(read.text, edits));
1397
- return "added";
1398
- }
1399
- //#endregion
1400
- //#region src/warn.ts
1401
- const warned = /* @__PURE__ */ new Set();
1402
- function warnOnce(message, dedupeKey = message) {
1403
- if (warned.has(dedupeKey)) return;
1404
- warned.add(dedupeKey);
1405
- console.warn(`[verbaly] ${message}`);
1406
- }
1407
- function warnParseError(file, message) {
1408
- warnOnce(`${file}: could not be parsed (${message}), its messages were not extracted`);
1409
- }
1410
- const DTS_HEADER = "// generated by verbaly: do not edit";
1411
- const SLICE_HELPERS = `function readSlice(root, path) {
1412
- const locale = readPath({ supported: locales, path });
1413
- if (!locale || locale === sourceLocale) return undefined;
1414
- const messages = inlineMessages(root);
1415
- return messages ? { locale, messages } : undefined;
1416
- }
1417
-
1418
- export function adoptPage(options) {
1419
- const slice = readSlice(options?.root, options?.path);
1420
- if (slice) v.addMessages(slice.locale, slice.messages, { partial: true });
1421
- return slice ? slice.locale : undefined;
1422
- }
1423
-
1424
- `;
1425
- function generateRuntimeModule(cfg, options = {}) {
1426
- const importPath = options.localeImport ?? ((locale) => `virtual:verbaly/locale/${locale}`);
1427
- const others = cfg.locales.filter((locale) => locale !== cfg.sourceLocale);
1428
- const src = JSON.stringify(cfg.sourceLocale);
1429
- const loaders = others.map((locale) => ` ${JSON.stringify(locale)}: () => import('${importPath(locale)}'),`).join("\n");
1430
- const icu = options.icu ? ",\n parseIcu" : "";
1431
- const rel = options.relative ? ",\n relativeFormatter" : "";
1432
- const slice = options.inlineCatalog ? ",\n inlineMessages" : "";
1433
- const slices = options.inlineCatalog ? SLICE_HELPERS : "";
1434
- return `import {
1435
- createVerbaly,
1436
- localeFromPath as readPath,
1437
- localePath as writePath,
1438
- switchLocale as runSwitch${icu}${rel}${slice},
1439
- } from 'verbaly';
1440
- import source from '${importPath(cfg.sourceLocale)}';
1441
-
1442
- export const sourceLocale = ${src};
1443
- export const locales = ${JSON.stringify(cfg.locales)};
1444
- export const routing = ${JSON.stringify(cfg.routing)};
1445
-
1446
- // bound to this project: the locale set, the source and the routing mode are never passed in
1447
- export function localePath(locale, options) {
1448
- return writePath(locale, { ...options, supported: locales, sourceLocale, routing });
1449
- }
1450
-
1451
- export function localeFromPath(options) {
1452
- return readPath({ ...options, supported: locales });
1453
- }
1454
-
1455
- // identity: it exists so the compiler can see keys that live in a module instead of at a call site
1456
- export function defineKeys(keys) {
1457
- return keys;
1458
- }
1459
-
1460
- // the whole switch a language control needs, in either mode: catalog or navigation, then persistence
1461
- export function switchLocale(locale, options) {
1462
- return runSwitch(v, locale, { supported: locales, sourceLocale, routing, ...options });
1463
- }
1464
-
1465
- const localeLoaders = {
1466
- ${loaders}
1467
- };
1468
-
1469
- // raw catalog access: SSR integrations serialize it across the client boundary
1470
- export async function loadMessages(locale) {
1471
- if (locale === ${src}) return source;
1472
- // own entries only: a locale named constructor must be a miss, not the Object function
1473
- const loader = Object.prototype.hasOwnProperty.call(localeLoaders, locale)
1474
- ? localeLoaders[locale]
1475
- : undefined;
1476
- return loader ? (await loader()).default : {};
1477
- }
1478
-
1479
- ${slices}// per-request/per-instance factory (SSR): the singleton below is browser/SPA-only
1480
- export function createInstance(options) {${options.inlineCatalog ? "\n const page = readSlice();" : ""}
1481
- return createVerbaly({
1482
- locale: ${options.inlineCatalog ? `page ? page.locale : ${src}` : src},
1483
- fallback: ${src},
1484
- messages: ${options.inlineCatalog ? `page ? { [${src}]: source, [page.locale]: page.messages } : { [${src}]: source }` : `{ [${src}]: source }`},
1485
- loaders: localeLoaders,${options.inlineCatalog ? "\n partial: page ? [page.locale] : undefined," : ""}${options.icu ? "\n icu: parseIcu," : ""}
1486
- ...options,${options.relative ? "\n // merged, not spread over: passing your own formatters must not drop this one\n formatters: { relative: relativeFormatter, ...options?.formatters }," : ""}
1487
- });
1488
- }
1489
-
1490
- // the no-FOUC contract in one call: fresh instance + catalog awaited before render
1491
- export async function createRequestInstance(locale) {
1492
- const instance = createInstance({ locale });
1493
- await instance.loadLocale(locale);
1494
- return instance;
1495
- }
1496
-
1497
- const v = createInstance();
1498
-
1499
- // a hook with no provider above it (a test, a story) reads this one; a server never registers it
1500
- if (typeof document !== 'undefined') globalThis[Symbol.for('verbaly.app')] = v;
1501
-
1502
- export const verbaly = v;
1503
- export const t = v.t;
1504
-
1505
- export function getLocale() {
1506
- return v.locale;
1507
- }
1508
-
1509
- export function subscribe(listener) {
1510
- return v.subscribe(listener);
1511
- }
1512
-
1513
- export async function setLocale(locale) {
1514
- await v.loadLocale(locale);
1515
- v.setLocale(locale);
1516
- }
1517
- ${options.extraExports ?? ""}`;
1518
- }
1519
- function generateLocaleModule(catalog) {
1520
- return `export default ${JSON.stringify(catalog).replace(/([{,])"__proto__":/, "$1[\"__proto__\"]:")};\n`;
1521
- }
1522
- function generateDts(catalog, options = {}) {
1523
- const lines = [];
1524
- const locales = options.locales?.length ? [...options.locales].sort(byCodeUnit).map((locale) => JSON.stringify(locale)).join(" | ") : "string";
1525
- for (const [key, message] of Object.entries(catalog).sort(([a], [b]) => byCodeUnit(a, b))) {
1526
- const params = collectParams(message);
1527
- if (params.size === 0) lines.push(` ${JSON.stringify(key)}: never;`);
1528
- else {
1529
- const fields = [...params.entries()].map(([name, types]) => `${JSON.stringify(name)}: ${renderParamType(types)}`).join("; ");
1530
- lines.push(` ${JSON.stringify(key)}: { ${fields} };`);
1531
- }
1532
- }
1533
- return `${DTS_HEADER}
1534
- // biome-ignore-all lint: generated by verbaly
1535
- // biome-ignore-all format: generated by verbaly
1536
- // prettier-ignore
1537
- declare module 'virtual:verbaly' {
1538
- export interface VerbalyMessages {
1539
- ${lines.join("\n")}
1540
- }
1541
- export type VerbalyKey = keyof VerbalyMessages & string;
1542
- export type VerbalyLocale = ${locales};
1543
-
1544
- export type VerbalyKeyTree = VerbalyKey | { readonly [name: string]: VerbalyKeyTree };
1545
- export function defineKeys<const T extends VerbalyKeyTree>(keys: T): T;
1546
-
1547
- export const verbaly: import('verbaly').Verbaly;
1548
-
1549
- export const sourceLocale: VerbalyLocale;
1550
- export const locales: string[];
1551
- export const routing: import('verbaly').Routing;
1552
- export function localePath(
1553
- locale: string,
1554
- options?: { path?: string; base?: string },
1555
- ): string;
1556
- export function localeFromPath(options?: {
1557
- path?: string;
1558
- base?: string;
1559
- }): string | undefined;
1560
- export function loadMessages(locale: string): Promise<Record<string, string>>;${options.inlineCatalog ? "\n export function adoptPage(options?: {\n root?: ParentNode;\n path?: string;\n }): string | undefined;" : ""}
1561
- export function createInstance(
1562
- options?: import('verbaly').VerbalyOptions,
1563
- ): import('verbaly').Verbaly;
1564
- export function createRequestInstance(locale: string): Promise<import('verbaly').Verbaly>;
1565
-
1566
- // a literal key must exist; a string, a template with data in it or a union of keys is data
1567
- export const t: {
1568
- <K extends VerbalyKey | TemplateStringsArray | (string & {})>(
1569
- first: K extends TemplateStringsArray
1570
- ? K
1571
- : {} extends Record<K & string, 1>
1572
- ? K
1573
- : K extends VerbalyKey ? K : VerbalyKey,
1574
- ...rest: [K] extends [never]
1575
- ? [params?: import('verbaly').Params]
1576
- : [K] extends [(K extends unknown ? (key: K) => void : never) extends (key: infer One) => void ? One : never]
1577
- ? K extends TemplateStringsArray
1578
- ? unknown[]
1579
- : {} extends Record<K & string, 1>
1580
- ? [params?: import('verbaly').Params]
1581
- : K extends VerbalyKey
1582
- ? [VerbalyMessages[K]] extends [never] ? [] : [VerbalyMessages[K]]
1583
- : unknown[]
1584
- : [params?: import('verbaly').Params]
1585
- ): string;
1586
- id(key: string): (strings: TemplateStringsArray, ...values: unknown[]) => string;
1587
- };
1588
-
1589
- export function setLocale(locale: string): Promise<void>;
1590
- export function switchLocale(
1591
- locale: string,
1592
- options?: Omit<
1593
- import('verbaly').SwitchLocaleOptions,
1594
- 'routing' | 'supported' | 'sourceLocale'
1595
- >,
1596
- ): Promise<void>;
1597
- export function getLocale(): string;
1598
- export function subscribe(listener: () => void): () => void;
1599
-
1600
- // nested, so it augments verbaly: at the top of a script it would replace the real module
1601
- module 'verbaly' {
1602
- interface Register {
1603
- t: typeof t;
1604
- locale: VerbalyLocale;
1605
- }
1606
- }
1607
- }
1608
-
1609
- // prettier-ignore
1610
- declare module 'virtual:verbaly/locale/*' {
1611
- const messages: Record<string, string>;
1612
- export default messages;
1613
- }
1614
- `;
1615
- }
1616
- function projectDtsOptions(cfg) {
1617
- return {
1618
- inlineCatalog: cfg.render.inlineCatalog === true,
1619
- locales: cfg.locales
1620
- };
1621
- }
1622
- function writeDts(cfg, catalog, file) {
1623
- const target = file === void 0 ? cfg.dts : file;
1624
- if (target === false) return void 0;
1625
- let existing;
1626
- try {
1627
- existing = readFileSync(target, "utf8");
1628
- } catch {}
1629
- const content = withLineEndings(generateDts(catalog, projectDtsOptions(cfg)), existing);
1630
- const changed = existing !== content;
1631
- if (changed) {
1632
- mkdirSync(dirname(target), { recursive: true });
1633
- writeFileSync(target, content);
1634
- }
1635
- removeRootDts(cfg, target);
1636
- if (resolve(target).startsWith(resolve(cfg.root, ".verbaly") + sep)) {
1637
- const ignore = join(cfg.root, ".verbaly", ".gitignore");
1638
- if (!existsSync(ignore)) writeFileSync(ignore, "*\n");
1639
- const state = includeTypes(cfg.root, target);
1640
- const entry = relative(cfg.root, target).replaceAll("\\", "/");
1641
- if (state === "added") warnOnce(`added "${entry}" to the include of tsconfig.json, so TypeScript reads the types`);
1642
- else if (state === "unreadable") warnOnce(`tsconfig.json could not be read, so add "${entry}" to its include yourself`);
1643
- }
1644
- return {
1645
- file: target,
1646
- changed
1647
- };
1648
- }
1649
- function removeRootDts(cfg, target) {
1650
- const old = join(cfg.root, "verbaly.d.ts");
1651
- if (resolve(target) === resolve(old)) return;
1652
- let head;
1653
- try {
1654
- head = readFileSync(old, "utf8").slice(0, 36);
1655
- } catch {
1656
- return;
1657
- }
1658
- if (head !== "// generated by verbaly: do not edit") return;
1659
- rmSync(old);
1660
- warnOnce(`the types live in ${relative(cfg.root, target).replaceAll("\\", "/")} now, so the verbaly.d.ts Verbaly wrote at the root was removed`);
1661
- }
1662
- //#endregion
1663
- //#region src/findings.ts
1664
- function siteOf(msg) {
1665
- return {
1666
- file: msg.file,
1667
- line: msg.line,
1668
- message: msg.message
1669
- };
1670
- }
1671
- function collisionEntries(registry) {
1672
- return registry.collisions().map(({ key, kept, dropped }) => ({
1673
- key,
1674
- sites: [kept, ...dropped].map(siteOf)
1675
- }));
1676
- }
1677
- function scanFindings(cfg, registry, replaced = []) {
1678
- const messages = registry.messages();
1679
- const out = [];
1680
- for (const { key, before } of replaced) {
1681
- const msg = messages.get(key);
1682
- if (msg) out.push({
1683
- kind: "replaced",
1684
- locale: cfg.sourceLocale,
1685
- key,
1686
- before,
1687
- site: siteOf(msg)
1688
- });
1689
- }
1690
- for (const entry of collisionEntries(registry)) out.push({
1691
- kind: "collision",
1692
- ...entry
1693
- });
1694
- for (const { name, file, line } of registry.missed()) out.push({
1695
- kind: "renamed",
1696
- name,
1697
- file,
1698
- line
1699
- });
1700
- for (const msg of messages.values()) {
1701
- const params = msg.params.map((param) => param.name).filter((name) => /^_\d+$/.test(name));
1702
- if (params.length > 0) out.push({
1703
- kind: "positional",
1704
- params,
1705
- site: siteOf(msg)
1706
- });
1707
- const slice = escapedSyntax(msg.message);
1708
- if (slice) out.push({
1709
- kind: "escaped",
1710
- slice,
1711
- site: siteOf(msg)
1712
- });
1713
- }
1714
- for (const { file, message } of registry.parseErrors()) out.push({
1715
- kind: "unparsed",
1716
- file,
1717
- message
1718
- });
1719
- return out;
1720
- }
1721
- function sourcePlace(at, root) {
1722
- const file = root ? relative(root, at.file).replaceAll("\\", "/") : at.file;
1723
- return at.line ? `${file}:${at.line}` : file;
1724
- }
1725
- function quoted(at, root) {
1726
- return `"${truncate(at.message, 40)}" (${sourcePlace(at, root)})`;
1727
- }
1728
- function formatCollision({ key, sites }, root) {
1729
- const [kept, ...others] = sites;
1730
- const texts = new Set(sites.map((at) => at.message)).size;
1731
- return `${key}: one key with ${counted(texts, "text")}, and every place shows ${quoted(kept, root)}, never ${others.map((at) => quoted(at, root)).join(" or ")}: give each text its own key`;
1732
- }
1733
- function formatFinding(finding, root) {
1734
- switch (finding.kind) {
1735
- case "collision": return formatCollision(finding, root);
1736
- case "replaced": {
1737
- const place = sourcePlace(finding.site, root);
1738
- return finding.edited ? `${finding.locale}.json: your edit of "${finding.key}" was replaced, its text lives in ${place}: change it there` : `${finding.locale}: ${finding.key} follows the code (${place}): "${truncate(finding.site.message, 40)}", was "${truncate(finding.before, 40)}"`;
1739
- }
1740
- case "renamed": return `${sourcePlace(finding, root)}: ${finding.name}\`…\` is never extracted, so it stays in the source language: name it t`;
1741
- case "positional": {
1742
- const names = finding.params.map((name) => `{${name}}`).join(", ");
1743
- return `${sourcePlace(finding.site, root)}: ${names} in "${truncate(finding.site.message, 60)}" reaches the translator without a name, put the value in a named variable first`;
1744
- }
1745
- case "escaped": return `${sourcePlace(finding.site, root)}: ${shownSlice(finding.slice)} renders as literal text: write ${inlineBlock(finding.slice)}`;
1746
- case "unparsed": return `${sourcePlace(finding, root)}: could not be parsed (${finding.message}), its messages were not extracted`;
1747
- case "outdated": return `[${finding.locale}] ${finding.key}: translated from an older source text, update it or keep it with \`npx verbaly review --approve\``;
1748
- case "lock": {
1749
- const lock = sourcePlace(finding, root);
1750
- if (finding.merged) return `${lock} had a merge conflict and now holds both sides, drafts and stamps included: add it to the commit that resolves the merge`;
1751
- return finding.from ? `${sourcePlace({ file: finding.from }, root)} moved to ${lock}, next to your config: commit both changes` : `${lock} now keeps the source text each translation was made for and which ones are drafts: commit it with your catalogs`;
1752
- }
1753
- }
1754
- }
1755
- function findingId(finding) {
1756
- switch (finding.kind) {
1757
- case "collision":
1758
- case "replaced": return `${finding.kind}:${finding.key}`;
1759
- case "outdated": return `outdated:${finding.locale}:${finding.key}`;
1760
- case "renamed": return `renamed:${finding.file}:${finding.name}`;
1761
- case "positional": return `positional:${finding.site.file}:${finding.params.join(",")}`;
1762
- case "escaped": return `escaped:${finding.site.file}:${finding.slice}`;
1763
- case "unparsed": return `unparsed:${finding.file}`;
1764
- case "lock": return `lock:${finding.merged ? "merged:" : ""}${finding.file}`;
1765
- }
1766
- }
1767
- function createDevReporter(root, print = (line) => console.warn(`[verbaly] ${line}`), cap = 5) {
1768
- const shown = /* @__PURE__ */ new Map();
1769
- return { report(channel, findings) {
1770
- const before = shown.get(channel) ?? /* @__PURE__ */ new Set();
1771
- const now = /* @__PURE__ */ new Set();
1772
- const fresh = [];
1773
- for (const finding of findings) {
1774
- const id = findingId(finding);
1775
- if (now.has(id)) continue;
1776
- now.add(id);
1777
- if (!before.has(id)) fresh.push(finding);
1778
- }
1779
- shown.set(channel, now);
1780
- for (const finding of fresh.slice(0, cap)) print(formatFinding(finding, root));
1781
- if (fresh.length > cap) print(`and ${fresh.length - cap} more: \`npx verbaly doctor\` names them`);
1782
- } };
1783
- }
1784
- //#endregion
1785
- //#region src/state.ts
1786
- const STATE_FILE = "verbaly.lock";
1787
- const LOCK_VERSION = 1;
1788
- const README = "Written by Verbaly: the source text each translation was made for, which ones are drafts, and which languages migrate converted. Commit it with your catalogs and never edit it: deleting it marks every draft as reviewed.";
1789
- const LEGACY_STATE_FILE = ".verbaly-state.json";
1790
- const LEGACY_DRAFTS_FILE = ".verbaly-drafts.json";
1791
- const resolved = /* @__PURE__ */ new Set();
1792
- function statePath(cfg) {
1793
- return join(cfg.root, STATE_FILE);
1794
- }
1795
- function legacyPaths(cfg) {
1796
- return [join(cfg.dir, LEGACY_STATE_FILE), join(cfg.dir, LEGACY_DRAFTS_FILE)];
1797
- }
1798
- function loadState(cfg) {
1799
- const lock = readSides(statePath(cfg)) ?? [];
1800
- for (const side of lock) checkVersion(statePath(cfg), side.version);
1801
- const [legacyState = [], legacyDrafts = []] = legacyPaths(cfg).map((path) => readSides(path) ?? []);
1802
- const state = {
1803
- drafts: {},
1804
- fingerprints: {}
1805
- };
1806
- const kept = lock.length > 1 ? keptStamp(cfg) : void 0;
1807
- [...lock, ...legacyState].forEach((source, index) => {
1808
- for (const [locale, keys] of Object.entries(readDrafts(source.drafts))) markDrafts(state.drafts, locale, keys);
1809
- for (const [locale, stamps] of Object.entries(readFingerprints(source.fingerprints))) {
1810
- const into = state.fingerprints[locale] ??= emptyCatalog();
1811
- for (const [key, stamped] of Object.entries(stamps)) {
1812
- const held = own(into, key);
1813
- if (held === void 0) into[key] = stamped;
1814
- else if (index < lock.length && held !== stamped && kept?.(locale, key, stamped)) into[key] = stamped;
1815
- }
1816
- }
1817
- const migrated = readMigrated(source.migrated);
1818
- if (migrated) state.migrated = [.../* @__PURE__ */ new Set([...state.migrated ?? [], ...migrated])];
1819
- });
1820
- for (const side of legacyDrafts) for (const [locale, keys] of Object.entries(readDrafts(side))) markDrafts(state.drafts, locale, keys);
1821
- return state;
1822
- }
1823
- function keptStamp(cfg) {
1824
- const read = /* @__PURE__ */ new Map();
1825
- return (locale, key, stamped) => {
1826
- if (!read.has(locale)) try {
1827
- read.set(locale, readCatalog(cfg, locale));
1828
- } catch {
1829
- read.set(locale, void 0);
1830
- }
1831
- const translated = own(read.get(locale) ?? {}, key);
1832
- return translated !== void 0 && translationOf(stamped) === fingerprint(translated);
1833
- };
1834
- }
1835
- function stateFile(cfg) {
1836
- return [statePath(cfg), ...legacyPaths(cfg)].find((path) => existsSync(path));
1837
- }
1838
- function lockNews(cfg, before) {
1839
- const lock = statePath(cfg);
1840
- if (resolved.delete(lock)) return {
1841
- file: lock,
1842
- merged: true
1843
- };
1844
- if (before === lock || !existsSync(lock)) return void 0;
1845
- return before ? {
1846
- file: lock,
1847
- from: before
1848
- } : { file: lock };
1849
- }
1850
- function checkVersion(path, version) {
1851
- if (typeof version === "number" && version > LOCK_VERSION) throw new Error(`[verbaly] ${path} was written by a newer Verbaly (format ${version}): update @verbaly/compiler to read it`);
1852
- }
1853
- function readState(cfg) {
1854
- const marked = (readText(statePath(cfg))?.split(/\r?\n/) ?? []).some((line) => CONFLICT.start.test(line)) ? { conflict: true } : {};
1855
- try {
1856
- return {
1857
- state: loadState(cfg),
1858
- ...marked
1859
- };
1860
- } catch (error) {
1861
- return {
1862
- state: {
1863
- drafts: {},
1864
- fingerprints: {}
1865
- },
1866
- problem: error.message.replace(/^\[verbaly\] /, ""),
1867
- ...marked
1868
- };
1869
- }
1870
- }
1871
- function saveState(cfg, state) {
1872
- const fresh = serializeState(state);
1873
- const path = statePath(cfg);
1874
- const legacy = legacyPaths(cfg);
1875
- if (fresh === void 0) {
1876
- for (const file of [path, ...legacy]) rmSync(file, { force: true });
1877
- return;
1878
- }
1879
- const existing = readText(path);
1880
- if (existing === void 0) mkdirSync(cfg.root, { recursive: true });
1881
- const serialized = withLineEndings(fresh, existing ?? legacy.map(readText).find((text) => text !== void 0));
1882
- if (existing !== serialized) {
1883
- if (existing !== void 0 && conflictSides(existing)) resolved.add(path);
1884
- writeFileSync(path, serialized);
1885
- }
1886
- for (const file of legacy) rmSync(file, { force: true });
1887
- }
1888
- function readText(path) {
1889
- try {
1890
- return readFileSync(path, "utf8");
1891
- } catch {
1892
- return;
1893
- }
1894
- }
1895
- function updateState(cfg, catalogs) {
1896
- const next = refreshState(cfg, catalogs, loadState(cfg));
1897
- saveState(cfg, next);
1898
- return next;
1899
- }
1900
- function refreshState(cfg, catalogs, previous) {
1901
- const flat = flatCatalogs(catalogs);
1902
- const source = flat[cfg.sourceLocale] ?? {};
1903
- const shown = new Set(targetLocales(cfg).filter((locale) => Object.hasOwn(flat, locale) && existsSync(catalogPath(cfg, locale))));
1904
- const drafts = {};
1905
- for (const [locale, keys] of Object.entries(previous.drafts)) {
1906
- if (!shown.has(locale)) {
1907
- drafts[locale] = keys;
1908
- continue;
1909
- }
1910
- const live = keys.filter((key) => own(flat[locale], key));
1911
- if (live.length) drafts[locale] = live;
1912
- }
1913
- const fingerprints = {};
1914
- for (const [locale, stamps] of Object.entries(previous.fingerprints)) if (!shown.has(locale)) fingerprints[locale] = stamps;
1915
- for (const locale of shown) {
1916
- const stamps = refreshStamps(source, flat[locale], previous.fingerprints[locale] ?? {});
1917
- if (Object.keys(stamps).length) fingerprints[locale] = stamps;
1918
- }
1919
- return {
1920
- drafts,
1921
- fingerprints,
1922
- migrated: previous.migrated
1923
- };
1924
- }
1925
- function refreshStamps(source, catalog, before) {
1926
- const after = emptyCatalog();
1927
- for (const key of /* @__PURE__ */ new Set([...Object.keys(before), ...Object.keys(source)])) {
1928
- const translated = own(catalog, key);
1929
- if (!translated) continue;
1930
- const was = own(before, key);
1931
- if (was !== void 0 && translationOf(was) === fingerprint(translated)) {
1932
- after[key] = was;
1933
- continue;
1934
- }
1935
- const text = own(source, key);
1936
- if (text && tracked(key, text)) after[key] = stamp(text, translated);
1937
- else if (was !== void 0) after[key] = was;
1938
- }
1939
- return after;
1940
- }
1941
- function recordTranslations(cfg, source, writes) {
1942
- const state = loadState(cfg);
1943
- for (const { locale, entries, draft } of writes) {
1944
- if (entries.length === 0) continue;
1945
- const stamps = state.fingerprints[locale] ??= emptyCatalog();
1946
- for (const entry of entries) {
1947
- const from = entry.source || own(source, entry.key);
1948
- if (from && entry.text && tracked(entry.key, from)) stamps[entry.key] = stamp(from, entry.text);
1949
- }
1950
- const keys = entries.map((entry) => entry.key);
1951
- if (draft === true) markDrafts(state.drafts, locale, keys);
1952
- else if (draft === false) clearDrafts(state.drafts, locale, keys);
1953
- }
1954
- saveState(cfg, state);
1955
- return state;
1956
- }
1957
- function effectiveDrafts(drafts, catalogs) {
1958
- const out = {};
1959
- for (const [locale, keys] of Object.entries(drafts)) {
1960
- const catalog = catalogs[locale] ?? {};
1961
- const live = keys.filter((key) => own(catalog, key));
1962
- if (live.length) out[locale] = live;
1963
- }
1964
- return out;
1965
- }
1966
- function markDrafts(drafts, locale, keys) {
1967
- if (!keys.length) return;
1968
- drafts[locale] = [.../* @__PURE__ */ new Set([...drafts[locale] ?? [], ...keys])];
1969
- }
1970
- function clearDrafts(drafts, locale, keys) {
1971
- if (!drafts[locale]) return;
1972
- if (!keys) {
1973
- delete drafts[locale];
1974
- return;
1975
- }
1976
- const drop = new Set(keys);
1977
- drafts[locale] = drafts[locale].filter((key) => !drop.has(key));
1978
- if (!drafts[locale].length) delete drafts[locale];
1979
- }
1980
- function fingerprint(text) {
1981
- return stableKey(text);
1982
- }
1983
- function tracked(key, text) {
1984
- return stableKey(text) !== key;
1985
- }
1986
- function stamp(source, translated) {
1987
- return `${fingerprint(source)}.${fingerprint(translated)}`;
1988
- }
1989
- function outdatedTranslations(cfg, catalogs, fingerprints) {
1990
- const source = catalogs[cfg.sourceLocale] ?? {};
1991
- const out = [];
1992
- for (const locale of targetLocales(cfg)) {
1993
- const catalog = catalogs[locale] ?? {};
1994
- for (const [key, was] of Object.entries(fingerprints[locale] ?? {})) {
1995
- const text = own(source, key);
1996
- const translated = own(catalog, key);
1997
- if (!text || !translated) continue;
1998
- if (translationOf(was) !== fingerprint(translated)) continue;
1999
- if (sourceOf(was) !== fingerprint(text)) out.push({
2000
- locale,
2001
- key
2002
- });
2003
- }
2004
- }
2005
- return out.sort((a, b) => byCodeUnit(a.locale, b.locale) || byCodeUnit(a.key, b.key));
2006
- }
2007
- function sourceOf(stamped) {
2008
- return stamped.slice(0, stamped.indexOf("."));
2009
- }
2010
- function translationOf(stamped) {
2011
- return stamped.slice(stamped.indexOf(".") + 1);
2012
- }
2013
- function flatCatalogs(catalogs) {
2014
- const out = {};
2015
- for (const [locale, catalog] of Object.entries(catalogs)) out[locale] = flatten(catalog);
2016
- return out;
2017
- }
2018
- function serializeState(state) {
2019
- const drafts = {};
2020
- for (const locale of Object.keys(state.drafts).sort()) {
2021
- const keys = [...new Set(state.drafts[locale])].sort();
2022
- if (keys.length) drafts[locale] = keys;
2023
- }
2024
- const fingerprints = {};
2025
- for (const locale of Object.keys(state.fingerprints).sort()) {
2026
- const entries = state.fingerprints[locale] ?? {};
2027
- const keys = Object.keys(entries).sort();
2028
- if (!keys.length) continue;
2029
- fingerprints[locale] = Object.fromEntries(keys.map((key) => [key, entries[key]]));
2030
- }
2031
- const migrated = [...new Set(state.migrated ?? [])].sort();
2032
- if (!Object.keys(drafts).length && !Object.keys(fingerprints).length && !migrated.length) return;
2033
- const out = {
2034
- _readme: README,
2035
- version: LOCK_VERSION
2036
- };
2037
- if (Object.keys(drafts).length) out.drafts = drafts;
2038
- if (Object.keys(fingerprints).length) out.fingerprints = fingerprints;
2039
- if (migrated.length) out.migrated = migrated;
2040
- return JSON.stringify(out, null, 2) + "\n";
2041
- }
2042
- function readSides(path) {
2043
- const content = readText(path);
2044
- if (content === void 0) return void 0;
2045
- const body = content.charCodeAt(0) === 65279 ? content.slice(1) : content;
2046
- const sides = conflictSides(body);
2047
- return (sides ?? [body]).map((text) => parseObject(path, text, sides !== void 0));
2048
- }
2049
- function parseObject(path, text, conflicted) {
2050
- let value;
2051
- try {
2052
- value = JSON.parse(text);
2053
- } catch (error) {
2054
- throw corrupt(path, conflicted, error);
2055
- }
2056
- if (!isObject(value)) throw corrupt(path, conflicted);
2057
- return value;
2058
- }
2059
- const CONFLICT = {
2060
- start: /^<{7}(?: |$)/,
2061
- base: /^\|{7}(?: |$)/,
2062
- split: /^={7}$/,
2063
- end: /^>{7}(?: |$)/
2064
- };
2065
- function conflictSides(text) {
2066
- const lines = text.split(/\r?\n/);
2067
- if (!lines.some((line) => CONFLICT.start.test(line))) return void 0;
2068
- const ours = [];
2069
- const theirs = [];
2070
- let at = "both";
2071
- for (const line of lines) if (at === "both" && CONFLICT.start.test(line)) at = "ours";
2072
- else if (at === "ours" && CONFLICT.base.test(line)) at = "base";
2073
- else if ((at === "ours" || at === "base") && CONFLICT.split.test(line)) at = "theirs";
2074
- else if (at === "theirs" && CONFLICT.end.test(line)) at = "both";
2075
- else if (at !== "base") {
2076
- if (at !== "theirs") ours.push(line);
2077
- if (at !== "ours") theirs.push(line);
2078
- }
2079
- return at === "both" ? [ours.join("\n"), theirs.join("\n")] : void 0;
2080
- }
2081
- function corrupt(path, conflicted, cause) {
2082
- return new Error(conflicted ? `[verbaly] ${path} has a merge conflict Verbaly cannot read: resolve it by hand and keep the entries of both sides (dropping a side, or the file, approves its drafts)` : `[verbaly] ${path} is not valid JSON: restore it from git or fix it (deleting it approves every draft)`, { cause });
2083
- }
2084
- function isObject(value) {
2085
- return typeof value === "object" && value !== null && !Array.isArray(value);
2086
- }
2087
- function readDrafts(value) {
2088
- const out = {};
2089
- if (!isObject(value)) return out;
2090
- for (const [locale, keys] of Object.entries(value)) if (Array.isArray(keys)) out[locale] = keys.filter((key) => typeof key === "string");
2091
- return out;
2092
- }
2093
- function readMigrated(value) {
2094
- if (!Array.isArray(value)) return void 0;
2095
- const locales = value.filter((locale) => typeof locale === "string");
2096
- return locales.length ? locales : void 0;
2097
- }
2098
- function readFingerprints(value) {
2099
- const out = {};
2100
- if (!isObject(value)) return out;
2101
- for (const [locale, entries] of Object.entries(value)) {
2102
- if (!isObject(entries)) continue;
2103
- const kept = emptyCatalog();
2104
- for (const [key, stamped] of Object.entries(entries)) if (typeof stamped === "string" && stamped.includes(".")) kept[key] = stamped;
2105
- out[locale] = kept;
2106
- }
2107
- return out;
2108
- }
2109
- //#endregion
2110
- //#region src/project.ts
2111
- async function syncProject(cfg, options = {}) {
2112
- const registry = options.registry ?? await extractProject(cfg);
2113
- const catalogs = options.catalogs ?? loadCatalogs(cfg);
2114
- if (options.confirm) confirmFromDisk(cfg, catalogs, registry);
2115
- const pruneBlocked = options.prune === true && registry.parseErrors().length > 0;
2116
- const pruned = options.prune ? pruneCatalogs(cfg, catalogs, registry) : {};
2117
- const { added, replaced } = syncCatalogs(cfg, catalogs, registry);
2118
- const result = {
2119
- registry,
2120
- catalogs,
2121
- added,
2122
- replaced,
2123
- pruned,
2124
- pruneBlocked,
2125
- findings: scanFindings(cfg, registry, replaced),
2126
- written: {}
2127
- };
2128
- if (options.dryRun) return result;
2129
- const changed = /* @__PURE__ */ new Set([...Object.keys(added), ...Object.keys(pruned)]);
2130
- if (replaced.length > 0) changed.add(cfg.sourceLocale);
2131
- for (const locale of cfg.locales) {
2132
- if (options.write === "changed" && !changed.has(locale)) continue;
2133
- result.written[locale] = writeCatalog(cfg, locale, catalogs[locale] ?? {});
2134
- }
2135
- writeDts(cfg, catalogs[cfg.sourceLocale] ?? {});
2136
- const before = stateFile(cfg);
2137
- try {
2138
- result.state = updateState(cfg, catalogs);
2139
- } catch (error) {
2140
- result.stateProblem = error.message.replace(/^\[verbaly\] /, "");
2141
- }
2142
- const news = lockNews(cfg, before);
2143
- if (news) result.findings.push({
2144
- kind: "lock",
2145
- ...news
2146
- });
2147
- return result;
2148
- }
2149
- function confirmFromDisk(cfg, catalogs, registry) {
2150
- const source = catalogs[cfg.sourceLocale] ?? {};
2151
- const stale = /* @__PURE__ */ new Set();
2152
- for (const [key, msg] of registry.messages()) if (own(source, key) !== msg.message) stale.add(msg.file);
2153
- for (const file of stale) {
2154
- let code;
2155
- try {
2156
- code = readFileSync(file, "utf8");
2157
- } catch {
2158
- registry.remove(file);
2159
- continue;
2160
- }
2161
- registry.update(file, analyzeFile(code, file));
2162
- }
2163
- }
2164
- //#endregion
2165
- //#region src/migrate.ts
2166
- const KNOWN = [
2167
- "i18next",
2168
- "react-i18next",
2169
- "vue-i18n",
2170
- "react-intl",
2171
- "next-intl",
2172
- "svelte-i18n"
2173
- ];
2174
- function detectLibraries(root) {
2175
- const path = join(root, "package.json");
2176
- if (!existsSync(path)) return [];
2177
- let manifest;
2178
- try {
2179
- manifest = JSON.parse(readFileSync(path, "utf8"));
2180
- } catch {
2181
- return [];
2182
- }
2183
- const deps = {
2184
- ...manifest.dependencies,
2185
- ...manifest.devDependencies
2186
- };
2187
- return KNOWN.filter((name) => deps[name] !== void 0);
2188
- }
2189
- const PLAIN = /\{\{\s*([A-Za-z_$][\w$]*)\s*\}\}/g;
2190
- new RegExp(/\{\{[^{}]*\}\}/.source, "g");
2191
- new RegExp(`^${PLAIN.source}$`);
2192
- new RegExp(`^(.*)_(${[...[
2193
- "zero",
2194
- "one",
2195
- "two",
2196
- "few",
2197
- "many",
2198
- "other"
2199
- ], "plural"].join("|")})$`);
2200
- //#endregion
2201
- //#region src/tag.ts
2202
- function isLocaleTag(tag) {
2203
- try {
2204
- Intl.getCanonicalLocales(tag);
2205
- return true;
2206
- } catch {
2207
- return false;
2208
- }
2209
- }
2210
- function suggestTag(tag) {
2211
- const near = tag.replace(/_/g, "-");
2212
- return near !== tag && isLocaleTag(near) ? near : void 0;
2213
- }
2214
- //#endregion
2215
- //#region src/init.ts
2216
- const CATALOG_DIRS = [
2217
- "locales",
2218
- "src/locales",
2219
- "src/i18n/locales",
2220
- "src/i18n",
2221
- "i18n",
2222
- "lang",
2223
- "src/lang",
2224
- "translations",
2225
- "src/translations",
2226
- "messages"
2227
- ];
2228
- function existingCatalogs(root) {
2229
- return CATALOG_DIRS.find((dir) => {
2230
- try {
2231
- return readdirSync(join(root, dir)).some((file) => file.endsWith(".json") && isLocaleTag(file.slice(0, -5)));
2232
- } catch {
2233
- return false;
2234
- }
2235
- });
2236
- }
2237
- function cliReachable(root) {
2238
- const bin = join(root, "node_modules", ".bin");
2239
- return existsSync(join(bin, "verbaly")) || existsSync(join(bin, "verbaly.CMD"));
2240
- }
2241
- const CLI_INSTALL_FIX = "add `@verbaly/compiler` to your dev dependencies, then `npx verbaly` resolves";
2242
- function configSource(options, typescript) {
2243
- const fields = [` sourceLocale: '${options.sourceLocale ?? "en"}',`];
2244
- if (options.locales?.length) fields.push(` locales: [${options.locales.map((l) => `'${l}'`).join(", ")}],`);
2245
- if (options.dir) fields.push(` dir: '${options.dir}',`);
2246
- const body = `export default {\n${fields.join("\n")}\n}`;
2247
- if (typescript) return `import type { VerbalyConfig } from '@verbaly/compiler';\n\n${body} satisfies VerbalyConfig;\n`;
2248
- return `/** @type {import('@verbaly/compiler').VerbalyConfig} */\n${body};\n`;
2249
- }
2250
- async function init(input = {}) {
2251
- const root = input.root ?? process.cwd();
2252
- const created = [];
2253
- const skipped = [];
2254
- const renamed = [];
2255
- const refused = [];
2256
- const typed = input.locales?.flatMap((locale) => {
2257
- if (isLocaleTag(locale)) return [locale];
2258
- const near = suggestTag(locale);
2259
- if (near) renamed.push({
2260
- from: locale,
2261
- to: near
2262
- });
2263
- else refused.push(locale);
2264
- return near ? [near] : [];
2265
- });
2266
- const locales = typed && [...new Set(typed)];
2267
- let sourceLocale = input.sourceLocale;
2268
- if (sourceLocale !== void 0 && !isLocaleTag(sourceLocale)) {
2269
- const near = suggestTag(sourceLocale);
2270
- if (!near) throw new Error(`[verbaly] "${sourceLocale}" is not a locale tag: pass --source with one like en or pt-BR`);
2271
- renamed.push({
2272
- from: sourceLocale,
2273
- to: near
2274
- });
2275
- sourceLocale = near;
2276
- }
2277
- const options = {
2278
- ...input,
2279
- locales,
2280
- sourceLocale
2281
- };
2282
- const existing = findConfigFile(root);
2283
- const typescript = existsSync(join(root, "tsconfig.json"));
2284
- const configFile = existing ?? (typescript ? "verbaly.config.ts" : "verbaly.config.mjs");
2285
- const found = existing || options.dir ? void 0 : existingCatalogs(root);
2286
- if (existing) skipped.push(existing);
2287
- else {
2288
- const dir = found === "locales" ? void 0 : found;
2289
- writeFileSync(join(root, configFile), configSource({
2290
- ...options,
2291
- dir: options.dir ?? dir
2292
- }, typescript));
2293
- created.push(configFile);
2294
- }
2295
- const fromFile = existing ? await loadConfigFile(root) : {};
2296
- const scaffold = {
2297
- dir: options.dir ?? fromFile.dir ?? found,
2298
- sourceLocale: options.sourceLocale ?? fromFile.sourceLocale,
2299
- locales: options.locales ?? fromFile.locales
2300
- };
2301
- const dir = join(root, scaffold.dir ?? "locales");
2302
- if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
2303
- for (const locale of /* @__PURE__ */ new Set([scaffold.sourceLocale ?? "en", ...scaffold.locales ?? []])) {
2304
- const file = join(dir, `${locale}.json`);
2305
- const label = relative(root, file).replaceAll("\\", "/");
2306
- if (existsSync(file)) skipped.push(label);
2307
- else {
2308
- writeFileSync(file, "{}\n");
2309
- created.push(label);
2310
- }
2311
- }
2312
- const host = detectHost(root);
2313
- const deps = readDependencies(root);
2314
- const missing = host?.install.filter((pkg) => !deps[pkg]) ?? [];
2315
- const next = host ? [...missing.length ? [installCommand(root, missing)] : [], host.wire] : ["run \"verbaly extract\" after writing your first t`…` message"];
2316
- const others = detectLibraries(root);
2317
- if (found && others.length) next.push(`port the ${others.join(" and ")} catalogs: npx verbaly migrate reports, --write applies`);
2318
- return {
2319
- created,
2320
- skipped,
2321
- host: host?.name,
2322
- configFile,
2323
- next,
2324
- renamed,
2325
- refused,
2326
- found
2327
- };
2328
- }
2329
- //#endregion
2330
- //#region src/check.ts
2331
- function gatePasses(result) {
2332
- return result.missing.length === 0 && result.unknown.length === 0 && result.collisions.length === 0 && !result.broken.some((entry) => entry.severity === "error");
2333
- }
2334
- function warningCount(result) {
2335
- return result.broken.filter((entry) => entry.severity === "warning").length + result.extra.length + result.divergent.length + result.outdated.length;
2336
- }
2337
- function check(cfg, catalogs, registry, fingerprints = {}) {
2338
- return gatePass(() => checkPass(cfg, catalogs, registry, fingerprints));
2339
- }
2340
- function checkPass(cfg, catalogs, registry, fingerprints) {
2341
- const extracted = registry.messages();
2342
- const flat = {};
2343
- for (const locale of cfg.locales) flat[locale] = flatten(catalogs[locale] ?? {});
2344
- const source = flat[cfg.sourceLocale] ?? {};
2345
- const shipped = shippedCatalogs(cfg, flat, registry);
2346
- const sourceText = shipped[cfg.sourceLocale];
2347
- const used = registry.usedKeys();
2348
- const unknown = [];
2349
- for (const [key, files] of registry.usedKeys(true)) if (!(extracted.has(key) || cfg.locales.some((locale) => flat[locale]?.[key] !== void 0))) unknown.push({
2350
- key,
2351
- files
2352
- });
2353
- const needed = /* @__PURE__ */ new Set([...extracted.keys(), ...Object.keys(source)]);
2354
- const missing = [];
2355
- for (const key of extracted.keys()) if (!source[key]) missing.push({
2356
- locale: cfg.sourceLocale,
2357
- key,
2358
- source: extracted.get(key)?.message
2359
- });
2360
- for (const locale of cfg.locales) {
2361
- if (locale === cfg.sourceLocale) continue;
2362
- for (const key of needed) if (!flat[locale]?.[key]) missing.push({
2363
- locale,
2364
- key,
2365
- source: source[key] ?? extracted.get(key)?.message
2366
- });
2367
- }
2368
- const broken = [];
2369
- const add = (locale, key, issues) => {
2370
- for (const issue of issues) broken.push({
2371
- locale,
2372
- key,
2373
- severity: issue.severity,
2374
- issue: issue.message
2375
- });
2376
- };
2377
- const divergent = [];
2378
- for (const [key, entry] of extracted) {
2379
- const written = source[key];
2380
- if (written && written !== entry.message) divergent.push({
2381
- key,
2382
- catalog: written,
2383
- code: siteOf(entry)
2384
- });
2385
- }
2386
- for (const [key, text] of Object.entries(sourceText)) add(cfg.sourceLocale, key, validateMessage(text, cfg.sourceLocale));
2387
- for (const locale of cfg.locales) {
2388
- if (locale === cfg.sourceLocale) continue;
2389
- for (const [key, translated] of Object.entries(flat[locale] ?? {})) {
2390
- if (!translated) continue;
2391
- add(locale, key, validateMessage(translated, locale));
2392
- const text = sourceText[key];
2393
- if (text) add(locale, key, validatePair(text, translated));
2394
- }
2395
- }
2396
- const extra = [];
2397
- for (const locale of cfg.locales) {
2398
- if (locale === cfg.sourceLocale) continue;
2399
- for (const key of Object.keys(flat[locale] ?? {})) {
2400
- if (source[key] !== void 0 || extracted.has(key)) continue;
2401
- extra.push({
2402
- locale,
2403
- key,
2404
- files: used.get(key) ?? []
2405
- });
2406
- }
2407
- }
2408
- const collisions = collisionEntries(registry);
2409
- return {
2410
- ok: gatePasses({
2411
- missing,
2412
- unknown,
2413
- broken,
2414
- collisions
2415
- }),
2416
- missing,
2417
- unknown,
2418
- broken,
2419
- extra,
2420
- collisions,
2421
- divergent,
2422
- outdated: outdatedTranslations(cfg, shipped, fingerprints)
2423
- };
2424
- }
2425
- function formatCheckResult(result, root) {
2426
- const show = (file) => root ? relative(root, file).replaceAll("\\", "/") : file;
2427
- const lines = [];
2428
- if (result.missing.length > 0) {
2429
- lines.push("missing translations:");
2430
- for (const entry of result.missing) {
2431
- const hint = entry.source ? `: "${truncate(entry.source, 40)}"` : "";
2432
- lines.push(` [${entry.locale}] ${entry.key}${hint}`);
2433
- }
2434
- }
2435
- if (result.unknown.length > 0) {
2436
- lines.push("unknown keys (not in any catalog):");
2437
- for (const entry of result.unknown) lines.push(` ${entry.key} (used in ${entry.files.map(show).join(", ")})`);
2438
- }
2439
- const errors = result.broken.filter((entry) => entry.severity === "error");
2440
- if (errors.length > 0) {
2441
- lines.push("broken translations:");
2442
- for (const entry of errors) lines.push(` [${entry.locale}] ${entry.key}: ${entry.issue}`);
2443
- }
2444
- if (result.collisions.length > 0) {
2445
- lines.push("keys written with more than one text:");
2446
- for (const entry of result.collisions) lines.push(` ${formatCollision(entry, root)}`);
2447
- }
2448
- return lines.join("\n");
2449
- }
2450
- function formatBuildReport(result, sourceLocale, root, cap = 5) {
2451
- const show = (file) => root ? relative(root, file).replaceAll("\\", "/") : file;
2452
- const lines = [];
2453
- const list = (entries, line) => {
2454
- for (const entry of entries.slice(0, cap)) lines.push(` ${line(entry)}`);
2455
- if (entries.length > cap) lines.push(` and ${entries.length - cap} more`);
2456
- };
2457
- const broken = result.broken.filter((entry) => entry.severity === "error");
2458
- if (broken.length > 0) {
2459
- lines.push(`✗ the build goes on with ${counted(broken.length, "broken translation")}, each rendering differently from its source:`);
2460
- list(broken, (entry) => `[${entry.locale}] ${entry.key}: ${entry.issue}`);
2461
- }
2462
- if (result.collisions.length > 0) {
2463
- lines.push(`✗ the build goes on with ${counted(result.collisions.length, "key")} written with more than one text:`);
2464
- list(result.collisions, (entry) => formatCollision(entry, root));
2465
- }
2466
- const quoted = (entry) => entry.source ? `: "${truncate(entry.source, 40)}"` : "";
2467
- const untranslated = result.missing.filter((entry) => entry.locale !== sourceLocale);
2468
- if (untranslated.length > 0) {
2469
- lines.push(`⚠ the build goes on without ${counted(untranslated.length, "translation")}, shown in ${sourceLocale} instead:`);
2470
- list(untranslated, (entry) => `[${entry.locale}] ${entry.key}${quoted(entry)}`);
2471
- }
2472
- if (result.unknown.length > 0) {
2473
- lines.push(`⚠ the build goes on with ${counted(result.unknown.length, "key")} no catalog has, so the key itself shows:`);
2474
- list(result.unknown, (entry) => `${entry.key} (used in ${entry.files.map(show).join(", ")})`);
2475
- }
2476
- const unsynced = result.missing.filter((entry) => entry.locale === sourceLocale);
2477
- if (unsynced.length > 0) lines.push(`⚠ the build goes on with ${counted(unsynced.length, "text")} the ${sourceLocale} catalog does not have yet, taken from the code`);
2478
- return lines;
2479
- }
2480
- function checkNextSteps(result, cliReachable = true) {
2481
- const steps = [];
2482
- if (result.missing.length > 0) steps.push("missing: run `npx verbaly extract` to scaffold the keys, then fill them (or run `npx verbaly translate`)");
2483
- if (result.unknown.length > 0) steps.push("unknown keys: the key used in the code is in no catalog, fix the key or run `npx verbaly extract`");
2484
- if (result.broken.some((entry) => entry.severity === "error")) steps.push("broken: a translation has to keep the params, tags and plural cases of its source message");
2485
- if (result.collisions.length > 0) steps.push("collisions: give each text its own key in t.id(…), or write the same text in every place");
2486
- if (steps.length > 0 && !cliReachable) steps.push(`the verbaly command is not linked in this project: ${CLI_INSTALL_FIX}`);
2487
- return steps.join("\n");
2488
- }
2489
- function formatCheckWarnings(result, root, options = {}) {
2490
- const lines = result.broken.filter((entry) => entry.severity === "warning").map((entry) => ` [${entry.locale}] ${entry.key}: ${entry.issue}`);
2491
- for (const entry of result.extra) lines.push(entry.files.length > 0 ? ` [${entry.locale}] ${entry.key}: only this translation has it, so the source language shows the key itself` : ` [${entry.locale}] ${entry.key}: only this translation has it, and no code reads it`);
2492
- for (const { key, catalog, code } of result.divergent) lines.push(` ${key}: the source catalog says "${truncate(catalog, 40)}" and the code says "${truncate(code.message, 40)}" (${sourcePlace(code, root)}): the code wins, so edit the text there (extract writes it into the catalog)`);
2493
- if (!options.outdatedFails) for (const entry of result.outdated) lines.push(` ${formatFinding({
2494
- kind: "outdated",
2495
- ...entry
2496
- }, root)}`);
2497
- return lines.join("\n");
2498
- }
2499
- //#endregion
2500
- //#region src/transform.ts
2501
- function quote(text, single) {
2502
- if (!single) return JSON.stringify(text);
2503
- return `'${text.replace(/\\/g, "\\\\").replace(/'/g, "\\'")}'`;
2504
- }
2505
- function transformCode(code, file, analysis) {
2506
- const own = analysis ?? analyzeFile(code, file);
2507
- if (!analysis && own.parseError) warnParseError(file, own.parseError);
2508
- const { tagged } = own;
2509
- if (tagged.length === 0) return null;
2510
- const s = new MagicString(code);
2511
- for (const msg of tagged) {
2512
- const seen = /* @__PURE__ */ new Set();
2513
- const entries = msg.params.filter((p) => !seen.has(p.name) && seen.add(p.name));
2514
- const pairs = entries.map((p) => `${quote(p.name, msg.singleQuote)}: ${code.slice(p.start, p.end)}`).join(", ");
2515
- if (msg.jsx) {
2516
- const values = entries.length ? ` values={{ ${pairs} }}` : "";
2517
- const components = msg.jsx.components.length ? ` components={{ ${msg.jsx.components.map((c) => `${JSON.stringify(c.name)}: ${c.source}`).join(", ")} }}` : "";
2518
- s.overwrite(msg.start, msg.end, `<${msg.jsx.name} id=${JSON.stringify(msg.key)}${values}${components} />`);
2519
- continue;
2520
- }
2521
- const tagSource = code.slice(msg.tagStart, msg.tagEnd);
2522
- const args = entries.length ? `, { ${pairs} }` : "";
2523
- s.overwrite(msg.start, msg.end, `${tagSource}(${quote(msg.key, msg.singleQuote)}${args})`);
2524
- }
2525
- return {
2526
- code: s.toString(),
2527
- map: s.generateMap({ hires: true })
2528
- };
2529
- }
2530
- //#endregion
2531
- //#region src/plugin.ts
2532
- const RESOLVED_VIRTUAL_ID = "\0virtual:verbaly";
2533
- const LOCALE_MODULE_PREFIX = `${RESOLVED_VIRTUAL_ID}/locale/`;
2534
- const SOURCE_FILE_RE = /\.(?:[cm]?[jt]sx?|svelte|vue|astro)$/;
2535
- function resolveVirtualId(id) {
2536
- if (id === "virtual:verbaly" || id.startsWith(`virtual:verbaly/`)) return "\0" + id;
2537
- }
2538
- function loadVirtualModule(id, cfg, catalogs) {
2539
- const client = clientCatalogs(cfg, catalogs);
2540
- if (id === RESOLVED_VIRTUAL_ID) return generateRuntimeModule(cfg, {
2541
- icu: cfg.icu ?? needsIcu(client),
2542
- relative: cfg.relative ?? needsRelative(client),
2543
- inlineCatalog: cfg.render.inlineCatalog === true
2544
- });
2545
- if (id.startsWith(LOCALE_MODULE_PREFIX)) return generateLocaleModule(client[id.slice(LOCALE_MODULE_PREFIX.length)] ?? {});
2546
- }
2547
- function isTransformTarget(id) {
2548
- return SOURCE_FILE_RE.test(id) && !id.includes("node_modules") && !id.startsWith("\0");
2549
- }
2550
- function createSourceFilter(cfg) {
2551
- if (cfg.include.length === 0) return () => false;
2552
- const matches = picomatch(cfg.include, { ignore: cfg.exclude });
2553
- return (id) => {
2554
- const rel = relative(cfg.root, id).replaceAll("\\", "/");
2555
- return !rel.startsWith("..") && matches(rel);
2556
- };
2557
- }
2558
- function transformSource(code, id, registry, scan) {
2559
- const analysis = (scan && scannedAnalysis(scan, id, code)) ?? analyzeFile(code, id);
2560
- registry.update(id, analysis);
2561
- if (analysis.parseError) warnParseError(id, analysis.parseError);
2562
- const messages = emptyCatalog();
2563
- for (const msg of analysis.tagged) messages[msg.key] ??= msg.message;
2564
- return {
2565
- messages,
2566
- result: transformCode(code, id, analysis) ?? null
2567
- };
2568
- }
2569
- function runBuildGate(cfg, registry, failOnMissing) {
2570
- const catalogs = loadCatalogs(cfg);
2571
- for (const issue of auditBundle(cfg, catalogs, registry)) warnOnce(`${formatBundleIssue(issue)}\n fix: ${issue.fix}`, `bundle:${issue.prefix}`);
2572
- const found = check(cfg, catalogs, registry, buildFingerprints(cfg));
2573
- if (failOnMissing === true && !gatePasses(found)) throw new Error(`[verbaly] build blocked\n${formatCheckResult(found, cfg.root)}\n${checkNextSteps(found, cliReachable(cfg.root))}`);
2574
- reportGate(cfg, found);
2575
- const warnings = warningCount(found);
2576
- if (warnings > 0) warnOnce(`check has ${counted(warnings, "warning")}, and the build still passes: run \`npx verbaly check\` to read them`, "gate:warnings");
2577
- }
2578
- const reported = /* @__PURE__ */ new Map();
2579
- function reportGate(cfg, found) {
2580
- const before = reported.get(cfg.root) ?? /* @__PURE__ */ new Set();
2581
- const now = /* @__PURE__ */ new Set();
2582
- const fresh = (entries, id) => entries.filter((entry) => {
2583
- const key = id(entry);
2584
- now.add(key);
2585
- return !before.has(key);
2586
- });
2587
- const report = {
2588
- broken: fresh(found.broken.filter((entry) => entry.severity === "error"), (entry) => `broken:${entry.locale}:${entry.key}:${entry.issue}`),
2589
- missing: fresh(found.missing, (entry) => `missing:${entry.locale}:${entry.key}`),
2590
- unknown: fresh(found.unknown, (entry) => `unknown:${entry.key}`),
2591
- collisions: fresh(found.collisions, (entry) => `collision:${entry.key}`)
2592
- };
2593
- reported.set(cfg.root, now);
2594
- const lines = formatBuildReport(report, cfg.sourceLocale, cfg.root);
2595
- if (lines.length === 0) return;
2596
- const steps = checkNextSteps({
2597
- ...found,
2598
- ...report
2599
- }, cliReachable(cfg.root));
2600
- const block = [
2601
- ...lines.map((line) => line.startsWith(" ") ? line : `[verbaly] ${line}`),
2602
- "[verbaly] to fix them:",
2603
- ...steps.split("\n").map((step) => ` ${step}`),
2604
- "[verbaly] `npx verbaly check` lists every one, and in your CI it stops a release on them"
2605
- ];
2606
- console.warn(block.join("\n"));
2607
- }
2608
- function buildFingerprints(cfg) {
2609
- const { state, problem } = readState(cfg);
2610
- if (problem) warnOnce(`${problem}, so outdated translations are not reported`, "gate:state");
2611
- return state.fingerprints;
2612
- }
2613
- //#endregion
2614
- //#region src/scope.ts
2615
- const TAGGED_HINT = /(?<![\w$.])\$?t(?:\.id\s*\([^)]*\))?\s*`/;
2616
- const NOT_SOURCE = [
2617
- "**/node_modules/**",
2618
- "**/dist/**",
2619
- "**/build/**",
2620
- "**/out/**",
2621
- "**/coverage/**"
2622
- ];
2623
- function relativeId(cfg, id) {
2624
- return relative(cfg.root, id).replaceAll("\\", "/");
2625
- }
2626
- function suggestedPattern(rel) {
2627
- const slash = rel.indexOf("/");
2628
- return slash < 0 ? rel : `${rel.slice(0, slash)}/**/*.${SOURCE_EXTENSIONS}`;
2629
- }
2630
- function outsidePath(cfg) {
2631
- const included = picomatch(cfg.include);
2632
- const excluded = picomatch(cfg.exclude);
2633
- return (id) => {
2634
- const rel = relativeId(cfg, id);
2635
- return rel.startsWith("..") || included(rel) || excluded(rel) ? void 0 : rel;
2636
- };
2637
- }
2638
- function createOutsideCheck(cfg) {
2639
- if (cfg.include.length === 0) return () => void 0;
2640
- const outside = outsidePath(cfg);
2641
- return (code, id) => {
2642
- const rel = outside(id);
2643
- if (rel === void 0 || !TAGGED_HINT.test(code)) return void 0;
2644
- if (analyzeFile(code, id).tagged.length === 0) return void 0;
2645
- return {
2646
- file: id,
2647
- pattern: suggestedPattern(rel)
2648
- };
2649
- };
2650
- }
2651
- function formatOutside(cfg, found) {
2652
- return `${relativeId(cfg, found.file)} uses t\`…\` outside the include of your verbaly config, so its texts are never extracted and show in ${cfg.sourceLocale} in every language: add "${found.pattern}" to include (or the file to exclude, if it is not app code)`;
2653
- }
2654
- async function reportOutsideInclude(cfg) {
2655
- for (const found of await filesOutsideInclude(cfg)) warnOnce(formatOutside(cfg, found), `outside:${found.file}`);
2656
- }
2657
- async function filesOutsideInclude(cfg) {
2658
- if (cfg.include.length === 0) return [];
2659
- const check = createOutsideCheck(cfg);
2660
- const outside = outsidePath(cfg);
2661
- const files = await glob([`**/*.${SOURCE_EXTENSIONS}`], {
2662
- cwd: cfg.root,
2663
- ignore: [...NOT_SOURCE, ...cfg.exclude],
2664
- absolute: true
2665
- });
2666
- const found = [];
2667
- for (const file of files.sort()) {
2668
- if (outside(file) === void 0) continue;
2669
- let code;
2670
- try {
2671
- code = readFileSync(file, "utf8");
2672
- } catch {
2673
- continue;
2674
- }
2675
- const entry = check(code, file);
2676
- if (entry) found.push(entry);
2677
- }
2678
- return found;
2679
- }
2680
- //#endregion
1
+ import { $ as collectOrigins, A as formatCheckWarnings, B as recordTranslations, C as loadVirtualModule, D as transformCode, E as transformSource, F as effectiveDrafts, G as formatCollision, H as updateState, I as loadState, J as generateLocaleModule, K as formatFinding, L as markDrafts, M as syncProject, N as STATE_FILE, O as check, P as clearDrafts, Q as validatePair, R as outdatedTranslations, S as isTransformTarget, T as runBuildGate, U as collisionEntries, V as saveState, W as createDevReporter, X as writeDts, Y as generateRuntimeModule, Z as validateMessage, _ as reportOutsideInclude, _t as writeCatalog, a as formatRenderWarnings, at as MessageRegistry, b as SOURCE_FILE_RE, c as mergeTranslations, d as writeDrafts, dt as targetLocales, et as extractProject, f as doctor, ft as loadCatalogs, g as status, gt as readCatalog, h as formatStatusResult, ht as parseCatalog, i as watchTree, it as stableKey, j as init, k as formatCheckResult, l as resolveProvider, lt as loadConfig, m as formatDoctorHealth, mt as needsRelative, nt as shippedCatalogs, o as renderSite, ot as clientCatalogs, p as formatDoctorEntry, pt as needsIcu, q as generateDts, r as wrapProject, rt as syncCatalogs, s as formatTranslateFailures, st as counted, t as formatCliError, tt as pruneCatalogs, u as translateCatalogs, ut as resolveConfig, v as LOCALE_MODULE_PREFIX, w as resolveVirtualId, x as createSourceFilter, y as RESOLVED_VIRTUAL_ID, z as readState } from "./run-CfZ-z1Io.js";
2681
2
  //#region src/drafts.ts
2682
3
  function loadDrafts(cfg) {
2683
4
  return loadState(cfg).drafts;
2684
5
  }
2685
6
  function saveDrafts(cfg, drafts) {
7
+ const state = loadState(cfg);
2686
8
  saveState(cfg, {
2687
- ...loadState(cfg),
9
+ ...state,
2688
10
  drafts
2689
11
  });
2690
12
  }
2691
13
  //#endregion
2692
- //#region src/status.ts
2693
- function status(cfg, catalogs, registry, drafts = {}, fingerprints = {}) {
2694
- const extracted = registry.messages();
2695
- const flat = {};
2696
- for (const locale of cfg.locales) flat[locale] = flatten(catalogs[locale] ?? {});
2697
- const source = flat[cfg.sourceLocale] ?? {};
2698
- const needed = /* @__PURE__ */ new Set([...extracted.keys(), ...Object.keys(source)]);
2699
- const live = effectiveDrafts(drafts, flat);
2700
- const shipped = shippedCatalogs(cfg, flat, registry);
2701
- const sourceText = shipped[cfg.sourceLocale];
2702
- const outdated = outdatedTranslations(cfg, shipped, fingerprints);
2703
- const locales = [];
2704
- for (const locale of cfg.locales) {
2705
- if (locale === cfg.sourceLocale) continue;
2706
- const catalog = flat[locale] ?? {};
2707
- let translated = 0;
2708
- for (const key of needed) if (catalog[key]) translated += 1;
2709
- let broken = 0;
2710
- for (const [key, text] of Object.entries(catalog)) {
2711
- if (!text) continue;
2712
- const from = sourceText[key];
2713
- if ([...validateMessage(text, locale), ...from ? validatePair(from, text) : []].some((issue) => issue.severity === "error")) broken += 1;
2714
- }
2715
- locales.push({
2716
- locale,
2717
- translated,
2718
- total: needed.size,
2719
- drafts: live[locale]?.length ?? 0,
2720
- broken,
2721
- outdated: outdated.filter((entry) => entry.locale === locale).length
2722
- });
2723
- }
2724
- return {
2725
- messages: needed.size,
2726
- source: cfg.sourceLocale,
2727
- locales
2728
- };
2729
- }
2730
- function formatStatusResult(result) {
2731
- const lines = [`[verbaly] ${counted(result.messages, "message")} · source: ${result.source}`];
2732
- if (result.locales.length === 0) {
2733
- lines.push(" no target locales (add locales to your config)");
2734
- return lines.join("\n");
2735
- }
2736
- for (const { locale, translated, total, drafts, broken, outdated } of result.locales) {
2737
- const pct = total === 0 ? 100 : Math.floor(translated / total * 100);
2738
- const mark = translated === total && broken === 0 && outdated === 0 ? " ✓" : "";
2739
- const notes = [
2740
- drafts > 0 ? `${drafts} unreviewed` : "",
2741
- broken > 0 ? `${broken} broken` : "",
2742
- outdated > 0 ? `${outdated} outdated` : ""
2743
- ].filter(Boolean);
2744
- const note = notes.length > 0 ? `, ${notes.join(", ")}` : "";
2745
- lines.push(` ${locale}: ${translated}/${total} translated (${pct}%${note})${mark}`);
2746
- }
2747
- return lines.join("\n");
2748
- }
2749
- //#endregion
2750
- //#region src/doctor.ts
2751
- const PREVIEW = 5;
2752
- function readRoutingChoice(root, configFile) {
2753
- try {
2754
- return /\brouting["']?\s*[:=]/.test(readFileSync(join(root, configFile), "utf8"));
2755
- } catch {
2756
- return false;
2757
- }
2758
- }
2759
- const ROUTING_SAYS = {
2760
- "prefix-except-source": "the source locale has no prefix, every other locale does",
2761
- "prefix-all": "every locale has a prefix, the source included",
2762
- "no-prefix": "the language is not in the url, one address serves every locale"
2763
- };
2764
- const ICON = {
2765
- ok: "✓",
2766
- warn: "⚠",
2767
- error: "✗"
2768
- };
2769
- function formatDoctorEntry(entry) {
2770
- const head = ` ${ICON[entry.level]} ${entry.check}: ${entry.message}`;
2771
- return entry.fix ? `${head}
2772
- fix: ${entry.fix}` : head;
2773
- }
2774
- function formatDoctorHealth(result) {
2775
- if (!result.ok) return "problems found";
2776
- const warnings = result.entries.filter((entry) => entry.level === "warn").length;
2777
- return warnings > 0 ? `setup works, with ${counted(warnings, "warning")} to read` : "setup looks healthy";
2778
- }
2779
- async function doctor(cfg) {
2780
- const entries = [];
2781
- const ok = (name, message) => entries.push({
2782
- level: "ok",
2783
- check: name,
2784
- message
2785
- });
2786
- const warn = (name, message, fix) => entries.push({
2787
- level: "warn",
2788
- check: name,
2789
- message,
2790
- fix
2791
- });
2792
- const error = (name, message, fix) => entries.push({
2793
- level: "error",
2794
- check: name,
2795
- message,
2796
- fix
2797
- });
2798
- const rel = (path) => relative(cfg.root, path).replaceAll("\\", "/");
2799
- const configFile = findConfigFile(cfg.root);
2800
- if (configFile) ok("config", `${configFile} found`);
2801
- else warn("config", "no config file, running on defaults", "run `npx verbaly init`");
2802
- if (cliReachable(cfg.root)) ok("cli", "the verbaly command is available in this project");
2803
- else warn("cli", "the verbaly command is not linked in node_modules/.bin", CLI_INSTALL_FIX);
2804
- const catalogs = {};
2805
- let catalogsHealthy = true;
2806
- if (!existsSync(cfg.dir)) {
2807
- catalogsHealthy = false;
2808
- error("catalogs", `catalogs directory ${rel(cfg.dir)}/ does not exist`, "run `npx verbaly init` to scaffold it");
2809
- } else {
2810
- for (const locale of cfg.locales) {
2811
- const file = join(cfg.dir, `${locale}.json`);
2812
- if (!existsSync(file)) {
2813
- catalogsHealthy = false;
2814
- error(`locale ${locale}`, `${rel(file)} is missing`, "run `npx verbaly extract` to create it");
2815
- continue;
2816
- }
2817
- const parsed = parseTree(readFileSync(file, "utf8"));
2818
- if (parsed === void 0) {
2819
- catalogsHealthy = false;
2820
- error(`locale ${locale}`, `${rel(file)} is not valid JSON`, "repair the file (or delete it and run `npx verbaly extract`)");
2821
- continue;
2822
- }
2823
- if (!isTree(parsed)) {
2824
- catalogsHealthy = false;
2825
- error(`locale ${locale}`, `${rel(file)} is not a JSON object of messages`, "a catalog is an object of texts (groups of text are fine): fix the file");
2826
- continue;
2827
- }
2828
- const bad = badLeaf(parsed);
2829
- if (bad) {
2830
- catalogsHealthy = false;
2831
- error(`locale ${locale}`, `${rel(file)} has a non-string value at "${bad}"`, "catalog values are text (groups of text are fine); fix the value");
2832
- } else catalogs[locale] = flatten(parsed);
2833
- }
2834
- if (catalogsHealthy) {
2835
- const how = cfg.localesDeclared ? "" : ", no locales set, so the catalog files decide";
2836
- ok("catalogs", `${counted(cfg.locales.length, "locale")} (${cfg.locales.join(", ")}) in ${rel(cfg.dir)}/${how}`);
2837
- }
2838
- }
2839
- for (const locale of cfg.locales) {
2840
- if (isLocaleTag(locale)) continue;
2841
- const near = suggestTag(locale);
2842
- const file = rel(join(cfg.dir, `${locale}.json`));
2843
- warn("locales", `"${locale}" is not a locale tag, so numbers, dates and plurals in it format in a fallback`, near ? `rename it to ${near}: the file ${file} and your config` : `name it with a language tag like es or pt-BR, in ${file} and in your config`);
2844
- }
2845
- const source = catalogs[cfg.sourceLocale];
2846
- if (source && Object.keys(source).length === 0) warn("source", `source catalog ${cfg.sourceLocale}.json is empty`, "write your first t`…` message and run `npx verbaly extract`");
2847
- const mirrors = cfg.render.site !== void 0 || Object.keys(cfg.render).length > 0;
2848
- if (cfg.routing === "no-prefix" && mirrors) warn("routing", "routing is \"no-prefix\" but a render section is configured, and render writes one url tree per locale", "drop the render section, or set routing to \"prefix-except-source\" so the helpers agree with the urls");
2849
- else if (cfg.routing === "prefix-all" && mirrors) warn("routing", `routing is "prefix-all" but render keeps ${cfg.sourceLocale} at the root, so its links point at a /${cfg.sourceLocale}/ tree nobody wrote`, "set routing to \"prefix-except-source\", the url tree render writes");
2850
- else {
2851
- const how = (configFile ? readRoutingChoice(cfg.root, configFile) : false) ? "" : " (from your setup, no routing set)";
2852
- ok("routing", `${cfg.routing}${how}: ${ROUTING_SAYS[cfg.routing]}`);
2853
- }
2854
- const deps = readDependencies(cfg.root);
2855
- const host = detectHost(cfg.root);
2856
- const installed = WIRING_PACKAGES.find((pkg) => deps[pkg]);
2857
- if (!host) ok("plugin", "no framework or bundler detected, the CLI flow (extract/check) applies");
2858
- else if (installed) ok("plugin", `${installed} installed for ${host.name}`);
2859
- else warn("plugin", `${host.name} detected but ${host.pkg} is not installed`, `${installCommand(cfg.root, host.install)}, then ${host.wire}`);
2860
- const scanning = cfg.include.length > 0;
2861
- if (!scanning) ok("sources", "source scanning is off (include: []), the catalogs are the source of truth");
2862
- if (source && scanning && cfg.dts !== false) {
2863
- const dtsPath = cfg.dts;
2864
- const shown = rel(dtsPath);
2865
- const regenerate = host?.name === "astro" ? "run `npx astro sync`, which writes the types and links them" : host?.name === "nuxt" ? "run `npx nuxi prepare`, which writes the types and links them" : "run `npx verbaly typegen`";
2866
- const expected = generateDts(source, projectDtsOptions(cfg));
2867
- if (!existsSync(dtsPath)) warn("types", `${shown} has not been generated`, regenerate);
2868
- else if (readFileSync(dtsPath, "utf8").replace(/\r\n/g, "\n") !== expected) warn("types", `${shown} is stale`, "run `npx verbaly typegen`");
2869
- else ok("types", `${shown} is up to date`);
2870
- if (dtsPath.startsWith(join(cfg.root, ".verbaly"))) {
2871
- const state = typesIncluded(cfg.root, dtsPath);
2872
- if (state === "missing" || state === "unreadable") warn("types", state === "missing" ? `tsconfig.json does not include ${shown}, so TypeScript never reads the types` : `tsconfig.json could not be read, so it may not include ${shown}`, `run \`npx verbaly typegen\`, which adds the line, or add "${shown}" to include`);
2873
- }
2874
- const old = join(cfg.root, "verbaly.d.ts");
2875
- if (dtsPath !== old && existsSync(old) && readFileSync(old, "utf8").startsWith("// generated by verbaly: do not edit")) warn("types", `the verbaly.d.ts Verbaly wrote at the root is still there next to ${shown}, and they declare the same module twice`, "run `npx verbaly typegen`, which removes it");
2876
- }
2877
- const registry = await extractProject(cfg);
2878
- if (scanning) {
2879
- const unreadable = registry.parseErrors();
2880
- if (unreadable.length > 0) {
2881
- const first = unreadable[0];
2882
- warn("sources", `could not parse ${counted(unreadable.length, "file")}, so the messages inside are not extracted (${rel(first.file)}: ${first.message})`, "fix the syntax error, or exclude the file in your config if it is not source");
2883
- }
2884
- const outside = await filesOutsideInclude(cfg);
2885
- if (outside.length > 0) {
2886
- const files = outside.map((entry) => rel(entry.file));
2887
- const patterns = [...new Set(outside.map((entry) => `"${entry.pattern}"`))];
2888
- warn("sources", `t\`…\` is written in ${counted(outside.length, "file")} outside include, and those texts are never extracted or translated (${preview(files)})`, `add ${patterns.join(" and ")} to include in your verbaly config, or the files to exclude if they are not app code`);
2889
- }
2890
- const stray = registry.strayImports();
2891
- if (stray.length > 0) {
2892
- const files = [...new Set(stray.map((entry) => rel(entry.file)))];
2893
- error("imports", `t is imported from a verbaly package, which never exports it, in ${counted(files.length, "file")} (${preview(files)})`, "t comes from your instance (React: const t = useT()) or from virtual:verbaly");
2894
- }
2895
- const missed = registry.missed();
2896
- if (missed.length > 0) {
2897
- const first = missed[0];
2898
- warn("sources", `a t under another name keeps ${counted(missed.length, "text")} out of extraction (${sourcePlace(first, cfg.root)}: ${first.name}\`…\`)`, "name it t (const t = useT()), the only name verbaly reads, or use t(key) with the key in the catalog");
2899
- }
2900
- const positional = [...registry.messages().values()].filter((msg) => msg.params.some((param) => /^_\d+$/.test(param.name)));
2901
- if (positional.length > 0) {
2902
- const first = positional[0];
2903
- warn("messages", `a translator gets a nameless value like {_0} in ${counted(positional.length, "message")} (${sourcePlace(first, cfg.root)}: "${first.message}")`, "put the value in a named variable first (const date = formatDate(d)), so the message says {date}");
2904
- }
2905
- const escaped = [...registry.messages().values()].map((msg) => ({
2906
- file: rel(msg.file),
2907
- slice: escapedSyntax(msg.message)
2908
- })).filter((entry) => entry.slice !== void 0);
2909
- if (escaped.length > 0) warn("messages", `a block ships as literal text in ${counted(escaped.length, "extracted message")} (${escaped[0].file}: ${shownSlice(escaped[0].slice)})`, `in a tagged template, write ${inlineBlock(escaped[0].slice)}`);
2910
- }
2911
- if (source && scanning) {
2912
- const extracted = registry.messages();
2913
- const used = registry.usedKeys();
2914
- const orphans = Object.keys(source).filter((key) => !extracted.has(key) && !used.has(key));
2915
- const unread = registry.parseErrors().length > 0;
2916
- if (orphans.length > 0) warn("orphans", `${counted(orphans.length, "catalog key")} no longer referenced in code (${preview(orphans)})`, unread ? "fix the files that do not parse first, they may use these, and `npx verbaly extract --prune` leaves every key alone until then" : "run `npx verbaly extract --prune` to drop them");
2917
- else ok("orphans", "no orphan keys");
2918
- }
2919
- const excluded = cfg.bundle.exclude ?? [];
2920
- if (excluded.length > 0 && catalogsHealthy) {
2921
- const issues = auditBundle(cfg, catalogs, registry);
2922
- for (const issue of issues) warn("bundle", formatBundleIssue(issue), issue.fix);
2923
- if (issues.length === 0) ok("bundle", `${counted(excluded.length, "group")} kept out of the client (${preview(excluded)})`);
2924
- }
2925
- const { state, problem, conflict } = readState(cfg);
2926
- if (problem) warn("state", problem, conflict ? "resolve it by hand, keeping the entries of both sides: taking one side approves the drafts of the other" : `restore ${STATE_FILE} from git: deleting it would mark every machine draft as reviewed`);
2927
- else if (conflict) warn("state", `${STATE_FILE} has a merge conflict, and both sides were read`, "run `npx verbaly extract`, which writes both sides into it, then commit it");
2928
- if (catalogsHealthy) {
2929
- const stale = Object.entries(state.drafts).flatMap(([locale, keys]) => {
2930
- const live = new Set(effectiveDrafts({ [locale]: keys }, catalogs)[locale] ?? []);
2931
- return keys.filter((key) => !live.has(key)).map((key) => `${locale}: ${key}`);
2932
- });
2933
- if (stale.length > 0) warn("drafts", `${STATE_FILE} lists ${counted(stale.length, "draft")} whose translation is gone (${preview(stale)})`, "run `npx verbaly extract`, which drops them");
2934
- }
2935
- if (catalogsHealthy) {
2936
- const result = check(cfg, catalogs, registry, state.fingerprints);
2937
- if (result.unknown.length > 0) error("keys", `${counted(result.unknown.length, "unknown key")} used in code (${preview(result.unknown.map((u) => u.key))})`, "fix the key or add it to the catalogs (`npx verbaly check` for details)");
2938
- if (result.missing.length > 0) {
2939
- const locales = [...new Set(result.missing.map((m) => m.locale))];
2940
- warn("translations", `${counted(result.missing.length, "missing translation")} (${locales.join(", ")})`, "run `npx verbaly translate` or fill the catalogs (`npx verbaly check` for details)");
2941
- }
2942
- const broken = result.broken.filter((entry) => entry.severity === "error");
2943
- if (broken.length > 0) {
2944
- const locales = [...new Set(broken.map((b) => b.locale))];
2945
- error("translations", `${counted(broken.length, "broken translation")} (${locales.join(", ")}): present but not rendering what the source renders`, "run `npx verbaly check` to read what each one lost");
2946
- }
2947
- if (result.extra.length > 0) {
2948
- const shown = result.extra.map((entry) => `${entry.locale}: ${entry.key}`);
2949
- warn("extras", `a translation has ${counted(result.extra.length, "key")} the source catalog does not (${preview(shown)})`, scanning ? "add them to the source catalog if your code uses them, or run `npx verbaly extract --prune` to drop the rest" : "add them to the source catalog if your code uses them, or delete them from the translations");
2950
- }
2951
- const warnings = result.broken.filter((entry) => entry.severity === "warning");
2952
- if (warnings.length > 0) warn("translations", `${counted(warnings.length, "structural warning")} (plural forms a language asks for)`, "run `npx verbaly check` to read them, they never fail the build");
2953
- if (result.collisions.length > 0) {
2954
- const first = result.collisions[0];
2955
- error("keys", `${counted(result.collisions.length, "key")} written with more than one text, and every place shows the first (${first.key}: ${first.sites.map((at) => sourcePlace(at, cfg.root)).join(", ")})`, "give each text its own key (`npx verbaly check` lists every place)");
2956
- }
2957
- if (result.divergent.length > 0) {
2958
- const first = result.divergent[0];
2959
- warn("source texts", `the code and ${cfg.sourceLocale}.json disagree on ${counted(result.divergent.length, "text")}, and the code's text ships (${first.key}, ${sourcePlace(first.code, cfg.root)})`, "edit those texts in the code; `npx verbaly extract` writes them into the catalog");
2960
- }
2961
- if (result.outdated.length > 0) {
2962
- const shown = result.outdated.map((entry) => `${entry.locale}: ${entry.key}`);
2963
- warn("outdated", `${counted(result.outdated.length, "translation")} written for an older source text (${preview(shown)})`, "update them, or keep them with `npx verbaly review --approve`");
2964
- }
2965
- if (result.ok) ok("translations", "all translations complete");
2966
- }
2967
- return {
2968
- ok: entries.every((entry) => entry.level !== "error"),
2969
- entries
2970
- };
2971
- }
2972
- function preview(keys) {
2973
- const head = keys.slice(0, PREVIEW).join(", ");
2974
- return keys.length > PREVIEW ? `${head}, …` : head;
2975
- }
2976
- //#endregion
2977
- //#region src/translate.ts
2978
- const RETRY_STATUS = /* @__PURE__ */ new Set([
2979
- 408,
2980
- 409,
2981
- 425,
2982
- 429,
2983
- 500,
2984
- 502,
2985
- 503,
2986
- 504,
2987
- 529
2988
- ]);
2989
- function retryable(error) {
2990
- const status = error?.status;
2991
- const code = error?.statusCode;
2992
- const value = typeof status === "number" ? status : code;
2993
- return typeof value === "number" ? RETRY_STATUS.has(value) : true;
2994
- }
2995
- function reason(error) {
2996
- return error instanceof Error ? error.message : String(error);
2997
- }
2998
- const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
2999
- async function attempt(run, retries, delay) {
3000
- for (let round = 0;; round++) try {
3001
- return await run();
3002
- } catch (error) {
3003
- if (round >= retries || !retryable(error)) throw error;
3004
- await wait(delay * 2 ** round);
3005
- }
3006
- }
3007
- async function pooled(jobs, limit, run) {
3008
- let next = 0;
3009
- const workers = Array.from({ length: Math.min(limit, jobs.length) }, async () => {
3010
- while (next < jobs.length) await run(jobs[next++]);
3011
- });
3012
- await Promise.all(workers);
3013
- }
3014
- async function translateCatalogs(cfg, catalogs, provider, options = {}) {
3015
- const batchSize = options.batchSize ?? 20;
3016
- const concurrency = Math.max(1, options.concurrency ?? 4);
3017
- const retries = Math.max(0, options.retries ?? 2);
3018
- const retryDelay = options.retryDelay ?? 500;
3019
- const targets = targetLocales(cfg, options.locales);
3020
- const source = catalogs[cfg.sourceLocale] ?? {};
3021
- const result = {
3022
- translated: {},
3023
- invalid: {},
3024
- pending: {},
3025
- failed: []
3026
- };
3027
- const jobs = [];
3028
- for (const locale of targets) {
3029
- const catalog = catalogs[locale] ??= emptyCatalog();
3030
- const missing = Object.keys(source).filter((key) => source[key] && !own(catalog, key));
3031
- if (missing.length === 0) continue;
3032
- if (options.dryRun) {
3033
- result.pending[locale] = missing;
3034
- continue;
3035
- }
3036
- const batches = Math.ceil(missing.length / batchSize);
3037
- for (let i = 0; i < missing.length; i += batchSize) {
3038
- const index = Math.floor(i / batchSize) + 1;
3039
- jobs.push({
3040
- locale,
3041
- index,
3042
- batches,
3043
- keys: missing.slice(i, i + batchSize)
3044
- });
3045
- }
3046
- }
3047
- await pooled(jobs, concurrency, async (job) => {
3048
- const { locale, keys } = job;
3049
- const catalog = catalogs[locale];
3050
- const messages = Object.fromEntries(keys.map((key) => [key, source[key]]));
3051
- const origins = options.origins ? Object.fromEntries(keys.filter((key) => Object.hasOwn(options.origins, key)).map((key) => [key, options.origins[key]])) : void 0;
3052
- let out;
3053
- try {
3054
- out = await attempt(() => provider({
3055
- sourceLocale: cfg.sourceLocale,
3056
- targetLocale: locale,
3057
- messages,
3058
- origins,
3059
- instructions: cfg.translate.instructions,
3060
- glossary: glossaryFor(cfg, locale, messages)
3061
- }), retries, retryDelay);
3062
- } catch (error) {
3063
- const message = reason(error);
3064
- result.failed.push({
3065
- locale,
3066
- keys,
3067
- error: message
3068
- });
3069
- options.onProgress?.({
3070
- ...progressOf(job),
3071
- error: message
3072
- });
3073
- return;
3074
- }
3075
- for (const key of keys) {
3076
- const text = out[key];
3077
- if (typeof text === "string" && text.trim() && structureMatches(source[key], text)) {
3078
- catalog[key] = text;
3079
- (result.translated[locale] ??= []).push(key);
3080
- } else (result.invalid[locale] ??= []).push(key);
3081
- }
3082
- options.onProgress?.(progressOf(job));
3083
- });
3084
- for (const locale of Object.keys(result.translated)) result.translated[locale].sort();
3085
- for (const locale of Object.keys(result.invalid)) result.invalid[locale].sort();
3086
- result.failed.sort((a, b) => byCodeUnit(a.locale, b.locale) || compare(a.keys, b.keys));
3087
- return result;
3088
- }
3089
- function compare(a, b) {
3090
- return byCodeUnit(a[0] ?? "", b[0] ?? "");
3091
- }
3092
- function mergeTranslations(cfg, locale, translated, keys) {
3093
- const source = readCatalog(cfg, cfg.sourceLocale);
3094
- const current = readCatalog(cfg, locale);
3095
- const written = [];
3096
- for (const key of keys) {
3097
- const text = translated[key];
3098
- if (!source[key] || current[key] || !text) continue;
3099
- current[key] = text;
3100
- written.push(key);
3101
- }
3102
- if (written.length > 0) writeCatalog(cfg, locale, current);
3103
- return written;
3104
- }
3105
- function writeDrafts(cfg, locale, entries, options = {}) {
3106
- const targets = targetLocales(cfg);
3107
- if (!targets.includes(locale)) throw new Error(`[verbaly] "${locale}" is not a language this project translates into (${targets.join(", ") || "none yet"})`);
3108
- loadState(cfg);
3109
- const catalogs = { [cfg.sourceLocale]: readCatalog(cfg, cfg.sourceLocale) };
3110
- const source = options.registry ? shippedCatalogs(cfg, catalogs, options.registry, { newKeys: false })[cfg.sourceLocale] : catalogs[cfg.sourceLocale];
3111
- const current = readCatalog(cfg, locale);
3112
- const result = {
3113
- written: [],
3114
- kept: [],
3115
- invalid: [],
3116
- unknown: []
3117
- };
3118
- for (const { key, text } of entries) {
3119
- const from = own(source, key);
3120
- if (!from) result.unknown.push(key);
3121
- else if (!text.trim() || !structureMatches(from, text)) result.invalid.push(key);
3122
- else if (own(current, key) && !options.overwrite) result.kept.push(key);
3123
- else {
3124
- current[key] = text;
3125
- result.written.push(key);
3126
- }
3127
- }
3128
- if (result.written.length > 0) {
3129
- writeCatalog(cfg, locale, current);
3130
- recordTranslations(cfg, source, [{
3131
- locale,
3132
- entries: result.written.map((key) => ({
3133
- key,
3134
- text: current[key]
3135
- })),
3136
- draft: true
3137
- }]);
3138
- }
3139
- return result;
3140
- }
3141
- function formatTranslateFailures(failed) {
3142
- const grouped = [];
3143
- for (const entry of failed) {
3144
- const same = grouped.find((it) => it.locale === entry.locale && it.error === entry.error);
3145
- if (same) same.keys = [...same.keys, ...entry.keys];
3146
- else grouped.push({
3147
- ...entry,
3148
- keys: [...entry.keys]
3149
- });
3150
- }
3151
- return grouped.map(({ locale, error, keys }) => ` ${locale}: ${counted(keys.length, "message")} not translated (${error}): ${keys.join(", ")}`);
3152
- }
3153
- async function resolveProvider(cfg, model) {
3154
- const configured = cfg.translate.provider;
3155
- if (typeof configured === "function") return configured;
3156
- const { claudeProvider } = await import("./claude-Baoc6pYL.js");
3157
- return claudeProvider({ model: model ?? cfg.translate.model });
3158
- }
3159
- function structureMatches(source, translated) {
3160
- try {
3161
- return ![...validateMessage(translated), ...validatePair(source, translated)].some((issue) => issue.severity === "error");
3162
- } catch {
3163
- return false;
3164
- }
3165
- }
3166
- function progressOf(job) {
3167
- return {
3168
- locale: job.locale,
3169
- batch: job.index,
3170
- batches: job.batches,
3171
- keys: job.keys.length
3172
- };
3173
- }
3174
- function glossaryFor(cfg, locale, messages) {
3175
- const entries = cfg.translate.glossary;
3176
- if (!entries) return void 0;
3177
- const text = Object.values(messages).join("\n").toLowerCase();
3178
- const out = {};
3179
- for (const [term, rendering] of Object.entries(entries)) {
3180
- if (!text.includes(term.toLowerCase())) continue;
3181
- const value = typeof rendering === "string" ? rendering : rendering[locale];
3182
- if (value) out[term] = value;
3183
- }
3184
- return Object.keys(out).length > 0 ? out : void 0;
3185
- }
3186
- //#endregion
3187
- //#region src/render.ts
3188
- function localeInstance(catalogs, locale, sourceLocale) {
3189
- return createVerbaly({
3190
- locale,
3191
- fallback: sourceLocale,
3192
- messages: catalogs
3193
- });
3194
- }
3195
- const HREFLANG_OPEN = "<!--verbaly:hreflang-->";
3196
- const HREFLANG_CLOSE = "<!--/verbaly:hreflang-->";
3197
- const CATALOG_OPEN = "<!--verbaly:catalog-->";
3198
- const CATALOG_CLOSE = "<!--/verbaly:catalog-->";
3199
- const REDIRECT_OPEN = "<!--verbaly:redirect-->";
3200
- const REDIRECT_CLOSE = "<!--/verbaly:redirect-->";
3201
- const VOID = new Set(VOID_TAGS);
3202
- const START_TAG = /<([a-zA-Z][a-zA-Z0-9-]*)((?:"[^"]*"|'[^']*'|[^"'>])*)>/g;
3203
- const ATTR = /([^\s=/"'<>]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+)))?/g;
3204
- function renderHtml(html, options) {
3205
- const attr = options.attribute ?? "data-verbaly";
3206
- const argsAttr = `${attr}-args`;
3207
- const attrsAttr = `${attr}-attr`;
3208
- const richAttr = `${attr}-rich`;
3209
- const linksAttr = `${attr}-links`;
3210
- const richTags = new Set(options.richTags ?? RICH_TAGS);
3211
- const globalLinks = options.richLinks;
3212
- const sourceLocale = options.sourceLocale ?? "en";
3213
- const v = options.instance ?? localeInstance(options.catalogs, options.locale, sourceLocale);
3214
- const t = v.t;
3215
- const ms = new MagicString(html);
3216
- const missing = /* @__PURE__ */ new Set();
3217
- const used = /* @__PURE__ */ new Set();
3218
- const skip = protectedRanges(html);
3219
- const inSkip = (index) => skip.some(([from, to]) => index >= from && index < to);
3220
- const filled = [];
3221
- const inFilled = (index) => filled.some(([from, to]) => index >= from && index < to);
3222
- const selfUrl = options.alternates?.find((a) => a.hreflang === options.locale)?.href;
3223
- const sourceUrl = options.alternates?.find((a) => a.hreflang === "x-default")?.href;
3224
- const rewriteUrl = selfUrl !== void 0 && selfUrl !== sourceUrl;
3225
- START_TAG.lastIndex = 0;
3226
- let m;
3227
- while ((m = START_TAG.exec(html)) !== null) {
3228
- if (inSkip(m.index) || inFilled(m.index)) continue;
3229
- const [full, rawName, attrChunk] = m;
3230
- const tagName = rawName.toLowerCase();
3231
- const openEnd = m.index + full.length;
3232
- const chunkStart = m.index + 1 + rawName.length;
3233
- if (tagName === "html" && options.setLang !== false) {
3234
- setAttribute(ms, html, chunkStart, openEnd, attrChunk, "lang", options.locale);
3235
- setAttribute(ms, html, chunkStart, openEnd, attrChunk, "dir", localeDirection(options.locale));
3236
- continue;
3237
- }
3238
- const attrs = parseAttrs(attrChunk);
3239
- if (rewriteUrl && tagName === "link" && attrs.get("rel")?.toLowerCase() === "canonical" && decodeEntities(attrs.get("href") ?? "") === sourceUrl) setAttribute(ms, html, chunkStart, openEnd, attrChunk, "href", selfUrl);
3240
- if (rewriteUrl && tagName === "meta" && attrs.get("property") === "og:url" && decodeEntities(attrs.get("content") ?? "") === sourceUrl) setAttribute(ms, html, chunkStart, openEnd, attrChunk, "content", selfUrl);
3241
- const mirror = options.mirror;
3242
- if (mirror) {
3243
- if (tagName === "a" || tagName === "area") {
3244
- const inside = mirroredHref(attrs.get("href"), mirror);
3245
- if (inside) setAttribute(ms, html, chunkStart, openEnd, attrChunk, "href", inside);
3246
- } else if (tagName === "form" || tagName === "button" || tagName === "input") {
3247
- const name = tagName === "form" ? "action" : "formaction";
3248
- const inside = mirroredHref(attrs.get(name), mirror);
3249
- if (inside) setAttribute(ms, html, chunkStart, openEnd, attrChunk, name, inside);
3250
- } else if (tagName === "meta" && attrs.get("http-equiv")?.toLowerCase() === "refresh") {
3251
- const content = attrs.get("content") ?? "";
3252
- const url = /^([^;]*;\s*url\s*=\s*)(.*)$/i.exec(decodeEntities(content));
3253
- const inside = url && mirroredHref(url[2], mirror);
3254
- if (inside) setAttribute(ms, html, chunkStart, openEnd, attrChunk, "content", `${url[1]}${inside}`);
3255
- }
3256
- }
3257
- const key = attrs.get(attr);
3258
- const attrMapRaw = attrs.get(attrsAttr);
3259
- if (key === void 0 && attrMapRaw === void 0) continue;
3260
- const args = parseArgs(attrs.get(argsAttr), argsAttr);
3261
- if (key) {
3262
- if (!v.has(key)) missing.add(key);
3263
- else if (!VOID.has(tagName) && !attrChunk.trimEnd().endsWith("/")) {
3264
- used.add(key);
3265
- const close = findClose(html, tagName, openEnd, inSkip);
3266
- if (close) {
3267
- const text = t(key, args);
3268
- const own = parseArgs(attrs.get(linksAttr), linksAttr);
3269
- const merged = own ? globalLinks ? {
3270
- ...globalLinks,
3271
- ...own
3272
- } : own : globalLinks;
3273
- const links = mirror ? mirroredLinks(merged, mirror) : merged;
3274
- const nodes = attrs.has(richAttr) ? parseTags(text) : [];
3275
- if (mirror && links) {
3276
- const carried = usedLinks(nodes, links);
3277
- if (carried && JSON.stringify(carried) !== JSON.stringify(own)) setAttribute(ms, html, chunkStart, openEnd, attrChunk, linksAttr, JSON.stringify(carried));
3278
- }
3279
- const content = attrs.has(richAttr) ? richToHtml(nodes, richTags, links) : escapeHtml(text);
3280
- if (html.slice(openEnd, close.contentEnd) !== content) {
3281
- if (openEnd === close.contentEnd) ms.appendLeft(openEnd, content);
3282
- else ms.overwrite(openEnd, close.contentEnd, content);
3283
- }
3284
- filled.push([openEnd, close.contentEnd]);
3285
- }
3286
- }
3287
- }
3288
- if (attrMapRaw !== void 0) {
3289
- const map = parseArgs(attrMapRaw, attrsAttr);
3290
- if (map) for (const [name, attrKey] of Object.entries(map)) {
3291
- if (typeof attrKey !== "string") continue;
3292
- if (!v.has(attrKey)) {
3293
- missing.add(attrKey);
3294
- continue;
3295
- }
3296
- used.add(attrKey);
3297
- const value = safeAttribute(name, t(attrKey, args));
3298
- if (value !== void 0) setAttribute(ms, html, chunkStart, openEnd, attrChunk, name, value);
3299
- }
3300
- }
3301
- }
3302
- if (options.alternates?.length) injectAlternates(ms, html, options.alternates);
3303
- if (options.redirect) injectRedirect(ms, html, options.redirect);
3304
- if (options.inlineCatalog && options.locale !== sourceLocale) {
3305
- const slice = pageSlice(v, options.locale, used);
3306
- if (Object.keys(slice).length > 0) injectCatalog(ms, html, slice);
3307
- }
3308
- return {
3309
- html: ms.toString(),
3310
- missing: [...missing],
3311
- used: [...used]
3312
- };
3313
- }
3314
- function pageSlice(v, locale, used) {
3315
- const slice = Object.create(null);
3316
- for (const key of used) {
3317
- const found = v.inspect(key);
3318
- slice[key] = found?.from === locale ? found.source : "";
3319
- }
3320
- return slice;
3321
- }
3322
- function publicPath(rel) {
3323
- const path = `/${rel.replace(/(^|\/)index\.html$/, "$1")}`;
3324
- return path.length > 1 ? path.replace(/\/+$/, "") : path;
3325
- }
3326
- function linkFor(links, name) {
3327
- return links && Object.hasOwn(links, name) ? links[name] : void 0;
3328
- }
3329
- function usedLinks(nodes, links) {
3330
- const out = {};
3331
- const walk = (list) => {
3332
- for (const node of list) {
3333
- if (typeof node === "string") continue;
3334
- const link = linkFor(links, node.name);
3335
- if (link !== void 0) out[node.name] = link;
3336
- walk(node.children);
3337
- }
3338
- };
3339
- walk(nodes);
3340
- return Object.keys(out).length > 0 ? out : void 0;
3341
- }
3342
- function mirroredLinks(links, mirror) {
3343
- if (!links) return links;
3344
- const out = {};
3345
- for (const [name, link] of Object.entries(links)) {
3346
- const inside = mirroredHref(typeof link === "string" ? link : link.href, mirror);
3347
- if (inside === void 0) out[name] = link;
3348
- else out[name] = typeof link === "string" ? inside : {
3349
- ...link,
3350
- href: inside
3351
- };
3352
- }
3353
- return out;
3354
- }
3355
- function mirroredHref(raw, mirror) {
3356
- if (raw === void 0) return void 0;
3357
- const href = decodeEntities(raw);
3358
- if (!href.startsWith("/") || href.startsWith("//")) return void 0;
3359
- const base = mirror.base ?? "";
3360
- const inside = base ? stripBase(href, base) : href;
3361
- if (base && inside === href) return void 0;
3362
- const cut = inside.search(/[?#]/);
3363
- const path = cut < 0 ? inside : inside.slice(0, cut);
3364
- if (!mirror.pages.has(publicPath(path.replace(/^\//, "")))) return void 0;
3365
- return `${base}${mirror.prefix}${inside}`;
3366
- }
3367
- function stripBase(path, base) {
3368
- if (!path.startsWith(base)) return path;
3369
- const rest = path.slice(base.length);
3370
- if (rest === "") return "/";
3371
- return rest.startsWith("/") ? rest : path;
3372
- }
3373
- function normalizeBase(base) {
3374
- const trimmed = base?.replace(/^\/+/, "").replace(/\/+$/, "");
3375
- return trimmed ? `/${trimmed}` : "";
3376
- }
3377
- const REDIRECT_BODY = "(function(){var T=/^[a-z]{2,3}(-[a-z]{4})?(-([a-z]{2}|[0-9]{3}))?$/i;function M(t,g){t=String(t||\"\");if(S.indexOf(t)>=0)return t;if(g&&!T.test(t))return;while(t){var i=t.lastIndexOf(\"-\");if(i<0)return;t=t.slice(0,i);if(S.indexOf(t)>=0)return t}}var p=location.pathname;if(B){if(p.indexOf(B)!==0)return;p=p.slice(B.length)||\"/\";if(p.charAt(0)!==\"/\")return}if(M(p.split(\"/\")[1],1))return;var w;if(K)try{w=M(localStorage.getItem(K))}catch(e){}if(!w){var l=navigator.languages||[navigator.language];for(var i=0;i<l.length&&!w;i++)w=M(l[i])}if(!w||w===D)return;location.replace(B+\"/\"+w+p+location.search+location.hash)})()";
3378
- function jsLiteral(value) {
3379
- return JSON.stringify(value ?? null).replace(/</g, "\\u003c");
3380
- }
3381
- function redirectScript(options) {
3382
- return `<script>var ${[
3383
- `S=${jsLiteral(options.locales)}`,
3384
- `D=${jsLiteral(options.sourceLocale)}`,
3385
- `B=${jsLiteral(normalizeBase(options.base))}`,
3386
- `K=${options.storageKey === false ? "null" : jsLiteral(options.storageKey ?? LOCALE_STORAGE_KEY)}`
3387
- ].join(",")};${REDIRECT_BODY};<\/script>`;
3388
- }
3389
- function injectRedirect(ms, html, options) {
3390
- const block = `${REDIRECT_OPEN}${redirectScript(options)}${REDIRECT_CLOSE}`;
3391
- const from = html.indexOf(REDIRECT_OPEN);
3392
- if (from !== -1) {
3393
- const to = html.indexOf(REDIRECT_CLOSE, from);
3394
- if (to !== -1) {
3395
- const end = to + 24;
3396
- if (html.slice(from, end) !== block) ms.overwrite(from, end, block);
3397
- return;
3398
- }
3399
- }
3400
- const head = /<head\b(?:"[^"]*"|'[^']*'|[^"'>])*>/i.exec(html);
3401
- if (head) ms.appendRight(head.index + head[0].length, block);
3402
- }
3403
- function injectAlternates(ms, html, alternates) {
3404
- const links = alternates.map((a) => `<link rel="alternate" hreflang="${escapeAttr(a.hreflang)}" href="${escapeAttr(a.href)}">`).join("");
3405
- const block = `${HREFLANG_OPEN}${links}${HREFLANG_CLOSE}`;
3406
- const from = html.indexOf(HREFLANG_OPEN);
3407
- if (from !== -1) {
3408
- const to = html.indexOf(HREFLANG_CLOSE, from);
3409
- if (to !== -1) {
3410
- const end = to + 24;
3411
- if (html.slice(from, end) !== block) ms.overwrite(from, end, block);
3412
- return;
3413
- }
3414
- }
3415
- const head = /<\/head\s*>/i.exec(html);
3416
- if (head) ms.appendLeft(head.index, block);
3417
- }
3418
- function injectCatalog(ms, html, messages) {
3419
- const json = JSON.stringify(messages).replace(/<\//g, "<\\/").replace(/<!--/g, "\\u003c!--");
3420
- const tag = `<script ${CATALOG_SCRIPT} type="application/json">${json}<\/script>`;
3421
- const block = `${CATALOG_OPEN}${tag}${CATALOG_CLOSE}`;
3422
- const from = html.indexOf(CATALOG_OPEN);
3423
- if (from !== -1) {
3424
- const to = html.indexOf(CATALOG_CLOSE, from);
3425
- if (to !== -1) {
3426
- const end = to + 23;
3427
- if (html.slice(from, end) !== block) ms.overwrite(from, end, block);
3428
- return;
3429
- }
3430
- }
3431
- const head = /<\/head\s*>/i.exec(html);
3432
- if (head) ms.appendLeft(head.index, block);
3433
- }
3434
- const TITLE_TAG = /<title\b([^>]*)>/i;
3435
- const REFRESH_META = /<meta\b[^>]*http-equiv\s*=\s*["']?refresh/i;
3436
- const NOINDEX_META = /<meta\b[^>]*name\s*=\s*["']?robots["']?[^>]*content\s*=\s*["'][^"']*noindex/i;
3437
- function isIndexable(html) {
3438
- return !REFRESH_META.test(html) && !NOINDEX_META.test(html);
3439
- }
3440
- function headIsBound(html, attr) {
3441
- if (REFRESH_META.test(html)) return true;
3442
- const title = TITLE_TAG.exec(html);
3443
- return title ? title[1].includes(attr) : true;
3444
- }
3445
- async function renderSite(cfg, options = {}) {
3446
- const site = join(cfg.root, options.site ?? cfg.render.site ?? "dist");
3447
- const locales = options.locales ?? cfg.locales;
3448
- const attribute = options.attribute ?? cfg.render.attribute;
3449
- const base = normalizeBase(options.base ?? cfg.render.base);
3450
- const baseUrl = (options.baseUrl ?? cfg.render.baseUrl)?.replace(/\/+$/, "");
3451
- const wantHreflang = (options.hreflang ?? cfg.render.hreflang ?? true) && baseUrl !== void 0;
3452
- const patterns = options.exclude ?? cfg.render.exclude ?? [];
3453
- const excluded = patterns.length > 0 ? picomatch(patterns) : () => false;
3454
- const sitemap = options.sitemap ?? cfg.render.sitemap ?? false;
3455
- const wantSitemap = sitemap !== false && baseUrl !== void 0;
3456
- const clean = options.clean ?? cfg.render.clean ?? false;
3457
- const wanted = options.redirect ?? cfg.render.redirect ?? false;
3458
- const redirect = wanted === false ? void 0 : wanted === true ? {} : wanted;
3459
- const script = redirect && {
3460
- locales,
3461
- sourceLocale: cfg.sourceLocale,
3462
- base,
3463
- storageKey: redirect.storageKey
3464
- };
3465
- const catalogs = shippedCatalogs(cfg, loadCatalogs(cfg), await extractProject(cfg));
3466
- const instances = new Map(locales.map((locale) => [locale, localeInstance(catalogs, locale, cfg.sourceLocale)]));
3467
- if (clean) {
3468
- for (const locale of locales) if (locale !== cfg.sourceLocale) rmSync(join(site, locale), {
3469
- recursive: true,
3470
- force: true
3471
- });
3472
- }
3473
- const files = await glob("**/*.html", {
3474
- cwd: site,
3475
- absolute: true,
3476
- ignore: locales.map((locale) => `${locale}/**`)
3477
- });
3478
- const pages = new Set(files.map((file) => publicPath(relative(site, file).replace(/\\/g, "/"))));
3479
- const missing = {};
3480
- const untranslatedHead = [];
3481
- const urls = [];
3482
- for (const file of files) {
3483
- const html = readFileSync(file, "utf8");
3484
- const rel = relative(site, file).replace(/\\/g, "/");
3485
- if (locales.length > 1 && !headIsBound(html, attribute ?? "data-verbaly")) untranslatedHead.push(rel);
3486
- const alternates = wantHreflang ? pageAlternates(baseUrl, rel, locales, cfg.sourceLocale) : [];
3487
- if (wantHreflang && isIndexable(html) && !excluded(rel)) urls.push({
3488
- rel,
3489
- alternates
3490
- });
3491
- const routed = script && (redirect.on === "all" || rel === "index.html");
3492
- for (const locale of locales) {
3493
- const result = renderHtml(html, {
3494
- locale,
3495
- instance: instances.get(locale),
3496
- sourceLocale: cfg.sourceLocale,
3497
- attribute,
3498
- richTags: options.richTags,
3499
- richLinks: options.richLinks ?? cfg.render.links,
3500
- alternates,
3501
- mirror: locale === cfg.sourceLocale ? void 0 : {
3502
- prefix: `/${locale}`,
3503
- base,
3504
- pages
3505
- },
3506
- redirect: routed && locale === cfg.sourceLocale ? script : void 0,
3507
- inlineCatalog: cfg.render.inlineCatalog === true
3508
- });
3509
- for (const key of result.missing) {
3510
- const list = missing[locale] ??= [];
3511
- if (!list.includes(key)) list.push(key);
3512
- }
3513
- const out = locale === cfg.sourceLocale ? file : join(site, locale, rel);
3514
- mkdirSync(dirname(out), { recursive: true });
3515
- writeFileSync(out, result.html);
3516
- }
3517
- }
3518
- if (wantSitemap && urls.length) writeFileSync(join(site, typeof sitemap === "string" ? sitemap : "sitemap-i18n.xml"), buildSitemap(urls));
3519
- return {
3520
- files: files.length,
3521
- locales: [...locales],
3522
- missing,
3523
- untranslatedHead
3524
- };
3525
- }
3526
- function formatRenderWarnings(result, sourceLocale) {
3527
- const lines = [];
3528
- for (const [locale, keys] of Object.entries(result.missing)) lines.push(` ${locale}: ${counted(keys.length, "key")} not pre-filled: ${keys.join(", ")}`);
3529
- if (result.untranslatedHead.length > 0) lines.push(` ${counted(result.untranslatedHead.length, "page")} of ${result.files} ship the same <title> in every locale (${result.untranslatedHead[0]}), so search results read in ${sourceLocale}`, ` fix: bind the head too, <title data-verbaly="key"> and a meta through data-verbaly-attr`);
3530
- return lines;
3531
- }
3532
- function pagePath(rel) {
3533
- const path = rel.replace(/(^|\/)index\.html$/, "$1");
3534
- return path ? `/${path}` : "/";
3535
- }
3536
- function pageAlternates(baseUrl, rel, locales, sourceLocale) {
3537
- return alternateLinks({
3538
- supported: locales,
3539
- sourceLocale,
3540
- path: pagePath(rel),
3541
- routing: "prefix-except-source",
3542
- baseUrl
3543
- });
3544
- }
3545
- function buildSitemap(urls) {
3546
- return `<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml">${urls.flatMap(({ alternates }) => {
3547
- const alts = alternates.map((a) => `<xhtml:link rel="alternate" hreflang="${a.hreflang}" href="${escapeAttr(a.href)}"/>`).join("");
3548
- return alternates.filter((a) => a.hreflang !== "x-default").map((self) => `<url><loc>${escapeAttr(self.href)}</loc>${alts}</url>`);
3549
- }).join("")}</urlset>\n`;
3550
- }
3551
- function parseAttrs(chunk) {
3552
- const attrs = /* @__PURE__ */ new Map();
3553
- ATTR.lastIndex = 0;
3554
- let m;
3555
- while ((m = ATTR.exec(chunk)) !== null) attrs.set(m[1].toLowerCase(), m[2] ?? m[3] ?? m[4] ?? "");
3556
- return attrs;
3557
- }
3558
- function parseArgs(raw, attribute) {
3559
- if (!raw) return void 0;
3560
- try {
3561
- return JSON.parse(decodeEntities(raw));
3562
- } catch {
3563
- warnOnce(`invalid JSON in ${attribute}: ${raw}`, `${attribute}:${raw}`);
3564
- return;
3565
- }
3566
- }
3567
- function protectedRanges(html) {
3568
- const ranges = [];
3569
- const re = /<!--[\s\S]*?-->|<script\b[\s\S]*?<\/script\s*>|<style\b[\s\S]*?<\/style\s*>/gi;
3570
- let m;
3571
- while ((m = re.exec(html)) !== null) {
3572
- const openEnd = m[0].startsWith("<!--") ? m.index : html.indexOf(">", m.index) + 1;
3573
- ranges.push([openEnd, m.index + m[0].length]);
3574
- }
3575
- return ranges;
3576
- }
3577
- function findClose(html, tagName, from, inSkip) {
3578
- const re = new RegExp(`<${tagName}(?=[\\s/>])(?:"[^"]*"|'[^']*'|[^"'>])*>|</${tagName}\\s*>`, "gi");
3579
- re.lastIndex = from;
3580
- let depth = 1;
3581
- let m;
3582
- while ((m = re.exec(html)) !== null) {
3583
- if (inSkip(m.index)) continue;
3584
- if (m[0][1] === "/") {
3585
- depth -= 1;
3586
- if (depth === 0) return { contentEnd: m.index };
3587
- } else if (!m[0].endsWith("/>")) depth += 1;
3588
- }
3589
- return null;
3590
- }
3591
- function setAttribute(ms, html, chunkStart, openEnd, attrChunk, name, value) {
3592
- const escaped = escapeAttr(value);
3593
- const existing = new RegExp(`(\\s${name}\\s*=\\s*)("[^"]*"|'[^']*'|[^\\s>]+)`, "i").exec(attrChunk);
3594
- if (existing) {
3595
- const valueStart = chunkStart + existing.index + existing[1].length;
3596
- const valueEnd = valueStart + existing[2].length;
3597
- if (html.slice(valueStart, valueEnd) !== `"${escaped}"`) ms.overwrite(valueStart, valueEnd, `"${escaped}"`);
3598
- return;
3599
- }
3600
- const insertAt = openEnd - (html.slice(openEnd - 2, openEnd) === "/>" ? 2 : 1);
3601
- ms.appendLeft(insertAt, ` ${name}="${escaped}"`);
3602
- }
3603
- function richToHtml(nodes, allowed, links) {
3604
- let out = "";
3605
- for (const node of nodes) {
3606
- const link = typeof node === "string" ? void 0 : linkFor(links, node.name);
3607
- if (typeof node === "string") out += escapeHtml(node);
3608
- else if (link !== void 0) {
3609
- const { href, target, rel } = normalizeLink(link);
3610
- let attrs = href !== void 0 ? ` href="${escapeAttr(href)}"` : "";
3611
- if (target) attrs += ` target="${escapeAttr(target)}"`;
3612
- if (rel) attrs += ` rel="${escapeAttr(rel)}"`;
3613
- out += `<a${attrs}>${richToHtml(node.children, allowed, links)}</a>`;
3614
- } else if (allowed.has(node.name)) out += VOID.has(node.name) ? `<${node.name}>` : `<${node.name}>${richToHtml(node.children, allowed, links)}</${node.name}>`;
3615
- else out += richToHtml(node.children, allowed, links);
3616
- }
3617
- return out;
3618
- }
3619
- function escapeHtml(text) {
3620
- return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
3621
- }
3622
- function escapeAttr(text) {
3623
- return escapeHtml(text).replace(/"/g, "&quot;");
3624
- }
3625
- function decodeEntities(text) {
3626
- return text.replace(/&quot;/g, "\"").replace(/&#39;/g, "'").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&");
3627
- }
3628
- //#endregion
3629
- //#region src/watch.ts
3630
- const NATIVE_TREE = process.platform === "darwin" || process.platform === "win32";
3631
- function watchTree(root, options, onFile) {
3632
- const watchers = /* @__PURE__ */ new Map();
3633
- const close = (name) => {
3634
- watchers.get(name)?.close();
3635
- watchers.delete(name);
3636
- };
3637
- const open = (name, recursive, listener) => {
3638
- const watcher = watch(join(root, name), {
3639
- recursive,
3640
- persistent: options.persistent ?? true
3641
- }, listener);
3642
- watcher.on("error", (error) => {
3643
- close(name);
3644
- console.warn(`[verbaly] stopped watching ${name || "the project"}:`, error);
3645
- });
3646
- watchers.set(name, watcher);
3647
- };
3648
- if (options.native ?? NATIVE_TREE) open("", true, (_event, file) => {
3649
- if (file) onFile(file);
3650
- });
3651
- else {
3652
- const sync = (name) => {
3653
- close(name);
3654
- if (name !== options.keep && (name === "node_modules" || name.startsWith("."))) return;
3655
- try {
3656
- if (!lstatSync(join(root, name)).isDirectory()) return;
3657
- open(name, true, (_event, file) => {
3658
- if (file) onFile(`${name}/${file}`);
3659
- });
3660
- } catch (error) {
3661
- if (error.code !== "ENOENT") console.warn(`[verbaly] could not watch ${name}:`, error);
3662
- }
3663
- };
3664
- open("", false, (event, file) => {
3665
- if (!file) return;
3666
- if (event === "rename") sync(file);
3667
- onFile(file);
3668
- });
3669
- for (const entry of readdirSync(root, { withFileTypes: true })) if (entry.isDirectory()) sync(entry.name);
3670
- }
3671
- return () => {
3672
- for (const name of [...watchers.keys()]) close(name);
3673
- };
3674
- }
3675
- //#endregion
3676
- //#region src/wrap.ts
3677
- const WRAP_ATTRS = /* @__PURE__ */ new Set([
3678
- "title",
3679
- "alt",
3680
- "placeholder",
3681
- "aria-label"
3682
- ]);
3683
- const CODE_TAGS = /* @__PURE__ */ new Set([
3684
- "code",
3685
- "pre",
3686
- "kbd",
3687
- "samp",
3688
- "var"
3689
- ]);
3690
- const T_NAMES = /* @__PURE__ */ new Set(["t"]);
3691
- const LETTER = /\p{L}/u;
3692
- const WHITESPACE = /\s/;
3693
- async function wrapProject(cfg, options = {}) {
3694
- const files = (await glob(cfg.include, {
3695
- cwd: cfg.root,
3696
- ignore: cfg.exclude,
3697
- absolute: true
3698
- })).filter((file) => /\.[jt]sx$/.test(file));
3699
- const result = {
3700
- files: files.length,
3701
- changed: [],
3702
- wrapped: [],
3703
- skipped: [],
3704
- blocked: []
3705
- };
3706
- for (const file of files) {
3707
- const code = readFileSync(file, "utf8");
3708
- const label = relative(cfg.root, file).replaceAll("\\", "/");
3709
- const out = wrapCode(code, label);
3710
- result.wrapped.push(...out.wrapped);
3711
- result.skipped.push(...out.skipped);
3712
- if (out.code === void 0) continue;
3713
- result.changed.push(label);
3714
- if (!out.hasT) {
3715
- result.blocked.push({
3716
- file: label,
3717
- texts: out.wrapped.length,
3718
- client: out.client
3719
- });
3720
- continue;
3721
- }
3722
- if (options.write) writeFileSync(file, out.code);
3723
- }
3724
- return result;
3725
- }
3726
- function wrapCode(code, file) {
3727
- const wrapped = [];
3728
- const skipped = [];
3729
- let ast;
3730
- try {
3731
- ast = parse$1(code, {
3732
- sourceType: "module",
3733
- errorRecovery: true,
3734
- plugins: ["typescript", "jsx"]
3735
- }).program;
3736
- } catch {
3737
- return {
3738
- wrapped,
3739
- skipped,
3740
- hasT: false,
3741
- client: false
3742
- };
3743
- }
3744
- const hasT = declaresT(ast);
3745
- const client = hasDirective(ast, "use client");
3746
- const s = new MagicString(code);
3747
- const visited = /* @__PURE__ */ new Set();
3748
- let changed = false;
3749
- walk$1(ast, (node) => {
3750
- if (node.type !== "JSXElement" && node.type !== "JSXFragment") return;
3751
- if (visited.has(node)) return;
3752
- processElement(node);
3753
- });
3754
- return changed ? {
3755
- code: s.toString(),
3756
- wrapped,
3757
- skipped,
3758
- hasT,
3759
- client
3760
- } : {
3761
- wrapped,
3762
- skipped,
3763
- hasT,
3764
- client
3765
- };
3766
- function processElement(node) {
3767
- visited.add(node);
3768
- if (node.type === "JSXElement") {
3769
- const opening = node.openingElement;
3770
- const name = opening.name;
3771
- if (name.type === "JSXIdentifier" && name.name === "Trans") return markSubtree(node);
3772
- if (hasVerbalyAttr(opening)) return markSubtree(node);
3773
- if (name.type === "JSXIdentifier" && CODE_TAGS.has(name.name)) return markSubtree(node);
3774
- wrapAttributes(opening);
3775
- }
3776
- const children = node.children ?? [];
3777
- const hasElementChild = children.some((c) => c.type === "JSXElement" || c.type === "JSXFragment");
3778
- const hasText = children.some((c) => c.type === "JSXText" && LETTER.test(c.value) || c.type === "JSXExpressionContainer" && c.expression.type === "StringLiteral" && LETTER.test(c.expression.value));
3779
- if (hasElementChild && hasText) {
3780
- skip(node, snippet(children), "mixed text and markup: wrap by hand or use <Trans>");
3781
- return markSubtree(node);
3782
- }
3783
- if (hasText) {
3784
- wrapSegment(node, children);
3785
- return markSubtree(node);
3786
- }
3787
- for (const child of children) if (child.type === "JSXElement" || child.type === "JSXFragment") processElement(child);
3788
- }
3789
- function wrapSegment(parent, children) {
3790
- const meaningful = children.filter((c) => c.type === "JSXText" && c.value.trim() !== "" || c.type === "JSXExpressionContainer" && c.expression.type !== "JSXEmptyExpression");
3791
- if (meaningful.length === 0) return;
3792
- const first = meaningful[0];
3793
- const last = meaningful[meaningful.length - 1];
3794
- if (first.type === "JSXExpressionContainer" && meaningful.length > 1) {
3795
- skip(parent, snippet(children), "starts with an interpolation: wrap the sentence by hand");
3796
- return;
3797
- }
3798
- let template = "";
3799
- let report = "";
3800
- for (let i = children.indexOf(first); i <= children.indexOf(last); i++) {
3801
- const child = children[i];
3802
- if (child.type === "JSXText") {
3803
- let value = cleanJsxText(child.value);
3804
- if (child === first) value = value.trimStart();
3805
- if (child === last) value = value.trimEnd();
3806
- template += escapeTemplate(value);
3807
- report += value;
3808
- } else if (child.type === "JSXExpressionContainer") {
3809
- const expr = child.expression;
3810
- if (expr.type === "JSXEmptyExpression") continue;
3811
- if (usesT(expr)) {
3812
- skip(parent, snippet(children), "already uses t: finish it by hand");
3813
- return;
3814
- }
3815
- if (containsJsx(expr)) {
3816
- skip(parent, snippet(children), "an expression renders markup: wrap by hand or use <Trans>");
3817
- markSubtree(child);
3818
- return;
3819
- }
3820
- if (expr.type === "StringLiteral") {
3821
- template += escapeTemplate(expr.value);
3822
- report += expr.value;
3823
- } else {
3824
- const source = code.slice(expr.start, expr.end);
3825
- template += "${" + source + "}";
3826
- report += "${" + source + "}";
3827
- }
3828
- } else return;
3829
- }
3830
- if (!LETTER.test(report)) return;
3831
- if (isIdentifierLike(report)) return;
3832
- const start = first.type === "JSXText" ? first.start + leadingWs(first.value) : first.start;
3833
- const end = last.type === "JSXText" ? last.end - trailingWs(last.value) : last.end;
3834
- s.overwrite(start, end, "{t`" + template + "`}");
3835
- changed = true;
3836
- wrapped.push({
3837
- file,
3838
- line: line(first),
3839
- text: report,
3840
- kind: "text"
3841
- });
3842
- }
3843
- function wrapAttributes(opening) {
3844
- for (const attr of opening.attributes) {
3845
- if (attr.type !== "JSXAttribute") continue;
3846
- const name = attr.name;
3847
- if (name.type !== "JSXIdentifier" || !WRAP_ATTRS.has(name.name)) continue;
3848
- const value = attr.value;
3849
- if (value?.type !== "StringLiteral") continue;
3850
- const raw = value.value;
3851
- if (!LETTER.test(raw) || isIdentifierLike(raw)) continue;
3852
- s.overwrite(value.start, value.end, "{t`" + escapeTemplate(raw) + "`}");
3853
- changed = true;
3854
- wrapped.push({
3855
- file,
3856
- line: line(value),
3857
- text: raw,
3858
- kind: "attribute",
3859
- attribute: name.name
3860
- });
3861
- }
3862
- }
3863
- function skip(node, text, reason) {
3864
- skipped.push({
3865
- file,
3866
- line: line(node),
3867
- text,
3868
- reason
3869
- });
3870
- }
3871
- function snippet(children) {
3872
- const start = children[0]?.start ?? 0;
3873
- const end = children[children.length - 1]?.end ?? start;
3874
- const text = code.slice(start, end).replace(/\s+/g, " ").trim();
3875
- return text.length > 60 ? text.slice(0, 59) + "…" : text;
3876
- }
3877
- function markSubtree(node) {
3878
- walk$1(node, (n) => {
3879
- if (n.type === "JSXElement" || n.type === "JSXFragment") visited.add(n);
3880
- });
3881
- }
3882
- }
3883
- function isIdentifierLike(text) {
3884
- const trimmed = text.trim();
3885
- if (WHITESPACE.test(trimmed)) return false;
3886
- const first = [...trimmed].find((char) => LETTER.test(char));
3887
- return first !== void 0 && first !== first.toUpperCase();
3888
- }
3889
- function hasDirective(program, value) {
3890
- return (program.directives ?? []).some((d) => d.value?.value === value);
3891
- }
3892
- function declaresT(program) {
3893
- let found = false;
3894
- walk$1(program, (node) => {
3895
- if (found) return;
3896
- if (node.type === "ImportDeclaration") {
3897
- for (const spec of node.specifiers) if (isTName(spec.local?.name)) found = true;
3898
- return;
3899
- }
3900
- if (node.type === "VariableDeclarator" && bindsT(node.id)) found = true;
3901
- if (node.type === "FunctionDeclaration" && isTName(node.id?.name)) found = true;
3902
- if (node.params?.some((param) => bindsT(param))) found = true;
3903
- });
3904
- return found;
3905
- }
3906
- function bindsT(pattern) {
3907
- if (!pattern) return false;
3908
- if (pattern.type === "Identifier") return isTName(pattern.name);
3909
- if (pattern.type === "AssignmentPattern") return bindsT(pattern.left);
3910
- if (pattern.type === "ObjectPattern") return pattern.properties.some((prop) => prop.type === "RestElement" ? bindsT(prop.argument) : bindsT(prop.value));
3911
- if (pattern.type === "ArrayPattern") return pattern.elements.some((el) => bindsT(el ?? void 0));
3912
- return false;
3913
- }
3914
- function isTName(name) {
3915
- return typeof name === "string" && T_NAMES.has(name);
3916
- }
3917
- function hasVerbalyAttr(opening) {
3918
- return opening.attributes.some((attr) => {
3919
- if (attr.type !== "JSXAttribute") return false;
3920
- const name = attr.name;
3921
- return name.type === "JSXIdentifier" && name.name.startsWith("data-verbaly");
3922
- });
3923
- }
3924
- function usesT(node) {
3925
- let found = false;
3926
- walk$1(node, (n) => {
3927
- if (n.type === "TaggedTemplateExpression" && isTReference(n.tag, T_NAMES)) found = true;
3928
- if (n.type === "CallExpression" && isTReference(n.callee, T_NAMES)) found = true;
3929
- });
3930
- return found;
3931
- }
3932
- function containsJsx(node) {
3933
- let found = false;
3934
- walk$1(node, (n) => {
3935
- if (n.type === "JSXElement" || n.type === "JSXFragment") found = true;
3936
- });
3937
- return found;
3938
- }
3939
- function escapeTemplate(text) {
3940
- return text.replace(/[\\`]/g, "\\$&").replace(/\$\{/g, "\\${");
3941
- }
3942
- function leadingWs(text) {
3943
- return text.length - text.trimStart().length;
3944
- }
3945
- function trailingWs(text) {
3946
- return text.length - text.trimEnd().length;
3947
- }
3948
- function line(node) {
3949
- return node.loc?.start?.line ?? 1;
3950
- }
3951
- //#endregion
3952
- //#region src/run.ts
3953
- function formatCliError(error) {
3954
- const message = error instanceof Error ? error.message : String(error);
3955
- return message.startsWith("[verbaly]") ? message : `[verbaly] ${message}`;
3956
- }
3957
- //#endregion
3958
14
  export { LOCALE_MODULE_PREFIX, MessageRegistry, RESOLVED_VIRTUAL_ID, SOURCE_FILE_RE, STATE_FILE, check, clearDrafts, clientCatalogs, collectOrigins, collisionEntries, counted, createDevReporter, createSourceFilter, doctor, effectiveDrafts, extractProject, formatCheckResult, formatCheckWarnings, formatCliError, formatCollision, formatDoctorEntry, formatDoctorHealth, formatFinding, formatRenderWarnings, formatStatusResult, formatTranslateFailures, generateDts, generateLocaleModule, generateRuntimeModule, init, isTransformTarget, loadCatalogs, loadConfig, loadDrafts, loadState, loadVirtualModule, markDrafts, mergeTranslations, needsIcu, needsRelative, outdatedTranslations, parseCatalog, pruneCatalogs, readCatalog, readState, recordTranslations, renderSite, reportOutsideInclude, resolveConfig, resolveProvider, resolveVirtualId, runBuildGate, saveDrafts, shippedCatalogs, stableKey, status, syncCatalogs, syncProject, targetLocales, transformCode, transformSource, translateCatalogs, updateState, validateMessage, validatePair, watchTree, wrapProject, writeCatalog, writeDrafts, writeDts };
3959
-
3960
- //# sourceMappingURL=index.js.map