@verbaly/compiler 0.44.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/cli.js CHANGED
@@ -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",
@@ -347,11 +671,12 @@ function formatCheckResult(result) {
347
671
  }
348
672
  return lines.join("\n");
349
673
  }
350
- function checkNextSteps(result) {
674
+ function checkNextSteps(result, cliReachable = true) {
351
675
  const steps = [];
352
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`)");
353
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`");
354
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}`);
355
680
  return steps.join("\n");
356
681
  }
357
682
  function formatCheckWarnings(result) {
@@ -477,264 +802,109 @@ function generateDts(catalog) {
477
802
  lines.push(` ${JSON.stringify(key)}: { ${fields} };`);
478
803
  }
479
804
  }
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;
647
- continue;
648
- }
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
- }
655
- }
656
- return message.length;
657
- }
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]);
664
- }
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
- };
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;
689
854
  }
690
- const CONFIG_FILES = [
691
- "verbaly.config.js",
692
- "verbaly.config.mjs",
693
- "verbaly.config.ts",
694
- "verbaly.config.mts",
695
- "verbaly.config.json"
696
- ];
697
- function findConfigFile(root) {
698
- return CONFIG_FILES.find((name) => existsSync(join(root, name)));
855
+
856
+ declare module 'virtual:verbaly/locale/*' {
857
+ const messages: Record<string, string>;
858
+ export default messages;
699
859
  }
700
- async function loadConfigFile(root) {
701
- for (const name of ["verbaly.config.js", "verbaly.config.mjs"]) {
702
- const path = join(root, name);
703
- if (existsSync(path)) return (await import(pathToFileURL(path).href)).default ?? {};
704
- }
705
- for (const name of ["verbaly.config.ts", "verbaly.config.mts"]) {
706
- const path = join(root, name);
707
- if (existsSync(path)) return loadTsConfig(path);
708
- }
709
- const jsonPath = join(root, "verbaly.config.json");
710
- if (existsSync(jsonPath)) return JSON.parse(readFileSync(jsonPath, "utf8"));
711
- return {};
860
+ `;
712
861
  }
713
- async function loadTsConfig(path) {
862
+ function writeDts(cfg, catalog, file) {
863
+ file ??= join(cfg.root, "verbaly.d.ts");
864
+ const content = generateDts(catalog);
714
865
  try {
715
- const { bundleRequire } = await import("bundle-require");
716
- const { mod } = await bundleRequire({ filepath: path });
717
- return mod.default ?? {};
718
- } catch (error) {
719
- if (isModuleNotFound(error, "esbuild")) throw new Error(`[verbaly] ${path} needs esbuild: install it with pnpm add -D esbuild`, { cause: error });
720
- throw error;
721
- }
722
- }
723
- function isModuleNotFound(error, name) {
724
- return error instanceof Error && error.code === "ERR_MODULE_NOT_FOUND" && error.message.includes(name);
866
+ if (readFileSync(file, "utf8") === content) return;
867
+ } catch {}
868
+ mkdirSync(dirname(file), { recursive: true });
869
+ writeFileSync(file, content);
725
870
  }
