@menapo/vi18n 0.1.1 → 0.2.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.
Files changed (121) hide show
  1. package/README.md +19 -0
  2. package/dist/{apply-Bre-lY9J.js → apply-Bg-3rB2m.js} +69 -89
  3. package/dist/{captured-Bj8bO6vd.js → captured-DfLk50Ji.js} +196 -217
  4. package/dist/{check-BIKEuu6B.js → check-CunekuYs.js} +76 -85
  5. package/dist/cli.js +2 -3
  6. package/dist/{collect-Cx4_SKOe.js → collect-CYATDjdo.js} +1 -2
  7. package/dist/collisions-CDSdtLQm.js +215 -0
  8. package/dist/{compile-Cc97JaW2.js → compile-DqkofbiO.js} +376 -331
  9. package/dist/compile-hva0qjhZ.js +240 -0
  10. package/dist/concurrency-BCY_4zcr.js +1 -0
  11. package/dist/concurrency-Dy2ny50V.js +107 -0
  12. package/dist/config.d.ts +1 -5
  13. package/dist/config.js +4 -5
  14. package/dist/{types-D3QGM8XO.js → diagnostics-LgIWyeSp.js} +28 -27
  15. package/dist/{dir-zw6bGMKQ.js → dir-TGLYuOZb.js} +34 -37
  16. package/dist/{duplicates-yuRljQ6h.js → duplicates-8cudcHNj.js} +10 -27
  17. package/dist/engine-ecRD8-IE.js +556 -0
  18. package/dist/engine.d.ts +1 -5
  19. package/dist/engine.js +297 -168
  20. package/dist/exchange-DjwlrTQ9.js +41 -0
  21. package/dist/{exclude-Du-Zd_qI.js → exclude-BFETmvde.js} +2 -3
  22. package/dist/{export-C9Sy6UWv.js → export-D2tsqWIr.js} +17 -38
  23. package/dist/{extract-C3S8btx0.js → extract-BxYchVmY.js} +114 -82
  24. package/dist/{formats-9unqj_fZ.js → formats-BaryZ2N7.js} +352 -276
  25. package/dist/fs-ezCMZeDV.js +52 -0
  26. package/dist/i18next-COO6o0tX.js +1907 -0
  27. package/dist/i18next-Dr7DCQlQ.js +1 -0
  28. package/dist/{import-nANvQutw.js → import-vSC29Cn4.js} +81 -75
  29. package/dist/index.d.ts +1 -13
  30. package/dist/index.js +14 -16
  31. package/dist/{init-C2ScuW6a.js → init-Cc7A-8VX.js} +466 -501
  32. package/dist/{library-D5CWvTQs.js → library-tp_xqzSY.js} +975 -451
  33. package/dist/lingui-BnnlqGXT.js +902 -0
  34. package/dist/lint.d.ts +0 -4
  35. package/dist/lint.js +70 -82
  36. package/dist/{load-gW-oJt1Q.js → load-BSIeGJ5v.js} +275 -148
  37. package/dist/{load-CQRz4PpM.js → load-SSrAeJVB.js} +1214 -1116
  38. package/dist/{locales-DX4MOBFE.js → locales-D0U-yVRm.js} +271 -237
  39. package/dist/{lsp-RMMMc88P.js → lsp-DvC11pBZ.js} +4 -5
  40. package/dist/{match-BGr8EXB3.js → match-BLDcj610.js} +11 -4
  41. package/dist/{mcp-CHVwBoRP.js → mcp-D2zzOTBy.js} +4 -5
  42. package/dist/{merge-driver-BTX87aVm.js → merge-driver-BLI8OtAc.js} +138 -122
  43. package/dist/migrate-1r43OBfe.js +1 -0
  44. package/dist/migrate-ChDGhlC-.js +2169 -0
  45. package/dist/{openai-CTaMDcl-.js → openai-CLn4puY8.js} +128 -87
  46. package/dist/{output-DWE3SIUA.js → output-D5tAt8q4.js} +15 -9
  47. package/dist/parse.d.ts +1 -3
  48. package/dist/parse.js +7 -8
  49. package/dist/{pipeline-C9Dbotkh.js → pipeline-BJSkkRYC.js} +387 -359
  50. package/dist/{pipeline-DbX6rlo5.js → pipeline-BeCc441z.js} +1 -1
  51. package/dist/project-B5KIO0q-.js +544 -0
  52. package/dist/{pseudo-DRv30iN5.js → pseudo-B2DUpoLu.js} +126 -3
  53. package/dist/{raw-C4Y6vyGY.js → raw-YsYZMS9n.js} +52 -29
  54. package/dist/react-intl-C8JehBBL.js +634 -0
  55. package/dist/rename-ZVGq9ZG1.js +577 -0
  56. package/dist/repeated-uuI1tUGg.js +85 -0
  57. package/dist/restore-xlBIrtRt.js +199 -0
  58. package/dist/rewrite-BwzXoBiA.js +415 -0
  59. package/dist/{rich-DCUKl5HM.js → rich-ApY1Dm4S.js} +35 -28
  60. package/dist/rolldown-runtime-C1I3wEg2.js +43 -0
  61. package/dist/{rolldown-runtime-D7D4PA-g.js → rolldown-runtime-D8jQpDG7.js} +1 -2
  62. package/dist/run-CQ9pDLSa.js +674 -0
  63. package/dist/scan-worker.d.ts +2 -4
  64. package/dist/scan-worker.js +1 -1
  65. package/dist/{scoped-BMYpSthj.js → scoped-h3KE8XWW.js} +3 -4
  66. package/dist/{server-Da1Ot9IN.js → server-Br8tAuG2.js} +312 -386
  67. package/dist/{server-deBOq2vq.js → server-DJRpUQVZ.js} +1059 -333
  68. package/dist/server.d.ts +1 -17
  69. package/dist/server.js +419 -379
  70. package/dist/{sitemap-DJXzKoza.js → sitemap-CSAkm6oi.js} +21 -33
  71. package/dist/{sources-D19czDSA.js → sources-DNVbYsgs.js} +713 -373
  72. package/dist/{status-zr4jY59Y.js → status-q6M3rBrh.js} +30 -30
  73. package/dist/{stdio-FPOKQAgu.js → stdio-D9kTzyqB.js} +2 -4
  74. package/dist/{stdio-CVaJfxA7.js → stdio-FWIVU3P4.js} +1 -2
  75. package/dist/sync-BNIAwMhR.js +1352 -0
  76. package/dist/{t-DC-c9zE5.js → t-gvEXx25s.js} +76 -53
  77. package/dist/test.d.ts +5 -16
  78. package/dist/test.js +126 -56
  79. package/dist/translate-BP4iVhOR.js +336 -0
  80. package/dist/{ts-BaU5yOf0.js → ts-BX6kwig5.js} +25 -14
  81. package/dist/{types-DtvQ7UdD.js → types-3kwyaCAm.js} +1 -2
  82. package/dist/{types-DsdWBG0b.d.ts → types-B4wNX6PA.d.ts} +6 -8
  83. package/dist/{types-CgUCkFU1.d.ts → types-_4UdFhR9.d.ts} +24 -21
  84. package/dist/types-xR2exI3L.js +42 -0
  85. package/dist/{units-CQ5Q99RC.js → units-DPPfCN7j.js} +7 -16
  86. package/dist/{url-CRfCOhUI.js → url-Bpc6wLea.js} +24 -11
  87. package/dist/{url-CsBkRaJy.js → url-D2_VlEeH.js} +25 -12
  88. package/dist/{validate-BxpupdAf.js → validate-CgzaDdOY.js} +690 -377
  89. package/dist/{validate-D6DJepZv.js → validate-PGgMsasz.js} +3 -5
  90. package/dist/{version-Byqi2guX.js → version-DC-J5WvV.js} +3 -5
  91. package/dist/{vite-scan-CT_vsp4g.js → vite-scan-kM8Ta3rO.js} +87 -92
  92. package/dist/vite.d.ts +2 -6
  93. package/dist/vite.js +6500 -6032
  94. package/dist/vue-i18n-_uIXlFVh.js +806 -0
  95. package/dist/{which-BOemZ5Q8.js → which-DFWk_KwN.js} +44 -37
  96. package/dist/{worker-84U6uYB3.js → worker-zlhNj4y3.js} +454 -608
  97. package/package.json +5 -5
  98. package/dist/check-HsmmpJZg.js +0 -1
  99. package/dist/codec-DuvU2VQy.js +0 -207
  100. package/dist/collisions-CfpZU8e4.js +0 -217
  101. package/dist/compile-BaDh0cHG.js +0 -245
  102. package/dist/concurrency-C9UUWuDC.js +0 -96
  103. package/dist/concurrency-DONL7t4V.js +0 -1
  104. package/dist/engine-C2ENBRJe.js +0 -531
  105. package/dist/i18next-9HAoxwUI.js +0 -1
  106. package/dist/i18next-BEJgv_S8.js +0 -1596
  107. package/dist/lingui-zUiCl9Um.js +0 -833
  108. package/dist/messages-BfjIExyB.js +0 -166
  109. package/dist/migrate-IpLDMXmq.js +0 -1484
  110. package/dist/migrate-rCQuOGsf.js +0 -1
  111. package/dist/project-Bw9UPIdx.js +0 -1046
  112. package/dist/project-C4GpaN-n.js +0 -381
  113. package/dist/react-intl-BP0u-D5m.js +0 -519
  114. package/dist/restore-CiYv-jxS.js +0 -175
  115. package/dist/rewrite-EsIw_lsq.js +0 -803
  116. package/dist/run-BEcnBbu-.js +0 -694
  117. package/dist/runtime-DTMmliT1.js +0 -64
  118. package/dist/sync-B9V2KFwb.js +0 -658
  119. package/dist/translate-CQnJfLjO.js +0 -299
  120. package/dist/types-wSh9fCBY.js +0 -11
  121. package/dist/vue-i18n-g0iGy6CZ.js +0 -651
