@menapo/vi18n 0.1.1 → 0.1.2

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.
Files changed (118) hide show
  1. package/dist/{apply-Bre-lY9J.js → apply-FAHl1R6T.js} +69 -89
  2. package/dist/{captured-Bj8bO6vd.js → captured-CTjjDF5o.js} +196 -217
  3. package/dist/{check-BIKEuu6B.js → check-DwFwOB1d.js} +66 -84
  4. package/dist/cli.js +2 -3
  5. package/dist/{collect-Cx4_SKOe.js → collect-CYATDjdo.js} +1 -2
  6. package/dist/collisions-uMTuq36M.js +215 -0
  7. package/dist/compile-CEvH-6sY.js +240 -0
  8. package/dist/{compile-Cc97JaW2.js → compile-DqkofbiO.js} +376 -331
  9. package/dist/concurrency-BCY_4zcr.js +1 -0
  10. package/dist/concurrency-Dy2ny50V.js +107 -0
  11. package/dist/config.d.ts +1 -5
  12. package/dist/config.js +4 -5
  13. package/dist/{types-D3QGM8XO.js → diagnostics-1onDF6Ua.js} +26 -26
  14. package/dist/{dir-zw6bGMKQ.js → dir-TGLYuOZb.js} +34 -37
  15. package/dist/{duplicates-yuRljQ6h.js → duplicates-CsUXRX2J.js} +10 -27
  16. package/dist/engine-Bf7nVigL.js +556 -0
  17. package/dist/engine.d.ts +1 -5
  18. package/dist/engine.js +297 -168
  19. package/dist/exchange-DYG9RZoT.js +41 -0
  20. package/dist/{exclude-Du-Zd_qI.js → exclude-vMnm3lqU.js} +2 -3
  21. package/dist/{export-C9Sy6UWv.js → export-BYq0gfLd.js} +17 -38
  22. package/dist/{extract-C3S8btx0.js → extract-CYtuEo8u.js} +114 -82
  23. package/dist/{formats-9unqj_fZ.js → formats-ChV1LVH_.js} +352 -276
  24. package/dist/fs-ezCMZeDV.js +52 -0
  25. package/dist/i18next-1waHziMy.js +1 -0
  26. package/dist/i18next-D66Icz3L.js +1907 -0
  27. package/dist/{import-nANvQutw.js → import-BApbQlmm.js} +81 -75
  28. package/dist/index.d.ts +1 -13
  29. package/dist/index.js +14 -16
  30. package/dist/{init-C2ScuW6a.js → init-J7AwwA5e.js} +466 -501
  31. package/dist/{library-D5CWvTQs.js → library-BfSOBeBd.js} +975 -451
  32. package/dist/lingui-Ee2farVo.js +902 -0
  33. package/dist/lint.d.ts +0 -4
  34. package/dist/lint.js +68 -81
  35. package/dist/{load-gW-oJt1Q.js → load-BFLLqY8x.js} +272 -147
  36. package/dist/{load-CQRz4PpM.js → load-CMwhukZ4.js} +1211 -1115
  37. package/dist/{locales-DX4MOBFE.js → locales-DxLDrx-h.js} +271 -237
  38. package/dist/{lsp-RMMMc88P.js → lsp-BC7xDGON.js} +4 -5
  39. package/dist/{match-BGr8EXB3.js → match-BLDcj610.js} +11 -4
  40. package/dist/{mcp-CHVwBoRP.js → mcp-Cka8ywDF.js} +4 -5
  41. package/dist/{merge-driver-BTX87aVm.js → merge-driver-B04Apm29.js} +138 -122
  42. package/dist/migrate-D7TNl6SD.js +2169 -0
  43. package/dist/migrate-khCY8TE0.js +1 -0
  44. package/dist/{openai-CTaMDcl-.js → openai-RWw0YlAx.js} +128 -87
  45. package/dist/{output-DWE3SIUA.js → output-CF9uvk_-.js} +15 -9
  46. package/dist/parse.d.ts +1 -3
  47. package/dist/parse.js +7 -8
  48. package/dist/{pipeline-DbX6rlo5.js → pipeline-B30irGMD.js} +1 -1
  49. package/dist/{pipeline-C9Dbotkh.js → pipeline-sgl_q_op.js} +387 -359
  50. package/dist/project-DSzWKU3C.js +544 -0
  51. package/dist/{pseudo-DRv30iN5.js → pseudo-DNbNNVGP.js} +125 -3
  52. package/dist/{raw-C4Y6vyGY.js → raw-YsYZMS9n.js} +52 -29
  53. package/dist/react-intl-tzGIk6G3.js +634 -0
  54. package/dist/restore-BG_zMpSj.js +199 -0
  55. package/dist/rewrite-hAcRJwiZ.js +415 -0
  56. package/dist/{rich-DCUKl5HM.js → rich-ApY1Dm4S.js} +35 -28
  57. package/dist/rolldown-runtime-C1I3wEg2.js +43 -0
  58. package/dist/{rolldown-runtime-D7D4PA-g.js → rolldown-runtime-D8jQpDG7.js} +1 -2
  59. package/dist/run-CFzR3V93.js +647 -0
  60. package/dist/scan-worker.d.ts +2 -4
  61. package/dist/scan-worker.js +1 -1
  62. package/dist/{scoped-BMYpSthj.js → scoped-h3KE8XWW.js} +3 -4
  63. package/dist/{server-deBOq2vq.js → server-WlxZH0oX.js} +275 -330
  64. package/dist/{server-Da1Ot9IN.js → server-ceuzzkal.js} +292 -386
  65. package/dist/server.d.ts +1 -17
  66. package/dist/server.js +415 -381
  67. package/dist/{sitemap-DJXzKoza.js → sitemap-796jJKUT.js} +21 -33
  68. package/dist/{sources-D19czDSA.js → sources-DuOdM02f.js} +712 -373
  69. package/dist/{status-zr4jY59Y.js → status-CTH3qI-0.js} +30 -30
  70. package/dist/{stdio-FPOKQAgu.js → stdio-D9kTzyqB.js} +2 -4
  71. package/dist/{stdio-CVaJfxA7.js → stdio-FWIVU3P4.js} +1 -2
  72. package/dist/sync-CpL0Qsgw.js +1352 -0
  73. package/dist/{t-DC-c9zE5.js → t-gvEXx25s.js} +76 -53
  74. package/dist/test.d.ts +5 -16
  75. package/dist/test.js +77 -48
  76. package/dist/translate-BrfVRkjl.js +336 -0
  77. package/dist/{ts-BaU5yOf0.js → ts-BX6kwig5.js} +25 -14
  78. package/dist/{types-DtvQ7UdD.js → types-3kwyaCAm.js} +1 -2
  79. package/dist/{types-DsdWBG0b.d.ts → types-BaG1LboH.d.ts} +2 -6
  80. package/dist/{types-CgUCkFU1.d.ts → types-Cy2bPdSg.d.ts} +14 -20
  81. package/dist/types-Ds_vebja.js +41 -0
  82. package/dist/{units-CQ5Q99RC.js → units-VVLgQ7x7.js} +7 -16
  83. package/dist/{url-CRfCOhUI.js → url-Bpc6wLea.js} +24 -11
  84. package/dist/{url-CsBkRaJy.js → url-D2_VlEeH.js} +25 -12
  85. package/dist/{validate-D6DJepZv.js → validate-PGgMsasz.js} +3 -5
  86. package/dist/{validate-BxpupdAf.js → validate-zv4-IZyZ.js} +690 -377
  87. package/dist/{version-Byqi2guX.js → version-BFs370Ce.js} +3 -5
  88. package/dist/{vite-scan-CT_vsp4g.js → vite-scan-DFKSGVE9.js} +87 -92
  89. package/dist/vite.d.ts +2 -6
  90. package/dist/vite.js +6482 -6018
  91. package/dist/vue-i18n-CBmZqHbG.js +806 -0
  92. package/dist/{which-BOemZ5Q8.js → which-BpyJyBkX.js} +44 -37
  93. package/dist/{worker-84U6uYB3.js → worker-BjzVqJVO.js} +454 -608
  94. package/package.json +5 -5
  95. package/dist/check-HsmmpJZg.js +0 -1
  96. package/dist/codec-DuvU2VQy.js +0 -207
  97. package/dist/collisions-CfpZU8e4.js +0 -217
  98. package/dist/compile-BaDh0cHG.js +0 -245
  99. package/dist/concurrency-C9UUWuDC.js +0 -96
  100. package/dist/concurrency-DONL7t4V.js +0 -1
  101. package/dist/engine-C2ENBRJe.js +0 -531
  102. package/dist/i18next-9HAoxwUI.js +0 -1
  103. package/dist/i18next-BEJgv_S8.js +0 -1596
  104. package/dist/lingui-zUiCl9Um.js +0 -833
  105. package/dist/messages-BfjIExyB.js +0 -166
  106. package/dist/migrate-IpLDMXmq.js +0 -1484
  107. package/dist/migrate-rCQuOGsf.js +0 -1
  108. package/dist/project-Bw9UPIdx.js +0 -1046
  109. package/dist/project-C4GpaN-n.js +0 -381
  110. package/dist/react-intl-BP0u-D5m.js +0 -519
  111. package/dist/restore-CiYv-jxS.js +0 -175
  112. package/dist/rewrite-EsIw_lsq.js +0 -803
  113. package/dist/run-BEcnBbu-.js +0 -694
  114. package/dist/runtime-DTMmliT1.js +0 -64
  115. package/dist/sync-B9V2KFwb.js +0 -658
  116. package/dist/translate-CQnJfLjO.js +0 -299
  117. package/dist/types-wSh9fCBY.js +0 -11
  118. package/dist/vue-i18n-g0iGy6CZ.js +0 -651
