@verbaly/compiler 0.67.0 → 0.69.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +47 -13
- package/dist/{claude-BmD8W9uW.js → claude-DmnZ1cvR.js} +2 -2
- package/dist/{claude-BmD8W9uW.js.map → claude-DmnZ1cvR.js.map} +1 -1
- package/dist/{claude-D-j-ZiYH.js → claude-mvcniUPN.js} +2 -2
- package/dist/{claude-D-j-ZiYH.js.map → claude-mvcniUPN.js.map} +1 -1
- package/dist/cli.js +2228 -1643
- package/dist/cli.js.map +1 -1
- package/dist/index.d.ts +212 -102
- package/dist/index.js +869 -426
- package/dist/index.js.map +1 -1
- package/dist/text-Bh96y7ik.js +240 -0
- package/dist/text-Bh96y7ik.js.map +1 -0
- package/package.json +5 -4
- package/dist/text-M4XbWU6N.js +0 -98
- package/dist/text-M4XbWU6N.js.map +0 -1
package/dist/index.js
CHANGED
|
@@ -1,12 +1,19 @@
|
|
|
1
|
-
import { a as loadConfigFile, i as
|
|
1
|
+
import { a as findConfigFile, c as loadConfigFile, d as WIRING_PACKAGES, f as detectHost, i as SOURCE_EXTENSIONS, l as resolveConfig, m as readDependencies, n as counted, p as installCommand, r as truncate, s as loadConfig, t as byCodeUnit, u as targetLocales } from "./text-Bh96y7ik.js";
|
|
2
2
|
import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, rmSync, watch, writeFileSync } from "node:fs";
|
|
3
|
-
import { dirname, join, relative } from "node:path";
|
|
3
|
+
import { dirname, join, relative, resolve, sep } from "node:path";
|
|
4
4
|
import { CATALOG_SCRIPT, LOCALE_STORAGE_KEY, RICH_TAGS, VOID_TAGS, alternateLinks, createVerbaly, flatten, localeDirection, normalizeLink, parse, parseIcu, parseTags, safeAttribute } from "verbaly";
|
|
5
5
|
import { glob } from "tinyglobby";
|
|
6
6
|
import { parse as parse$1 } from "@babel/parser";
|
|
7
7
|
import { createHash } from "node:crypto";
|
|
8
|
+
import { applyEdits, modify, parse as parse$2 } from "jsonc-parser";
|
|
8
9
|
import picomatch from "picomatch";
|
|
9
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
|
|
10
17
|
//#region src/catalog.ts
|
|
11
18
|
function emptyCatalog() {
|
|
12
19
|
return Object.create(null);
|
|
@@ -130,7 +137,7 @@ function writeCatalog(cfg, locale, catalog) {
|
|
|
130
137
|
}
|
|
131
138
|
const parsed = existing === void 0 ? void 0 : parseTree(existing);
|
|
132
139
|
const previous = isTree(parsed) ? parsed : void 0;
|
|
133
|
-
const serialized = serializeCatalog(catalog, wantsNesting(cfg, locale, existing, previous), previous);
|
|
140
|
+
const serialized = withLineEndings(serializeCatalog(catalog, wantsNesting(cfg, locale, existing, previous), previous), existing);
|
|
134
141
|
if (existing === serialized) return serialized;
|
|
135
142
|
writeFileSync(path, serialized);
|
|
136
143
|
return serialized;
|
|
@@ -206,25 +213,28 @@ var MessageRegistry = class {
|
|
|
206
213
|
}
|
|
207
214
|
messages() {
|
|
208
215
|
const out = /* @__PURE__ */ new Map();
|
|
209
|
-
for (const analysis of this.
|
|
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
|
+
}
|
|
210
220
|
return out;
|
|
211
221
|
}
|
|
212
222
|
collisions() {
|
|
213
|
-
const
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
if (
|
|
217
|
-
|
|
218
|
-
kept: msg,
|
|
219
|
-
dropped: []
|
|
220
|
-
});
|
|
221
|
-
else if (msg.message !== found.kept.message && !found.dropped.some((other) => other.message === msg.message)) found.dropped.push(msg);
|
|
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]);
|
|
222
228
|
}
|
|
223
|
-
return [...
|
|
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
|
+
}));
|
|
224
234
|
}
|
|
225
235
|
usedKeys(strict = false) {
|
|
226
236
|
const out = /* @__PURE__ */ new Map();
|
|
227
|
-
for (const analysis of this.
|
|
237
|
+
for (const analysis of this.inOrder()) for (const used of analysis.usedKeys) {
|
|
228
238
|
if (strict && used.loose) continue;
|
|
229
239
|
const files = out.get(used.key) ?? [];
|
|
230
240
|
if (!files.includes(used.file)) files.push(used.file);
|
|
@@ -233,29 +243,38 @@ var MessageRegistry = class {
|
|
|
233
243
|
return out;
|
|
234
244
|
}
|
|
235
245
|
strayImports() {
|
|
236
|
-
return
|
|
246
|
+
return this.inOrder().flatMap((analysis) => analysis.strayImports);
|
|
237
247
|
}
|
|
238
248
|
missed() {
|
|
239
|
-
return
|
|
249
|
+
return this.inOrder().flatMap((analysis) => analysis.missed);
|
|
240
250
|
}
|
|
241
251
|
parseErrors() {
|
|
242
252
|
const out = [];
|
|
243
|
-
for (const
|
|
244
|
-
file
|
|
245
|
-
|
|
246
|
-
|
|
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
|
+
}
|
|
247
260
|
return out;
|
|
248
261
|
}
|
|
249
262
|
origins() {
|
|
250
263
|
const out = this.usedKeys();
|
|
251
|
-
for (const analysis of this.
|
|
264
|
+
for (const analysis of this.inOrder()) for (const msg of analysis.tagged) {
|
|
252
265
|
const files = out.get(msg.key) ?? [];
|
|
253
266
|
if (!files.includes(msg.file)) files.push(msg.file);
|
|
254
267
|
out.set(msg.key, files);
|
|
255
268
|
}
|
|
256
269
|
return out;
|
|
257
270
|
}
|
|
271
|
+
inOrder() {
|
|
272
|
+
return [...this.files.keys()].sort().map((file) => this.files.get(file));
|
|
273
|
+
}
|
|
258
274
|
};
|
|
275
|
+
function earlier(a, b) {
|
|
276
|
+
return a.file === b.file ? a.start < b.start : a.file < b.file;
|
|
277
|
+
}
|
|
259
278
|
//#endregion
|
|
260
279
|
//#region src/key.ts
|
|
261
280
|
function stableKey(message) {
|
|
@@ -277,6 +296,9 @@ const DEFAULT_T_NAMES = ["t"];
|
|
|
277
296
|
const JSX_FILE_RE = /\.(?:[cm]?jsx?|tsx)$/;
|
|
278
297
|
const DEFINE_KEYS = "defineKeys";
|
|
279
298
|
function analyze(code, file, options = {}) {
|
|
299
|
+
return analyzeScript(code, file, options).analysis;
|
|
300
|
+
}
|
|
301
|
+
function analyzeScript(code, file, options = {}) {
|
|
280
302
|
const names = new Set(options.tNames ?? DEFAULT_T_NAMES);
|
|
281
303
|
const ast = parse$1(code, {
|
|
282
304
|
sourceType: "module",
|
|
@@ -286,19 +308,20 @@ function analyze(code, file, options = {}) {
|
|
|
286
308
|
const tagged = [];
|
|
287
309
|
const usedKeys = [];
|
|
288
310
|
const strayImports = [];
|
|
289
|
-
const
|
|
290
|
-
const
|
|
311
|
+
const bindings = new Bindings(names);
|
|
312
|
+
const candidates = [];
|
|
291
313
|
walk$1(ast.program, (node) => {
|
|
292
|
-
if (node.type === "ImportDeclaration")
|
|
314
|
+
if (node.type === "ImportDeclaration") {
|
|
315
|
+
collectStrayImports(node, file, strayImports);
|
|
316
|
+
bindings.addImport(node);
|
|
317
|
+
} else if (node.type === "VariableDeclarator") bindings.addDeclarator(node);
|
|
293
318
|
else if (node.type === "TaggedTemplateExpression") {
|
|
294
319
|
const tag = node.tag;
|
|
295
320
|
const explicit = explicitId(tag, names);
|
|
296
321
|
if (!explicit && !isTReference(tag, names)) {
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
file,
|
|
301
|
-
start: node.start
|
|
322
|
+
candidates.push({
|
|
323
|
+
kind: "tag",
|
|
324
|
+
node
|
|
302
325
|
});
|
|
303
326
|
return;
|
|
304
327
|
}
|
|
@@ -311,6 +334,7 @@ function analyze(code, file, options = {}) {
|
|
|
311
334
|
params: message.params,
|
|
312
335
|
start: node.start,
|
|
313
336
|
end: node.end,
|
|
337
|
+
line: lineOf(node),
|
|
314
338
|
tagStart: explicit ? explicit.refStart : tag.start,
|
|
315
339
|
tagEnd: explicit ? explicit.refEnd : tag.end,
|
|
316
340
|
file
|
|
@@ -323,11 +347,11 @@ function analyze(code, file, options = {}) {
|
|
|
323
347
|
return;
|
|
324
348
|
}
|
|
325
349
|
if (!isTReference(callee, names)) {
|
|
326
|
-
const key =
|
|
327
|
-
if (key !== void 0)
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
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
|
|
331
355
|
});
|
|
332
356
|
return;
|
|
333
357
|
}
|
|
@@ -335,41 +359,136 @@ function analyze(code, file, options = {}) {
|
|
|
335
359
|
if (key !== void 0) usedKeys.push(usedKey(key, file, args[0]));
|
|
336
360
|
} else if (node.type === "JSXElement") handleTrans(code, node, file, tagged, usedKeys, names);
|
|
337
361
|
});
|
|
362
|
+
const renamed = bindings.renamed(options.renamed);
|
|
363
|
+
const missed = [];
|
|
364
|
+
for (const candidate of candidates) {
|
|
365
|
+
if (candidate.kind === "call") {
|
|
366
|
+
if (renamed.has(candidate.name)) usedKeys.push({
|
|
367
|
+
key: candidate.key,
|
|
368
|
+
file,
|
|
369
|
+
loose: true
|
|
370
|
+
});
|
|
371
|
+
continue;
|
|
372
|
+
}
|
|
373
|
+
const { node } = candidate;
|
|
374
|
+
const name = renamedTag(node.tag, renamed);
|
|
375
|
+
if (!name) continue;
|
|
376
|
+
missed.push({
|
|
377
|
+
name,
|
|
378
|
+
file,
|
|
379
|
+
start: node.start,
|
|
380
|
+
line: lineOf(node)
|
|
381
|
+
});
|
|
382
|
+
const key = missedKey(code, node, names);
|
|
383
|
+
if (key !== void 0) usedKeys.push({
|
|
384
|
+
key,
|
|
385
|
+
file,
|
|
386
|
+
loose: true
|
|
387
|
+
});
|
|
388
|
+
}
|
|
338
389
|
return {
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
390
|
+
analysis: {
|
|
391
|
+
tagged,
|
|
392
|
+
usedKeys,
|
|
393
|
+
strayImports,
|
|
394
|
+
missed
|
|
395
|
+
},
|
|
396
|
+
renamed: [...renamed]
|
|
343
397
|
};
|
|
344
398
|
}
|
|
345
|
-
function
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
399
|
+
function lineOf(node) {
|
|
400
|
+
return node.loc?.start.line ?? 1;
|
|
401
|
+
}
|
|
402
|
+
const VERBALY_SOURCE = /^(?:verbaly|virtual:verbaly|@verbaly\/[\w-]+(?:\/[\w-]+)*)$/;
|
|
403
|
+
const T_FACTORIES = /* @__PURE__ */ new Map([["useT", "call"], ["getT", "await"]]);
|
|
404
|
+
const INSTANCE_FACTORIES = /* @__PURE__ */ new Set(["useVerbaly", "getVerbaly"]);
|
|
405
|
+
var Bindings = class {
|
|
406
|
+
names;
|
|
407
|
+
imports = /* @__PURE__ */ new Map();
|
|
408
|
+
direct = /* @__PURE__ */ new Set();
|
|
409
|
+
declared = [];
|
|
410
|
+
destructured = [];
|
|
411
|
+
constructor(names) {
|
|
412
|
+
this.names = names;
|
|
413
|
+
}
|
|
414
|
+
addImport(node) {
|
|
415
|
+
const source = node.source.value;
|
|
416
|
+
if (typeof source !== "string") return;
|
|
417
|
+
for (const spec of node.specifiers) {
|
|
418
|
+
const local = identifierName(spec.local);
|
|
419
|
+
if (!local) continue;
|
|
420
|
+
const imported = spec.type === "ImportSpecifier" ? importedName(spec.imported) : spec.type;
|
|
421
|
+
this.imports.set(local, {
|
|
422
|
+
source,
|
|
423
|
+
imported
|
|
424
|
+
});
|
|
425
|
+
if (source === "virtual:verbaly" && imported === "t") this.direct.add(local);
|
|
364
426
|
}
|
|
365
|
-
}
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
427
|
+
}
|
|
428
|
+
addDeclarator(node) {
|
|
429
|
+
const id = node.id;
|
|
430
|
+
const init = node.init;
|
|
431
|
+
if (!init) return;
|
|
432
|
+
if (id.type === "Identifier") {
|
|
433
|
+
this.declared.push({
|
|
434
|
+
name: id.name,
|
|
435
|
+
init
|
|
436
|
+
});
|
|
437
|
+
return;
|
|
438
|
+
}
|
|
439
|
+
if (id.type !== "ObjectPattern") return;
|
|
440
|
+
for (const property of id.properties) {
|
|
441
|
+
if (property.type !== "ObjectProperty" || property.computed) continue;
|
|
442
|
+
if (identifierName(property.key) !== "t") continue;
|
|
443
|
+
const value = property.value;
|
|
444
|
+
const name = identifierName(value.type === "AssignmentPattern" ? value.left : value);
|
|
445
|
+
if (name) this.destructured.push({
|
|
446
|
+
name,
|
|
447
|
+
init
|
|
448
|
+
});
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
renamed(seed = []) {
|
|
452
|
+
const out = new Set(seed);
|
|
453
|
+
const add = (name) => {
|
|
454
|
+
if (this.names.has(name)) return;
|
|
455
|
+
out.add(name);
|
|
456
|
+
if (this.names.has("$t")) out.add(`$${name}`);
|
|
457
|
+
};
|
|
458
|
+
for (const name of this.direct) add(name);
|
|
459
|
+
for (const { name, init } of this.declared) if (this.handsOutT(init)) add(name);
|
|
460
|
+
for (const { name, init } of this.destructured) if (this.carriesT(init)) add(name);
|
|
461
|
+
return out;
|
|
462
|
+
}
|
|
463
|
+
handsOutT(init) {
|
|
464
|
+
const awaited = init.type === "AwaitExpression";
|
|
465
|
+
const call = awaited ? init.argument : init;
|
|
466
|
+
if (call.type !== "CallExpression") return false;
|
|
467
|
+
const origin = this.origin(identifierName(call.callee));
|
|
468
|
+
if (origin.verbaly === false) return false;
|
|
469
|
+
const how = T_FACTORIES.get(origin.imported);
|
|
470
|
+
return how !== void 0 && how === "await" === awaited;
|
|
471
|
+
}
|
|
472
|
+
carriesT(init) {
|
|
473
|
+
const inner = init.type === "AwaitExpression" ? init.argument : init;
|
|
474
|
+
const name = identifierName(inner.type === "CallExpression" ? inner.callee : inner);
|
|
475
|
+
if (!name) return false;
|
|
476
|
+
return this.origin(name).verbaly ?? INSTANCE_FACTORIES.has(name);
|
|
477
|
+
}
|
|
478
|
+
origin(local) {
|
|
479
|
+
const found = this.imports.get(local);
|
|
480
|
+
if (!found) return {
|
|
481
|
+
verbaly: void 0,
|
|
482
|
+
imported: local
|
|
483
|
+
};
|
|
484
|
+
return {
|
|
485
|
+
verbaly: VERBALY_SOURCE.test(found.source),
|
|
486
|
+
imported: found.imported
|
|
487
|
+
};
|
|
488
|
+
}
|
|
489
|
+
};
|
|
490
|
+
function importedName(node) {
|
|
491
|
+
return node.type === "StringLiteral" ? node.value : identifierName(node);
|
|
373
492
|
}
|
|
374
493
|
function identifierName(node) {
|
|
375
494
|
return node?.type === "Identifier" ? node.name : "";
|
|
@@ -385,6 +504,16 @@ function renamedTag(tag, renamed) {
|
|
|
385
504
|
const object = identifierName(callee.object);
|
|
386
505
|
return renamed.has(object) ? object : void 0;
|
|
387
506
|
}
|
|
507
|
+
function missedKey(code, node, names) {
|
|
508
|
+
const tag = node.tag;
|
|
509
|
+
if (tag.type === "CallExpression") {
|
|
510
|
+
const args = tag.arguments;
|
|
511
|
+
const first = args[0];
|
|
512
|
+
return args.length === 1 && first?.type === "StringLiteral" ? first.value : void 0;
|
|
513
|
+
}
|
|
514
|
+
const message = buildMessage(code, node.quasi, names);
|
|
515
|
+
return message ? stableKey(message.text) : void 0;
|
|
516
|
+
}
|
|
388
517
|
function collectDeclaredKeys(node, file, out) {
|
|
389
518
|
if (node?.type !== "ObjectExpression") return;
|
|
390
519
|
for (const property of node.properties) {
|
|
@@ -441,6 +570,7 @@ function handleTrans(code, node, file, tagged, usedKeys, names) {
|
|
|
441
570
|
params: built.params,
|
|
442
571
|
start: node.start,
|
|
443
572
|
end: node.end,
|
|
573
|
+
line: lineOf(node),
|
|
444
574
|
tagStart: nameNode.start,
|
|
445
575
|
tagEnd: nameNode.end,
|
|
446
576
|
file,
|
|
@@ -646,6 +776,7 @@ function analyzeFile(code, file) {
|
|
|
646
776
|
tagged: [],
|
|
647
777
|
usedKeys: [],
|
|
648
778
|
strayImports: [],
|
|
779
|
+
missed: [],
|
|
649
780
|
parseError: parseErrorMessage(error)
|
|
650
781
|
};
|
|
651
782
|
}
|
|
@@ -654,55 +785,63 @@ const SCRIPT_RE = /(<script\b[^>]*>)([\s\S]*?)(<\/script\s*>)/gi;
|
|
|
654
785
|
const STYLE_RE = /<style\b[^>]*>[\s\S]*?<\/style\s*>/gi;
|
|
655
786
|
const COMMENT_RE = /<!--[\s\S]*?-->/g;
|
|
656
787
|
const FRONTMATTER_RE = /^(\uFEFF?\s*---\r?\n)([\s\S]*?)\r?\n---(?=\r?\n|$)/;
|
|
657
|
-
const CANDIDATE_SVELTE = /(?<![\w$])\$?t(?=[`(]|\.id\()/g;
|
|
658
|
-
const CANDIDATE_VUE = /(?<![\w$])t(?=[`(]|\.id\()/g;
|
|
659
788
|
const MUSTACHE_RE = /\{\{[\s\S]*?\}\}/g;
|
|
660
789
|
const DIRECTIVE_RE = /\s(?:v-[\w-]+(?::[^\s=>/]+)?|[:@][^\s=>/]+)\s*=\s*("[^"]*"|'[^']*')/g;
|
|
661
790
|
function analyzeSfc(code, file) {
|
|
662
791
|
const svelte = file.endsWith(".svelte");
|
|
663
|
-
const
|
|
792
|
+
const tNames = svelte ? ["t", "$t"] : ["t"];
|
|
664
793
|
const tagged = [];
|
|
665
794
|
const usedKeys = [];
|
|
666
795
|
const strayImports = [];
|
|
796
|
+
const missed = [];
|
|
797
|
+
const renamed = /* @__PURE__ */ new Set();
|
|
798
|
+
const lineAt = lineCounter(code);
|
|
667
799
|
let parseError;
|
|
668
|
-
const block = (
|
|
800
|
+
const block = (content, offset) => {
|
|
801
|
+
const segment = analyzeSegment(content, file, { tNames });
|
|
669
802
|
parseError ??= segment.error;
|
|
803
|
+
for (const name of segment.renamed) renamed.add(name);
|
|
670
804
|
merge(segment.analysis, offset, false);
|
|
671
805
|
};
|
|
672
806
|
const frontmatter = file.endsWith(".astro") ? FRONTMATTER_RE.exec(code) : null;
|
|
673
|
-
if (frontmatter?.[2]) block(
|
|
807
|
+
if (frontmatter?.[2]) block(frontmatter[2], frontmatter[1].length);
|
|
674
808
|
for (const match of code.matchAll(SCRIPT_RE)) {
|
|
675
809
|
const content = match[2];
|
|
676
|
-
if (
|
|
677
|
-
block(analyzeSegment(content, file, options), match.index + match[1].length);
|
|
810
|
+
if (content) block(content, match.index + match[1].length);
|
|
678
811
|
}
|
|
679
812
|
const markup = blank(blank(blank(frontmatter ? " ".repeat(frontmatter[0].length) + code.slice(frontmatter[0].length) : code, SCRIPT_RE), STYLE_RE), COMMENT_RE);
|
|
680
|
-
const
|
|
813
|
+
const markupOptions = {
|
|
814
|
+
tNames,
|
|
815
|
+
renamed: [...renamed]
|
|
816
|
+
};
|
|
681
817
|
const ranges = file.endsWith(".vue") ? vueExpressionRanges(markup) : braceRanges(markup);
|
|
682
818
|
let range = 0;
|
|
683
819
|
let consumedTo = 0;
|
|
684
|
-
for (const match of markup.matchAll(
|
|
820
|
+
for (const match of markup.matchAll(candidatePattern(svelte, renamed))) {
|
|
685
821
|
const start = match.index;
|
|
686
822
|
if (start < consumedTo) continue;
|
|
687
823
|
while (range < ranges.length && ranges[range][1] <= start) range += 1;
|
|
688
824
|
if (range >= ranges.length || start < ranges[range][0]) continue;
|
|
689
|
-
const end = expressionExtent(markup, start);
|
|
825
|
+
const end = expressionExtent(markup, start, match[0].length);
|
|
690
826
|
if (end === void 0) continue;
|
|
691
|
-
merge(analyzeSegment(code.slice(start, end), file,
|
|
827
|
+
merge(analyzeSegment(code.slice(start, end), file, markupOptions).analysis, start, true);
|
|
692
828
|
consumedTo = end;
|
|
693
829
|
}
|
|
694
830
|
return {
|
|
695
831
|
tagged,
|
|
696
832
|
usedKeys,
|
|
697
833
|
strayImports,
|
|
834
|
+
missed,
|
|
698
835
|
...parseError && { parseError }
|
|
699
836
|
};
|
|
700
837
|
function merge(analysis, offset, markupSegment) {
|
|
701
838
|
if (!analysis) return;
|
|
839
|
+
const lines = lineAt(offset) - 1;
|
|
702
840
|
for (const msg of analysis.tagged) tagged.push({
|
|
703
841
|
...msg,
|
|
704
842
|
start: msg.start + offset,
|
|
705
843
|
end: msg.end + offset,
|
|
844
|
+
line: msg.line + lines,
|
|
706
845
|
tagStart: msg.tagStart + offset,
|
|
707
846
|
tagEnd: msg.tagEnd + offset,
|
|
708
847
|
params: msg.params.map((p) => ({
|
|
@@ -712,15 +851,41 @@ function analyzeSfc(code, file) {
|
|
|
712
851
|
})),
|
|
713
852
|
...markupSegment && { singleQuote: true }
|
|
714
853
|
});
|
|
854
|
+
for (const call of analysis.missed) missed.push({
|
|
855
|
+
...call,
|
|
856
|
+
start: call.start + offset,
|
|
857
|
+
line: call.line + lines
|
|
858
|
+
});
|
|
715
859
|
usedKeys.push(...analysis.usedKeys);
|
|
716
860
|
strayImports.push(...analysis.strayImports);
|
|
717
861
|
}
|
|
718
862
|
}
|
|
863
|
+
function candidatePattern(svelte, renamed) {
|
|
864
|
+
const names = [.../* @__PURE__ */ new Set(["t", ...[...renamed].map((name) => name.replace(/^\$/, ""))])].map((name) => name.replace(/[$]/g, "\\$")).join("|");
|
|
865
|
+
return new RegExp(`(?<![\\w$])${svelte ? "\\$?" : ""}(?:${names})(?=[\`(]|\\.id\\()`, "g");
|
|
866
|
+
}
|
|
867
|
+
function lineCounter(code) {
|
|
868
|
+
const breaks = [];
|
|
869
|
+
for (let i = code.indexOf("\n"); i !== -1; i = code.indexOf("\n", i + 1)) breaks.push(i);
|
|
870
|
+
return (offset) => {
|
|
871
|
+
let low = 0;
|
|
872
|
+
let high = breaks.length;
|
|
873
|
+
while (low < high) {
|
|
874
|
+
const mid = low + high >> 1;
|
|
875
|
+
if (breaks[mid] < offset) low = mid + 1;
|
|
876
|
+
else high = mid;
|
|
877
|
+
}
|
|
878
|
+
return low + 1;
|
|
879
|
+
};
|
|
880
|
+
}
|
|
719
881
|
function analyzeSegment(code, file, options) {
|
|
720
882
|
try {
|
|
721
|
-
return
|
|
883
|
+
return analyzeScript(code, file, options);
|
|
722
884
|
} catch (error) {
|
|
723
|
-
return {
|
|
885
|
+
return {
|
|
886
|
+
renamed: [],
|
|
887
|
+
error: parseErrorMessage(error)
|
|
888
|
+
};
|
|
724
889
|
}
|
|
725
890
|
}
|
|
726
891
|
function blank(source, re) {
|
|
@@ -751,10 +916,8 @@ function vueExpressionRanges(markup) {
|
|
|
751
916
|
}
|
|
752
917
|
return ranges.sort((a, b) => a[0] - b[0]);
|
|
753
918
|
}
|
|
754
|
-
function expressionExtent(code, start) {
|
|
755
|
-
|
|
756
|
-
if (code[i] === "$") i += 1;
|
|
757
|
-
i += 1;
|
|
919
|
+
function expressionExtent(code, start, nameLength) {
|
|
920
|
+
const i = start + nameLength;
|
|
758
921
|
if (code.startsWith(".id(", i)) {
|
|
759
922
|
const close = balancedEnd(code, i + 3);
|
|
760
923
|
if (close === void 0 || code[close] !== "`") return void 0;
|
|
@@ -801,7 +964,7 @@ async function extractProject(cfg) {
|
|
|
801
964
|
absolute: true
|
|
802
965
|
});
|
|
803
966
|
const registry = new MessageRegistry();
|
|
804
|
-
for (const file of files) registry.update(file, analyzeFile(readFileSync(file, "utf8"), file));
|
|
967
|
+
for (const file of files.sort()) registry.update(file, analyzeFile(readFileSync(file, "utf8"), file));
|
|
805
968
|
return registry;
|
|
806
969
|
}
|
|
807
970
|
async function collectOrigins(cfg, reuse) {
|
|
@@ -816,11 +979,13 @@ function syncCatalogs(cfg, catalogs, registry) {
|
|
|
816
979
|
const source = catalogs[cfg.sourceLocale] ??= emptyCatalog();
|
|
817
980
|
for (const [key, msg] of registry.messages()) {
|
|
818
981
|
const before = own(source, key);
|
|
819
|
-
if (before
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
982
|
+
if (before === msg.message) continue;
|
|
983
|
+
source[key] = msg.message;
|
|
984
|
+
if (before) replaced.push({
|
|
985
|
+
key,
|
|
986
|
+
before
|
|
987
|
+
});
|
|
988
|
+
else (added[cfg.sourceLocale] ??= []).push(key);
|
|
824
989
|
}
|
|
825
990
|
const needed = Object.keys(source);
|
|
826
991
|
for (const locale of cfg.locales) {
|
|
@@ -836,6 +1001,14 @@ function syncCatalogs(cfg, catalogs, registry) {
|
|
|
836
1001
|
replaced
|
|
837
1002
|
};
|
|
838
1003
|
}
|
|
1004
|
+
function shippedCatalogs(cfg, catalogs, registry, options = {}) {
|
|
1005
|
+
const source = Object.assign(emptyCatalog(), flatten(catalogs[cfg.sourceLocale] ?? {}));
|
|
1006
|
+
for (const [key, msg] of registry.messages()) if (options.newKeys !== false || own(source, key) !== void 0) source[key] = msg.message;
|
|
1007
|
+
return {
|
|
1008
|
+
...catalogs,
|
|
1009
|
+
[cfg.sourceLocale]: source
|
|
1010
|
+
};
|
|
1011
|
+
}
|
|
839
1012
|
function pruneCatalogs(cfg, catalogs, registry) {
|
|
840
1013
|
const removed = {};
|
|
841
1014
|
if (registry.parseErrors().length > 0) return removed;
|
|
@@ -1056,6 +1229,78 @@ function renderParamType(types) {
|
|
|
1056
1229
|
]) members.add(m);
|
|
1057
1230
|
return [...members].join(" | ");
|
|
1058
1231
|
}
|
|
1232
|
+
//#endregion
|
|
1233
|
+
//#region src/tsconfig.ts
|
|
1234
|
+
function readTsconfig(root) {
|
|
1235
|
+
const path = join(root, "tsconfig.json");
|
|
1236
|
+
let text;
|
|
1237
|
+
try {
|
|
1238
|
+
text = readFileSync(path, "utf8");
|
|
1239
|
+
} catch {
|
|
1240
|
+
return "no-tsconfig";
|
|
1241
|
+
}
|
|
1242
|
+
const errors = [];
|
|
1243
|
+
const json = parse$2(text, errors, { allowTrailingComma: true });
|
|
1244
|
+
if (errors.length > 0 || typeof json !== "object" || json === null || Array.isArray(json)) return "unreadable";
|
|
1245
|
+
return {
|
|
1246
|
+
path,
|
|
1247
|
+
text,
|
|
1248
|
+
json
|
|
1249
|
+
};
|
|
1250
|
+
}
|
|
1251
|
+
function covered(list, entry) {
|
|
1252
|
+
if (!Array.isArray(list)) return false;
|
|
1253
|
+
return list.some((item) => {
|
|
1254
|
+
if (typeof item !== "string") return false;
|
|
1255
|
+
const pattern = item.replace(/^\.\//, "").replace(/\/+$/, "");
|
|
1256
|
+
return picomatch(pattern)(entry) || picomatch(`${pattern}/**/*`)(entry);
|
|
1257
|
+
});
|
|
1258
|
+
}
|
|
1259
|
+
function formatting(text) {
|
|
1260
|
+
const indent = /\n([ \t]+)\S/.exec(text)?.[1] ?? " ";
|
|
1261
|
+
return {
|
|
1262
|
+
insertSpaces: !indent.startsWith(" "),
|
|
1263
|
+
tabSize: indent.startsWith(" ") ? 1 : indent.length,
|
|
1264
|
+
eol: text.includes("\r\n") ? "\r\n" : "\n"
|
|
1265
|
+
};
|
|
1266
|
+
}
|
|
1267
|
+
function typesIncluded(root, file) {
|
|
1268
|
+
const read = readTsconfig(root);
|
|
1269
|
+
if (typeof read === "string") return read;
|
|
1270
|
+
const entry = relative(root, file).replaceAll("\\", "/");
|
|
1271
|
+
const { include, files } = read.json;
|
|
1272
|
+
if (covered(include, entry) || covered(files, entry)) return "present";
|
|
1273
|
+
return "missing";
|
|
1274
|
+
}
|
|
1275
|
+
function includeTypes(root, file) {
|
|
1276
|
+
const read = readTsconfig(root);
|
|
1277
|
+
if (typeof read === "string") return read;
|
|
1278
|
+
const entry = relative(root, file).replaceAll("\\", "/");
|
|
1279
|
+
const { include, files } = read.json;
|
|
1280
|
+
if (covered(include, entry) || covered(files, entry)) return "present";
|
|
1281
|
+
const options = { formattingOptions: formatting(read.text) };
|
|
1282
|
+
const edits = Array.isArray(include) ? modify(read.text, ["include", -1], entry, {
|
|
1283
|
+
...options,
|
|
1284
|
+
isArrayInsertion: true
|
|
1285
|
+
}) : Array.isArray(files) && include === void 0 ? modify(read.text, ["files", -1], entry, {
|
|
1286
|
+
...options,
|
|
1287
|
+
isArrayInsertion: true
|
|
1288
|
+
}) : modify(read.text, ["include"], ["**/*", entry], options);
|
|
1289
|
+
writeFileSync(read.path, applyEdits(read.text, edits));
|
|
1290
|
+
return "added";
|
|
1291
|
+
}
|
|
1292
|
+
//#endregion
|
|
1293
|
+
//#region src/warn.ts
|
|
1294
|
+
const warned = /* @__PURE__ */ new Set();
|
|
1295
|
+
function warnOnce(message, dedupeKey = message) {
|
|
1296
|
+
if (warned.has(dedupeKey)) return;
|
|
1297
|
+
warned.add(dedupeKey);
|
|
1298
|
+
console.warn(`[verbaly] ${message}`);
|
|
1299
|
+
}
|
|
1300
|
+
function warnParseError(file, message) {
|
|
1301
|
+
warnOnce(`${file}: could not be parsed (${message}), its messages were not extracted`);
|
|
1302
|
+
}
|
|
1303
|
+
const DTS_HEADER = "// generated by verbaly: do not edit";
|
|
1059
1304
|
const SLICE_HELPERS = `function readSlice(root, path) {
|
|
1060
1305
|
const locale = readPath({ supported: locales, path });
|
|
1061
1306
|
if (!locale || locale === sourceLocale) return undefined;
|
|
@@ -1166,7 +1411,8 @@ function generateLocaleModule(catalog) {
|
|
|
1166
1411
|
}
|
|
1167
1412
|
function generateDts(catalog, options = {}) {
|
|
1168
1413
|
const lines = [];
|
|
1169
|
-
|
|
1414
|
+
const locales = options.locales?.length ? [...options.locales].sort(byCodeUnit).map((locale) => JSON.stringify(locale)).join(" | ") : "string";
|
|
1415
|
+
for (const [key, message] of Object.entries(catalog).sort(([a], [b]) => byCodeUnit(a, b))) {
|
|
1170
1416
|
const params = collectParams(message);
|
|
1171
1417
|
if (params.size === 0) lines.push(` ${JSON.stringify(key)}: never;`);
|
|
1172
1418
|
else {
|
|
@@ -1174,19 +1420,20 @@ function generateDts(catalog, options = {}) {
|
|
|
1174
1420
|
lines.push(` ${JSON.stringify(key)}: { ${fields} };`);
|
|
1175
1421
|
}
|
|
1176
1422
|
}
|
|
1177
|
-
return
|
|
1423
|
+
return `${DTS_HEADER}
|
|
1178
1424
|
declare module 'virtual:verbaly' {
|
|
1179
1425
|
export interface VerbalyMessages {
|
|
1180
1426
|
${lines.join("\n")}
|
|
1181
1427
|
}
|
|
1182
1428
|
export type VerbalyKey = keyof VerbalyMessages & string;
|
|
1429
|
+
export type VerbalyLocale = ${locales};
|
|
1183
1430
|
|
|
1184
1431
|
export type VerbalyKeyTree = VerbalyKey | { readonly [name: string]: VerbalyKeyTree };
|
|
1185
1432
|
export function defineKeys<const T extends VerbalyKeyTree>(keys: T): T;
|
|
1186
1433
|
|
|
1187
|
-
export const verbaly: import('verbaly').Verbaly
|
|
1434
|
+
export const verbaly: import('verbaly').Verbaly;
|
|
1188
1435
|
|
|
1189
|
-
export const sourceLocale:
|
|
1436
|
+
export const sourceLocale: VerbalyLocale;
|
|
1190
1437
|
export const locales: string[];
|
|
1191
1438
|
export const routing: import('verbaly').Routing;
|
|
1192
1439
|
export function localePath(
|
|
@@ -1199,17 +1446,16 @@ ${lines.join("\n")}
|
|
|
1199
1446
|
}): string | undefined;
|
|
1200
1447
|
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;" : ""}
|
|
1201
1448
|
export function createInstance(
|
|
1202
|
-
options?: import('verbaly').VerbalyOptions
|
|
1203
|
-
): import('verbaly').Verbaly
|
|
1204
|
-
export function createRequestInstance(
|
|
1205
|
-
locale: string,
|
|
1206
|
-
): Promise<import('verbaly').Verbaly<VerbalyKey>>;
|
|
1449
|
+
options?: import('verbaly').VerbalyOptions,
|
|
1450
|
+
): import('verbaly').Verbaly;
|
|
1451
|
+
export function createRequestInstance(locale: string): Promise<import('verbaly').Verbaly>;
|
|
1207
1452
|
|
|
1208
|
-
export function t<K extends VerbalyKey>(
|
|
1209
|
-
|
|
1210
|
-
...
|
|
1453
|
+
export function t<K extends VerbalyKey | TemplateStringsArray>(
|
|
1454
|
+
first: K,
|
|
1455
|
+
...rest: K extends VerbalyKey
|
|
1456
|
+
? [VerbalyMessages[K]] extends [never] ? [] : [VerbalyMessages[K]]
|
|
1457
|
+
: unknown[]
|
|
1211
1458
|
): string;
|
|
1212
|
-
export function t(strings: TemplateStringsArray, ...values: unknown[]): string;
|
|
1213
1459
|
export namespace t {
|
|
1214
1460
|
export function id(
|
|
1215
1461
|
key: string,
|
|
@@ -1226,6 +1472,14 @@ ${lines.join("\n")}
|
|
|
1226
1472
|
): Promise<void>;
|
|
1227
1473
|
export function getLocale(): string;
|
|
1228
1474
|
export function subscribe(listener: () => void): () => void;
|
|
1475
|
+
|
|
1476
|
+
// nested, so it augments verbaly: at the top of a script it would replace the real module
|
|
1477
|
+
module 'verbaly' {
|
|
1478
|
+
interface Register {
|
|
1479
|
+
t: typeof t;
|
|
1480
|
+
locale: VerbalyLocale;
|
|
1481
|
+
}
|
|
1482
|
+
}
|
|
1229
1483
|
}
|
|
1230
1484
|
|
|
1231
1485
|
declare module 'virtual:verbaly/locale/*' {
|
|
@@ -1234,208 +1488,167 @@ declare module 'virtual:verbaly/locale/*' {
|
|
|
1234
1488
|
}
|
|
1235
1489
|
`;
|
|
1236
1490
|
}
|
|
1491
|
+
function projectDtsOptions(cfg) {
|
|
1492
|
+
return {
|
|
1493
|
+
inlineCatalog: cfg.render.inlineCatalog === true,
|
|
1494
|
+
locales: cfg.locales
|
|
1495
|
+
};
|
|
1496
|
+
}
|
|
1237
1497
|
function writeDts(cfg, catalog, file) {
|
|
1238
1498
|
const target = file === void 0 ? cfg.dts : file;
|
|
1239
|
-
if (target === false) return;
|
|
1240
|
-
|
|
1241
|
-
const content = generateDts(catalog, { inlineCatalog: cfg.render.inlineCatalog === true });
|
|
1499
|
+
if (target === false) return void 0;
|
|
1500
|
+
let existing;
|
|
1242
1501
|
try {
|
|
1243
|
-
|
|
1502
|
+
existing = readFileSync(target, "utf8");
|
|
1244
1503
|
} catch {}
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1504
|
+
const content = withLineEndings(generateDts(catalog, projectDtsOptions(cfg)), existing);
|
|
1505
|
+
const changed = existing !== content;
|
|
1506
|
+
if (changed) {
|
|
1507
|
+
mkdirSync(dirname(target), { recursive: true });
|
|
1508
|
+
writeFileSync(target, content);
|
|
1509
|
+
}
|
|
1510
|
+
removeRootDts(cfg, target);
|
|
1511
|
+
if (resolve(target).startsWith(resolve(cfg.root, ".verbaly") + sep)) {
|
|
1512
|
+
const ignore = join(cfg.root, ".verbaly", ".gitignore");
|
|
1513
|
+
if (!existsSync(ignore)) writeFileSync(ignore, "*\n");
|
|
1514
|
+
const state = includeTypes(cfg.root, target);
|
|
1515
|
+
const entry = relative(cfg.root, target).replaceAll("\\", "/");
|
|
1516
|
+
if (state === "added") warnOnce(`added "${entry}" to the include of tsconfig.json, so TypeScript reads the types`);
|
|
1517
|
+
else if (state === "unreadable") warnOnce(`tsconfig.json could not be read, so add "${entry}" to its include yourself`);
|
|
1256
1518
|
}
|
|
1519
|
+
return {
|
|
1520
|
+
file: target,
|
|
1521
|
+
changed
|
|
1522
|
+
};
|
|
1257
1523
|
}
|
|
1258
|
-
function
|
|
1259
|
-
const
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
//#endregion
|
|
1263
|
-
//#region src/init.ts
|
|
1264
|
-
const HOSTS = [
|
|
1265
|
-
{
|
|
1266
|
-
name: "nuxt",
|
|
1267
|
-
dep: "nuxt",
|
|
1268
|
-
pkg: "@verbaly/nuxt",
|
|
1269
|
-
wire: "add '@verbaly/nuxt' to the modules in nuxt.config"
|
|
1270
|
-
},
|
|
1271
|
-
{
|
|
1272
|
-
name: "next",
|
|
1273
|
-
dep: "next",
|
|
1274
|
-
pkg: "@verbaly/next",
|
|
1275
|
-
wire: "wrap the export of next.config with withVerbaly"
|
|
1276
|
-
},
|
|
1277
|
-
{
|
|
1278
|
-
name: "sveltekit",
|
|
1279
|
-
dep: "@sveltejs/kit",
|
|
1280
|
-
pkg: "@verbaly/vite",
|
|
1281
|
-
wire: "add verbaly() to the plugins in vite.config (per-request locale: @verbaly/sveltekit)"
|
|
1282
|
-
},
|
|
1283
|
-
{
|
|
1284
|
-
name: "astro",
|
|
1285
|
-
dep: "astro",
|
|
1286
|
-
pkg: "@verbaly/astro",
|
|
1287
|
-
wire: "add verbaly() to the integrations in astro.config"
|
|
1288
|
-
},
|
|
1289
|
-
{
|
|
1290
|
-
name: "vite",
|
|
1291
|
-
dep: "vite",
|
|
1292
|
-
pkg: "@verbaly/vite",
|
|
1293
|
-
wire: "add verbaly() to the plugins in vite.config"
|
|
1294
|
-
},
|
|
1295
|
-
{
|
|
1296
|
-
name: "webpack",
|
|
1297
|
-
dep: "webpack",
|
|
1298
|
-
pkg: "@verbaly/unplugin",
|
|
1299
|
-
wire: "add the verbaly webpack plugin to your build config"
|
|
1300
|
-
},
|
|
1301
|
-
{
|
|
1302
|
-
name: "rspack",
|
|
1303
|
-
dep: "@rspack/core",
|
|
1304
|
-
pkg: "@verbaly/unplugin",
|
|
1305
|
-
wire: "add the verbaly rspack plugin to your build config"
|
|
1306
|
-
},
|
|
1307
|
-
{
|
|
1308
|
-
name: "rollup",
|
|
1309
|
-
dep: "rollup",
|
|
1310
|
-
pkg: "@verbaly/unplugin",
|
|
1311
|
-
wire: "add the verbaly rollup plugin to your build config"
|
|
1312
|
-
},
|
|
1313
|
-
{
|
|
1314
|
-
name: "esbuild",
|
|
1315
|
-
dep: "esbuild",
|
|
1316
|
-
pkg: "@verbaly/unplugin",
|
|
1317
|
-
wire: "add the verbaly esbuild plugin to your build config"
|
|
1318
|
-
}
|
|
1319
|
-
];
|
|
1320
|
-
const WIRING_PACKAGES = [...new Set(HOSTS.map((host) => host.pkg))];
|
|
1321
|
-
function readDependencies(root) {
|
|
1322
|
-
const path = join(root, "package.json");
|
|
1323
|
-
if (!existsSync(path)) return {};
|
|
1524
|
+
function removeRootDts(cfg, target) {
|
|
1525
|
+
const old = join(cfg.root, "verbaly.d.ts");
|
|
1526
|
+
if (resolve(target) === resolve(old)) return;
|
|
1527
|
+
let head;
|
|
1324
1528
|
try {
|
|
1325
|
-
|
|
1326
|
-
return {
|
|
1327
|
-
...pkg.dependencies,
|
|
1328
|
-
...pkg.devDependencies
|
|
1329
|
-
};
|
|
1529
|
+
head = readFileSync(old, "utf8").slice(0, 36);
|
|
1330
1530
|
} catch {
|
|
1331
|
-
return
|
|
1531
|
+
return;
|
|
1332
1532
|
}
|
|
1533
|
+
if (head !== "// generated by verbaly: do not edit") return;
|
|
1534
|
+
rmSync(old);
|
|
1535
|
+
warnOnce(`the types live in ${relative(cfg.root, target).replaceAll("\\", "/")} now, so the verbaly.d.ts Verbaly wrote at the root was removed`);
|
|
1333
1536
|
}
|
|
1334
|
-
|
|
1335
|
-
|
|
1336
|
-
|
|
1337
|
-
|
|
1338
|
-
|
|
1339
|
-
|
|
1340
|
-
|
|
1341
|
-
|
|
1537
|
+
//#endregion
|
|
1538
|
+
//#region src/findings.ts
|
|
1539
|
+
function siteOf(msg) {
|
|
1540
|
+
return {
|
|
1541
|
+
file: msg.file,
|
|
1542
|
+
line: msg.line,
|
|
1543
|
+
message: msg.message
|
|
1544
|
+
};
|
|
1342
1545
|
}
|
|
1343
|
-
function
|
|
1344
|
-
|
|
1345
|
-
|
|
1346
|
-
|
|
1347
|
-
|
|
1348
|
-
if (typescript) return `import type { VerbalyConfig } from '@verbaly/compiler';\n\n${body} satisfies VerbalyConfig;\n`;
|
|
1349
|
-
return `/** @type {import('@verbaly/compiler').VerbalyConfig} */\n${body};\n`;
|
|
1546
|
+
function collisionEntries(registry) {
|
|
1547
|
+
return registry.collisions().map(({ key, kept, dropped }) => ({
|
|
1548
|
+
key,
|
|
1549
|
+
sites: [kept, ...dropped].map(siteOf)
|
|
1550
|
+
}));
|
|
1350
1551
|
}
|
|
1351
|
-
|
|
1352
|
-
const
|
|
1353
|
-
const
|
|
1354
|
-
const
|
|
1355
|
-
|
|
1356
|
-
|
|
1357
|
-
|
|
1358
|
-
|
|
1359
|
-
|
|
1360
|
-
|
|
1361
|
-
|
|
1362
|
-
to: near
|
|
1552
|
+
function scanFindings(cfg, registry, replaced = []) {
|
|
1553
|
+
const messages = registry.messages();
|
|
1554
|
+
const out = [];
|
|
1555
|
+
for (const { key, before } of replaced) {
|
|
1556
|
+
const msg = messages.get(key);
|
|
1557
|
+
if (msg) out.push({
|
|
1558
|
+
kind: "replaced",
|
|
1559
|
+
locale: cfg.sourceLocale,
|
|
1560
|
+
key,
|
|
1561
|
+
before,
|
|
1562
|
+
site: siteOf(msg)
|
|
1363
1563
|
});
|
|
1364
|
-
|
|
1365
|
-
|
|
1564
|
+
}
|
|
1565
|
+
for (const entry of collisionEntries(registry)) out.push({
|
|
1566
|
+
kind: "collision",
|
|
1567
|
+
...entry
|
|
1366
1568
|
});
|
|
1367
|
-
const
|
|
1368
|
-
|
|
1369
|
-
|
|
1370
|
-
|
|
1371
|
-
|
|
1372
|
-
|
|
1373
|
-
|
|
1374
|
-
|
|
1569
|
+
for (const { name, file, line } of registry.missed()) out.push({
|
|
1570
|
+
kind: "renamed",
|
|
1571
|
+
name,
|
|
1572
|
+
file,
|
|
1573
|
+
line
|
|
1574
|
+
});
|
|
1575
|
+
for (const msg of messages.values()) {
|
|
1576
|
+
const params = msg.params.map((param) => param.name).filter((name) => /^_\d+$/.test(name));
|
|
1577
|
+
if (params.length > 0) out.push({
|
|
1578
|
+
kind: "positional",
|
|
1579
|
+
params,
|
|
1580
|
+
site: siteOf(msg)
|
|
1581
|
+
});
|
|
1582
|
+
const slice = escapedSyntax(msg.message);
|
|
1583
|
+
if (slice) out.push({
|
|
1584
|
+
kind: "escaped",
|
|
1585
|
+
slice,
|
|
1586
|
+
site: siteOf(msg)
|
|
1375
1587
|
});
|
|
1376
|
-
sourceLocale = near;
|
|
1377
|
-
}
|
|
1378
|
-
const options = {
|
|
1379
|
-
...input,
|
|
1380
|
-
locales,
|
|
1381
|
-
sourceLocale
|
|
1382
|
-
};
|
|
1383
|
-
const existing = findConfigFile(root);
|
|
1384
|
-
const typescript = existsSync(join(root, "tsconfig.json"));
|
|
1385
|
-
const configFile = existing ?? (typescript ? "verbaly.config.ts" : "verbaly.config.mjs");
|
|
1386
|
-
if (existing) skipped.push(existing);
|
|
1387
|
-
else {
|
|
1388
|
-
writeFileSync(join(root, configFile), configSource(options, typescript));
|
|
1389
|
-
created.push(configFile);
|
|
1390
|
-
}
|
|
1391
|
-
const fromFile = existing ? await loadConfigFile(root) : {};
|
|
1392
|
-
const scaffold = {
|
|
1393
|
-
dir: options.dir ?? fromFile.dir,
|
|
1394
|
-
sourceLocale: options.sourceLocale ?? fromFile.sourceLocale,
|
|
1395
|
-
locales: options.locales ?? fromFile.locales
|
|
1396
|
-
};
|
|
1397
|
-
const dir = join(root, scaffold.dir ?? "locales");
|
|
1398
|
-
if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
|
|
1399
|
-
for (const locale of /* @__PURE__ */ new Set([scaffold.sourceLocale ?? "en", ...scaffold.locales ?? []])) {
|
|
1400
|
-
const file = join(dir, `${locale}.json`);
|
|
1401
|
-
const label = relative(root, file).replaceAll("\\", "/");
|
|
1402
|
-
if (existsSync(file)) skipped.push(label);
|
|
1403
|
-
else {
|
|
1404
|
-
writeFileSync(file, "{}\n");
|
|
1405
|
-
created.push(label);
|
|
1406
|
-
}
|
|
1407
1588
|
}
|
|
1408
|
-
const
|
|
1409
|
-
|
|
1410
|
-
|
|
1411
|
-
|
|
1412
|
-
|
|
1413
|
-
|
|
1414
|
-
configFile,
|
|
1415
|
-
next,
|
|
1416
|
-
renamed,
|
|
1417
|
-
refused
|
|
1418
|
-
};
|
|
1589
|
+
for (const { file, message } of registry.parseErrors()) out.push({
|
|
1590
|
+
kind: "unparsed",
|
|
1591
|
+
file,
|
|
1592
|
+
message
|
|
1593
|
+
});
|
|
1594
|
+
return out;
|
|
1419
1595
|
}
|
|
1420
|
-
|
|
1421
|
-
|
|
1422
|
-
|
|
1423
|
-
|
|
1424
|
-
|
|
1425
|
-
|
|
1426
|
-
|
|
1427
|
-
}
|
|
1428
|
-
|
|
1429
|
-
const
|
|
1430
|
-
return (
|
|
1431
|
-
|
|
1432
|
-
|
|
1433
|
-
|
|
1434
|
-
|
|
1596
|
+
function sourcePlace(at, root) {
|
|
1597
|
+
const file = root ? relative(root, at.file).replaceAll("\\", "/") : at.file;
|
|
1598
|
+
return at.line ? `${file}:${at.line}` : file;
|
|
1599
|
+
}
|
|
1600
|
+
function quoted(at, root) {
|
|
1601
|
+
return `"${truncate(at.message, 40)}" (${sourcePlace(at, root)})`;
|
|
1602
|
+
}
|
|
1603
|
+
function formatCollision({ key, sites }, root) {
|
|
1604
|
+
const [kept, ...others] = sites;
|
|
1605
|
+
const texts = new Set(sites.map((at) => at.message)).size;
|
|
1606
|
+
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`;
|
|
1607
|
+
}
|
|
1608
|
+
function formatFinding(finding, root) {
|
|
1609
|
+
switch (finding.kind) {
|
|
1610
|
+
case "collision": return formatCollision(finding, root);
|
|
1611
|
+
case "replaced": {
|
|
1612
|
+
const place = sourcePlace(finding.site, root);
|
|
1613
|
+
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)}"`;
|
|
1435
1614
|
}
|
|
1436
|
-
|
|
1437
|
-
|
|
1438
|
-
|
|
1615
|
+
case "renamed": return `${sourcePlace(finding, root)}: ${finding.name}\`…\` is never extracted, so it stays in the source language: name it t`;
|
|
1616
|
+
case "positional": {
|
|
1617
|
+
const names = finding.params.map((name) => `{${name}}`).join(", ");
|
|
1618
|
+
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`;
|
|
1619
|
+
}
|
|
1620
|
+
case "escaped": return `${sourcePlace(finding.site, root)}: ${finding.slice} renders as literal text, a tagged template has no params (use t(key, params) for a plural or format block, or pass a \${…} value)`;
|
|
1621
|
+
case "unparsed": return `${sourcePlace(finding, root)}: could not be parsed (${finding.message}), its messages were not extracted`;
|
|
1622
|
+
case "outdated": return `[${finding.locale}] ${finding.key}: translated from an older source text, update it or keep it with \`npx verbaly review --approve\``;
|
|
1623
|
+
}
|
|
1624
|
+
}
|
|
1625
|
+
function findingId(finding) {
|
|
1626
|
+
switch (finding.kind) {
|
|
1627
|
+
case "collision":
|
|
1628
|
+
case "replaced": return `${finding.kind}:${finding.key}`;
|
|
1629
|
+
case "outdated": return `outdated:${finding.locale}:${finding.key}`;
|
|
1630
|
+
case "renamed": return `renamed:${finding.file}:${finding.name}`;
|
|
1631
|
+
case "positional": return `positional:${finding.site.file}:${finding.params.join(",")}`;
|
|
1632
|
+
case "escaped": return `escaped:${finding.site.file}:${finding.slice}`;
|
|
1633
|
+
case "unparsed": return `unparsed:${finding.file}`;
|
|
1634
|
+
}
|
|
1635
|
+
}
|
|
1636
|
+
function createDevReporter(root, print = (line) => console.warn(`[verbaly] ${line}`), cap = 5) {
|
|
1637
|
+
const shown = /* @__PURE__ */ new Map();
|
|
1638
|
+
return { report(channel, findings) {
|
|
1639
|
+
const before = shown.get(channel) ?? /* @__PURE__ */ new Set();
|
|
1640
|
+
const now = /* @__PURE__ */ new Set();
|
|
1641
|
+
const fresh = [];
|
|
1642
|
+
for (const finding of findings) {
|
|
1643
|
+
const id = findingId(finding);
|
|
1644
|
+
if (now.has(id)) continue;
|
|
1645
|
+
now.add(id);
|
|
1646
|
+
if (!before.has(id)) fresh.push(finding);
|
|
1647
|
+
}
|
|
1648
|
+
shown.set(channel, now);
|
|
1649
|
+
for (const finding of fresh.slice(0, cap)) print(formatFinding(finding, root));
|
|
1650
|
+
if (fresh.length > cap) print(`and ${fresh.length - cap} more: \`npx verbaly doctor\` names them`);
|
|
1651
|
+
} };
|
|
1439
1652
|
}
|
|
1440
1653
|
//#endregion
|
|
1441
1654
|
//#region src/state.ts
|
|
@@ -1446,29 +1659,37 @@ function statePath(cfg, file = STATE_FILE) {
|
|
|
1446
1659
|
}
|
|
1447
1660
|
function loadState(cfg) {
|
|
1448
1661
|
const current = readJson(statePath(cfg));
|
|
1449
|
-
if (current !== void 0)
|
|
1450
|
-
if (!isObject(current)) throw corrupt(statePath(cfg));
|
|
1451
|
-
return {
|
|
1452
|
-
drafts: readDrafts(current.drafts),
|
|
1453
|
-
fingerprints: readFingerprints(current.fingerprints)
|
|
1454
|
-
};
|
|
1455
|
-
}
|
|
1662
|
+
if (current !== void 0 && !isObject(current)) throw corrupt(statePath(cfg));
|
|
1456
1663
|
const legacy = readJson(statePath(cfg, LEGACY_DRAFTS_FILE));
|
|
1457
|
-
if (legacy
|
|
1664
|
+
if (legacy !== void 0 && !isObject(legacy)) throw corrupt(statePath(cfg, LEGACY_DRAFTS_FILE));
|
|
1665
|
+
const state = isObject(current) ? {
|
|
1666
|
+
drafts: readDrafts(current.drafts),
|
|
1667
|
+
fingerprints: readFingerprints(current.fingerprints)
|
|
1668
|
+
} : {
|
|
1458
1669
|
drafts: {},
|
|
1459
1670
|
fingerprints: {}
|
|
1460
1671
|
};
|
|
1461
|
-
if (
|
|
1462
|
-
return
|
|
1463
|
-
|
|
1464
|
-
|
|
1465
|
-
|
|
1672
|
+
if (legacy !== void 0) for (const [locale, keys] of Object.entries(readDrafts(legacy))) markDrafts(state.drafts, locale, keys);
|
|
1673
|
+
return state;
|
|
1674
|
+
}
|
|
1675
|
+
function readState(cfg) {
|
|
1676
|
+
try {
|
|
1677
|
+
return { state: loadState(cfg) };
|
|
1678
|
+
} catch (error) {
|
|
1679
|
+
return {
|
|
1680
|
+
state: {
|
|
1681
|
+
drafts: {},
|
|
1682
|
+
fingerprints: {}
|
|
1683
|
+
},
|
|
1684
|
+
problem: error.message.replace(/^\[verbaly\] /, "")
|
|
1685
|
+
};
|
|
1686
|
+
}
|
|
1466
1687
|
}
|
|
1467
1688
|
function saveState(cfg, state) {
|
|
1468
|
-
const
|
|
1689
|
+
const fresh = serializeState(state);
|
|
1469
1690
|
const path = statePath(cfg);
|
|
1470
1691
|
const legacy = statePath(cfg, LEGACY_DRAFTS_FILE);
|
|
1471
|
-
if (
|
|
1692
|
+
if (fresh === void 0) {
|
|
1472
1693
|
rmSync(path, { force: true });
|
|
1473
1694
|
rmSync(legacy, { force: true });
|
|
1474
1695
|
return;
|
|
@@ -1479,18 +1700,71 @@ function saveState(cfg, state) {
|
|
|
1479
1700
|
} catch {
|
|
1480
1701
|
mkdirSync(cfg.dir, { recursive: true });
|
|
1481
1702
|
}
|
|
1703
|
+
const serialized = withLineEndings(fresh, existing);
|
|
1482
1704
|
if (existing !== serialized) writeFileSync(path, serialized);
|
|
1483
1705
|
if (existsSync(legacy)) rmSync(legacy);
|
|
1484
1706
|
}
|
|
1485
1707
|
function updateState(cfg, catalogs) {
|
|
1486
|
-
const
|
|
1487
|
-
const next = {
|
|
1488
|
-
drafts: effectiveDrafts(state.drafts, catalogs),
|
|
1489
|
-
fingerprints: refreshFingerprints(cfg, catalogs, state.fingerprints)
|
|
1490
|
-
};
|
|
1708
|
+
const next = refreshState(cfg, catalogs, loadState(cfg));
|
|
1491
1709
|
saveState(cfg, next);
|
|
1492
1710
|
return next;
|
|
1493
1711
|
}
|
|
1712
|
+
function refreshState(cfg, catalogs, previous) {
|
|
1713
|
+
const flat = flatCatalogs(catalogs);
|
|
1714
|
+
const source = flat[cfg.sourceLocale] ?? {};
|
|
1715
|
+
const shown = new Set(targetLocales(cfg).filter((locale) => Object.hasOwn(flat, locale) && existsSync(catalogPath(cfg, locale))));
|
|
1716
|
+
const drafts = {};
|
|
1717
|
+
for (const [locale, keys] of Object.entries(previous.drafts)) {
|
|
1718
|
+
if (!shown.has(locale)) {
|
|
1719
|
+
drafts[locale] = keys;
|
|
1720
|
+
continue;
|
|
1721
|
+
}
|
|
1722
|
+
const live = keys.filter((key) => own(flat[locale], key));
|
|
1723
|
+
if (live.length) drafts[locale] = live;
|
|
1724
|
+
}
|
|
1725
|
+
const fingerprints = {};
|
|
1726
|
+
for (const [locale, stamps] of Object.entries(previous.fingerprints)) if (!shown.has(locale)) fingerprints[locale] = stamps;
|
|
1727
|
+
for (const locale of shown) {
|
|
1728
|
+
const stamps = refreshStamps(source, flat[locale], previous.fingerprints[locale] ?? {});
|
|
1729
|
+
if (Object.keys(stamps).length) fingerprints[locale] = stamps;
|
|
1730
|
+
}
|
|
1731
|
+
return {
|
|
1732
|
+
drafts,
|
|
1733
|
+
fingerprints
|
|
1734
|
+
};
|
|
1735
|
+
}
|
|
1736
|
+
function refreshStamps(source, catalog, before) {
|
|
1737
|
+
const after = emptyCatalog();
|
|
1738
|
+
for (const key of /* @__PURE__ */ new Set([...Object.keys(before), ...Object.keys(source)])) {
|
|
1739
|
+
const translated = own(catalog, key);
|
|
1740
|
+
if (!translated) continue;
|
|
1741
|
+
const was = own(before, key);
|
|
1742
|
+
if (was !== void 0 && translationOf(was) === fingerprint(translated)) {
|
|
1743
|
+
after[key] = was;
|
|
1744
|
+
continue;
|
|
1745
|
+
}
|
|
1746
|
+
const text = own(source, key);
|
|
1747
|
+
if (text && tracked(key, text)) after[key] = stamp(text, translated);
|
|
1748
|
+
else if (was !== void 0) after[key] = was;
|
|
1749
|
+
}
|
|
1750
|
+
return after;
|
|
1751
|
+
}
|
|
1752
|
+
function recordTranslations(cfg, source, writes) {
|
|
1753
|
+
const state = loadState(cfg);
|
|
1754
|
+
for (const { locale, entries, draft } of writes) {
|
|
1755
|
+
if (entries.length === 0) continue;
|
|
1756
|
+
const stamps = state.fingerprints[locale] ??= emptyCatalog();
|
|
1757
|
+
for (const entry of entries) {
|
|
1758
|
+
const from = entry.source || own(source, entry.key);
|
|
1759
|
+
if (from && entry.text && tracked(entry.key, from)) stamps[entry.key] = stamp(from, entry.text);
|
|
1760
|
+
}
|
|
1761
|
+
const keys = entries.map((entry) => entry.key);
|
|
1762
|
+
if (draft === true) markDrafts(state.drafts, locale, keys);
|
|
1763
|
+
else if (draft === false) clearDrafts(state.drafts, locale, keys);
|
|
1764
|
+
}
|
|
1765
|
+
saveState(cfg, state);
|
|
1766
|
+
return state;
|
|
1767
|
+
}
|
|
1494
1768
|
function effectiveDrafts(drafts, catalogs) {
|
|
1495
1769
|
const out = {};
|
|
1496
1770
|
for (const [locale, keys] of Object.entries(drafts)) {
|
|
@@ -1500,6 +1774,20 @@ function effectiveDrafts(drafts, catalogs) {
|
|
|
1500
1774
|
}
|
|
1501
1775
|
return out;
|
|
1502
1776
|
}
|
|
1777
|
+
function markDrafts(drafts, locale, keys) {
|
|
1778
|
+
if (!keys.length) return;
|
|
1779
|
+
drafts[locale] = [.../* @__PURE__ */ new Set([...drafts[locale] ?? [], ...keys])];
|
|
1780
|
+
}
|
|
1781
|
+
function clearDrafts(drafts, locale, keys) {
|
|
1782
|
+
if (!drafts[locale]) return;
|
|
1783
|
+
if (!keys) {
|
|
1784
|
+
delete drafts[locale];
|
|
1785
|
+
return;
|
|
1786
|
+
}
|
|
1787
|
+
const drop = new Set(keys);
|
|
1788
|
+
drafts[locale] = drafts[locale].filter((key) => !drop.has(key));
|
|
1789
|
+
if (!drafts[locale].length) delete drafts[locale];
|
|
1790
|
+
}
|
|
1503
1791
|
function fingerprint(text) {
|
|
1504
1792
|
return stableKey(text);
|
|
1505
1793
|
}
|
|
@@ -1509,23 +1797,6 @@ function tracked(key, text) {
|
|
|
1509
1797
|
function stamp(source, translated) {
|
|
1510
1798
|
return `${fingerprint(source)}.${fingerprint(translated)}`;
|
|
1511
1799
|
}
|
|
1512
|
-
function refreshFingerprints(cfg, catalogs, previous) {
|
|
1513
|
-
const source = catalogs[cfg.sourceLocale] ?? {};
|
|
1514
|
-
const out = {};
|
|
1515
|
-
for (const locale of targetLocales(cfg)) {
|
|
1516
|
-
const catalog = catalogs[locale] ?? {};
|
|
1517
|
-
const before = previous[locale] ?? {};
|
|
1518
|
-
const after = emptyCatalog();
|
|
1519
|
-
for (const [key, text] of Object.entries(source)) {
|
|
1520
|
-
const translated = own(catalog, key);
|
|
1521
|
-
if (!text || !translated || !tracked(key, text)) continue;
|
|
1522
|
-
const was = own(before, key);
|
|
1523
|
-
after[key] = was !== void 0 && translationOf(was) === fingerprint(translated) ? was : stamp(text, translated);
|
|
1524
|
-
}
|
|
1525
|
-
if (Object.keys(after).length) out[locale] = after;
|
|
1526
|
-
}
|
|
1527
|
-
return out;
|
|
1528
|
-
}
|
|
1529
1800
|
function outdatedTranslations(cfg, catalogs, fingerprints) {
|
|
1530
1801
|
const source = catalogs[cfg.sourceLocale] ?? {};
|
|
1531
1802
|
const out = [];
|
|
@@ -1542,7 +1813,7 @@ function outdatedTranslations(cfg, catalogs, fingerprints) {
|
|
|
1542
1813
|
});
|
|
1543
1814
|
}
|
|
1544
1815
|
}
|
|
1545
|
-
return out.sort((a, b) => a.locale
|
|
1816
|
+
return out.sort((a, b) => byCodeUnit(a.locale, b.locale) || byCodeUnit(a.key, b.key));
|
|
1546
1817
|
}
|
|
1547
1818
|
function sourceOf(stamped) {
|
|
1548
1819
|
return stamped.slice(0, stamped.indexOf("."));
|
|
@@ -1550,6 +1821,11 @@ function sourceOf(stamped) {
|
|
|
1550
1821
|
function translationOf(stamped) {
|
|
1551
1822
|
return stamped.slice(stamped.indexOf(".") + 1);
|
|
1552
1823
|
}
|
|
1824
|
+
function flatCatalogs(catalogs) {
|
|
1825
|
+
const out = {};
|
|
1826
|
+
for (const [locale, catalog] of Object.entries(catalogs)) out[locale] = flatten(catalog);
|
|
1827
|
+
return out;
|
|
1828
|
+
}
|
|
1553
1829
|
function serializeState(state) {
|
|
1554
1830
|
const drafts = {};
|
|
1555
1831
|
for (const locale of Object.keys(state.drafts).sort()) {
|
|
@@ -1583,7 +1859,7 @@ function readJson(path) {
|
|
|
1583
1859
|
}
|
|
1584
1860
|
}
|
|
1585
1861
|
function corrupt(path, cause) {
|
|
1586
|
-
return new Error(`[verbaly] ${path} is not valid JSON
|
|
1862
|
+
return new Error(`[verbaly] ${path} is not valid JSON: restore it from git or fix it (deleting it approves every draft)`, { cause });
|
|
1587
1863
|
}
|
|
1588
1864
|
function isObject(value) {
|
|
1589
1865
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
@@ -1606,6 +1882,153 @@ function readFingerprints(value) {
|
|
|
1606
1882
|
return out;
|
|
1607
1883
|
}
|
|
1608
1884
|
//#endregion
|
|
1885
|
+
//#region src/project.ts
|
|
1886
|
+
async function syncProject(cfg, options = {}) {
|
|
1887
|
+
const registry = options.registry ?? await extractProject(cfg);
|
|
1888
|
+
const catalogs = options.catalogs ?? loadCatalogs(cfg);
|
|
1889
|
+
if (options.confirm) confirmFromDisk(cfg, catalogs, registry);
|
|
1890
|
+
const pruneBlocked = options.prune === true && registry.parseErrors().length > 0;
|
|
1891
|
+
const pruned = options.prune ? pruneCatalogs(cfg, catalogs, registry) : {};
|
|
1892
|
+
const { added, replaced } = syncCatalogs(cfg, catalogs, registry);
|
|
1893
|
+
const result = {
|
|
1894
|
+
registry,
|
|
1895
|
+
catalogs,
|
|
1896
|
+
added,
|
|
1897
|
+
replaced,
|
|
1898
|
+
pruned,
|
|
1899
|
+
pruneBlocked,
|
|
1900
|
+
findings: scanFindings(cfg, registry, replaced),
|
|
1901
|
+
written: {}
|
|
1902
|
+
};
|
|
1903
|
+
if (options.dryRun) return result;
|
|
1904
|
+
const changed = /* @__PURE__ */ new Set([...Object.keys(added), ...Object.keys(pruned)]);
|
|
1905
|
+
if (replaced.length > 0) changed.add(cfg.sourceLocale);
|
|
1906
|
+
for (const locale of cfg.locales) {
|
|
1907
|
+
if (options.write === "changed" && !changed.has(locale)) continue;
|
|
1908
|
+
result.written[locale] = writeCatalog(cfg, locale, catalogs[locale] ?? {});
|
|
1909
|
+
}
|
|
1910
|
+
writeDts(cfg, catalogs[cfg.sourceLocale] ?? {});
|
|
1911
|
+
try {
|
|
1912
|
+
result.state = updateState(cfg, catalogs);
|
|
1913
|
+
} catch (error) {
|
|
1914
|
+
result.stateProblem = error.message.replace(/^\[verbaly\] /, "");
|
|
1915
|
+
}
|
|
1916
|
+
return result;
|
|
1917
|
+
}
|
|
1918
|
+
function confirmFromDisk(cfg, catalogs, registry) {
|
|
1919
|
+
const source = catalogs[cfg.sourceLocale] ?? {};
|
|
1920
|
+
const stale = /* @__PURE__ */ new Set();
|
|
1921
|
+
for (const [key, msg] of registry.messages()) if (own(source, key) !== msg.message) stale.add(msg.file);
|
|
1922
|
+
for (const file of stale) {
|
|
1923
|
+
let code;
|
|
1924
|
+
try {
|
|
1925
|
+
code = readFileSync(file, "utf8");
|
|
1926
|
+
} catch {
|
|
1927
|
+
registry.remove(file);
|
|
1928
|
+
continue;
|
|
1929
|
+
}
|
|
1930
|
+
registry.update(file, analyzeFile(code, file));
|
|
1931
|
+
}
|
|
1932
|
+
}
|
|
1933
|
+
//#endregion
|
|
1934
|
+
//#region src/tag.ts
|
|
1935
|
+
function isLocaleTag(tag) {
|
|
1936
|
+
try {
|
|
1937
|
+
Intl.getCanonicalLocales(tag);
|
|
1938
|
+
return true;
|
|
1939
|
+
} catch {
|
|
1940
|
+
return false;
|
|
1941
|
+
}
|
|
1942
|
+
}
|
|
1943
|
+
function suggestTag(tag) {
|
|
1944
|
+
const near = tag.replace(/_/g, "-");
|
|
1945
|
+
return near !== tag && isLocaleTag(near) ? near : void 0;
|
|
1946
|
+
}
|
|
1947
|
+
//#endregion
|
|
1948
|
+
//#region src/init.ts
|
|
1949
|
+
function cliReachable(root) {
|
|
1950
|
+
const bin = join(root, "node_modules", ".bin");
|
|
1951
|
+
return existsSync(join(bin, "verbaly")) || existsSync(join(bin, "verbaly.CMD"));
|
|
1952
|
+
}
|
|
1953
|
+
const CLI_INSTALL_FIX = "add `@verbaly/compiler` to your dev dependencies, then `npx verbaly` resolves";
|
|
1954
|
+
function configSource(options, typescript) {
|
|
1955
|
+
const fields = [` sourceLocale: '${options.sourceLocale ?? "en"}',`];
|
|
1956
|
+
if (options.locales?.length) fields.push(` locales: [${options.locales.map((l) => `'${l}'`).join(", ")}],`);
|
|
1957
|
+
if (options.dir) fields.push(` dir: '${options.dir}',`);
|
|
1958
|
+
const body = `export default {\n${fields.join("\n")}\n}`;
|
|
1959
|
+
if (typescript) return `import type { VerbalyConfig } from '@verbaly/compiler';\n\n${body} satisfies VerbalyConfig;\n`;
|
|
1960
|
+
return `/** @type {import('@verbaly/compiler').VerbalyConfig} */\n${body};\n`;
|
|
1961
|
+
}
|
|
1962
|
+
async function init(input = {}) {
|
|
1963
|
+
const root = input.root ?? process.cwd();
|
|
1964
|
+
const created = [];
|
|
1965
|
+
const skipped = [];
|
|
1966
|
+
const renamed = [];
|
|
1967
|
+
const refused = [];
|
|
1968
|
+
const typed = input.locales?.flatMap((locale) => {
|
|
1969
|
+
if (isLocaleTag(locale)) return [locale];
|
|
1970
|
+
const near = suggestTag(locale);
|
|
1971
|
+
if (near) renamed.push({
|
|
1972
|
+
from: locale,
|
|
1973
|
+
to: near
|
|
1974
|
+
});
|
|
1975
|
+
else refused.push(locale);
|
|
1976
|
+
return near ? [near] : [];
|
|
1977
|
+
});
|
|
1978
|
+
const locales = typed && [...new Set(typed)];
|
|
1979
|
+
let sourceLocale = input.sourceLocale;
|
|
1980
|
+
if (sourceLocale !== void 0 && !isLocaleTag(sourceLocale)) {
|
|
1981
|
+
const near = suggestTag(sourceLocale);
|
|
1982
|
+
if (!near) throw new Error(`[verbaly] "${sourceLocale}" is not a locale tag: pass --source with one like en or pt-BR`);
|
|
1983
|
+
renamed.push({
|
|
1984
|
+
from: sourceLocale,
|
|
1985
|
+
to: near
|
|
1986
|
+
});
|
|
1987
|
+
sourceLocale = near;
|
|
1988
|
+
}
|
|
1989
|
+
const options = {
|
|
1990
|
+
...input,
|
|
1991
|
+
locales,
|
|
1992
|
+
sourceLocale
|
|
1993
|
+
};
|
|
1994
|
+
const existing = findConfigFile(root);
|
|
1995
|
+
const typescript = existsSync(join(root, "tsconfig.json"));
|
|
1996
|
+
const configFile = existing ?? (typescript ? "verbaly.config.ts" : "verbaly.config.mjs");
|
|
1997
|
+
if (existing) skipped.push(existing);
|
|
1998
|
+
else {
|
|
1999
|
+
writeFileSync(join(root, configFile), configSource(options, typescript));
|
|
2000
|
+
created.push(configFile);
|
|
2001
|
+
}
|
|
2002
|
+
const fromFile = existing ? await loadConfigFile(root) : {};
|
|
2003
|
+
const scaffold = {
|
|
2004
|
+
dir: options.dir ?? fromFile.dir,
|
|
2005
|
+
sourceLocale: options.sourceLocale ?? fromFile.sourceLocale,
|
|
2006
|
+
locales: options.locales ?? fromFile.locales
|
|
2007
|
+
};
|
|
2008
|
+
const dir = join(root, scaffold.dir ?? "locales");
|
|
2009
|
+
if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
|
|
2010
|
+
for (const locale of /* @__PURE__ */ new Set([scaffold.sourceLocale ?? "en", ...scaffold.locales ?? []])) {
|
|
2011
|
+
const file = join(dir, `${locale}.json`);
|
|
2012
|
+
const label = relative(root, file).replaceAll("\\", "/");
|
|
2013
|
+
if (existsSync(file)) skipped.push(label);
|
|
2014
|
+
else {
|
|
2015
|
+
writeFileSync(file, "{}\n");
|
|
2016
|
+
created.push(label);
|
|
2017
|
+
}
|
|
2018
|
+
}
|
|
2019
|
+
const host = detectHost(root);
|
|
2020
|
+
const next = host ? [installCommand(root, host.install), host.wire] : ["run \"verbaly extract\" after writing your first t`…` message"];
|
|
2021
|
+
return {
|
|
2022
|
+
created,
|
|
2023
|
+
skipped,
|
|
2024
|
+
host: host?.name,
|
|
2025
|
+
configFile,
|
|
2026
|
+
next,
|
|
2027
|
+
renamed,
|
|
2028
|
+
refused
|
|
2029
|
+
};
|
|
2030
|
+
}
|
|
2031
|
+
//#endregion
|
|
1609
2032
|
//#region src/check.ts
|
|
1610
2033
|
function gatePasses(result) {
|
|
1611
2034
|
return result.missing.length === 0 && result.unknown.length === 0 && !result.broken.some((entry) => entry.severity === "error");
|
|
@@ -1615,15 +2038,11 @@ function warningCount(result) {
|
|
|
1615
2038
|
}
|
|
1616
2039
|
function check(cfg, catalogs, registry, fingerprints = {}) {
|
|
1617
2040
|
const extracted = registry.messages();
|
|
1618
|
-
const locate = createLocator();
|
|
1619
|
-
const site = (msg) => ({
|
|
1620
|
-
file: msg.file,
|
|
1621
|
-
line: locate(msg.file, msg.start),
|
|
1622
|
-
message: msg.message
|
|
1623
|
-
});
|
|
1624
2041
|
const flat = {};
|
|
1625
2042
|
for (const locale of cfg.locales) flat[locale] = flatten(catalogs[locale] ?? {});
|
|
1626
2043
|
const source = flat[cfg.sourceLocale] ?? {};
|
|
2044
|
+
const shipped = shippedCatalogs(cfg, flat, registry);
|
|
2045
|
+
const sourceText = shipped[cfg.sourceLocale];
|
|
1627
2046
|
const used = registry.usedKeys();
|
|
1628
2047
|
const unknown = [];
|
|
1629
2048
|
for (const [key, files] of registry.usedKeys(true)) if (!(extracted.has(key) || cfg.locales.some((locale) => flat[locale]?.[key] !== void 0))) unknown.push({
|
|
@@ -1654,16 +2073,14 @@ function check(cfg, catalogs, registry, fingerprints = {}) {
|
|
|
1654
2073
|
issue: issue.message
|
|
1655
2074
|
});
|
|
1656
2075
|
};
|
|
1657
|
-
const sourceText = Object.assign(emptyCatalog(), source);
|
|
1658
2076
|
const divergent = [];
|
|
1659
2077
|
for (const [key, entry] of extracted) {
|
|
1660
|
-
const written =
|
|
2078
|
+
const written = source[key];
|
|
1661
2079
|
if (written && written !== entry.message) divergent.push({
|
|
1662
2080
|
key,
|
|
1663
2081
|
catalog: written,
|
|
1664
|
-
code:
|
|
2082
|
+
code: siteOf(entry)
|
|
1665
2083
|
});
|
|
1666
|
-
sourceText[key] = entry.message;
|
|
1667
2084
|
}
|
|
1668
2085
|
for (const [key, text] of Object.entries(sourceText)) add(cfg.sourceLocale, key, validateMessage(text, cfg.sourceLocale));
|
|
1669
2086
|
for (const locale of cfg.locales) {
|
|
@@ -1687,8 +2104,6 @@ function check(cfg, catalogs, registry, fingerprints = {}) {
|
|
|
1687
2104
|
});
|
|
1688
2105
|
}
|
|
1689
2106
|
}
|
|
1690
|
-
const collisions = collisionEntries(registry, locate);
|
|
1691
|
-
const outdated = outdatedTranslations(cfg, flat, fingerprints);
|
|
1692
2107
|
return {
|
|
1693
2108
|
ok: gatePasses({
|
|
1694
2109
|
missing,
|
|
@@ -1699,9 +2114,9 @@ function check(cfg, catalogs, registry, fingerprints = {}) {
|
|
|
1699
2114
|
unknown,
|
|
1700
2115
|
broken,
|
|
1701
2116
|
extra,
|
|
1702
|
-
collisions,
|
|
2117
|
+
collisions: collisionEntries(registry),
|
|
1703
2118
|
divergent,
|
|
1704
|
-
outdated
|
|
2119
|
+
outdated: outdatedTranslations(cfg, shipped, fingerprints)
|
|
1705
2120
|
};
|
|
1706
2121
|
}
|
|
1707
2122
|
function formatCheckResult(result, root) {
|
|
@@ -1733,49 +2148,20 @@ function checkNextSteps(result, cliReachable = true) {
|
|
|
1733
2148
|
if (steps.length > 0 && !cliReachable) steps.push(`the verbaly command is not linked in this project: ${CLI_INSTALL_FIX}`);
|
|
1734
2149
|
return steps.join("\n");
|
|
1735
2150
|
}
|
|
1736
|
-
function
|
|
1737
|
-
return registry.collisions().map(({ key, kept, dropped }) => ({
|
|
1738
|
-
key,
|
|
1739
|
-
sites: [kept, ...dropped].map((msg) => ({
|
|
1740
|
-
file: msg.file,
|
|
1741
|
-
line: locate(msg.file, msg.start),
|
|
1742
|
-
message: msg.message
|
|
1743
|
-
}))
|
|
1744
|
-
}));
|
|
1745
|
-
}
|
|
1746
|
-
function sourcePlace(at, root) {
|
|
1747
|
-
const file = root ? relative(root, at.file).replaceAll("\\", "/") : at.file;
|
|
1748
|
-
return at.line ? `${file}:${at.line}` : file;
|
|
1749
|
-
}
|
|
1750
|
-
function quoted(at, root) {
|
|
1751
|
-
return `"${truncate(at.message, 40)}" (${sourcePlace(at, root)})`;
|
|
1752
|
-
}
|
|
1753
|
-
function formatCollision({ key, sites }, root) {
|
|
1754
|
-
const [kept, ...others] = sites;
|
|
1755
|
-
return ` ${key}: one key with ${counted(sites.length, "text")}, and every place shows ${quoted(kept, root)}, never ${others.map((at) => quoted(at, root)).join(" or ")}: give each text its own key`;
|
|
1756
|
-
}
|
|
1757
|
-
function formatCheckWarnings(result, root) {
|
|
2151
|
+
function formatCheckWarnings(result, root, options = {}) {
|
|
1758
2152
|
const lines = result.broken.filter((entry) => entry.severity === "warning").map((entry) => ` [${entry.locale}] ${entry.key}: ${entry.issue}`);
|
|
1759
2153
|
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`);
|
|
1760
|
-
for (const entry of result.collisions) lines.push(
|
|
1761
|
-
|
|
1762
|
-
|
|
2154
|
+
for (const entry of result.collisions) lines.push(` ${formatFinding({
|
|
2155
|
+
kind: "collision",
|
|
2156
|
+
...entry
|
|
2157
|
+
}, root)}`);
|
|
2158
|
+
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)`);
|
|
2159
|
+
if (!options.outdatedFails) for (const entry of result.outdated) lines.push(` ${formatFinding({
|
|
2160
|
+
kind: "outdated",
|
|
2161
|
+
...entry
|
|
2162
|
+
}, root)}`);
|
|
1763
2163
|
return lines.join("\n");
|
|
1764
2164
|
}
|
|
1765
|
-
function truncate(text, max) {
|
|
1766
|
-
return text.length > max ? text.slice(0, max - 1) + "…" : text;
|
|
1767
|
-
}
|
|
1768
|
-
//#endregion
|
|
1769
|
-
//#region src/warn.ts
|
|
1770
|
-
const warned = /* @__PURE__ */ new Set();
|
|
1771
|
-
function warnOnce(message, dedupeKey = message) {
|
|
1772
|
-
if (warned.has(dedupeKey)) return;
|
|
1773
|
-
warned.add(dedupeKey);
|
|
1774
|
-
console.warn(`[verbaly] ${message}`);
|
|
1775
|
-
}
|
|
1776
|
-
function warnParseError(file, message) {
|
|
1777
|
-
warnOnce(`${file}: could not be parsed (${message}), its messages were not extracted`);
|
|
1778
|
-
}
|
|
1779
2165
|
//#endregion
|
|
1780
2166
|
//#region src/transform.ts
|
|
1781
2167
|
function quote(text, single) {
|
|
@@ -1860,12 +2246,68 @@ function runBuildGate(cfg, registry, failOnMissing) {
|
|
|
1860
2246
|
throw new Error(`[verbaly] build blocked\n${formatCheckResult(result, cfg.root)}\n${checkNextSteps(result, cliReachable(cfg.root))}`);
|
|
1861
2247
|
}
|
|
1862
2248
|
function buildFingerprints(cfg) {
|
|
1863
|
-
|
|
1864
|
-
|
|
1865
|
-
|
|
1866
|
-
|
|
1867
|
-
|
|
2249
|
+
const { state, problem } = readState(cfg);
|
|
2250
|
+
if (problem) warnOnce(`${problem}, so outdated translations are not reported`, "gate:state");
|
|
2251
|
+
return state.fingerprints;
|
|
2252
|
+
}
|
|
2253
|
+
//#endregion
|
|
2254
|
+
//#region src/scope.ts
|
|
2255
|
+
const TAGGED_HINT = /(?<![\w$.])\$?t(?:\.id\s*\([^)]*\))?\s*`/;
|
|
2256
|
+
const NOT_SOURCE = [
|
|
2257
|
+
"**/node_modules/**",
|
|
2258
|
+
"**/dist/**",
|
|
2259
|
+
"**/build/**",
|
|
2260
|
+
"**/out/**",
|
|
2261
|
+
"**/coverage/**"
|
|
2262
|
+
];
|
|
2263
|
+
function relativeId(cfg, id) {
|
|
2264
|
+
return relative(cfg.root, id).replaceAll("\\", "/");
|
|
2265
|
+
}
|
|
2266
|
+
function suggestedPattern(rel) {
|
|
2267
|
+
const slash = rel.indexOf("/");
|
|
2268
|
+
return slash < 0 ? rel : `${rel.slice(0, slash)}/**/*.${SOURCE_EXTENSIONS}`;
|
|
2269
|
+
}
|
|
2270
|
+
function createOutsideCheck(cfg) {
|
|
2271
|
+
if (cfg.include.length === 0) return () => void 0;
|
|
2272
|
+
const included = picomatch(cfg.include);
|
|
2273
|
+
const excluded = picomatch(cfg.exclude);
|
|
2274
|
+
return (code, id) => {
|
|
2275
|
+
const rel = relativeId(cfg, id);
|
|
2276
|
+
if (rel.startsWith("..") || included(rel) || excluded(rel)) return void 0;
|
|
2277
|
+
if (!TAGGED_HINT.test(code)) return void 0;
|
|
2278
|
+
if (analyzeFile(code, id).tagged.length === 0) return void 0;
|
|
2279
|
+
return {
|
|
2280
|
+
file: id,
|
|
2281
|
+
pattern: suggestedPattern(rel)
|
|
2282
|
+
};
|
|
2283
|
+
};
|
|
2284
|
+
}
|
|
2285
|
+
function formatOutside(cfg, found) {
|
|
2286
|
+
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)`;
|
|
2287
|
+
}
|
|
2288
|
+
async function reportOutsideInclude(cfg) {
|
|
2289
|
+
for (const found of await filesOutsideInclude(cfg)) warnOnce(formatOutside(cfg, found), `outside:${found.file}`);
|
|
2290
|
+
}
|
|
2291
|
+
async function filesOutsideInclude(cfg) {
|
|
2292
|
+
if (cfg.include.length === 0) return [];
|
|
2293
|
+
const check = createOutsideCheck(cfg);
|
|
2294
|
+
const files = await glob([`**/*.${SOURCE_EXTENSIONS}`], {
|
|
2295
|
+
cwd: cfg.root,
|
|
2296
|
+
ignore: [...NOT_SOURCE, ...cfg.exclude],
|
|
2297
|
+
absolute: true
|
|
2298
|
+
});
|
|
2299
|
+
const found = [];
|
|
2300
|
+
for (const file of files.sort()) {
|
|
2301
|
+
let code;
|
|
2302
|
+
try {
|
|
2303
|
+
code = readFileSync(file, "utf8");
|
|
2304
|
+
} catch {
|
|
2305
|
+
continue;
|
|
2306
|
+
}
|
|
2307
|
+
const outside = check(code, file);
|
|
2308
|
+
if (outside) found.push(outside);
|
|
1868
2309
|
}
|
|
2310
|
+
return found;
|
|
1869
2311
|
}
|
|
1870
2312
|
//#endregion
|
|
1871
2313
|
//#region src/drafts.ts
|
|
@@ -1878,20 +2320,6 @@ function saveDrafts(cfg, drafts) {
|
|
|
1878
2320
|
drafts
|
|
1879
2321
|
});
|
|
1880
2322
|
}
|
|
1881
|
-
function markDrafts(drafts, locale, keys) {
|
|
1882
|
-
if (!keys.length) return;
|
|
1883
|
-
drafts[locale] = [.../* @__PURE__ */ new Set([...drafts[locale] ?? [], ...keys])];
|
|
1884
|
-
}
|
|
1885
|
-
function clearDrafts(drafts, locale, keys) {
|
|
1886
|
-
if (!drafts[locale]) return;
|
|
1887
|
-
if (!keys) {
|
|
1888
|
-
delete drafts[locale];
|
|
1889
|
-
return;
|
|
1890
|
-
}
|
|
1891
|
-
const drop = new Set(keys);
|
|
1892
|
-
drafts[locale] = drafts[locale].filter((key) => !drop.has(key));
|
|
1893
|
-
if (!drafts[locale].length) delete drafts[locale];
|
|
1894
|
-
}
|
|
1895
2323
|
//#endregion
|
|
1896
2324
|
//#region src/status.ts
|
|
1897
2325
|
function status(cfg, catalogs, registry, drafts = {}, fingerprints = {}) {
|
|
@@ -1901,7 +2329,9 @@ function status(cfg, catalogs, registry, drafts = {}, fingerprints = {}) {
|
|
|
1901
2329
|
const source = flat[cfg.sourceLocale] ?? {};
|
|
1902
2330
|
const needed = /* @__PURE__ */ new Set([...extracted.keys(), ...Object.keys(source)]);
|
|
1903
2331
|
const live = effectiveDrafts(drafts, flat);
|
|
1904
|
-
const
|
|
2332
|
+
const shipped = shippedCatalogs(cfg, flat, registry);
|
|
2333
|
+
const sourceText = shipped[cfg.sourceLocale];
|
|
2334
|
+
const outdated = outdatedTranslations(cfg, shipped, fingerprints);
|
|
1905
2335
|
const locales = [];
|
|
1906
2336
|
for (const locale of cfg.locales) {
|
|
1907
2337
|
if (locale === cfg.sourceLocale) continue;
|
|
@@ -1911,7 +2341,7 @@ function status(cfg, catalogs, registry, drafts = {}, fingerprints = {}) {
|
|
|
1911
2341
|
let broken = 0;
|
|
1912
2342
|
for (const [key, text] of Object.entries(catalog)) {
|
|
1913
2343
|
if (!text) continue;
|
|
1914
|
-
const from =
|
|
2344
|
+
const from = sourceText[key];
|
|
1915
2345
|
if ([...validateMessage(text, locale), ...from ? validatePair(from, text) : []].some((issue) => issue.severity === "error")) broken += 1;
|
|
1916
2346
|
}
|
|
1917
2347
|
locales.push({
|
|
@@ -2053,14 +2483,23 @@ async function doctor(cfg) {
|
|
|
2053
2483
|
const installed = WIRING_PACKAGES.find((pkg) => deps[pkg]);
|
|
2054
2484
|
if (!host) ok("plugin", "no framework or bundler detected, the CLI flow (extract/check) applies");
|
|
2055
2485
|
else if (installed) ok("plugin", `${installed} installed for ${host.name}`);
|
|
2056
|
-
else warn("plugin", `${host.name} detected but ${host.pkg} is not installed`,
|
|
2486
|
+
else warn("plugin", `${host.name} detected but ${host.pkg} is not installed`, `${installCommand(cfg.root, host.install)}, then ${host.wire}`);
|
|
2057
2487
|
const scanning = cfg.include.length > 0;
|
|
2058
2488
|
if (!scanning) ok("sources", "source scanning is off (include: []), the catalogs are the source of truth");
|
|
2059
2489
|
if (source && scanning && cfg.dts !== false) {
|
|
2060
|
-
const dtsPath = cfg.dts
|
|
2061
|
-
|
|
2062
|
-
|
|
2063
|
-
|
|
2490
|
+
const dtsPath = cfg.dts;
|
|
2491
|
+
const shown = rel(dtsPath);
|
|
2492
|
+
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`";
|
|
2493
|
+
const expected = generateDts(source, projectDtsOptions(cfg));
|
|
2494
|
+
if (!existsSync(dtsPath)) warn("types", `${shown} has not been generated`, regenerate);
|
|
2495
|
+
else if (readFileSync(dtsPath, "utf8").replace(/\r\n/g, "\n") !== expected) warn("types", `${shown} is stale`, "run `npx verbaly typegen`");
|
|
2496
|
+
else ok("types", `${shown} is up to date`);
|
|
2497
|
+
if (dtsPath.startsWith(join(cfg.root, ".verbaly"))) {
|
|
2498
|
+
const state = typesIncluded(cfg.root, dtsPath);
|
|
2499
|
+
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`);
|
|
2500
|
+
}
|
|
2501
|
+
const old = join(cfg.root, "verbaly.d.ts");
|
|
2502
|
+
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");
|
|
2064
2503
|
}
|
|
2065
2504
|
const registry = await extractProject(cfg);
|
|
2066
2505
|
if (scanning) {
|
|
@@ -2069,6 +2508,12 @@ async function doctor(cfg) {
|
|
|
2069
2508
|
const first = unreadable[0];
|
|
2070
2509
|
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");
|
|
2071
2510
|
}
|
|
2511
|
+
const outside = await filesOutsideInclude(cfg);
|
|
2512
|
+
if (outside.length > 0) {
|
|
2513
|
+
const files = outside.map((entry) => rel(entry.file));
|
|
2514
|
+
const patterns = [...new Set(outside.map((entry) => `"${entry.pattern}"`))];
|
|
2515
|
+
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`);
|
|
2516
|
+
}
|
|
2072
2517
|
const stray = registry.strayImports();
|
|
2073
2518
|
if (stray.length > 0) {
|
|
2074
2519
|
const files = [...new Set(stray.map((entry) => rel(entry.file)))];
|
|
@@ -2076,15 +2521,13 @@ async function doctor(cfg) {
|
|
|
2076
2521
|
}
|
|
2077
2522
|
const missed = registry.missed();
|
|
2078
2523
|
if (missed.length > 0) {
|
|
2079
|
-
const locate = createLocator();
|
|
2080
2524
|
const first = missed[0];
|
|
2081
|
-
|
|
2082
|
-
warn("sources", `a t under another name keeps ${counted(missed.length, "text")} out of extraction (${rel(first.file)}${line ? `:${line}` : ""}: ${first.name}\`…\`)`, "name it t (const t = useT()), the only name verbaly reads, or use t(key) with the key in the catalog");
|
|
2525
|
+
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");
|
|
2083
2526
|
}
|
|
2084
2527
|
const positional = [...registry.messages().values()].filter((msg) => msg.params.some((param) => /^_\d+$/.test(param.name)));
|
|
2085
2528
|
if (positional.length > 0) {
|
|
2086
2529
|
const first = positional[0];
|
|
2087
|
-
warn("messages", `a translator gets a nameless value like {_0} in ${counted(positional.length, "message")} (${
|
|
2530
|
+
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}");
|
|
2088
2531
|
}
|
|
2089
2532
|
const escaped = [...registry.messages().values()].map((msg) => ({
|
|
2090
2533
|
file: rel(msg.file),
|
|
@@ -2106,15 +2549,8 @@ async function doctor(cfg) {
|
|
|
2106
2549
|
for (const issue of issues) warn("bundle", formatBundleIssue(issue), issue.fix);
|
|
2107
2550
|
if (issues.length === 0) ok("bundle", `${counted(excluded.length, "group")} kept out of the client (${preview(excluded)})`);
|
|
2108
2551
|
}
|
|
2109
|
-
|
|
2110
|
-
|
|
2111
|
-
fingerprints: {}
|
|
2112
|
-
};
|
|
2113
|
-
try {
|
|
2114
|
-
state = loadState(cfg);
|
|
2115
|
-
} catch (error) {
|
|
2116
|
-
warn("state", error.message.replace(/^\[verbaly\] /, ""), `delete ${STATE_FILE}: drafts and outdated tracking start again from the catalogs`);
|
|
2117
|
-
}
|
|
2552
|
+
const { state, problem } = readState(cfg);
|
|
2553
|
+
if (problem) warn("state", problem, `restore ${STATE_FILE} from git: deleting it would mark every machine draft as reviewed`);
|
|
2118
2554
|
if (catalogsHealthy) {
|
|
2119
2555
|
const stale = Object.entries(state.drafts).flatMap(([locale, keys]) => {
|
|
2120
2556
|
const live = new Set(effectiveDrafts({ [locale]: keys }, catalogs)[locale] ?? []);
|
|
@@ -2273,11 +2709,11 @@ async function translateCatalogs(cfg, catalogs, provider, options = {}) {
|
|
|
2273
2709
|
});
|
|
2274
2710
|
for (const locale of Object.keys(result.translated)) result.translated[locale].sort();
|
|
2275
2711
|
for (const locale of Object.keys(result.invalid)) result.invalid[locale].sort();
|
|
2276
|
-
result.failed.sort((a, b) => a.locale
|
|
2712
|
+
result.failed.sort((a, b) => byCodeUnit(a.locale, b.locale) || compare(a.keys, b.keys));
|
|
2277
2713
|
return result;
|
|
2278
2714
|
}
|
|
2279
2715
|
function compare(a, b) {
|
|
2280
|
-
return (a[0] ?? ""
|
|
2716
|
+
return byCodeUnit(a[0] ?? "", b[0] ?? "");
|
|
2281
2717
|
}
|
|
2282
2718
|
function mergeTranslations(cfg, locale, translated, keys) {
|
|
2283
2719
|
const source = readCatalog(cfg, cfg.sourceLocale);
|
|
@@ -2295,7 +2731,9 @@ function mergeTranslations(cfg, locale, translated, keys) {
|
|
|
2295
2731
|
function writeDrafts(cfg, locale, entries, options = {}) {
|
|
2296
2732
|
const targets = targetLocales(cfg);
|
|
2297
2733
|
if (!targets.includes(locale)) throw new Error(`[verbaly] "${locale}" is not a language this project translates into (${targets.join(", ") || "none yet"})`);
|
|
2298
|
-
|
|
2734
|
+
loadState(cfg);
|
|
2735
|
+
const catalogs = { [cfg.sourceLocale]: readCatalog(cfg, cfg.sourceLocale) };
|
|
2736
|
+
const source = options.registry ? shippedCatalogs(cfg, catalogs, options.registry, { newKeys: false })[cfg.sourceLocale] : catalogs[cfg.sourceLocale];
|
|
2299
2737
|
const current = readCatalog(cfg, locale);
|
|
2300
2738
|
const result = {
|
|
2301
2739
|
written: [],
|
|
@@ -2315,9 +2753,14 @@ function writeDrafts(cfg, locale, entries, options = {}) {
|
|
|
2315
2753
|
}
|
|
2316
2754
|
if (result.written.length > 0) {
|
|
2317
2755
|
writeCatalog(cfg, locale, current);
|
|
2318
|
-
|
|
2319
|
-
|
|
2320
|
-
|
|
2756
|
+
recordTranslations(cfg, source, [{
|
|
2757
|
+
locale,
|
|
2758
|
+
entries: result.written.map((key) => ({
|
|
2759
|
+
key,
|
|
2760
|
+
text: current[key]
|
|
2761
|
+
})),
|
|
2762
|
+
draft: true
|
|
2763
|
+
}]);
|
|
2321
2764
|
}
|
|
2322
2765
|
return result;
|
|
2323
2766
|
}
|
|
@@ -2336,7 +2779,7 @@ function formatTranslateFailures(failed) {
|
|
|
2336
2779
|
async function resolveProvider(cfg, model) {
|
|
2337
2780
|
const configured = cfg.translate.provider;
|
|
2338
2781
|
if (typeof configured === "function") return configured;
|
|
2339
|
-
const { claudeProvider } = await import("./claude-
|
|
2782
|
+
const { claudeProvider } = await import("./claude-mvcniUPN.js");
|
|
2340
2783
|
return claudeProvider({ model: model ?? cfg.translate.model });
|
|
2341
2784
|
}
|
|
2342
2785
|
function structureMatches(source, translated) {
|
|
@@ -2645,7 +3088,7 @@ async function renderSite(cfg, options = {}) {
|
|
|
2645
3088
|
base,
|
|
2646
3089
|
storageKey: redirect.storageKey
|
|
2647
3090
|
};
|
|
2648
|
-
const catalogs = loadCatalogs(cfg);
|
|
3091
|
+
const catalogs = shippedCatalogs(cfg, loadCatalogs(cfg), await extractProject(cfg));
|
|
2649
3092
|
const instances = new Map(locales.map((locale) => [locale, localeInstance(catalogs, locale, cfg.sourceLocale)]));
|
|
2650
3093
|
if (clean) {
|
|
2651
3094
|
for (const locale of locales) if (locale !== cfg.sourceLocale) rmSync(join(site, locale), {
|
|
@@ -3138,6 +3581,6 @@ function formatCliError(error) {
|
|
|
3138
3581
|
return message.startsWith("[verbaly]") ? message : `[verbaly] ${message}`;
|
|
3139
3582
|
}
|
|
3140
3583
|
//#endregion
|
|
3141
|
-
export { LOCALE_MODULE_PREFIX, MessageRegistry, RESOLVED_VIRTUAL_ID, SOURCE_FILE_RE, STATE_FILE, check, clearDrafts, clientCatalogs, collectOrigins, collisionEntries, counted, createSourceFilter, doctor, effectiveDrafts, extractProject, formatCheckResult, formatCheckWarnings, formatCliError, formatCollision, formatDoctorEntry, formatRenderWarnings, formatStatusResult, formatTranslateFailures, generateDts, generateLocaleModule, generateRuntimeModule, init, isTransformTarget, loadCatalogs, loadConfig, loadDrafts, loadState, loadVirtualModule, markDrafts, mergeTranslations, needsIcu, needsRelative, outdatedTranslations, parseCatalog, pruneCatalogs, readCatalog, renderSite, resolveConfig, resolveProvider, resolveVirtualId, runBuildGate, saveDrafts, stableKey, status, syncCatalogs, targetLocales, transformCode, transformSource, translateCatalogs, updateState, validateMessage, validatePair, watchTree, wrapProject, writeCatalog, writeDrafts, writeDts };
|
|
3584
|
+
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, 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 };
|
|
3142
3585
|
|
|
3143
3586
|
//# sourceMappingURL=index.js.map
|