@@ -0,0 +1,240 @@
1
+ import { t as findCollisions } from "./collisions-CDSdtLQm.js";
2
+ import { c as assetCatalogsModule, l as serverCatalogVersion, o as serverCatalogJson, s as SERVER_FILES, t as compileLocales, u as serverCatalogsDir } from "./locales-D0U-yVRm.js";
3
+ import { c as toRuntimeConfig } from "./load-BSIeGJ5v.js";
4
+ import { n as readIfExists, r as writeFileAtomic } from "./fs-ezCMZeDV.js";
5
+ import { a as table, i as rootRelative, r as plural } from "./output-D5tAt8q4.js";
6
+ import { a as hasErrors, c as occurrencesOf, f as readErrors, i as computeDrift, m as scan, o as loadCatalogs, r as compareText, s as loadProject } from "./project-B5KIO0q-.js";
7
+ import { r as EXIT } from "./types-xR2exI3L.js";
8
+ import { join, resolve } from "node:path";
9
+ import { mkdir, readdir, rm } from "node:fs/promises";
10
+ // src/cli/commands/compile.ts
11
+ /**
12
+ * `vi18n compile [--out dir] [--assets dir] [--strict] [--pseudo] [--check]`
13
+ * (INTERNALS §2.12, PLAN §5.3): compiled catalogs for code Vite does not
14
+ * build (a wrangler Worker, e-mail rendering), loaded with
15
+ * `registerCatalogs`. It refuses to run while `extract --check` reports
16
+ * drift, so what ships always matches the code. A committed `--out`
17
+ * directory can still lag behind the catalogs (a translation edited,
18
+ * `extract` run without `compile`): `--check` compares it with what would be
19
+ * written, for CI.
20
+ *
21
+ * `--assets` is the Workers layout of `ssr.catalogs: "assets"` (spike S12):
22
+ * the catalogs go to the static-assets directory under the server message
23
+ * set's version, and `<out>/catalogs.js` reads them through `env.ASSETS`, so
24
+ * the Worker bundles none and only the locales requests use take memory.
25
+ */
26
+ async function compile(ctx, flags) {
27
+ const project = await loadProject(ctx);
28
+ const { config, codec } = project;
29
+ const data = {
30
+ out: null,
31
+ assets: null,
32
+ files: [],
33
+ missing: {},
34
+ drift: []
35
+ };
36
+ const scanned = await scan(project);
37
+ ctx.out.report(scanned.diagnostics.filter((d) => d.severity === "error"));
38
+ const loaded = await loadCatalogs(project);
39
+ if (await refuses(ctx, project, scanned, loaded)) return {
40
+ exitCode: EXIT.failure,
41
+ data
42
+ };
43
+ const locales = [...config.locales, ...flags.pseudo ? config.pseudoLocales : []];
44
+ const compiled = compileLocales({
45
+ config,
46
+ codec,
47
+ messages: scanned.messages,
48
+ keep: config.extraction.keep,
49
+ catalogs: loaded.set,
50
+ locales
51
+ });
52
+ let missingTotal = 0;
53
+ for (const locale of config.locales) {
54
+ const result = compiled.get(locale);
55
+ ctx.out.report(result.diagnostics);
56
+ if (locale === config.sourceLocale) continue;
57
+ let count = 0;
58
+ for (const status of result.status.values()) if (status.state === "missing") count++;
59
+ data.missing[locale] = count;
60
+ missingTotal += count;
61
+ }
62
+ if (flags.out !== null) await writeOutput(ctx, project, {
63
+ compiled,
64
+ locales,
65
+ messages: scanned.messages
66
+ }, {
67
+ ...flags,
68
+ out: flags.out
69
+ }, data);
70
+ printSummary(ctx, data, flags);
71
+ const failed = hasErrors(ctx.out.diagnostics) || flags.strict && missingTotal > 0;
72
+ if (flags.strict && missingTotal > 0) ctx.out.note(`vi18n compile --strict: ${plural(missingTotal, "missing translation")}`);
73
+ return {
74
+ exitCode: failed ? EXIT.failure : EXIT.ok,
75
+ data
76
+ };
77
+ }
78
+ /** Whether compile must not run: unreadable catalogs, a live id collision, or drift (each reported). */
79
+ async function refuses(ctx, project, scanned, loaded) {
80
+ const unreadable = readErrors(loaded.diagnostics);
81
+ if (unreadable.length > 0) {
82
+ ctx.out.report(unreadable);
83
+ return true;
84
+ }
85
+ const collided = findCollisions(occurrencesOf(scanned), loaded.set, project.codec, { referenced: new Set(project.config.extraction.keep) });
86
+ if (hasErrors(collided)) {
87
+ ctx.out.report(collided);
88
+ return true;
89
+ }
90
+ const refusals = (await computeDrift(project, scanned.messages, loaded.set)).diagnostics.filter((d) => d.code === "catalog-drift" || d.code === "id-scheme-mismatch");
91
+ if (refusals.length === 0) return false;
92
+ ctx.out.report(refusals);
93
+ ctx.out.note("vi18n compile: the catalogs do not match the code; run vi18n extract first");
94
+ return true;
95
+ }
96
+ /** Writes (or with `--check` compares) every file of `--out` and `--assets`. */
97
+ async function writeOutput(ctx, project, input, flags, data) {
98
+ const { config } = project;
99
+ const out = resolve(ctx.global.cwd, flags.out);
100
+ data.out = rootRelative(config.root, out);
101
+ if (!flags.check) await mkdir(out, { recursive: true });
102
+ const assets = flags.assets === null ? null : resolve(ctx.global.cwd, flags.assets);
103
+ if (assets !== null) data.assets = rootRelative(config.root, assets);
104
+ const { files, version } = outputFiles(project, input, flags, {
105
+ out,
106
+ assets
107
+ });
108
+ const fix = `vi18n compile --out ${flags.out}${assets === null ? "" : ` --assets ${flags.assets}`}${flags.pseudo ? " --pseudo" : ""}`;
109
+ for (const [path, content] of files) {
110
+ const file = rootRelative(config.root, path);
111
+ data.files.push(file);
112
+ if (!flags.check) {
113
+ await writeFileAtomic(path, content, { ifChanged: true });
114
+ continue;
115
+ }
116
+ const drift = await fileDrift(path, file, content, fix);
117
+ if (drift === null) continue;
118
+ data.drift.push(file);
119
+ ctx.out.report([drift]);
120
+ }
121
+ if (version === null || assets === null || flags.check) return;
122
+ const removed = await removeOtherVersions(assets, version, [...config.locales, ...config.pseudoLocales]);
123
+ if (removed > 0) ctx.out.note(`removed ${plural(removed, "earlier catalog version")} from ${ctx.out.display(rootRelative(config.root, join(assets, "vi18n")))}`);
124
+ }
125
+ /** The files to write, and the server catalog version under `--assets` (null without). */
126
+ function outputFiles(project, input, flags, dirs) {
127
+ const { config, codec } = project;
128
+ const { compiled, locales } = input;
129
+ const { out, assets } = dirs;
130
+ const files = [];
131
+ const runtime = toRuntimeConfig(config, {
132
+ base: "/",
133
+ pseudo: flags.pseudo
134
+ });
135
+ const catalogJson = (locale) => serverCatalogJson(compiled.get(locale).messages) + "\n";
136
+ let version = null;
137
+ if (assets === null) for (const locale of locales) files.push([join(out, `${locale}.json`), catalogJson(locale)]);
138
+ else {
139
+ version = serverCatalogVersion({
140
+ idScheme: codec.idScheme,
141
+ v: null,
142
+ ids: compiled.get(config.sourceLocale).messages.keys(),
143
+ sourceHashOf: (id) => input.messages.get(id)?.sourceHash ?? ""
144
+ });
145
+ for (const locale of locales) {
146
+ const path = join(assets, serverCatalogsDir(version), locale, SERVER_FILES.catalog);
147
+ files.push([path, catalogJson(locale)]);
148
+ }
149
+ runtime.ssr.maxLoadedLocales = config.ssr.maxLoadedLocales;
150
+ }
151
+ files.push([join(out, "sources.json"), sourcesJson(input.messages)]);
152
+ files.push([join(out, "config.json"), JSON.stringify(runtime) + "\n"]);
153
+ if (version !== null) {
154
+ files.push([join(out, "catalogs.js"), assetCatalogsModule({
155
+ locales,
156
+ dir: serverCatalogsDir(version),
157
+ deploy: `deploy ${flags.assets} (written by vi18n compile --assets) with this Worker`,
158
+ modules: "compile without --assets to bundle the catalogs as modules"
159
+ })]);
160
+ files.push([join(out, "catalogs.d.ts"), CATALOGS_DTS]);
161
+ }
162
+ return {
163
+ files,
164
+ version
165
+ };
166
+ }
167
+ /** `--check`: a missing or different file is drift. */
168
+ async function fileDrift(path, file, content, fix) {
169
+ const current = await readIfExists(path);
170
+ if (current !== null && current.replace(/\r\n/g, "\n") === content) return null;
171
+ return {
172
+ code: "catalog-drift",
173
+ severity: "error",
174
+ message: current === null ? `${file} does not exist yet; run ${fix}` : `${file} is out of date; run ${fix}`,
175
+ file
176
+ };
177
+ }
178
+ function printSummary(ctx, data, flags) {
179
+ const rows = Object.entries(data.missing).map(([locale, count]) => [locale, count]);
180
+ if (rows.length > 0) ctx.out.result(table(["locale", "missing"], rows));
181
+ if (data.out === null) return;
182
+ const where = ctx.out.display(data.out) + (data.assets === null ? "" : ` and ${ctx.out.display(data.assets)}`);
183
+ if (!flags.check) {
184
+ ctx.out.result(`wrote ${plural(data.files.length, "file")} to ${where}`);
185
+ return;
186
+ }
187
+ ctx.out.result(data.drift.length > 0 ? `vi18n compile --check: ${data.drift.length} out-of-date file(s) in ${where}` : `vi18n compile --check: ${where} ${data.assets === null ? "is" : "are"} up to date`);
188
+ }
189
+ /** Types of the generated `catalogs.js` for TypeScript apps (no `allowJs` needed). */
190
+ const CATALOGS_DTS = `// Generated by vi18n compile --assets: catalog loaders for registerCatalogs().
191
+ declare const catalogs: { [locale: string]: () => Promise<{ [id: string]: unknown }> };
192
+ export default catalogs;
193
+ `;
194
+ /** A version directory name (`hash8`): base64url, 8 characters. */
195
+ const VERSION_NAME = /^[\w-]{8}$/;
196
+ /**
197
+ * Removes the versions of `<assets>/vi18n/` other than `version` that this
198
+ * command wrote: directories named like a version holding only
199
+ * `<locale>/catalog.json` for configured locales. Anything else there (a
200
+ * Vite build's stable manifests, the app's own files) is left alone.
201
+ */
202
+ async function removeOtherVersions(assets, version, locales) {
203
+ const root = join(assets, "vi18n");
204
+ let removed = 0;
205
+ for (const entry of await readdir(root, { withFileTypes: true }).catch(() => [])) {
206
+ if (!entry.isDirectory() || entry.name === version || !VERSION_NAME.test(entry.name)) continue;
207
+ const dir = join(root, entry.name);
208
+ if (!await onlyCatalogs(dir, locales)) continue;
209
+ await rm(dir, {
210
+ recursive: true,
211
+ force: true
212
+ });
213
+ removed++;
214
+ }
215
+ return removed;
216
+ }
217
+ async function onlyCatalogs(dir, locales) {
218
+ for (const entry of await readdir(dir, { withFileTypes: true })) {
219
+ if (!entry.isDirectory() || !locales.includes(entry.name)) return false;
220
+ if ((await readdir(join(dir, entry.name), { withFileTypes: true })).some((file) => !file.isFile() || file.name !== SERVER_FILES.catalog)) return false;
221
+ }
222
+ return true;
223
+ }
224
+ /**
225
+ * Every exact source literal of a generated-id message → its id, so
226
+ * untransformed code (`t("Hello {name}")` in a Worker) finds the compiled
227
+ * message (PLAN §5.3). Manual ids are looked up by id and need no entry.
228
+ */
229
+ function sourcesJson(messages) {
230
+ const pairs = [];
231
+ for (const message of messages.values()) {
232
+ if (message.manual) continue;
233
+ for (const source of message.sources) pairs.push([source, message.id]);
234
+ }
235
+ pairs.sort((a, b) => compareText(a[0], b[0]));
236
+ const data = Object.create(null);
237
+ for (const [source, id] of pairs) data[source] = id;
238
+ return JSON.stringify(data) + "\n";
239
+ }
240
+ export { compile };
@@ -0,0 +1 @@
1
+ export { t as adaptiveConcurrency } from "./concurrency-Dy2ny50V.js";
@@ -0,0 +1,107 @@
1
+ // src/ai/concurrency.ts
2
+ /**
3
+ * Adaptive concurrency (PLAN §5.20, INTERNALS §2.15): requests start at
4
+ * `ai.concurrency` in flight; a rate limit halves that and holds every new
5
+ * request for the delay the server asked (`RetryInfo`, `Retry-After`), and
6
+ * each full window of requests without one gives a slot back (AIMD). The
7
+ * provider retries the limited request itself; this only decides how many
8
+ * others may start. One instance spans a whole `vi18n translate` run, so a
9
+ * quota learnt on one locale is not rediscovered on the next.
10
+ */
11
+ /** Hold after a rate limit whose answer named no delay. */
12
+ const DEFAULT_HOLD_MS = 1e3;
13
+ function adaptiveConcurrency(max, now = Date.now) {
14
+ return new AdaptiveConcurrency(Math.max(1, Math.floor(max)), now);
15
+ }
16
+ var AdaptiveConcurrency = class {
17
+ max;
18
+ limit;
19
+ rateLimits = 0;
20
+ inFlight = 0;
21
+ holdUntil = 0;
22
+ successes = 0;
23
+ epoch = 0;
24
+ waiters = [];
25
+ timer = null;
26
+ now;
27
+ constructor(max, now) {
28
+ this.max = max;
29
+ this.limit = max;
30
+ this.now = now;
31
+ }
32
+ acquire(signal) {
33
+ return new Promise((resolve, reject) => {
34
+ if (signal?.aborted === true) {
35
+ reject(signal.reason);
36
+ return;
37
+ }
38
+ const onAbort = () => {
39
+ const index = this.waiters.indexOf(waiter);
40
+ if (index !== -1) this.waiters.splice(index, 1);
41
+ reject(signal?.reason);
42
+ };
43
+ const waiter = { grant: () => {
44
+ signal?.removeEventListener("abort", onAbort);
45
+ this.inFlight++;
46
+ resolve(new AdaptiveSlot(this, this.epoch));
47
+ } };
48
+ signal?.addEventListener("abort", onAbort, { once: true });
49
+ this.waiters.push(waiter);
50
+ this.pump();
51
+ });
52
+ }
53
+ /** Grants waiting requests while there is room and no hold; a hold re-pumps when it ends. */
54
+ pump() {
55
+ if (this.timer !== null) {
56
+ clearTimeout(this.timer);
57
+ this.timer = null;
58
+ }
59
+ while (this.waiters.length > 0 && this.inFlight < this.limit) {
60
+ const wait = this.holdUntil - this.now();
61
+ if (wait > 0) {
62
+ this.timer = setTimeout(() => this.pump(), wait);
63
+ return;
64
+ }
65
+ this.waiters.shift().grant();
66
+ }
67
+ }
68
+ /** A request sent in `epoch` met a rate limit: the first of its burst halves the limit. */
69
+ rateLimited(epoch, retryAfterMs) {
70
+ this.rateLimits++;
71
+ if (epoch === this.epoch) {
72
+ this.limit = Math.max(1, Math.floor(this.limit / 2));
73
+ this.successes = 0;
74
+ this.epoch++;
75
+ }
76
+ this.holdUntil = Math.max(this.holdUntil, this.now() + (retryAfterMs ?? DEFAULT_HOLD_MS));
77
+ }
78
+ /** A request sent in `epoch` ended; a full window of unlimited ones gives a slot back. */
79
+ released(epoch, limited) {
80
+ this.inFlight--;
81
+ if (!limited && epoch === this.epoch && ++this.successes >= this.limit && this.limit < this.max) {
82
+ this.limit++;
83
+ this.successes = 0;
84
+ }
85
+ this.pump();
86
+ }
87
+ };
88
+ var AdaptiveSlot = class {
89
+ limited = false;
90
+ done = false;
91
+ owner;
92
+ epoch;
93
+ constructor(owner, epoch) {
94
+ this.owner = owner;
95
+ this.epoch = epoch;
96
+ }
97
+ rateLimited(retryAfterMs) {
98
+ this.limited = true;
99
+ this.owner.rateLimited(this.epoch, retryAfterMs);
100
+ }
101
+ release() {
102
+ if (this.done) return;
103
+ this.done = true;
104
+ this.owner.released(this.epoch, this.limited);
105
+ }
106
+ };
107
+ export { adaptiveConcurrency as t };
package/dist/config.d.ts CHANGED
@@ -1,5 +1,4 @@
1
- import { a as Vi18nConfig, c as OpenAICompatibleOptions, d as ProviderResponse, f as Tier, l as ProviderOptions, m as TranslationProvider, n as OutputOptions, o as AiItem, p as TranslateOptions, r as PseudoLocale, s as BatchOptions, t as Level, u as ProviderRequest, v as LocaleStrategy, y as UrlStrategy } from "./types-CgUCkFU1.js";
2
- //#region src/config/index.d.ts
1
+ import { a as Vi18nConfig, c as OpenAICompatibleOptions, d as ProviderResponse, f as Tier, l as ProviderOptions, m as TranslationProvider, n as OutputOptions, o as AiItem, p as TranslateOptions, r as PseudoLocale, s as BatchOptions, t as Level, u as ProviderRequest, v as LocaleStrategy, y as UrlStrategy } from "./types-_4UdFhR9.js";
3
2
  /**
4
3
  * Types a `vi18n.config.ts`. The config is validated when it is loaded
5
4
  * (`vi18n` plugin, CLI), where errors can name the file.
@@ -14,8 +13,5 @@ export declare function defineConfig(config: Vi18nConfig): Vi18nConfig;
14
13
  * Domains play no part: the list is the paths any unlisted host serves.
15
14
  */
