@verbaly/compiler 0.45.0 → 0.47.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/cli.js CHANGED
@@ -8,7 +8,7 @@ import { glob } from "tinyglobby";
8
8
  import { parse as parse$1 } from "@babel/parser";
9
9
  import { createHash } from "node:crypto";
10
10
  import MagicString from "magic-string";
11
- import "picomatch";
11
+ import picomatch from "picomatch";
12
12
  //#region src/catalog.ts
13
13
  function catalogPath(cfg, locale) {
14
14
  return join(cfg.dir, `${locale}.json`);
@@ -104,6 +104,330 @@ function wantsNesting(cfg, locale, existing) {
104
104
  return isNested(readTree(cfg, cfg.sourceLocale));
105
105
  }
106
106
  //#endregion
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 : ""}⟧`;
200
+ }
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
+ }
215
+ }
216
+ return message.length;
217
+ }
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]);
224
+ }
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));
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
+ };
252
+ }
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)));
262
+ }
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 ?? {};
267
+ }
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 {};
275
+ }
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
+ }
285
+ }
286
+ function isModuleNotFound(error, name) {
287
+ return error instanceof Error && error.code === "ERR_MODULE_NOT_FOUND" && error.message.includes(name);
288
+ }
289
+ function targetLocales(cfg, override) {
290
+ return (override ?? cfg.locales).filter((locale) => locale !== cfg.sourceLocale && cfg.locales.includes(locale));
291
+ }
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
107
431
  //#region src/validate.ts
108
432
  const PLURAL_CATEGORIES = /* @__PURE__ */ new Set([
109
433
  "zero",
@@ -327,7 +651,8 @@ function check(cfg, catalogs, registry) {
327
651
  broken
328
652
  };
329
653
  }
330
- function formatCheckResult(result) {
654
+ function formatCheckResult(result, root) {
655
+ const show = (file) => root ? relative(root, file).replaceAll("\\", "/") : file;
331
656
  const lines = [];
332
657
  if (result.missing.length > 0) {
333
658
  lines.push("missing translations:");
@@ -338,404 +663,214 @@ function formatCheckResult(result) {
338
663
  }
339
664
  if (result.unknown.length > 0) {
340
665
  lines.push("unknown keys (not in any catalog):");
341
- for (const entry of result.unknown) lines.push(` ${entry.key} (used in ${entry.files.join(", ")})`);
666
+ for (const entry of result.unknown) lines.push(` ${entry.key} (used in ${entry.files.map(show).join(", ")})`);
342
667
  }
343
668
  const errors = result.broken.filter((entry) => entry.severity === "error");
344
669
  if (errors.length > 0) {
345
670
  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;
671
+ for (const entry of errors) lines.push(` [${entry.locale}] ${entry.key}: ${entry.issue}`);
672
+ }
673
+ return lines.join("\n");
529
674
  }
530
-
531
- declare module 'virtual:verbaly/locale/*' {
532
- const messages: Record<string, string>;
533
- export default messages;
675
+ function checkNextSteps(result, cliReachable = true) {
676
+ const steps = [];
677
+ if (result.missing.length > 0) steps.push("missing: run `npx verbaly extract` to scaffold the keys, then fill them (or run `npx verbaly translate`)");
678
+ 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`");
679
+ 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");
680
+ if (steps.length > 0 && !cliReachable) steps.push(`the verbaly command is not linked in this project: ${CLI_INSTALL_FIX}`);
681
+ return steps.join("\n");
534
682
  }