726
- function targetLocales(cfg, override) {
727
- return (override ?? cfg.locales).filter((locale) => locale !== cfg.sourceLocale && cfg.locales.includes(locale));
871
+ //#endregion
872
+ //#region src/text.ts
873
+ function counted(count, noun, many = `${noun}s`) {
874
+ return `${count} ${count === 1 ? noun : many}`;
728
875
  }
729
- async function loadConfig(root, overrides = {}) {
730
- return resolveConfig({
731
- ...await loadConfigFile(root),
732
- ...definedOnly(overrides),
733
- root
734
- });
876
+ //#endregion
877
+ //#region src/bundle.ts
878
+ function isExcluded(key, prefixes) {
879
+ return prefixes.some((prefix) => key === prefix || key.startsWith(`${prefix}.`));
880
+ }
881
+ function auditBundle(cfg, catalogs, registry) {
882
+ const prefixes = cfg.bundle.exclude ?? [];
883
+ if (prefixes.length === 0) return [];
884
+ const source = Object.keys(catalogs[cfg.sourceLocale] ?? {});
885
+ const used = registry.usedKeys();
886
+ const issues = [];
887
+ for (const prefix of prefixes) {
888
+ if (!source.some((key) => isExcluded(key, [prefix]))) {
889
+ issues.push({
890
+ prefix,
891
+ problem: `matches no key in ${cfg.sourceLocale}.json, so it excludes nothing`,
892
+ fix: "check the spelling against your catalog, or drop it from bundle.exclude"
893
+ });
894
+ continue;
895
+ }
896
+ const files = /* @__PURE__ */ new Set();
897
+ for (const [key, where] of used) if (isExcluded(key, [prefix])) for (const file of where) files.add(file);
898
+ if (files.size > 0) issues.push({
899
+ prefix,
900
+ problem: `is read by t() in ${counted(files.size, "file")}, where it resolves to the key itself`,
901
+ fix: "pre-render those pages with render, load the group with addMessages, or stop excluding it"
902
+ });
903
+ }
904
+ return issues;
735
905
  }
736
- function definedOnly(config) {
737
- return Object.fromEntries(Object.entries(config).filter(([, value]) => value !== void 0));
906
+ function formatBundleIssue(issue) {
907
+ return `bundle.exclude "${issue.prefix}" ${issue.problem}`;
738
908
  }
739
909
  //#endregion
740
910
  //#region src/warn.ts
@@ -1291,128 +1461,6 @@ function pruneCatalogs(cfg, catalogs, registry) {
1291
1461
  return removed;
1292
1462
  }
1293
1463
  //#endregion
1294
- //#region src/init.ts
1295
- const HOSTS = [
1296
- {
1297
- name: "nuxt",
1298
- dep: "nuxt",
1299
- pkg: "@verbaly/nuxt",
1300
- wire: "add '@verbaly/nuxt' to the modules in nuxt.config"
1301
- },
1302
- {
1303
- name: "next",
1304
- dep: "next",
1305
- pkg: "@verbaly/next",
1306
- wire: "wrap the export of next.config with withVerbaly"
1307
- },
1308
- {
1309
- name: "sveltekit",
1310
- dep: "@sveltejs/kit",
1311
- pkg: "@verbaly/vite",
1312
- wire: "add verbaly() to the plugins in vite.config (per-request locale: @verbaly/sveltekit)"
1313
- },
1314
- {
1315
- name: "astro",
1316
- dep: "astro",
1317
- pkg: "@verbaly/astro",
1318
- wire: "add verbaly() to the integrations in astro.config"
1319
- },
1320
- {
1321
- name: "vite",
1322
- dep: "vite",
1323
- pkg: "@verbaly/vite",
1324
- wire: "add verbaly() to the plugins in vite.config"
1325
- },
1326
- {
1327
- name: "webpack",
1328
- dep: "webpack",
1329
- pkg: "@verbaly/unplugin",
1330
- wire: "add the verbaly webpack plugin to your build config"
1331
- },
1332
- {
1333
- name: "rspack",
1334
- dep: "@rspack/core",
1335
- pkg: "@verbaly/unplugin",
1336
- wire: "add the verbaly rspack plugin to your build config"
1337
- },
1338
- {
1339
- name: "rollup",
1340
- dep: "rollup",
1341
- pkg: "@verbaly/unplugin",
1342
- wire: "add the verbaly rollup plugin to your build config"
1343
- },
1344
- {
1345
- name: "esbuild",
1346
- dep: "esbuild",
1347
- pkg: "@verbaly/unplugin",
1348
- wire: "add the verbaly esbuild plugin to your build config"
1349
- }
1350
- ];
1351
- const WIRING_PACKAGES = [...new Set(HOSTS.map((host) => host.pkg))];
1352
- function readDependencies(root) {
1353
- const path = join(root, "package.json");
1354
- if (!existsSync(path)) return {};
1355
- try {
1356
- const pkg = JSON.parse(readFileSync(path, "utf8"));
1357
- return {
1358
- ...pkg.dependencies,
1359
- ...pkg.devDependencies
1360
- };
1361
- } catch {
1362
- return {};
1363
- }
1364
- }
1365
- function detectHost(root) {
1366
- const deps = readDependencies(root);
1367
- return HOSTS.find((host) => deps[host.dep]);
1368
- }
1369
- function configSource(options, typescript) {
1370
- const fields = [` sourceLocale: '${options.sourceLocale ?? "en"}',`];
1371
- if (options.locales?.length) fields.push(` locales: [${options.locales.map((l) => `'${l}'`).join(", ")}],`);
1372
- if (options.dir) fields.push(` dir: '${options.dir}',`);
1373
- const body = `export default {\n${fields.join("\n")}\n}`;
1374
- if (typescript) return `import type { VerbalyConfig } from '@verbaly/compiler';\n\n${body} satisfies VerbalyConfig;\n`;
1375
- return `/** @type {import('@verbaly/compiler').VerbalyConfig} */\n${body};\n`;
1376
- }
1377
- function init(options = {}) {
1378
- const root = options.root ?? process.cwd();
1379
- const created = [];
1380
- const skipped = [];
1381
- const existing = findConfigFile(root);
1382
- const typescript = existsSync(join(root, "tsconfig.json"));
1383
- const configFile = existing ?? (typescript ? "verbaly.config.ts" : "verbaly.config.mjs");
1384
- if (existing) skipped.push(existing);
1385
- else {
1386
- writeFileSync(join(root, configFile), configSource(options, typescript));
1387
- created.push(configFile);
1388
- }
1389
- const dir = join(root, options.dir ?? "locales");
1390
- if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
1391
- for (const locale of /* @__PURE__ */ new Set([options.sourceLocale ?? "en", ...options.locales ?? []])) {
1392
- const file = join(dir, `${locale}.json`);
1393
- const label = relative(root, file).replaceAll("\\", "/");
1394
- if (existsSync(file)) skipped.push(label);
1395
- else {
1396
- writeFileSync(file, "{}\n");
1397
- created.push(label);
1398
- }
1399
- }
1400
- const host = detectHost(root);
1401
- const next = host ? [`pnpm add -D ${host.pkg}`, host.wire] : ["run \"verbaly extract\" after writing your first t`…` message"];
1402
- return {
1403
- created,
1404
- skipped,
1405
- host: host?.name,
1406
- configFile,
1407
- next
1408
- };
1409
- }
1410
- //#endregion
1411
- //#region src/text.ts
1412
- function counted(count, noun, many = `${noun}s`) {
1413
- return `${count} ${count === 1 ? noun : many}`;
1414
- }
1415
- //#endregion
1416
1464
  //#region src/doctor.ts
1417
1465
  const PREVIEW = 5;
1418
1466
  function readRoutingChoice(root, configFile) {
@@ -1460,6 +1508,8 @@ async function doctor(cfg) {
1460
1508
  const configFile = findConfigFile(cfg.root);
1461
1509
  if (configFile) ok("config", `${configFile} found`);
1462
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);
1463
1513
  const catalogs = {};
1464
1514
  let catalogsHealthy = true;
1465
1515
  if (!existsSync(cfg.dir)) {
@@ -1485,7 +1535,10 @@ async function doctor(cfg) {
1485
1535
  error(`locale ${locale}`, `${rel(file)} is not valid JSON`, "repair the file (or delete it and run `npx verbaly extract`)");
1486
1536
  }
1487
1537
  }
1488
- if (catalogsHealthy) ok("catalogs", `${counted(cfg.locales.length, "locale")} (${cfg.locales.join(", ")}) in ${rel(cfg.dir)}/`);
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
+ }
1489
1542
  }
1490
1543
  const source = catalogs[cfg.sourceLocale];
1491
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`");
@@ -1534,6 +1587,12 @@ async function doctor(cfg) {
1534
1587
  if (orphans.length > 0) warn("orphans", `${counted(orphans.length, "catalog key")} no longer referenced in code (${preview(orphans)})`, "run `npx verbaly extract --prune` to drop them");
1535
1588
  else ok("orphans", "no orphan keys");
1536
1589
  }
1590
+ const excluded = cfg.bundle.exclude ?? [];
1591
+ if (excluded.length > 0 && catalogsHealthy) {
1592
+ const issues = auditBundle(cfg, catalogs, registry);
1593
+ for (const issue of issues) warn("bundle", formatBundleIssue(issue), issue.fix);
1594
+ if (issues.length === 0) ok("bundle", `${counted(excluded.length, "group")} kept out of the client (${preview(excluded)})`);
1595
+ }
1537
1596
  if (catalogsHealthy) {
1538
1597
  const result = check(cfg, catalogs, registry);
1539
1598
  if (result.unknown.length > 0) error("keys", `${counted(result.unknown.length, "unknown key")} used in code (${preview(result.unknown.map((u) => u.key))})`, "fix the key or add it to the catalogs (`npx verbaly check` for details)");
@@ -2808,8 +2867,16 @@ const WRAP_ATTRS = /* @__PURE__ */ new Set([
2808
2867
  "placeholder",
2809
2868
  "aria-label"
2810
2869
  ]);
2870
+ const CODE_TAGS = /* @__PURE__ */ new Set([
2871
+ "code",
2872
+ "pre",
2873
+ "kbd",
2874
+ "samp",
2875
+ "var"
2876
+ ]);
2811
2877
  const T_NAMES = /* @__PURE__ */ new Set(["t"]);
2812
2878
  const LETTER = /\p{L}/u;
2879
+ const WHITESPACE = /\s/;
2813
2880
  async function wrapProject(cfg, options = {}) {
2814
2881
  const files = (await glob(cfg.include, {
2815
2882
  cwd: cfg.root,
@@ -2820,7 +2887,8 @@ async function wrapProject(cfg, options = {}) {
2820
2887
  files: files.length,
2821
2888
  changed: [],
2822
2889
  wrapped: [],
2823
- skipped: []
2890
+ skipped: [],
2891
+ blocked: []
2824
2892
  };
2825
2893
  for (const file of files) {
2826
2894
  const code = readFileSync(file, "utf8");
@@ -2828,10 +2896,17 @@ async function wrapProject(cfg, options = {}) {
2828
2896
  const out = wrapCode(code, label);
2829
2897
  result.wrapped.push(...out.wrapped);
2830
2898
  result.skipped.push(...out.skipped);
2831
- if (out.code !== void 0) {
2832
- result.changed.push(label);
2833
- if (options.write) writeFileSync(file, out.code);
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;
2834
2908
  }
2909
+ if (options.write) writeFileSync(file, out.code);
2835
2910
  }
2836
2911
  return result;
2837
2912
  }
@@ -2848,9 +2923,13 @@ function wrapCode(code, file) {
2848
2923
  } catch {
2849
2924
  return {
2850
2925
  wrapped,
2851
- skipped
2926
+ skipped,
2927
+ hasT: false,
2928
+ client: false
2852
2929
  };
2853
2930
  }
2931
+ const hasT = declaresT(ast);
2932
+ const client = hasDirective(ast, "use client");
2854
2933
  const s = new MagicString(code);
2855
2934
  const visited = /* @__PURE__ */ new Set();
2856
2935
  let changed = false;
@@ -2862,10 +2941,14 @@ function wrapCode(code, file) {
2862
2941
  return changed ? {
2863
2942
  code: s.toString(),
2864
2943
  wrapped,
2865
- skipped
2944
+ skipped,
2945
+ hasT,
2946
+ client
2866
2947
  } : {
2867
2948
  wrapped,
2868
- skipped
2949
+ skipped,
2950
+ hasT,
2951
+ client
2869
2952
  };
2870
2953
  function processElement(node) {
2871
2954
  visited.add(node);
@@ -2874,6 +2957,7 @@ function wrapCode(code, file) {
2874
2957
  const name = opening.name;
2875
2958
  if (name.type === "JSXIdentifier" && name.name === "Trans") return markSubtree(node);
2876
2959
  if (hasVerbalyAttr(opening)) return markSubtree(node);
2960
+ if (name.type === "JSXIdentifier" && CODE_TAGS.has(name.name)) return markSubtree(node);
2877
2961
  wrapAttributes(opening);
2878
2962
  }
2879
2963
  const children = node.children ?? [];
@@ -2894,6 +2978,10 @@ function wrapCode(code, file) {
2894
2978
  if (meaningful.length === 0) return;
2895
2979
  const first = meaningful[0];
2896
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
+ }
2897
2985
  let template = "";
2898
2986
  let report = "";
2899
2987
  for (let i = children.indexOf(first); i <= children.indexOf(last); i++) {
@@ -2927,6 +3015,7 @@ function wrapCode(code, file) {
2927
3015
  } else return;
2928
3016
  }
2929
3017
  if (!LETTER.test(report)) return;
3018
+ if (isIdentifierLike(report)) return;
2930
3019
  const start = first.type === "JSXText" ? first.start + leadingWs(first.value) : first.start;
2931
3020
  const end = last.type === "JSXText" ? last.end - trailingWs(last.value) : last.end;
2932
3021
  s.overwrite(start, end, "{t`" + template + "`}");
@@ -2946,7 +3035,7 @@ function wrapCode(code, file) {
2946
3035
  const value = attr.value;
2947
3036
  if (value?.type !== "StringLiteral") continue;
2948
3037
  const raw = value.value;
2949
- if (!LETTER.test(raw)) continue;
3038
+ if (!LETTER.test(raw) || isIdentifierLike(raw)) continue;
2950
3039
  s.overwrite(value.start, value.end, "{t`" + escapeTemplate(raw) + "`}");
2951
3040
  changed = true;
2952
3041
  wrapped.push({
@@ -2978,6 +3067,40 @@ function wrapCode(code, file) {
2978
3067
  });
2979
3068
  }
2980
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
+ }
2981
3104
  function hasVerbalyAttr(opening) {
2982
3105
  return opening.attributes.some((attr) => {
2983
3106
  if (attr.type !== "JSXAttribute") return false;
@@ -3099,12 +3222,12 @@ async function runCli(args = process.argv.slice(2)) {
3099
3222
  const command = positionals[0];
3100
3223
  if (values.help || !command) {
3101
3224
  console.log(HELP);
3102
- process.exitCode = command ? 0 : 1;
3225
+ process.exitCode = values.help ? 0 : 1;
3103
3226
  return;
3104
3227
  }
3105
3228
  if (rejectStrayFlags(command, values)) return;
3106
3229
  if (command === "init") {
3107
- const result = init({
3230
+ const result = await init({
3108
3231
  root: values.root,
3109
3232
  dir: values.dir,
3110
3233
  sourceLocale: values.source,
@@ -3175,10 +3298,14 @@ async function runCli(args = process.argv.slice(2)) {
3175
3298
  console.log(`[verbaly] nothing to wrap (${counted(result.files, "file")} scanned) ✓`);
3176
3299
  return;
3177
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));
3178
3304
  const verb = values.write ? "wrapped" : "would wrap";
3179
3305
  const note = values.write ? "" : " (report only, use --write to apply)";
3180
- console.log(`[verbaly] ${verb} ${counted(result.wrapped.length, "text")} in ${counted(result.changed.length, "file")}${note}`);
3181
- for (const entry of result.wrapped) {
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) {
3182
3309
  const attr = entry.kind === "attribute" ? `${entry.attribute} → ` : "";
3183
3310
  console.log(` ${entry.file}:${entry.line} ${attr}"${entry.text}"`);
3184
3311
  }
@@ -3186,7 +3313,14 @@ async function runCli(args = process.argv.slice(2)) {
3186
3313
  console.log(" needs a human:");
3187
3314
  for (const entry of result.skipped) console.log(` ${entry.file}:${entry.line} "${entry.text}" (${entry.reason})`);
3188
3315
  }
3189
- if (values.write && result.changed.length > 0) console.log(" next: make t available where TS complains (React: const t = useT()), then run verbaly extract");
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");
3190
3324
  return;
3191
3325
  }
3192
3326
  if (command === "status") {