16
15
  export declare function localizedPaths(paths: readonly string[], config: Vi18nConfig): string[];
17
- //#endregion
18
- //#region src/ai/openai.d.ts
19
16
  export declare function openaiCompatible(options: OpenAICompatibleOptions): TranslationProvider;
20
- //#endregion
21
17
  export type { AiItem, BatchOptions, Level, LocaleStrategy, OpenAICompatibleOptions, OutputOptions, ProviderOptions, ProviderRequest, ProviderResponse, PseudoLocale, Tier, TranslateOptions, TranslationProvider, UrlStrategy, Vi18nConfig };
package/dist/config.js CHANGED
@@ -1,7 +1,7 @@
1
- import { n as DEFAULT_CONFIG } from "./types-D3QGM8XO.js";
2
- import { i as localizedPathsFor } from "./url-CRfCOhUI.js";
3
- import { n as openaiCompatible } from "./openai-CTaMDcl-.js";
4
- //#region src/config/index.ts
1
+ import { i as localizedPathsFor } from "./url-Bpc6wLea.js";
2
+ import { i as DEFAULT_CONFIG } from "./diagnostics-LgIWyeSp.js";
3
+ import { n as openaiCompatible } from "./openai-CLn4puY8.js";
4
+ // src/config/index.ts
5
5
  /**
6
6
  * `@menapo/vi18n/config` implementation (docs/INTERNALS.md §3.4). Loaded by
7
7
  * every `vi18n.config.ts` under Node, so it stays a few lines: no zod, no file
@@ -35,5 +35,4 @@ function localizedPaths(paths, config) {
35
35
  }
36
36
  });
37
37
  }
38
- //#endregion
39
38
  export { defineConfig, localizedPaths, openaiCompatible };
@@ -1,27 +1,6 @@
1
- //#region src/core/diagnostics.ts
2
- /**
3
- * The only way core code creates a throwable diagnostic, so every error that
4
- * crosses a module boundary can be reported without knowing who threw it.
5
- */
6
- function diagnosticError(diagnostic) {
7
- const error = new Error(diagnostic.message);
8
- error.name = "DiagnosticError";
9
- error.diagnostic = diagnostic;
10
- return error;
11
- }
12
- /**
13
- * Recognises a {@link DiagnosticError} by shape rather than by class: errors
14
- * thrown in a `vm` context or another bundled copy of vi18n fail `instanceof`,
15
- * while `Object.prototype.toString` sees the internal error slot in any realm.
16
- */
17
- function isDiagnosticError(error) {
18
- if (typeof error !== "object" || error === null) return false;
19
- if (!(error instanceof Error) && Object.prototype.toString.call(error) !== "[object Error]") return false;
20
- const diagnostic = error.diagnostic;
21
- return typeof diagnostic === "object" && diagnostic !== null && typeof diagnostic.code === "string";
22
- }
23
- //#endregion
24
- //#region src/config/types.ts
1
+ // src/config/types.ts
2
+ /** The two generated pseudo-locales (PLAN §4.7, §5.21). */
3
+ const PSEUDO_LOCALES = ["en-XA", "ar-XB"];
25
4
  /** The only config file name (revision 4.2). */