@@ -1,13 +1,12 @@
1
- import { a as diagnosticError, n as DEFAULT_CONFIG, o as isDiagnosticError } from "./types-D3QGM8XO.js";
2
- import { a as isManualId, f as parseICU, r as validateTranslation, t as pluralCategories, u as normalizeSource } from "./validate-BxpupdAf.js";
3
- import { n as printICU, t as createCodec } from "./codec-DuvU2VQy.js";
4
- import { C as usableTranslation, S as entryKey, b as emptyCatalog, m as updateCatalogFile, o as catalogLayout, s as catalogPath, w as sourceMatches, y as createEntry } from "./library-D5CWvTQs.js";
5
- import { t as excludeKind } from "./exclude-Du-Zd_qI.js";
6
- import { t as VERSION } from "./version-Byqi2guX.js";
7
- import { r as resolveDuplicates } from "./duplicates-yuRljQ6h.js";
8
- import { a as answerItems, c as exchange, d as readKey, f as requestText, i as MAX_DELAY_MS, l as field, m as sleep, o as count$1, p as retryAfterDelay, r as openaiPreset, s as detail, u as providerError } from "./openai-CTaMDcl-.js";
9
- import { t as adaptiveConcurrency } from "./concurrency-C9UUWuDC.js";
10
- //#region src/ai/mask.ts
1
+ import { i as DEFAULT_CONFIG, n as isDiagnosticError, t as diagnosticError } from "./diagnostics-1onDF6Ua.js";
2
+ import { r as resolveDuplicates } from "./duplicates-CsUXRX2J.js";
3
+ import { A as usableTranslation, C as emptyCatalog, E as entryKey, L as compareText, M as sourceMatches, h as updateCatalogFile, o as catalogLayout, s as catalogPath, x as createEntry } from "./library-BfSOBeBd.js";
4
+ import { b as parseICU, f as createCodec, h as isManualId, r as validateTranslation, t as pluralCategories, v as normalizeSource, y as printICU } from "./validate-zv4-IZyZ.js";
5
+ import { t as VERSION } from "./version-BFs370Ce.js";
6
+ import { t as adaptiveConcurrency } from "./concurrency-Dy2ny50V.js";
7
+ import { t as excludeKind } from "./exclude-vMnm3lqU.js";
8
+ import { _ as tokenCount, a as answerItems, c as exchange, d as providerError, f as readKey, g as sleep, h as retryAfterDelay, i as MAX_DELAY_MS, l as field, m as requireKey, o as costAt, p as requestText, r as openaiPreset, s as detail, u as parseBaseURL } from "./openai-RWw0YlAx.js";
9
+ // src/ai/mask.ts
11
10
  /**
12
11
  * Tokens already present in the text come first, so a literal `@@PH1@@` is
13
12
  * itself masked and cannot be confused with ours. URLs come before e-mail
@@ -28,6 +27,12 @@ const URL_TRAILER = /[.,;:!?'"’”»]+$/;
28
27
  function maskToken(index) {
29
28
  return `@@PH${index + 1}@@`;
30
29
  }
30
+ /** Whether the text holds a token of ours; the `includes` keeps the common case to one scan. */
31
+ function hasMaskToken(text) {
32
+ return text.includes("@@PH") && ANY_TOKEN.test(text);
33
+ }
34
+ /** `TOKEN` without the global flag, so `test` keeps no `lastIndex`. */
35
+ const ANY_TOKEN = /@@PH\d+@@/;
31
36
  function createMaskTable() {
32
37
  return {
33
38
  values: [],
@@ -41,46 +46,7 @@ function createMaskTable() {
41
46
  * nothing was masked, so the common case allocates no new AST.
42
47
  */
43
48
  function maskMessage(message, table) {
44
- return maskNodes(message, table);
45
- }
46
- function maskNodes(nodes, table) {
47
- let out = null;
48
- for (let i = 0; i < nodes.length; i++) {
49
- const node = nodes[i];
50
- const masked = maskNode(node, table);
51
- if (masked !== node && out === null) out = nodes.slice(0, i);
52
- if (out !== null) out.push(masked);
53
- }
54
- return out ?? nodes;
55
- }
56
- function maskNode(node, table) {
57
- switch (node.type) {
58
- case "literal": {
59
- const value = maskText(node.value, table);
60
- return value === node.value ? node : {
61
- type: "literal",
62
- value
63
- };
64
- }
65
- case "tag": {
66
- if (node.children === null) return node;
67
- const children = maskNodes(node.children, table);
68
- return children === node.children ? node : {
69
- type: "tag",
70
- name: node.name,
71
- children
72
- };
73
- }
74
- case "select":
75
- case "plural": {
76
- const options = mapOptions(node.options, (value) => maskNodes(value, table));
77
- return options === node.options ? node : {
78
- ...node,
79
- options
80
- };
81
- }
82
- default: return node;
83
- }
49
+ return mapLiterals(message, (text) => maskText(text, table));
84
50
  }
85
51
  function mapOptions(options, map) {
86
52
  let out = null;
@@ -152,7 +118,7 @@ function unmaskMessage(message, values) {
152
118
  return mapLiterals(message, (text) => unmaskText(text, values));
153
119
  }
154
120
  function unmaskText(text, values) {
155
- if (!text.includes("@@PH")) return text;
121
+ if (!hasMaskToken(text)) return text;
156
122
  return text.replace(TOKEN, (token, n) => values[Number(n) - 1] ?? token);
157
123
  }
158
124
  function mapLiterals(nodes, map) {
@@ -185,8 +151,7 @@ function mapLiterals(nodes, map) {
185
151
  }
186
152
  return out ?? nodes;
187
153
  }
188
- //#endregion
189
- //#region src/ai/checks.ts
154
+ // src/ai/checks.ts
190
155
  /**
191
156
  * Validation of AI answers (INTERNALS §2.15, PLAN §5.20). AI output is
192
157
  * untrusted: an answer ships only when it passes everything `check` enforces
@@ -214,9 +179,10 @@ function mapLiterals(nodes, map) {
214
179
  * in the translation in any case ("Arbeitsber…" in "Arbeitsbereiche"), and a
215
180
  * kept name when it occurs as written ("Tidepool" in "Tidepools").
216
181
  */
217
- const NO_TERMS$1 = Object.freeze({
218
- glossary: [],
219
- keep: []
182
+ /** A source that uses no glossary term and no kept name; shared, so it is frozen. */
183
+ const NO_TERMS = Object.freeze({
184
+ glossary: Object.freeze([]),
185
+ keep: Object.freeze([])
220
186
  });
221
187
  /** At least this share of a translation's letters must be in the target script. */
222
188
  const SCRIPT_SHARE = .5;
@@ -224,7 +190,7 @@ function checkSubject(input) {
224
190
  const script = targetScript(input.locale);
225
191
  const categories = selectable(input.locale);
226
192
  const text = literalText(input.source);
227
- const terms = input.terms ?? NO_TERMS$1;
193
+ const terms = input.terms ?? NO_TERMS;
228
194
  return {
229
195
  locale: input.locale,
230
196
  canonical: input.canonical,
@@ -284,19 +250,13 @@ function checkAnswer(answer, subject) {
284
250
  ...subject.maxLength === void 0 ? {} : { maxLength: subject.maxLength },
285
251
  ai: true
286
252
  })) if (diagnostic.severity === "error") failing.push(`${diagnostic.code}: ${diagnostic.message}`);
287
- const leading = leadingSpace(translation);
288
- const trailing = trailingSpace(translation);
289
- if (leading !== subject.leading || trailing !== subject.trailing) failing.push(`whitespace: start with ${JSON.stringify(subject.leading)} and end with ${JSON.stringify(subject.trailing)} like the source, not ${JSON.stringify(leading)} and ${JSON.stringify(trailing)}`);
253
+ checkWhitespace(translation, subject, failing);
290
254
  compareRanges(subject.newlines, rangesOf(parsed, collectNewlines), describeNewline, failing);
291
255
  compareRanges(subject.digits, rangesOf(parsed, collectDigits), describeDigits, failing);
292
- if (!identical && subject.script !== null) {
293
- let share = scriptShare(literalText(masked).replace(TOKEN, " "), subject);
294
- if (share === null) {
295
- if (lettersOf(literalText(parsed)) === subject.letters) identical = true;
296
- else share = 0;
297
- }
298
- if (share !== null && share < SCRIPT_SHARE) failing.push(`script: only ${Math.round(share * 100)} % of the letters are in the ${subject.script.code} script ${subject.locale} is written in; translate the text instead of copying it`);
299
- }
256
+ if (!identical && subject.script !== null) identical = checkScript({
257
+ masked,
258
+ parsed
259
+ }, subject, subject.script, failing);
300
260
  checkTerms(literalText(parsed), subject, failing);
301
261
  return failing.length === 0 ? {
302
262
  ok: true,
@@ -307,6 +267,28 @@ function checkAnswer(answer, subject) {
307
267
  checks: failing
308
268
  };
309
269
  }
270
+ function checkWhitespace(translation, subject, failing) {
271
+ const leading = leadingSpace(translation);
272
+ const trailing = trailingSpace(translation);
273
+ if (leading !== subject.leading || trailing !== subject.trailing) failing.push(`whitespace: start with ${JSON.stringify(subject.leading)} and end with ${JSON.stringify(subject.trailing)} like the source, not ${JSON.stringify(leading)} and ${JSON.stringify(trailing)}`);
274
+ }
275
+ /**
276
+ * Whether enough of the answer's letters are in the target script. Returns
277
+ * whether the answer is a copy of the source: one of nothing but the
278
+ * source's own Latin words, in the same order (a changed apostrophe or a
279
+ * dropped "?"), is accepted and listed like identical output so somebody
280
+ * reviews it; any other such answer is untranslated text dressed as a
281
+ * translation.
282
+ */
283
+ function checkScript(answer, subject, script, failing) {
284
+ let share = scriptShare(literalText(answer.masked).replace(TOKEN, " "), script, subject.latinRuns);
285
+ if (share === null) {
286
+ if (lettersOf(literalText(answer.parsed)) === subject.letters) return true;
287
+ share = 0;
288
+ }
289
+ if (share < SCRIPT_SHARE) failing.push(`script: only ${Math.round(share * 100)} % of the letters are in the ${script.code} script ${subject.locale} is written in; translate the text instead of copying it`);
290
+ return false;
291
+ }
310
292
  function checkTerms(text, subject, failing) {
311
293
  const { glossary, keep } = subject.terms;
312
294
  if (glossary.length > 0) {
@@ -418,9 +400,14 @@ const ZERO = {
418
400
  min: 0,
419
401
  max: 0
420
402
  };
403
+ const TIMES = [
404
+ "0 times",
405
+ "once",
406
+ "twice"
407
+ ];
421
408
  function times(range) {
422
- const n = (count) => count === 0 ? "0 times" : count === 1 ? "once" : count === 2 ? "twice" : `${count} times`;
423
- return range.min === range.max ? n(range.min) : `${range.min}–${range.max} times`;
409
+ if (range.min !== range.max) return `${range.min}–${range.max} times`;
410
+ return TIMES[range.min] ?? `${range.min} times`;
424
411
  }
425
412
  function describeToken(token, expected, actual) {
426
413
  if (expected.max === 0) return `placeholder-token: ${token} is not in the source; remove it (copy only the source's @@PHn@@ tokens)`;
@@ -433,7 +420,7 @@ function describeDigits(digits, expected, actual) {
433
420
  return expected.max === 0 ? `digits: the number ${digits} is not in the source; do not add numbers` : `digits: keep the number ${digits} as the source has it (${times(expected)}); the translation has it ${times(actual)}`;
434
421
  }
435
422
  function collectTokens(text, found) {
436
- if (!text.includes("@@PH")) return;
423
+ if (!hasMaskToken(text)) return;
437
424
  for (const match of text.matchAll(TOKEN)) found(match[0]);
438
425
  }
439
426
  function collectNewlines(text, found) {
@@ -441,7 +428,7 @@ function collectNewlines(text, found) {
441
428
  }
442
429
  const DIGIT_RUN = /\p{Nd}+/gu;
443
430
  function collectDigits(text, found, same) {
444
- const scanned = text.includes("@@PH") ? text.replace(TOKEN, " ") : text;
431
+ const scanned = hasMaskToken(text) ? text.replace(TOKEN, " ") : text;
445
432
  for (const match of scanned.matchAll(DIGIT_RUN)) {
446
433
  const digits = normalizeDigits(match[0]);
447
434
  if (digits !== same) found(digits);
@@ -521,8 +508,7 @@ const LATIN_RUN = /\p{scx=Latn}+/gu;
521
508
  * every letter is such a run: that is a copy of the source (or of its brand
522
509
  * names), not a translation to measure. Without letters the share is 1.
523
510
  */
524
- function scriptShare(text, subject) {
525
- const script = subject.script;
511
+ function scriptShare(text, script, latinRuns) {
526
512
  let total = 0;
527
513
  let inScript = 0;
528
514
  for (const match of text.matchAll(LETTER)) {
@@ -530,8 +516,8 @@ function scriptShare(text, subject) {
530
516
  if (script.letter.test(match[0])) inScript++;
531
517
  }
532
518
  if (total === 0) return 1;
533
- if (subject.latinRuns.size > 0) for (const match of text.matchAll(LATIN_RUN)) {
534
- if (!subject.latinRuns.has(match[0])) continue;
519
+ if (latinRuns.size > 0) for (const match of text.matchAll(LATIN_RUN)) {
520
+ if (!latinRuns.has(match[0])) continue;
535
521
  for (const _letter of match[0].matchAll(LETTER)) total--;
536
522
  }
537
523
  return total <= 0 ? null : inScript / total;
@@ -565,8 +551,31 @@ function trailingSpace(text) {
565
551
  while (start > 0 && SPACE.test(text[start - 1])) start--;
566
552
  return text.slice(start);
567
553
  }
568
- //#endregion
569
- //#region src/ai/exclude.ts
554
+ // src/core/config/glob.ts
555
+ /** Config globs, as `ai.exclude` and `output.baseEntries` write them. */
556
+ /**
557
+ * Anchored at both ends and at the config root: `**` crosses `/` (and `**\/`
558
+ * matches no directory too), `*` and `?` do not. `ai.exclude` file globs use
559
+ * it; the build's module-id globs (`src/vite/build/graph.ts`) follow the same rules.
560
+ */
561
+ function globToRegExp(glob) {
562
+ let source = "";
563
+ for (let i = 0; i < glob.length; i++) {
564
+ const char = glob[i];
565
+ if (char === "*") {
566
+ if (glob[i + 1] === "*") {
567
+ i++;
568
+ if (glob[i + 1] === "/") {
569
+ i++;
570
+ source += "(?:.*/)?";
571
+ } else source += ".*";
572
+ } else source += "[^/]*";
573
+ } else if (char === "?") source += "[^/]";
574
+ else source += char.replace(/[.+^${}()|[\]\\]/g, "\\$&");
575
+ }
576
+ return new RegExp("^" + source + "$");
577
+ }
578
+ // src/ai/exclude.ts
570
579
  function compileExclusion(config) {
571
580
  const locales = /* @__PURE__ */ new Set();
572
581
  const ids = /* @__PURE__ */ new Set();
@@ -588,30 +597,17 @@ function compileExclusion(config) {
588
597
  message: (id, refs) => ids.has(id) || globs.length > 0 && refs.some((ref) => globs.some((glob) => glob.test(ref)))
589
598
  };
590
599
  }
600
+ // src/ai/prices.ts
591
601
  /**
592
- * Anchored at both ends and at the config root: `**` crosses `/` (and `**\/`
593
- * matches no directory too), `*` and `?` do not — the module-id globs of the
594
- * build (`src/vite/build/graph.ts`), which this layer may not import.
602
+ * Pinned Gemini prices for `--dry-run` and `--max-cost` (INTERNALS §2.15,
603
+ * PLAN §5.20). Standard tier, USD per 1M tokens, from report 07's table
604
+ * (LiteLLM's copy of ai.google.dev/gemini-api/docs/pricing, a secondary
605
+ * source). Re-verify before each release: Gemini ids and prices churn, and
606
+ * the 3.x Flash rate is reported to double on 2027-01-01.
607
+ *
608
+ * Thinking tokens bill at the output rate, which is why the provider counts
609
+ * them as output.
595
610
  */
596
- function globToRegExp(glob) {
597
- let source = "";
598
- for (let i = 0; i < glob.length; i++) {
599
- const char = glob[i];
600
- if (char === "*") {
601
- if (glob[i + 1] === "*") {
602
- i++;
603
- if (glob[i + 1] === "/") {
604
- i++;
605
- source += "(?:.*/)?";
606
- } else source += ".*";
607
- } else source += "[^/]*";
608
- } else if (char === "?") source += "[^/]";
609
- else source += char.replace(/[.+^${}()|[\]\\]/g, "\\$&");
610
- }
611
- return new RegExp("^" + source + "$");
612
- }
613
- //#endregion
614
- //#region src/ai/prices.ts
615
611
  const CHECKED = "2026-10-09";
616
612
  const FLASH_3X = {
617
613
  input: .75,
@@ -661,7 +657,7 @@ const PRICES = Object.freeze({
661
657
  const TIER_DISCOUNT = .5;
662
658
  /** The pinned price of a model, accepting the API's `models/<id>` spelling; null when unlisted. */
663
659
  function priceOf(model) {
664
- const id = model.startsWith("models/") ? model.slice(7) : model;
660
+ const id = stripModelPrefix(model);
665
661
  return Object.hasOwn(PRICES, id) ? PRICES[id] : null;
666
662
  }
667
663
  /**
@@ -670,9 +666,11 @@ function priceOf(model) {
670
666
  * `NaN <= limit` are both false; the CLI refuses with `ai-cost-limit`).
671
667
  */
672
668
  function costOf(model, usage) {
673
- const price = priceOf(model);
674
- if (price === null) return NaN;
675
- return (usage.inputTokens * price.input + usage.outputTokens * price.output) / 1e6;
669
+ return costAt(priceOf(model), usage);
670
+ }
671
+ /** A model id without the API's `models/` prefix. */
672
+ function stripModelPrefix(model) {
673
+ return model.startsWith("models/") ? model.slice(7) : model;
676
674
  }
677
675
  /** Inline batch jobs take at most 20 MB of requests; the margin covers the envelope. */
678
676
  const MAX_JOB_BYTES = 15e6;
@@ -683,25 +681,22 @@ function gemini(options = {}) {
683
681
  const model = stripModelPrefix(options.model ?? DEFAULT_CONFIG.ai.model);
684
682
  const apiKeyEnv = options.apiKeyEnv ?? DEFAULT_CONFIG.ai.apiKeyEnv;
685
683
  const tier = options.tier ?? "standard";
686
- const base = (options.baseURL ?? "https://generativelanguage.googleapis.com/v1beta").replace(/\/+$/, "");
684
+ const { base, origin } = parseBaseURL(options.baseURL ?? "https://generativelanguage.googleapis.com/v1beta", "gemini");
687
685
  if (options.baseURL !== void 0 && options.apiKeyEnv === void 0) {
688
- if (new URL(base).origin !== new URL("https://generativelanguage.googleapis.com/v1beta").origin) throw diagnosticError({
686
+ if (origin !== new URL("https://generativelanguage.googleapis.com/v1beta").origin) throw diagnosticError({
689
687
  code: "config-invalid",
690
688
  severity: "error",
691
689
  message: `gemini({ baseURL: "${base}" }) would send the Gemini key to another host; set apiKeyEnv explicitly to the variable holding that host's key`
692
690
  });
693
691
  }
694
692
  const url = `${base}/models/${encodeURIComponent(model)}:generateContent`;
695
- const missingKey = () => readKey(options.env, apiKeyEnv) === null ? {
693
+ const keyMissing = () => ({
696
694
  code: "ai-missing-key",
697
695
  severity: "error",
698
696
  message: `Set ${apiKeyEnv} to a Gemini API key (https://aistudio.google.com/apikey) to translate with ${model}`
699
- } : null;
700
- const key = () => {
701
- const problem = missingKey();
702
- if (problem !== null) throw diagnosticError(problem);
703
- return readKey(options.env, apiKeyEnv);
704
- };
697
+ });
698
+ const missingKey = () => readKey(options.env, apiKeyEnv) === null ? keyMissing() : null;
699
+ const key = () => requireKey(options.env, apiKeyEnv, keyMissing);
705
700
  const fetchFn = () => options.fetch ?? globalThis.fetch;
706
701
  const provider = {
707
702
  name: "gemini",
@@ -740,9 +735,6 @@ function gemini(options = {}) {
740
735
  });
741
736
  return provider;
742
737
  }
743
- function stripModelPrefix(model) {
744
- return model.startsWith("models/") ? model.slice(7) : model;
745
- }
746
738
  /** A `GenerateContentRequest`. */
747
739
  function requestBody(request, flex) {
748
740
  const body = {
@@ -795,8 +787,8 @@ function readAnswer(json) {
795
787
  const result = { items: [] };
796
788
  const metadata = field(json, "usageMetadata");
797
789
  if (metadata !== void 0) result.usage = {
798
- inputTokens: count$1(field(metadata, "promptTokenCount")),
799
- outputTokens: count$1(field(metadata, "candidatesTokenCount")) + count$1(field(metadata, "thoughtsTokenCount"))
790
+ inputTokens: tokenCount(field(metadata, "promptTokenCount")),
791
+ outputTokens: tokenCount(field(metadata, "candidatesTokenCount")) + tokenCount(field(metadata, "thoughtsTokenCount"))
800
792
  };
801
793
  const candidates = field(json, "candidates");
802
794
  const first = Array.isArray(candidates) ? candidates[0] : void 0;
@@ -972,14 +964,21 @@ async function cancel(jobs, results, context) {
972
964
  } catch {}
973
965
  }
974
966
  }
975
- //#endregion
976
- //#region src/ai/glossary.ts
977
- /** The glossary for one target locale: its own target, else its language's (`de` covers `de-CH`). */
978
- function glossaryFor(config, locale) {
967
+ // src/ai/glossary.ts
968
+ /**
969
+ * A per-locale setting for `locale`: its own entry, else its language's
970
+ * (`de` covers `de-CH`), so a regional variant inherits what its team chose.
971
+ */
972
+ function forLocale(record, locale) {
973
+ if (Object.hasOwn(record, locale)) return record[locale];
979
974
  const language = locale.split("-")[0];
975
+ return Object.hasOwn(record, language) ? record[language] : void 0;
976
+ }
977
+ /** The glossary for one target locale: its own target, else its language's. */
978
+ function glossaryFor(config, locale) {
980
979
  const out = [];
981
980
  for (const [term, targets] of Object.entries(config.ai.glossary)) {
982
- const target = Object.hasOwn(targets, locale) ? targets[locale] : Object.hasOwn(targets, language) ? targets[language] : void 0;
981
+ const target = forLocale(targets, locale);
983
982
  if (target !== void 0) out.push({
984
983
  term,
985
984
  target
@@ -987,17 +986,13 @@ function glossaryFor(config, locale) {
987
986
  }
988
987
  return out;
989
988
  }
990
- const EMPTY = Object.freeze({
991
- glossary: [],
992
- keep: []
993
- });
994
989
  /** One matcher per locale run: the patterns are compiled once. */
995
990
  function termMatcher(config, locale) {
996
991
  const glossary = glossaryFor(config, locale);
997
992
  const keep = [...new Set(config.ai.doNotTranslate)];
998
993
  if (glossary.length === 0 && keep.length === 0) return {
999
994
  empty: true,
1000
- find: () => EMPTY
995
+ find: () => NO_TERMS
1001
996
  };
1002
997
  const plural = config.sourceLocale.split("-")[0] === "en" ? "(?:e?s)?" : "";
1003
998
  const patterns = [...glossary.map((entry, index) => ({
@@ -1024,7 +1019,7 @@ function termMatcher(config, locale) {
1024
1019
  keep.forEach((term, index) => {
1025
1020
  if ((ranges.get(`k${index}`)?.max ?? 0) > 0) hits.keep.push(term);
1026
1021
  });
1027
- return hits.glossary.length === 0 && hits.keep.length === 0 ? EMPTY : hits;
1022
+ return hits.glossary.length === 0 && hits.keep.length === 0 ? NO_TERMS : hits;
1028
1023
  }
1029
1024
  };
1030
1025
  }
@@ -1039,20 +1034,16 @@ function termLines(locale, glossary, keep) {
1039
1034
  const lines = [];
1040
1035
  if (glossary.length > 0) {
1041
1036
  lines.push("", `Glossary for ${locale}: translate each term exactly as given, inflected as the grammar needs:`);
1042
- const sorted = [...glossary].sort((a, b) => compareText$1(a.term, b.term));
1037
+ const sorted = [...glossary].sort((a, b) => compareText(a.term, b.term));
1043
1038
  for (const entry of sorted) lines.push(`- ${JSON.stringify(entry.term)} → ${JSON.stringify(entry.target)}`);
1044
1039
  }
1045
1040
  if (keep.length > 0) {
1046
- const sorted = [...keep].sort(compareText$1);
1041
+ const sorted = [...keep].sort(compareText);
1047
1042
  lines.push("", `Never translate or transliterate these names; copy them exactly: ${sorted.map((term) => JSON.stringify(term)).join(", ")}`);
1048
1043
  }
1049
1044
  return lines;
1050
1045
  }
1051
- function compareText$1(a, b) {
1052
- return a < b ? -1 : a > b ? 1 : 0;
1053
- }
1054
- //#endregion
1055
- //#region src/ai/prompt.ts
1046
+ // src/ai/prompt.ts
1056
1047
  /** Gemini `responseJsonSchema`; results are mapped back by `id`, never by position. */
1057
1048
  const RESPONSE_SCHEMA = Object.freeze({
1058
1049
  type: "object",
@@ -1074,20 +1065,14 @@ const RESPONSE_SCHEMA = Object.freeze({
1074
1065
  * `de-CH`), so a regional variant inherits the formality its team chose.
1075
1066
  */
1076
1067
  function toneFor(config, locale) {
1077
- const tones = config.ai.tone;
1078
- if (Object.hasOwn(tones, locale)) return tones[locale];
1079
- const language = locale.split("-")[0];
1080
- return Object.hasOwn(tones, language) ? tones[language] : null;
1068
+ return forLocale(config.ai.tone, locale) ?? null;
1081
1069
  }
1082
1070
  /**
1083
1071
  * The stable system prefix for one target locale. `terms` are the glossary
1084
1072
  * entries and kept names the locale's requested messages use (none: no
1085
1073
  * section), fixed for the run so every batch shares the prefix.
1086
1074
  */
1087
- function systemPrompt(config, targetLocale, terms = {
1088
- glossary: [],
1089
- keep: []
1090
- }) {
1075
+ function systemPrompt(config, targetLocale, terms = NO_TERMS) {
1091
1076
  const lines = [`You translate the user interface messages of a software product from ${config.sourceLocale} to ${targetLocale} (BCP 47 locale tags).`];
1092
1077
  if (config.ai.description !== null && config.ai.description.trim() !== "") lines.push("", `About the product: ${config.ai.description.trim()}`);
1093
1078
  const tone = toneFor(config, targetLocale);
@@ -1130,18 +1115,18 @@ function messageShape(message) {
1130
1115
  }
1131
1116
  /** Builds an item with its fields in one fixed order, so request bodies (and fixture hashes) are stable. */
1132
1117
  function createItem(fields) {
1133
- const item = {
1118
+ const { context, files, maxLength, pluralCategories } = fields;
1119
+ return {
1134
1120
  id: fields.id,
1135
- source: fields.source
1121
+ source: fields.source,
1122
+ ...context === null ? {} : { context },
1123
+ ...files === void 0 || files.length === 0 ? {} : { files: [...files] },
1124
+ placeholders: fields.placeholders,
1125
+ tags: fields.tags,
1126
+ ...maxLength === null ? {} : { maxLength },
1127
+ ...pluralCategories === null ? {} : { pluralCategories },
1128
+ examples: fields.examples
1136
1129
  };
1137
- if (fields.context !== null) item.context = fields.context;
1138
- if (fields.files !== void 0 && fields.files.length > 0) item.files = [...fields.files];
1139
- item.placeholders = fields.placeholders;
1140
- item.tags = fields.tags;
1141
- if (fields.maxLength !== null) item.maxLength = fields.maxLength;
1142
- if (fields.pluralCategories !== null) item.pluralCategories = fields.pluralCategories;
1143
- item.examples = fields.examples;
1144
- return item;
1145
1130
  }
1146
1131
  const WORD = /[\p{L}\p{N}]+/gu;
1147
1132
  function wordSet(text) {
@@ -1157,45 +1142,47 @@ function wordSet(text) {
1157
1142
  * ranked (a bounded selection), never every candidate touched.
1158
1143
  */
1159
1144
  function createExampleIndex(candidates) {
1160
- const sizes = new Int32Array(candidates.length);
1161
- const postings = /* @__PURE__ */ new Map();
1162
- for (let i = 0; i < candidates.length; i++) {
1163
- const words = wordSet(candidates[i].source);
1164
- sizes[i] = words.size;
1165
- for (const word of words) {
1166
- const list = postings.get(word);
1167
- if (list === void 0) postings.set(word, [i]);
1168
- else list.push(i);
1145
+ return new JaccardIndex(candidates);
1146
+ }
1147
+ var JaccardIndex = class {
1148
+ candidates;
1149
+ /** Word-set size per candidate. */
1150
+ sizes;
1151
+ /** Word → the candidates that have it. */
1152
+ postings = /* @__PURE__ */ new Map();
1153
+ shared;
1154
+ scores;
1155
+ touched = [];
1156
+ constructor(candidates) {
1157
+ this.candidates = candidates;
1158
+ this.sizes = new Int32Array(candidates.length);
1159
+ this.shared = new Int32Array(candidates.length);
1160
+ this.scores = new Float64Array(candidates.length);
1161
+ for (let i = 0; i < candidates.length; i++) {
1162
+ const words = wordSet(candidates[i].source);
1163
+ this.sizes[i] = words.size;
1164
+ for (const word of words) {
1165
+ const list = this.postings.get(word);
1166
+ if (list === void 0) this.postings.set(word, [i]);
1167
+ else list.push(i);
1168
+ }
1169
1169
  }
1170
1170
  }
1171
- const shared = new Int32Array(candidates.length);
1172
- const touched = [];
1173
- const scores = new Float64Array(candidates.length);
1174
- /** Most similar first, ties by key. */
1175
- const before = (a, b) => {
1176
- const byScore = scores[a] - scores[b];
1177
- if (byScore !== 0) return byScore > 0;
1178
- return candidates[a].key < candidates[b].key;
1179
- };
1180
- /** The `size` best of `touched` in rank order, by insertion into a short sorted list. */
1181
- const best = (size) => {
1182
- const top = [];
1183
- for (const i of touched) {
1184
- if (top.length === size && !before(i, top[size - 1])) continue;
1185
- let at = top.length === size ? size - 1 : top.length;
1186
- while (at > 0 && before(i, top[at - 1])) {
1187
- top[at] = top[at - 1];
1188
- at--;
1189
- }
1190
- top[at] = i;
1171
+ nearest(source, exclude, limit, accept) {
1172
+ if (limit <= 0 || this.candidates.length === 0) return [];
1173
+ try {
1174
+ this.score(wordSet(source));
1175
+ return this.select(exclude, limit, accept);
1176
+ } finally {
1177
+ for (const i of this.touched) this.shared[i] = 0;
1178
+ this.touched.length = 0;
1191
1179
  }
1192
- return top;
1193
- };
1194
- return { nearest(source, exclude, limit, accept) {
1195
- if (limit <= 0 || candidates.length === 0) return [];
1196
- const words = wordSet(source);
1180
+ }
1181
+ /** Jaccard similarity of every candidate sharing a word with `words`. */
1182
+ score(words) {
1183
+ const { shared, touched, scores, sizes } = this;
1197
1184
  for (const word of words) {
1198
- const list = postings.get(word);
1185
+ const list = this.postings.get(word);
1199
1186
  if (list === void 0) continue;
1200
1187
  for (const i of list) {
1201
1188
  const seen = shared[i];
@@ -1207,29 +1194,48 @@ function createExampleIndex(candidates) {
1207
1194
  const common = shared[i];
1208
1195
  scores[i] = common / (words.size + sizes[i] - common);
1209
1196
  }
1197
+ }
1198
+ /**
1199
+ * `accept` may reject some of the best; the selection widens until enough
1200
+ * are accepted or every touched candidate has been ranked.
1201
+ */
1202
+ select(exclude, limit, accept) {
1210
1203
  const found = [];
1211
- try {
1212
- let size = limit + 4;
1213
- let checked = 0;
1214
- for (;;) {
1215
- const ranked = best(Math.min(size, touched.length));
1216
- for (let r = checked; r < ranked.length && found.length < limit; r++) {
1217
- const candidate = candidates[ranked[r]];
1218
- if (candidate.key !== exclude && accept(candidate)) found.push(candidate);
1219
- }
1220
- checked = ranked.length;
1221
- if (found.length === limit || ranked.length === touched.length) break;
1222
- size *= 4;
1204
+ let size = limit + 4;
1205
+ let checked = 0;
1206
+ for (;;) {
1207
+ const ranked = this.best(Math.min(size, this.touched.length));
1208
+ for (let r = checked; r < ranked.length && found.length < limit; r++) {
1209
+ const candidate = this.candidates[ranked[r]];
1210
+ if (candidate.key !== exclude && accept(candidate)) found.push(candidate);
1223
1211
  }
1224
- } finally {
1225
- for (const i of touched) shared[i] = 0;
1226
- touched.length = 0;
1212
+ checked = ranked.length;
1213
+ if (found.length === limit || ranked.length === this.touched.length) return found;
1214
+ size *= 4;
1227
1215
  }
1228
- return found;
1229
- } };
1230
- }
1231
- //#endregion
1232
- //#region src/ai/pipeline.ts
1216
+ }
1217
+ /** The `size` best touched candidates in rank order, by insertion into a short sorted list. */
1218
+ best(size) {
1219
+ const top = [];
1220
+ for (const i of this.touched) {
1221
+ if (top.length === size && !this.before(i, top[size - 1])) continue;
1222
+ let at = top.length === size ? size - 1 : top.length;
1223
+ while (at > 0 && this.before(i, top[at - 1])) {
1224
+ top[at] = top[at - 1];
1225
+ at--;
1226
+ }
1227
+ top[at] = i;
1228
+ }
1229
+ return top;
1230
+ }
1231
+ /** Most similar first, ties by key. */
1232
+ before(a, b) {
1233
+ const byScore = this.scores[a] - this.scores[b];
1234
+ if (byScore !== 0) return byScore > 0;
1235
+ return this.candidates[a].key < this.candidates[b].key;
1236
+ }
1237
+ };
1238
+ // src/ai/pipeline.ts
1233
1239
  /**
1234
1240
  * AI translation pipeline (INTERNALS §2.15, PLAN §5.20): decide per entry
1235
1241
  * what to send, send it in batches, check every answer, retry failures with
@@ -1253,63 +1259,31 @@ function planTranslations(input) {
1253
1259
  const layout = catalogLayout(config);
1254
1260
  const read = catalogs.get(locale)?.catalog ?? null;
1255
1261
  const catalog = read === null ? null : resolveDuplicates(read, codec).catalog;
1256
- const sourceRead = catalogs.get(config.sourceLocale)?.catalog ?? null;
1257
- const own = /* @__PURE__ */ new Map();
1258
- if (catalog !== null) for (const entry of catalog.entries) {
1259
- const key = entryKey(entry, layout, codec);
1260
- if (key !== null && !own.has(key)) own.set(key, entry);
1261
- }
1262
- const targets = referencedTargets(messages, config.extraction.keep, own, sourceRead, layout, codec);
1263
- const plan = [];
1264
- const exclusion = compileExclusion(config);
1265
- const excludedLocale = exclusion.locale(locale);
1266
1262
  const context = {
1267
1263
  config,
1268
1264
  codec,
1269
1265
  layout,
1270
1266
  locale,
1271
1267
  catalog,
1272
- sourceCatalog: sourceRead,
1268
+ sourceCatalog: catalogs.get(config.sourceLocale)?.catalog ?? null,
1269
+ sourceEntries: null,
1270
+ sourceTexts: null,
1273
1271
  reuse: null,
1274
1272
  examples: null
1275
1273
  };
1274
+ const own = entriesByKey(catalog?.entries ?? [], layout, codec);
1275
+ const targets = referencedTargets(context, messages, own);
1276
+ const exclusion = compileExclusion(config);
1277
+ const excludedLocale = exclusion.locale(locale);
1278
+ const plan = [];
1276
1279
  for (const target of targets) {
1277
- const { identity } = target;
1278
- if (excludedLocale || exclusion.message(identity.id, target.refs)) {
1279
- plan.push({
1280
- kind: "skip",
1281
- id: identity.id,
1282
- reason: "excluded"
1283
- });
1284
- continue;
1285
- }
1286
- const entry = own.get(identity.id);
1287
- if (entry !== void 0 && entry.translation !== "") {
1288
- if (!(retranslate === "all" || retranslate === "ai" && entry.state === "ai")) {
1289
- const usable = usableTranslation(entry, layout, identity, codec, locale);
1290
- plan.push({
1291
- kind: "skip",
1292
- id: identity.id,
1293
- reason: usable.ok ? "has-translation" : "invalid-kept"
1294
- });
1295
- continue;
1296
- }
1297
- }
1298
- const reused = retranslate === "all" ? null : findReuse(context, identity, retranslate);
1299
- if (reused !== null) {
1300
- plan.push({
1301
- kind: "reuse",
1302
- id: identity.id,
1303
- ...reused
1304
- });
1305
- continue;
1306
- }
1307
- plan.push({
1308
- kind: "request",
1309
- id: identity.id,
1310
- item: requestItem(context, target),
1311
- canonical: identity.canonical
1280
+ const { id } = target.identity;
1281
+ if (excludedLocale || exclusion.message(id, target.refs)) plan.push({
1282
+ kind: "skip",
1283
+ id,
1284
+ reason: "excluded"
1312
1285
  });
1286
+ else plan.push(planTarget(context, target, own.get(id), retranslate));
1313
1287
  }
1314
1288
  const referenced = new Set(targets.map((target) => target.identity.id));
1315
1289
  for (const [key, entry] of own) if (!referenced.has(key) && entry.translation === "") plan.push({
@@ -1319,12 +1293,53 @@ function planTranslations(input) {
1319
1293
  });
1320
1294
  return plan.sort((a, b) => compareText(a.id, b.id));
1321
1295
  }
1296
+ /** What to do with one referenced message: keep its translation, reuse another's, or request one. */
1297
+ function planTarget(context, target, entry, retranslate) {
1298
+ const { identity } = target;
1299
+ if (entry !== void 0 && entry.translation !== "" && !rerequested(entry, retranslate)) {
1300
+ const { layout, codec, locale } = context;
1301
+ const usable = usableTranslation(entry, layout, identity, codec, locale);
1302
+ return {
1303
+ kind: "skip",
1304
+ id: identity.id,
1305
+ reason: usable.ok ? "has-translation" : "invalid-kept"
1306
+ };
1307
+ }
1308
+ const reused = retranslate === "all" ? null : findReuse(context, identity, retranslate);
1309
+ if (reused !== null) return {
1310
+ kind: "reuse",
1311
+ id: identity.id,
1312
+ ...reused
1313
+ };
1314
+ return {
1315
+ kind: "request",
1316
+ id: identity.id,
1317
+ item: requestItem(context, target),
1318
+ canonical: identity.canonical
1319
+ };
1320
+ }
1321
+ function rerequested(entry, retranslate) {
1322
+ return retranslate === "all" || retranslate === "ai" && entry.state === "ai";
1323
+ }
1324
+ /**
1325
+ * Entries by key, the first entry of a key winning as everywhere a catalog
1326
+ * is read; `accept` limits the index to the keys a caller needs.
1327
+ */
1328
+ function entriesByKey(entries, layout, codec, accept) {
1329
+ const byKey = /* @__PURE__ */ new Map();
1330
+ for (const entry of entries) {
1331
+ const key = entryKey(entry, layout, codec);
1332
+ if (key === null || byKey.has(key)) continue;
1333
+ if (accept === void 0 || accept(key)) byKey.set(key, entry);
1334
+ }
1335
+ return byKey;
1336
+ }
1322
1337
  /**
1323
1338
  * Messages the code references, plus `keep` ids, whose text comes from the
1324
1339
  * catalogs (the locale's own entry, else the source locale's). A keep id no
1325
1340
  * catalog knows has no text to translate; sync reports it (`keep-missing-entry`).
1326
1341
  */
1327
- function referencedTargets(messages, keep, own, sourceCatalog, layout, codec) {
1342
+ function referencedTargets(context, messages, own) {
1328
1343
  const targets = [];
1329
1344
  for (const message of messages.values()) targets.push({
1330
1345
  identity: message,
@@ -1332,25 +1347,24 @@ function referencedTargets(messages, keep, own, sourceCatalog, layout, codec) {
1332
1347
  maxLength: message.maxLength,
1333
1348
  refs: message.refs
1334
1349
  });
1335
- let sourceEntries = null;
1336
1350
  const kept = /* @__PURE__ */ new Set();
1337
- for (const id of keep) {
1351
+ for (const id of context.config.extraction.keep) {
1338
1352
  if (messages.has(id) || kept.has(id)) continue;
1339
1353
  kept.add(id);
1340
- if (sourceEntries === null) {
1341
- sourceEntries = /* @__PURE__ */ new Map();
1342
- for (const entry of sourceCatalog?.entries ?? []) {
1343
- const key = entryKey(entry, layout, codec);
1344
- if (key !== null && !sourceEntries.has(key)) sourceEntries.set(key, entry);
1345
- }
1346
- }
1347
1354
  const entry = own.get(id);
1348
- const text = entry?.source ?? sourceEntries.get(id)?.source ?? null;
1349
- const target = keepTarget(id, entry ?? sourceEntries.get(id), text, codec);
1355
+ const fromSource = sourceEntry(context, id);
1356
+ const text = entry?.source ?? fromSource?.source ?? null;
1357
+ const target = keepTarget(id, entry ?? fromSource, text, context.codec);
1350
1358
  if (target !== null) targets.push(target);
1351
1359
  }
1352
1360
  return targets;
1353
1361
  }
1362
+ /** The source locale's entry for `key`; the index is built on first use. */
1363
+ function sourceEntry(context, key) {
1364
+ const { sourceCatalog, layout, codec } = context;
1365
+ context.sourceEntries ??= entriesByKey(sourceCatalog?.entries ?? [], layout, codec);
1366
+ return context.sourceEntries.get(key);
1367
+ }
1354
1368
  /** A keep id as a message, its text and notes taken from a catalog entry. */
1355
1369
  function keepTarget(id, notes, text, codec) {
1356
1370
  const canonical = text === null ? null : canonicalOrNull(text, codec);
@@ -1378,7 +1392,7 @@ function keepTarget(id, notes, text, codec) {
1378
1392
  */
1379
1393
  function findReuse(context, identity, retranslate) {
1380
1394
  if (identity.manual || context.catalog === null) return null;
1381
- context.reuse ??= reuseIndex(context);
1395
+ context.reuse ??= reuseIndex(context, context.catalog);
1382
1396
  const candidates = context.reuse.get(identity.canonical);
1383
1397
  if (candidates === void 0) return null;
1384
1398
  const states = retranslate === "ai" ? ["translated"] : ["translated", "ai"];
@@ -1387,23 +1401,21 @@ function findReuse(context, identity, retranslate) {
1387
1401
  if (!validFor(entry.translation, identity.canonical, context)) continue;
1388
1402
  return {
1389
1403
  translation: entry.translation,
1390
- state: state === "ai" ? "ai" : "translated",
1404
+ state,
1391
1405
  from: key
1392
1406
  };
1393
1407
  }
1394
1408
  return null;
1395
1409
  }
1396
- function reuseIndex(context) {
1410
+ function reuseIndex(context, catalog) {
1397
1411
  const { codec, layout } = context;
1398
1412
  const index = /* @__PURE__ */ new Map();
1399
- const sourceTexts = layout === "id" ? sourceTextsByLabel(context) : null;
1400
- for (const entry of context.catalog.entries) {
1413
+ for (const entry of catalog.entries) {
1401
1414
  if (entry.manualId !== null || entry.foreignContext !== null) continue;
1402
1415
  if (entry.translation === "" || entry.fuzzy || entry.state === "untranslated") continue;
1403
1416
  const key = entryKey(entry, layout, codec);
1404
1417
  if (key === null) continue;
1405
- const text = entry.source ?? sourceTexts?.get(key) ?? null;
1406
- const canonical = text === null ? null : canonicalOrNull(text, codec);
1418
+ const canonical = entrySourceCanonical(entry, context);
1407
1419
  if (canonical === null) continue;
1408
1420
  const list = index.get(canonical);
1409
1421
  if (list === void 0) index.set(canonical, [{
@@ -1418,10 +1430,23 @@ function reuseIndex(context) {
1418
1430
  for (const list of index.values()) list.sort((a, b) => compareText(a.key, b.key));
1419
1431
  return index;
1420
1432
  }
1421
- /** `"id"` layout: a target entry without `#. source:` takes its text from the source locale's entry. */
1422
- function sourceTextsByLabel(context) {
1433
+ /**
1434
+ * A target entry's source text in canonical form, null when it has none that
1435
+ * parses. In the `"id"` layout an entry without `#. source:` takes its text
1436
+ * from the source locale's entry with the same label.
1437
+ */
1438
+ function entrySourceCanonical(entry, context) {
1439
+ const text = entry.source ?? sourceTextByLabel(context, entry.label);
1440
+ return text === null ? null : canonicalOrNull(text, context.codec);
1441
+ }
1442
+ function sourceTextByLabel(context, label) {
1443
+ if (label === null || context.layout !== "id") return null;
1444
+ context.sourceTexts ??= sourceTextsByLabel(context.sourceCatalog);
1445
+ return context.sourceTexts.get(label) ?? null;
1446
+ }
1447
+ function sourceTextsByLabel(sourceCatalog) {
1423
1448
  const texts = /* @__PURE__ */ new Map();
1424
- for (const entry of context.sourceCatalog?.entries ?? []) if (entry.manualId === null && entry.label !== null && entry.source !== null) texts.set(entry.label, entry.source);
1449
+ for (const entry of sourceCatalog?.entries ?? []) if (entry.manualId === null && entry.label !== null && entry.source !== null) texts.set(entry.label, entry.source);
1425
1450
  return texts;
1426
1451
  }
1427
1452
  /** A translation ships only when it parses and validates against the source (INTERNALS §2.6.7). */
@@ -1479,7 +1504,7 @@ function maskedCanonical(canonical, source) {
1479
1504
  function examplesFor(context, identity) {
1480
1505
  if (context.catalog === null) return [];
1481
1506
  context.examples ??= {
1482
- index: createExampleIndex(exampleCandidates(context)),
1507
+ index: createExampleIndex(exampleCandidates(context, context.catalog)),
1483
1508
  valid: /* @__PURE__ */ new Map()
1484
1509
  };
1485
1510
  const { index, valid } = context.examples;
@@ -1492,17 +1517,15 @@ function examplesFor(context, identity) {
1492
1517
  return ok;
1493
1518
  }).map((candidate) => maskedExample(candidate, context.codec));
1494
1519
  }
1495
- function exampleCandidates(context) {
1520
+ function exampleCandidates(context, catalog) {
1496
1521
  const { codec, layout } = context;
1497
- const sourceTexts = layout === "id" ? sourceTextsByLabel(context) : null;
1498
1522
  const candidates = [];
1499
- for (const entry of context.catalog.entries) {
1523
+ for (const entry of catalog.entries) {
1500
1524
  if (entry.state !== "translated" || entry.translation === "" || entry.fuzzy) continue;
1501
1525
  if (entry.foreignContext !== null) continue;
1502
1526
  const key = entryKey(entry, layout, codec);
1503
1527
  if (key === null) continue;
1504
- const text = entry.source ?? (entry.label === null ? null : sourceTexts?.get(entry.label)) ?? null;
1505
- const canonical = text === null ? null : canonicalOrNull(text, codec);
1528
+ const canonical = entrySourceCanonical(entry, context);
1506
1529
  if (canonical === null) continue;
1507
1530
  candidates.push({
1508
1531
  key,
@@ -1538,12 +1561,7 @@ async function runTranslations(input) {
1538
1561
  }
1539
1562
  };
1540
1563
  signal?.throwIfAborted();
1541
- let writes = Promise.resolve();
1542
- const persist = (results, reused) => {
1543
- const next = writes.then(() => input.persist(results, reused));
1544
- writes = next.catch(() => void 0);
1545
- return next;
1546
- };
1564
+ const persist = serialPersist(input.persist);
1547
1565
  const reused = [];
1548
1566
  for (const entry of plan) if (entry.kind === "reuse") reused.push({
1549
1567
  id: entry.id,
@@ -1551,9 +1569,9 @@ async function runTranslations(input) {
1551
1569
  state: entry.state
1552
1570
  });
1553
1571
  const prepared = localeRequests(config, locale, plan);
1554
- const requests = prepared.entries.map((entry, index) => ({
1572
+ const requests = prepared.requests.map(({ entry, terms }) => ({
1555
1573
  item: entry.item,
1556
- subject: subjectOf(entry, locale, prepared.terms[index]),
1574
+ subject: subjectOf(entry, locale, terms),
1557
1575
  failing: null
1558
1576
  }));
1559
1577
  if (reused.length > 0) {
@@ -1562,10 +1580,9 @@ async function runTranslations(input) {
1562
1580
  }
1563
1581
  summary.requested = requests.length;
1564
1582
  if (requests.length === 0) return summary;
1565
- const batches = chunk(requests, batchSize(config));
1566
1583
  const concurrency = input.concurrency ?? adaptiveConcurrency(config.ai.concurrency);
1567
1584
  const rateLimitsBefore = concurrency.rateLimits;
1568
- const run = {
1585
+ await runBatches(chunk(requests, batchSize(config)), {
1569
1586
  provider,
1570
1587
  locale,
1571
1588
  sourceLocale: config.sourceLocale,
@@ -1575,29 +1592,44 @@ async function runTranslations(input) {
1575
1592
  signal,
1576
1593
  concurrency,
1577
1594
  fatal: null
1595
+ });
1596
+ if (concurrency.rateLimits > rateLimitsBefore) summary.rateLimited = {
1597
+ count: concurrency.rateLimits - rateLimitsBefore,
1598
+ concurrency: concurrency.limit
1599
+ };
1600
+ summary.identical.sort(compareText);
1601
+ summary.failed.sort((a, b) => compareText(a.id, b.id));
1602
+ return summary;
1603
+ }
1604
+ /**
1605
+ * One writer at a time, in completion order: `persist` implementations
1606
+ * track the file's hash between calls.
1607
+ */
1608
+ function serialPersist(persist) {
1609
+ let writes = Promise.resolve();
1610
+ return (results, reused) => {
1611
+ const next = writes.then(() => persist(results, reused));
1612
+ writes = next.catch(() => void 0);
1613
+ return next;
1578
1614
  };
1615
+ }
1616
+ /** Sends the batches from as many workers as the concurrency allows; the first fatal error is rethrown. */
1617
+ async function runBatches(batches, run) {
1579
1618
  let next = 0;
1580
1619
  const worker = async () => {
1581
1620
  while (run.fatal === null && next < batches.length) {
1582
1621
  const batch = batches[next++];
1583
1622
  try {
1584
- signal?.throwIfAborted();
1623
+ run.signal?.throwIfAborted();
1585
1624
  await translateBatch(run, batch);
1586
1625
  } catch (error) {
1587
1626
  run.fatal ??= { error };
1588
1627
  }
1589
1628
  }
1590
1629
  };
1591
- const workers = Math.max(1, Math.min(concurrency.max, batches.length));
1630
+ const workers = Math.max(1, Math.min(run.concurrency.max, batches.length));
1592
1631
  await Promise.all(Array.from({ length: workers }, worker));
1593
1632
  if (run.fatal !== null) throw run.fatal.error;
1594
- if (concurrency.rateLimits > rateLimitsBefore) summary.rateLimited = {
1595
- count: concurrency.rateLimits - rateLimitsBefore,
1596
- concurrency: concurrency.limit
1597
- };
1598
- summary.identical.sort(compareText);
1599
- summary.failed.sort((a, b) => compareText(a.id, b.id));
1600
- return summary;
1601
1633
  }
1602
1634
  /**
1603
1635
  * One batch: the first request, then up to {@link MAX_RETRIES} requests for
@@ -1685,31 +1717,31 @@ function localeRequests(config, locale, plan) {
1685
1717
  const matcher = termMatcher(config, locale);
1686
1718
  if (matcher.empty) return {
1687
1719
  system: systemPrompt(config, locale),
1688
- entries,
1689
- terms: entries.map(() => NO_TERMS)
1720
+ requests: entries.map((entry) => ({
1721
+ entry,
1722
+ terms: NO_TERMS
1723
+ }))
1690
1724
  };
1691
1725
  const categories = selectable(locale);
1692
1726
  const glossary = /* @__PURE__ */ new Map();
1693
1727
  const keep = /* @__PURE__ */ new Set();
1694
- const terms = entries.map((entry) => {
1695
- const hits = matcher.find(parseSource(entry.canonical ?? entry.item.source), categories);
1696
- for (const hit of hits.glossary) glossary.set(hit.term, hit);
1697
- for (const term of hits.keep) keep.add(term);
1698
- return hits;
1728
+ const requests = entries.map((entry) => {
1729
+ const terms = matcher.find(parseSource(entry.canonical ?? entry.item.source), categories);
1730
+ for (const hit of terms.glossary) glossary.set(hit.term, hit);
1731
+ for (const term of terms.keep) keep.add(term);
1732
+ return {
1733
+ entry,
1734
+ terms
1735
+ };
1699
1736
  });
1700
1737
  return {
1701
1738
  system: systemPrompt(config, locale, {
1702
1739
  glossary: [...glossary.values()],
1703
1740
  keep: [...keep]
1704
1741
  }),
1705
- entries,
1706
- terms
1742
+ requests
1707
1743
  };
1708
1744
  }
1709
- const NO_TERMS = Object.freeze({
1710
- glossary: [],
1711
- keep: []
1712
- });
1713
1745
  function batchSize(config) {
1714
1746
  return Math.max(1, Math.floor(config.ai.batchSize));
1715
1747
  }
@@ -1720,8 +1752,8 @@ function batchSize(config) {
1720
1752
  */
1721
1753
  function firstRequests(input) {
1722
1754
  const { config, locale } = input;
1723
- const { system, entries } = localeRequests(config, locale, input.plan);
1724
- return chunk(entries.map((entry) => entry.item), batchSize(config)).map((items) => ({
1755
+ const { system, requests } = localeRequests(config, locale, input.plan);
1756
+ return chunk(requests.map((request) => request.entry.item), batchSize(config)).map((items) => ({
1725
1757
  sourceLocale: config.sourceLocale,
1726
1758
  targetLocale: locale,
1727
1759
  system,
@@ -1774,7 +1806,7 @@ function subjectOf(entry, locale, terms) {
1774
1806
  ...maxLength
1775
1807
  });
1776
1808
  }
1777
- if (/@@PH\d+@@/.test(item.source)) throw new Error(`runTranslations: the request for ${entry.id} has masked text but no canonical source to unmask it with; pass the plan item planTranslations returned`);
1809
+ if (hasMaskToken(item.source)) throw new Error(`runTranslations: the request for ${entry.id} has masked text but no canonical source to unmask it with; pass the plan item planTranslations returned`);
1778
1810
  const source = parseSource(item.source);
1779
1811
  return checkSubject({
1780
1812
  source,
@@ -1832,28 +1864,26 @@ function createProvider(config, overrides = {}) {
1832
1864
  ...overrides.fetch === void 0 ? {} : { fetch: overrides.fetch },
1833
1865
  ...overrides.env === void 0 ? {} : { env: overrides.env }
1834
1866
  };
1835
- const preset = overrides.provider ?? (config.ai.provider === "gemini" ? "gemini" : null);
1867
+ const configured = config.ai.provider;
1868
+ if (overrides.provider === void 0 && configured !== "gemini") return standardTierOnly(overrides.model !== void 0 && configured.withModel !== void 0 ? configured.withModel(overrides.model) : configured, tier);
1869
+ const preset = overrides.provider ?? "gemini";
1836
1870
  if (preset === "gemini") return gemini({
1837
- model: overrides.model ?? (config.ai.provider === "gemini" ? config.ai.model : DEFAULT_CONFIG.ai.model),
1871
+ model: overrides.model ?? (configured === "gemini" ? config.ai.model : DEFAULT_CONFIG.ai.model),
1838
1872
  apiKeyEnv: config.ai.apiKeyEnv,
1839
1873
  tier,
1840
1874
  ...io
1841
1875
  });
1842
- let provider;
1843
- if (preset === null) {
1844
- provider = config.ai.provider;
1845
- if (overrides.model !== void 0 && provider.withModel !== void 0) provider = provider.withModel(overrides.model);
1846
- } else {
1847
- if (overrides.model === void 0) throw diagnosticError({
1848
- code: "config-invalid",
1849
- severity: "error",
1850
- message: `--provider ${preset} needs --model <id>: vi18n pins no model for it`
1851
- });
1852
- provider = openaiPreset(preset, {
1853
- model: overrides.model,
1854
- ...io
1855
- });
1856
- }
1876
+ if (overrides.model === void 0) throw diagnosticError({
1877
+ code: "config-invalid",
1878
+ severity: "error",
1879
+ message: `--provider ${preset} needs --model <id>: vi18n pins no model for it`
1880
+ });
1881
+ return standardTierOnly(openaiPreset(preset, {
1882
+ model: overrides.model,
1883
+ ...io
1884
+ }), tier);
1885
+ }
1886
+ function standardTierOnly(provider, tier) {
1857
1887
  if (tier !== "standard") throw diagnosticError({
1858
1888
  code: "config-invalid",
1859
1889
  severity: "error",
@@ -1883,11 +1913,10 @@ function catalogPersister(input) {
1883
1913
  const layout = catalogLayout(config);
1884
1914
  const path = input.catalog?.path ?? catalogPath(config, locale);
1885
1915
  let expectedHash = input.catalog?.hash ?? null;
1916
+ const read = input.catalog?.catalog;
1917
+ const plannedEntries = read ? resolveDuplicates(read, codec).catalog.entries : [];
1886
1918
  const planned = /* @__PURE__ */ new Map();
1887
- if (input.catalog?.catalog) for (const entry of resolveDuplicates(input.catalog.catalog, codec).catalog.entries) {
1888
- const key = entryKey(entry, layout, codec);
1889
- if (key !== null && !planned.has(key)) planned.set(key, entry.translation);
1890
- }
1919
+ for (const [key, entry] of entriesByKey(plannedEntries, layout, codec)) planned.set(key, entry.translation);
1891
1920
  const options = {
1892
1921
  locale,
1893
1922
  layout,
@@ -1898,13 +1927,7 @@ function catalogPersister(input) {
1898
1927
  let keepEntries = null;
1899
1928
  const keepEntry = (key) => {
1900
1929
  if (!keep.has(key)) return void 0;
1901
- if (keepEntries === null) {
1902
- keepEntries = /* @__PURE__ */ new Map();
1903
- for (const entry of input.sourceCatalog?.catalog?.entries ?? []) {
1904
- const id = entryKey(entry, layout, codec);
1905
- if (id !== null && keep.has(id) && !keepEntries.has(id)) keepEntries.set(id, entry);
1906
- }
1907
- }
1930
+ keepEntries ??= entriesByKey(input.sourceCatalog?.catalog?.entries ?? [], layout, codec, (id) => keep.has(id));
1908
1931
  return keepEntries.get(key);
1909
1932
  };
1910
1933
  return async (results, reused) => {
@@ -1920,13 +1943,7 @@ function catalogPersister(input) {
1920
1943
  if (writes.size === 0) return;
1921
1944
  const anyAi = [...writes.values()].some((write) => write.state === "ai");
1922
1945
  const written = await updateCatalogFile(path, expectedHash, (current) => {
1923
- if (current !== null && current.header.idScheme !== null && current.header.idScheme !== codec.idScheme) throw diagnosticError({
1924
- code: "id-scheme-mismatch",
1925
- severity: "error",
1926
- message: `${locale}'s catalog uses ${current.header.idScheme}, not ${codec.idScheme}; run vi18n extract before vi18n translate`,
1927
- file: path,
1928
- locale
1929
- });
1946
+ if (current !== null) checkIdScheme(current, codec, path, locale);
1930
1947
  return applyWrites(current ?? emptyCatalog(locale, layout, {
1931
1948
  idScheme: codec.idScheme,
1932
1949
  sourceLocale: config.sourceLocale
@@ -1943,6 +1960,17 @@ function catalogPersister(input) {
1943
1960
  if (written.written && written.hash !== null) input.onWrite?.(path, written.hash);
1944
1961
  };
1945
1962
  }
1963
+ function checkIdScheme(current, codec, path, locale) {
1964
+ const { idScheme } = current.header;
1965
+ if (idScheme === null || idScheme === codec.idScheme) return;
1966
+ throw diagnosticError({
1967
+ code: "id-scheme-mismatch",
1968
+ severity: "error",
1969
+ message: `${locale}'s catalog uses ${idScheme}, not ${codec.idScheme}; run vi18n extract before vi18n translate`,
1970
+ file: path,
1971
+ locale
1972
+ });
1973
+ }
1946
1974
  function applyWrites(catalog, writes, context) {
1947
1975
  const { layout, codec, messages, planned } = context;
1948
1976
  const entries = catalog.entries.slice();
@@ -2008,13 +2036,18 @@ function keptMessage(key, entry, codec) {
2008
2036
  function newEntry(message, layout) {
2009
2037
  return createEntry({
2010
2038
  manualId: message.manual ? message.id : null,
2011
- label: layout === "id" ? message.label : layout === "json" && !message.manual ? message.id : null,
2039
+ label: newLabel(message, layout),
2012
2040
  source: message.canonical,
2013
2041
  refs: message.refs.slice(),
2014
2042
  contexts: message.contexts.slice(),
2015
2043
  maxLength: message.maxLength ?? null
2016
2044
  });
2017
2045
  }
2046
+ /** The label a new entry carries: the `"id"` layout's label, a generated id as the JSON key. */
2047
+ function newLabel(message, layout) {
2048
+ if (layout === "id") return message.label;
2049
+ return layout === "json" && !message.manual ? message.id : null;
2050
+ }
2018
2051
  function canonicalOrNull(text, codec) {
2019
2052
  try {
2020
2053
  return codec.canonicalize(text);
@@ -2023,9 +2056,4 @@ function canonicalOrNull(text, codec) {
2023
2056
  throw error;
2024
2057
  }
2025
2058
  }
2026
- /** UTF-16 code-unit order, as everywhere in vi18n output. */
2027
- function compareText(a, b) {
2028
- return a < b ? -1 : a > b ? 1 : 0;
2029
- }
2030
- //#endregion
2031
2059
  export { firstRequests as a, runTranslations as c, estimateUsage as i, catalogPersister as n, planTranslations as o, createProvider as r, replayProvider as s, MAX_RETRIES as t };