535
- `;
683
+ function formatCheckWarnings(result) {
684
+ return result.broken.filter((entry) => entry.severity === "warning").map((entry) => ` [${entry.locale}] ${entry.key}: ${entry.issue}`).join("\n");
536
685
  }
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);
686
+ function truncate(text, max) {
687
+ return text.length > max ? text.slice(0, max - 1) + "…" : text;
545
688
  }
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
- }
689
+ function githubCheckAnnotations(result, registry, root) {
690
+ const messages = registry.messages();
691
+ const contents = /* @__PURE__ */ new Map();
692
+ const readSource = (file) => {
693
+ if (!contents.has(file)) try {
694
+ contents.set(file, readFileSync(file, "utf8"));
695
+ } catch {
696
+ contents.set(file, void 0);
630
697
  }
631
- const mapped = ACCENTS[ch];
632
- if (mapped) {
633
- out += mapped;
634
- letters += 1;
635
- } else out += ch;
636
- i += 1;
698
+ return contents.get(file);
699
+ };
700
+ const lines = [];
701
+ const byKey = /* @__PURE__ */ new Map();
702
+ for (const entry of result.missing) {
703
+ const grouped = byKey.get(entry.key);
704
+ if (grouped) grouped.locales.push(entry.locale);
705
+ else byKey.set(entry.key, {
706
+ ...entry,
707
+ locales: [entry.locale]
708
+ });
637
709
  }
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;
710
+ for (const entry of byKey.values()) {
711
+ const origin = messages.get(entry.key);
712
+ const hint = entry.source ? `: "${truncate(entry.source, 60)}"` : "";
713
+ const text = escapeData(`missing [${entry.locales.join(", ")}] ${entry.key}${hint}`);
714
+ if (origin) {
715
+ const file = relative(root, origin.file).replaceAll("\\", "/");
716
+ const content = readSource(origin.file);
717
+ const line = content === void 0 ? void 0 : lineAt(content, origin.start);
718
+ lines.push(`::error file=${escapeProperty(file)}${line ? `,line=${line}` : ""}::${text}`);
719
+ } else lines.push(`::error::${text}`);
720
+ }
721
+ for (const entry of result.unknown) {
722
+ const text = escapeData(`unknown key "${entry.key}" (not in any catalog)`);
723
+ const file = entry.files[0];
724
+ lines.push(file ? `::error file=${escapeProperty(relative(root, file).replaceAll("\\", "/"))}::${text}` : `::error::${text}`);
725
+ }
726
+ for (const entry of result.broken) {
727
+ const origin = messages.get(entry.key);
728
+ const text = escapeData(`[${entry.locale}] ${entry.key}: ${entry.issue}`);
729
+ const command = entry.severity === "error" ? "error" : "warning";
730
+ if (!origin) {
731
+ lines.push(`::${command}::${text}`);
647
732
  continue;
648
733
  }
649
- const ch = message[i];
650
- if (ch === "{") depth += 1;
651
- else if (ch === "}") {
652
- depth -= 1;
653
- if (depth === 0) return i + 1;
654
- }
734
+ const file = relative(root, origin.file).replaceAll("\\", "/");
735
+ const content = readSource(origin.file);
736
+ const line = content === void 0 ? void 0 : lineAt(content, origin.start);
737
+ lines.push(`::${command} file=${escapeProperty(file)}${line ? `,line=${line}` : ""}::${text}`);
655
738
  }
656
- return message.length;
739
+ return lines;
657
740
  }
658
- function pseudoCatalogs(cfg, catalogs, locale = PSEUDO_LOCALE) {
659
- const source = catalogs[cfg.sourceLocale] ?? {};
660
- const target = {};
661
- for (const [key, msg] of Object.entries(source)) target[key] = msg ? pseudoLocalize(msg) : "";
662
- catalogs[locale] = target;
663
- return Object.keys(target).filter((key) => target[key]);
741
+ function lineAt(content, offset) {
742
+ let line = 1;
743
+ const end = Math.min(offset, content.length);
744
+ for (let i = 0; i < end; i++) if (content[i] === "\n") line += 1;
745
+ return line;
664
746
  }
665
- //#endregion
666
- //#region src/config.ts
667
- function resolveConfig(config = {}) {
668
- const root = resolve(config.root ?? process.cwd());
669
- const dir = resolve(root, config.dir ?? "locales");
670
- const sourceLocale = config.sourceLocale ?? "en";
671
- const locales = /* @__PURE__ */ new Set([sourceLocale, ...config.locales ?? []]);
672
- if (existsSync(dir)) {
673
- for (const file of readdirSync(dir)) if (file.endsWith(".json") && !file.startsWith(".") && file !== `en-XA.json`) locales.add(file.slice(0, -5));
674
- }
675
- return {
676
- root,
677
- dir,
678
- sourceLocale,
679
- routing: config.routing ?? (config.render ? "prefix-except-source" : "no-prefix"),
680
- icu: config.icu,
681
- relative: config.relative,
682
- locales: [...locales],
683
- include: config.include ?? ["{src,app}/**/*.{js,jsx,ts,tsx,mjs,mts,svelte,vue,astro}"],
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 ?? {}
689
- };
747
+ function escapeData(text) {
748
+ return text.replaceAll("%", "%25").replaceAll("\r", "%0D").replaceAll("\n", "%0A");
690
749
  }
691
- const CONFIG_FILES = [
692
- "verbaly.config.js",
693
- "verbaly.config.mjs",
694
- "verbaly.config.ts",
695
- "verbaly.config.mts",
696
- "verbaly.config.json"
697
- ];
698
- function findConfigFile(root) {
699
- return CONFIG_FILES.find((name) => existsSync(join(root, name)));
750
+ function escapeProperty(text) {
751
+ return escapeData(text).replaceAll(":", "%3A").replaceAll(",", "%2C");
700
752
  }
701
- async function loadConfigFile(root) {
702
- for (const name of ["verbaly.config.js", "verbaly.config.mjs"]) {
703
- const path = join(root, name);
704
- if (existsSync(path)) return (await import(pathToFileURL(path).href)).default ?? {};
705
- }
706
- for (const name of ["verbaly.config.ts", "verbaly.config.mts"]) {
707
- const path = join(root, name);
708
- if (existsSync(path)) return loadTsConfig(path);
753
+ //#endregion
754
+ //#region src/params.ts
755
+ const NUMBER_FORMATS = /* @__PURE__ */ new Set([
756
+ "number",
757
+ "integer",
758
+ "percent",
759
+ "currency"
760
+ ]);
761
+ const DATE_FORMATS = /* @__PURE__ */ new Set(["date", "time"]);
762
+ function collectParams(message) {
763
+ const out = /* @__PURE__ */ new Map();
764
+ visit(parse(message), out);
765
+ return out;
766
+ }
767
+ function visit(nodes, out) {
768
+ for (const node of nodes) {
769
+ if (node.kind !== "param") continue;
770
+ const types = out.get(node.name) ?? /* @__PURE__ */ new Set();
771
+ out.set(node.name, types);
772
+ if (node.variants) {
773
+ for (const [key, body] of node.variants) {
774
+ if (PLURAL_CATEGORIES.has(key) || /^=\d+$/.test(key)) types.add("number");
775
+ else if (key !== "other") types.add("string");
776
+ visit(body, out);
777
+ }
778
+ if (types.size === 0) types.add("string");
779
+ } else if (node.format && NUMBER_FORMATS.has(node.format)) types.add("number");
780
+ else if (node.format && DATE_FORMATS.has(node.format)) types.add("date");
781
+ else types.add("unknown");
709
782
  }
710
- const jsonPath = join(root, "verbaly.config.json");
711
- if (existsSync(jsonPath)) return JSON.parse(readFileSync(jsonPath, "utf8"));
712
- return {};
713
783
  }
714
- async function loadTsConfig(path) {
715
- try {
716
- const { bundleRequire } = await import("bundle-require");
717
- const { mod } = await bundleRequire({ filepath: path });
718
- return mod.default ?? {};
719
- } catch (error) {
720
- if (isModuleNotFound(error, "esbuild")) throw new Error(`[verbaly] ${path} needs esbuild: install it with pnpm add -D esbuild`, { cause: error });
721
- throw error;
722
- }
784
+ function renderParamType(types) {
785
+ if (types.has("unknown") || types.size === 0) return "unknown";
786
+ const members = /* @__PURE__ */ new Set();
787
+ if (types.has("number")) members.add("number");
788
+ if (types.has("string")) members.add("string");
789
+ if (types.has("date")) for (const m of [
790
+ "Date",
791
+ "number",
792
+ "string"
793
+ ]) members.add(m);
794
+ return [...members].join(" | ");
723
795
  }
724
- function isModuleNotFound(error, name) {
725
- return error instanceof Error && error.code === "ERR_MODULE_NOT_FOUND" && error.message.includes(name);
796
+ function generateDts(catalog) {
797
+ const lines = [];
798
+ for (const [key, message] of Object.entries(catalog).sort(([a], [b]) => a.localeCompare(b))) {
799
+ const params = collectParams(message);
800
+ if (params.size === 0) lines.push(` ${JSON.stringify(key)}: never;`);
801
+ else {
802
+ const fields = [...params.entries()].map(([name, types]) => `${JSON.stringify(name)}: ${renderParamType(types)}`).join("; ");
803
+ lines.push(` ${JSON.stringify(key)}: { ${fields} };`);
804
+ }
805
+ }
806
+ return `// generated by verbaly: do not edit
807
+ declare module 'virtual:verbaly' {
808
+ export interface VerbalyMessages {
809
+ ${lines.join("\n")}
810
+ }
811
+ export type VerbalyKey = keyof VerbalyMessages & string;
812
+
813
+ export type VerbalyKeyTree = VerbalyKey | { readonly [name: string]: VerbalyKeyTree };
814
+ export function defineKeys<const T extends VerbalyKeyTree>(keys: T): T;
815
+
816
+ export const verbaly: import('verbaly').Verbaly<VerbalyKey>;
817
+
818
+ export const sourceLocale: string;
819
+ export const locales: string[];
820
+ export const routing: import('verbaly').Routing;
821
+ export function localePath(
822
+ locale: string,
823
+ options?: { path?: string; base?: string },
824
+ ): string;
825
+ export function localeFromPath(options?: {
826
+ path?: string;
827
+ base?: string;
828
+ }): string | undefined;
829
+ export function loadMessages(locale: string): Promise<Record<string, string>>;
830
+ export function createInstance(
831
+ options?: import('verbaly').VerbalyOptions<VerbalyKey>,
832
+ ): import('verbaly').Verbaly<VerbalyKey>;
833
+ export function createRequestInstance(
834
+ locale: string,
835
+ ): Promise<import('verbaly').Verbaly<VerbalyKey>>;
836
+
837
+ export function t<K extends VerbalyKey>(
838
+ key: K,
839
+ ...args: [VerbalyMessages[K]] extends [never] ? [] : [VerbalyMessages[K]]
840
+ ): string;
841
+ export function t(strings: TemplateStringsArray, ...values: unknown[]): string;
842
+ export namespace t {
843
+ export function id(
844
+ key: string,
845
+ ): (strings: TemplateStringsArray, ...values: unknown[]) => string;
846
+ }
847
+
848
+ export function setLocale(locale: string): Promise<void>;
849
+ export function switchLocale(
850
+ locale: string,
851
+ options?: Omit<
852
+ import('verbaly').SwitchLocaleOptions,
853
+ 'routing' | 'supported' | 'sourceLocale'
854
+ >,
855
+ ): Promise<void>;
856
+ export function getLocale(): string;
857
+ export function subscribe(listener: () => void): () => void;
726
858
  }
