@verbaly/compiler 0.45.0 → 0.46.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-DAzXUvmS.js → claude-B-vethK9.js} +2 -2
- package/dist/{claude-DAzXUvmS.js.map → claude-B-vethK9.js.map} +1 -1
- package/dist/cli.js +807 -713
- package/dist/cli.js.map +1 -1
- package/dist/{config-ByO-vjIC.js → config-iLrfRYDB.js} +4 -2
- package/dist/config-iLrfRYDB.js.map +1 -0
- package/dist/index.d.ts +8 -1
- package/dist/index.js +164 -89
- package/dist/index.js.map +1 -1
- package/package.json +4 -4
- package/dist/config-ByO-vjIC.js.map +0 -1
package/dist/cli.js
CHANGED
|
@@ -104,99 +104,423 @@ function wantsNesting(cfg, locale, existing) {
|
|
|
104
104
|
return isNested(readTree(cfg, cfg.sourceLocale));
|
|
105
105
|
}
|
|
106
106
|
//#endregion
|
|
107
|
-
//#region src/
|
|
108
|
-
const
|
|
109
|
-
|
|
110
|
-
"
|
|
111
|
-
"
|
|
112
|
-
"
|
|
113
|
-
"
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
107
|
+
//#region src/pseudo.ts
|
|
108
|
+
const PSEUDO_LOCALE = "en-XA";
|
|
109
|
+
const ACCENTS = {
|
|
110
|
+
a: "á",
|
|
111
|
+
b: "ƀ",
|
|
112
|
+
c: "ç",
|
|
113
|
+
d: "đ",
|
|
114
|
+
e: "é",
|
|
115
|
+
f: "ƒ",
|
|
116
|
+
g: "ğ",
|
|
117
|
+
h: "ĥ",
|
|
118
|
+
i: "í",
|
|
119
|
+
j: "ĵ",
|
|
120
|
+
k: "ķ",
|
|
121
|
+
l: "ĺ",
|
|
122
|
+
m: "ɱ",
|
|
123
|
+
n: "ñ",
|
|
124
|
+
o: "ó",
|
|
125
|
+
p: "þ",
|
|
126
|
+
q: "ǫ",
|
|
127
|
+
r: "ŕ",
|
|
128
|
+
s: "š",
|
|
129
|
+
t: "ţ",
|
|
130
|
+
u: "ú",
|
|
131
|
+
v: "ṽ",
|
|
132
|
+
w: "ŵ",
|
|
133
|
+
x: "ẋ",
|
|
134
|
+
y: "ý",
|
|
135
|
+
z: "ž",
|
|
136
|
+
A: "Á",
|
|
137
|
+
B: "Ɓ",
|
|
138
|
+
C: "Ç",
|
|
139
|
+
D: "Đ",
|
|
140
|
+
E: "É",
|
|
141
|
+
F: "Ƒ",
|
|
142
|
+
G: "Ğ",
|
|
143
|
+
H: "Ĥ",
|
|
144
|
+
I: "Í",
|
|
145
|
+
J: "Ĵ",
|
|
146
|
+
K: "Ķ",
|
|
147
|
+
L: "Ĺ",
|
|
148
|
+
M: "Ḿ",
|
|
149
|
+
N: "Ñ",
|
|
150
|
+
O: "Ó",
|
|
151
|
+
P: "Þ",
|
|
152
|
+
Q: "Ǫ",
|
|
153
|
+
R: "Ŕ",
|
|
154
|
+
S: "Š",
|
|
155
|
+
T: "Ţ",
|
|
156
|
+
U: "Ú",
|
|
157
|
+
V: "Ṽ",
|
|
158
|
+
W: "Ŵ",
|
|
159
|
+
X: "Ẍ",
|
|
160
|
+
Y: "Ý",
|
|
161
|
+
Z: "Ž"
|
|
162
|
+
};
|
|
163
|
+
const TAG_AT = /<\/?[a-zA-Z][\w-]*\/?>/y;
|
|
164
|
+
function pseudoLocalize(message) {
|
|
165
|
+
let out = "";
|
|
166
|
+
let letters = 0;
|
|
167
|
+
let i = 0;
|
|
168
|
+
while (i < message.length) {
|
|
169
|
+
const two = message.slice(i, i + 2);
|
|
170
|
+
if (two === "{{" || two === "}}" || two === "||" || two === "##") {
|
|
171
|
+
out += two;
|
|
172
|
+
i += 2;
|
|
173
|
+
continue;
|
|
174
|
+
}
|
|
175
|
+
const ch = message[i];
|
|
176
|
+
if (ch === "{") {
|
|
177
|
+
const end = matchBrace$1(message, i);
|
|
178
|
+
out += message.slice(i, end);
|
|
179
|
+
i = end;
|
|
180
|
+
continue;
|
|
181
|
+
}
|
|
182
|
+
if (ch === "<") {
|
|
183
|
+
TAG_AT.lastIndex = i;
|
|
184
|
+
const m = TAG_AT.exec(message);
|
|
185
|
+
if (m) {
|
|
186
|
+
out += m[0];
|
|
187
|
+
i += m[0].length;
|
|
188
|
+
continue;
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
const mapped = ACCENTS[ch];
|
|
192
|
+
if (mapped) {
|
|
193
|
+
out += mapped;
|
|
194
|
+
letters += 1;
|
|
195
|
+
} else out += ch;
|
|
196
|
+
i += 1;
|
|
197
|
+
}
|
|
198
|
+
const pad = "~".repeat(Math.ceil(letters / 3));
|
|
199
|
+
return `⟦${out}${pad ? " " + pad : ""}⟧`;
|
|
120
200
|
}
|
|
121
|
-
function
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
const
|
|
125
|
-
if (
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
201
|
+
function matchBrace$1(message, start) {
|
|
202
|
+
let depth = 0;
|
|
203
|
+
for (let i = start; i < message.length; i++) {
|
|
204
|
+
const two = message.slice(i, i + 2);
|
|
205
|
+
if (two === "{{" || two === "}}") {
|
|
206
|
+
i += 1;
|
|
207
|
+
continue;
|
|
208
|
+
}
|
|
209
|
+
const ch = message[i];
|
|
210
|
+
if (ch === "{") depth += 1;
|
|
211
|
+
else if (ch === "}") {
|
|
212
|
+
depth -= 1;
|
|
213
|
+
if (depth === 0) return i + 1;
|
|
214
|
+
}
|
|
131
215
|
}
|
|
216
|
+
return message.length;
|
|
132
217
|
}
|
|
133
|
-
function
|
|
134
|
-
const
|
|
135
|
-
|
|
136
|
-
|
|
218
|
+
function pseudoCatalogs(cfg, catalogs, locale = PSEUDO_LOCALE) {
|
|
219
|
+
const source = catalogs[cfg.sourceLocale] ?? {};
|
|
220
|
+
const target = {};
|
|
221
|
+
for (const [key, msg] of Object.entries(source)) target[key] = msg ? pseudoLocalize(msg) : "";
|
|
222
|
+
catalogs[locale] = target;
|
|
223
|
+
return Object.keys(target).filter((key) => target[key]);
|
|
137
224
|
}
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
225
|
+
//#endregion
|
|
226
|
+
//#region src/config.ts
|
|
227
|
+
function resolveConfig(config = {}) {
|
|
228
|
+
const root = resolve(config.root ?? process.cwd());
|
|
229
|
+
const dir = resolve(root, config.dir ?? "locales");
|
|
230
|
+
const sourceLocale = config.sourceLocale ?? "en";
|
|
231
|
+
const localesDeclared = config.locales !== void 0;
|
|
232
|
+
const locales = /* @__PURE__ */ new Set([sourceLocale, ...config.locales ?? []]);
|
|
233
|
+
if (!localesDeclared && existsSync(dir)) {
|
|
234
|
+
for (const file of readdirSync(dir)) if (file.endsWith(".json") && !file.startsWith(".") && file !== `en-XA.json`) locales.add(file.slice(0, -5));
|
|
143
235
|
}
|
|
236
|
+
return {
|
|
237
|
+
root,
|
|
238
|
+
dir,
|
|
239
|
+
sourceLocale,
|
|
240
|
+
localesDeclared,
|
|
241
|
+
routing: config.routing ?? (config.render ? "prefix-except-source" : "no-prefix"),
|
|
242
|
+
icu: config.icu,
|
|
243
|
+
relative: config.relative,
|
|
244
|
+
locales: [...locales],
|
|
245
|
+
include: config.include ?? ["{src,app}/**/*.{js,jsx,ts,tsx,mjs,mts,svelte,vue,astro}"],
|
|
246
|
+
exclude: config.exclude ?? ["**/node_modules/**", "**/dist/**"],
|
|
247
|
+
dts: typeof config.dts === "string" ? resolve(root, config.dts) : config.dts,
|
|
248
|
+
translate: config.translate ?? {},
|
|
249
|
+
render: config.render ?? {},
|
|
250
|
+
bundle: config.bundle ?? {}
|
|
251
|
+
};
|
|
144
252
|
}
|
|
145
|
-
const
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
return out.sort();
|
|
253
|
+
const CONFIG_FILES = [
|
|
254
|
+
"verbaly.config.js",
|
|
255
|
+
"verbaly.config.mjs",
|
|
256
|
+
"verbaly.config.ts",
|
|
257
|
+
"verbaly.config.mts",
|
|
258
|
+
"verbaly.config.json"
|
|
259
|
+
];
|
|
260
|
+
function findConfigFile(root) {
|
|
261
|
+
return CONFIG_FILES.find((name) => existsSync(join(root, name)));
|
|
155
262
|
}
|
|
156
|
-
function
|
|
157
|
-
const
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
const at = rest.indexOf(item);
|
|
161
|
-
if (at < 0) out.push(item);
|
|
162
|
-
else rest.splice(at, 1);
|
|
263
|
+
async function loadConfigFile(root) {
|
|
264
|
+
for (const name of ["verbaly.config.js", "verbaly.config.mjs"]) {
|
|
265
|
+
const path = join(root, name);
|
|
266
|
+
if (existsSync(path)) return (await import(pathToFileURL(path).href)).default ?? {};
|
|
163
267
|
}
|
|
164
|
-
|
|
268
|
+
for (const name of ["verbaly.config.ts", "verbaly.config.mts"]) {
|
|
269
|
+
const path = join(root, name);
|
|
270
|
+
if (existsSync(path)) return loadTsConfig(path);
|
|
271
|
+
}
|
|
272
|
+
const jsonPath = join(root, "verbaly.config.json");
|
|
273
|
+
if (existsSync(jsonPath)) return JSON.parse(readFileSync(jsonPath, "utf8"));
|
|
274
|
+
return {};
|
|
165
275
|
}
|
|
166
|
-
function
|
|
167
|
-
|
|
276
|
+
async function loadTsConfig(path) {
|
|
277
|
+
try {
|
|
278
|
+
const { bundleRequire } = await import("bundle-require");
|
|
279
|
+
const { mod } = await bundleRequire({ filepath: path });
|
|
280
|
+
return mod.default ?? {};
|
|
281
|
+
} catch (error) {
|
|
282
|
+
if (isModuleNotFound(error, "esbuild")) throw new Error(`[verbaly] ${path} needs esbuild: install it with pnpm add -D esbuild`, { cause: error });
|
|
283
|
+
throw error;
|
|
284
|
+
}
|
|
168
285
|
}
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
return ESCAPED_SYNTAX.exec(message)?.[0];
|
|
286
|
+
function isModuleNotFound(error, name) {
|
|
287
|
+
return error instanceof Error && error.code === "ERR_MODULE_NOT_FOUND" && error.message.includes(name);
|
|
172
288
|
}
|
|
173
|
-
function
|
|
174
|
-
|
|
175
|
-
for (const [name, shape] of shapes(message)) {
|
|
176
|
-
if (!shape.plural) continue;
|
|
177
|
-
if (!shape.selectors.includes("other")) {
|
|
178
|
-
issues.push({
|
|
179
|
-
severity: "error",
|
|
180
|
-
message: `the plural block for {${name}} has no "other" case, so any count it does not list renders empty`
|
|
181
|
-
});
|
|
182
|
-
continue;
|
|
183
|
-
}
|
|
184
|
-
if (!locale) continue;
|
|
185
|
-
const missing = reachableCategories(locale, shape.ordinal).filter((category) => category !== "other" && !shape.selectors.includes(category));
|
|
186
|
-
if (missing.length > 0) issues.push({
|
|
187
|
-
severity: "warning",
|
|
188
|
-
message: `${locale} also needs the ${list(missing)} plural ${missing.length > 1 ? "forms" : "form"} for {${name}}`
|
|
189
|
-
});
|
|
190
|
-
}
|
|
191
|
-
return issues;
|
|
289
|
+
function targetLocales(cfg, override) {
|
|
290
|
+
return (override ?? cfg.locales).filter((locale) => locale !== cfg.sourceLocale && cfg.locales.includes(locale));
|
|
192
291
|
}
|
|
193
|
-
function
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
292
|
+
async function loadConfig(root, overrides = {}) {
|
|
293
|
+
return resolveConfig({
|
|
294
|
+
...await loadConfigFile(root),
|
|
295
|
+
...definedOnly(overrides),
|
|
296
|
+
root
|
|
297
|
+
});
|
|
298
|
+
}
|
|
299
|
+
function definedOnly(config) {
|
|
300
|
+
return Object.fromEntries(Object.entries(config).filter(([, value]) => value !== void 0));
|
|
301
|
+
}
|
|
302
|
+
//#endregion
|
|
303
|
+
//#region src/init.ts
|
|
304
|
+
const HOSTS = [
|
|
305
|
+
{
|
|
306
|
+
name: "nuxt",
|
|
307
|
+
dep: "nuxt",
|
|
308
|
+
pkg: "@verbaly/nuxt",
|
|
309
|
+
wire: "add '@verbaly/nuxt' to the modules in nuxt.config"
|
|
310
|
+
},
|
|
311
|
+
{
|
|
312
|
+
name: "next",
|
|
313
|
+
dep: "next",
|
|
314
|
+
pkg: "@verbaly/next",
|
|
315
|
+
wire: "wrap the export of next.config with withVerbaly"
|
|
316
|
+
},
|
|
317
|
+
{
|
|
318
|
+
name: "sveltekit",
|
|
319
|
+
dep: "@sveltejs/kit",
|
|
320
|
+
pkg: "@verbaly/vite",
|
|
321
|
+
wire: "add verbaly() to the plugins in vite.config (per-request locale: @verbaly/sveltekit)"
|
|
322
|
+
},
|
|
323
|
+
{
|
|
324
|
+
name: "astro",
|
|
325
|
+
dep: "astro",
|
|
326
|
+
pkg: "@verbaly/astro",
|
|
327
|
+
wire: "add verbaly() to the integrations in astro.config"
|
|
328
|
+
},
|
|
329
|
+
{
|
|
330
|
+
name: "vite",
|
|
331
|
+
dep: "vite",
|
|
332
|
+
pkg: "@verbaly/vite",
|
|
333
|
+
wire: "add verbaly() to the plugins in vite.config"
|
|
334
|
+
},
|
|
335
|
+
{
|
|
336
|
+
name: "webpack",
|
|
337
|
+
dep: "webpack",
|
|
338
|
+
pkg: "@verbaly/unplugin",
|
|
339
|
+
wire: "add the verbaly webpack plugin to your build config"
|
|
340
|
+
},
|
|
341
|
+
{
|
|
342
|
+
name: "rspack",
|
|
343
|
+
dep: "@rspack/core",
|
|
344
|
+
pkg: "@verbaly/unplugin",
|
|
345
|
+
wire: "add the verbaly rspack plugin to your build config"
|
|
346
|
+
},
|
|
347
|
+
{
|
|
348
|
+
name: "rollup",
|
|
349
|
+
dep: "rollup",
|
|
350
|
+
pkg: "@verbaly/unplugin",
|
|
351
|
+
wire: "add the verbaly rollup plugin to your build config"
|
|
352
|
+
},
|
|
353
|
+
{
|
|
354
|
+
name: "esbuild",
|
|
355
|
+
dep: "esbuild",
|
|
356
|
+
pkg: "@verbaly/unplugin",
|
|
357
|
+
wire: "add the verbaly esbuild plugin to your build config"
|
|
358
|
+
}
|
|
359
|
+
];
|
|
360
|
+
const WIRING_PACKAGES = [...new Set(HOSTS.map((host) => host.pkg))];
|
|
361
|
+
function readDependencies(root) {
|
|
362
|
+
const path = join(root, "package.json");
|
|
363
|
+
if (!existsSync(path)) return {};
|
|
364
|
+
try {
|
|
365
|
+
const pkg = JSON.parse(readFileSync(path, "utf8"));
|
|
366
|
+
return {
|
|
367
|
+
...pkg.dependencies,
|
|
368
|
+
...pkg.devDependencies
|
|
369
|
+
};
|
|
370
|
+
} catch {
|
|
371
|
+
return {};
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
function cliReachable(root) {
|
|
375
|
+
const bin = join(root, "node_modules", ".bin");
|
|
376
|
+
return existsSync(join(bin, "verbaly")) || existsSync(join(bin, "verbaly.CMD"));
|
|
377
|
+
}
|
|
378
|
+
const CLI_INSTALL_FIX = "add `@verbaly/compiler` to your dev dependencies, then `npx verbaly` resolves";
|
|
379
|
+
function detectHost(root) {
|
|
380
|
+
const deps = readDependencies(root);
|
|
381
|
+
return HOSTS.find((host) => deps[host.dep]);
|
|
382
|
+
}
|
|
383
|
+
function configSource(options, typescript) {
|
|
384
|
+
const fields = [` sourceLocale: '${options.sourceLocale ?? "en"}',`];
|
|
385
|
+
if (options.locales?.length) fields.push(` locales: [${options.locales.map((l) => `'${l}'`).join(", ")}],`);
|
|
386
|
+
if (options.dir) fields.push(` dir: '${options.dir}',`);
|
|
387
|
+
const body = `export default {\n${fields.join("\n")}\n}`;
|
|
388
|
+
if (typescript) return `import type { VerbalyConfig } from '@verbaly/compiler';\n\n${body} satisfies VerbalyConfig;\n`;
|
|
389
|
+
return `/** @type {import('@verbaly/compiler').VerbalyConfig} */\n${body};\n`;
|
|
390
|
+
}
|
|
391
|
+
async function init(options = {}) {
|
|
392
|
+
const root = options.root ?? process.cwd();
|
|
393
|
+
const created = [];
|
|
394
|
+
const skipped = [];
|
|
395
|
+
const existing = findConfigFile(root);
|
|
396
|
+
const typescript = existsSync(join(root, "tsconfig.json"));
|
|
397
|
+
const configFile = existing ?? (typescript ? "verbaly.config.ts" : "verbaly.config.mjs");
|
|
398
|
+
if (existing) skipped.push(existing);
|
|
399
|
+
else {
|
|
400
|
+
writeFileSync(join(root, configFile), configSource(options, typescript));
|
|
401
|
+
created.push(configFile);
|
|
402
|
+
}
|
|
403
|
+
const fromFile = existing ? await loadConfigFile(root) : {};
|
|
404
|
+
const scaffold = {
|
|
405
|
+
dir: options.dir ?? fromFile.dir,
|
|
406
|
+
sourceLocale: options.sourceLocale ?? fromFile.sourceLocale,
|
|
407
|
+
locales: options.locales ?? fromFile.locales
|
|
408
|
+
};
|
|
409
|
+
const dir = join(root, scaffold.dir ?? "locales");
|
|
410
|
+
if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
|
|
411
|
+
for (const locale of /* @__PURE__ */ new Set([scaffold.sourceLocale ?? "en", ...scaffold.locales ?? []])) {
|
|
412
|
+
const file = join(dir, `${locale}.json`);
|
|
413
|
+
const label = relative(root, file).replaceAll("\\", "/");
|
|
414
|
+
if (existsSync(file)) skipped.push(label);
|
|
415
|
+
else {
|
|
416
|
+
writeFileSync(file, "{}\n");
|
|
417
|
+
created.push(label);
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
const host = detectHost(root);
|
|
421
|
+
const next = host ? [`pnpm add -D ${host.pkg}`, host.wire] : ["run \"verbaly extract\" after writing your first t`…` message"];
|
|
422
|
+
return {
|
|
423
|
+
created,
|
|
424
|
+
skipped,
|
|
425
|
+
host: host?.name,
|
|
426
|
+
configFile,
|
|
427
|
+
next
|
|
428
|
+
};
|
|
429
|
+
}
|
|
430
|
+
//#endregion
|
|
431
|
+
//#region src/validate.ts
|
|
432
|
+
const PLURAL_CATEGORIES = /* @__PURE__ */ new Set([
|
|
433
|
+
"zero",
|
|
434
|
+
"one",
|
|
435
|
+
"two",
|
|
436
|
+
"few",
|
|
437
|
+
"many"
|
|
438
|
+
]);
|
|
439
|
+
const EXACT = /^=\d+$/;
|
|
440
|
+
function shapes(message) {
|
|
441
|
+
const out = /* @__PURE__ */ new Map();
|
|
442
|
+
walk$1(parse(message), out);
|
|
443
|
+
return out;
|
|
444
|
+
}
|
|
445
|
+
function walk$1(nodes, out) {
|
|
446
|
+
for (const node of nodes) {
|
|
447
|
+
if (node.kind !== "param" || !node.variants) continue;
|
|
448
|
+
const selectors = node.variants.map(([key]) => key);
|
|
449
|
+
if (!out.has(node.name)) out.set(node.name, {
|
|
450
|
+
selectors,
|
|
451
|
+
plural: selectors.some((key) => PLURAL_CATEGORIES.has(key)),
|
|
452
|
+
ordinal: node.ordinal === true
|
|
453
|
+
});
|
|
454
|
+
for (const [, body] of node.variants) walk$1(body, out);
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
function paramNames(message) {
|
|
458
|
+
const names = /* @__PURE__ */ new Set();
|
|
459
|
+
collect(parse(message), names);
|
|
460
|
+
return [...names].sort();
|
|
461
|
+
}
|
|
462
|
+
function collect(nodes, out) {
|
|
463
|
+
for (const node of nodes) {
|
|
464
|
+
if (node.kind !== "param") continue;
|
|
465
|
+
out.add(node.name);
|
|
466
|
+
if (node.variants) for (const [, body] of node.variants) collect(body, out);
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
const TAG = /<(\/?)([a-zA-Z][\w-]*)(\/?)>/g;
|
|
470
|
+
function markupNames(message) {
|
|
471
|
+
const out = /* @__PURE__ */ new Set();
|
|
472
|
+
for (const match of message.matchAll(TAG)) if (match[1] || match[3]) out.add(match[2]);
|
|
473
|
+
return out;
|
|
474
|
+
}
|
|
475
|
+
function tagTokens(message, markup) {
|
|
476
|
+
const out = [];
|
|
477
|
+
for (const match of message.matchAll(TAG)) if (markup.has(match[2])) out.push(`${match[1]}${match[2]}${match[3]}`);
|
|
478
|
+
return out.sort();
|
|
479
|
+
}
|
|
480
|
+
function surplus(a, b) {
|
|
481
|
+
const rest = [...b];
|
|
482
|
+
const out = [];
|
|
483
|
+
for (const item of a) {
|
|
484
|
+
const at = rest.indexOf(item);
|
|
485
|
+
if (at < 0) out.push(item);
|
|
486
|
+
else rest.splice(at, 1);
|
|
487
|
+
}
|
|
488
|
+
return out;
|
|
489
|
+
}
|
|
490
|
+
function list(items) {
|
|
491
|
+
return items.length > 1 ? `${items.slice(0, -1).join(", ")} and ${items[items.length - 1]}` : items[0];
|
|
492
|
+
}
|
|
493
|
+
const ESCAPED_SYNTAX = /(?<!\{)\{\{\s*[\w.]+\s*[|:][^{}]*\}\}/;
|
|
494
|
+
function escapedSyntax(message) {
|
|
495
|
+
return ESCAPED_SYNTAX.exec(message)?.[0];
|
|
496
|
+
}
|
|
497
|
+
function validateMessage(message, locale) {
|
|
498
|
+
const issues = [];
|
|
499
|
+
for (const [name, shape] of shapes(message)) {
|
|
500
|
+
if (!shape.plural) continue;
|
|
501
|
+
if (!shape.selectors.includes("other")) {
|
|
502
|
+
issues.push({
|
|
503
|
+
severity: "error",
|
|
504
|
+
message: `the plural block for {${name}} has no "other" case, so any count it does not list renders empty`
|
|
505
|
+
});
|
|
506
|
+
continue;
|
|
507
|
+
}
|
|
508
|
+
if (!locale) continue;
|
|
509
|
+
const missing = reachableCategories(locale, shape.ordinal).filter((category) => category !== "other" && !shape.selectors.includes(category));
|
|
510
|
+
if (missing.length > 0) issues.push({
|
|
511
|
+
severity: "warning",
|
|
512
|
+
message: `${locale} also needs the ${list(missing)} plural ${missing.length > 1 ? "forms" : "form"} for {${name}}`
|
|
513
|
+
});
|
|
514
|
+
}
|
|
515
|
+
return issues;
|
|
516
|
+
}
|
|
517
|
+
function validatePair(source, translated) {
|
|
518
|
+
const issues = [];
|
|
519
|
+
const lostParams = surplus(paramNames(source), paramNames(translated));
|
|
520
|
+
const newParams = surplus(paramNames(translated), paramNames(source));
|
|
521
|
+
if (lostParams.length > 0) issues.push({
|
|
522
|
+
severity: "error",
|
|
523
|
+
message: `${list(lostParams.map((name) => `{${name}}`))} ${lostParams.length > 1 ? "are" : "is"} missing, so ${lostParams.length > 1 ? "their values" : "its value"} never reaches the text`
|
|
200
524
|
});
|
|
201
525
|
if (newParams.length > 0) issues.push({
|
|
202
526
|
severity: "error",
|
|
@@ -216,526 +540,333 @@ function validatePair(source, translated) {
|
|
|
216
540
|
const target = shapes(translated);
|
|
217
541
|
for (const [name, shape] of shapes(source)) {
|
|
218
542
|
const other = target.get(name);
|
|
219
|
-
if (!other) {
|
|
220
|
-
issues.push({
|
|
221
|
-
severity: "error",
|
|
222
|
-
message: `the ${shape.plural ? "plural" : "select"} block for {${name}} was flattened into plain text`
|
|
223
|
-
});
|
|
224
|
-
continue;
|
|
225
|
-
}
|
|
226
|
-
if (shape.selectors.includes("other") && !other.selectors.includes("other") && !other.plural) issues.push({
|
|
227
|
-
severity: "error",
|
|
228
|
-
message: `the "other" case for {${name}} is missing, so unlisted values render empty`
|
|
229
|
-
});
|
|
230
|
-
const lostExact = shape.selectors.filter((key) => EXACT.test(key)).filter((key) => !other.selectors.includes(key));
|
|
231
|
-
if (lostExact.length > 0) issues.push({
|
|
232
|
-
severity: "warning",
|
|
233
|
-
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"`
|
|
234
|
-
});
|
|
235
|
-
}
|
|
236
|
-
return issues;
|
|
237
|
-
}
|
|
238
|
-
function tagReport(tokens) {
|
|
239
|
-
const out = [];
|
|
240
|
-
const seen = /* @__PURE__ */ new Set();
|
|
241
|
-
for (const token of tokens) {
|
|
242
|
-
const name = token.replaceAll("/", "");
|
|
243
|
-
if (seen.has(name)) continue;
|
|
244
|
-
seen.add(name);
|
|
245
|
-
out.push(token.endsWith("/") ? `<${name}/>` : `<${name}>`);
|
|
246
|
-
}
|
|
247
|
-
return out;
|
|
248
|
-
}
|
|
249
|
-
const COUNT_PROBE = 200;
|
|
250
|
-
const reachable = /* @__PURE__ */ new Map();
|
|
251
|
-
function reachableCategories(locale, ordinal) {
|
|
252
|
-
const type = ordinal ? "ordinal" : "cardinal";
|
|
253
|
-
const cacheKey = `${locale}\u0000${type}`;
|
|
254
|
-
const hit = reachable.get(cacheKey);
|
|
255
|
-
if (hit) return hit;
|
|
256
|
-
let out;
|
|
257
|
-
try {
|
|
258
|
-
const rules = new Intl.PluralRules(locale, { type });
|
|
259
|
-
const seen = /* @__PURE__ */ new Set();
|
|
260
|
-
for (let n = 0; n <= COUNT_PROBE; n++) seen.add(rules.select(n));
|
|
261
|
-
out = [...seen];
|
|
262
|
-
} catch {
|
|
263
|
-
out = [];
|
|
264
|
-
}
|
|
265
|
-
reachable.set(cacheKey, out);
|
|
266
|
-
return out;
|
|
267
|
-
}
|
|
268
|
-
//#endregion
|
|
269
|
-
//#region src/check.ts
|
|
270
|
-
function gatePasses(result) {
|
|
271
|
-
return result.missing.length === 0 && result.unknown.length === 0 && !result.broken.some((entry) => entry.severity === "error");
|
|
272
|
-
}
|
|
273
|
-
function check(cfg, catalogs, registry) {
|
|
274
|
-
const extracted = registry.messages();
|
|
275
|
-
const flat = {};
|
|
276
|
-
for (const locale of cfg.locales) flat[locale] = flatten(catalogs[locale] ?? {});
|
|
277
|
-
const source = flat[cfg.sourceLocale] ?? {};
|
|
278
|
-
const unknown = [];
|
|
279
|
-
for (const [key, files] of registry.usedKeys()) if (!(extracted.has(key) || cfg.locales.some((locale) => flat[locale]?.[key] !== void 0))) unknown.push({
|
|
280
|
-
key,
|
|
281
|
-
files
|
|
282
|
-
});
|
|
283
|
-
const needed = /* @__PURE__ */ new Set([...extracted.keys(), ...Object.keys(source)]);
|
|
284
|
-
const missing = [];
|
|
285
|
-
for (const key of extracted.keys()) if (!source[key]) missing.push({
|
|
286
|
-
locale: cfg.sourceLocale,
|
|
287
|
-
key,
|
|
288
|
-
source: extracted.get(key)?.message
|
|
289
|
-
});
|
|
290
|
-
for (const locale of cfg.locales) {
|
|
291
|
-
if (locale === cfg.sourceLocale) continue;
|
|
292
|
-
for (const key of needed) if (!flat[locale]?.[key]) missing.push({
|
|
293
|
-
locale,
|
|
294
|
-
key,
|
|
295
|
-
source: source[key] ?? extracted.get(key)?.message
|
|
296
|
-
});
|
|
297
|
-
}
|
|
298
|
-
const broken = [];
|
|
299
|
-
const add = (locale, key, issues) => {
|
|
300
|
-
for (const issue of issues) broken.push({
|
|
301
|
-
locale,
|
|
302
|
-
key,
|
|
303
|
-
severity: issue.severity,
|
|
304
|
-
issue: issue.message
|
|
305
|
-
});
|
|
306
|
-
};
|
|
307
|
-
const sourceText = { ...source };
|
|
308
|
-
for (const [key, entry] of extracted) if (!sourceText[key]) sourceText[key] = entry.message;
|
|
309
|
-
for (const [key, text] of Object.entries(sourceText)) add(cfg.sourceLocale, key, validateMessage(text, cfg.sourceLocale));
|
|
310
|
-
for (const locale of cfg.locales) {
|
|
311
|
-
if (locale === cfg.sourceLocale) continue;
|
|
312
|
-
for (const [key, translated] of Object.entries(flat[locale] ?? {})) {
|
|
313
|
-
if (!translated) continue;
|
|
314
|
-
add(locale, key, validateMessage(translated, locale));
|
|
315
|
-
const text = sourceText[key];
|
|
316
|
-
if (text) add(locale, key, validatePair(text, translated));
|
|
317
|
-
}
|
|
318
|
-
}
|
|
319
|
-
return {
|
|
320
|
-
ok: gatePasses({
|
|
321
|
-
missing,
|
|
322
|
-
unknown,
|
|
323
|
-
broken
|
|
324
|
-
}),
|
|
325
|
-
missing,
|
|
326
|
-
unknown,
|
|
327
|
-
broken
|
|
328
|
-
};
|
|
329
|
-
}
|
|
330
|
-
function formatCheckResult(result) {
|
|
331
|
-
const lines = [];
|
|
332
|
-
if (result.missing.length > 0) {
|
|
333
|
-
lines.push("missing translations:");
|
|
334
|
-
for (const entry of result.missing) {
|
|
335
|
-
const hint = entry.source ? `: "${truncate(entry.source, 40)}"` : "";
|
|
336
|
-
lines.push(` [${entry.locale}] ${entry.key}${hint}`);
|
|
337
|
-
}
|
|
338
|
-
}
|
|
339
|
-
if (result.unknown.length > 0) {
|
|
340
|
-
lines.push("unknown keys (not in any catalog):");
|
|
341
|
-
for (const entry of result.unknown) lines.push(` ${entry.key} (used in ${entry.files.join(", ")})`);
|
|
342
|
-
}
|
|
343
|
-
const errors = result.broken.filter((entry) => entry.severity === "error");
|
|
344
|
-
if (errors.length > 0) {
|
|
345
|
-
lines.push("broken translations:");
|
|
346
|
-
for (const entry of errors) lines.push(` [${entry.locale}] ${entry.key}: ${entry.issue}`);
|
|
347
|
-
}
|
|
348
|
-
return lines.join("\n");
|
|
349
|
-
}
|
|
350
|
-
function checkNextSteps(result) {
|
|
351
|
-
const steps = [];
|
|
352
|
-
if (result.missing.length > 0) steps.push("missing: run `npx verbaly extract` to scaffold the keys, then fill them (or run `npx verbaly translate`)");
|
|
353
|
-
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`");
|
|
354
|
-
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");
|
|
355
|
-
return steps.join("\n");
|
|
356
|
-
}
|
|
357
|
-
function formatCheckWarnings(result) {
|
|
358
|
-
return result.broken.filter((entry) => entry.severity === "warning").map((entry) => ` [${entry.locale}] ${entry.key}: ${entry.issue}`).join("\n");
|
|
359
|
-
}
|
|
360
|
-
function truncate(text, max) {
|
|
361
|
-
return text.length > max ? text.slice(0, max - 1) + "…" : text;
|
|
362
|
-
}
|
|
363
|
-
function githubCheckAnnotations(result, registry, root) {
|
|
364
|
-
const messages = registry.messages();
|
|
365
|
-
const contents = /* @__PURE__ */ new Map();
|
|
366
|
-
const readSource = (file) => {
|
|
367
|
-
if (!contents.has(file)) try {
|
|
368
|
-
contents.set(file, readFileSync(file, "utf8"));
|
|
369
|
-
} catch {
|
|
370
|
-
contents.set(file, void 0);
|
|
371
|
-
}
|
|
372
|
-
return contents.get(file);
|
|
373
|
-
};
|
|
374
|
-
const lines = [];
|
|
375
|
-
const byKey = /* @__PURE__ */ new Map();
|
|
376
|
-
for (const entry of result.missing) {
|
|
377
|
-
const grouped = byKey.get(entry.key);
|
|
378
|
-
if (grouped) grouped.locales.push(entry.locale);
|
|
379
|
-
else byKey.set(entry.key, {
|
|
380
|
-
...entry,
|
|
381
|
-
locales: [entry.locale]
|
|
382
|
-
});
|
|
383
|
-
}
|
|
384
|
-
for (const entry of byKey.values()) {
|
|
385
|
-
const origin = messages.get(entry.key);
|
|
386
|
-
const hint = entry.source ? `: "${truncate(entry.source, 60)}"` : "";
|
|
387
|
-
const text = escapeData(`missing [${entry.locales.join(", ")}] ${entry.key}${hint}`);
|
|
388
|
-
if (origin) {
|
|
389
|
-
const file = relative(root, origin.file).replaceAll("\\", "/");
|
|
390
|
-
const content = readSource(origin.file);
|
|
391
|
-
const line = content === void 0 ? void 0 : lineAt(content, origin.start);
|
|
392
|
-
lines.push(`::error file=${escapeProperty(file)}${line ? `,line=${line}` : ""}::${text}`);
|
|
393
|
-
} else lines.push(`::error::${text}`);
|
|
394
|
-
}
|
|
395
|
-
for (const entry of result.unknown) {
|
|
396
|
-
const text = escapeData(`unknown key "${entry.key}" (not in any catalog)`);
|
|
397
|
-
const file = entry.files[0];
|
|
398
|
-
lines.push(file ? `::error file=${escapeProperty(relative(root, file).replaceAll("\\", "/"))}::${text}` : `::error::${text}`);
|
|
399
|
-
}
|
|
400
|
-
for (const entry of result.broken) {
|
|
401
|
-
const origin = messages.get(entry.key);
|
|
402
|
-
const text = escapeData(`[${entry.locale}] ${entry.key}: ${entry.issue}`);
|
|
403
|
-
const command = entry.severity === "error" ? "error" : "warning";
|
|
404
|
-
if (!origin) {
|
|
405
|
-
lines.push(`::${command}::${text}`);
|
|
406
|
-
continue;
|
|
407
|
-
}
|
|
408
|
-
const file = relative(root, origin.file).replaceAll("\\", "/");
|
|
409
|
-
const content = readSource(origin.file);
|
|
410
|
-
const line = content === void 0 ? void 0 : lineAt(content, origin.start);
|
|
411
|
-
lines.push(`::${command} file=${escapeProperty(file)}${line ? `,line=${line}` : ""}::${text}`);
|
|
412
|
-
}
|
|
413
|
-
return lines;
|
|
414
|
-
}
|
|
415
|
-
function lineAt(content, offset) {
|
|
416
|
-
let line = 1;
|
|
417
|
-
const end = Math.min(offset, content.length);
|
|
418
|
-
for (let i = 0; i < end; i++) if (content[i] === "\n") line += 1;
|
|
419
|
-
return line;
|
|
420
|
-
}
|
|
421
|
-
function escapeData(text) {
|
|
422
|
-
return text.replaceAll("%", "%25").replaceAll("\r", "%0D").replaceAll("\n", "%0A");
|
|
423
|
-
}
|
|
424
|
-
function escapeProperty(text) {
|
|
425
|
-
return escapeData(text).replaceAll(":", "%3A").replaceAll(",", "%2C");
|
|
426
|
-
}
|
|
427
|
-
//#endregion
|
|
428
|
-
//#region src/params.ts
|
|
429
|
-
const NUMBER_FORMATS = /* @__PURE__ */ new Set([
|
|
430
|
-
"number",
|
|
431
|
-
"integer",
|
|
432
|
-
"percent",
|
|
433
|
-
"currency"
|
|
434
|
-
]);
|
|
435
|
-
const DATE_FORMATS = /* @__PURE__ */ new Set(["date", "time"]);
|
|
436
|
-
function collectParams(message) {
|
|
437
|
-
const out = /* @__PURE__ */ new Map();
|
|
438
|
-
visit(parse(message), out);
|
|
439
|
-
return out;
|
|
440
|
-
}
|
|
441
|
-
function visit(nodes, out) {
|
|
442
|
-
for (const node of nodes) {
|
|
443
|
-
if (node.kind !== "param") continue;
|
|
444
|
-
const types = out.get(node.name) ?? /* @__PURE__ */ new Set();
|
|
445
|
-
out.set(node.name, types);
|
|
446
|
-
if (node.variants) {
|
|
447
|
-
for (const [key, body] of node.variants) {
|
|
448
|
-
if (PLURAL_CATEGORIES.has(key) || /^=\d+$/.test(key)) types.add("number");
|
|
449
|
-
else if (key !== "other") types.add("string");
|
|
450
|
-
visit(body, out);
|
|
451
|
-
}
|
|
452
|
-
if (types.size === 0) types.add("string");
|
|
453
|
-
} else if (node.format && NUMBER_FORMATS.has(node.format)) types.add("number");
|
|
454
|
-
else if (node.format && DATE_FORMATS.has(node.format)) types.add("date");
|
|
455
|
-
else types.add("unknown");
|
|
456
|
-
}
|
|
457
|
-
}
|
|
458
|
-
function renderParamType(types) {
|
|
459
|
-
if (types.has("unknown") || types.size === 0) return "unknown";
|
|
460
|
-
const members = /* @__PURE__ */ new Set();
|
|
461
|
-
if (types.has("number")) members.add("number");
|
|
462
|
-
if (types.has("string")) members.add("string");
|
|
463
|
-
if (types.has("date")) for (const m of [
|
|
464
|
-
"Date",
|
|
465
|
-
"number",
|
|
466
|
-
"string"
|
|
467
|
-
]) members.add(m);
|
|
468
|
-
return [...members].join(" | ");
|
|
469
|
-
}
|
|
470
|
-
function generateDts(catalog) {
|
|
471
|
-
const lines = [];
|
|
472
|
-
for (const [key, message] of Object.entries(catalog).sort(([a], [b]) => a.localeCompare(b))) {
|
|
473
|
-
const params = collectParams(message);
|
|
474
|
-
if (params.size === 0) lines.push(` ${JSON.stringify(key)}: never;`);
|
|
475
|
-
else {
|
|
476
|
-
const fields = [...params.entries()].map(([name, types]) => `${JSON.stringify(name)}: ${renderParamType(types)}`).join("; ");
|
|
477
|
-
lines.push(` ${JSON.stringify(key)}: { ${fields} };`);
|
|
478
|
-
}
|
|
479
|
-
}
|
|
480
|
-
return `// generated by verbaly: do not edit
|
|
481
|
-
declare module 'virtual:verbaly' {
|
|
482
|
-
export interface VerbalyMessages {
|
|
483
|
-
${lines.join("\n")}
|
|
484
|
-
}
|
|
485
|
-
export type VerbalyKey = keyof VerbalyMessages & string;
|
|
486
|
-
|
|
487
|
-
export const verbaly: import('verbaly').Verbaly<VerbalyKey>;
|
|
488
|
-
|
|
489
|
-
export const sourceLocale: string;
|
|
490
|
-
export const locales: string[];
|
|
491
|
-
export const routing: import('verbaly').Routing;
|
|
492
|
-
export function localePath(
|
|
493
|
-
locale: string,
|
|
494
|
-
options?: { path?: string; base?: string },
|
|
495
|
-
): string;
|
|
496
|
-
export function localeFromPath(options?: {
|
|
497
|
-
path?: string;
|
|
498
|
-
base?: string;
|
|
499
|
-
}): string | undefined;
|
|
500
|
-
export function loadMessages(locale: string): Promise<Record<string, string>>;
|
|
501
|
-
export function createInstance(
|
|
502
|
-
options?: import('verbaly').VerbalyOptions<VerbalyKey>,
|
|
503
|
-
): import('verbaly').Verbaly<VerbalyKey>;
|
|
504
|
-
export function createRequestInstance(
|
|
505
|
-
locale: string,
|
|
506
|
-
): Promise<import('verbaly').Verbaly<VerbalyKey>>;
|
|
507
|
-
|
|
508
|
-
export function t<K extends VerbalyKey>(
|
|
509
|
-
key: K,
|
|
510
|
-
...args: [VerbalyMessages[K]] extends [never] ? [] : [VerbalyMessages[K]]
|
|
511
|
-
): string;
|
|
512
|
-
export function t(strings: TemplateStringsArray, ...values: unknown[]): string;
|
|
513
|
-
export namespace t {
|
|
514
|
-
export function id(
|
|
515
|
-
key: string,
|
|
516
|
-
): (strings: TemplateStringsArray, ...values: unknown[]) => string;
|
|
517
|
-
}
|
|
518
|
-
|
|
519
|
-
export function setLocale(locale: string): Promise<void>;
|
|
520
|
-
export function switchLocale(
|
|
521
|
-
locale: string,
|
|
522
|
-
options?: Omit<
|
|
523
|
-
import('verbaly').SwitchLocaleOptions,
|
|
524
|
-
'routing' | 'supported' | 'sourceLocale'
|
|
525
|
-
>,
|
|
526
|
-
): Promise<void>;
|
|
527
|
-
export function getLocale(): string;
|
|
528
|
-
export function subscribe(listener: () => void): () => void;
|
|
529
|
-
}
|
|
530
|
-
|
|
531
|
-
declare module 'virtual:verbaly/locale/*' {
|
|
532
|
-
const messages: Record<string, string>;
|
|
533
|
-
export default messages;
|
|
534
|
-
}
|
|
535
|
-
`;
|
|
536
|
-
}
|
|
537
|
-
function writeDts(cfg, catalog, file) {
|
|
538
|
-
file ??= join(cfg.root, "verbaly.d.ts");
|
|
539
|
-
const content = generateDts(catalog);
|
|
540
|
-
try {
|
|
541
|
-
if (readFileSync(file, "utf8") === content) return;
|
|
542
|
-
} catch {}
|
|
543
|
-
mkdirSync(dirname(file), { recursive: true });
|
|
544
|
-
writeFileSync(file, content);
|
|
545
|
-
}
|
|
546
|
-
//#endregion
|
|
547
|
-
//#region src/pseudo.ts
|
|
548
|
-
const PSEUDO_LOCALE = "en-XA";
|
|
549
|
-
const ACCENTS = {
|
|
550
|
-
a: "á",
|
|
551
|
-
b: "ƀ",
|
|
552
|
-
c: "ç",
|
|
553
|
-
d: "đ",
|
|
554
|
-
e: "é",
|
|
555
|
-
f: "ƒ",
|
|
556
|
-
g: "ğ",
|
|
557
|
-
h: "ĥ",
|
|
558
|
-
i: "í",
|
|
559
|
-
j: "ĵ",
|
|
560
|
-
k: "ķ",
|
|
561
|
-
l: "ĺ",
|
|
562
|
-
m: "ɱ",
|
|
563
|
-
n: "ñ",
|
|
564
|
-
o: "ó",
|
|
565
|
-
p: "þ",
|
|
566
|
-
q: "ǫ",
|
|
567
|
-
r: "ŕ",
|
|
568
|
-
s: "š",
|
|
569
|
-
t: "ţ",
|
|
570
|
-
u: "ú",
|
|
571
|
-
v: "ṽ",
|
|
572
|
-
w: "ŵ",
|
|
573
|
-
x: "ẋ",
|
|
574
|
-
y: "ý",
|
|
575
|
-
z: "ž",
|
|
576
|
-
A: "Á",
|
|
577
|
-
B: "Ɓ",
|
|
578
|
-
C: "Ç",
|
|
579
|
-
D: "Đ",
|
|
580
|
-
E: "É",
|
|
581
|
-
F: "Ƒ",
|
|
582
|
-
G: "Ğ",
|
|
583
|
-
H: "Ĥ",
|
|
584
|
-
I: "Í",
|
|
585
|
-
J: "Ĵ",
|
|
586
|
-
K: "Ķ",
|
|
587
|
-
L: "Ĺ",
|
|
588
|
-
M: "Ḿ",
|
|
589
|
-
N: "Ñ",
|
|
590
|
-
O: "Ó",
|
|
591
|
-
P: "Þ",
|
|
592
|
-
Q: "Ǫ",
|
|
593
|
-
R: "Ŕ",
|
|
594
|
-
S: "Š",
|
|
595
|
-
T: "Ţ",
|
|
596
|
-
U: "Ú",
|
|
597
|
-
V: "Ṽ",
|
|
598
|
-
W: "Ŵ",
|
|
599
|
-
X: "Ẍ",
|
|
600
|
-
Y: "Ý",
|
|
601
|
-
Z: "Ž"
|
|
602
|
-
};
|
|
603
|
-
const TAG_AT = /<\/?[a-zA-Z][\w-]*\/?>/y;
|
|
604
|
-
function pseudoLocalize(message) {
|
|
605
|
-
let out = "";
|
|
606
|
-
let letters = 0;
|
|
607
|
-
let i = 0;
|
|
608
|
-
while (i < message.length) {
|
|
609
|
-
const two = message.slice(i, i + 2);
|
|
610
|
-
if (two === "{{" || two === "}}" || two === "||" || two === "##") {
|
|
611
|
-
out += two;
|
|
612
|
-
i += 2;
|
|
613
|
-
continue;
|
|
614
|
-
}
|
|
615
|
-
const ch = message[i];
|
|
616
|
-
if (ch === "{") {
|
|
617
|
-
const end = matchBrace$1(message, i);
|
|
618
|
-
out += message.slice(i, end);
|
|
619
|
-
i = end;
|
|
620
|
-
continue;
|
|
621
|
-
}
|
|
622
|
-
if (ch === "<") {
|
|
623
|
-
TAG_AT.lastIndex = i;
|
|
624
|
-
const m = TAG_AT.exec(message);
|
|
625
|
-
if (m) {
|
|
626
|
-
out += m[0];
|
|
627
|
-
i += m[0].length;
|
|
628
|
-
continue;
|
|
629
|
-
}
|
|
630
|
-
}
|
|
631
|
-
const mapped = ACCENTS[ch];
|
|
632
|
-
if (mapped) {
|
|
633
|
-
out += mapped;
|
|
634
|
-
letters += 1;
|
|
635
|
-
} else out += ch;
|
|
636
|
-
i += 1;
|
|
637
|
-
}
|
|
638
|
-
const pad = "~".repeat(Math.ceil(letters / 3));
|
|
639
|
-
return `⟦${out}${pad ? " " + pad : ""}⟧`;
|
|
640
|
-
}
|
|
641
|
-
function matchBrace$1(message, start) {
|
|
642
|
-
let depth = 0;
|
|
643
|
-
for (let i = start; i < message.length; i++) {
|
|
644
|
-
const two = message.slice(i, i + 2);
|
|
645
|
-
if (two === "{{" || two === "}}") {
|
|
646
|
-
i += 1;
|
|
543
|
+
if (!other) {
|
|
544
|
+
issues.push({
|
|
545
|
+
severity: "error",
|
|
546
|
+
message: `the ${shape.plural ? "plural" : "select"} block for {${name}} was flattened into plain text`
|
|
547
|
+
});
|
|
647
548
|
continue;
|
|
648
549
|
}
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
550
|
+
if (shape.selectors.includes("other") && !other.selectors.includes("other") && !other.plural) issues.push({
|
|
551
|
+
severity: "error",
|
|
552
|
+
message: `the "other" case for {${name}} is missing, so unlisted values render empty`
|
|
553
|
+
});
|
|
554
|
+
const lostExact = shape.selectors.filter((key) => EXACT.test(key)).filter((key) => !other.selectors.includes(key));
|
|
555
|
+
if (lostExact.length > 0) issues.push({
|
|
556
|
+
severity: "warning",
|
|
557
|
+
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"`
|
|
558
|
+
});
|
|
655
559
|
}
|
|
656
|
-
return
|
|
560
|
+
return issues;
|
|
657
561
|
}
|
|
658
|
-
function
|
|
659
|
-
const
|
|
660
|
-
const
|
|
661
|
-
for (const
|
|
662
|
-
|
|
663
|
-
|
|
562
|
+
function tagReport(tokens) {
|
|
563
|
+
const out = [];
|
|
564
|
+
const seen = /* @__PURE__ */ new Set();
|
|
565
|
+
for (const token of tokens) {
|
|
566
|
+
const name = token.replaceAll("/", "");
|
|
567
|
+
if (seen.has(name)) continue;
|
|
568
|
+
seen.add(name);
|
|
569
|
+
out.push(token.endsWith("/") ? `<${name}/>` : `<${name}>`);
|
|
570
|
+
}
|
|
571
|
+
return out;
|
|
572
|
+
}
|
|
573
|
+
const COUNT_PROBE = 200;
|
|
574
|
+
const reachable = /* @__PURE__ */ new Map();
|
|
575
|
+
function reachableCategories(locale, ordinal) {
|
|
576
|
+
const type = ordinal ? "ordinal" : "cardinal";
|
|
577
|
+
const cacheKey = `${locale}\u0000${type}`;
|
|
578
|
+
const hit = reachable.get(cacheKey);
|
|
579
|
+
if (hit) return hit;
|
|
580
|
+
let out;
|
|
581
|
+
try {
|
|
582
|
+
const rules = new Intl.PluralRules(locale, { type });
|
|
583
|
+
const seen = /* @__PURE__ */ new Set();
|
|
584
|
+
for (let n = 0; n <= COUNT_PROBE; n++) seen.add(rules.select(n));
|
|
585
|
+
out = [...seen];
|
|
586
|
+
} catch {
|
|
587
|
+
out = [];
|
|
588
|
+
}
|
|
589
|
+
reachable.set(cacheKey, out);
|
|
590
|
+
return out;
|
|
664
591
|
}
|
|
665
592
|
//#endregion
|
|
666
|
-
//#region src/
|
|
667
|
-
function
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
const
|
|
672
|
-
|
|
673
|
-
|
|
593
|
+
//#region src/check.ts
|
|
594
|
+
function gatePasses(result) {
|
|
595
|
+
return result.missing.length === 0 && result.unknown.length === 0 && !result.broken.some((entry) => entry.severity === "error");
|
|
596
|
+
}
|
|
597
|
+
function check(cfg, catalogs, registry) {
|
|
598
|
+
const extracted = registry.messages();
|
|
599
|
+
const flat = {};
|
|
600
|
+
for (const locale of cfg.locales) flat[locale] = flatten(catalogs[locale] ?? {});
|
|
601
|
+
const source = flat[cfg.sourceLocale] ?? {};
|
|
602
|
+
const unknown = [];
|
|
603
|
+
for (const [key, files] of registry.usedKeys()) if (!(extracted.has(key) || cfg.locales.some((locale) => flat[locale]?.[key] !== void 0))) unknown.push({
|
|
604
|
+
key,
|
|
605
|
+
files
|
|
606
|
+
});
|
|
607
|
+
const needed = /* @__PURE__ */ new Set([...extracted.keys(), ...Object.keys(source)]);
|
|
608
|
+
const missing = [];
|
|
609
|
+
for (const key of extracted.keys()) if (!source[key]) missing.push({
|
|
610
|
+
locale: cfg.sourceLocale,
|
|
611
|
+
key,
|
|
612
|
+
source: extracted.get(key)?.message
|
|
613
|
+
});
|
|
614
|
+
for (const locale of cfg.locales) {
|
|
615
|
+
if (locale === cfg.sourceLocale) continue;
|
|
616
|
+
for (const key of needed) if (!flat[locale]?.[key]) missing.push({
|
|
617
|
+
locale,
|
|
618
|
+
key,
|
|
619
|
+
source: source[key] ?? extracted.get(key)?.message
|
|
620
|
+
});
|
|
621
|
+
}
|
|
622
|
+
const broken = [];
|
|
623
|
+
const add = (locale, key, issues) => {
|
|
624
|
+
for (const issue of issues) broken.push({
|
|
625
|
+
locale,
|
|
626
|
+
key,
|
|
627
|
+
severity: issue.severity,
|
|
628
|
+
issue: issue.message
|
|
629
|
+
});
|
|
630
|
+
};
|
|
631
|
+
const sourceText = { ...source };
|
|
632
|
+
for (const [key, entry] of extracted) if (!sourceText[key]) sourceText[key] = entry.message;
|
|
633
|
+
for (const [key, text] of Object.entries(sourceText)) add(cfg.sourceLocale, key, validateMessage(text, cfg.sourceLocale));
|
|
634
|
+
for (const locale of cfg.locales) {
|
|
635
|
+
if (locale === cfg.sourceLocale) continue;
|
|
636
|
+
for (const [key, translated] of Object.entries(flat[locale] ?? {})) {
|
|
637
|
+
if (!translated) continue;
|
|
638
|
+
add(locale, key, validateMessage(translated, locale));
|
|
639
|
+
const text = sourceText[key];
|
|
640
|
+
if (text) add(locale, key, validatePair(text, translated));
|
|
641
|
+
}
|
|
674
642
|
}
|
|
675
643
|
return {
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
exclude: config.exclude ?? ["**/node_modules/**", "**/dist/**"],
|
|
685
|
-
dts: typeof config.dts === "string" ? resolve(root, config.dts) : config.dts,
|
|
686
|
-
translate: config.translate ?? {},
|
|
687
|
-
render: config.render ?? {},
|
|
688
|
-
bundle: config.bundle ?? {}
|
|
644
|
+
ok: gatePasses({
|
|
645
|
+
missing,
|
|
646
|
+
unknown,
|
|
647
|
+
broken
|
|
648
|
+
}),
|
|
649
|
+
missing,
|
|
650
|
+
unknown,
|
|
651
|
+
broken
|
|
689
652
|
};
|
|
690
653
|
}
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
];
|
|
698
|
-
|
|
699
|
-
|
|
654
|
+
function formatCheckResult(result) {
|
|
655
|
+
const lines = [];
|
|
656
|
+
if (result.missing.length > 0) {
|
|
657
|
+
lines.push("missing translations:");
|
|
658
|
+
for (const entry of result.missing) {
|
|
659
|
+
const hint = entry.source ? `: "${truncate(entry.source, 40)}"` : "";
|
|
660
|
+
lines.push(` [${entry.locale}] ${entry.key}${hint}`);
|
|
661
|
+
}
|
|
662
|
+
}
|
|
663
|
+
if (result.unknown.length > 0) {
|
|
664
|
+
lines.push("unknown keys (not in any catalog):");
|
|
665
|
+
for (const entry of result.unknown) lines.push(` ${entry.key} (used in ${entry.files.join(", ")})`);
|
|
666
|
+
}
|
|
667
|
+
const errors = result.broken.filter((entry) => entry.severity === "error");
|
|
668
|
+
if (errors.length > 0) {
|
|
669
|
+
lines.push("broken translations:");
|
|
670
|
+
for (const entry of errors) lines.push(` [${entry.locale}] ${entry.key}: ${entry.issue}`);
|
|
671
|
+
}
|
|
672
|
+
return lines.join("\n");
|
|
700
673
|
}
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
674
|
+
function checkNextSteps(result, cliReachable = true) {
|
|
675
|
+
const steps = [];
|
|
676
|
+
if (result.missing.length > 0) steps.push("missing: run `npx verbaly extract` to scaffold the keys, then fill them (or run `npx verbaly translate`)");
|
|
677
|
+
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`");
|
|
678
|
+
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");
|
|
679
|
+
if (steps.length > 0 && !cliReachable) steps.push(`the verbaly command is not linked in this project: ${CLI_INSTALL_FIX}`);
|
|
680
|
+
return steps.join("\n");
|
|
681
|
+
}
|
|
682
|
+
function formatCheckWarnings(result) {
|
|
683
|
+
return result.broken.filter((entry) => entry.severity === "warning").map((entry) => ` [${entry.locale}] ${entry.key}: ${entry.issue}`).join("\n");
|
|
684
|
+
}
|
|
685
|
+
function truncate(text, max) {
|
|
686
|
+
return text.length > max ? text.slice(0, max - 1) + "…" : text;
|
|
687
|
+
}
|
|
688
|
+
function githubCheckAnnotations(result, registry, root) {
|
|
689
|
+
const messages = registry.messages();
|
|
690
|
+
const contents = /* @__PURE__ */ new Map();
|
|
691
|
+
const readSource = (file) => {
|
|
692
|
+
if (!contents.has(file)) try {
|
|
693
|
+
contents.set(file, readFileSync(file, "utf8"));
|
|
694
|
+
} catch {
|
|
695
|
+
contents.set(file, void 0);
|
|
696
|
+
}
|
|
697
|
+
return contents.get(file);
|
|
698
|
+
};
|
|
699
|
+
const lines = [];
|
|
700
|
+
const byKey = /* @__PURE__ */ new Map();
|
|
701
|
+
for (const entry of result.missing) {
|
|
702
|
+
const grouped = byKey.get(entry.key);
|
|
703
|
+
if (grouped) grouped.locales.push(entry.locale);
|
|
704
|
+
else byKey.set(entry.key, {
|
|
705
|
+
...entry,
|
|
706
|
+
locales: [entry.locale]
|
|
707
|
+
});
|
|
705
708
|
}
|
|
706
|
-
for (const
|
|
707
|
-
const
|
|
708
|
-
|
|
709
|
+
for (const entry of byKey.values()) {
|
|
710
|
+
const origin = messages.get(entry.key);
|
|
711
|
+
const hint = entry.source ? `: "${truncate(entry.source, 60)}"` : "";
|
|
712
|
+
const text = escapeData(`missing [${entry.locales.join(", ")}] ${entry.key}${hint}`);
|
|
713
|
+
if (origin) {
|
|
714
|
+
const file = relative(root, origin.file).replaceAll("\\", "/");
|
|
715
|
+
const content = readSource(origin.file);
|
|
716
|
+
const line = content === void 0 ? void 0 : lineAt(content, origin.start);
|
|
717
|
+
lines.push(`::error file=${escapeProperty(file)}${line ? `,line=${line}` : ""}::${text}`);
|
|
718
|
+
} else lines.push(`::error::${text}`);
|
|
709
719
|
}
|
|
710
|
-
const
|
|
711
|
-
|
|
712
|
-
|
|
720
|
+
for (const entry of result.unknown) {
|
|
721
|
+
const text = escapeData(`unknown key "${entry.key}" (not in any catalog)`);
|
|
722
|
+
const file = entry.files[0];
|
|
723
|
+
lines.push(file ? `::error file=${escapeProperty(relative(root, file).replaceAll("\\", "/"))}::${text}` : `::error::${text}`);
|
|
724
|
+
}
|
|
725
|
+
for (const entry of result.broken) {
|
|
726
|
+
const origin = messages.get(entry.key);
|
|
727
|
+
const text = escapeData(`[${entry.locale}] ${entry.key}: ${entry.issue}`);
|
|
728
|
+
const command = entry.severity === "error" ? "error" : "warning";
|
|
729
|
+
if (!origin) {
|
|
730
|
+
lines.push(`::${command}::${text}`);
|
|
731
|
+
continue;
|
|
732
|
+
}
|
|
733
|
+
const file = relative(root, origin.file).replaceAll("\\", "/");
|
|
734
|
+
const content = readSource(origin.file);
|
|
735
|
+
const line = content === void 0 ? void 0 : lineAt(content, origin.start);
|
|
736
|
+
lines.push(`::${command} file=${escapeProperty(file)}${line ? `,line=${line}` : ""}::${text}`);
|
|
737
|
+
}
|
|
738
|
+
return lines;
|
|
739
|
+
}
|
|
740
|
+
function lineAt(content, offset) {
|
|
741
|
+
let line = 1;
|
|
742
|
+
const end = Math.min(offset, content.length);
|
|
743
|
+
for (let i = 0; i < end; i++) if (content[i] === "\n") line += 1;
|
|
744
|
+
return line;
|
|
745
|
+
}
|
|
746
|
+
function escapeData(text) {
|
|
747
|
+
return text.replaceAll("%", "%25").replaceAll("\r", "%0D").replaceAll("\n", "%0A");
|
|
748
|
+
}
|
|
749
|
+
function escapeProperty(text) {
|
|
750
|
+
return escapeData(text).replaceAll(":", "%3A").replaceAll(",", "%2C");
|
|
751
|
+
}
|
|
752
|
+
//#endregion
|
|
753
|
+
//#region src/params.ts
|
|
754
|
+
const NUMBER_FORMATS = /* @__PURE__ */ new Set([
|
|
755
|
+
"number",
|
|
756
|
+
"integer",
|
|
757
|
+
"percent",
|
|
758
|
+
"currency"
|
|
759
|
+
]);
|
|
760
|
+
const DATE_FORMATS = /* @__PURE__ */ new Set(["date", "time"]);
|
|
761
|
+
function collectParams(message) {
|
|
762
|
+
const out = /* @__PURE__ */ new Map();
|
|
763
|
+
visit(parse(message), out);
|
|
764
|
+
return out;
|
|
713
765
|
}
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
const
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
766
|
+
function visit(nodes, out) {
|
|
767
|
+
for (const node of nodes) {
|
|
768
|
+
if (node.kind !== "param") continue;
|
|
769
|
+
const types = out.get(node.name) ?? /* @__PURE__ */ new Set();
|
|
770
|
+
out.set(node.name, types);
|
|
771
|
+
if (node.variants) {
|
|
772
|
+
for (const [key, body] of node.variants) {
|
|
773
|
+
if (PLURAL_CATEGORIES.has(key) || /^=\d+$/.test(key)) types.add("number");
|
|
774
|
+
else if (key !== "other") types.add("string");
|
|
775
|
+
visit(body, out);
|
|
776
|
+
}
|
|
777
|
+
if (types.size === 0) types.add("string");
|
|
778
|
+
} else if (node.format && NUMBER_FORMATS.has(node.format)) types.add("number");
|
|
779
|
+
else if (node.format && DATE_FORMATS.has(node.format)) types.add("date");
|
|
780
|
+
else types.add("unknown");
|
|
722
781
|
}
|
|
723
782
|
}
|
|
724
|
-
function
|
|
725
|
-
|
|
783
|
+
function renderParamType(types) {
|
|
784
|
+
if (types.has("unknown") || types.size === 0) return "unknown";
|
|
785
|
+
const members = /* @__PURE__ */ new Set();
|
|
786
|
+
if (types.has("number")) members.add("number");
|
|
787
|
+
if (types.has("string")) members.add("string");
|
|
788
|
+
if (types.has("date")) for (const m of [
|
|
789
|
+
"Date",
|
|
790
|
+
"number",
|
|
791
|
+
"string"
|
|
792
|
+
]) members.add(m);
|
|
793
|
+
return [...members].join(" | ");
|
|
726
794
|
}
|
|
727
|
-
function
|
|
728
|
-
|
|
795
|
+
function generateDts(catalog) {
|
|
796
|
+
const lines = [];
|
|
797
|
+
for (const [key, message] of Object.entries(catalog).sort(([a], [b]) => a.localeCompare(b))) {
|
|
798
|
+
const params = collectParams(message);
|
|
799
|
+
if (params.size === 0) lines.push(` ${JSON.stringify(key)}: never;`);
|
|
800
|
+
else {
|
|
801
|
+
const fields = [...params.entries()].map(([name, types]) => `${JSON.stringify(name)}: ${renderParamType(types)}`).join("; ");
|
|
802
|
+
lines.push(` ${JSON.stringify(key)}: { ${fields} };`);
|
|
803
|
+
}
|
|
804
|
+
}
|
|
805
|
+
return `// generated by verbaly: do not edit
|
|
806
|
+
declare module 'virtual:verbaly' {
|
|
807
|
+
export interface VerbalyMessages {
|
|
808
|
+
${lines.join("\n")}
|
|
809
|
+
}
|
|
810
|
+
export type VerbalyKey = keyof VerbalyMessages & string;
|
|
811
|
+
|
|
812
|
+
export const verbaly: import('verbaly').Verbaly<VerbalyKey>;
|
|
813
|
+
|
|
814
|
+
export const sourceLocale: string;
|
|
815
|
+
export const locales: string[];
|
|
816
|
+
export const routing: import('verbaly').Routing;
|
|
817
|
+
export function localePath(
|
|
818
|
+
locale: string,
|
|
819
|
+
options?: { path?: string; base?: string },
|
|
820
|
+
): string;
|
|
821
|
+
export function localeFromPath(options?: {
|
|
822
|
+
path?: string;
|
|
823
|
+
base?: string;
|
|
824
|
+
}): string | undefined;
|
|
825
|
+
export function loadMessages(locale: string): Promise<Record<string, string>>;
|
|
826
|
+
export function createInstance(
|
|
827
|
+
options?: import('verbaly').VerbalyOptions<VerbalyKey>,
|
|
828
|
+
): import('verbaly').Verbaly<VerbalyKey>;
|
|
829
|
+
export function createRequestInstance(
|
|
830
|
+
locale: string,
|
|
831
|
+
): Promise<import('verbaly').Verbaly<VerbalyKey>>;
|
|
832
|
+
|
|
833
|
+
export function t<K extends VerbalyKey>(
|
|
834
|
+
key: K,
|
|
835
|
+
...args: [VerbalyMessages[K]] extends [never] ? [] : [VerbalyMessages[K]]
|
|
836
|
+
): string;
|
|
837
|
+
export function t(strings: TemplateStringsArray, ...values: unknown[]): string;
|
|
838
|
+
export namespace t {
|
|
839
|
+
export function id(
|
|
840
|
+
key: string,
|
|
841
|
+
): (strings: TemplateStringsArray, ...values: unknown[]) => string;
|
|
842
|
+
}
|
|
843
|
+
|
|
844
|
+
export function setLocale(locale: string): Promise<void>;
|
|
845
|
+
export function switchLocale(
|
|
846
|
+
locale: string,
|
|
847
|
+
options?: Omit<
|
|
848
|
+
import('verbaly').SwitchLocaleOptions,
|
|
849
|
+
'routing' | 'supported' | 'sourceLocale'
|
|
850
|
+
>,
|
|
851
|
+
): Promise<void>;
|
|
852
|
+
export function getLocale(): string;
|
|
853
|
+
export function subscribe(listener: () => void): () => void;
|
|
729
854
|
}
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
root
|
|
735
|
-
});
|
|
855
|
+
|
|
856
|
+
declare module 'virtual:verbaly/locale/*' {
|
|
857
|
+
const messages: Record<string, string>;
|
|
858
|
+
export default messages;
|
|
736
859
|
}
|
|
737
|
-
|
|
738
|
-
|
|
860
|
+
`;
|
|
861
|
+
}
|
|
862
|
+
function writeDts(cfg, catalog, file) {
|
|
863
|
+
file ??= join(cfg.root, "verbaly.d.ts");
|
|
864
|
+
const content = generateDts(catalog);
|
|
865
|
+
try {
|
|
866
|
+
if (readFileSync(file, "utf8") === content) return;
|
|
867
|
+
} catch {}
|
|
868
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
869
|
+
writeFileSync(file, content);
|
|
739
870
|
}
|
|
740
871
|
//#endregion
|
|
741
872
|
//#region src/text.ts
|
|
@@ -1330,123 +1461,6 @@ function pruneCatalogs(cfg, catalogs, registry) {
|
|
|
1330
1461
|
return removed;
|
|
1331
1462
|
}
|
|
1332
1463
|
//#endregion
|
|
1333
|
-
//#region src/init.ts
|
|
1334
|
-
const HOSTS = [
|
|
1335
|
-
{
|
|
1336
|
-
name: "nuxt",
|
|
1337
|
-
dep: "nuxt",
|
|
1338
|
-
pkg: "@verbaly/nuxt",
|
|
1339
|
-
wire: "add '@verbaly/nuxt' to the modules in nuxt.config"
|
|
1340
|
-
},
|
|
1341
|
-
{
|
|
1342
|
-
name: "next",
|
|
1343
|
-
dep: "next",
|
|
1344
|
-
pkg: "@verbaly/next",
|
|
1345
|
-
wire: "wrap the export of next.config with withVerbaly"
|
|
1346
|
-
},
|
|
1347
|
-
{
|
|
1348
|
-
name: "sveltekit",
|
|
1349
|
-
dep: "@sveltejs/kit",
|
|
1350
|
-
pkg: "@verbaly/vite",
|
|
1351
|
-
wire: "add verbaly() to the plugins in vite.config (per-request locale: @verbaly/sveltekit)"
|
|
1352
|
-
},
|
|
1353
|
-
{
|
|
1354
|
-
name: "astro",
|
|
1355
|
-
dep: "astro",
|
|
1356
|
-
pkg: "@verbaly/astro",
|
|
1357
|
-
wire: "add verbaly() to the integrations in astro.config"
|
|
1358
|
-
},
|
|
1359
|
-
{
|
|
1360
|
-
name: "vite",
|
|
1361
|
-
dep: "vite",
|
|
1362
|
-
pkg: "@verbaly/vite",
|
|
1363
|
-
wire: "add verbaly() to the plugins in vite.config"
|
|
1364
|
-
},
|
|
1365
|
-
{
|
|
1366
|
-
name: "webpack",
|
|
1367
|
-
dep: "webpack",
|
|
1368
|
-
pkg: "@verbaly/unplugin",
|
|
1369
|
-
wire: "add the verbaly webpack plugin to your build config"
|
|
1370
|
-
},
|
|
1371
|
-
{
|
|
1372
|
-
name: "rspack",
|
|
1373
|
-
dep: "@rspack/core",
|
|
1374
|
-
pkg: "@verbaly/unplugin",
|
|
1375
|
-
wire: "add the verbaly rspack plugin to your build config"
|
|
1376
|
-
},
|
|
1377
|
-
{
|
|
1378
|
-
name: "rollup",
|
|
1379
|
-
dep: "rollup",
|
|
1380
|
-
pkg: "@verbaly/unplugin",
|
|
1381
|
-
wire: "add the verbaly rollup plugin to your build config"
|
|
1382
|
-
},
|
|
1383
|
-
{
|
|
1384
|
-
name: "esbuild",
|
|
1385
|
-
dep: "esbuild",
|
|
1386
|
-
pkg: "@verbaly/unplugin",
|
|
1387
|
-
wire: "add the verbaly esbuild plugin to your build config"
|
|
1388
|
-
}
|
|
1389
|
-
];
|
|
1390
|
-
const WIRING_PACKAGES = [...new Set(HOSTS.map((host) => host.pkg))];
|
|
1391
|
-
function readDependencies(root) {
|
|
1392
|
-
const path = join(root, "package.json");
|
|
1393
|
-
if (!existsSync(path)) return {};
|
|
1394
|
-
try {
|
|
1395
|
-
const pkg = JSON.parse(readFileSync(path, "utf8"));
|
|
1396
|
-
return {
|
|
1397
|
-
...pkg.dependencies,
|
|
1398
|
-
...pkg.devDependencies
|
|
1399
|
-
};
|
|
1400
|
-
} catch {
|
|
1401
|
-
return {};
|
|
1402
|
-
}
|
|
1403
|
-
}
|
|
1404
|
-
function detectHost(root) {
|
|
1405
|
-
const deps = readDependencies(root);
|
|
1406
|
-
return HOSTS.find((host) => deps[host.dep]);
|
|
1407
|
-
}
|
|
1408
|
-
function configSource(options, typescript) {
|
|
1409
|
-
const fields = [` sourceLocale: '${options.sourceLocale ?? "en"}',`];
|
|
1410
|
-
if (options.locales?.length) fields.push(` locales: [${options.locales.map((l) => `'${l}'`).join(", ")}],`);
|
|
1411
|
-
if (options.dir) fields.push(` dir: '${options.dir}',`);
|
|
1412
|
-
const body = `export default {\n${fields.join("\n")}\n}`;
|
|
1413
|
-
if (typescript) return `import type { VerbalyConfig } from '@verbaly/compiler';\n\n${body} satisfies VerbalyConfig;\n`;
|
|
1414
|
-
return `/** @type {import('@verbaly/compiler').VerbalyConfig} */\n${body};\n`;
|
|
1415
|
-
}
|
|
1416
|
-
function init(options = {}) {
|
|
1417
|
-
const root = options.root ?? process.cwd();
|
|
1418
|
-
const created = [];
|
|
1419
|
-
const skipped = [];
|
|
1420
|
-
const existing = findConfigFile(root);
|
|
1421
|
-
const typescript = existsSync(join(root, "tsconfig.json"));
|
|
1422
|
-
const configFile = existing ?? (typescript ? "verbaly.config.ts" : "verbaly.config.mjs");
|
|
1423
|
-
if (existing) skipped.push(existing);
|
|
1424
|
-
else {
|
|
1425
|
-
writeFileSync(join(root, configFile), configSource(options, typescript));
|
|
1426
|
-
created.push(configFile);
|
|
1427
|
-
}
|
|
1428
|
-
const dir = join(root, options.dir ?? "locales");
|
|
1429
|
-
if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
|
|
1430
|
-
for (const locale of /* @__PURE__ */ new Set([options.sourceLocale ?? "en", ...options.locales ?? []])) {
|
|
1431
|
-
const file = join(dir, `${locale}.json`);
|
|
1432
|
-
const label = relative(root, file).replaceAll("\\", "/");
|
|
1433
|
-
if (existsSync(file)) skipped.push(label);
|
|
1434
|
-
else {
|
|
1435
|
-
writeFileSync(file, "{}\n");
|
|
1436
|
-
created.push(label);
|
|
1437
|
-
}
|
|
1438
|
-
}
|
|
1439
|
-
const host = detectHost(root);
|
|
1440
|
-
const next = host ? [`pnpm add -D ${host.pkg}`, host.wire] : ["run \"verbaly extract\" after writing your first t`…` message"];
|
|
1441
|
-
return {
|
|
1442
|
-
created,
|
|
1443
|
-
skipped,
|
|
1444
|
-
host: host?.name,
|
|
1445
|
-
configFile,
|
|
1446
|
-
next
|
|
1447
|
-
};
|
|
1448
|
-
}
|
|
1449
|
-
//#endregion
|
|
1450
1464
|
//#region src/doctor.ts
|
|
1451
1465
|
const PREVIEW = 5;
|
|
1452
1466
|
function readRoutingChoice(root, configFile) {
|
|
@@ -1494,6 +1508,8 @@ async function doctor(cfg) {
|
|
|
1494
1508
|
const configFile = findConfigFile(cfg.root);
|
|
1495
1509
|
if (configFile) ok("config", `${configFile} found`);
|
|
1496
1510
|
else warn("config", "no config file, running on defaults", "run `npx verbaly init`");
|
|
1511
|
+
if (cliReachable(cfg.root)) ok("cli", "the verbaly command is available in this project");
|
|
1512
|
+
else warn("cli", "the verbaly command is not linked in node_modules/.bin", CLI_INSTALL_FIX);
|
|
1497
1513
|
const catalogs = {};
|
|
1498
1514
|
let catalogsHealthy = true;
|
|
1499
1515
|
if (!existsSync(cfg.dir)) {
|
|
@@ -1519,7 +1535,10 @@ async function doctor(cfg) {
|
|
|
1519
1535
|
error(`locale ${locale}`, `${rel(file)} is not valid JSON`, "repair the file (or delete it and run `npx verbaly extract`)");
|
|
1520
1536
|
}
|
|
1521
1537
|
}
|
|
1522
|
-
if (catalogsHealthy)
|
|
1538
|
+
if (catalogsHealthy) {
|
|
1539
|
+
const how = cfg.localesDeclared ? "" : ", no locales set, so the catalog files decide";
|
|
1540
|
+
ok("catalogs", `${counted(cfg.locales.length, "locale")} (${cfg.locales.join(", ")}) in ${rel(cfg.dir)}/${how}`);
|
|
1541
|
+
}
|
|
1523
1542
|
}
|
|
1524
1543
|
const source = catalogs[cfg.sourceLocale];
|
|
1525
1544
|
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`");
|
|
@@ -2848,8 +2867,16 @@ const WRAP_ATTRS = /* @__PURE__ */ new Set([
|
|
|
2848
2867
|
"placeholder",
|
|
2849
2868
|
"aria-label"
|
|
2850
2869
|
]);
|
|
2870
|
+
const CODE_TAGS = /* @__PURE__ */ new Set([
|
|
2871
|
+
"code",
|
|
2872
|
+
"pre",
|
|
2873
|
+
"kbd",
|
|
2874
|
+
"samp",
|
|
2875
|
+
"var"
|
|
2876
|
+
]);
|
|
2851
2877
|
const T_NAMES = /* @__PURE__ */ new Set(["t"]);
|
|
2852
2878
|
const LETTER = /\p{L}/u;
|
|
2879
|
+
const WHITESPACE = /\s/;
|
|
2853
2880
|
async function wrapProject(cfg, options = {}) {
|
|
2854
2881
|
const files = (await glob(cfg.include, {
|
|
2855
2882
|
cwd: cfg.root,
|
|
@@ -2860,7 +2887,8 @@ async function wrapProject(cfg, options = {}) {
|
|
|
2860
2887
|
files: files.length,
|
|
2861
2888
|
changed: [],
|
|
2862
2889
|
wrapped: [],
|
|
2863
|
-
skipped: []
|
|
2890
|
+
skipped: [],
|
|
2891
|
+
blocked: []
|
|
2864
2892
|
};
|
|
2865
2893
|
for (const file of files) {
|
|
2866
2894
|
const code = readFileSync(file, "utf8");
|
|
@@ -2868,10 +2896,17 @@ async function wrapProject(cfg, options = {}) {
|
|
|
2868
2896
|
const out = wrapCode(code, label);
|
|
2869
2897
|
result.wrapped.push(...out.wrapped);
|
|
2870
2898
|
result.skipped.push(...out.skipped);
|
|
2871
|
-
if (out.code
|
|
2872
|
-
|
|
2873
|
-
|
|
2899
|
+
if (out.code === void 0) continue;
|
|
2900
|
+
result.changed.push(label);
|
|
2901
|
+
if (!out.hasT) {
|
|
2902
|
+
result.blocked.push({
|
|
2903
|
+
file: label,
|
|
2904
|
+
texts: out.wrapped.length,
|
|
2905
|
+
client: out.client
|
|
2906
|
+
});
|
|
2907
|
+
continue;
|
|
2874
2908
|
}
|
|
2909
|
+
if (options.write) writeFileSync(file, out.code);
|
|
2875
2910
|
}
|
|
2876
2911
|
return result;
|
|
2877
2912
|
}
|
|
@@ -2888,9 +2923,13 @@ function wrapCode(code, file) {
|
|
|
2888
2923
|
} catch {
|
|
2889
2924
|
return {
|
|
2890
2925
|
wrapped,
|
|
2891
|
-
skipped
|
|
2926
|
+
skipped,
|
|
2927
|
+
hasT: false,
|
|
2928
|
+
client: false
|
|
2892
2929
|
};
|
|
2893
2930
|
}
|
|
2931
|
+
const hasT = declaresT(ast);
|
|
2932
|
+
const client = hasDirective(ast, "use client");
|
|
2894
2933
|
const s = new MagicString(code);
|
|
2895
2934
|
const visited = /* @__PURE__ */ new Set();
|
|
2896
2935
|
let changed = false;
|
|
@@ -2902,10 +2941,14 @@ function wrapCode(code, file) {
|
|
|
2902
2941
|
return changed ? {
|
|
2903
2942
|
code: s.toString(),
|
|
2904
2943
|
wrapped,
|
|
2905
|
-
skipped
|
|
2944
|
+
skipped,
|
|
2945
|
+
hasT,
|
|
2946
|
+
client
|
|
2906
2947
|
} : {
|
|
2907
2948
|
wrapped,
|
|
2908
|
-
skipped
|
|
2949
|
+
skipped,
|
|
2950
|
+
hasT,
|
|
2951
|
+
client
|
|
2909
2952
|
};
|
|
2910
2953
|
function processElement(node) {
|
|
2911
2954
|
visited.add(node);
|
|
@@ -2914,6 +2957,7 @@ function wrapCode(code, file) {
|
|
|
2914
2957
|
const name = opening.name;
|
|
2915
2958
|
if (name.type === "JSXIdentifier" && name.name === "Trans") return markSubtree(node);
|
|
2916
2959
|
if (hasVerbalyAttr(opening)) return markSubtree(node);
|
|
2960
|
+
if (name.type === "JSXIdentifier" && CODE_TAGS.has(name.name)) return markSubtree(node);
|
|
2917
2961
|
wrapAttributes(opening);
|
|
2918
2962
|
}
|
|
2919
2963
|
const children = node.children ?? [];
|
|
@@ -2934,6 +2978,10 @@ function wrapCode(code, file) {
|
|
|
2934
2978
|
if (meaningful.length === 0) return;
|
|
2935
2979
|
const first = meaningful[0];
|
|
2936
2980
|
const last = meaningful[meaningful.length - 1];
|
|
2981
|
+
if (first.type === "JSXExpressionContainer" && meaningful.length > 1) {
|
|
2982
|
+
skip(parent, snippet(children), "starts with an interpolation: wrap the sentence by hand");
|
|
2983
|
+
return;
|
|
2984
|
+
}
|
|
2937
2985
|
let template = "";
|
|
2938
2986
|
let report = "";
|
|
2939
2987
|
for (let i = children.indexOf(first); i <= children.indexOf(last); i++) {
|
|
@@ -2967,6 +3015,7 @@ function wrapCode(code, file) {
|
|
|
2967
3015
|
} else return;
|
|
2968
3016
|
}
|
|
2969
3017
|
if (!LETTER.test(report)) return;
|
|
3018
|
+
if (isIdentifierLike(report)) return;
|
|
2970
3019
|
const start = first.type === "JSXText" ? first.start + leadingWs(first.value) : first.start;
|
|
2971
3020
|
const end = last.type === "JSXText" ? last.end - trailingWs(last.value) : last.end;
|
|
2972
3021
|
s.overwrite(start, end, "{t`" + template + "`}");
|
|
@@ -2986,7 +3035,7 @@ function wrapCode(code, file) {
|
|
|
2986
3035
|
const value = attr.value;
|
|
2987
3036
|
if (value?.type !== "StringLiteral") continue;
|
|
2988
3037
|
const raw = value.value;
|
|
2989
|
-
if (!LETTER.test(raw)) continue;
|
|
3038
|
+
if (!LETTER.test(raw) || isIdentifierLike(raw)) continue;
|
|
2990
3039
|
s.overwrite(value.start, value.end, "{t`" + escapeTemplate(raw) + "`}");
|
|
2991
3040
|
changed = true;
|
|
2992
3041
|
wrapped.push({
|
|
@@ -3018,6 +3067,40 @@ function wrapCode(code, file) {
|
|
|
3018
3067
|
});
|
|
3019
3068
|
}
|
|
3020
3069
|
}
|
|
3070
|
+
function isIdentifierLike(text) {
|
|
3071
|
+
const trimmed = text.trim();
|
|
3072
|
+
if (WHITESPACE.test(trimmed)) return false;
|
|
3073
|
+
const first = [...trimmed].find((char) => LETTER.test(char));
|
|
3074
|
+
return first !== void 0 && first !== first.toUpperCase();
|
|
3075
|
+
}
|
|
3076
|
+
function hasDirective(program, value) {
|
|
3077
|
+
return (program.directives ?? []).some((d) => d.value?.value === value);
|
|
3078
|
+
}
|
|
3079
|
+
function declaresT(program) {
|
|
3080
|
+
let found = false;
|
|
3081
|
+
walk(program, (node) => {
|
|
3082
|
+
if (found) return;
|
|
3083
|
+
if (node.type === "ImportDeclaration") {
|
|
3084
|
+
for (const spec of node.specifiers) if (isTName(spec.local?.name)) found = true;
|
|
3085
|
+
return;
|
|
3086
|
+
}
|
|
3087
|
+
if (node.type === "VariableDeclarator" && bindsT(node.id)) found = true;
|
|
3088
|
+
if (node.type === "FunctionDeclaration" && isTName(node.id?.name)) found = true;
|
|
3089
|
+
if (node.params?.some((param) => bindsT(param))) found = true;
|
|
3090
|
+
});
|
|
3091
|
+
return found;
|
|
3092
|
+
}
|
|
3093
|
+
function bindsT(pattern) {
|
|
3094
|
+
if (!pattern) return false;
|
|
3095
|
+
if (pattern.type === "Identifier") return isTName(pattern.name);
|
|
3096
|
+
if (pattern.type === "AssignmentPattern") return bindsT(pattern.left);
|
|
3097
|
+
if (pattern.type === "ObjectPattern") return pattern.properties.some((prop) => prop.type === "RestElement" ? bindsT(prop.argument) : bindsT(prop.value));
|
|
3098
|
+
if (pattern.type === "ArrayPattern") return pattern.elements.some((el) => bindsT(el ?? void 0));
|
|
3099
|
+
return false;
|
|
3100
|
+
}
|
|
3101
|
+
function isTName(name) {
|
|
3102
|
+
return typeof name === "string" && T_NAMES.has(name);
|
|
3103
|
+
}
|
|
3021
3104
|
function hasVerbalyAttr(opening) {
|
|
3022
3105
|
return opening.attributes.some((attr) => {
|
|
3023
3106
|
if (attr.type !== "JSXAttribute") return false;
|
|
@@ -3139,12 +3222,12 @@ async function runCli(args = process.argv.slice(2)) {
|
|
|
3139
3222
|
const command = positionals[0];
|
|
3140
3223
|
if (values.help || !command) {
|
|
3141
3224
|
console.log(HELP);
|
|
3142
|
-
process.exitCode =
|
|
3225
|
+
process.exitCode = values.help ? 0 : 1;
|
|
3143
3226
|
return;
|
|
3144
3227
|
}
|
|
3145
3228
|
if (rejectStrayFlags(command, values)) return;
|
|
3146
3229
|
if (command === "init") {
|
|
3147
|
-
const result = init({
|
|
3230
|
+
const result = await init({
|
|
3148
3231
|
root: values.root,
|
|
3149
3232
|
dir: values.dir,
|
|
3150
3233
|
sourceLocale: values.source,
|
|
@@ -3215,10 +3298,14 @@ async function runCli(args = process.argv.slice(2)) {
|
|
|
3215
3298
|
console.log(`[verbaly] nothing to wrap (${counted(result.files, "file")} scanned) ✓`);
|
|
3216
3299
|
return;
|
|
3217
3300
|
}
|
|
3301
|
+
const blocked = new Set(result.blocked.map((entry) => entry.file));
|
|
3302
|
+
const done = result.changed.filter((file) => !blocked.has(file));
|
|
3303
|
+
const texts = result.wrapped.filter((entry) => !blocked.has(entry.file));
|
|
3218
3304
|
const verb = values.write ? "wrapped" : "would wrap";
|
|
3219
3305
|
const note = values.write ? "" : " (report only, use --write to apply)";
|
|
3220
|
-
|
|
3221
|
-
|
|
3306
|
+
const counts = values.write ? `${counted(texts.length, "text")} in ${counted(done.length, "file")}` : `${counted(result.wrapped.length, "text")} in ${counted(result.changed.length, "file")}`;
|
|
3307
|
+
console.log(`[verbaly] ${verb} ${counts}${note}`);
|
|
3308
|
+
for (const entry of values.write ? texts : result.wrapped) {
|
|
3222
3309
|
const attr = entry.kind === "attribute" ? `${entry.attribute} → ` : "";
|
|
3223
3310
|
console.log(` ${entry.file}:${entry.line} ${attr}"${entry.text}"`);
|
|
3224
3311
|
}
|
|
@@ -3226,7 +3313,14 @@ async function runCli(args = process.argv.slice(2)) {
|
|
|
3226
3313
|
console.log(" needs a human:");
|
|
3227
3314
|
for (const entry of result.skipped) console.log(` ${entry.file}:${entry.line} "${entry.text}" (${entry.reason})`);
|
|
3228
3315
|
}
|
|
3229
|
-
if (
|
|
3316
|
+
if (result.blocked.length > 0) {
|
|
3317
|
+
console.log(` nothing written in ${counted(result.blocked.length, "file")} with no t in scope:`);
|
|
3318
|
+
for (const entry of result.blocked) {
|
|
3319
|
+
const how = entry.client ? "\"use client\", so const t = useT()" : "no \"use client\": check which side renders it before you pick the binding";
|
|
3320
|
+
console.log(` ${entry.file} ${counted(entry.texts, "text")}, ${how}`);
|
|
3321
|
+
}
|
|
3322
|
+
console.log(" next: add t there, run verbaly wrap --write again, then verbaly extract");
|
|
3323
|
+
} else if (values.write && done.length > 0) console.log(" next: run verbaly extract");
|
|
3230
3324
|
return;
|
|
3231
3325
|
}
|
|
3232
3326
|
if (command === "status") {
|