26
5
  const CONFIG_FILE = "vi18n.config.ts";
27
6
  /** Import sources that always apply; `extraction.importSources` is appended to them. */
@@ -70,7 +49,8 @@ const DEFAULT_CONFIG = {
70
49
  aliases: [],
71
50
  globals: [],
72
51
  keep: [],
73
- dependencies: []
52
+ dependencies: [],
53
+ repeatedText: 3
74
54
  },
75
55
  ids: { length: ID_LENGTH.default },
76
56
  catalogs: {
@@ -142,5 +122,26 @@ const DEFAULT_CONFIG = {
142
122
  moduleScope: "warn"
143
123
  }
144
124
  };
145
- //#endregion
146
- export { diagnosticError as a, ID_LENGTH as i, DEFAULT_CONFIG as n, isDiagnosticError as o, DEFAULT_IMPORT_SOURCES as r, CONFIG_FILE as t };
125
+ // src/core/diagnostics.ts
126
+ /**
127
+ * The only way core code creates a throwable diagnostic, so every error that
128
+ * crosses a module boundary can be reported without knowing who threw it.
129
+ */
130
+ function diagnosticError(diagnostic) {
131
+ const error = new Error(diagnostic.message);
132
+ error.name = "DiagnosticError";
133
+ error.diagnostic = diagnostic;
134
+ return error;
135
+ }
136
+ /**
137
+ * Recognises a {@link DiagnosticError} by shape rather than by class: errors
138
+ * thrown in a `vm` context or another bundled copy of vi18n fail `instanceof`,
139
+ * while `Object.prototype.toString` sees the internal error slot in any realm.
140
+ */
141
+ function isDiagnosticError(error) {
142
+ if (typeof error !== "object" || error === null) return false;
143
+ if (!(error instanceof Error) && Object.prototype.toString.call(error) !== "[object Error]") return false;
144
+ const diagnostic = error.diagnostic;
145
+ return typeof diagnostic === "object" && diagnostic !== null && typeof diagnostic.code === "string";
146
+ }
147
+ export { DEFAULT_IMPORT_SOURCES as a, DEFAULT_CONFIG as i, isDiagnosticError as n, ID_LENGTH as o, CONFIG_FILE as r, PSEUDO_LOCALES as s, diagnosticError as t };
@@ -1,4 +1,4 @@
1
- //#region src/runtime/ctx.ts
1
+ // src/runtime/ctx.ts
2
2
  /** Dev helpers shared by the runtime modules. */