727
- function targetLocales(cfg, override) {
728
- return (override ?? cfg.locales).filter((locale) => locale !== cfg.sourceLocale && cfg.locales.includes(locale));
859
+
860
+ declare module 'virtual:verbaly/locale/*' {
861
+ const messages: Record<string, string>;
862
+ export default messages;
729
863
  }
730
- async function loadConfig(root, overrides = {}) {
731
- return resolveConfig({
732
- ...await loadConfigFile(root),
733
- ...definedOnly(overrides),
734
- root
735
- });
864
+ `;
736
865
  }
737
- function definedOnly(config) {
738
- return Object.fromEntries(Object.entries(config).filter(([, value]) => value !== void 0));
866
+ function writeDts(cfg, catalog, file) {
867
+ file ??= join(cfg.root, "verbaly.d.ts");
868
+ const content = generateDts(catalog);
869
+ try {
870
+ if (readFileSync(file, "utf8") === content) return;
871
+ } catch {}
872
+ mkdirSync(dirname(file), { recursive: true });
873
+ writeFileSync(file, content);
739
874
  }
740
875
  //#endregion
741
876
  //#region src/text.ts
@@ -854,6 +989,7 @@ const SKIP_KEYS = /* @__PURE__ */ new Set([
854
989
  ]);
855
990
  const DEFAULT_T_NAMES = ["t"];
856
991
  const JSX_FILE_RE = /\.(?:[cm]?jsx?|tsx)$/;
992
+ const DEFINE_KEYS = "defineKeys";
857
993
  function analyze(code, file, options = {}) {
858
994
  const names = new Set(options.tNames ?? DEFAULT_T_NAMES);
859
995
  const ast = parse$1(code, {
@@ -885,8 +1021,13 @@ function analyze(code, file, options = {}) {
885
1021
  });
886
1022
  } else if (node.type === "CallExpression") {
887
1023
  const callee = node.callee;
1024
+ const args = node.arguments;
1025
+ if (callee.type === "Identifier" && callee.name === DEFINE_KEYS) {
1026
+ collectDeclaredKeys(args[0], file, usedKeys);
1027
+ return;
1028
+ }
888
1029
  if (!isTReference(callee, names)) return;
889
- const first = node.arguments[0];
1030
+ const first = args[0];
890
1031
  if (first?.type === "StringLiteral") usedKeys.push({
891
1032
  key: first.value,
892
1033
  file
@@ -899,6 +1040,19 @@ function analyze(code, file, options = {}) {
899
1040
  strayImports
900
1041
  };
901
1042
  }
1043
+ function collectDeclaredKeys(node, file, out) {
1044
+ if (node?.type !== "ObjectExpression") return;
1045
+ for (const property of node.properties) {
1046
+ if (property.type !== "ObjectProperty") continue;
1047
+ const value = property.value;
1048
+ if (value.type === "StringLiteral") {
1049
+ if (value.value !== "") out.push({
1050
+ key: value.value,
1051
+ file
1052
+ });
1053
+ } else if (value.type === "ObjectExpression") collectDeclaredKeys(value, file, out);
1054
+ }
1055
+ }
902
1056
  const VERBALY_PACKAGE = /^(?:verbaly|@verbaly\/[\w-]+)$/;
903
1057
  function collectStrayImports(node, file, out) {
904
1058
  const source = node.source;
@@ -906,8 +1060,10 @@ function collectStrayImports(node, file, out) {
906
1060
  for (const spec of node.specifiers) {
907
1061
  if (spec.type !== "ImportSpecifier") continue;
908
1062
  const imported = spec.imported;
909
- if (imported.type === "Identifier" && imported.name === "t") out.push({
910
- name: "t",
1063
+ if (imported.type !== "Identifier") continue;
1064
+ const name = imported.name;
1065
+ if (name === "t" || name === DEFINE_KEYS) out.push({
1066
+ name,
911
1067
  source: source.value,
912
1068
  file
913
1069
  });
@@ -1330,123 +1486,6 @@ function pruneCatalogs(cfg, catalogs, registry) {
1330
1486
  return removed;
1331
1487
  }
1332
1488
  //#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
1489
  //#region src/doctor.ts
1451
1490
  const PREVIEW = 5;
1452
1491
  function readRoutingChoice(root, configFile) {
@@ -1494,6 +1533,8 @@ async function doctor(cfg) {
1494
1533
  const configFile = findConfigFile(cfg.root);
1495
1534
  if (configFile) ok("config", `${configFile} found`);
1496
1535
  else warn("config", "no config file, running on defaults", "run `npx verbaly init`");
1536
+ if (cliReachable(cfg.root)) ok("cli", "the verbaly command is available in this project");
1537
+ else warn("cli", "the verbaly command is not linked in node_modules/.bin", CLI_INSTALL_FIX);
1497
1538
  const catalogs = {};
1498
1539
  let catalogsHealthy = true;
1499
1540
  if (!existsSync(cfg.dir)) {
@@ -1519,7 +1560,10 @@ async function doctor(cfg) {
1519
1560
  error(`locale ${locale}`, `${rel(file)} is not valid JSON`, "repair the file (or delete it and run `npx verbaly extract`)");
1520
1561
  }
1521
1562
  }
1522
- if (catalogsHealthy) ok("catalogs", `${counted(cfg.locales.length, "locale")} (${cfg.locales.join(", ")}) in ${rel(cfg.dir)}/`);
1563
+ if (catalogsHealthy) {
1564
+ const how = cfg.localesDeclared ? "" : ", no locales set, so the catalog files decide";
1565
+ ok("catalogs", `${counted(cfg.locales.length, "locale")} (${cfg.locales.join(", ")}) in ${rel(cfg.dir)}/${how}`);
1566
+ }
1523
1567
  }
1524
1568
  const source = catalogs[cfg.sourceLocale];
1525
1569
  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`");
@@ -2560,6 +2604,10 @@ function injectAlternates(ms, html, alternates) {
2560
2604
  }
2561
2605
  const TITLE_TAG = /<title\b([^>]*)>/i;
2562
2606
  const REFRESH_META = /<meta\b[^>]*http-equiv\s*=\s*["']?refresh/i;
2607
+ const NOINDEX_META = /<meta\b[^>]*name\s*=\s*["']?robots["']?[^>]*content\s*=\s*["'][^"']*noindex/i;
2608
+ function isIndexable(html) {
2609
+ return !REFRESH_META.test(html) && !NOINDEX_META.test(html);
2610
+ }
2563
2611
  function headIsBound(html, attr) {
2564
2612
  if (REFRESH_META.test(html)) return true;
2565
2613
  const title = TITLE_TAG.exec(html);
@@ -2572,6 +2620,8 @@ async function renderSite(cfg, options = {}) {
2572
2620
  const base = normalizeBase(options.base ?? cfg.render.base);
2573
2621
  const baseUrl = (options.baseUrl ?? cfg.render.baseUrl)?.replace(/\/+$/, "");
2574
2622
  const wantHreflang = (options.hreflang ?? cfg.render.hreflang ?? true) && baseUrl !== void 0;
2623
+ const patterns = options.exclude ?? cfg.render.exclude ?? [];
2624
+ const excluded = patterns.length > 0 ? picomatch(patterns) : () => false;
2575
2625
  const sitemap = options.sitemap ?? cfg.render.sitemap ?? false;
2576
2626
  const wantSitemap = sitemap !== false && baseUrl !== void 0;
2577
2627
  const clean = options.clean ?? cfg.render.clean ?? false;
@@ -2605,7 +2655,7 @@ async function renderSite(cfg, options = {}) {
2605
2655
  const rel = relative(site, file).replace(/\\/g, "/");
2606
2656
  if (locales.length > 1 && !headIsBound(html, attribute ?? "data-verbaly")) untranslatedHead.push(rel);
2607
2657
  const alternates = wantHreflang ? pageAlternates(baseUrl, rel, locales, cfg.sourceLocale) : [];
2608
- if (wantHreflang) urls.push({
2658
+ if (wantHreflang && isIndexable(html) && !excluded(rel)) urls.push({
2609
2659
  rel,
2610
2660
  alternates
2611
2661
  });
@@ -2848,8 +2898,16 @@ const WRAP_ATTRS = /* @__PURE__ */ new Set([
2848
2898
  "placeholder",
2849
2899
  "aria-label"
2850
2900
  ]);
2901
+ const CODE_TAGS = /* @__PURE__ */ new Set([
2902
+ "code",
2903
+ "pre",
2904
+ "kbd",
2905
+ "samp",
2906
+ "var"
2907
+ ]);
2851
2908
  const T_NAMES = /* @__PURE__ */ new Set(["t"]);
2852
2909
  const LETTER = /\p{L}/u;
2910
+ const WHITESPACE = /\s/;
2853
2911
  async function wrapProject(cfg, options = {}) {
2854
2912
  const files = (await glob(cfg.include, {
2855
2913
  cwd: cfg.root,
@@ -2860,7 +2918,8 @@ async function wrapProject(cfg, options = {}) {
2860
2918
  files: files.length,
2861
2919
  changed: [],
2862
2920
  wrapped: [],
2863
- skipped: []
2921
+ skipped: [],
2922
+ blocked: []
2864
2923
  };
2865
2924
  for (const file of files) {
2866
2925
  const code = readFileSync(file, "utf8");
@@ -2868,10 +2927,17 @@ async function wrapProject(cfg, options = {}) {
2868
2927
  const out = wrapCode(code, label);
2869
2928
  result.wrapped.push(...out.wrapped);
2870
2929
  result.skipped.push(...out.skipped);
2871
- if (out.code !== void 0) {
2872
- result.changed.push(label);
2873
- if (options.write) writeFileSync(file, out.code);
2930
+ if (out.code === void 0) continue;
2931
+ result.changed.push(label);
2932
+ if (!out.hasT) {
2933
+ result.blocked.push({
2934
+ file: label,
2935
+ texts: out.wrapped.length,
2936
+ client: out.client
2937
+ });
2938
+ continue;
2874
2939
  }
2940
+ if (options.write) writeFileSync(file, out.code);
2875
2941
  }
2876
2942
  return result;
2877
2943
  }
@@ -2888,9 +2954,13 @@ function wrapCode(code, file) {
2888
2954
  } catch {
2889
2955
  return {
2890
2956
  wrapped,
2891
- skipped
2957
+ skipped,
2958
+ hasT: false,
2959
+ client: false
2892
2960
  };
2893
2961
  }
2962
+ const hasT = declaresT(ast);
2963
+ const client = hasDirective(ast, "use client");
2894
2964
  const s = new MagicString(code);
2895
2965
  const visited = /* @__PURE__ */ new Set();
2896
2966
  let changed = false;
@@ -2902,10 +2972,14 @@ function wrapCode(code, file) {
2902
2972
  return changed ? {
2903
2973
  code: s.toString(),
2904
2974
  wrapped,
2905
- skipped
2975
+ skipped,
2976
+ hasT,
2977
+ client
2906
2978
  } : {
2907
2979
  wrapped,
2908
- skipped
2980
+ skipped,
2981
+ hasT,
2982
+ client
2909
2983
  };
2910
2984
  function processElement(node) {
2911
2985
  visited.add(node);
@@ -2914,6 +2988,7 @@ function wrapCode(code, file) {
2914
2988
  const name = opening.name;
2915
2989
  if (name.type === "JSXIdentifier" && name.name === "Trans") return markSubtree(node);
2916
2990
  if (hasVerbalyAttr(opening)) return markSubtree(node);
2991
+ if (name.type === "JSXIdentifier" && CODE_TAGS.has(name.name)) return markSubtree(node);
2917
2992
  wrapAttributes(opening);
2918
2993
  }
2919
2994
  const children = node.children ?? [];
@@ -2934,6 +3009,10 @@ function wrapCode(code, file) {
2934
3009
  if (meaningful.length === 0) return;
2935
3010
  const first = meaningful[0];
2936
3011
  const last = meaningful[meaningful.length - 1];
3012
+ if (first.type === "JSXExpressionContainer" && meaningful.length > 1) {
3013
+ skip(parent, snippet(children), "starts with an interpolation: wrap the sentence by hand");
3014
+ return;
3015
+ }
2937
3016
  let template = "";
2938
3017
  let report = "";
2939
3018
  for (let i = children.indexOf(first); i <= children.indexOf(last); i++) {
@@ -2967,6 +3046,7 @@ function wrapCode(code, file) {
2967
3046
  } else return;
2968
3047
  }
2969
3048
  if (!LETTER.test(report)) return;
3049
+ if (isIdentifierLike(report)) return;
2970
3050
  const start = first.type === "JSXText" ? first.start + leadingWs(first.value) : first.start;
2971
3051
  const end = last.type === "JSXText" ? last.end - trailingWs(last.value) : last.end;
2972
3052
  s.overwrite(start, end, "{t`" + template + "`}");
@@ -2986,7 +3066,7 @@ function wrapCode(code, file) {
2986
3066
  const value = attr.value;
2987
3067
  if (value?.type !== "StringLiteral") continue;
2988
3068
  const raw = value.value;
2989
- if (!LETTER.test(raw)) continue;
3069
+ if (!LETTER.test(raw) || isIdentifierLike(raw)) continue;
2990
3070
  s.overwrite(value.start, value.end, "{t`" + escapeTemplate(raw) + "`}");
2991
3071
  changed = true;
2992
3072
  wrapped.push({
@@ -3018,6 +3098,40 @@ function wrapCode(code, file) {
3018
3098
  });
3019
3099
  }
3020
3100
  }
3101
+ function isIdentifierLike(text) {
3102
+ const trimmed = text.trim();
3103
+ if (WHITESPACE.test(trimmed)) return false;
3104
+ const first = [...trimmed].find((char) => LETTER.test(char));
3105
+ return first !== void 0 && first !== first.toUpperCase();
3106
+ }
3107
+ function hasDirective(program, value) {
3108
+ return (program.directives ?? []).some((d) => d.value?.value === value);
3109
+ }
3110
+ function declaresT(program) {
3111
+ let found = false;
3112
+ walk(program, (node) => {
3113
+ if (found) return;
3114
+ if (node.type === "ImportDeclaration") {
3115
+ for (const spec of node.specifiers) if (isTName(spec.local?.name)) found = true;
3116
+ return;
3117
+ }
3118
+ if (node.type === "VariableDeclarator" && bindsT(node.id)) found = true;
3119
+ if (node.type === "FunctionDeclaration" && isTName(node.id?.name)) found = true;
3120
+ if (node.params?.some((param) => bindsT(param))) found = true;
3121
+ });
3122
+ return found;
3123
+ }
3124
+ function bindsT(pattern) {
3125
+ if (!pattern) return false;
3126
+ if (pattern.type === "Identifier") return isTName(pattern.name);
3127
+ if (pattern.type === "AssignmentPattern") return bindsT(pattern.left);
3128
+ if (pattern.type === "ObjectPattern") return pattern.properties.some((prop) => prop.type === "RestElement" ? bindsT(prop.argument) : bindsT(prop.value));
3129
+ if (pattern.type === "ArrayPattern") return pattern.elements.some((el) => bindsT(el ?? void 0));
3130
+ return false;
3131
+ }
3132
+ function isTName(name) {
3133
+ return typeof name === "string" && T_NAMES.has(name);
3134
+ }
3021
3135
  function hasVerbalyAttr(opening) {
3022
3136
  return opening.attributes.some((attr) => {
3023
3137
  if (attr.type !== "JSXAttribute") return false;
@@ -3139,12 +3253,12 @@ async function runCli(args = process.argv.slice(2)) {
3139
3253
  const command = positionals[0];
3140
3254
  if (values.help || !command) {
3141
3255
  console.log(HELP);
3142
- process.exitCode = command ? 0 : 1;
3256
+ process.exitCode = values.help ? 0 : 1;
3143
3257
  return;
3144
3258
  }
3145
3259
  if (rejectStrayFlags(command, values)) return;
3146
3260
  if (command === "init") {
3147
- const result = init({
3261
+ const result = await init({
3148
3262
  root: values.root,
3149
3263
  dir: values.dir,
3150
3264
  sourceLocale: values.source,
@@ -3215,10 +3329,14 @@ async function runCli(args = process.argv.slice(2)) {
3215
3329
  console.log(`[verbaly] nothing to wrap (${counted(result.files, "file")} scanned) ✓`);
3216
3330
  return;
3217
3331
  }
3332
+ const blocked = new Set(result.blocked.map((entry) => entry.file));
3333
+ const done = result.changed.filter((file) => !blocked.has(file));
3334
+ const texts = result.wrapped.filter((entry) => !blocked.has(entry.file));
3218
3335
  const verb = values.write ? "wrapped" : "would wrap";
3219
3336
  const note = values.write ? "" : " (report only, use --write to apply)";
3220
- console.log(`[verbaly] ${verb} ${counted(result.wrapped.length, "text")} in ${counted(result.changed.length, "file")}${note}`);
3221
- for (const entry of result.wrapped) {
3337
+ const counts = values.write ? `${counted(texts.length, "text")} in ${counted(done.length, "file")}` : `${counted(result.wrapped.length, "text")} in ${counted(result.changed.length, "file")}`;
3338
+ console.log(`[verbaly] ${verb} ${counts}${note}`);
3339
+ for (const entry of values.write ? texts : result.wrapped) {
3222
3340
  const attr = entry.kind === "attribute" ? `${entry.attribute} → ` : "";
3223
3341
  console.log(` ${entry.file}:${entry.line} ${attr}"${entry.text}"`);
3224
3342
  }
@@ -3226,7 +3344,14 @@ async function runCli(args = process.argv.slice(2)) {
3226
3344
  console.log(" needs a human:");
3227
3345
  for (const entry of result.skipped) console.log(` ${entry.file}:${entry.line} "${entry.text}" (${entry.reason})`);
3228
3346
  }
3229
- if (values.write && result.changed.length > 0) console.log(" next: make t available where TS complains (React: const t = useT()), then run verbaly extract");
3347
+ if (result.blocked.length > 0) {
3348
+ console.log(` nothing written in ${counted(result.blocked.length, "file")} with no t in scope:`);
3349
+ for (const entry of result.blocked) {
3350
+ const how = entry.client ? "\"use client\", so const t = useT()" : "no \"use client\": check which side renders it before you pick the binding";
3351
+ console.log(` ${entry.file} ${counted(entry.texts, "text")}, ${how}`);
3352
+ }
3353
+ console.log(" next: add t there, run verbaly wrap --write again, then verbaly extract");
3354
+ } else if (values.write && done.length > 0) console.log(" next: run verbaly extract");
3230
3355
  return;
3231
3356
  }
3232
3357
  if (command === "status") {
@@ -3263,7 +3388,7 @@ async function runCli(args = process.argv.slice(2)) {
3263
3388
  return;
3264
3389
  }
3265
3390
  const brokenCount = result.broken.filter((entry) => entry.severity === "error").length;
3266
- const report = reporter === "github" ? `[verbaly] check failed: ${result.missing.length} missing, ${result.unknown.length} unknown, ${brokenCount} broken` : `[verbaly] check failed\n${formatCheckResult(result)}`;
3391
+ const report = reporter === "github" ? `[verbaly] check failed: ${result.missing.length} missing, ${result.unknown.length} unknown, ${brokenCount} broken` : `[verbaly] check failed\n${formatCheckResult(result, cfg.root)}`;
3267
3392
  console.error(`${report}\n${checkNextSteps(result)}`);
3268
3393
  process.exitCode = 1;
3269
3394
  return;