@verbaly/compiler 0.80.0 → 0.82.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 +20 -18
- package/dist/{claude-DelQkcx5.js → claude-D31sQLmS.js} +3 -2
- package/dist/cli.js +1 -1
- package/dist/index.d.ts +78 -41
- package/dist/index.js +2 -2
- package/dist/{run-DTmm0EUF.js → run-We8xWd57.js} +1170 -812
- package/package.json +3 -3
|
@@ -9,7 +9,7 @@ import { createHash } from "node:crypto";
|
|
|
9
9
|
import { applyEdits, modify, parse as parse$2 } from "jsonc-parser";
|
|
10
10
|
import picomatch from "picomatch";
|
|
11
11
|
import MagicString from "magic-string";
|
|
12
|
-
import { parseArgs } from "node:util";
|
|
12
|
+
import { parseArgs as parseArgs$1 } from "node:util";
|
|
13
13
|
// src/config/host.ts
|
|
14
14
|
const HOSTS = [
|
|
15
15
|
{
|
|
@@ -55,6 +55,7 @@ const HOSTS = [
|
|
|
55
55
|
},
|
|
56
56
|
{
|
|
57
57
|
name: "vite",
|
|
58
|
+
bundler: true,
|
|
58
59
|
dep: "vite",
|
|
59
60
|
pkg: "@verbaly/vite",
|
|
60
61
|
install: ["verbaly", "@verbaly/vite"],
|
|
@@ -62,6 +63,7 @@ const HOSTS = [
|
|
|
62
63
|
},
|
|
63
64
|
{
|
|
64
65
|
name: "webpack",
|
|
66
|
+
bundler: true,
|
|
65
67
|
dep: "webpack",
|
|
66
68
|
pkg: "@verbaly/unplugin",
|
|
67
69
|
install: ["verbaly", "@verbaly/unplugin"],
|
|
@@ -69,6 +71,7 @@ const HOSTS = [
|
|
|
69
71
|
},
|
|
70
72
|
{
|
|
71
73
|
name: "rspack",
|
|
74
|
+
bundler: true,
|
|
72
75
|
dep: "@rspack/core",
|
|
73
76
|
pkg: "@verbaly/unplugin",
|
|
74
77
|
install: ["verbaly", "@verbaly/unplugin"],
|
|
@@ -76,6 +79,7 @@ const HOSTS = [
|
|
|
76
79
|
},
|
|
77
80
|
{
|
|
78
81
|
name: "rollup",
|
|
82
|
+
bundler: true,
|
|
79
83
|
dep: "rollup",
|
|
80
84
|
pkg: "@verbaly/unplugin",
|
|
81
85
|
install: ["verbaly", "@verbaly/unplugin"],
|
|
@@ -83,6 +87,7 @@ const HOSTS = [
|
|
|
83
87
|
},
|
|
84
88
|
{
|
|
85
89
|
name: "esbuild",
|
|
90
|
+
bundler: true,
|
|
86
91
|
dep: "esbuild",
|
|
87
92
|
pkg: "@verbaly/unplugin",
|
|
88
93
|
install: ["verbaly", "@verbaly/unplugin"],
|
|
@@ -103,9 +108,42 @@ function readDependencies(root) {
|
|
|
103
108
|
return {};
|
|
104
109
|
}
|
|
105
110
|
}
|
|
111
|
+
const ADAPTERS = [
|
|
112
|
+
["@verbaly/react", [
|
|
113
|
+
"react",
|
|
114
|
+
"preact",
|
|
115
|
+
"@verbaly/react"
|
|
116
|
+
]],
|
|
117
|
+
["@verbaly/vue", [
|
|
118
|
+
"vue",
|
|
119
|
+
"nuxt",
|
|
120
|
+
"@verbaly/vue"
|
|
121
|
+
]],
|
|
122
|
+
["@verbaly/svelte", [
|
|
123
|
+
"svelte",
|
|
124
|
+
"@sveltejs/kit",
|
|
125
|
+
"@verbaly/svelte"
|
|
126
|
+
]]
|
|
127
|
+
];
|
|
128
|
+
function adaptersIn(deps) {
|
|
129
|
+
return ADAPTERS.filter(([, libs]) => libs.some((lib) => deps[lib])).map(([adapter]) => adapter);
|
|
130
|
+
}
|
|
131
|
+
function componentAdapters(root) {
|
|
132
|
+
return adaptersIn(readDependencies(root));
|
|
133
|
+
}
|
|
106
134
|
function detectHost(root) {
|
|
107
135
|
const deps = readDependencies(root);
|
|
108
|
-
|
|
136
|
+
const host = HOSTS.find((entry) => deps[entry.dep]);
|
|
137
|
+
if (!host?.bundler) return host;
|
|
138
|
+
const install = [
|
|
139
|
+
...host.install.slice(0, 1),
|
|
140
|
+
...adaptersIn(deps),
|
|
141
|
+
...host.install.slice(1)
|
|
142
|
+
];
|
|
143
|
+
return {
|
|
144
|
+
...host,
|
|
145
|
+
install
|
|
146
|
+
};
|
|
109
147
|
}
|
|
110
148
|
const LOCKFILES = [
|
|
111
149
|
["pnpm-lock.yaml", "pnpm"],
|
|
@@ -169,7 +207,9 @@ function resolveConfig(config = {}) {
|
|
|
169
207
|
const sourceLocale = config.sourceLocale ?? "en";
|
|
170
208
|
const host = detectHost(root)?.name;
|
|
171
209
|
const localesDeclared = config.locales !== void 0;
|
|
172
|
-
const
|
|
210
|
+
const written = config.locales;
|
|
211
|
+
const listed = typeof written === "string" ? [written] : config.locales ?? [];
|
|
212
|
+
const locales = /* @__PURE__ */ new Set([sourceLocale, ...listed]);
|
|
173
213
|
if (!localesDeclared && existsSync(dir)) {
|
|
174
214
|
for (const file of readdirSync(dir)) if (file.endsWith(".json") && !file.startsWith(".") && file !== `en-XA.json`) locales.add(file.slice(0, -5));
|
|
175
215
|
}
|
|
@@ -361,10 +401,19 @@ function isNested(tree) {
|
|
|
361
401
|
function group() {
|
|
362
402
|
return Object.create(null);
|
|
363
403
|
}
|
|
364
|
-
function
|
|
404
|
+
function pathsOf(tree, prefix = [], out = /* @__PURE__ */ new Map()) {
|
|
405
|
+
for (const [name, value] of Object.entries(tree)) {
|
|
406
|
+
const path = [...prefix, name];
|
|
407
|
+
if (typeof value === "string") out.set(path.join("."), path);
|
|
408
|
+
else if (isTree(value)) pathsOf(value, path, out);
|
|
409
|
+
}
|
|
410
|
+
return out;
|
|
411
|
+
}
|
|
412
|
+
function nest(catalog, shape) {
|
|
365
413
|
const tree = group();
|
|
414
|
+
const written = shape ? pathsOf(shape) : void 0;
|
|
366
415
|
for (const [key, message] of Object.entries(catalog).sort(([a], [b]) => a < b ? -1 : 1)) {
|
|
367
|
-
const parts = key.split(".");
|
|
416
|
+
const parts = written?.get(key) ?? key.split(".");
|
|
368
417
|
const leaf = parts[parts.length - 1];
|
|
369
418
|
let node = parts.length > 1 ? tree : void 0;
|
|
370
419
|
for (let i = 0; node && i < parts.length - 1; i++) {
|
|
@@ -407,8 +456,8 @@ function orderLike(tree, previous) {
|
|
|
407
456
|
for (const key of Object.keys(tree).sort()) if (!Object.hasOwn(previous, key)) take(key);
|
|
408
457
|
return out;
|
|
409
458
|
}
|
|
410
|
-
function serializeCatalog(catalog, nested = false, previous) {
|
|
411
|
-
const tree = nested ? nest(catalog) : catalog;
|
|
459
|
+
function serializeCatalog(catalog, nested = false, previous, shape = previous) {
|
|
460
|
+
const tree = nested ? nest(catalog, shape) : catalog;
|
|
412
461
|
return JSON.stringify(previous ? orderLike(tree, previous) : sortTree(tree), null, 2) + "\n";
|
|
413
462
|
}
|
|
414
463
|
function writeCatalog(cfg, locale, catalog) {
|
|
@@ -421,17 +470,20 @@ function writeCatalog(cfg, locale, catalog) {
|
|
|
421
470
|
}
|
|
422
471
|
const parsed = existing === void 0 ? void 0 : parseTree(existing);
|
|
423
472
|
const previous = isTree(parsed) ? parsed : void 0;
|
|
424
|
-
const
|
|
473
|
+
const shape = shapeFor(cfg, locale, existing, previous);
|
|
474
|
+
const serialized = withLineEndings(serializeCatalog(catalog, shape !== void 0 && isNested(shape), previous, shape), existing);
|
|
425
475
|
if (existing === serialized) return serialized;
|
|
426
476
|
writeFileSync(path, serialized);
|
|
427
477
|
return serialized;
|
|
428
478
|
}
|
|
429
|
-
function
|
|
430
|
-
if (existing !== void 0) return previous
|
|
431
|
-
|
|
432
|
-
return isNested(readTree(cfg, cfg.sourceLocale));
|
|
479
|
+
function shapeFor(cfg, locale, existing, previous) {
|
|
480
|
+
if (existing !== void 0) return previous;
|
|
481
|
+
return locale === cfg.sourceLocale ? void 0 : readTree(cfg, cfg.sourceLocale);
|
|
433
482
|
}
|
|
434
483
|
const ICU_ARG = /(^|[^{])\{\s*[a-zA-Z0-9_]+\s*,\s*(?:plural|selectordinal|select|number|date|time)\b/;
|
|
484
|
+
function isIcu(message) {
|
|
485
|
+
return ICU_ARG.test(message);
|
|
486
|
+
}
|
|
435
487
|
function needsIcu(catalogs) {
|
|
436
488
|
return someMessage(catalogs, ICU_ARG);
|
|
437
489
|
}
|
|
@@ -460,6 +512,9 @@ function trimTrailingSlashes(text) {
|
|
|
460
512
|
while (end > 0 && text.charCodeAt(end - 1) === 47) end -= 1;
|
|
461
513
|
return text.slice(0, end);
|
|
462
514
|
}
|
|
515
|
+
function singleQuoted(text) {
|
|
516
|
+
return `'${text.replace(/[\\']/g, "\\$&")}'`;
|
|
517
|
+
}
|
|
463
518
|
function byCodeUnit(a, b) {
|
|
464
519
|
return a < b ? -1 : a > b ? 1 : 0;
|
|
465
520
|
}
|
|
@@ -627,13 +682,21 @@ function analyzeScript(code, file, options = {}) {
|
|
|
627
682
|
if (isAppModule(source)) appImported = true;
|
|
628
683
|
else if (ADAPTER_SOURCE.test(source)) adapterImport ??= node.start;
|
|
629
684
|
};
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
685
|
+
for (const node of ast.program.body) if (node.type === "ImportDeclaration") {
|
|
686
|
+
collectStrayImports(node, file, strayImports);
|
|
687
|
+
bindings.addImport(node);
|
|
688
|
+
noteLoad(node);
|
|
689
|
+
} else if (node.type === "ExportNamedDeclaration" || node.type === "ExportAllDeclaration") noteLoad(node);
|
|
690
|
+
const ownTrans = !bindings.other(TRANS);
|
|
691
|
+
const program = ast.program;
|
|
692
|
+
const functions = [];
|
|
693
|
+
const scopeOf = (node) => {
|
|
694
|
+
for (let i = functions.length - 1; i >= 0; i--) if (node.start >= functions[i].start && node.end <= functions[i].end) return functions[i];
|
|
695
|
+
return program;
|
|
696
|
+
};
|
|
697
|
+
walk$1(program, (node) => {
|
|
698
|
+
if (FUNCTIONS.has(node.type)) functions.push(node);
|
|
699
|
+
if (node.type === "VariableDeclarator") bindings.addDeclarator(node, scopeOf(node));
|
|
637
700
|
else if (node.type === "TaggedTemplateExpression") {
|
|
638
701
|
const tag = node.tag;
|
|
639
702
|
const explicit = explicitId(tag, names);
|
|
@@ -679,8 +742,13 @@ function analyzeScript(code, file, options = {}) {
|
|
|
679
742
|
key,
|
|
680
743
|
file
|
|
681
744
|
});
|
|
682
|
-
} else if (node.type === "JSXElement") handleTrans(code, node, file, tagged, usedKeys, names);
|
|
745
|
+
} else if (ownTrans && node.type === "JSXElement") handleTrans(code, node, file, tagged, usedKeys, names);
|
|
746
|
+
});
|
|
747
|
+
const kept = tagged.filter((entry) => {
|
|
748
|
+
const name = code.slice(entry.tagStart, entry.tagEnd);
|
|
749
|
+
return entry.jsx || !names.has(name) || !bindings.foreign(name, entry.tagStart);
|
|
683
750
|
});
|
|
751
|
+
if (kept.length < tagged.length) tagged.splice(0, tagged.length, ...kept);
|
|
684
752
|
const renamed = bindings.renamed(options.renamed);
|
|
685
753
|
const missed = [];
|
|
686
754
|
for (const candidate of candidates) {
|
|
@@ -730,9 +798,19 @@ function loadsAtRuntime(node) {
|
|
|
730
798
|
function lineOf(node) {
|
|
731
799
|
return node.loc?.start.line ?? 1;
|
|
732
800
|
}
|
|
801
|
+
const OTHER_I18N = /^(?:react-i18next|next-i18next|next-translate|ttag|@lingui\/[\w-]+)(?:\/.*)?$/;
|
|
802
|
+
const TRANS = "Trans";
|
|
733
803
|
const VERBALY_SOURCE = /^(?:verbaly|@verbaly\/[\w-]+(?:\/[\w-]+)*)$/;
|
|
734
804
|
const T_FACTORIES = /* @__PURE__ */ new Map([["useT", "call"], ["getT", "await"]]);
|
|
735
805
|
const INSTANCE_FACTORIES = /* @__PURE__ */ new Set(["useVerbaly", "getVerbaly"]);
|
|
806
|
+
const FUNCTIONS = /* @__PURE__ */ new Set([
|
|
807
|
+
"FunctionDeclaration",
|
|
808
|
+
"FunctionExpression",
|
|
809
|
+
"ArrowFunctionExpression",
|
|
810
|
+
"ObjectMethod",
|
|
811
|
+
"ClassMethod",
|
|
812
|
+
"ClassPrivateMethod"
|
|
813
|
+
]);
|
|
736
814
|
var Bindings = class {
|
|
737
815
|
names;
|
|
738
816
|
imports = /* @__PURE__ */ new Map();
|
|
@@ -756,14 +834,15 @@ var Bindings = class {
|
|
|
756
834
|
if (isAppModule(source) && imported === "t") this.direct.add(local);
|
|
757
835
|
}
|
|
758
836
|
}
|
|
759
|
-
addDeclarator(node) {
|
|
837
|
+
addDeclarator(node, scope) {
|
|
760
838
|
const id = node.id;
|
|
761
839
|
const init = node.init;
|
|
762
840
|
if (!init) return;
|
|
763
841
|
if (id.type === "Identifier") {
|
|
764
842
|
this.declared.push({
|
|
765
843
|
name: id.name,
|
|
766
|
-
init
|
|
844
|
+
init,
|
|
845
|
+
scope
|
|
767
846
|
});
|
|
768
847
|
return;
|
|
769
848
|
}
|
|
@@ -775,10 +854,27 @@ var Bindings = class {
|
|
|
775
854
|
const name = identifierName(value.type === "AssignmentPattern" ? value.left : value);
|
|
776
855
|
if (name) this.destructured.push({
|
|
777
856
|
name,
|
|
778
|
-
init
|
|
857
|
+
init,
|
|
858
|
+
scope
|
|
779
859
|
});
|
|
780
860
|
}
|
|
781
861
|
}
|
|
862
|
+
other(local) {
|
|
863
|
+
return OTHER_I18N.test(this.imports.get(local)?.source ?? "");
|
|
864
|
+
}
|
|
865
|
+
foreign(name, at) {
|
|
866
|
+
let theirs = this.other(name);
|
|
867
|
+
let reach = Infinity;
|
|
868
|
+
for (const { name: bound, init, scope } of [...this.declared, ...this.destructured]) {
|
|
869
|
+
if (bound !== name || at < scope.start || at >= scope.end) continue;
|
|
870
|
+
if (scope.end - scope.start >= reach) continue;
|
|
871
|
+
reach = scope.end - scope.start;
|
|
872
|
+
const inner = init.type === "AwaitExpression" ? init.argument : init;
|
|
873
|
+
const read = inner.type === "CallExpression" ? inner.callee : inner;
|
|
874
|
+
theirs = this.other(identifierName(read));
|
|
875
|
+
}
|
|
876
|
+
return theirs;
|
|
877
|
+
}
|
|
782
878
|
renamed(seed = []) {
|
|
783
879
|
const out = new Set(seed);
|
|
784
880
|
const add = (name) => {
|
|
@@ -864,10 +960,9 @@ function staticString(node) {
|
|
|
864
960
|
if (node.type === "TemplateLiteral" && node.expressions.length === 0) return cookedValue(node.quasis[0]);
|
|
865
961
|
if (node.type === "JSXExpressionContainer") return staticString(node.expression);
|
|
866
962
|
}
|
|
867
|
-
const VERBALY_PACKAGE = /^(?:verbaly|@verbaly\/[\w-]+)$/;
|
|
868
963
|
function collectStrayImports(node, file, out) {
|
|
869
964
|
const source = node.source;
|
|
870
|
-
if (typeof source.value !== "string" || !
|
|
965
|
+
if (typeof source.value !== "string" || !VERBALY_SOURCE.test(source.value)) return;
|
|
871
966
|
for (const spec of node.specifiers) {
|
|
872
967
|
if (spec.type !== "ImportSpecifier") continue;
|
|
873
968
|
const imported = spec.imported;
|
|
@@ -883,7 +978,7 @@ function collectStrayImports(node, file, out) {
|
|
|
883
978
|
function handleTrans(code, node, file, tagged, usedKeys, names) {
|
|
884
979
|
const opening = node.openingElement;
|
|
885
980
|
const nameNode = opening.name;
|
|
886
|
-
if (nameNode.type !== "JSXIdentifier" || nameNode.name !==
|
|
981
|
+
if (nameNode.type !== "JSXIdentifier" || nameNode.name !== TRANS) return;
|
|
887
982
|
const attrs = opening.attributes;
|
|
888
983
|
const idAttr = attrs.find((a) => a.type === "JSXAttribute" && a.name.name === "id");
|
|
889
984
|
const children = node.children;
|
|
@@ -1710,7 +1805,7 @@ function visit(nodes, out) {
|
|
|
1710
1805
|
else if (key !== "other") types.add("string");
|
|
1711
1806
|
visit(body, out);
|
|
1712
1807
|
}
|
|
1713
|
-
if (types.size === 0) types.add("string");
|
|
1808
|
+
if (types.size === 0) types.add("number").add("string");
|
|
1714
1809
|
} else if (node.format && NUMBER_FORMATS.has(node.format)) types.add("number");
|
|
1715
1810
|
else if (node.format && DATE_FORMATS.has(node.format)) types.add("date");
|
|
1716
1811
|
else types.add("unknown");
|
|
@@ -1810,7 +1905,7 @@ function generateRuntimeModule(cfg, options = {}) {
|
|
|
1810
1905
|
const importPath = options.localeImport ?? ((locale) => "@verbaly/app/locale/" + locale);
|
|
1811
1906
|
const others = cfg.locales.filter((locale) => locale !== cfg.sourceLocale);
|
|
1812
1907
|
const src = JSON.stringify(cfg.sourceLocale);
|
|
1813
|
-
const loaders = others.map((locale) => ` ${loaderKey(locale)}: () => import(
|
|
1908
|
+
const loaders = others.map((locale) => ` ${loaderKey(locale)}: () => import(${singleQuoted(importPath(locale))}),`).join("\n");
|
|
1814
1909
|
const icu = options.icu ? ",\n parseIcu" : "";
|
|
1815
1910
|
const rel = options.relative ? ",\n relativeFormatter" : "";
|
|
1816
1911
|
const slice = options.inlineCatalog ? ",\n inlineMessages" : "";
|
|
@@ -1822,7 +1917,7 @@ function generateRuntimeModule(cfg, options = {}) {
|
|
|
1822
1917
|
persistLocale,
|
|
1823
1918
|
switchLocale as runSwitch${icu}${rel}${slice},
|
|
1824
1919
|
} from 'verbaly';
|
|
1825
|
-
import source from
|
|
1920
|
+
import source from ${singleQuoted(importPath(cfg.sourceLocale))};
|
|
1826
1921
|
|
|
1827
1922
|
export const sourceLocale = ${src};
|
|
1828
1923
|
export const locales = ${JSON.stringify(cfg.locales)};
|
|
@@ -2072,127 +2167,6 @@ function removeRootDts(cfg, target) {
|
|
|
2072
2167
|
rmSync(old);
|
|
2073
2168
|
warnOnce(`the types live in ${relative(cfg.root, target).replaceAll("\\", "/")} now, so the verbaly.d.ts Verbaly wrote at the root was removed`);
|
|
2074
2169
|
}
|
|
2075
|
-
// src/gate/findings.ts
|
|
2076
|
-
function siteOf(msg) {
|
|
2077
|
-
return {
|
|
2078
|
-
file: msg.file,
|
|
2079
|
-
line: msg.line,
|
|
2080
|
-
message: msg.message
|
|
2081
|
-
};
|
|
2082
|
-
}
|
|
2083
|
-
function collisionEntries(registry) {
|
|
2084
|
-
return registry.collisions().map(({ key, kept, dropped }) => ({
|
|
2085
|
-
key,
|
|
2086
|
-
sites: [kept, ...dropped].map(siteOf)
|
|
2087
|
-
}));
|
|
2088
|
-
}
|
|
2089
|
-
function scanFindings(cfg, registry, replaced = []) {
|
|
2090
|
-
const messages = registry.messages();
|
|
2091
|
-
const out = [];
|
|
2092
|
-
for (const { key, before } of replaced) {
|
|
2093
|
-
const msg = messages.get(key);
|
|
2094
|
-
if (msg) out.push({
|
|
2095
|
-
kind: "replaced",
|
|
2096
|
-
locale: cfg.sourceLocale,
|
|
2097
|
-
key,
|
|
2098
|
-
before,
|
|
2099
|
-
site: siteOf(msg)
|
|
2100
|
-
});
|
|
2101
|
-
}
|
|
2102
|
-
for (const entry of collisionEntries(registry)) out.push({
|
|
2103
|
-
kind: "collision",
|
|
2104
|
-
...entry
|
|
2105
|
-
});
|
|
2106
|
-
for (const { name, file, line } of registry.missed()) out.push({
|
|
2107
|
-
kind: "renamed",
|
|
2108
|
-
name,
|
|
2109
|
-
file,
|
|
2110
|
-
line
|
|
2111
|
-
});
|
|
2112
|
-
for (const msg of messages.values()) {
|
|
2113
|
-
const params = msg.params.map((param) => param.name).filter((name) => /^_\d+$/.test(name));
|
|
2114
|
-
if (params.length > 0) out.push({
|
|
2115
|
-
kind: "positional",
|
|
2116
|
-
params,
|
|
2117
|
-
site: siteOf(msg)
|
|
2118
|
-
});
|
|
2119
|
-
const slice = escapedSyntax(msg.message);
|
|
2120
|
-
if (slice) out.push({
|
|
2121
|
-
kind: "escaped",
|
|
2122
|
-
slice,
|
|
2123
|
-
site: siteOf(msg)
|
|
2124
|
-
});
|
|
2125
|
-
}
|
|
2126
|
-
for (const { file, message } of registry.parseErrors()) out.push({
|
|
2127
|
-
kind: "unparsed",
|
|
2128
|
-
file,
|
|
2129
|
-
message
|
|
2130
|
-
});
|
|
2131
|
-
return out;
|
|
2132
|
-
}
|
|
2133
|
-
function sourcePlace(at, root) {
|
|
2134
|
-
const file = root ? relative(root, at.file).replaceAll("\\", "/") : at.file;
|
|
2135
|
-
return at.line ? `${file}:${at.line}` : file;
|
|
2136
|
-
}
|
|
2137
|
-
function quoted(at, root) {
|
|
2138
|
-
return `"${truncate(at.message, 40)}" (${sourcePlace(at, root)})`;
|
|
2139
|
-
}
|
|
2140
|
-
function formatCollision({ key, sites }, root) {
|
|
2141
|
-
const [kept, ...others] = sites;
|
|
2142
|
-
const texts = new Set(sites.map((at) => at.message)).size;
|
|
2143
|
-
return `${key}: one key with ${counted(texts, "text")}, and every place shows ${quoted(kept, root)}, never ${others.map((at) => quoted(at, root)).join(" or ")}: give each text its own key`;
|
|
2144
|
-
}
|
|
2145
|
-
function formatFinding(finding, root) {
|
|
2146
|
-
switch (finding.kind) {
|
|
2147
|
-
case "collision": return formatCollision(finding, root);
|
|
2148
|
-
case "replaced": {
|
|
2149
|
-
const place = sourcePlace(finding.site, root);
|
|
2150
|
-
return finding.edited ? `${finding.locale}.json: your edit of "${finding.key}" was replaced, its text lives in ${place}: change it there` : `${finding.locale}: ${finding.key} follows the code (${place}): "${truncate(finding.site.message, 40)}", was "${truncate(finding.before, 40)}"`;
|
|
2151
|
-
}
|
|
2152
|
-
case "renamed": return `${sourcePlace(finding, root)}: ${finding.name}\`…\` is never extracted, so it stays in the source language: name it t`;
|
|
2153
|
-
case "positional": {
|
|
2154
|
-
const names = finding.params.map((name) => `{${name}}`).join(", ");
|
|
2155
|
-
return `${sourcePlace(finding.site, root)}: ${names} in "${truncate(finding.site.message, 60)}" reaches the translator without a name, put the value in a named variable first`;
|
|
2156
|
-
}
|
|
2157
|
-
case "escaped": return `${sourcePlace(finding.site, root)}: ${shownSlice(finding.slice)} renders as literal text: write ${inlineBlock(finding.slice)}`;
|
|
2158
|
-
case "unparsed": return `${sourcePlace(finding, root)}: could not be parsed (${finding.message}), its messages were not extracted`;
|
|
2159
|
-
case "outdated": return `[${finding.locale}] ${finding.key}: translated from an older source text, update it or keep it with \`npx verbaly review --approve\``;
|
|
2160
|
-
case "lock": {
|
|
2161
|
-
const lock = sourcePlace(finding, root);
|
|
2162
|
-
if (finding.merged) return `${lock} had a merge conflict and now holds both sides, drafts and stamps included: add it to the commit that resolves the merge`;
|
|
2163
|
-
return finding.from ? `${sourcePlace({ file: finding.from }, root)} moved to ${lock}, next to your config: commit both changes` : `${lock} now keeps the source text each translation was made for and which ones are drafts: commit it with your catalogs`;
|
|
2164
|
-
}
|
|
2165
|
-
}
|
|
2166
|
-
}
|
|
2167
|
-
function findingId(finding) {
|
|
2168
|
-
switch (finding.kind) {
|
|
2169
|
-
case "collision":
|
|
2170
|
-
case "replaced": return `${finding.kind}:${finding.key}`;
|
|
2171
|
-
case "outdated": return `outdated:${finding.locale}:${finding.key}`;
|
|
2172
|
-
case "renamed": return `renamed:${finding.file}:${finding.name}`;
|
|
2173
|
-
case "positional": return `positional:${finding.site.file}:${finding.params.join(",")}`;
|
|
2174
|
-
case "escaped": return `escaped:${finding.site.file}:${finding.slice}`;
|
|
2175
|
-
case "unparsed": return `unparsed:${finding.file}`;
|
|
2176
|
-
case "lock": return `lock:${finding.merged ? "merged:" : ""}${finding.file}`;
|
|
2177
|
-
}
|
|
2178
|
-
}
|
|
2179
|
-
function createDevReporter(root, print = (line) => console.warn(`[verbaly] ${line}`), cap = 5) {
|
|
2180
|
-
const shown = /* @__PURE__ */ new Map();
|
|
2181
|
-
return { report(channel, findings) {
|
|
2182
|
-
const before = shown.get(channel) ?? /* @__PURE__ */ new Set();
|
|
2183
|
-
const now = /* @__PURE__ */ new Set();
|
|
2184
|
-
const fresh = [];
|
|
2185
|
-
for (const finding of findings) {
|
|
2186
|
-
const id = findingId(finding);
|
|
2187
|
-
if (now.has(id)) continue;
|
|
2188
|
-
now.add(id);
|
|
2189
|
-
if (!before.has(id)) fresh.push(finding);
|
|
2190
|
-
}
|
|
2191
|
-
shown.set(channel, now);
|
|
2192
|
-
for (const finding of fresh.slice(0, cap)) print(formatFinding(finding, root));
|
|
2193
|
-
if (fresh.length > cap) print(`and ${fresh.length - cap} more: \`npx verbaly doctor\` names them`);
|
|
2194
|
-
} };
|
|
2195
|
-
}
|
|
2196
2170
|
// src/catalog/state.ts
|
|
2197
2171
|
const STATE_FILE = "verbaly.lock";
|
|
2198
2172
|
const LOCK_VERSION = 1;
|
|
@@ -2527,71 +2501,507 @@ function readFingerprints(value) {
|
|
|
2527
2501
|
}
|
|
2528
2502
|
return out;
|
|
2529
2503
|
}
|
|
2530
|
-
// src/
|
|
2531
|
-
|
|
2532
|
-
|
|
2533
|
-
|
|
2534
|
-
|
|
2535
|
-
|
|
2536
|
-
const pruned = options.prune ? pruneCatalogs(cfg, catalogs, registry) : {};
|
|
2537
|
-
const { added, replaced } = syncCatalogs(cfg, catalogs, registry);
|
|
2538
|
-
const result = {
|
|
2539
|
-
registry,
|
|
2540
|
-
catalogs,
|
|
2541
|
-
messages: Object.keys(catalogs[cfg.sourceLocale] ?? {}).length,
|
|
2542
|
-
inCode: registry.messages().size,
|
|
2543
|
-
added,
|
|
2544
|
-
replaced,
|
|
2545
|
-
pruned,
|
|
2546
|
-
pruneBlocked,
|
|
2547
|
-
findings: scanFindings(cfg, registry, replaced),
|
|
2548
|
-
written: emptyCatalog()
|
|
2504
|
+
// src/gate/findings.ts
|
|
2505
|
+
function siteOf(msg) {
|
|
2506
|
+
return {
|
|
2507
|
+
file: msg.file,
|
|
2508
|
+
line: msg.line,
|
|
2509
|
+
message: msg.message
|
|
2549
2510
|
};
|
|
2550
|
-
|
|
2551
|
-
|
|
2552
|
-
|
|
2553
|
-
|
|
2554
|
-
|
|
2555
|
-
|
|
2556
|
-
|
|
2557
|
-
|
|
2558
|
-
const
|
|
2559
|
-
|
|
2560
|
-
|
|
2561
|
-
|
|
2562
|
-
|
|
2511
|
+
}
|
|
2512
|
+
function collisionEntries(registry) {
|
|
2513
|
+
return registry.collisions().map(({ key, kept, dropped }) => ({
|
|
2514
|
+
key,
|
|
2515
|
+
sites: [kept, ...dropped].map(siteOf)
|
|
2516
|
+
}));
|
|
2517
|
+
}
|
|
2518
|
+
function scanFindings(cfg, registry, replaced = []) {
|
|
2519
|
+
const messages = registry.messages();
|
|
2520
|
+
const out = [];
|
|
2521
|
+
for (const { key, before } of replaced) {
|
|
2522
|
+
const msg = messages.get(key);
|
|
2523
|
+
if (msg) out.push({
|
|
2524
|
+
kind: "replaced",
|
|
2525
|
+
locale: cfg.sourceLocale,
|
|
2526
|
+
key,
|
|
2527
|
+
before,
|
|
2528
|
+
site: siteOf(msg)
|
|
2529
|
+
});
|
|
2563
2530
|
}
|
|
2564
|
-
const
|
|
2565
|
-
|
|
2566
|
-
|
|
2567
|
-
...news
|
|
2531
|
+
for (const entry of collisionEntries(registry)) out.push({
|
|
2532
|
+
kind: "collision",
|
|
2533
|
+
...entry
|
|
2568
2534
|
});
|
|
2569
|
-
|
|
2570
|
-
|
|
2571
|
-
|
|
2572
|
-
|
|
2573
|
-
|
|
2574
|
-
|
|
2575
|
-
for (const
|
|
2576
|
-
|
|
2577
|
-
|
|
2578
|
-
|
|
2579
|
-
|
|
2580
|
-
|
|
2581
|
-
|
|
2582
|
-
|
|
2583
|
-
|
|
2535
|
+
for (const { name, file, line } of registry.missed()) out.push({
|
|
2536
|
+
kind: "renamed",
|
|
2537
|
+
name,
|
|
2538
|
+
file,
|
|
2539
|
+
line
|
|
2540
|
+
});
|
|
2541
|
+
for (const msg of messages.values()) {
|
|
2542
|
+
const params = msg.params.map((param) => param.name).filter((name) => /^_\d+$/.test(name));
|
|
2543
|
+
if (params.length > 0) out.push({
|
|
2544
|
+
kind: "positional",
|
|
2545
|
+
params,
|
|
2546
|
+
site: siteOf(msg)
|
|
2547
|
+
});
|
|
2548
|
+
const slice = escapedSyntax(msg.message);
|
|
2549
|
+
if (slice) out.push({
|
|
2550
|
+
kind: "escaped",
|
|
2551
|
+
slice,
|
|
2552
|
+
site: siteOf(msg)
|
|
2553
|
+
});
|
|
2584
2554
|
}
|
|
2555
|
+
for (const { file, message } of registry.parseErrors()) out.push({
|
|
2556
|
+
kind: "unparsed",
|
|
2557
|
+
file,
|
|
2558
|
+
message
|
|
2559
|
+
});
|
|
2560
|
+
return out;
|
|
2585
2561
|
}
|
|
2586
|
-
|
|
2587
|
-
|
|
2588
|
-
return
|
|
2562
|
+
function sourcePlace(at, root) {
|
|
2563
|
+
const file = root ? relative(root, at.file).replaceAll("\\", "/") : at.file;
|
|
2564
|
+
return at.line ? `${file}:${at.line}` : file;
|
|
2589
2565
|
}
|
|
2590
|
-
function
|
|
2591
|
-
return
|
|
2566
|
+
function quoted(at, root) {
|
|
2567
|
+
return `"${truncate(at.message, 40)}" (${sourcePlace(at, root)})`;
|
|
2592
2568
|
}
|
|
2593
|
-
function
|
|
2594
|
-
|
|
2569
|
+
function formatCollision({ key, sites }, root) {
|
|
2570
|
+
const [kept, ...others] = sites;
|
|
2571
|
+
const texts = new Set(sites.map((at) => at.message)).size;
|
|
2572
|
+
return `${key}: one key with ${counted(texts, "text")}, and every place shows ${quoted(kept, root)}, never ${others.map((at) => quoted(at, root)).join(" or ")}: give each text its own key`;
|
|
2573
|
+
}
|
|
2574
|
+
function formatFinding(finding, root) {
|
|
2575
|
+
switch (finding.kind) {
|
|
2576
|
+
case "collision": return formatCollision(finding, root);
|
|
2577
|
+
case "replaced": {
|
|
2578
|
+
const place = sourcePlace(finding.site, root);
|
|
2579
|
+
return finding.edited ? `${finding.locale}.json: your edit of "${finding.key}" was replaced, its text lives in ${place}: change it there` : `${finding.locale}: ${finding.key} follows the code (${place}): "${truncate(finding.site.message, 40)}", was "${truncate(finding.before, 40)}"`;
|
|
2580
|
+
}
|
|
2581
|
+
case "renamed": return `${sourcePlace(finding, root)}: ${finding.name}\`…\` is never extracted, so it stays in the source language: name it t`;
|
|
2582
|
+
case "positional": {
|
|
2583
|
+
const names = finding.params.map((name) => `{${name}}`).join(", ");
|
|
2584
|
+
return `${sourcePlace(finding.site, root)}: ${names} in "${truncate(finding.site.message, 60)}" reaches the translator without a name, put the value in a named variable first`;
|
|
2585
|
+
}
|
|
2586
|
+
case "escaped": return `${sourcePlace(finding.site, root)}: ${shownSlice(finding.slice)} renders as literal text: write ${inlineBlock(finding.slice)}`;
|
|
2587
|
+
case "unparsed": return `${sourcePlace(finding, root)}: could not be parsed (${finding.message}), its messages were not extracted`;
|
|
2588
|
+
case "outdated": return `[${finding.locale}] ${finding.key}: translated from an older source text, update it or keep it with \`npx verbaly review --approve\``;
|
|
2589
|
+
case "lock": {
|
|
2590
|
+
const lock = sourcePlace(finding, root);
|
|
2591
|
+
if (finding.merged) return `${lock} had a merge conflict and now holds both sides, drafts and stamps included: add it to the commit that resolves the merge`;
|
|
2592
|
+
return finding.from ? `${sourcePlace({ file: finding.from }, root)} moved to ${lock}, next to your config: commit both changes` : `${lock} now keeps the source text each translation was made for and which ones are drafts: commit it with your catalogs`;
|
|
2593
|
+
}
|
|
2594
|
+
}
|
|
2595
|
+
}
|
|
2596
|
+
function findingId(finding) {
|
|
2597
|
+
switch (finding.kind) {
|
|
2598
|
+
case "collision":
|
|
2599
|
+
case "replaced": return `${finding.kind}:${finding.key}`;
|
|
2600
|
+
case "outdated": return `outdated:${finding.locale}:${finding.key}`;
|
|
2601
|
+
case "renamed": return `renamed:${finding.file}:${finding.name}`;
|
|
2602
|
+
case "positional": return `positional:${finding.site.file}:${finding.params.join(",")}`;
|
|
2603
|
+
case "escaped": return `escaped:${finding.site.file}:${finding.slice}`;
|
|
2604
|
+
case "unparsed": return `unparsed:${finding.file}`;
|
|
2605
|
+
case "lock": return `lock:${finding.merged ? "merged:" : ""}${finding.file}`;
|
|
2606
|
+
}
|
|
2607
|
+
}
|
|
2608
|
+
function createDevReporter(root, print = (line) => console.warn(`[verbaly] ${line}`), cap = 5) {
|
|
2609
|
+
const shown = /* @__PURE__ */ new Map();
|
|
2610
|
+
let stateBroken = false;
|
|
2611
|
+
const report = (channel, findings) => {
|
|
2612
|
+
const before = shown.get(channel) ?? /* @__PURE__ */ new Set();
|
|
2613
|
+
const now = /* @__PURE__ */ new Set();
|
|
2614
|
+
const fresh = [];
|
|
2615
|
+
for (const finding of findings) {
|
|
2616
|
+
const id = findingId(finding);
|
|
2617
|
+
if (now.has(id)) continue;
|
|
2618
|
+
now.add(id);
|
|
2619
|
+
if (!before.has(id)) fresh.push(finding);
|
|
2620
|
+
}
|
|
2621
|
+
shown.set(channel, now);
|
|
2622
|
+
for (const finding of fresh.slice(0, cap)) print(formatFinding(finding, root));
|
|
2623
|
+
if (fresh.length > cap) print(`and ${fresh.length - cap} more: \`npx verbaly doctor\` names them`);
|
|
2624
|
+
};
|
|
2625
|
+
return {
|
|
2626
|
+
report,
|
|
2627
|
+
sync(cfg, result, edited) {
|
|
2628
|
+
const replaced = [];
|
|
2629
|
+
const code = [];
|
|
2630
|
+
const lock = [];
|
|
2631
|
+
for (const finding of result.findings) if (finding.kind === "collision" || finding.kind === "renamed") code.push(finding);
|
|
2632
|
+
else if (finding.kind === "lock") lock.push(finding);
|
|
2633
|
+
else if (finding.kind === "replaced") {
|
|
2634
|
+
const answer = edited(finding);
|
|
2635
|
+
if (answer !== void 0) replaced.push({
|
|
2636
|
+
...finding,
|
|
2637
|
+
edited: answer
|
|
2638
|
+
});
|
|
2639
|
+
}
|
|
2640
|
+
report("replaced", replaced);
|
|
2641
|
+
report("code", code);
|
|
2642
|
+
report("lock", lock);
|
|
2643
|
+
const outdated = result.state ? outdatedTranslations(cfg, result.catalogs, result.state.fingerprints) : [];
|
|
2644
|
+
report("outdated", outdated.map((entry) => ({
|
|
2645
|
+
kind: "outdated",
|
|
2646
|
+
...entry
|
|
2647
|
+
})));
|
|
2648
|
+
if (result.stateProblem && !stateBroken) print(`${result.stateProblem}, so drafts are not tracked`);
|
|
2649
|
+
stateBroken = Boolean(result.stateProblem);
|
|
2650
|
+
}
|
|
2651
|
+
};
|
|
2652
|
+
}
|
|
2653
|
+
// src/project/project.ts
|
|
2654
|
+
async function syncProject(cfg, options = {}) {
|
|
2655
|
+
const registry = options.registry ?? await extractProject(cfg);
|
|
2656
|
+
const catalogs = options.catalogs ?? loadCatalogs(cfg);
|
|
2657
|
+
if (options.confirm) confirmFromDisk(cfg, catalogs, registry);
|
|
2658
|
+
const pruneBlocked = options.prune === true && registry.parseErrors().length > 0;
|
|
2659
|
+
const pruned = options.prune ? pruneCatalogs(cfg, catalogs, registry) : {};
|
|
2660
|
+
const { added, replaced } = syncCatalogs(cfg, catalogs, registry);
|
|
2661
|
+
const result = {
|
|
2662
|
+
registry,
|
|
2663
|
+
catalogs,
|
|
2664
|
+
messages: Object.keys(catalogs[cfg.sourceLocale] ?? {}).length,
|
|
2665
|
+
inCode: registry.messages().size,
|
|
2666
|
+
added,
|
|
2667
|
+
replaced,
|
|
2668
|
+
pruned,
|
|
2669
|
+
pruneBlocked,
|
|
2670
|
+
findings: scanFindings(cfg, registry, replaced),
|
|
2671
|
+
written: emptyCatalog()
|
|
2672
|
+
};
|
|
2673
|
+
if (options.dryRun) return result;
|
|
2674
|
+
const changed = /* @__PURE__ */ new Set([...Object.keys(added), ...Object.keys(pruned)]);
|
|
2675
|
+
if (replaced.length > 0) changed.add(cfg.sourceLocale);
|
|
2676
|
+
for (const locale of cfg.locales) {
|
|
2677
|
+
if (options.write === "changed" && !changed.has(locale)) continue;
|
|
2678
|
+
result.written[locale] = writeCatalog(cfg, locale, catalogs[locale] ?? {});
|
|
2679
|
+
}
|
|
2680
|
+
writeDts(cfg, catalogs[cfg.sourceLocale] ?? {});
|
|
2681
|
+
const before = stateFile(cfg);
|
|
2682
|
+
try {
|
|
2683
|
+
result.state = updateState(cfg, catalogs);
|
|
2684
|
+
} catch (error) {
|
|
2685
|
+
result.stateProblem = error.message.replace(/^\[verbaly\] /, "");
|
|
2686
|
+
}
|
|
2687
|
+
const news = lockNews(cfg, before);
|
|
2688
|
+
if (news) result.findings.push({
|
|
2689
|
+
kind: "lock",
|
|
2690
|
+
...news
|
|
2691
|
+
});
|
|
2692
|
+
return result;
|
|
2693
|
+
}
|
|
2694
|
+
function confirmFromDisk(cfg, catalogs, registry) {
|
|
2695
|
+
const source = catalogs[cfg.sourceLocale] ?? {};
|
|
2696
|
+
const stale = /* @__PURE__ */ new Set();
|
|
2697
|
+
for (const [key, msg] of registry.messages()) if (own(source, key) !== msg.message) stale.add(msg.file);
|
|
2698
|
+
for (const file of stale) {
|
|
2699
|
+
let code;
|
|
2700
|
+
try {
|
|
2701
|
+
code = readFileSync(file, "utf8");
|
|
2702
|
+
} catch {
|
|
2703
|
+
registry.remove(file);
|
|
2704
|
+
continue;
|
|
2705
|
+
}
|
|
2706
|
+
registry.update(file, analyzeFile(code, file));
|
|
2707
|
+
}
|
|
2708
|
+
}
|
|
2709
|
+
// src/exchange/translate.ts
|
|
2710
|
+
const RETRY_STATUS = /* @__PURE__ */ new Set([
|
|
2711
|
+
408,
|
|
2712
|
+
409,
|
|
2713
|
+
425,
|
|
2714
|
+
429,
|
|
2715
|
+
500,
|
|
2716
|
+
502,
|
|
2717
|
+
503,
|
|
2718
|
+
504,
|
|
2719
|
+
529
|
|
2720
|
+
]);
|
|
2721
|
+
function retryable(error) {
|
|
2722
|
+
const status = error?.status;
|
|
2723
|
+
const code = error?.statusCode;
|
|
2724
|
+
const value = typeof status === "number" ? status : code;
|
|
2725
|
+
return typeof value === "number" ? RETRY_STATUS.has(value) : true;
|
|
2726
|
+
}
|
|
2727
|
+
function reason(error) {
|
|
2728
|
+
return error instanceof Error ? error.message : String(error);
|
|
2729
|
+
}
|
|
2730
|
+
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
2731
|
+
async function attempt(run, retries, delay) {
|
|
2732
|
+
for (let round = 0;; round++) try {
|
|
2733
|
+
return await run();
|
|
2734
|
+
} catch (error) {
|
|
2735
|
+
if (round >= retries || !retryable(error)) throw error;
|
|
2736
|
+
await wait(delay * 2 ** round);
|
|
2737
|
+
}
|
|
2738
|
+
}
|
|
2739
|
+
async function pooled(jobs, limit, run) {
|
|
2740
|
+
let next = 0;
|
|
2741
|
+
const workers = Array.from({ length: Math.min(limit, jobs.length) }, async () => {
|
|
2742
|
+
while (next < jobs.length) await run(jobs[next++]);
|
|
2743
|
+
});
|
|
2744
|
+
await Promise.all(workers);
|
|
2745
|
+
}
|
|
2746
|
+
async function translateCatalogs(cfg, catalogs, provider, options = {}) {
|
|
2747
|
+
const batchSize = options.batchSize ?? 20;
|
|
2748
|
+
const concurrency = Math.max(1, options.concurrency ?? 4);
|
|
2749
|
+
const retries = Math.max(0, options.retries ?? 2);
|
|
2750
|
+
const retryDelay = options.retryDelay ?? 500;
|
|
2751
|
+
const targets = targetLocales(cfg, options.locales);
|
|
2752
|
+
const source = catalogs[cfg.sourceLocale] ?? {};
|
|
2753
|
+
const result = {
|
|
2754
|
+
translated: emptyCatalog(),
|
|
2755
|
+
invalid: emptyCatalog(),
|
|
2756
|
+
pending: emptyCatalog(),
|
|
2757
|
+
failed: []
|
|
2758
|
+
};
|
|
2759
|
+
const jobs = [];
|
|
2760
|
+
for (const locale of targets) {
|
|
2761
|
+
const catalog = catalogs[locale] ??= emptyCatalog();
|
|
2762
|
+
const missing = Object.keys(source).filter((key) => source[key] && !own(catalog, key));
|
|
2763
|
+
if (missing.length === 0) continue;
|
|
2764
|
+
if (options.dryRun) {
|
|
2765
|
+
result.pending[locale] = missing;
|
|
2766
|
+
continue;
|
|
2767
|
+
}
|
|
2768
|
+
const batches = Math.ceil(missing.length / batchSize);
|
|
2769
|
+
for (let i = 0; i < missing.length; i += batchSize) {
|
|
2770
|
+
const index = Math.floor(i / batchSize) + 1;
|
|
2771
|
+
jobs.push({
|
|
2772
|
+
locale,
|
|
2773
|
+
index,
|
|
2774
|
+
batches,
|
|
2775
|
+
keys: missing.slice(i, i + batchSize)
|
|
2776
|
+
});
|
|
2777
|
+
}
|
|
2778
|
+
}
|
|
2779
|
+
await pooled(jobs, concurrency, async (job) => {
|
|
2780
|
+
const { locale, keys } = job;
|
|
2781
|
+
const catalog = catalogs[locale];
|
|
2782
|
+
const messages = Object.fromEntries(keys.map((key) => [key, source[key]]));
|
|
2783
|
+
const origins = options.origins ? Object.fromEntries(keys.filter((key) => Object.hasOwn(options.origins, key)).map((key) => [key, options.origins[key]])) : void 0;
|
|
2784
|
+
let out;
|
|
2785
|
+
try {
|
|
2786
|
+
out = await attempt(() => provider({
|
|
2787
|
+
sourceLocale: cfg.sourceLocale,
|
|
2788
|
+
targetLocale: locale,
|
|
2789
|
+
messages,
|
|
2790
|
+
origins,
|
|
2791
|
+
instructions: cfg.translate.instructions,
|
|
2792
|
+
glossary: glossaryFor(cfg, locale, messages)
|
|
2793
|
+
}), retries, retryDelay);
|
|
2794
|
+
} catch (error) {
|
|
2795
|
+
const message = reason(error);
|
|
2796
|
+
result.failed.push({
|
|
2797
|
+
locale,
|
|
2798
|
+
keys,
|
|
2799
|
+
error: message
|
|
2800
|
+
});
|
|
2801
|
+
options.onProgress?.({
|
|
2802
|
+
...progressOf(job),
|
|
2803
|
+
error: message
|
|
2804
|
+
});
|
|
2805
|
+
return;
|
|
2806
|
+
}
|
|
2807
|
+
for (const key of keys) {
|
|
2808
|
+
const text = out[key];
|
|
2809
|
+
if (typeof text === "string" && text.trim() && structureMatches(source[key], text)) {
|
|
2810
|
+
catalog[key] = text;
|
|
2811
|
+
(result.translated[locale] ??= []).push(key);
|
|
2812
|
+
} else (result.invalid[locale] ??= []).push(key);
|
|
2813
|
+
}
|
|
2814
|
+
options.onProgress?.(progressOf(job));
|
|
2815
|
+
});
|
|
2816
|
+
for (const locale of Object.keys(result.translated)) result.translated[locale].sort();
|
|
2817
|
+
for (const locale of Object.keys(result.invalid)) result.invalid[locale].sort();
|
|
2818
|
+
result.failed.sort((a, b) => byCodeUnit(a.locale, b.locale) || compare(a.keys, b.keys));
|
|
2819
|
+
return result;
|
|
2820
|
+
}
|
|
2821
|
+
function compare(a, b) {
|
|
2822
|
+
return byCodeUnit(a[0] ?? "", b[0] ?? "");
|
|
2823
|
+
}
|
|
2824
|
+
function mergeTranslations(cfg, locale, translated, keys) {
|
|
2825
|
+
const source = readCatalog(cfg, cfg.sourceLocale);
|
|
2826
|
+
const current = readCatalog(cfg, locale);
|
|
2827
|
+
const written = [];
|
|
2828
|
+
for (const key of keys) {
|
|
2829
|
+
const text = translated[key];
|
|
2830
|
+
if (!source[key] || current[key] || !text) continue;
|
|
2831
|
+
current[key] = text;
|
|
2832
|
+
written.push(key);
|
|
2833
|
+
}
|
|
2834
|
+
if (written.length > 0) writeCatalog(cfg, locale, current);
|
|
2835
|
+
return written;
|
|
2836
|
+
}
|
|
2837
|
+
function writeDrafts(cfg, locale, entries, options = {}) {
|
|
2838
|
+
const targets = targetLocales(cfg);
|
|
2839
|
+
if (!targets.includes(locale)) throw new Error(`[verbaly] "${locale}" is not a language this project translates into (${targets.join(", ") || "none yet"})`);
|
|
2840
|
+
loadState(cfg);
|
|
2841
|
+
const catalogs = { [cfg.sourceLocale]: readCatalog(cfg, cfg.sourceLocale) };
|
|
2842
|
+
const source = options.registry ? shippedCatalogs(cfg, catalogs, options.registry, { newKeys: false })[cfg.sourceLocale] : catalogs[cfg.sourceLocale];
|
|
2843
|
+
const current = readCatalog(cfg, locale);
|
|
2844
|
+
const result = {
|
|
2845
|
+
written: [],
|
|
2846
|
+
kept: [],
|
|
2847
|
+
invalid: [],
|
|
2848
|
+
unknown: []
|
|
2849
|
+
};
|
|
2850
|
+
for (const { key, text } of entries) {
|
|
2851
|
+
const from = own(source, key);
|
|
2852
|
+
if (!from) result.unknown.push(key);
|
|
2853
|
+
else if (!text.trim() || !structureMatches(from, text)) result.invalid.push(key);
|
|
2854
|
+
else if (own(current, key) && !options.overwrite) result.kept.push(key);
|
|
2855
|
+
else {
|
|
2856
|
+
current[key] = text;
|
|
2857
|
+
result.written.push(key);
|
|
2858
|
+
}
|
|
2859
|
+
}
|
|
2860
|
+
if (result.written.length > 0) {
|
|
2861
|
+
writeCatalog(cfg, locale, current);
|
|
2862
|
+
const written = result.written.map((key) => ({
|
|
2863
|
+
key,
|
|
2864
|
+
text: current[key]
|
|
2865
|
+
}));
|
|
2866
|
+
const before = stateFile(cfg);
|
|
2867
|
+
recordTranslations(cfg, source, [{
|
|
2868
|
+
locale,
|
|
2869
|
+
entries: written,
|
|
2870
|
+
draft: true
|
|
2871
|
+
}]);
|
|
2872
|
+
const lock = lockNews(cfg, before);
|
|
2873
|
+
if (lock) result.lock = lock;
|
|
2874
|
+
}
|
|
2875
|
+
return result;
|
|
2876
|
+
}
|
|
2877
|
+
function formatTranslateFailures(failed) {
|
|
2878
|
+
const grouped = [];
|
|
2879
|
+
for (const entry of failed) {
|
|
2880
|
+
const same = grouped.find((it) => it.locale === entry.locale && it.error === entry.error);
|
|
2881
|
+
if (same) same.keys = [...same.keys, ...entry.keys];
|
|
2882
|
+
else grouped.push({
|
|
2883
|
+
...entry,
|
|
2884
|
+
keys: [...entry.keys]
|
|
2885
|
+
});
|
|
2886
|
+
}
|
|
2887
|
+
return grouped.map(({ locale, error, keys }) => ` ${locale}: ${counted(keys.length, "message")} not translated (${error}): ${keys.join(", ")}`);
|
|
2888
|
+
}
|
|
2889
|
+
async function resolveProvider(cfg, model) {
|
|
2890
|
+
const configured = cfg.translate.provider;
|
|
2891
|
+
if (typeof configured === "function") return configured;
|
|
2892
|
+
const { claudeProvider } = await import("./claude-D31sQLmS.js");
|
|
2893
|
+
return claudeProvider({ model: model ?? cfg.translate.model });
|
|
2894
|
+
}
|
|
2895
|
+
function structureMatches(source, translated) {
|
|
2896
|
+
try {
|
|
2897
|
+
return ![...validateMessage(translated), ...validatePair(source, translated)].some((issue) => issue.severity === "error");
|
|
2898
|
+
} catch {
|
|
2899
|
+
return false;
|
|
2900
|
+
}
|
|
2901
|
+
}
|
|
2902
|
+
function progressOf(job) {
|
|
2903
|
+
return {
|
|
2904
|
+
locale: job.locale,
|
|
2905
|
+
batch: job.index,
|
|
2906
|
+
batches: job.batches,
|
|
2907
|
+
keys: job.keys.length
|
|
2908
|
+
};
|
|
2909
|
+
}
|
|
2910
|
+
function glossaryFor(cfg, locale, messages) {
|
|
2911
|
+
const entries = cfg.translate.glossary;
|
|
2912
|
+
if (!entries) return void 0;
|
|
2913
|
+
const text = Object.values(messages).join("\n").toLowerCase();
|
|
2914
|
+
const out = {};
|
|
2915
|
+
for (const [term, rendering] of Object.entries(entries)) {
|
|
2916
|
+
if (!text.includes(term.toLowerCase())) continue;
|
|
2917
|
+
const value = typeof rendering === "string" ? rendering : rendering[locale];
|
|
2918
|
+
if (value) out[term] = value;
|
|
2919
|
+
}
|
|
2920
|
+
return Object.keys(out).length > 0 ? out : void 0;
|
|
2921
|
+
}
|
|
2922
|
+
// src/project/translate.ts
|
|
2923
|
+
async function translateProject(cfg, options = {}) {
|
|
2924
|
+
const dryRun = options.dryRun === true;
|
|
2925
|
+
if (!dryRun) loadState(cfg);
|
|
2926
|
+
const registry = await extractProject(cfg);
|
|
2927
|
+
const catalogs = shippedCatalogs(cfg, loadCatalogs(cfg), registry, { newKeys: false });
|
|
2928
|
+
const run = await translateCatalogs(cfg, catalogs, options.provider ?? await resolveProvider(cfg, options.model), {
|
|
2929
|
+
locales: options.locales,
|
|
2930
|
+
batchSize: cfg.translate.batchSize,
|
|
2931
|
+
concurrency: cfg.translate.concurrency,
|
|
2932
|
+
retries: cfg.translate.retries,
|
|
2933
|
+
dryRun,
|
|
2934
|
+
origins: dryRun ? void 0 : await collectOrigins(cfg, registry),
|
|
2935
|
+
onProgress: dryRun ? void 0 : options.onProgress
|
|
2936
|
+
});
|
|
2937
|
+
const result = {
|
|
2938
|
+
pending: run.pending,
|
|
2939
|
+
written: emptyCatalog(),
|
|
2940
|
+
kept: emptyCatalog(),
|
|
2941
|
+
invalid: run.invalid,
|
|
2942
|
+
failed: run.failed
|
|
2943
|
+
};
|
|
2944
|
+
if (dryRun) return result;
|
|
2945
|
+
const writes = [];
|
|
2946
|
+
for (const [locale, keys] of Object.entries(run.translated)) {
|
|
2947
|
+
const catalog = catalogs[locale] ?? {};
|
|
2948
|
+
const landed = mergeTranslations(cfg, locale, catalog, keys);
|
|
2949
|
+
const left = keys.filter((key) => !landed.includes(key));
|
|
2950
|
+
if (left.length > 0) result.kept[locale] = left;
|
|
2951
|
+
if (landed.length === 0) continue;
|
|
2952
|
+
result.written[locale] = landed;
|
|
2953
|
+
writes.push({
|
|
2954
|
+
locale,
|
|
2955
|
+
draft: true,
|
|
2956
|
+
entries: landed.map((key) => ({
|
|
2957
|
+
key,
|
|
2958
|
+
text: catalog[key]
|
|
2959
|
+
}))
|
|
2960
|
+
});
|
|
2961
|
+
}
|
|
2962
|
+
const before = stateFile(cfg);
|
|
2963
|
+
if (writes.length > 0) recordTranslations(cfg, catalogs[cfg.sourceLocale] ?? {}, writes);
|
|
2964
|
+
const lock = lockNews(cfg, before);
|
|
2965
|
+
if (lock) result.lock = lock;
|
|
2966
|
+
return result;
|
|
2967
|
+
}
|
|
2968
|
+
// src/gate/check.ts
|
|
2969
|
+
function gatePasses(result) {
|
|
2970
|
+
return result.missing.length === 0 && result.unknown.length === 0 && result.collisions.length === 0 && !result.broken.some((entry) => entry.severity === "error");
|
|
2971
|
+
}
|
|
2972
|
+
function relativeCheck(root, result) {
|
|
2973
|
+
const rel = (file) => relative(root, file).replaceAll("\\", "/");
|
|
2974
|
+
return {
|
|
2975
|
+
...result,
|
|
2976
|
+
unknown: result.unknown.map((entry) => ({
|
|
2977
|
+
...entry,
|
|
2978
|
+
files: entry.files.map(rel)
|
|
2979
|
+
})),
|
|
2980
|
+
extra: result.extra.map((entry) => ({
|
|
2981
|
+
...entry,
|
|
2982
|
+
files: entry.files.map(rel)
|
|
2983
|
+
})),
|
|
2984
|
+
collisions: result.collisions.map((entry) => ({
|
|
2985
|
+
...entry,
|
|
2986
|
+
sites: entry.sites.map((at) => ({
|
|
2987
|
+
...at,
|
|
2988
|
+
file: rel(at.file)
|
|
2989
|
+
}))
|
|
2990
|
+
})),
|
|
2991
|
+
divergent: result.divergent.map((entry) => ({
|
|
2992
|
+
...entry,
|
|
2993
|
+
code: {
|
|
2994
|
+
...entry.code,
|
|
2995
|
+
file: rel(entry.code.file)
|
|
2996
|
+
}
|
|
2997
|
+
}))
|
|
2998
|
+
};
|
|
2999
|
+
}
|
|
3000
|
+
function warningCount(result) {
|
|
3001
|
+
return result.broken.filter((entry) => entry.severity === "warning").length + result.extra.length + result.divergent.length + result.outdated.length;
|
|
3002
|
+
}
|
|
3003
|
+
function check(cfg, catalogs, registry, fingerprints = emptyCatalog()) {
|
|
3004
|
+
return gatePass(() => checkPass(cfg, catalogs, registry, fingerprints));
|
|
2595
3005
|
}
|
|
2596
3006
|
function checkPass(cfg, catalogs, registry, fingerprints) {
|
|
2597
3007
|
const extracted = registry.messages();
|
|
@@ -2817,8 +3227,7 @@ function escapeProperty(text) {
|
|
|
2817
3227
|
}
|
|
2818
3228
|
// src/scan/transform.ts
|
|
2819
3229
|
function quote(text, single) {
|
|
2820
|
-
|
|
2821
|
-
return `'${text.replace(/\\/g, "\\\\").replace(/'/g, "\\'")}'`;
|
|
3230
|
+
return single ? singleQuoted(text) : JSON.stringify(text);
|
|
2822
3231
|
}
|
|
2823
3232
|
function transformCode(code, file, analysis, options = {}) {
|
|
2824
3233
|
const own = analysis ?? analyzeFile(code, file);
|
|
@@ -2835,7 +3244,9 @@ function transformCode(code, file, analysis, options = {}) {
|
|
|
2835
3244
|
if (msg.jsx) {
|
|
2836
3245
|
const values = entries.length ? ` values={{ ${pairs} }}` : "";
|
|
2837
3246
|
const components = msg.jsx.components.length ? ` components={{ ${msg.jsx.components.map((c) => `${JSON.stringify(c.name)}: ${c.source}`).join(", ")} }}` : "";
|
|
2838
|
-
|
|
3247
|
+
const quoted = JSON.stringify(msg.key);
|
|
3248
|
+
const id = quoted === `"${msg.key}"` ? quoted : `{${quoted}}`;
|
|
3249
|
+
s.overwrite(msg.start, msg.end, `<${msg.jsx.name} id=${id}${values}${components} />`);
|
|
2839
3250
|
continue;
|
|
2840
3251
|
}
|
|
2841
3252
|
const tagSource = code.slice(msg.tagStart, msg.tagEnd);
|
|
@@ -2856,14 +3267,21 @@ function resolveVirtualId(id) {
|
|
|
2856
3267
|
if (id.startsWith("@verbaly/app/locale/")) return LOCALE_MODULE_PREFIX + id.slice(20);
|
|
2857
3268
|
if (id.startsWith(`virtual:verbaly/`)) return "\0" + id;
|
|
2858
3269
|
}
|
|
2859
|
-
function
|
|
3270
|
+
function clientModules(cfg, catalogs, options = {}) {
|
|
2860
3271
|
const client = clientCatalogs(cfg, catalogs);
|
|
2861
|
-
|
|
2862
|
-
|
|
2863
|
-
|
|
2864
|
-
|
|
2865
|
-
|
|
2866
|
-
|
|
3272
|
+
return {
|
|
3273
|
+
runtime: () => generateRuntimeModule(cfg, {
|
|
3274
|
+
...options,
|
|
3275
|
+
icu: cfg.icu ?? needsIcu(client),
|
|
3276
|
+
relative: cfg.relative ?? needsRelative(client),
|
|
3277
|
+
inlineCatalog: cfg.render.inlineCatalog === true
|
|
3278
|
+
}),
|
|
3279
|
+
locale: (locale) => generateLocaleModule(own(client, locale) ?? {})
|
|
3280
|
+
};
|
|
3281
|
+
}
|
|
3282
|
+
function loadVirtualModule(id, cfg, catalogs) {
|
|
3283
|
+
if (id === RESOLVED_VIRTUAL_ID) return clientModules(cfg, catalogs).runtime();
|
|
3284
|
+
if (id.startsWith(LOCALE_MODULE_PREFIX)) return clientModules(cfg, catalogs).locale(id.slice(LOCALE_MODULE_PREFIX.length));
|
|
2867
3285
|
}
|
|
2868
3286
|
function isTransformTarget(id) {
|
|
2869
3287
|
return SOURCE_FILE_RE.test(id) && !id.includes("node_modules") && !id.startsWith("\0");
|
|
@@ -3108,7 +3526,7 @@ const OPTIONS = {
|
|
|
3108
3526
|
}
|
|
3109
3527
|
};
|
|
3110
3528
|
function parseCli(args) {
|
|
3111
|
-
return parseArgs({
|
|
3529
|
+
return parseArgs$1({
|
|
3112
3530
|
args,
|
|
3113
3531
|
allowPositionals: true,
|
|
3114
3532
|
options: OPTIONS
|
|
@@ -3339,11 +3757,12 @@ async function doctor(cfg) {
|
|
|
3339
3757
|
else warn("plugin", `${host.name} detected but ${host.pkg} is not installed`, `${installCommand(cfg.root, host.install)}, then ${host.wire}`);
|
|
3340
3758
|
const scanning = cfg.include.length > 0;
|
|
3341
3759
|
if (!scanning) ok("sources", "source scanning is off (include: []), the catalogs are the source of truth");
|
|
3760
|
+
const registry = await extractProject(cfg);
|
|
3342
3761
|
if (source && scanning && cfg.dts !== false) {
|
|
3343
3762
|
const dtsPath = cfg.dts;
|
|
3344
3763
|
const shown = rel(dtsPath);
|
|
3345
3764
|
const regenerate = host?.name === "astro" ? "run `npx astro sync`, which writes the types and links them" : host?.name === "nuxt" ? "run `npx nuxi prepare`, which writes the types and links them" : "run `npx verbaly typegen`";
|
|
3346
|
-
const expected = generateDts(source, projectDtsOptions(cfg));
|
|
3765
|
+
const expected = generateDts(shippedCatalogs(cfg, catalogs, registry)[cfg.sourceLocale] ?? source, projectDtsOptions(cfg));
|
|
3347
3766
|
if (!existsSync(dtsPath)) warn("types", `${shown} has not been generated`, regenerate);
|
|
3348
3767
|
else if (readFileSync(dtsPath, "utf8").replace(/\r\n/g, "\n") !== expected) warn("types", `${shown} is stale`, "run `npx verbaly typegen`");
|
|
3349
3768
|
else ok("types", `${shown} is up to date`);
|
|
@@ -3354,7 +3773,6 @@ async function doctor(cfg) {
|
|
|
3354
3773
|
const old = join(cfg.root, "verbaly.d.ts");
|
|
3355
3774
|
if (dtsPath !== old && existsSync(old) && readFileSync(old, "utf8").startsWith("// generated by verbaly: do not edit")) warn("types", `the verbaly.d.ts Verbaly wrote at the root is still there next to ${shown}, and they declare the same module twice`, "run `npx verbaly typegen`, which removes it");
|
|
3356
3775
|
}
|
|
3357
|
-
const registry = await extractProject(cfg);
|
|
3358
3776
|
if (scanning) {
|
|
3359
3777
|
const unreadable = registry.parseErrors();
|
|
3360
3778
|
if (unreadable.length > 0) {
|
|
@@ -3469,39 +3887,106 @@ async function doctorCommand(cfg) {
|
|
|
3469
3887
|
process.exitCode = 1;
|
|
3470
3888
|
}
|
|
3471
3889
|
}
|
|
3890
|
+
// src/util/markup.ts
|
|
3891
|
+
const NAME$1 = `[^\\s=/"'<>]+`;
|
|
3892
|
+
const ATTRIBUTE = new RegExp(`(${NAME$1})(?:\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s>]+)))?`, "g");
|
|
3893
|
+
const ATTRIBUTE_NAME = new RegExp(`^${NAME$1}$`);
|
|
3894
|
+
const TAG_REST = `(?:"[^"]*"|'[^']*'|[^"'>])*`;
|
|
3895
|
+
function isAttributeName(name) {
|
|
3896
|
+
return ATTRIBUTE_NAME.test(name);
|
|
3897
|
+
}
|
|
3898
|
+
function readAttributes(chunk, lowerCase = false) {
|
|
3899
|
+
const attributes = /* @__PURE__ */ new Map();
|
|
3900
|
+
ATTRIBUTE.lastIndex = 0;
|
|
3901
|
+
let match;
|
|
3902
|
+
while ((match = ATTRIBUTE.exec(chunk)) !== null) {
|
|
3903
|
+
const name = lowerCase ? match[1].toLowerCase() : match[1];
|
|
3904
|
+
if (attributes.has(name)) continue;
|
|
3905
|
+
const quoted = match[2] ?? match[3];
|
|
3906
|
+
const value = quoted ?? match[4] ?? "";
|
|
3907
|
+
const end = match.index + match[0].length;
|
|
3908
|
+
const written = quoted !== void 0 ? value.length + 2 : value.length;
|
|
3909
|
+
attributes.set(name, {
|
|
3910
|
+
value,
|
|
3911
|
+
start: end - written,
|
|
3912
|
+
end
|
|
3913
|
+
});
|
|
3914
|
+
}
|
|
3915
|
+
return attributes;
|
|
3916
|
+
}
|
|
3917
|
+
const ENTITY = /&(?:(lt|gt|amp|quot|apos)|#(\d+)|#[xX]([0-9a-fA-F]+));/g;
|
|
3918
|
+
const NAMED = {
|
|
3919
|
+
lt: "<",
|
|
3920
|
+
gt: ">",
|
|
3921
|
+
amp: "&",
|
|
3922
|
+
quot: "\"",
|
|
3923
|
+
apos: "'"
|
|
3924
|
+
};
|
|
3925
|
+
function decodeEntities(text) {
|
|
3926
|
+
return text.replace(ENTITY, (whole, name, decimal, hex) => {
|
|
3927
|
+
if (name) return NAMED[name];
|
|
3928
|
+
const code = decimal ? parseInt(decimal, 10) : parseInt(hex, 16);
|
|
3929
|
+
return code <= 1114111 ? String.fromCodePoint(code) : whole;
|
|
3930
|
+
});
|
|
3931
|
+
}
|
|
3472
3932
|
// src/exchange/inline.ts
|
|
3473
3933
|
const OPEN_TAG = /^<([a-zA-Z][a-zA-Z0-9-]*)\s*(\/?)>/;
|
|
3934
|
+
const PH_EMPTY = new RegExp(`^<ph\\b(${TAG_REST}?)/\\s*>`);
|
|
3935
|
+
const PH_PAIRED = new RegExp(`^<ph\\b(${TAG_REST})>\\s*</ph\\s*>`);
|
|
3936
|
+
const PC_OPEN = new RegExp(`^<pc\\b(${TAG_REST})>`);
|
|
3937
|
+
const PC_TAGS = `<pc\\b${TAG_REST}>|</pc\\s*>`;
|
|
3474
3938
|
const BREAK = /^(?:br|wbr)$/;
|
|
3939
|
+
const VERBALY = {
|
|
3940
|
+
escape: (text, at) => text.startsWith("{{", at) || text.startsWith("}}", at) ? 2 : 0,
|
|
3941
|
+
translatable: hasTopLevelPipe
|
|
3942
|
+
};
|
|
3943
|
+
const ICU_BLOCK = /^\{\s*[a-zA-Z0-9_]+\s*,\s*(?:plural|selectordinal|select)\b/;
|
|
3944
|
+
const ICU = {
|
|
3945
|
+
escape(text, at) {
|
|
3946
|
+
if (text[at] !== "'") return 0;
|
|
3947
|
+
if (text[at + 1] === "'") return 2;
|
|
3948
|
+
if (!"{}#|".includes(text[at + 1] ?? " ")) return 0;
|
|
3949
|
+
for (let end = at + 1; end < text.length; end++) {
|
|
3950
|
+
if (text[end] !== "'") continue;
|
|
3951
|
+
if (text[end + 1] === "'") end += 1;
|
|
3952
|
+
else return end - at + 1;
|
|
3953
|
+
}
|
|
3954
|
+
return text.length - at;
|
|
3955
|
+
},
|
|
3956
|
+
translatable: (src) => ICU_BLOCK.test(src)
|
|
3957
|
+
};
|
|
3475
3958
|
function messageToInline(text) {
|
|
3476
|
-
return renderParts(parseParts(text, 0).parts, /* @__PURE__ */ new Map());
|
|
3959
|
+
return renderParts(parseParts(text, 0, isIcu(text) ? ICU : VERBALY).parts, /* @__PURE__ */ new Map());
|
|
3477
3960
|
}
|
|
3478
3961
|
function inlineToMessage(xml) {
|
|
3479
3962
|
let out = "";
|
|
3480
3963
|
let text = "";
|
|
3481
3964
|
let i = 0;
|
|
3482
3965
|
const flush = () => {
|
|
3483
|
-
out +=
|
|
3966
|
+
out += decodeEntities(text);
|
|
3484
3967
|
text = "";
|
|
3485
3968
|
};
|
|
3486
3969
|
while (i < xml.length) {
|
|
3487
3970
|
if (xml[i] === "<") {
|
|
3488
3971
|
const slice = xml.slice(i);
|
|
3489
|
-
const ph =
|
|
3972
|
+
const ph = PH_EMPTY.exec(slice) ?? PH_PAIRED.exec(slice);
|
|
3490
3973
|
if (ph) {
|
|
3491
3974
|
flush();
|
|
3492
|
-
|
|
3975
|
+
const attrs = readAttributes(ph[1]);
|
|
3976
|
+
out += attr(attrs, "disp") ?? `{${attr(attrs, "id") ?? "ph"}}`;
|
|
3493
3977
|
i += ph[0].length;
|
|
3494
3978
|
continue;
|
|
3495
3979
|
}
|
|
3496
|
-
const pc =
|
|
3980
|
+
const pc = PC_OPEN.exec(slice);
|
|
3497
3981
|
if (pc) {
|
|
3498
3982
|
const close = findPcClose(xml, i + pc[0].length);
|
|
3499
3983
|
if (close) {
|
|
3500
3984
|
flush();
|
|
3501
|
-
const
|
|
3502
|
-
|
|
3985
|
+
const attrs = readAttributes(pc[1]);
|
|
3986
|
+
const id = attr(attrs, "id") ?? "pc";
|
|
3987
|
+
out += attr(attrs, "dispStart") ?? `<${id}>`;
|
|
3503
3988
|
out += inlineToMessage(xml.slice(i + pc[0].length, close.innerEnd));
|
|
3504
|
-
out += attr(
|
|
3989
|
+
out += attr(attrs, "dispEnd") ?? `</${id}>`;
|
|
3505
3990
|
i = close.end;
|
|
3506
3991
|
continue;
|
|
3507
3992
|
}
|
|
@@ -3516,18 +4001,7 @@ function inlineToMessage(xml) {
|
|
|
3516
4001
|
function escapeXml(text) {
|
|
3517
4002
|
return text.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
|
3518
4003
|
}
|
|
3519
|
-
function
|
|
3520
|
-
return text.replace(/&(lt|gt|amp|quot|apos|#x?[0-9a-fA-F]+);/g, (_, entity) => {
|
|
3521
|
-
if (entity === "lt") return "<";
|
|
3522
|
-
if (entity === "gt") return ">";
|
|
3523
|
-
if (entity === "amp") return "&";
|
|
3524
|
-
if (entity === "quot") return "\"";
|
|
3525
|
-
if (entity === "apos") return "'";
|
|
3526
|
-
const code = entity.startsWith("#x") ? parseInt(entity.slice(2), 16) : parseInt(entity.slice(1), 10);
|
|
3527
|
-
return String.fromCodePoint(code);
|
|
3528
|
-
});
|
|
3529
|
-
}
|
|
3530
|
-
function parseParts(text, pos, closeTag) {
|
|
4004
|
+
function parseParts(text, pos, syntax, closeTag) {
|
|
3531
4005
|
const parts = [];
|
|
3532
4006
|
let plain = "";
|
|
3533
4007
|
const flush = () => {
|
|
@@ -3539,21 +4013,21 @@ function parseParts(text, pos, closeTag) {
|
|
|
3539
4013
|
};
|
|
3540
4014
|
let i = pos;
|
|
3541
4015
|
while (i < text.length) {
|
|
3542
|
-
const
|
|
3543
|
-
if (
|
|
3544
|
-
plain +=
|
|
3545
|
-
i +=
|
|
4016
|
+
const escaped = syntax.escape(text, i);
|
|
4017
|
+
if (escaped > 0) {
|
|
4018
|
+
plain += text.slice(i, i + escaped);
|
|
4019
|
+
i += escaped;
|
|
3546
4020
|
continue;
|
|
3547
4021
|
}
|
|
3548
4022
|
if (text[i] === "{") {
|
|
3549
|
-
const end = matchBrace$1(text, i);
|
|
4023
|
+
const end = matchBrace$1(text, i, syntax);
|
|
3550
4024
|
if (end === -1) {
|
|
3551
4025
|
plain += "{";
|
|
3552
4026
|
i += 1;
|
|
3553
4027
|
continue;
|
|
3554
4028
|
}
|
|
3555
4029
|
const src = text.slice(i, end + 1);
|
|
3556
|
-
if (
|
|
4030
|
+
if (syntax.translatable(src)) plain += src;
|
|
3557
4031
|
else {
|
|
3558
4032
|
flush();
|
|
3559
4033
|
parts.push({
|
|
@@ -3573,459 +4047,250 @@ function parseParts(text, pos, closeTag) {
|
|
|
3573
4047
|
end: i + closeTag.length + 3,
|
|
3574
4048
|
closed: true
|
|
3575
4049
|
};
|
|
3576
|
-
}
|
|
3577
|
-
const open = OPEN_TAG.exec(text.slice(i));
|
|
3578
|
-
if (open) {
|
|
3579
|
-
const [openSrc, name, selfClose] = open;
|
|
3580
|
-
if (selfClose || BREAK.test(name)) {
|
|
3581
|
-
flush();
|
|
3582
|
-
parts.push({
|
|
3583
|
-
kind: "ph",
|
|
3584
|
-
name: idSafe(name),
|
|
3585
|
-
src: openSrc
|
|
3586
|
-
});
|
|
3587
|
-
i += openSrc.length;
|
|
3588
|
-
continue;
|
|
3589
|
-
}
|
|
3590
|
-
const inner = parseParts(text, i + openSrc.length, name);
|
|
3591
|
-
if (inner.closed) {
|
|
3592
|
-
flush();
|
|
3593
|
-
parts.push({
|
|
3594
|
-
kind: "pc",
|
|
3595
|
-
name: idSafe(name),
|
|
3596
|
-
openSrc,
|
|
3597
|
-
closeSrc: `</${name}>`,
|
|
3598
|
-
children: inner.parts
|
|
3599
|
-
});
|
|
3600
|
-
i = inner.end;
|
|
3601
|
-
continue;
|
|
3602
|
-
}
|
|
3603
|
-
}
|
|
3604
|
-
plain += "<";
|
|
3605
|
-
i += 1;
|
|
3606
|
-
continue;
|
|
3607
|
-
}
|
|
3608
|
-
plain += text[i];
|
|
3609
|
-
i += 1;
|
|
3610
|
-
}
|
|
3611
|
-
flush();
|
|
3612
|
-
return {
|
|
3613
|
-
parts,
|
|
3614
|
-
end: i,
|
|
3615
|
-
closed: false
|
|
3616
|
-
};
|
|
3617
|
-
}
|
|
3618
|
-
function matchBrace$1(text, start) {
|
|
3619
|
-
let depth = 0;
|
|
3620
|
-
for (let i = start; i < text.length; i++) {
|
|
3621
|
-
const pair = text[i] + (text[i + 1] ?? "");
|
|
3622
|
-
if (pair === "{{" || pair === "}}") {
|
|
3623
|
-
i += 1;
|
|
3624
|
-
continue;
|
|
3625
|
-
}
|
|
3626
|
-
if (text[i] === "{") depth += 1;
|
|
3627
|
-
else if (text[i] === "}") {
|
|
3628
|
-
depth -= 1;
|
|
3629
|
-
if (depth === 0) return i;
|
|
3630
|
-
}
|
|
3631
|
-
}
|
|
3632
|
-
return -1;
|
|
3633
|
-
}
|
|
3634
|
-
function hasTopLevelPipe(src) {
|
|
3635
|
-
let depth = 0;
|
|
3636
|
-
for (let i = 0; i < src.length; i++) {
|
|
3637
|
-
const pair = src[i] + (src[i + 1] ?? "");
|
|
3638
|
-
if (pair === "{{" || pair === "}}" || pair === "||") {
|
|
3639
|
-
i += 1;
|
|
3640
|
-
continue;
|
|
3641
|
-
}
|
|
3642
|
-
if (src[i] === "{") depth += 1;
|
|
3643
|
-
else if (src[i] === "}") depth -= 1;
|
|
3644
|
-
else if (src[i] === "|" && depth === 1) return true;
|
|
3645
|
-
}
|
|
3646
|
-
return false;
|
|
3647
|
-
}
|
|
3648
|
-
function paramName(src) {
|
|
3649
|
-
const name = /^\{\s*([^{}|:\s]+)/.exec(src)?.[1];
|
|
3650
|
-
return name ? idSafe(name) : "ph";
|
|
3651
|
-
}
|
|
3652
|
-
function idSafe(name) {
|
|
3653
|
-
return name.replace(/[^a-zA-Z0-9._-]/g, "_") || "ph";
|
|
3654
|
-
}
|
|
3655
|
-
function renderParts(parts, taken) {
|
|
3656
|
-
let out = "";
|
|
3657
|
-
for (const part of parts) if (part.kind === "text") out += escapeXml(part.text);
|
|
3658
|
-
else if (part.kind === "ph") out += `<ph id="${uniqueId(part.name, taken)}" disp="${escapeXml(part.src)}"/>`;
|
|
3659
|
-
else {
|
|
3660
|
-
const id = uniqueId(part.name, taken);
|
|
3661
|
-
out += `<pc id="${id}" dispStart="${escapeXml(part.openSrc)}" dispEnd="${escapeXml(part.closeSrc)}">`;
|
|
3662
|
-
out += renderParts(part.children, taken);
|
|
3663
|
-
out += "</pc>";
|
|
3664
|
-
}
|
|
3665
|
-
return out;
|
|
3666
|
-
}
|
|
3667
|
-
function uniqueId(name, taken) {
|
|
3668
|
-
const count = taken.get(name) ?? 0;
|
|
3669
|
-
taken.set(name, count + 1);
|
|
3670
|
-
return count === 0 ? name : `${name}${count + 1}`;
|
|
3671
|
-
}
|
|
3672
|
-
function findPcClose(xml, from) {
|
|
3673
|
-
const tags = /<pc\b[^>]*>|<\/pc\s*>/g;
|
|
3674
|
-
tags.lastIndex = from;
|
|
3675
|
-
let depth = 1;
|
|
3676
|
-
for (let match = tags.exec(xml); match; match = tags.exec(xml)) {
|
|
3677
|
-
depth += match[0].startsWith("</") ? -1 : 1;
|
|
3678
|
-
if (depth === 0) return {
|
|
3679
|
-
innerEnd: match.index,
|
|
3680
|
-
end: tags.lastIndex
|
|
3681
|
-
};
|
|
3682
|
-
}
|
|
3683
|
-
}
|
|
3684
|
-
function attr(attrs, name) {
|
|
3685
|
-
const value = new RegExp(`\\b${name}\\s*=\\s*"([^"]*)"`).exec(attrs)?.[1];
|
|
3686
|
-
return value === void 0 ? void 0 : unescapeXml(value);
|
|
3687
|
-
}
|
|
3688
|
-
// src/exchange/mobile.ts
|
|
3689
|
-
function androidValuesDir(locale, sourceLocale) {
|
|
3690
|
-
if (locale === sourceLocale) return "values";
|
|
3691
|
-
const parts = locale.split("-");
|
|
3692
|
-
if (parts.length === 1) return `values-${locale}`;
|
|
3693
|
-
if (parts.length === 2 && /^[a-zA-Z]{2}$/.test(parts[1])) return `values-${parts[0]}-r${parts[1].toUpperCase()}`;
|
|
3694
|
-
return `values-b+${parts.join("+")}`;
|
|
3695
|
-
}
|
|
3696
|
-
function toAndroidXml(entries) {
|
|
3697
|
-
const names = /* @__PURE__ */ new Map();
|
|
3698
|
-
return [
|
|
3699
|
-
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>",
|
|
3700
|
-
"<resources>",
|
|
3701
|
-
...entries.map(({ key, text }) => {
|
|
3702
|
-
const name = androidName(key);
|
|
3703
|
-
const clash = names.get(name);
|
|
3704
|
-
if (clash !== void 0) throw new Error(`[verbaly] android-xml: keys "${clash}" and "${key}" both become resource name "${name}", rename one of them.`);
|
|
3705
|
-
names.set(name, key);
|
|
3706
|
-
return ` <string name="${name}">${androidText(text)}</string>`;
|
|
3707
|
-
}),
|
|
3708
|
-
"</resources>",
|
|
3709
|
-
""
|
|
3710
|
-
].join("\n");
|
|
3711
|
-
}
|
|
3712
|
-
function toIosStrings(entries) {
|
|
3713
|
-
return [...entries.map(({ key, text }) => `"${iosText(key)}" = "${iosText(text)}";`), ""].join("\n");
|
|
3714
|
-
}
|
|
3715
|
-
function androidName(key) {
|
|
3716
|
-
const name = key.replace(/[^A-Za-z0-9_]/g, "_");
|
|
3717
|
-
return /^[0-9]/.test(name) ? `_${name}` : name;
|
|
3718
|
-
}
|
|
3719
|
-
function androidText(text) {
|
|
3720
|
-
const escaped = text.replace(/\\/g, "\\\\").replace(/'/g, "\\'").replace(/"/g, "\\\"").replace(/\n/g, "\\n").replace(/\t/g, "\\t").replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
|
3721
|
-
return /^[@?]/.test(escaped) ? `\\${escaped}` : escaped;
|
|
3722
|
-
}
|
|
3723
|
-
function iosText(text) {
|
|
3724
|
-
return text.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/\n/g, "\\n").replace(/\t/g, "\\t");
|
|
3725
|
-
}
|
|
3726
|
-
// src/exchange/po.ts
|
|
3727
|
-
function toPo(sourceLocale, locale, entries) {
|
|
3728
|
-
return [
|
|
3729
|
-
[
|
|
3730
|
-
"msgid \"\"",
|
|
3731
|
-
"msgstr \"\"",
|
|
3732
|
-
`${poString("Project-Id-Version: verbaly\n")}`,
|
|
3733
|
-
`${poString("MIME-Version: 1.0\n")}`,
|
|
3734
|
-
`${poString("Content-Type: text/plain; charset=UTF-8\n")}`,
|
|
3735
|
-
`${poString("Content-Transfer-Encoding: 8bit\n")}`,
|
|
3736
|
-
`${poString(`Language: ${locale}\n`)}`,
|
|
3737
|
-
`${poString(`X-Source-Language: ${sourceLocale}\n`)}`
|
|
3738
|
-
].join("\n"),
|
|
3739
|
-
...entries.map(({ key, source, target, location }) => [
|
|
3740
|
-
...location?.length ? [`#: ${location.join(" ")}`] : [],
|
|
3741
|
-
`msgctxt ${poString(key)}`,
|
|
3742
|
-
`msgid ${poString(source)}`,
|
|
3743
|
-
`msgstr ${poString(target)}`
|
|
3744
|
-
].join("\n")),
|
|
3745
|
-
""
|
|
3746
|
-
].join("\n\n");
|
|
3747
|
-
}
|
|
3748
|
-
function parsePo(content) {
|
|
3749
|
-
const entries = Object.create(null);
|
|
3750
|
-
const sources = Object.create(null);
|
|
3751
|
-
let locale;
|
|
3752
|
-
let msgctxt;
|
|
3753
|
-
let msgid;
|
|
3754
|
-
let msgstr;
|
|
3755
|
-
let fuzzy = false;
|
|
3756
|
-
let field;
|
|
3757
|
-
const finish = () => {
|
|
3758
|
-
if (msgid === "" && msgctxt === void 0) {
|
|
3759
|
-
const lang = /^Language:[ \t]*(.+?)[ \t]*$/m.exec(msgstr ?? "")?.[1];
|
|
3760
|
-
if (lang) locale = lang;
|
|
3761
|
-
} else if (msgctxt !== void 0 && msgid !== void 0) {
|
|
3762
|
-
entries[msgctxt] = fuzzy ? "" : msgstr ?? "";
|
|
3763
|
-
sources[msgctxt] = msgid;
|
|
3764
|
-
}
|
|
3765
|
-
msgctxt = msgid = msgstr = field = void 0;
|
|
3766
|
-
fuzzy = false;
|
|
3767
|
-
};
|
|
3768
|
-
for (const raw of content.replace(/^\uFEFF/, "").split(/\r\n|[\r\n]/)) {
|
|
3769
|
-
const line = raw.trim();
|
|
3770
|
-
if (line === "") {
|
|
3771
|
-
finish();
|
|
3772
|
-
continue;
|
|
3773
|
-
}
|
|
3774
|
-
if (line.startsWith("#")) {
|
|
3775
|
-
if (/^#,.*\bfuzzy\b/.test(line)) fuzzy = true;
|
|
3776
|
-
continue;
|
|
3777
|
-
}
|
|
3778
|
-
const keyword = /^(msgctxt|msgid_plural|msgid|msgstr(?:\[\d+\])?)\s+(.*)$/.exec(line);
|
|
3779
|
-
if (keyword) {
|
|
3780
|
-
const [, name, rest] = keyword;
|
|
3781
|
-
const value = poUnquote(rest);
|
|
3782
|
-
if (value === void 0) continue;
|
|
3783
|
-
if (name === "msgctxt") {
|
|
3784
|
-
msgctxt = value;
|
|
3785
|
-
field = "msgctxt";
|
|
3786
|
-
} else if (name === "msgid") {
|
|
3787
|
-
msgid = value;
|
|
3788
|
-
field = "msgid";
|
|
3789
|
-
} else if (name === "msgstr" || name === "msgstr[0]") {
|
|
3790
|
-
msgstr = value;
|
|
3791
|
-
field = "msgstr";
|
|
3792
|
-
} else field = "other";
|
|
4050
|
+
}
|
|
4051
|
+
const open = OPEN_TAG.exec(text.slice(i));
|
|
4052
|
+
if (open) {
|
|
4053
|
+
const [openSrc, name, selfClose] = open;
|
|
4054
|
+
if (selfClose || BREAK.test(name)) {
|
|
4055
|
+
flush();
|
|
4056
|
+
parts.push({
|
|
4057
|
+
kind: "ph",
|
|
4058
|
+
name: idSafe(name),
|
|
4059
|
+
src: openSrc
|
|
4060
|
+
});
|
|
4061
|
+
i += openSrc.length;
|
|
4062
|
+
continue;
|
|
4063
|
+
}
|
|
4064
|
+
const inner = parseParts(text, i + openSrc.length, syntax, name);
|
|
4065
|
+
if (inner.closed) {
|
|
4066
|
+
flush();
|
|
4067
|
+
parts.push({
|
|
4068
|
+
kind: "pc",
|
|
4069
|
+
name: idSafe(name),
|
|
4070
|
+
openSrc,
|
|
4071
|
+
closeSrc: `</${name}>`,
|
|
4072
|
+
children: inner.parts
|
|
4073
|
+
});
|
|
4074
|
+
i = inner.end;
|
|
4075
|
+
continue;
|
|
4076
|
+
}
|
|
4077
|
+
}
|
|
4078
|
+
plain += "<";
|
|
4079
|
+
i += 1;
|
|
3793
4080
|
continue;
|
|
3794
4081
|
}
|
|
3795
|
-
|
|
3796
|
-
|
|
3797
|
-
if (field === "msgctxt") msgctxt = (msgctxt ?? "") + continuation;
|
|
3798
|
-
else if (field === "msgid") msgid = (msgid ?? "") + continuation;
|
|
3799
|
-
else msgstr = (msgstr ?? "") + continuation;
|
|
4082
|
+
plain += text[i];
|
|
4083
|
+
i += 1;
|
|
3800
4084
|
}
|
|
3801
|
-
|
|
4085
|
+
flush();
|
|
3802
4086
|
return {
|
|
3803
|
-
|
|
3804
|
-
|
|
3805
|
-
|
|
4087
|
+
parts,
|
|
4088
|
+
end: i,
|
|
4089
|
+
closed: false
|
|
3806
4090
|
};
|
|
3807
4091
|
}
|
|
3808
|
-
function
|
|
3809
|
-
|
|
3810
|
-
|
|
3811
|
-
|
|
3812
|
-
|
|
3813
|
-
|
|
3814
|
-
return match[1].replace(/\\(.)/g, (_, ch) => {
|
|
3815
|
-
if (ch === "n") return "\n";
|
|
3816
|
-
if (ch === "t") return " ";
|
|
3817
|
-
if (ch === "r") return "\r";
|
|
3818
|
-
return ch;
|
|
3819
|
-
});
|
|
3820
|
-
}
|
|
3821
|
-
// src/exchange/translate.ts
|
|
3822
|
-
const RETRY_STATUS = /* @__PURE__ */ new Set([
|
|
3823
|
-
408,
|
|
3824
|
-
409,
|
|
3825
|
-
425,
|
|
3826
|
-
429,
|
|
3827
|
-
500,
|
|
3828
|
-
502,
|
|
3829
|
-
503,
|
|
3830
|
-
504,
|
|
3831
|
-
529
|
|
3832
|
-
]);
|
|
3833
|
-
function retryable(error) {
|
|
3834
|
-
const status = error?.status;
|
|
3835
|
-
const code = error?.statusCode;
|
|
3836
|
-
const value = typeof status === "number" ? status : code;
|
|
3837
|
-
return typeof value === "number" ? RETRY_STATUS.has(value) : true;
|
|
3838
|
-
}
|
|
3839
|
-
function reason(error) {
|
|
3840
|
-
return error instanceof Error ? error.message : String(error);
|
|
3841
|
-
}
|
|
3842
|
-
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
3843
|
-
async function attempt(run, retries, delay) {
|
|
3844
|
-
for (let round = 0;; round++) try {
|
|
3845
|
-
return await run();
|
|
3846
|
-
} catch (error) {
|
|
3847
|
-
if (round >= retries || !retryable(error)) throw error;
|
|
3848
|
-
await wait(delay * 2 ** round);
|
|
3849
|
-
}
|
|
3850
|
-
}
|
|
3851
|
-
async function pooled(jobs, limit, run) {
|
|
3852
|
-
let next = 0;
|
|
3853
|
-
const workers = Array.from({ length: Math.min(limit, jobs.length) }, async () => {
|
|
3854
|
-
while (next < jobs.length) await run(jobs[next++]);
|
|
3855
|
-
});
|
|
3856
|
-
await Promise.all(workers);
|
|
3857
|
-
}
|
|
3858
|
-
async function translateCatalogs(cfg, catalogs, provider, options = {}) {
|
|
3859
|
-
const batchSize = options.batchSize ?? 20;
|
|
3860
|
-
const concurrency = Math.max(1, options.concurrency ?? 4);
|
|
3861
|
-
const retries = Math.max(0, options.retries ?? 2);
|
|
3862
|
-
const retryDelay = options.retryDelay ?? 500;
|
|
3863
|
-
const targets = targetLocales(cfg, options.locales);
|
|
3864
|
-
const source = catalogs[cfg.sourceLocale] ?? {};
|
|
3865
|
-
const result = {
|
|
3866
|
-
translated: emptyCatalog(),
|
|
3867
|
-
invalid: emptyCatalog(),
|
|
3868
|
-
pending: emptyCatalog(),
|
|
3869
|
-
failed: []
|
|
3870
|
-
};
|
|
3871
|
-
const jobs = [];
|
|
3872
|
-
for (const locale of targets) {
|
|
3873
|
-
const catalog = catalogs[locale] ??= emptyCatalog();
|
|
3874
|
-
const missing = Object.keys(source).filter((key) => source[key] && !own(catalog, key));
|
|
3875
|
-
if (missing.length === 0) continue;
|
|
3876
|
-
if (options.dryRun) {
|
|
3877
|
-
result.pending[locale] = missing;
|
|
4092
|
+
function matchBrace$1(text, start, syntax) {
|
|
4093
|
+
let depth = 0;
|
|
4094
|
+
for (let i = start; i < text.length; i++) {
|
|
4095
|
+
const escaped = syntax.escape(text, i);
|
|
4096
|
+
if (escaped > 0) {
|
|
4097
|
+
i += escaped - 1;
|
|
3878
4098
|
continue;
|
|
3879
4099
|
}
|
|
3880
|
-
|
|
3881
|
-
|
|
3882
|
-
|
|
3883
|
-
|
|
3884
|
-
locale,
|
|
3885
|
-
index,
|
|
3886
|
-
batches,
|
|
3887
|
-
keys: missing.slice(i, i + batchSize)
|
|
3888
|
-
});
|
|
4100
|
+
if (text[i] === "{") depth += 1;
|
|
4101
|
+
else if (text[i] === "}") {
|
|
4102
|
+
depth -= 1;
|
|
4103
|
+
if (depth === 0) return i;
|
|
3889
4104
|
}
|
|
3890
4105
|
}
|
|
3891
|
-
|
|
3892
|
-
|
|
3893
|
-
|
|
3894
|
-
|
|
3895
|
-
|
|
3896
|
-
|
|
3897
|
-
|
|
3898
|
-
|
|
3899
|
-
|
|
3900
|
-
targetLocale: locale,
|
|
3901
|
-
messages,
|
|
3902
|
-
origins,
|
|
3903
|
-
instructions: cfg.translate.instructions,
|
|
3904
|
-
glossary: glossaryFor(cfg, locale, messages)
|
|
3905
|
-
}), retries, retryDelay);
|
|
3906
|
-
} catch (error) {
|
|
3907
|
-
const message = reason(error);
|
|
3908
|
-
result.failed.push({
|
|
3909
|
-
locale,
|
|
3910
|
-
keys,
|
|
3911
|
-
error: message
|
|
3912
|
-
});
|
|
3913
|
-
options.onProgress?.({
|
|
3914
|
-
...progressOf(job),
|
|
3915
|
-
error: message
|
|
3916
|
-
});
|
|
3917
|
-
return;
|
|
3918
|
-
}
|
|
3919
|
-
for (const key of keys) {
|
|
3920
|
-
const text = out[key];
|
|
3921
|
-
if (typeof text === "string" && text.trim() && structureMatches(source[key], text)) {
|
|
3922
|
-
catalog[key] = text;
|
|
3923
|
-
(result.translated[locale] ??= []).push(key);
|
|
3924
|
-
} else (result.invalid[locale] ??= []).push(key);
|
|
4106
|
+
return -1;
|
|
4107
|
+
}
|
|
4108
|
+
function hasTopLevelPipe(src) {
|
|
4109
|
+
let depth = 0;
|
|
4110
|
+
for (let i = 0; i < src.length; i++) {
|
|
4111
|
+
const pair = src[i] + (src[i + 1] ?? "");
|
|
4112
|
+
if (pair === "{{" || pair === "}}" || pair === "||") {
|
|
4113
|
+
i += 1;
|
|
4114
|
+
continue;
|
|
3925
4115
|
}
|
|
3926
|
-
|
|
3927
|
-
|
|
3928
|
-
|
|
3929
|
-
|
|
3930
|
-
|
|
3931
|
-
return result;
|
|
4116
|
+
if (src[i] === "{") depth += 1;
|
|
4117
|
+
else if (src[i] === "}") depth -= 1;
|
|
4118
|
+
else if (src[i] === "|" && depth === 1) return true;
|
|
4119
|
+
}
|
|
4120
|
+
return false;
|
|
3932
4121
|
}
|
|
3933
|
-
function
|
|
3934
|
-
|
|
4122
|
+
function paramName(src) {
|
|
4123
|
+
const name = /^\{\s*([^{}|:,\s]+)/.exec(src)?.[1];
|
|
4124
|
+
return name ? idSafe(name) : "ph";
|
|
3935
4125
|
}
|
|
3936
|
-
function
|
|
3937
|
-
|
|
3938
|
-
const current = readCatalog(cfg, locale);
|
|
3939
|
-
const written = [];
|
|
3940
|
-
for (const key of keys) {
|
|
3941
|
-
const text = translated[key];
|
|
3942
|
-
if (!source[key] || current[key] || !text) continue;
|
|
3943
|
-
current[key] = text;
|
|
3944
|
-
written.push(key);
|
|
3945
|
-
}
|
|
3946
|
-
if (written.length > 0) writeCatalog(cfg, locale, current);
|
|
3947
|
-
return written;
|
|
4126
|
+
function idSafe(name) {
|
|
4127
|
+
return name.replace(/[^a-zA-Z0-9._-]/g, "_") || "ph";
|
|
3948
4128
|
}
|
|
3949
|
-
function
|
|
3950
|
-
|
|
3951
|
-
|
|
3952
|
-
|
|
3953
|
-
|
|
3954
|
-
|
|
3955
|
-
|
|
3956
|
-
|
|
3957
|
-
|
|
3958
|
-
kept: [],
|
|
3959
|
-
invalid: [],
|
|
3960
|
-
unknown: []
|
|
3961
|
-
};
|
|
3962
|
-
for (const { key, text } of entries) {
|
|
3963
|
-
const from = own(source, key);
|
|
3964
|
-
if (!from) result.unknown.push(key);
|
|
3965
|
-
else if (!text.trim() || !structureMatches(from, text)) result.invalid.push(key);
|
|
3966
|
-
else if (own(current, key) && !options.overwrite) result.kept.push(key);
|
|
3967
|
-
else {
|
|
3968
|
-
current[key] = text;
|
|
3969
|
-
result.written.push(key);
|
|
3970
|
-
}
|
|
4129
|
+
function renderParts(parts, taken) {
|
|
4130
|
+
let out = "";
|
|
4131
|
+
for (const part of parts) if (part.kind === "text") out += escapeXml(part.text);
|
|
4132
|
+
else if (part.kind === "ph") out += `<ph id="${uniqueId(part.name, taken)}" disp="${escapeXml(part.src)}"/>`;
|
|
4133
|
+
else {
|
|
4134
|
+
const id = uniqueId(part.name, taken);
|
|
4135
|
+
out += `<pc id="${id}" dispStart="${escapeXml(part.openSrc)}" dispEnd="${escapeXml(part.closeSrc)}">`;
|
|
4136
|
+
out += renderParts(part.children, taken);
|
|
4137
|
+
out += "</pc>";
|
|
3971
4138
|
}
|
|
3972
|
-
|
|
3973
|
-
|
|
3974
|
-
|
|
3975
|
-
|
|
3976
|
-
|
|
3977
|
-
|
|
3978
|
-
|
|
3979
|
-
|
|
3980
|
-
|
|
3981
|
-
|
|
4139
|
+
return out;
|
|
4140
|
+
}
|
|
4141
|
+
function uniqueId(name, taken) {
|
|
4142
|
+
const count = taken.get(name) ?? 0;
|
|
4143
|
+
taken.set(name, count + 1);
|
|
4144
|
+
return count === 0 ? name : `${name}${count + 1}`;
|
|
4145
|
+
}
|
|
4146
|
+
function findPcClose(xml, from) {
|
|
4147
|
+
const tags = new RegExp(PC_TAGS, "g");
|
|
4148
|
+
tags.lastIndex = from;
|
|
4149
|
+
let depth = 1;
|
|
4150
|
+
for (let match = tags.exec(xml); match; match = tags.exec(xml)) {
|
|
4151
|
+
depth += match[0].startsWith("</") ? -1 : 1;
|
|
4152
|
+
if (depth === 0) return {
|
|
4153
|
+
innerEnd: match.index,
|
|
4154
|
+
end: tags.lastIndex
|
|
4155
|
+
};
|
|
3982
4156
|
}
|
|
3983
|
-
return result;
|
|
3984
4157
|
}
|
|
3985
|
-
function
|
|
3986
|
-
const
|
|
3987
|
-
|
|
3988
|
-
const same = grouped.find((it) => it.locale === entry.locale && it.error === entry.error);
|
|
3989
|
-
if (same) same.keys = [...same.keys, ...entry.keys];
|
|
3990
|
-
else grouped.push({
|
|
3991
|
-
...entry,
|
|
3992
|
-
keys: [...entry.keys]
|
|
3993
|
-
});
|
|
3994
|
-
}
|
|
3995
|
-
return grouped.map(({ locale, error, keys }) => ` ${locale}: ${counted(keys.length, "message")} not translated (${error}): ${keys.join(", ")}`);
|
|
4158
|
+
function attr(attrs, name) {
|
|
4159
|
+
const value = attrs.get(name)?.value;
|
|
4160
|
+
return value === void 0 ? void 0 : decodeEntities(value);
|
|
3996
4161
|
}
|
|
3997
|
-
|
|
3998
|
-
|
|
3999
|
-
if (
|
|
4000
|
-
const
|
|
4001
|
-
|
|
4162
|
+
// src/exchange/mobile.ts
|
|
4163
|
+
function androidValuesDir(locale, sourceLocale) {
|
|
4164
|
+
if (locale === sourceLocale) return "values";
|
|
4165
|
+
const parts = locale.split("-");
|
|
4166
|
+
if (parts.length === 1) return `values-${locale}`;
|
|
4167
|
+
if (parts.length === 2 && /^[a-zA-Z]{2}$/.test(parts[1])) return `values-${parts[0]}-r${parts[1].toUpperCase()}`;
|
|
4168
|
+
return `values-b+${parts.join("+")}`;
|
|
4002
4169
|
}
|
|
4003
|
-
function
|
|
4004
|
-
|
|
4005
|
-
|
|
4006
|
-
|
|
4007
|
-
|
|
4008
|
-
|
|
4170
|
+
function toAndroidXml(entries) {
|
|
4171
|
+
const names = /* @__PURE__ */ new Map();
|
|
4172
|
+
return [
|
|
4173
|
+
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>",
|
|
4174
|
+
"<resources>",
|
|
4175
|
+
...entries.map(({ key, text }) => {
|
|
4176
|
+
const name = androidName(key);
|
|
4177
|
+
const clash = names.get(name);
|
|
4178
|
+
if (clash !== void 0) throw new Error(`[verbaly] android-xml: keys "${clash}" and "${key}" both become resource name "${name}", rename one of them.`);
|
|
4179
|
+
names.set(name, key);
|
|
4180
|
+
return ` <string name="${name}">${androidText(text)}</string>`;
|
|
4181
|
+
}),
|
|
4182
|
+
"</resources>",
|
|
4183
|
+
""
|
|
4184
|
+
].join("\n");
|
|
4009
4185
|
}
|
|
4010
|
-
function
|
|
4186
|
+
function toIosStrings(entries) {
|
|
4187
|
+
return [...entries.map(({ key, text }) => `"${iosText(key)}" = "${iosText(text)}";`), ""].join("\n");
|
|
4188
|
+
}
|
|
4189
|
+
function androidName(key) {
|
|
4190
|
+
const name = key.replace(/[^A-Za-z0-9_]/g, "_");
|
|
4191
|
+
return /^[0-9]/.test(name) ? `_${name}` : name;
|
|
4192
|
+
}
|
|
4193
|
+
function androidText(text) {
|
|
4194
|
+
const escaped = text.replace(/\\/g, "\\\\").replace(/'/g, "\\'").replace(/"/g, "\\\"").replace(/\n/g, "\\n").replace(/\t/g, "\\t").replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
|
4195
|
+
return /^[@?]/.test(escaped) ? `\\${escaped}` : escaped;
|
|
4196
|
+
}
|
|
4197
|
+
function iosText(text) {
|
|
4198
|
+
return text.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/\n/g, "\\n").replace(/\t/g, "\\t");
|
|
4199
|
+
}
|
|
4200
|
+
// src/exchange/po.ts
|
|
4201
|
+
function toPo(sourceLocale, locale, entries) {
|
|
4202
|
+
return [
|
|
4203
|
+
[
|
|
4204
|
+
"msgid \"\"",
|
|
4205
|
+
"msgstr \"\"",
|
|
4206
|
+
`${poString("Project-Id-Version: verbaly\n")}`,
|
|
4207
|
+
`${poString("MIME-Version: 1.0\n")}`,
|
|
4208
|
+
`${poString("Content-Type: text/plain; charset=UTF-8\n")}`,
|
|
4209
|
+
`${poString("Content-Transfer-Encoding: 8bit\n")}`,
|
|
4210
|
+
`${poString(`Language: ${locale}\n`)}`,
|
|
4211
|
+
`${poString(`X-Source-Language: ${sourceLocale}\n`)}`
|
|
4212
|
+
].join("\n"),
|
|
4213
|
+
...entries.map(({ key, source, target, location }) => [
|
|
4214
|
+
...location?.length ? [`#: ${location.join(" ")}`] : [],
|
|
4215
|
+
`msgctxt ${poString(key)}`,
|
|
4216
|
+
`msgid ${poString(source)}`,
|
|
4217
|
+
`msgstr ${poString(target)}`
|
|
4218
|
+
].join("\n")),
|
|
4219
|
+
""
|
|
4220
|
+
].join("\n\n");
|
|
4221
|
+
}
|
|
4222
|
+
function parsePo(content) {
|
|
4223
|
+
const entries = Object.create(null);
|
|
4224
|
+
const sources = Object.create(null);
|
|
4225
|
+
let locale;
|
|
4226
|
+
let msgctxt;
|
|
4227
|
+
let msgid;
|
|
4228
|
+
let msgstr;
|
|
4229
|
+
let fuzzy = false;
|
|
4230
|
+
let field;
|
|
4231
|
+
const finish = () => {
|
|
4232
|
+
if (msgid === "" && msgctxt === void 0) {
|
|
4233
|
+
const lang = /^Language:[ \t]*(.+?)[ \t]*$/m.exec(msgstr ?? "")?.[1];
|
|
4234
|
+
if (lang) locale = lang;
|
|
4235
|
+
} else if (msgctxt !== void 0 && msgid !== void 0) {
|
|
4236
|
+
entries[msgctxt] = fuzzy ? "" : msgstr ?? "";
|
|
4237
|
+
sources[msgctxt] = msgid;
|
|
4238
|
+
}
|
|
4239
|
+
msgctxt = msgid = msgstr = field = void 0;
|
|
4240
|
+
fuzzy = false;
|
|
4241
|
+
};
|
|
4242
|
+
for (const raw of content.replace(/^\uFEFF/, "").split(/\r\n|[\r\n]/)) {
|
|
4243
|
+
const line = raw.trim();
|
|
4244
|
+
if (line === "") {
|
|
4245
|
+
finish();
|
|
4246
|
+
continue;
|
|
4247
|
+
}
|
|
4248
|
+
if (line.startsWith("#")) {
|
|
4249
|
+
if (/^#,.*\bfuzzy\b/.test(line)) fuzzy = true;
|
|
4250
|
+
continue;
|
|
4251
|
+
}
|
|
4252
|
+
const keyword = /^(msgctxt|msgid_plural|msgid|msgstr(?:\[\d+\])?)\s+(.*)$/.exec(line);
|
|
4253
|
+
if (keyword) {
|
|
4254
|
+
const [, name, rest] = keyword;
|
|
4255
|
+
const value = poUnquote(rest);
|
|
4256
|
+
if (value === void 0) continue;
|
|
4257
|
+
if (name === "msgctxt") {
|
|
4258
|
+
msgctxt = value;
|
|
4259
|
+
field = "msgctxt";
|
|
4260
|
+
} else if (name === "msgid") {
|
|
4261
|
+
msgid = value;
|
|
4262
|
+
field = "msgid";
|
|
4263
|
+
} else if (name === "msgstr" || name === "msgstr[0]") {
|
|
4264
|
+
msgstr = value;
|
|
4265
|
+
field = "msgstr";
|
|
4266
|
+
} else field = "other";
|
|
4267
|
+
continue;
|
|
4268
|
+
}
|
|
4269
|
+
const continuation = poUnquote(line);
|
|
4270
|
+
if (continuation === void 0 || field === void 0 || field === "other") continue;
|
|
4271
|
+
if (field === "msgctxt") msgctxt = (msgctxt ?? "") + continuation;
|
|
4272
|
+
else if (field === "msgid") msgid = (msgid ?? "") + continuation;
|
|
4273
|
+
else msgstr = (msgstr ?? "") + continuation;
|
|
4274
|
+
}
|
|
4275
|
+
finish();
|
|
4011
4276
|
return {
|
|
4012
|
-
locale
|
|
4013
|
-
|
|
4014
|
-
|
|
4015
|
-
keys: job.keys.length
|
|
4277
|
+
locale,
|
|
4278
|
+
entries,
|
|
4279
|
+
sources
|
|
4016
4280
|
};
|
|
4017
4281
|
}
|
|
4018
|
-
function
|
|
4019
|
-
|
|
4020
|
-
|
|
4021
|
-
|
|
4022
|
-
const
|
|
4023
|
-
|
|
4024
|
-
|
|
4025
|
-
|
|
4026
|
-
if (
|
|
4027
|
-
|
|
4028
|
-
|
|
4282
|
+
function poString(text) {
|
|
4283
|
+
return `"${text.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/\n/g, "\\n").replace(/\t/g, "\\t").replace(/\r/g, "\\r")}"`;
|
|
4284
|
+
}
|
|
4285
|
+
function poUnquote(text) {
|
|
4286
|
+
const match = /^"((?:[^"\\]|\\.)*)"$/.exec(text);
|
|
4287
|
+
if (!match) return void 0;
|
|
4288
|
+
return match[1].replace(/\\(.)/g, (_, ch) => {
|
|
4289
|
+
if (ch === "n") return "\n";
|
|
4290
|
+
if (ch === "t") return " ";
|
|
4291
|
+
if (ch === "r") return "\r";
|
|
4292
|
+
return ch;
|
|
4293
|
+
});
|
|
4029
4294
|
}
|
|
4030
4295
|
// src/exchange/exchange.ts
|
|
4031
4296
|
function isMobileFormat(format) {
|
|
@@ -4205,17 +4470,25 @@ function newLocale(cfg, detected) {
|
|
|
4205
4470
|
if (cfg.localesDeclared) return void 0;
|
|
4206
4471
|
return isLocaleTag(detected) ? detected : suggestTag(detected);
|
|
4207
4472
|
}
|
|
4473
|
+
const UNIT = `<(?:trans-)?unit\\b(${TAG_REST})>([\\s\\S]*?)</(?:trans-)?unit>`;
|
|
4474
|
+
const TARGET = new RegExp(`<target\\b${TAG_REST}>([\\s\\S]*?)</target>`);
|
|
4475
|
+
const SOURCE = new RegExp(`<source\\b${TAG_REST}>([\\s\\S]*?)</source>`);
|
|
4476
|
+
function tagAttribute(content, tag, name) {
|
|
4477
|
+
const open = new RegExp(`<${tag}\\b(${TAG_REST})>`).exec(content);
|
|
4478
|
+
return open && readAttributes(open[1]).get(name)?.value || void 0;
|
|
4479
|
+
}
|
|
4208
4480
|
function parseXliff(content) {
|
|
4209
|
-
const
|
|
4481
|
+
const head = (name) => tagAttribute(content, "xliff", name) ?? tagAttribute(content, "file", name);
|
|
4482
|
+
const locale = head("trgLang") ?? head("target-language");
|
|
4210
4483
|
const entries = Object.create(null);
|
|
4211
4484
|
const sources = Object.create(null);
|
|
4212
|
-
for (const match of content.matchAll(
|
|
4213
|
-
const id =
|
|
4485
|
+
for (const match of content.matchAll(new RegExp(UNIT, "g"))) {
|
|
4486
|
+
const id = readAttributes(match[1]).get("id")?.value;
|
|
4214
4487
|
if (!id) continue;
|
|
4215
|
-
const target =
|
|
4216
|
-
entries[
|
|
4217
|
-
const source =
|
|
4218
|
-
if (source !== void 0) sources[
|
|
4488
|
+
const target = TARGET.exec(match[2])?.[1];
|
|
4489
|
+
entries[decodeEntities(id)] = target === void 0 ? "" : inlineToMessage(stripCdata(target));
|
|
4490
|
+
const source = SOURCE.exec(match[2])?.[1];
|
|
4491
|
+
if (source !== void 0) sources[decodeEntities(id)] = inlineToMessage(stripCdata(source));
|
|
4219
4492
|
}
|
|
4220
4493
|
return {
|
|
4221
4494
|
locale,
|
|
@@ -4237,7 +4510,7 @@ function csvField(text) {
|
|
|
4237
4510
|
return /[",\r\n]/.test(text) ? `"${text.replace(/"/g, "\"\"")}"` : text;
|
|
4238
4511
|
}
|
|
4239
4512
|
function parseCsv(content) {
|
|
4240
|
-
const rows = csvRows(content);
|
|
4513
|
+
const rows = csvRows(content, csvSeparator(content));
|
|
4241
4514
|
const header = rows[0]?.map((cell) => cell.trim().toLowerCase()) ?? [];
|
|
4242
4515
|
const keyCol = header.indexOf("key");
|
|
4243
4516
|
const targetCol = header.indexOf("target");
|
|
@@ -4257,7 +4530,15 @@ function parseCsv(content) {
|
|
|
4257
4530
|
sources
|
|
4258
4531
|
};
|
|
4259
4532
|
}
|
|
4260
|
-
function
|
|
4533
|
+
function csvSeparator(content) {
|
|
4534
|
+
let quoted = false;
|
|
4535
|
+
const seen = /* @__PURE__ */ new Set();
|
|
4536
|
+
for (const char of content) if (char === "\"") quoted = !quoted;
|
|
4537
|
+
else if (!quoted && (char === "\n" || char === "\r")) break;
|
|
4538
|
+
else if (!quoted) seen.add(char);
|
|
4539
|
+
return seen.has(",") ? "," : seen.has(";") ? ";" : seen.has(" ") ? " " : ",";
|
|
4540
|
+
}
|
|
4541
|
+
function csvRows(content, separator) {
|
|
4261
4542
|
const rows = [];
|
|
4262
4543
|
let row = [];
|
|
4263
4544
|
let field = "";
|
|
@@ -4272,7 +4553,7 @@ function csvRows(content) {
|
|
|
4272
4553
|
} else quoted = false;
|
|
4273
4554
|
} else field += char;
|
|
4274
4555
|
} else if (char === "\"") quoted = true;
|
|
4275
|
-
else if (char ===
|
|
4556
|
+
else if (char === separator) {
|
|
4276
4557
|
row.push(field);
|
|
4277
4558
|
field = "";
|
|
4278
4559
|
} else if (char === "\n" || char === "\r") {
|
|
@@ -4672,8 +4953,9 @@ function migrateCatalogs(cfg, options = {}) {
|
|
|
4672
4953
|
const catalog = catalogs.get(locale);
|
|
4673
4954
|
const out = Object.assign(emptyCatalog(), catalog);
|
|
4674
4955
|
const convert = fromI18next && !done.has(locale);
|
|
4956
|
+
const reported = convert || done.has(locale);
|
|
4675
4957
|
for (const [key, value] of Object.entries(catalog)) {
|
|
4676
|
-
if (!
|
|
4958
|
+
if (!reported || typeof value !== "string") continue;
|
|
4677
4959
|
const problem = i18nextProblem(value);
|
|
4678
4960
|
if (problem) {
|
|
4679
4961
|
skipped.push({
|
|
@@ -4683,6 +4965,7 @@ function migrateCatalogs(cfg, options = {}) {
|
|
|
4683
4965
|
});
|
|
4684
4966
|
continue;
|
|
4685
4967
|
}
|
|
4968
|
+
if (!convert) continue;
|
|
4686
4969
|
const after = convertBraces(value);
|
|
4687
4970
|
if (after !== value) {
|
|
4688
4971
|
braces.push({
|
|
@@ -4694,7 +4977,12 @@ function migrateCatalogs(cfg, options = {}) {
|
|
|
4694
4977
|
out[key] = after;
|
|
4695
4978
|
}
|
|
4696
4979
|
}
|
|
4697
|
-
if (options.plurals)
|
|
4980
|
+
if (options.plurals) {
|
|
4981
|
+
mergePlurals(locale, catalog, out, plurals, skipped, convert);
|
|
4982
|
+
const merged = new Set(plurals.filter((entry) => entry.locale === locale).flatMap((entry) => entry.from));
|
|
4983
|
+
const left = braces.filter((entry) => entry.locale !== locale || !merged.has(entry.key));
|
|
4984
|
+
braces.splice(0, braces.length, ...left);
|
|
4985
|
+
}
|
|
4698
4986
|
if ((braces.some((b) => b.locale === locale) || plurals.some((p) => p.locale === locale)) && options.write) {
|
|
4699
4987
|
writeCatalog(cfg, locale, out);
|
|
4700
4988
|
written.push(locale);
|
|
@@ -4740,9 +5028,9 @@ function existingCatalogs(root) {
|
|
|
4740
5028
|
});
|
|
4741
5029
|
}
|
|
4742
5030
|
function configSource(options, typescript) {
|
|
4743
|
-
const fields = [` sourceLocale:
|
|
4744
|
-
if (options.locales?.length) fields.push(` locales: [${options.locales.map(
|
|
4745
|
-
if (options.dir) fields.push(` dir:
|
|
5031
|
+
const fields = [` sourceLocale: ${singleQuoted(options.sourceLocale ?? "en")},`];
|
|
5032
|
+
if (options.locales?.length) fields.push(` locales: [${options.locales.map(singleQuoted).join(", ")}],`);
|
|
5033
|
+
if (options.dir) fields.push(` dir: ${singleQuoted(options.dir)},`);
|
|
4746
5034
|
const body = `export default {\n${fields.join("\n")}\n}`;
|
|
4747
5035
|
if (typescript) return `import type { VerbalyConfig } from '@verbaly/compiler';\n\n${body} satisfies VerbalyConfig;\n`;
|
|
4748
5036
|
return `/** @type {import('@verbaly/compiler').VerbalyConfig} */\n${body};\n`;
|
|
@@ -5017,7 +5305,6 @@ const REDIRECT_OPEN = "<!--verbaly:redirect-->";
|
|
|
5017
5305
|
const REDIRECT_CLOSE = "<!--/verbaly:redirect-->";
|
|
5018
5306
|
const VOID = new Set(VOID_TAGS);
|
|
5019
5307
|
const START_TAG = /<([a-zA-Z][a-zA-Z0-9-]*)((?:"[^"]*"|'[^']*'|[^"'>])*)>/g;
|
|
5020
|
-
const ATTR = /([^\s=/"'<>]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+)))?/g;
|
|
5021
5308
|
function renderHtml(html, options) {
|
|
5022
5309
|
const attr = options.attribute ?? "data-verbaly";
|
|
5023
5310
|
const argsAttr = `${attr}-args`;
|
|
@@ -5047,34 +5334,36 @@ function renderHtml(html, options) {
|
|
|
5047
5334
|
const tagName = rawName.toLowerCase();
|
|
5048
5335
|
const openEnd = m.index + full.length;
|
|
5049
5336
|
const chunkStart = m.index + 1 + rawName.length;
|
|
5337
|
+
const attrs = readAttributes(attrChunk, true);
|
|
5338
|
+
const read = (name) => attrs.get(name)?.value;
|
|
5339
|
+
const set = (name, value) => setAttribute(ms, html, chunkStart, openEnd, attrs, name, value);
|
|
5050
5340
|
if (tagName === "html" && options.setLang !== false) {
|
|
5051
|
-
|
|
5052
|
-
|
|
5341
|
+
set("lang", options.locale);
|
|
5342
|
+
set("dir", localeDirection(options.locale));
|
|
5053
5343
|
continue;
|
|
5054
5344
|
}
|
|
5055
|
-
|
|
5056
|
-
if (rewriteUrl && tagName === "
|
|
5057
|
-
if (rewriteUrl && tagName === "meta" && attrs.get("property") === "og:url" && sameUrl(decodeEntities(attrs.get("content") ?? ""), sourceUrl)) setAttribute(ms, html, chunkStart, openEnd, attrChunk, "content", selfUrl);
|
|
5345
|
+
if (rewriteUrl && tagName === "link" && read("rel")?.toLowerCase() === "canonical" && sameUrl(decodeEntities(read("href") ?? ""), sourceUrl)) set("href", selfUrl);
|
|
5346
|
+
if (rewriteUrl && tagName === "meta" && read("property") === "og:url" && sameUrl(decodeEntities(read("content") ?? ""), sourceUrl)) set("content", selfUrl);
|
|
5058
5347
|
const mirror = options.mirror;
|
|
5059
5348
|
if (mirror) {
|
|
5060
5349
|
if (tagName === "a" || tagName === "area") {
|
|
5061
|
-
const inside = mirroredHref(
|
|
5062
|
-
if (inside)
|
|
5350
|
+
const inside = mirroredHref(read("href"), mirror);
|
|
5351
|
+
if (inside) set("href", inside);
|
|
5063
5352
|
} else if (tagName === "form" || tagName === "button" || tagName === "input") {
|
|
5064
5353
|
const name = tagName === "form" ? "action" : "formaction";
|
|
5065
|
-
const inside = mirroredHref(
|
|
5066
|
-
if (inside)
|
|
5067
|
-
} else if (tagName === "meta" &&
|
|
5068
|
-
const content =
|
|
5354
|
+
const inside = mirroredHref(read(name), mirror);
|
|
5355
|
+
if (inside) set(name, inside);
|
|
5356
|
+
} else if (tagName === "meta" && read("http-equiv")?.toLowerCase() === "refresh") {
|
|
5357
|
+
const content = read("content") ?? "";
|
|
5069
5358
|
const url = /^([^;]*;\s*url\s*=\s*)(.*)$/i.exec(decodeEntities(content));
|
|
5070
5359
|
const inside = url && mirroredHref(url[2], mirror);
|
|
5071
|
-
if (inside)
|
|
5360
|
+
if (inside) set("content", `${url[1]}${inside}`);
|
|
5072
5361
|
}
|
|
5073
5362
|
}
|
|
5074
|
-
const key =
|
|
5075
|
-
const attrMapRaw =
|
|
5363
|
+
const key = read(attr);
|
|
5364
|
+
const attrMapRaw = read(attrsAttr);
|
|
5076
5365
|
if (key === void 0 && attrMapRaw === void 0) continue;
|
|
5077
|
-
const args = parseArgs
|
|
5366
|
+
const args = parseArgs(read(argsAttr), argsAttr);
|
|
5078
5367
|
if (key) {
|
|
5079
5368
|
if (!v.has(key)) missing.add(key);
|
|
5080
5369
|
else if (!VOID.has(tagName) && !attrChunk.trimEnd().endsWith("/")) {
|
|
@@ -5082,7 +5371,7 @@ function renderHtml(html, options) {
|
|
|
5082
5371
|
const close = findClose(html, tagName, openEnd, inSkip);
|
|
5083
5372
|
if (close) {
|
|
5084
5373
|
const text = t(key, args);
|
|
5085
|
-
const own = parseArgs
|
|
5374
|
+
const own = parseArgs(read(linksAttr), linksAttr);
|
|
5086
5375
|
const merged = own ? globalLinks ? {
|
|
5087
5376
|
...globalLinks,
|
|
5088
5377
|
...own
|
|
@@ -5091,7 +5380,7 @@ function renderHtml(html, options) {
|
|
|
5091
5380
|
const nodes = attrs.has(richAttr) ? parseTags(text) : [];
|
|
5092
5381
|
if (mirror && links) {
|
|
5093
5382
|
const carried = usedLinks(nodes, links);
|
|
5094
|
-
if (carried && JSON.stringify(carried) !== JSON.stringify(own))
|
|
5383
|
+
if (carried && JSON.stringify(carried) !== JSON.stringify(own)) set(linksAttr, JSON.stringify(carried));
|
|
5095
5384
|
}
|
|
5096
5385
|
const content = attrs.has(richAttr) ? richToHtml(nodes, richTags, links) : escapeHtml(text);
|
|
5097
5386
|
if (html.slice(openEnd, close.contentEnd) !== content) {
|
|
@@ -5103,16 +5392,20 @@ function renderHtml(html, options) {
|
|
|
5103
5392
|
}
|
|
5104
5393
|
}
|
|
5105
5394
|
if (attrMapRaw !== void 0) {
|
|
5106
|
-
const map = parseArgs
|
|
5395
|
+
const map = parseArgs(attrMapRaw, attrsAttr);
|
|
5107
5396
|
if (map) for (const [name, attrKey] of Object.entries(map)) {
|
|
5108
5397
|
if (typeof attrKey !== "string") continue;
|
|
5398
|
+
if (!isAttributeName(name)) {
|
|
5399
|
+
warnOnce(`${attrsAttr} names "${name}", which is not an attribute name`);
|
|
5400
|
+
continue;
|
|
5401
|
+
}
|
|
5109
5402
|
if (!v.has(attrKey)) {
|
|
5110
5403
|
missing.add(attrKey);
|
|
5111
5404
|
continue;
|
|
5112
5405
|
}
|
|
5113
5406
|
used.add(attrKey);
|
|
5114
5407
|
const value = safeAttribute(name, t(attrKey, args));
|
|
5115
|
-
if (value !== void 0)
|
|
5408
|
+
if (value !== void 0) set(name, value);
|
|
5116
5409
|
}
|
|
5117
5410
|
}
|
|
5118
5411
|
}
|
|
@@ -5374,14 +5667,7 @@ function buildSitemap(urls) {
|
|
|
5374
5667
|
return alternates.filter((a) => a.hreflang !== "x-default").map((self) => `<url><loc>${escapeAttr(self.href)}</loc>${alts}</url>`);
|
|
5375
5668
|
}).join("")}</urlset>\n`;
|
|
5376
5669
|
}
|
|
5377
|
-
function
|
|
5378
|
-
const attrs = /* @__PURE__ */ new Map();
|
|
5379
|
-
ATTR.lastIndex = 0;
|
|
5380
|
-
let m;
|
|
5381
|
-
while ((m = ATTR.exec(chunk)) !== null) attrs.set(m[1].toLowerCase(), m[2] ?? m[3] ?? m[4] ?? "");
|
|
5382
|
-
return attrs;
|
|
5383
|
-
}
|
|
5384
|
-
function parseArgs$1(raw, attribute) {
|
|
5670
|
+
function parseArgs(raw, attribute) {
|
|
5385
5671
|
if (!raw) return void 0;
|
|
5386
5672
|
try {
|
|
5387
5673
|
return JSON.parse(decodeEntities(raw));
|
|
@@ -5425,17 +5711,18 @@ function findClose(html, tagName, from, inSkip) {
|
|
|
5425
5711
|
}
|
|
5426
5712
|
return null;
|
|
5427
5713
|
}
|
|
5428
|
-
function setAttribute(ms, html, chunkStart, openEnd,
|
|
5429
|
-
const
|
|
5430
|
-
const existing =
|
|
5714
|
+
function setAttribute(ms, html, chunkStart, openEnd, attrs, name, value) {
|
|
5715
|
+
const written = `"${escapeAttr(value)}"`;
|
|
5716
|
+
const existing = attrs.get(name.toLowerCase());
|
|
5431
5717
|
if (existing) {
|
|
5432
|
-
const
|
|
5433
|
-
const
|
|
5434
|
-
if (
|
|
5718
|
+
const from = chunkStart + existing.start;
|
|
5719
|
+
const to = chunkStart + existing.end;
|
|
5720
|
+
if (from === to) ms.appendLeft(from, `=${written}`);
|
|
5721
|
+
else if (html.slice(from, to) !== written) ms.overwrite(from, to, written);
|
|
5435
5722
|
return;
|
|
5436
5723
|
}
|
|
5437
5724
|
const insertAt = openEnd - (html.slice(openEnd - 2, openEnd) === "/>" ? 2 : 1);
|
|
5438
|
-
ms.appendLeft(insertAt, ` ${name}
|
|
5725
|
+
ms.appendLeft(insertAt, ` ${name}=${written}`);
|
|
5439
5726
|
}
|
|
5440
5727
|
function richToHtml(nodes, allowed, links) {
|
|
5441
5728
|
let out = "";
|
|
@@ -5459,9 +5746,6 @@ function escapeHtml(text) {
|
|
|
5459
5746
|
function escapeAttr(text) {
|
|
5460
5747
|
return escapeHtml(text).replace(/"/g, """);
|
|
5461
5748
|
}
|
|
5462
|
-
function decodeEntities(text) {
|
|
5463
|
-
return text.replace(/"/g, "\"").replace(/'/g, "'").replace(/</g, "<").replace(/>/g, ">").replace(/&/g, "&");
|
|
5464
|
-
}
|
|
5465
5749
|
// src/cli/commands/render.ts
|
|
5466
5750
|
async function renderCommand(cfg, values) {
|
|
5467
5751
|
const result = await renderSite(cfg, {
|
|
@@ -5535,19 +5819,14 @@ async function statusCommand(cfg, values) {
|
|
|
5535
5819
|
}
|
|
5536
5820
|
// src/cli/commands/translate.ts
|
|
5537
5821
|
async function translateCommand(cfg, values) {
|
|
5538
|
-
|
|
5539
|
-
const
|
|
5540
|
-
const catalogs = shippedCatalogs(cfg, loadCatalogs(cfg), registry, { newKeys: false });
|
|
5541
|
-
const result = await translateCatalogs(cfg, catalogs, await resolveProvider(cfg, values.model), {
|
|
5822
|
+
const dryRun = values["dry-run"];
|
|
5823
|
+
const result = await translateProject(cfg, {
|
|
5542
5824
|
locales: csv(values.locales),
|
|
5543
|
-
|
|
5544
|
-
|
|
5545
|
-
|
|
5546
|
-
dryRun: values["dry-run"],
|
|
5547
|
-
origins: values["dry-run"] ? void 0 : await collectOrigins(cfg, registry),
|
|
5548
|
-
onProgress: values["dry-run"] ? void 0 : reportProgress
|
|
5825
|
+
dryRun,
|
|
5826
|
+
model: values.model,
|
|
5827
|
+
onProgress: reportProgress
|
|
5549
5828
|
});
|
|
5550
|
-
if (
|
|
5829
|
+
if (dryRun) {
|
|
5551
5830
|
const entries = Object.entries(result.pending);
|
|
5552
5831
|
if (entries.length === 0) {
|
|
5553
5832
|
console.log("[verbaly] nothing to translate ✓");
|
|
@@ -5556,30 +5835,20 @@ async function translateCommand(cfg, values) {
|
|
|
5556
5835
|
for (const [locale, keys] of entries) console.log(` ${locale}: ${keys.length} missing: ${keys.join(", ")}`);
|
|
5557
5836
|
return;
|
|
5558
5837
|
}
|
|
5559
|
-
const
|
|
5560
|
-
const
|
|
5561
|
-
|
|
5562
|
-
|
|
5563
|
-
|
|
5564
|
-
|
|
5565
|
-
locale,
|
|
5566
|
-
draft: true,
|
|
5567
|
-
entries: written.map((key) => ({
|
|
5568
|
-
key,
|
|
5569
|
-
text: catalog[key]
|
|
5570
|
-
}))
|
|
5571
|
-
});
|
|
5572
|
-
console.log(` ${locale}: +${written.length} translated (draft)`);
|
|
5573
|
-
const kept = keys.length - written.length;
|
|
5574
|
-
if (kept > 0) console.log(` ${locale}: ${counted(kept, "message")} kept as written while this ran`);
|
|
5575
|
-
}
|
|
5576
|
-
const lockBefore = stateFile(cfg);
|
|
5577
|
-
if (writes.length > 0) recordTranslations(cfg, source, writes);
|
|
5578
|
-
sayLockNews(cfg, lockBefore);
|
|
5838
|
+
for (const [locale, keys] of Object.entries(result.written)) console.log(` ${locale}: +${keys.length} translated (draft)`);
|
|
5839
|
+
for (const [locale, keys] of Object.entries(result.kept)) console.log(` ${locale}: ${counted(keys.length, "message")} kept as written while this ran`);
|
|
5840
|
+
if (result.lock) console.log(` ${formatFinding({
|
|
5841
|
+
kind: "lock",
|
|
5842
|
+
...result.lock
|
|
5843
|
+
}, cfg.root)}`);
|
|
5579
5844
|
for (const [locale, keys] of Object.entries(result.invalid)) console.warn(` ${locale}: ${keys.length} rejected (params/tags not preserved): ${keys.join(", ")}`);
|
|
5580
5845
|
for (const line of formatTranslateFailures(result.failed)) console.error(line);
|
|
5581
5846
|
if (result.failed.length > 0) process.exitCode = 1;
|
|
5582
|
-
if (
|
|
5847
|
+
if ([
|
|
5848
|
+
result.written,
|
|
5849
|
+
result.kept,
|
|
5850
|
+
result.invalid
|
|
5851
|
+
].every((record) => Object.keys(record).length === 0) && result.failed.length === 0) console.log("[verbaly] nothing to translate ✓");
|
|
5583
5852
|
}
|
|
5584
5853
|
function reportProgress(progress) {
|
|
5585
5854
|
const head = ` ${progress.locale} ${progress.batch}/${progress.batches}`;
|
|
@@ -5616,6 +5885,17 @@ const CODE_TAGS = /* @__PURE__ */ new Set([
|
|
|
5616
5885
|
const T_NAMES = /* @__PURE__ */ new Set(["t"]);
|
|
5617
5886
|
const LETTER = /\p{L}/u;
|
|
5618
5887
|
const WHITESPACE = /\s/;
|
|
5888
|
+
const JSX_ADAPTERS = /* @__PURE__ */ new Set(["@verbaly/react", "@verbaly/vue"]);
|
|
5889
|
+
function jsxAdapters(root) {
|
|
5890
|
+
const named = componentAdapters(root).filter((adapter) => JSX_ADAPTERS.has(adapter));
|
|
5891
|
+
return named.length > 0 ? named : ["@verbaly/react"];
|
|
5892
|
+
}
|
|
5893
|
+
function bindingFor(cfg, adapters, client) {
|
|
5894
|
+
if (cfg.host !== "next") return `in the component: \`const t = useT()\` from ${adapters().join(" or ")}`;
|
|
5895
|
+
const onClient = "`const t = useT()` from @verbaly/next/client";
|
|
5896
|
+
if (client) return `"use client", so ${onClient}`;
|
|
5897
|
+
return `no "use client": a Server Component takes \`const t = await getT()\` from @verbaly/next/server, a client one ${onClient}`;
|
|
5898
|
+
}
|
|
5619
5899
|
async function wrapProject(cfg, options = {}) {
|
|
5620
5900
|
const files = (await glob(cfg.include, {
|
|
5621
5901
|
cwd: cfg.root,
|
|
@@ -5629,6 +5909,8 @@ async function wrapProject(cfg, options = {}) {
|
|
|
5629
5909
|
skipped: [],
|
|
5630
5910
|
blocked: []
|
|
5631
5911
|
};
|
|
5912
|
+
let found;
|
|
5913
|
+
const adapters = () => found ??= jsxAdapters(cfg.root);
|
|
5632
5914
|
for (const file of files) {
|
|
5633
5915
|
const code = readFileSync(file, "utf8");
|
|
5634
5916
|
const label = relative(cfg.root, file).replaceAll("\\", "/");
|
|
@@ -5638,10 +5920,12 @@ async function wrapProject(cfg, options = {}) {
|
|
|
5638
5920
|
if (out.code === void 0) continue;
|
|
5639
5921
|
result.changed.push(label);
|
|
5640
5922
|
if (!out.hasT) {
|
|
5923
|
+
const binding = bindingFor(cfg, adapters, out.client);
|
|
5641
5924
|
result.blocked.push({
|
|
5642
5925
|
file: label,
|
|
5643
5926
|
texts: out.wrapped.length,
|
|
5644
|
-
client: out.client
|
|
5927
|
+
client: out.client,
|
|
5928
|
+
binding
|
|
5645
5929
|
});
|
|
5646
5930
|
continue;
|
|
5647
5931
|
}
|
|
@@ -5667,16 +5951,23 @@ function wrapCode(code, file) {
|
|
|
5667
5951
|
client: false
|
|
5668
5952
|
};
|
|
5669
5953
|
}
|
|
5670
|
-
const
|
|
5954
|
+
const scopes = tScopes(ast);
|
|
5671
5955
|
const client = hasDirective(ast, "use client");
|
|
5672
5956
|
const s = new MagicString(code);
|
|
5673
5957
|
const visited = /* @__PURE__ */ new Set();
|
|
5674
5958
|
let changed = false;
|
|
5959
|
+
let reached = true;
|
|
5960
|
+
const write = (start, end, template) => {
|
|
5961
|
+
s.overwrite(start, end, "{t`" + template + "`}");
|
|
5962
|
+
changed = true;
|
|
5963
|
+
if (!tReaches(scopes, start)) reached = false;
|
|
5964
|
+
};
|
|
5675
5965
|
walk$1(ast, (node) => {
|
|
5676
5966
|
if (node.type !== "JSXElement" && node.type !== "JSXFragment") return;
|
|
5677
5967
|
if (visited.has(node)) return;
|
|
5678
5968
|
processElement(node);
|
|
5679
5969
|
});
|
|
5970
|
+
const hasT = changed ? reached : scopes.some((scope) => scope.bound);
|
|
5680
5971
|
return changed ? {
|
|
5681
5972
|
code: s.toString(),
|
|
5682
5973
|
wrapped,
|
|
@@ -5757,8 +6048,7 @@ function wrapCode(code, file) {
|
|
|
5757
6048
|
if (isIdentifierLike(report)) return;
|
|
5758
6049
|
const start = first.type === "JSXText" ? first.start + leadingWs(first.value) : first.start;
|
|
5759
6050
|
const end = last.type === "JSXText" ? last.end - trailingWs(last.value) : last.end;
|
|
5760
|
-
|
|
5761
|
-
changed = true;
|
|
6051
|
+
write(start, end, template);
|
|
5762
6052
|
wrapped.push({
|
|
5763
6053
|
file,
|
|
5764
6054
|
line: line(first),
|
|
@@ -5775,8 +6065,7 @@ function wrapCode(code, file) {
|
|
|
5775
6065
|
if (value?.type !== "StringLiteral") continue;
|
|
5776
6066
|
const raw = value.value;
|
|
5777
6067
|
if (!LETTER.test(raw) || isIdentifierLike(raw)) continue;
|
|
5778
|
-
|
|
5779
|
-
changed = true;
|
|
6068
|
+
write(value.start, value.end, escapeTemplate(raw));
|
|
5780
6069
|
wrapped.push({
|
|
5781
6070
|
file,
|
|
5782
6071
|
line: line(value),
|
|
@@ -5815,19 +6104,59 @@ function isIdentifierLike(text) {
|
|
|
5815
6104
|
function hasDirective(program, value) {
|
|
5816
6105
|
return (program.directives ?? []).some((d) => d.value?.value === value);
|
|
5817
6106
|
}
|
|
5818
|
-
|
|
5819
|
-
|
|
5820
|
-
|
|
5821
|
-
|
|
5822
|
-
|
|
5823
|
-
|
|
6107
|
+
const CALLS = /* @__PURE__ */ new Set([
|
|
6108
|
+
"CallExpression",
|
|
6109
|
+
"NewExpression",
|
|
6110
|
+
"OptionalCallExpression"
|
|
6111
|
+
]);
|
|
6112
|
+
function tScopes(program) {
|
|
6113
|
+
const scopes = [];
|
|
6114
|
+
const mark = (scope, bound) => {
|
|
6115
|
+
scopes.push({
|
|
6116
|
+
start: scope.start,
|
|
6117
|
+
end: scope.end,
|
|
6118
|
+
bound
|
|
6119
|
+
});
|
|
6120
|
+
};
|
|
6121
|
+
const visit = (node, scope, argument) => {
|
|
6122
|
+
let inner = scope;
|
|
6123
|
+
if (FUNCTIONS.has(node.type)) {
|
|
6124
|
+
inner = node;
|
|
6125
|
+
if (node.type === "FunctionDeclaration" && isTName(node.id?.name)) mark(scope, true);
|
|
6126
|
+
for (const param of node.params ?? []) {
|
|
6127
|
+
if (!bindsT(param)) continue;
|
|
6128
|
+
mark(node, !(argument && namesT(param)));
|
|
6129
|
+
}
|
|
6130
|
+
} else if (node.type === "ImportDeclaration") {
|
|
6131
|
+
if (node.specifiers.map((spec) => spec.local).some((local) => isTName(local?.name))) mark(program, true);
|
|
5824
6132
|
return;
|
|
6133
|
+
} else if (node.type === "VariableDeclarator" && bindsT(node.id)) mark(scope, true);
|
|
6134
|
+
const args = CALLS.has(node.type) ? node.arguments : void 0;
|
|
6135
|
+
for (const key in node) {
|
|
6136
|
+
if (key === "loc" || key.endsWith("Comments") || key === "extra") continue;
|
|
6137
|
+
const value = node[key];
|
|
6138
|
+
for (const child of Array.isArray(value) ? value : [value]) if (isAstNode(child)) visit(child, inner, args?.includes(child) ?? false);
|
|
5825
6139
|
}
|
|
5826
|
-
|
|
5827
|
-
|
|
5828
|
-
|
|
5829
|
-
|
|
5830
|
-
|
|
6140
|
+
};
|
|
6141
|
+
visit(program, program, false);
|
|
6142
|
+
return scopes;
|
|
6143
|
+
}
|
|
6144
|
+
function tReaches(scopes, position) {
|
|
6145
|
+
let nearest;
|
|
6146
|
+
for (const scope of scopes) {
|
|
6147
|
+
if (position < scope.start || position >= scope.end) continue;
|
|
6148
|
+
const size = scope.end - scope.start;
|
|
6149
|
+
const best = nearest ? nearest.end - nearest.start : Infinity;
|
|
6150
|
+
if (size < best || size === best && scope.bound) nearest = scope;
|
|
6151
|
+
}
|
|
6152
|
+
return nearest?.bound ?? false;
|
|
6153
|
+
}
|
|
6154
|
+
function isAstNode(value) {
|
|
6155
|
+
return typeof value?.type === "string";
|
|
6156
|
+
}
|
|
6157
|
+
function namesT(param) {
|
|
6158
|
+
const target = param.type === "AssignmentPattern" ? param.left : param;
|
|
6159
|
+
return target.type === "Identifier" && isTName(target.name);
|
|
5831
6160
|
}
|
|
5832
6161
|
function bindsT(pattern) {
|
|
5833
6162
|
if (!pattern) return false;
|
|
@@ -5874,41 +6203,46 @@ function trailingWs(text) {
|
|
|
5874
6203
|
function line(node) {
|
|
5875
6204
|
return node.loc?.start?.line ?? 1;
|
|
5876
6205
|
}
|
|
5877
|
-
|
|
5878
|
-
function binding(cfg, client) {
|
|
5879
|
-
if (cfg.host !== "next") return "in the component: `const t = useT()` from @verbaly/react";
|
|
5880
|
-
const onClient = "`const t = useT()` from @verbaly/next/client";
|
|
5881
|
-
if (client) return `"use client", so ${onClient}`;
|
|
5882
|
-
return `no "use client": a Server Component takes \`const t = await getT()\` from @verbaly/next/server, a client one ${onClient}`;
|
|
5883
|
-
}
|
|
5884
|
-
async function wrapCommand(cfg, values) {
|
|
5885
|
-
const result = await wrapProject(cfg, { write: values.write });
|
|
5886
|
-
if (result.wrapped.length === 0 && result.skipped.length === 0) {
|
|
5887
|
-
console.log(`[verbaly] nothing to wrap (${counted(result.files, "file")} scanned) ✓`);
|
|
5888
|
-
return;
|
|
5889
|
-
}
|
|
6206
|
+
function formatWrapResult(result, write) {
|
|
5890
6207
|
const blocked = new Set(result.blocked.map((entry) => entry.file));
|
|
5891
6208
|
const done = result.changed.filter((file) => !blocked.has(file));
|
|
5892
6209
|
const texts = result.wrapped.filter((entry) => !blocked.has(entry.file));
|
|
5893
|
-
|
|
5894
|
-
const note = values.write ? "" : " (report only, use --write to apply)";
|
|
5895
|
-
let counts = `${counted(texts.length, "text")} in ${counted(done.length, "file")}`;
|
|
6210
|
+
let counts = `${write ? "wrapped" : "would wrap"} ${counted(texts.length, "text")} in ${counted(done.length, "file")}`;
|
|
5896
6211
|
const waiting = result.wrapped.length - texts.length;
|
|
5897
|
-
if (!
|
|
5898
|
-
|
|
5899
|
-
for (const entry of
|
|
6212
|
+
if (!write && waiting > 0) counts += `, and ${counted(waiting, "text")} in ${counted(blocked.size, "file")} once t is in scope`;
|
|
6213
|
+
const lines = [];
|
|
6214
|
+
for (const entry of write ? texts : result.wrapped) {
|
|
5900
6215
|
const attr = entry.kind === "attribute" ? `${entry.attribute} → ` : "";
|
|
5901
|
-
|
|
6216
|
+
lines.push(` ${entry.file}:${entry.line} ${attr}"${entry.text}"`);
|
|
5902
6217
|
}
|
|
5903
6218
|
if (result.skipped.length > 0) {
|
|
5904
|
-
|
|
5905
|
-
for (const entry of result.skipped)
|
|
6219
|
+
lines.push(" needs a human:");
|
|
6220
|
+
for (const entry of result.skipped) lines.push(` ${entry.file}:${entry.line} "${entry.text}" (${entry.reason})`);
|
|
5906
6221
|
}
|
|
5907
6222
|
if (result.blocked.length > 0) {
|
|
5908
|
-
|
|
5909
|
-
for (const entry of result.blocked)
|
|
5910
|
-
|
|
5911
|
-
|
|
6223
|
+
lines.push(` nothing written in ${counted(result.blocked.length, "file")} with no t in scope:`);
|
|
6224
|
+
for (const entry of result.blocked) lines.push(` ${entry.file} ${counted(entry.texts, "text")}, ${entry.binding}`);
|
|
6225
|
+
}
|
|
6226
|
+
return {
|
|
6227
|
+
counts,
|
|
6228
|
+
lines,
|
|
6229
|
+
files: done.length
|
|
6230
|
+
};
|
|
6231
|
+
}
|
|
6232
|
+
// src/cli/commands/wrap.ts
|
|
6233
|
+
async function wrapCommand(cfg, values) {
|
|
6234
|
+
const write = values.write === true;
|
|
6235
|
+
const result = await wrapProject(cfg, { write });
|
|
6236
|
+
if (result.wrapped.length === 0 && result.skipped.length === 0) {
|
|
6237
|
+
console.log(`[verbaly] nothing to wrap (${counted(result.files, "file")} scanned) ✓`);
|
|
6238
|
+
return;
|
|
6239
|
+
}
|
|
6240
|
+
const report = formatWrapResult(result, write);
|
|
6241
|
+
const note = write ? "" : " (report only, use --write to apply)";
|
|
6242
|
+
console.log(`[verbaly] ${report.counts}${note}`);
|
|
6243
|
+
for (const line of report.lines) console.log(line);
|
|
6244
|
+
if (result.blocked.length > 0) console.log(" next: add t there, run verbaly wrap --write again, then verbaly extract");
|
|
6245
|
+
else if (write && report.files > 0) console.log(" next: run verbaly extract");
|
|
5912
6246
|
}
|
|
5913
6247
|
// src/cli/run.ts
|
|
5914
6248
|
const HELP = `verbaly · i18n compiler
|
|
@@ -5987,14 +6321,38 @@ async function runCli(args = process.argv.slice(2)) {
|
|
|
5987
6321
|
}
|
|
5988
6322
|
if (rejectStrayFlags(command, values)) return;
|
|
5989
6323
|
if (command === "init") return initCommand(values);
|
|
5990
|
-
|
|
6324
|
+
if (!Object.hasOwn(COMMANDS, command)) {
|
|
6325
|
+
console.error(`[verbaly] unknown command "${command}"\n${HELP}`);
|
|
6326
|
+
process.exitCode = 1;
|
|
6327
|
+
return;
|
|
6328
|
+
}
|
|
6329
|
+
const root = values.root ?? process.cwd();
|
|
6330
|
+
const project = {
|
|
5991
6331
|
dir: values.dir,
|
|
5992
|
-
sourceLocale: values.source
|
|
5993
|
-
|
|
6332
|
+
sourceLocale: values.source
|
|
6333
|
+
};
|
|
6334
|
+
const narrowed = csv(values.locales);
|
|
6335
|
+
if (narrowed || command === "review" && values.locale) {
|
|
6336
|
+
const whole = await loadConfig(root, project);
|
|
6337
|
+
const typo = narrowed ? strangers(whole, "locales", narrowed) : strangers(whole, "locale", [values.locale]);
|
|
6338
|
+
if (typo) {
|
|
6339
|
+
console.error(typo);
|
|
6340
|
+
process.exitCode = 1;
|
|
6341
|
+
return;
|
|
6342
|
+
}
|
|
6343
|
+
}
|
|
6344
|
+
const cfg = await loadConfig(root, {
|
|
6345
|
+
...project,
|
|
6346
|
+
locales: narrowed
|
|
5994
6347
|
});
|
|
5995
|
-
|
|
5996
|
-
|
|
5997
|
-
|
|
6348
|
+
return COMMANDS[command](cfg, values, positionals);
|
|
6349
|
+
}
|
|
6350
|
+
function strangers(cfg, flag, named) {
|
|
6351
|
+
const unknown = named.filter((locale) => !cfg.locales.includes(locale));
|
|
6352
|
+
if (unknown.length === 0) return void 0;
|
|
6353
|
+
const dir = relative(cfg.root, cfg.dir).replaceAll("\\", "/");
|
|
6354
|
+
const start = cfg.localesDeclared ? `add ${unknown.join(", ")} to locales in your verbaly config` : `create ${unknown.map((locale) => `${dir}/${locale}.json`).join(", ")} holding {}`;
|
|
6355
|
+
return `[verbaly] --${flag} names ${unknown.map((locale) => `"${locale}"`).join(", ")}, and this project has ${cfg.locales.join(", ")}\n fix: check the spelling, or ${start} to start a new language`;
|
|
5998
6356
|
}
|
|
5999
6357
|
function formatCliError(error) {
|
|
6000
6358
|
const message = error instanceof Error ? error.message : String(error);
|
|
@@ -6057,4 +6415,4 @@ function rejectStrayFlags(command, values) {
|
|
|
6057
6415
|
process.exitCode = 1;
|
|
6058
6416
|
return true;
|
|
6059
6417
|
}
|
|
6060
|
-
export {
|
|
6418
|
+
export { generateLocaleModule as $, relativeCheck as A, formatCollision as B, runBuildGate as C, resolveConfig as Ct, check as D, transformCode as E, translateCatalogs as F, loadState as G, STATE_FILE as H, writeDrafts as I, readState as J, markDrafts as K, syncProject as L, formatTranslateFailures as M, mergeTranslations as N, formatCheckResult as O, resolveProvider as P, generateDts as Q, collisionEntries as R, resolveVirtualId as S, loadConfig as St, writeBuildTypes as T, clearDrafts as U, formatFinding as V, effectiveDrafts as W, saveState as X, recordTranslations as Y, updateState as Z, SOURCE_FILE_RE as _, needsRelative as _t, formatRenderWarnings as a, extractProject as at, isTransformTarget as b, writeCatalog as bt, watchTree as c, syncCatalogs as ct, formatDoctorHealth as d, LOCALE_IMPORT as dt, generateRuntimeModule as et, formatStatusResult as f, MessageRegistry as ft, RESOLVED_VIRTUAL_ID as g, needsIcu as gt, LOCALE_MODULE_PREFIX as h, loadCatalogs as ht, wrapProject as i, collectOrigins as it, translateProject as j, formatCheckWarnings as k, doctor as l, stableKey as lt, reportOutsideInclude as m, counted as mt, runCli as n, validateMessage as nt, renderSite as o, pruneCatalogs as ot, status as p, clientCatalogs as pt, outdatedTranslations as q, formatWrapResult as r, validatePair as rt, init as s, shippedCatalogs as st, formatCliError as t, writeDts as tt, formatDoctorEntry as u, APP_ID as ut, clientModules as v, parseCatalog as vt, transformSource as w, targetLocales as wt, loadVirtualModule as x, isModuleNotFound as xt, createSourceFilter as y, readCatalog as yt, createDevReporter as z };
|