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