3
3
  /**
4
4
  * Dev mode, from the plugin's `define` (INTERNALS §6 D44): code bundled
@@ -35,8 +35,7 @@ const warnOnce = (text) => {
35
35
  warned.add(text);
36
36
  if (!seen) console.warn("vi18n: " + text);
37
37
  };
38
- //#endregion
39
- //#region src/runtime/scope.ts
38
+ // src/runtime/scope.ts
40
39
  function createScope(kind, locale, messages, options = {}) {
41
40
  return {
42
41
  kind,
@@ -51,8 +50,7 @@ function createScope(kind, locale, messages, options = {}) {
51
50
  labels: options.labels
52
51
  };
53
52
  }
54
- //#endregion
55
- //#region src/runtime/types.ts
53
+ // src/runtime/types.ts
56
54
  /**
57
55
  * Opcodes of the IR. The runtime may inline the literal numbers to save
58
56
  * bytes; 9 (`list`) and 10 (MF2 `.match`) are reserved and never emitted in 1.0.
@@ -71,8 +69,7 @@ const OP = {
71
69
  };
72
70
  /** The `globalThis[Symbol.for("menapo.vi18n")]` key. */
73
71
  const STATE_KEY = "menapo.vi18n";
74
- //#endregion
75
- //#region src/runtime/state.ts
72
+ // src/runtime/state.ts
76
73
  /**
77
74
  * The page-wide state on `globalThis[Symbol.for("menapo.vi18n")]`
78
75
  * (INTERNALS §2.11.1). The first runtime copy to evaluate creates it, or
@@ -148,28 +145,34 @@ function report(key, locale, reason) {
148
145
  if (DEV) console.error(e);
149
146
  }
150
147
  }
148
+ /**
149
+ * Dev: a client page that should have the engine. Servers run without it by
150
+ * design, and so does everything outside a document. This and the dev
151
+ * helpers below run only once `init()` returned, so `S` is set.
152
+ */
153
+ const clientPage = () => browser() && !S.serverResolver && S.registration?.consumer !== "server";
154
+ /**
155
+ * Dev: says why a client page renders no translations when the engine never
156
+ * evaluated (code the plugin did not process, a suite without the boot
157
+ * module).
158
+ */
159
+ function noEngine() {
160
+ if (clientPage()) warnOnce("the client engine is not loaded, so nothing is fetched or switched and t() renders no translations; the plugin's boot module imports \"@menapo/vi18n/engine\" first. Is this code processed by vi18n()?");
161
+ }
162
+ /** Dev: what to use instead of `setLocale()` where it cannot run. */
163
+ function setLocaleAdvice() {
164
+ if (clientPage()) return " and needs the client engine (\"@menapo/vi18n/engine\", imported by the boot module)";
165
+ return "; use withLocale() or scopeLocale() on the server";
166
+ }
151
167
  function createState(stub) {
152
168
  /** A request-less `t()` on the server (§2.11.1 `resolve`). */
153
169
  const noScope = () => {
154
- const reg = S.registration;
170
+ const reg = state.registration;
155
171
  if (!BUILD && reg?.test) return page;
156
172
  if (DEV) throw new Error("vi18n: t() called outside a request scope");
157
173
  const locale = reg?.config.sourceLocale ?? "und";
158
174
  report("", locale, "no-scope");
159
- return S.serverFallback ?? (fallback ??= createScope("request", locale, /* @__PURE__ */ new Map()));
160
- };
161
- /**
162
- * Dev: a client page that should have the engine. Servers run without it by
163
- * design, and so does everything outside a document.
164
- */
165
- const clientPage = () => browser() && !S.serverResolver && S.registration?.consumer !== "server";
166
- /**
167
- * Dev: says why a client page renders no translations when the engine never
168
- * evaluated (code the plugin did not process, a suite without the boot
169
- * module).
170
- */
171
- const noEngine = () => {
172
- if (clientPage()) warnOnce("the client engine is not loaded, so nothing is fetched or switched and t() renders no translations; the plugin's boot module imports \"@menapo/vi18n/engine\" first. Is this code processed by vi18n()?");
175
+ return state.serverFallback ?? (fallback ??= createScope("request", locale, /* @__PURE__ */ new Map()));
173
176
  };
174
177
  /**
175
178
  * The engine's client methods where it never evaluated: on servers and on
@@ -207,17 +210,17 @@ function createState(stub) {
207
210
  nav = navigate;
208
211
  },
209
212
  register(r) {
210
- S.registration = r;
211
- S.locales.length = 0;
212
- S.locales.push(...r.config.locales);
213
+ state.registration = r;
214
+ state.locales.length = 0;
215
+ state.locales.push(...r.config.locales);
213
216
  page.locale = r.config.sourceLocale;
214
217
  return engine ? engine(r) : resolved;
215
218
  },
216
219
  setLocale() {
217
- throw new Error("vi18n: setLocale() is client-only" + (DEV ? clientPage() ? " and needs the client engine (\"@menapo/vi18n/engine\", imported by the boot module)" : "; use withLocale() or scopeLocale() on the server" : ""));
220
+ throw new Error("vi18n: setLocale() is client-only" + (DEV ? setLocaleAdvice() : ""));
218
221
  },
219
222
  resolve: () => {
220
- const r = S.serverResolver;
223
+ const r = state.serverResolver;
221
224
  return r ? r() ?? noScope() : page;
222
225
  },
223
226
  untracked(fn) {
@@ -245,8 +248,8 @@ function createState(stub) {
245
248
  report(key, scope.locale, reason);
246
249
  }
247
250
  };
248
- const S = stub ? Object.assign(stub, core) : core;
249
- return S;
251
+ const state = stub ? Object.assign(stub, core) : core;
252
+ return state;
250
253
  }
251
254
  /** Creates the global state, or upgrades the boot stub, or joins another copy's state. */
252
255
  function init() {
@@ -263,12 +266,7 @@ function init() {
263
266
  }
264
267
  /** The state, for runtime modules. Evaluating the runtime is what creates (or joins) it. */
265
268
  const S = init();
266
- /** The global state this copy created or joined. Pinned for `/server` and generated glue. */
267
- function getState() {
268
- return S;
269
- }
270
- //#endregion
271
- //#region src/runtime/dir.ts
269
+ // src/runtime/dir.ts
272
270
  /** Text direction of a locale (PLAN §4.16). */
273
271
  const RTL_SCRIPTS = "AdlmArabHebrMandMendNkooRohgSamrSyrcThaaYezi";
274
272
  const cache = /* @__PURE__ */ new Map();
@@ -286,5 +284,4 @@ function textDirection(locale) {
286
284
  }
287
285
  return d;
288
286
  }
289
- //#endregion
290
- export { DEV as _, getState as a, trim as b, page as c, resolved as d, setEngine as f, BUILD as g, createScope as h, created as i, quiet as l, OP as m, S as n, nav as o, subs as p, changed as r, noop as s, textDirection as t, report as u, browser as v, warnOnce as x, own as y };
287
+ export { browser as _, nav as a, warnOnce as b, quiet as c, setEngine as d, subs as f, DEV as g, BUILD as h, created as i, report as l, createScope as m, S as n, noop as o, OP as p, changed as r, page as s, textDirection as t, resolved as u, own as v, trim as y };
@@ -1,10 +1,5 @@
1
- import { S as entryKey } from "./library-D5CWvTQs.js";
2
- //#region src/core/catalog/duplicates.ts
3
- const RANK = {
4
- translated: 2,
5
- ai: 1,
6
- untranslated: 0
7
- };
1
+ import { D as flagKey, E as entryKey, O as stricterLimit, S as defineFields, v as STATE_RANK } from "./library-tp_xqzSY.js";
2
+ // src/core/catalog/duplicates.ts
8
3
  /** Entries grouped by key; only keys seen more than once. Null when there are none. */
9
4
  function duplicateGroups(catalog, codec) {
10
5
  const first = /* @__PURE__ */ new Map();
@@ -28,7 +23,10 @@ function duplicateGroups(catalog, codec) {
28
23
  /** `translated` over `ai` over `untranslated`, then the first in the file. */
29
24
  function winnerOf(entries, indexes) {
30
25
  let best = indexes[0];
31
- for (const index of indexes) if (RANK[entries[index].state] > RANK[entries[best].state]) best = index;
26
+ for (const index of indexes) {
27
+ const state = entries[index].state;
28
+ if (STATE_RANK[state] > STATE_RANK[entries[best].state]) best = index;
29
+ }
32
30
  return best;
33
31
  }
34
32
  /**
@@ -100,20 +98,6 @@ function appendNew(into, seen, from) {
100
98
  }
101
99
  }
102
100
  /**
103
- * Copies `from`'s fields onto `into` in place, not by a spread per copy
104
- * (which would copy everything kept so far each time); defineProperty keeps
105
- * a `__proto__` field data, as the JSON reader does.
106
- */
107
- function defineFields(into, from) {
108
- for (const field of Object.keys(from)) Object.defineProperty(into, field, {
109
- value: from[field],
110
- enumerable: true,
111
- writable: true,
112
- configurable: true
113
- });
114
- return into;
115
- }
116
- /**
117
101
  * The winner with every other copy merged in, in file order: as merging the
118
102
  * copies one by one would, but with one pass over each copy, so the cost
119
103
  * stays linear in the group's size however many copies there are.
@@ -124,7 +108,7 @@ function mergeGroup(winner, others) {
124
108
  const comments = winner.comments.slice();
125
109
  const seenComments = new Set(comments);
126
110
  const flags = winner.flags.slice();
127
- const seenFlags = new Set(flags.map((flag) => flag.line + flag.name));
111
+ const seenFlags = new Set(flags.map(flagKey));
128
112
  const refs = new Set(winner.refs);
129
113
  let maxLength = winner.maxLength;
130
114
  let extra;
@@ -137,20 +121,20 @@ function mergeGroup(winner, others) {
137
121
  appendNew(contexts, seenContexts, other.contexts);
138
122
  appendNew(comments, seenComments, other.comments);
139
123
  for (const flag of other.flags) {
140
- const key = flag.line + flag.name;
124
+ const key = flagKey(flag);
141
125
  if (seenFlags.has(key)) continue;
142
126
  seenFlags.add(key);
143
127
  flags.push(flag);
144
128
  }
145
129
  for (const ref of other.refs) refs.add(ref);
146
- if (other.maxLength !== null) maxLength = maxLength === null ? other.maxLength : Math.min(maxLength, other.maxLength);
130
+ maxLength = stricterLimit(maxLength, other.maxLength);
147
131
  }
148
132
  const merged = {
149
133
  ...winner,
150
134
  contexts,
151
135
  comments,
152
136
  flags,
153
- refs: [...refs].sort((x, y) => x < y ? -1 : x > y ? 1 : 0),
137
+ refs: [...refs].sort(),
154
138
  maxLength
155
139
  };
156
140
  if (extra !== void 0) merged.extra = extra;
@@ -181,5 +165,4 @@ function mergeDuplicates(catalog, codec) {
181
165
  entries: entries.filter((_, index) => !dropped.has(index))
182
166
  };
183
167
  }
184
- //#endregion
185
168
  export { mergeDuplicates as n, resolveDuplicates as r, duplicateDiagnostics as t };