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