@verbaly/compiler 0.38.0 → 0.40.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
@@ -488,6 +488,15 @@ ${lines.join("\n")}
488
488
 
489
489
  export const sourceLocale: string;
490
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;
491
500
  export function loadMessages(locale: string): Promise<Record<string, string>>;
492
501
  export function createInstance(
493
502
  options?: import('verbaly').VerbalyOptions<VerbalyKey>,
@@ -660,6 +669,7 @@ function resolveConfig(config = {}) {
660
669
  root,
661
670
  dir,
662
671
  sourceLocale,
672
+ routing: config.routing ?? "prefix-except-source",
663
673
  locales: [...locales],
664
674
  include: config.include ?? ["{src,app}/**/*.{js,jsx,ts,tsx,mjs,mts,svelte,vue,astro}"],
665
675
  exclude: config.exclude ?? ["**/node_modules/**", "**/dist/**"],
@@ -1396,6 +1406,21 @@ function counted(count, noun, many = `${noun}s`) {
1396
1406
  //#endregion
1397
1407
  //#region src/doctor.ts
1398
1408
  const PREVIEW = 5;
1409
+ const ROUTING_SAYS = {
1410
+ "prefix-except-source": "the source locale has no prefix, every other locale does",
1411
+ "prefix-all": "every locale has a prefix, the source included",
1412
+ "no-prefix": "the language is not in the url, one address serves every locale"
1413
+ };
1414
+ const ICON = {
1415
+ ok: "✓",
1416
+ warn: "⚠",
1417
+ error: "✗"
1418
+ };
1419
+ function formatDoctorEntry(entry) {
1420
+ const head = ` ${ICON[entry.level]} ${entry.check}: ${entry.message}`;
1421
+ return entry.fix ? `${head}
1422
+ fix: ${entry.fix}` : head;
1423
+ }
1399
1424
  async function doctor(cfg) {
1400
1425
  const entries = [];
1401
1426
  const ok = (name, message) => entries.push({
@@ -1448,6 +1473,9 @@ async function doctor(cfg) {
1448
1473
  }
1449
1474
  const source = catalogs[cfg.sourceLocale];
1450
1475
  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`");
1476
+ const mirrors = cfg.render.site !== void 0 || Object.keys(cfg.render).length > 0;
1477
+ if (cfg.routing === "no-prefix" && mirrors) warn("routing", "routing is \"no-prefix\" but a render section is configured, and render writes one url tree per locale", "drop the render section, or set routing to \"prefix-except-source\" so the helpers agree with the urls");
1478
+ else ok("routing", `${cfg.routing}: ${ROUTING_SAYS[cfg.routing]}`);
1451
1479
  const deps = readDependencies(cfg.root);
1452
1480
  const host = detectHost(cfg.root);
1453
1481
  const installed = WIRING_PACKAGES.find((pkg) => deps[pkg]);
@@ -1467,41 +1495,40 @@ async function doctor(cfg) {
1467
1495
  const unreadable = registry.parseErrors();
1468
1496
  if (unreadable.length > 0) {
1469
1497
  const first = unreadable[0];
1470
- const one = unreadable.length === 1;
1471
- warn("sources", `${unreadable.length} ${one ? "file" : "files"} could not be parsed, so ${one ? "its" : "their"} messages are not extracted (${rel(first.file)}: ${first.message})`, "fix the syntax error, or exclude the file in your config if it is not source");
1498
+ warn("sources", `could not parse ${counted(unreadable.length, "file")}, so the messages inside are not extracted (${rel(first.file)}: ${first.message})`, "fix the syntax error, or exclude the file in your config if it is not source");
1472
1499
  }
1473
1500
  const stray = registry.strayImports();
1474
1501
  if (stray.length > 0) {
1475
1502
  const files = [...new Set(stray.map((entry) => rel(entry.file)))];
1476
- error("imports", `${files.length} ${files.length === 1 ? "file imports" : "files import"} t from a verbaly package, which never exports it (${preview(files)})`, "t comes from your instance (React: const t = useT()) or from virtual:verbaly");
1503
+ error("imports", `t is imported from a verbaly package, which never exports it, in ${counted(files.length, "file")} (${preview(files)})`, "t comes from your instance (React: const t = useT()) or from virtual:verbaly");
1477
1504
  }
1478
1505
  const escaped = [...registry.messages().values()].map((msg) => ({
1479
1506
  file: rel(msg.file),
1480
1507
  slice: escapedSyntax(msg.message)
1481
1508
  })).filter((entry) => entry.slice !== void 0);
1482
- if (escaped.length > 0) warn("messages", `${escaped.length} extracted ${escaped.length === 1 ? "message keeps" : "messages keep"} a block as literal text (${escaped[0].file}: ${escaped[0].slice})`, "a tagged template takes its values from ${…}: use t(key, params) for a plural or format block");
1509
+ if (escaped.length > 0) warn("messages", `a block ships as literal text in ${counted(escaped.length, "extracted message")} (${escaped[0].file}: ${escaped[0].slice})`, "a tagged template takes its values from ${…}: use t(key, params) for a plural or format block");
1483
1510
  }
1484
1511
  if (source && scanning) {
1485
1512
  const extracted = registry.messages();
1486
1513
  const used = registry.usedKeys();
1487
1514
  const orphans = Object.keys(source).filter((key) => !extracted.has(key) && !used.has(key));
1488
- if (orphans.length > 0) warn("orphans", `${orphans.length} catalog ${orphans.length === 1 ? "key is" : "keys are"} no longer referenced (${preview(orphans)})`, "run `npx verbaly extract --prune` to drop them");
1515
+ 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");
1489
1516
  else ok("orphans", "no orphan keys");
1490
1517
  }
1491
1518
  if (catalogsHealthy) {
1492
1519
  const result = check(cfg, catalogs, registry);
1493
- if (result.unknown.length > 0) error("keys", `${result.unknown.length} unknown ${result.unknown.length === 1 ? "key" : "keys"} used in code (${preview(result.unknown.map((u) => u.key))})`, "fix the key or add it to the catalogs (`npx verbaly check` for details)");
1520
+ 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)");
1494
1521
  if (result.missing.length > 0) {
1495
1522
  const locales = [...new Set(result.missing.map((m) => m.locale))];
1496
- warn("translations", `${result.missing.length} missing ${result.missing.length === 1 ? "translation" : "translations"} (${locales.join(", ")})`, "run `npx verbaly translate` or fill the catalogs (`npx verbaly check` for details)");
1523
+ warn("translations", `${counted(result.missing.length, "missing translation")} (${locales.join(", ")})`, "run `npx verbaly translate` or fill the catalogs (`npx verbaly check` for details)");
1497
1524
  }
1498
1525
  const broken = result.broken.filter((entry) => entry.severity === "error");
1499
1526
  if (broken.length > 0) {
1500
1527
  const locales = [...new Set(broken.map((b) => b.locale))];
1501
- error("translations", `${broken.length} broken ${broken.length === 1 ? "translation" : "translations"} (${locales.join(", ")}): present but not rendering what the source renders`, "run `npx verbaly check` to read what each one lost");
1528
+ error("translations", `${counted(broken.length, "broken translation")} (${locales.join(", ")}): present but not rendering what the source renders`, "run `npx verbaly check` to read what each one lost");
1502
1529
  }
1503
1530
  const warnings = result.broken.filter((entry) => entry.severity === "warning");
1504
- if (warnings.length > 0) warn("translations", `${warnings.length} structural ${warnings.length === 1 ? "warning" : "warnings"} (plural forms a language asks for)`, "run `npx verbaly check` to read them, they never fail the build");
1531
+ if (warnings.length > 0) warn("translations", `${counted(warnings.length, "structural warning")} (plural forms a language asks for)`, "run `npx verbaly check` to read them, they never fail the build");
1505
1532
  if (result.ok) ok("translations", "all translations complete");
1506
1533
  }
1507
1534
  return {
@@ -1921,15 +1948,56 @@ function poUnquote(text) {
1921
1948
  }
1922
1949
  //#endregion
1923
1950
  //#region src/translate.ts
1951
+ const RETRY_STATUS = /* @__PURE__ */ new Set([
1952
+ 408,
1953
+ 409,
1954
+ 425,
1955
+ 429,
1956
+ 500,
1957
+ 502,
1958
+ 503,
1959
+ 504,
1960
+ 529
1961
+ ]);
1962
+ function retryable(error) {
1963
+ const status = error?.status;
1964
+ const code = error?.statusCode;
1965
+ const value = typeof status === "number" ? status : code;
1966
+ return typeof value === "number" ? RETRY_STATUS.has(value) : true;
1967
+ }
1968
+ function reason(error) {
1969
+ return error instanceof Error ? error.message : String(error);
1970
+ }
1971
+ const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
1972
+ async function attempt(run, retries, delay) {
1973
+ for (let round = 0;; round++) try {
1974
+ return await run();
1975
+ } catch (error) {
1976
+ if (round >= retries || !retryable(error)) throw error;
1977
+ await wait(delay * 2 ** round);
1978
+ }
1979
+ }
1980
+ async function pooled(jobs, limit, run) {
1981
+ let next = 0;
1982
+ const workers = Array.from({ length: Math.min(limit, jobs.length) }, async () => {
1983
+ while (next < jobs.length) await run(jobs[next++]);
1984
+ });
1985
+ await Promise.all(workers);
1986
+ }
1924
1987
  async function translateCatalogs(cfg, catalogs, provider, options = {}) {
1925
1988
  const batchSize = options.batchSize ?? 20;
1989
+ const concurrency = Math.max(1, options.concurrency ?? 4);
1990
+ const retries = Math.max(0, options.retries ?? 2);
1991
+ const retryDelay = options.retryDelay ?? 500;
1926
1992
  const targets = targetLocales(cfg, options.locales);
1927
1993
  const source = catalogs[cfg.sourceLocale] ?? {};
1928
1994
  const result = {
1929
1995
  translated: {},
1930
1996
  invalid: {},
1931
- pending: {}
1997
+ pending: {},
1998
+ failed: []
1932
1999
  };
2000
+ const jobs = [];
1933
2001
  for (const locale of targets) {
1934
2002
  const catalog = catalogs[locale] ??= {};
1935
2003
  const missing = Object.keys(source).filter((key) => source[key] && !catalog[key]);
@@ -1938,31 +2006,78 @@ async function translateCatalogs(cfg, catalogs, provider, options = {}) {
1938
2006
  result.pending[locale] = missing;
1939
2007
  continue;
1940
2008
  }
2009
+ const batches = Math.ceil(missing.length / batchSize);
1941
2010
  for (let i = 0; i < missing.length; i += batchSize) {
1942
- const keys = missing.slice(i, i + batchSize);
1943
- const messages = Object.fromEntries(keys.map((key) => [key, source[key]]));
1944
- const origins = options.origins ? Object.fromEntries(keys.filter((key) => options.origins[key]).map((key) => [key, options.origins[key]])) : void 0;
1945
- const out = await provider({
2011
+ const index = Math.floor(i / batchSize) + 1;
2012
+ jobs.push({
2013
+ locale,
2014
+ index,
2015
+ batches,
2016
+ keys: missing.slice(i, i + batchSize)
2017
+ });
2018
+ }
2019
+ }
2020
+ await pooled(jobs, concurrency, async (job) => {
2021
+ const { locale, keys } = job;
2022
+ const catalog = catalogs[locale];
2023
+ const messages = Object.fromEntries(keys.map((key) => [key, source[key]]));
2024
+ const origins = options.origins ? Object.fromEntries(keys.filter((key) => options.origins[key]).map((key) => [key, options.origins[key]])) : void 0;
2025
+ let out;
2026
+ try {
2027
+ out = await attempt(() => provider({
1946
2028
  sourceLocale: cfg.sourceLocale,
1947
2029
  targetLocale: locale,
1948
2030
  messages,
1949
- origins
2031
+ origins,
2032
+ instructions: cfg.translate.instructions,
2033
+ glossary: glossaryFor(cfg, locale, messages)
2034
+ }), retries, retryDelay);
2035
+ } catch (error) {
2036
+ const message = reason(error);
2037
+ result.failed.push({
2038
+ locale,
2039
+ keys,
2040
+ error: message
1950
2041
  });
1951
- for (const key of keys) {
1952
- const text = out[key];
1953
- if (typeof text === "string" && text.trim() && structureMatches(source[key], text)) {
1954
- catalog[key] = text;
1955
- (result.translated[locale] ??= []).push(key);
1956
- } else (result.invalid[locale] ??= []).push(key);
1957
- }
2042
+ options.onProgress?.({
2043
+ ...progressOf(job),
2044
+ error: message
2045
+ });
2046
+ return;
1958
2047
  }
1959
- }
2048
+ for (const key of keys) {
2049
+ const text = out[key];
2050
+ if (typeof text === "string" && text.trim() && structureMatches(source[key], text)) {
2051
+ catalog[key] = text;
2052
+ (result.translated[locale] ??= []).push(key);
2053
+ } else (result.invalid[locale] ??= []).push(key);
2054
+ }
2055
+ options.onProgress?.(progressOf(job));
2056
+ });
2057
+ for (const locale of Object.keys(result.translated)) result.translated[locale].sort();
2058
+ for (const locale of Object.keys(result.invalid)) result.invalid[locale].sort();
2059
+ result.failed.sort((a, b) => a.locale.localeCompare(b.locale) || compare(a.keys, b.keys));
1960
2060
  return result;
1961
2061
  }
2062
+ function compare(a, b) {
2063
+ return (a[0] ?? "").localeCompare(b[0] ?? "");
2064
+ }
2065
+ function formatTranslateFailures(failed) {
2066
+ const grouped = [];
2067
+ for (const entry of failed) {
2068
+ const same = grouped.find((it) => it.locale === entry.locale && it.error === entry.error);
2069
+ if (same) same.keys = [...same.keys, ...entry.keys];
2070
+ else grouped.push({
2071
+ ...entry,
2072
+ keys: [...entry.keys]
2073
+ });
2074
+ }
2075
+ return grouped.map(({ locale, error, keys }) => ` ${locale}: ${counted(keys.length, "message")} not translated (${error}): ${keys.join(", ")}`);
2076
+ }
1962
2077
  async function resolveProvider(cfg, model) {
1963
2078
  const configured = cfg.translate.provider;
1964
2079
  if (typeof configured === "function") return configured;
1965
- const { claudeProvider } = await import("./claude-h9WA0ppg.js");
2080
+ const { claudeProvider } = await import("./claude-ByRATJ03.js");
1966
2081
  return claudeProvider({ model: model ?? cfg.translate.model });
1967
2082
  }
1968
2083
  function structureMatches(source, translated) {
@@ -1972,6 +2087,26 @@ function structureMatches(source, translated) {
1972
2087
  return false;
1973
2088
  }
1974
2089
  }
2090
+ function progressOf(job) {
2091
+ return {
2092
+ locale: job.locale,
2093
+ batch: job.index,
2094
+ batches: job.batches,
2095
+ keys: job.keys.length
2096
+ };
2097
+ }
2098
+ function glossaryFor(cfg, locale, messages) {
2099
+ const entries = cfg.translate.glossary;
2100
+ if (!entries) return void 0;
2101
+ const text = Object.values(messages).join("\n").toLowerCase();
2102
+ const out = {};
2103
+ for (const [term, rendering] of Object.entries(entries)) {
2104
+ if (!text.includes(term.toLowerCase())) continue;
2105
+ const value = typeof rendering === "string" ? rendering : rendering[locale];
2106
+ if (value) out[term] = value;
2107
+ }
2108
+ return Object.keys(out).length > 0 ? out : void 0;
2109
+ }
1975
2110
  //#endregion
1976
2111
  //#region src/exchange.ts
1977
2112
  function isMobileFormat(format) {
@@ -2364,6 +2499,13 @@ function injectAlternates(ms, html, alternates) {
2364
2499
  const head = /<\/head\s*>/i.exec(html);
2365
2500
  if (head) ms.appendLeft(head.index, block);
2366
2501
  }
2502
+ const TITLE_TAG = /<title\b([^>]*)>/i;
2503
+ const REFRESH_META = /<meta\b[^>]*http-equiv\s*=\s*["']?refresh/i;
2504
+ function headIsBound(html, attr) {
2505
+ if (REFRESH_META.test(html)) return true;
2506
+ const title = TITLE_TAG.exec(html);
2507
+ return title ? title[1].includes(attr) : true;
2508
+ }
2367
2509
  async function renderSite(cfg, options = {}) {
2368
2510
  const site = join(cfg.root, options.site ?? cfg.render.site ?? "dist");
2369
2511
  const locales = options.locales ?? cfg.locales;
@@ -2397,10 +2539,12 @@ async function renderSite(cfg, options = {}) {
2397
2539
  });
2398
2540
  const pages = new Set(files.map((file) => publicPath(relative(site, file).replace(/\\/g, "/"))));
2399
2541
  const missing = {};
2542
+ const untranslatedHead = [];
2400
2543
  const urls = [];
2401
2544
  for (const file of files) {
2402
2545
  const html = readFileSync(file, "utf8");
2403
2546
  const rel = relative(site, file).replace(/\\/g, "/");
2547
+ if (locales.length > 1 && !headIsBound(html, attribute ?? "data-verbaly")) untranslatedHead.push(rel);
2404
2548
  const alternates = wantHreflang ? pageAlternates(baseUrl, rel, locales, cfg.sourceLocale) : [];
2405
2549
  if (wantHreflang) urls.push({
2406
2550
  rel,
@@ -2436,9 +2580,16 @@ async function renderSite(cfg, options = {}) {
2436
2580
  return {
2437
2581
  files: files.length,
2438
2582
  locales: [...locales],
2439
- missing
2583
+ missing,
2584
+ untranslatedHead
2440
2585
  };
2441
2586
  }
2587
+ function formatRenderWarnings(result, sourceLocale) {
2588
+ const lines = [];
2589
+ for (const [locale, keys] of Object.entries(result.missing)) lines.push(` ${locale}: ${counted(keys.length, "key")} not pre-filled: ${keys.join(", ")}`);
2590
+ if (result.untranslatedHead.length > 0) lines.push(` ${counted(result.untranslatedHead.length, "page")} of ${result.files} ship the same <title> in every locale (${result.untranslatedHead[0]}), so search results read in ${sourceLocale}`, ` fix: bind the head too, <title data-verbaly="key"> and a meta through data-verbaly-attr`);
2591
+ return lines;
2592
+ }
2442
2593
  function pageUrl(baseUrl, prefix, rel) {
2443
2594
  const path = rel.replace(/(^|\/)index\.html$/, "$1");
2444
2595
  return `${baseUrl}${prefix}${path ? `/${path}` : "/"}`;
@@ -2953,18 +3104,12 @@ async function runCli(args = process.argv.slice(2)) {
2953
3104
  });
2954
3105
  if (command === "doctor") {
2955
3106
  const result = await doctor(cfg);
2956
- const icon = {
2957
- ok: "✓",
2958
- warn: "⚠",
2959
- error: "✗"
2960
- };
2961
3107
  console.log(`[verbaly] doctor: ${counted(result.entries.length, "check")}`);
2962
3108
  for (const entry of result.entries) {
2963
- const line = ` ${icon[entry.level]} ${entry.check}: ${entry.message}`;
3109
+ const line = formatDoctorEntry(entry);
2964
3110
  if (entry.level === "error") console.error(line);
2965
3111
  else if (entry.level === "warn") console.warn(line);
2966
3112
  else console.log(line);
2967
- if (entry.fix) console.log(` fix: ${entry.fix}`);
2968
3113
  }
2969
3114
  if (result.ok) console.log("[verbaly] setup looks healthy ✓");
2970
3115
  else {
@@ -3069,8 +3214,11 @@ async function runCli(args = process.argv.slice(2)) {
3069
3214
  const result = await translateCatalogs(cfg, catalogs, await resolveProvider(cfg, values.model), {
3070
3215
  locales: values.locales?.split(","),
3071
3216
  batchSize: cfg.translate.batchSize,
3217
+ concurrency: cfg.translate.concurrency,
3218
+ retries: cfg.translate.retries,
3072
3219
  dryRun: values["dry-run"],
3073
- origins: values["dry-run"] ? void 0 : await collectOrigins(cfg)
3220
+ origins: values["dry-run"] ? void 0 : await collectOrigins(cfg),
3221
+ onProgress: values["dry-run"] ? void 0 : reportProgress
3074
3222
  });
3075
3223
  if (values["dry-run"]) {
3076
3224
  const entries = Object.entries(result.pending);
@@ -3089,7 +3237,9 @@ async function runCli(args = process.argv.slice(2)) {
3089
3237
  }
3090
3238
  if (Object.keys(result.translated).length > 0) saveDrafts(cfg, drafts);
3091
3239
  for (const [locale, keys] of Object.entries(result.invalid)) console.warn(` ${locale}: ${keys.length} rejected (params/tags not preserved): ${keys.join(", ")}`);
3092
- if (Object.keys(result.translated).length === 0 && Object.keys(result.invalid).length === 0) console.log("[verbaly] nothing to translate ✓");
3240
+ for (const line of formatTranslateFailures(result.failed)) console.error(line);
3241
+ if (result.failed.length > 0) process.exitCode = 1;
3242
+ if (Object.keys(result.translated).length === 0 && Object.keys(result.invalid).length === 0 && result.failed.length === 0) console.log("[verbaly] nothing to translate ✓");
3093
3243
  return;
3094
3244
  }
3095
3245
  if (command === "review") {
@@ -3195,7 +3345,7 @@ async function runCli(args = process.argv.slice(2)) {
3195
3345
  clean: values.clean
3196
3346
  });
3197
3347
  console.log(`[verbaly] ${counted(result.files, "page")} × ${counted(result.locales.length, "locale")} (${result.locales.join(", ")})`);
3198
- for (const [locale, keys] of Object.entries(result.missing)) console.warn(` ${locale}: ${counted(keys.length, "key")} not pre-filled: ${keys.join(", ")}`);
3348
+ for (const line of formatRenderWarnings(result, cfg.sourceLocale)) console.warn(line);
3199
3349
  return;
3200
3350
  }
3201
3351
  if (command === "pseudo") {
@@ -3209,6 +3359,11 @@ async function runCli(args = process.argv.slice(2)) {
3209
3359
  console.error(`[verbaly] unknown command "${command}"\n${HELP}`);
3210
3360
  process.exitCode = 1;
3211
3361
  }
3362
+ function reportProgress(progress) {
3363
+ const head = ` ${progress.locale} ${progress.batch}/${progress.batches}`;
3364
+ if (progress.error) console.warn(`${head}: failed (${progress.error}), continuing`);
3365
+ else console.log(`${head}: ${counted(progress.keys, "message")}`);
3366
+ }
3212
3367
  function formatCliError(error) {
3213
3368
  const message = error instanceof Error ? error.message : String(error);
3214
3369
  return message.startsWith("[verbaly]") ? message : `[verbaly] ${message}`;