@menapo/vi18n 0.1.0 → 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 (119) hide show
  1. package/README.md +14 -14
  2. package/dist/{apply-Bre-lY9J.js → apply-FAHl1R6T.js} +69 -89
  3. package/dist/{captured-Bj8bO6vd.js → captured-CTjjDF5o.js} +196 -217
  4. package/dist/{check-DyrAbv73.js → check-DwFwOB1d.js} +66 -84
  5. package/dist/cli.js +2 -3
  6. package/dist/{collect-Cx4_SKOe.js → collect-CYATDjdo.js} +1 -2
  7. package/dist/collisions-uMTuq36M.js +215 -0
  8. package/dist/compile-CEvH-6sY.js +240 -0
  9. package/dist/{compile-Cc97JaW2.js → compile-DqkofbiO.js} +376 -331
  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-1onDF6Ua.js} +26 -26
  15. package/dist/{dir-zw6bGMKQ.js → dir-TGLYuOZb.js} +34 -37
  16. package/dist/{duplicates-yuRljQ6h.js → duplicates-CsUXRX2J.js} +10 -27
  17. package/dist/engine-Bf7nVigL.js +556 -0
  18. package/dist/engine.d.ts +1 -5
  19. package/dist/engine.js +297 -168
  20. package/dist/exchange-DYG9RZoT.js +41 -0
  21. package/dist/{exclude-Du-Zd_qI.js → exclude-vMnm3lqU.js} +2 -3
  22. package/dist/{export-DGsMbcTZ.js → export-BYq0gfLd.js} +17 -38
  23. package/dist/{extract-Dujlsgnk.js → extract-CYtuEo8u.js} +114 -82
  24. package/dist/{formats-KPIg-08V.js → formats-ChV1LVH_.js} +352 -276
  25. package/dist/fs-ezCMZeDV.js +52 -0
  26. package/dist/i18next-1waHziMy.js +1 -0
  27. package/dist/i18next-D66Icz3L.js +1907 -0
  28. package/dist/{import-Cwdhcywt.js → import-BApbQlmm.js} +81 -75
  29. package/dist/index.d.ts +1 -13
  30. package/dist/index.js +14 -16
  31. package/dist/{init-BecCTvKi.js → init-J7AwwA5e.js} +466 -501
  32. package/dist/{library-D5CWvTQs.js → library-BfSOBeBd.js} +975 -451
  33. package/dist/lingui-Ee2farVo.js +902 -0
  34. package/dist/lint.d.ts +0 -4
  35. package/dist/lint.js +69 -82
  36. package/dist/{load-gW-oJt1Q.js → load-BFLLqY8x.js} +272 -147
  37. package/dist/{load-CQRz4PpM.js → load-CMwhukZ4.js} +1211 -1115
  38. package/dist/{locales-DX4MOBFE.js → locales-DxLDrx-h.js} +271 -237
  39. package/dist/{lsp-Cq1Nuu-Q.js → lsp-BC7xDGON.js} +4 -5
  40. package/dist/{match-BGr8EXB3.js → match-BLDcj610.js} +11 -4
  41. package/dist/{mcp-Cf0T7qPW.js → mcp-Cka8ywDF.js} +4 -5
  42. package/dist/{merge-driver-CpiiSVIc.js → merge-driver-B04Apm29.js} +138 -122
  43. package/dist/migrate-D7TNl6SD.js +2169 -0
  44. package/dist/migrate-khCY8TE0.js +1 -0
  45. package/dist/{openai-CTaMDcl-.js → openai-RWw0YlAx.js} +128 -87
  46. package/dist/{output-DsaHKHEt.js → output-CF9uvk_-.js} +15 -9
  47. package/dist/parse.d.ts +1 -3
  48. package/dist/parse.js +7 -8
  49. package/dist/{pipeline-wxS0SApG.js → pipeline-B30irGMD.js} +1 -1
  50. package/dist/{pipeline-C7g11THL.js → pipeline-sgl_q_op.js} +387 -359
  51. package/dist/project-DSzWKU3C.js +544 -0
  52. package/dist/{pseudo-DRv30iN5.js → pseudo-DNbNNVGP.js} +125 -3
  53. package/dist/{raw-C4Y6vyGY.js → raw-YsYZMS9n.js} +52 -29
  54. package/dist/react-intl-tzGIk6G3.js +634 -0
  55. package/dist/restore-BG_zMpSj.js +199 -0
  56. package/dist/rewrite-hAcRJwiZ.js +415 -0
  57. package/dist/{rich-DCUKl5HM.js → rich-ApY1Dm4S.js} +35 -28
  58. package/dist/rolldown-runtime-C1I3wEg2.js +43 -0
  59. package/dist/{rolldown-runtime-D7D4PA-g.js → rolldown-runtime-D8jQpDG7.js} +1 -2
  60. package/dist/run-CFzR3V93.js +647 -0
  61. package/dist/scan-worker.d.ts +2 -4
  62. package/dist/scan-worker.js +1 -1
  63. package/dist/{scoped-BMYpSthj.js → scoped-h3KE8XWW.js} +3 -4
  64. package/dist/{server-BDkykMjb.js → server-WlxZH0oX.js} +275 -330
  65. package/dist/{server-qv3mz70d.js → server-ceuzzkal.js} +292 -386
  66. package/dist/server.d.ts +1 -17
  67. package/dist/server.js +415 -381
  68. package/dist/{sitemap-DV3o8QD7.js → sitemap-796jJKUT.js} +21 -33
  69. package/dist/{sources-D19czDSA.js → sources-DuOdM02f.js} +712 -373
  70. package/dist/{status-DZArW5aE.js → status-CTH3qI-0.js} +30 -30
  71. package/dist/{stdio-FPOKQAgu.js → stdio-D9kTzyqB.js} +2 -4
  72. package/dist/{stdio-CVaJfxA7.js → stdio-FWIVU3P4.js} +1 -2
  73. package/dist/sync-CpL0Qsgw.js +1352 -0
  74. package/dist/{t-DC-c9zE5.js → t-gvEXx25s.js} +76 -53
  75. package/dist/test.d.ts +5 -16
  76. package/dist/test.js +77 -48
  77. package/dist/translate-BrfVRkjl.js +336 -0
  78. package/dist/{ts-BaU5yOf0.js → ts-BX6kwig5.js} +25 -14
  79. package/dist/{types-DtvQ7UdD.js → types-3kwyaCAm.js} +1 -2
  80. package/dist/{types-DsdWBG0b.d.ts → types-BaG1LboH.d.ts} +2 -6
  81. package/dist/{types-CgUCkFU1.d.ts → types-Cy2bPdSg.d.ts} +14 -20
  82. package/dist/types-Ds_vebja.js +41 -0
  83. package/dist/{units-CQ5Q99RC.js → units-VVLgQ7x7.js} +7 -16
  84. package/dist/{url-CRfCOhUI.js → url-Bpc6wLea.js} +24 -11
  85. package/dist/{url-CsBkRaJy.js → url-D2_VlEeH.js} +25 -12
  86. package/dist/{validate-D6DJepZv.js → validate-PGgMsasz.js} +3 -5
  87. package/dist/{validate-BxpupdAf.js → validate-zv4-IZyZ.js} +690 -377
  88. package/dist/{version-BlyLGlOa.js → version-BFs370Ce.js} +3 -5
  89. package/dist/{vite-scan-B_YW4X_a.js → vite-scan-DFKSGVE9.js} +87 -92
  90. package/dist/vite.d.ts +2 -6
  91. package/dist/vite.js +6482 -6018
  92. package/dist/vue-i18n-CBmZqHbG.js +806 -0
  93. package/dist/{which-C6PFI1Dm.js → which-BpyJyBkX.js} +44 -37
  94. package/dist/{worker-84U6uYB3.js → worker-BjzVqJVO.js} +454 -608
  95. package/package.json +8 -8
  96. package/dist/check-D34P-S--.js +0 -1
  97. package/dist/codec-DuvU2VQy.js +0 -207
  98. package/dist/collisions-CfpZU8e4.js +0 -217
  99. package/dist/compile-B5Mz6WJm.js +0 -245
  100. package/dist/concurrency-C9UUWuDC.js +0 -96
  101. package/dist/concurrency-DONL7t4V.js +0 -1
  102. package/dist/engine-B7p40M__.js +0 -531
  103. package/dist/i18next-CrUnKFfh.js +0 -1596
  104. package/dist/i18next-Rgo-v9l0.js +0 -1
  105. package/dist/lingui--PcOOYry.js +0 -833
  106. package/dist/messages-Cxa-5tR0.js +0 -166
  107. package/dist/migrate-CntqvrW4.js +0 -1
  108. package/dist/migrate-dPgq9uzy.js +0 -1484
  109. package/dist/project-Dwx7iPm6.js +0 -381
  110. package/dist/project-pXipT8iG.js +0 -1046
  111. package/dist/react-intl-CaBVwJ9u.js +0 -519
  112. package/dist/restore-Btq66Tid.js +0 -175
  113. package/dist/rewrite-CiTRAICl.js +0 -803
  114. package/dist/run-DYD_VXKy.js +0 -694
  115. package/dist/runtime-DTMmliT1.js +0 -64
  116. package/dist/sync-CcVzger_.js +0 -658
  117. package/dist/translate-DZR3MkSA.js +0 -299
  118. package/dist/types-wSh9fCBY.js +0 -11
  119. package/dist/vue-i18n-CEMnpv7k.js +0 -651
@@ -0,0 +1,1352 @@
1
+ import { n as isDiagnosticError, r as CONFIG_FILE } from "./diagnostics-1onDF6Ua.js";
2
+ import { _ as parseIdScheme, a as displayPath, c as mapLimit, i as MISSING, s as isMissing, u as toPosix } from "./validate-zv4-IZyZ.js";
3
+ import { C as emptyCatalog, E as entryKey, F as isIncluded, I as listProjectFiles, L as compareText, N as serialized, a as ownedMessages, f as sameCatalogText, n as libraryCoverage, o as catalogLayout, p as serializeCatalog, r as libraryIds, s as catalogPath, x as createEntry, z as dependencyRef } from "./library-BfSOBeBd.js";
4
+ import { n as cacheVersion, t as VERSION } from "./version-BFs370Ce.js";
5
+ import { i as scanSource, n as WORKER_MARKER, r as scanConfig, t as ABORT_CODES } from "./worker-BjzVqJVO.js";
6
+ import { n as mergeDuplicates } from "./duplicates-CsUXRX2J.js";
7
+ import { basename, dirname, join, relative, resolve } from "node:path";
8
+ import { hash, randomBytes } from "node:crypto";
9
+ import { existsSync, readFileSync, realpathSync, statSync } from "node:fs";
10
+ import { mkdir, open, readFile, realpath, rename, rm, stat, unlink, writeFile } from "node:fs/promises";
11
+ import { fileURLToPath } from "node:url";
12
+ import { availableParallelism } from "node:os";
13
+ import { Worker } from "node:worker_threads";
14
+ // src/core/config/hash.ts
15
+ /**
16
+ * `configHash` (INTERNALS §2.7.1): the key every cache derived from a config
17
+ * carries (scan cache, transform cache), so any config or version change
18
+ * invalidates them and nothing else does.
19
+ */
20
+ function configHash(config, version) {
21
+ const { provider } = config.ai;
22
+ const hashed = {
23
+ ...config,
24
+ routing: {
25
+ ...config.routing,
26
+ routeStrategies: Object.entries(config.routing.routeStrategies)
27
+ },
28
+ ssr: {
29
+ ...config.ssr,
30
+ timeZoneFrom: Object.entries(config.ssr.timeZoneFrom)
31
+ },
32
+ ai: typeof provider === "string" ? config.ai : {
33
+ ...config.ai,
34
+ provider: {
35
+ name: provider.name,
36
+ model: provider.model
37
+ }
38
+ },
39
+ ...config.extraction.dependencies.length === 0 ? {} : { libraryIds: libraryIdList(config) }
40
+ };
41
+ return hash("sha256", stableJson(hashed) + "\0" + version, "hex");
42
+ }
43
+ /**
44
+ * JSON with object keys sorted at every depth, so the hash does not depend
45
+ * on the order in which a config was written or resolved. Array order is
46
+ * kept: strategy chains and fallbacks are ordered.
47
+ */
48
+ function stableJson(value) {
49
+ if (value === null || typeof value !== "object") return JSON.stringify(value) ?? "null";
50
+ if (Array.isArray(value)) {
51
+ let out = "[";
52
+ for (let i = 0; i < value.length; i++) out += (i === 0 ? "" : ",") + stableJson(value[i]);
53
+ return out + "]";
54
+ }
55
+ const record = value;
56
+ let out = "{";
57
+ let first = true;
58
+ for (const key of Object.keys(record).sort()) {
59
+ const item = record[key];
60
+ if (item === void 0 || typeof item === "function" || typeof item === "symbol") continue;
61
+ out += (first ? "" : ",") + JSON.stringify(key) + ":" + stableJson(item);
62
+ first = false;
63
+ }
64
+ return out + "}";
65
+ }
66
+ /**
67
+ * The opted-in packages' manual ids, or none while one is not installed:
68
+ * hashing never fails, loading the config does (§2.5.7).
69
+ */
70
+ function libraryIdList(config) {
71
+ try {
72
+ return [...libraryIds(config)];
73
+ } catch (error) {
74
+ if (isDiagnosticError(error)) return [];
75
+ throw error;
76
+ }
77
+ }
78
+ // src/core/extract/aggregate.ts
79
+ /**
80
+ * Groups occurrences by id. Contexts are split into single-line notes
81
+ * (trimmed, empty ones dropped, deduplicated, sorted by code unit); `maxLength`
82
+ * is the smallest given (§6 D15: the strictest limit is the safe one); `refs`
83
+ * and `sources` are sorted and unique; `locations` keep scan order. When
84
+ * occurrences share an id but not a canonical text — a collision callers
85
+ * report through `findCollisions` — the first one wins and the others are
86
+ * left out entirely.
87
+ */
88
+ function aggregateOccurrences(occurrences) {
89
+ const pending = /* @__PURE__ */ new Map();
90
+ for (const occurrence of occurrences) {
91
+ let entry = pending.get(occurrence.id);
92
+ if (entry === void 0) {
93
+ entry = {
94
+ message: {
95
+ id: occurrence.id,
96
+ manual: occurrence.manual,
97
+ canonical: occurrence.canonical,
98
+ sourceHash: occurrence.sourceHash,
99
+ label: occurrence.label,
100
+ contexts: [],
101
+ refs: [],
102
+ sources: [],
103
+ locations: []
104
+ },
105
+ contexts: /* @__PURE__ */ new Set(),
106
+ refs: /* @__PURE__ */ new Set(),
107
+ sources: /* @__PURE__ */ new Set()
108
+ };
109
+ pending.set(occurrence.id, entry);
110
+ } else if (entry.message.canonical !== occurrence.canonical) continue;
111
+ const { message } = entry;
112
+ if (occurrence.context !== void 0) for (const line of occurrence.context.split("\n")) {
113
+ const note = line.trim();
114
+ if (note !== "") entry.contexts.add(note);
115
+ }
116
+ if (occurrence.maxLength !== void 0 && (message.maxLength === void 0 || occurrence.maxLength < message.maxLength)) message.maxLength = occurrence.maxLength;
117
+ entry.refs.add(occurrence.file);
118
+ entry.sources.add(occurrence.source);
119
+ message.locations.push({
120
+ file: occurrence.file,
121
+ line: occurrence.line,
122
+ column: occurrence.column
123
+ });
124
+ }
125
+ const messages = /* @__PURE__ */ new Map();
126
+ for (const [id, { message, contexts, refs, sources }] of pending) {
127
+ message.contexts = [...contexts].sort();
128
+ message.refs = [...refs].sort();
129
+ message.sources = [...sources].sort();
130
+ messages.set(id, message);
131
+ }
132
+ return messages;
133
+ }
134
+ // src/core/extract/cache.ts
135
+ /**
136
+ * The CLI scan cache (INTERNALS §2.5.6): per absolute file, what the last
137
+ * scan found, keyed by mtime + size or else content hash, and invalidated by
138
+ * any config change and any change of vi18n's code (`configHash` over
139
+ * `cacheVersion()`, the version and a fingerprint of the code: the version
140
+ * alone stays `0.0.0` in the workspace and in vendored tarballs). It lives
141
+ * in `node_modules/.cache/vi18n/scan-v1.json` under the config root's
142
+ * nearest `node_modules`, so a clean install drops it.
143
+ */
144
+ const SCAN_CACHE_FILE = "scan-v1.json";
145
+ /** sha256 of the file text, the fallback key when mtime or size moved (checkouts, `touch`). */
146
+ function contentHash(text) {
147
+ return hash("sha256", text, "base64url");
148
+ }
149
+ /** `node_modules/.cache/vi18n/scan-v1.json` under the nearest `node_modules` at or above `root`. */
150
+ function scanCachePath(root) {
151
+ for (let dir = root;; dir = dirname(dir)) {
152
+ const modules = join(dir, "node_modules");
153
+ if (existsSync(modules)) return join(modules, ".cache", "vi18n", SCAN_CACHE_FILE);
154
+ if (dirname(dir) === dir) break;
155
+ }
156
+ return join(root, "node_modules", ".cache", "vi18n", SCAN_CACHE_FILE);
157
+ }
158
+ /** How long a save waits for another writer's lock, and when a lock counts as abandoned. */
159
+ const LOCK_WAIT_MS = 5e3;
160
+ const LOCK_STALE_MS = 3e4;
161
+ /** Saves of one cache file in this process, chained so each re-reads what the last wrote. */
162
+ const saving = /* @__PURE__ */ new Map();
163
+ let temps = 0;
164
+ const pause = (ms) => new Promise((done) => setTimeout(done, ms));
165
+ /**
166
+ * Takes `<cache>.lock` for a read-merge-write against other processes (a
167
+ * workspace's packages scanned in parallel share one cache file). Resolves
168
+ * to the release function, or null when the lock stayed taken: the caller
169
+ * skips the write rather than drop another writer's section.
170
+ */
171
+ async function lock(path) {
172
+ const file = path + ".lock";
173
+ const deadline = Date.now() + LOCK_WAIT_MS;
174
+ for (;;) {
175
+ try {
176
+ await (await open(file, "wx")).close();
177
+ return () => unlink(file).catch(() => {});
178
+ } catch (error) {
179
+ if (error.code !== "EEXIST") throw error;
180
+ }
181
+ const info = await stat(file).catch(() => null);
182
+ if (info !== null && Date.now() - info.mtimeMs > LOCK_STALE_MS) {
183
+ await unlink(file).catch(() => {});
184
+ continue;
185
+ }
186
+ if (Date.now() > deadline) return null;
187
+ await pause(10 + Math.random() * 40);
188
+ }
189
+ }
190
+ function isEntry(value) {
191
+ if (typeof value !== "object" || value === null) return false;
192
+ const e = value;
193
+ return typeof e.mtimeMs === "number" && typeof e.size === "number" && typeof e.contentHash === "string" && typeof e.configHash === "string" && typeof e.version === "string" && Array.isArray(e.occurrences) && Array.isArray(e.diagnostics);
194
+ }
195
+ async function readCacheFile(path) {
196
+ try {
197
+ const parsed = JSON.parse(await readFile(path, "utf8"));
198
+ if (parsed.format === 1 && typeof parsed.roots === "object" && parsed.roots !== null) return parsed;
199
+ } catch {}
200
+ return {
201
+ format: 1,
202
+ roots: {}
203
+ };
204
+ }
205
+ var ScanCache = class ScanCache {
206
+ path;
207
+ /** `configHash(config, version)`: entries with another key are misses. */
208
+ key;
209
+ /** `cacheVersion()` unless a caller names another: entries of other code are misses. */
210
+ version;
211
+ #root;
212
+ #entries;
213
+ #dirty = false;
214
+ constructor(path, root, key, version, entries) {
215
+ this.path = path;
216
+ this.#root = root;
217
+ this.key = key;
218
+ this.version = version;
219
+ this.#entries = entries;
220
+ }
221
+ /**
222
+ * Reads the cache for `config` (empty when there is none or it is
223
+ * corrupt). `version` defaults to the running code's `cacheVersion()`.
224
+ */
225
+ static async open(config, path = scanCachePath(config.root), version = cacheVersion()) {
226
+ const file = await readCacheFile(path);
227
+ const entries = /* @__PURE__ */ new Map();
228
+ const section = file.roots[config.root];
229
+ if (typeof section === "object" && section !== null) {
230
+ for (const [name, entry] of Object.entries(section)) if (isEntry(entry)) entries.set(name, entry);
231
+ }
232
+ return new ScanCache(path, config.root, configHash(config, version), version, entries);
233
+ }
234
+ get size() {
235
+ return this.#entries.size;
236
+ }
237
+ #current(file) {
238
+ const entry = this.#entries.get(file);
239
+ return entry !== void 0 && entry.configHash === this.key && entry.version === this.version ? entry : void 0;
240
+ }
241
+ /** A hit by file metadata alone: no read needed. */
242
+ byStat(file, mtimeMs, size) {
243
+ const entry = this.#current(file);
244
+ return entry !== void 0 && entry.mtimeMs === mtimeMs && entry.size === size ? entry : void 0;
245
+ }
246
+ /**
247
+ * A hit by content after the metadata moved; the entry is refreshed with
248
+ * the new metadata so the next run hits by stat again.
249
+ */
250
+ byContent(file, hashOfText, mtimeMs, size) {
251
+ const entry = this.#current(file);
252
+ if (entry === void 0 || entry.contentHash !== hashOfText) return void 0;
253
+ if (entry.mtimeMs !== mtimeMs || entry.size !== size) {
254
+ this.#entries.set(file, {
255
+ ...entry,
256
+ mtimeMs,
257
+ size
258
+ });
259
+ this.#dirty = true;
260
+ }
261
+ return entry;
262
+ }
263
+ set(file, entry) {
264
+ this.#entries.set(file, {
265
+ ...entry,
266
+ configHash: this.key,
267
+ version: this.version
268
+ });
269
+ this.#dirty = true;
270
+ }
271
+ delete(file) {
272
+ if (this.#entries.delete(file)) this.#dirty = true;
273
+ }
274
+ /** Drops entries of files that are no longer part of the project. */
275
+ retain(files) {
276
+ for (const file of this.#entries.keys()) if (!files.has(file)) {
277
+ this.#entries.delete(file);
278
+ this.#dirty = true;
279
+ }
280
+ }
281
+ /**
282
+ * Writes the cache when it changed: under a lock, re-read, replace this
283
+ * root's section, write a temporary file and rename it over the old one,
284
+ * so a concurrent scan of another root keeps its section and readers never
285
+ * see half a file. Returns false when the cache was not written (a
286
+ * read-only checkout, a lock held too long): a cache never fails a scan.
287
+ */
288
+ save() {
289
+ if (!this.#dirty) return Promise.resolve(true);
290
+ return serialized(saving, this.path, () => this.#write());
291
+ }
292
+ async #write() {
293
+ if (!this.#dirty) return true;
294
+ const temp = `${this.path}.${process.pid}.${++temps}.${randomBytes(4).toString("hex")}.tmp`;
295
+ let release = null;
296
+ try {
297
+ await mkdir(dirname(this.path), { recursive: true });
298
+ release = await lock(this.path);
299
+ if (release === null) return false;
300
+ const file = await readCacheFile(this.path);
301
+ for (const root of Object.keys(file.roots)) if (!existsSync(root)) delete file.roots[root];
302
+ const section = {};
303
+ for (const [name, entry] of this.#entries) section[name] = entry;
304
+ file.roots[this.#root] = section;
305
+ await writeFile(temp, JSON.stringify(file));
306
+ await rename(temp, this.path);
307
+ this.#dirty = false;
308
+ return true;
309
+ } catch {
310
+ await unlink(temp).catch(() => {});
311
+ return false;
312
+ } finally {
313
+ await release?.();
314
+ }
315
+ }
316
+ };
317
+ // src/core/extract/project.ts
318
+ /**
319
+ * The project scan (INTERNALS §2.5.6): what `vi18n extract` and the plugin's
320
+ * build seed know about every message in the code. Files come from the
321
+ * include walk, hits from the scan cache, and misses are scanned in-process
322
+ * or, past 200 of them, in a `worker_threads` pool. Results are in file
323
+ * order whichever path produced them, so a scan is deterministic.
324
+ */
325
+ /** Misses above which the pool pays for its start-up (each worker loads the parser and compilers). */
326
+ const POOL_THRESHOLD = 200;
327
+ const POOL_MAX = 8;
328
+ /** Files per worker message: large enough to amortise messaging, small enough to balance load. */
329
+ const BATCH = 16;
330
+ /** Explicit files resolved at once. */
331
+ const RESOLVE_CONCURRENCY = 64;
332
+ /**
333
+ * The worker entry next to this module: the source file in the workspace
334
+ * (Node strips its types), `scan-worker.js` beside the packed CLI chunk.
335
+ */
336
+ const WORKER_URL = new URL(import.meta.url.endsWith(".ts") ? "./worker.ts" : "./scan-worker.js", import.meta.url);
337
+ /** Missing, or a directory where a file was named or listed: nothing to scan. */
338
+ const NOT_A_FILE = /* @__PURE__ */ new Set([...MISSING, "EISDIR"]);
339
+ /** Maps an absolute file to its `#:` reference: posix, relative to the config root. */
340
+ function refMapper(config) {
341
+ const roots = [toPosix(config.root)];
342
+ let realRoot = null;
343
+ try {
344
+ realRoot = realpathSync(config.root);
345
+ if (toPosix(realRoot) !== roots[0]) roots.unshift(toPosix(realRoot));
346
+ } catch {}
347
+ return (file) => {
348
+ const posix = toPosix(file);
349
+ const dependency = dependencyRef(posix, config);
350
+ if (dependency !== null) return dependency;
351
+ for (const root of roots) if (posix.startsWith(root) && posix[root.length] === "/") return posix.slice(root.length + 1);
352
+ if (realRoot !== null) try {
353
+ return toPosix(relative(realRoot, realpathSync(file)));
354
+ } catch {}
355
+ return toPosix(relative(config.root, file));
356
+ };
357
+ }
358
+ async function explicitFiles(config, files) {
359
+ const out = /* @__PURE__ */ new Set();
360
+ await mapLimit(files, RESOLVE_CONCURRENCY, async (file) => {
361
+ const logical = resolve(config.root, file);
362
+ let real;
363
+ try {
364
+ real = await realpath(logical);
365
+ } catch (error) {
366
+ if (isMissing(error, NOT_A_FILE)) return;
367
+ throw error;
368
+ }
369
+ if (isIncluded(real, config) || isIncluded(logical, config)) out.add(real);
370
+ });
371
+ return [...out].sort();
372
+ }
373
+ function emptyRootDiagnostic(root, ref) {
374
+ const file = ref(root);
375
+ return {
376
+ code: "extract-empty-root",
377
+ severity: "error",
378
+ message: `The include entry ${file} matches no file; fix project.include or project.exclude in the config`,
379
+ file
380
+ };
381
+ }
382
+ /**
383
+ * A missing compiler fails every file of its kind with the same message;
384
+ * the project-level list names it once, with the other files as `related`.
385
+ */
386
+ function projectDiagnostics(scans, leading) {
387
+ const out = leading;
388
+ const missing = /* @__PURE__ */ new Map();
389
+ for (const scan of scans) for (const diagnostic of scan.diagnostics) {
390
+ if (diagnostic.code !== "extract-missing-compiler") {
391
+ out.push(diagnostic);
392
+ continue;
393
+ }
394
+ const first = missing.get(diagnostic.message);
395
+ if (first === void 0) {
396
+ const copy = { ...diagnostic };
397
+ missing.set(diagnostic.message, copy);
398
+ out.push(copy);
399
+ } else (first.related ??= []).push({
400
+ file: scan.refFile,
401
+ message: "also needs it"
402
+ });
403
+ }
404
+ return out;
405
+ }
406
+ /**
407
+ * A `worker_threads` pool, started before the files are read so the
408
+ * workers load the parser while the main thread reads. `run` hands out
409
+ * batches as workers finish, so one slow file (a large SFC) does not idle
410
+ * the rest.
411
+ */
412
+ var ScanPool = class {
413
+ #workers = [];
414
+ /** Set while a run is active: how a dead worker ends it. */
415
+ #fail = null;
416
+ #failed = false;
417
+ constructor(size, config, codec) {
418
+ const init = {
419
+ marker: WORKER_MARKER,
420
+ config: scanConfig(config),
421
+ idLength: codec.idLength
422
+ };
423
+ const onFailure = () => {
424
+ this.#failed = true;
425
+ this.#fail?.();
426
+ };
427
+ for (let i = 0; i < size; i++) {
428
+ const worker = new Worker(WORKER_URL, { workerData: init });
429
+ worker.on("error", onFailure);
430
+ worker.on("exit", (code) => {
431
+ if (code !== 0) onFailure();
432
+ });
433
+ this.#workers.push(worker);
434
+ }
435
+ }
436
+ /**
437
+ * Scans `misses` into `results` by file index. Resolves false when a
438
+ * worker could not start or died: the caller scans what is left
439
+ * in-process. A scan error inside a worker rejects, as it would
440
+ * in-process.
441
+ */
442
+ run(misses, results) {
443
+ if (this.#failed) return Promise.resolve(false);
444
+ const batches = [];
445
+ for (let i = 0; i < misses.length; i += BATCH) batches.push(misses.slice(i, i + BATCH));
446
+ let next = 0;
447
+ let pending = batches.length;
448
+ return new Promise((resolveRun, rejectRun) => {
449
+ let settled = false;
450
+ const finish = (outcome) => {
451
+ if (settled) return;
452
+ settled = true;
453
+ this.#fail = null;
454
+ for (const worker of this.#workers) worker.removeAllListeners("message");
455
+ if (outcome instanceof Error) rejectRun(outcome);
456
+ else resolveRun(outcome);
457
+ };
458
+ this.#fail = () => finish(false);
459
+ const send = (worker) => {
460
+ if (next >= batches.length) return;
461
+ const batch = next++;
462
+ const tasks = batches[batch].map((miss) => miss.task);
463
+ worker.postMessage({
464
+ batch,
465
+ tasks
466
+ });
467
+ };
468
+ if (pending === 0) finish(true);
469
+ for (const worker of this.#workers) {
470
+ worker.on("message", (response) => {
471
+ if (settled) return;
472
+ if ("error" in response) {
473
+ const error = new Error(response.error.message);
474
+ if (response.error.stack !== void 0) error.stack = response.error.stack;
475
+ finish(error);
476
+ return;
477
+ }
478
+ const batch = batches[response.batch];
479
+ for (let j = 0; j < batch.length; j++) results[batch[j].index] = response.results[j];
480
+ poolStats.files += batch.length;
481
+ if (--pending === 0) finish(true);
482
+ else send(worker);
483
+ });
484
+ send(worker);
485
+ send(worker);
486
+ }
487
+ });
488
+ }
489
+ close() {
490
+ for (const worker of this.#workers) worker.terminate();
491
+ }
492
+ };
493
+ function poolSize(misses, option) {
494
+ if (option !== void 0) return Math.max(0, Math.min(Math.floor(option), misses));
495
+ if (misses <= POOL_THRESHOLD) return 0;
496
+ return Math.max(0, Math.min(POOL_MAX, availableParallelism() - 1));
497
+ }
498
+ let workerEntryExists;
499
+ let warnedMissingEntry = false;
500
+ /** A pool for `misses` files, or null to scan in-process (also when the worker entry was not packed). */
501
+ function startPool(misses, option, config, codec) {
502
+ const size = poolSize(misses, option);
503
+ if (size === 0) return null;
504
+ workerEntryExists ??= existsSync(fileURLToPath(WORKER_URL));
505
+ return workerEntryExists ? new ScanPool(size, config, codec) : null;
506
+ }
507
+ /**
508
+ * A build that lost the worker entry still scans correctly, only slower:
509
+ * counted once per scan so tests of the packed layout see it, and said once
510
+ * when the caller asked for workers by number and would otherwise never
511
+ * learn why the scan did not speed up.
512
+ */
513
+ function missingEntryFallback(option) {
514
+ poolStats.fallbacks++;
515
+ if (option !== void 0 && option > 0 && !warnedMissingEntry) {
516
+ warnedMissingEntry = true;
517
+ console.warn(`[vi18n] The scan worker entry ${fileURLToPath(WORKER_URL)} is missing; scanning in-process`);
518
+ }
519
+ }
520
+ function cachedScan(file, refFile, entry) {
521
+ return {
522
+ file,
523
+ refFile,
524
+ occurrences: entry.occurrences,
525
+ diagnostics: entry.diagnostics,
526
+ fromCache: true
527
+ };
528
+ }
529
+ /**
530
+ * Files scanned by pool workers, and scans that wanted a pool but fell back
531
+ * in-process (a worker died, or the worker entry was not packed), since the
532
+ * process started. Diagnostics for tests and benchmarks; nothing reads
533
+ * them to decide anything.
534
+ */
535
+ const poolStats = {
536
+ files: 0,
537
+ fallbacks: 0
538
+ };
539
+ /**
540
+ * Scans the project (§2.5.6). `aborted` is true when an include entry
541
+ * matched no file, a file failed to parse or compile, or a compiler is
542
+ * missing; the scan still covers every other file so all problems are
543
+ * reported at once, but `vi18n extract` must not write.
544
+ */
545
+ async function scanProject(config, codec, options = {}) {
546
+ const ref = refMapper(config);
547
+ const { files, leading } = await filesToScan(config, options, ref);
548
+ const cache = options.cache === true ? await ScanCache.open(config) : null;
549
+ let pool = null;
550
+ if (cache === null || cache.size === 0) pool = startPool(files.length, options.workers, config, codec);
551
+ const scans = Array.from({ length: files.length });
552
+ try {
553
+ const misses = readFiles(files, ref, cache, scans);
554
+ pool ??= startPool(misses.length, options.workers, config, codec);
555
+ if (pool === null && workerEntryExists === false && poolSize(misses.length, options.workers) > 0) missingEntryFallback(options.workers);
556
+ const results = [];
557
+ if (pool !== null && misses.length > 0 && !await pool.run(misses, results)) poolStats.fallbacks++;
558
+ for (const miss of misses) {
559
+ const result = results[miss.index] ??= await scanSource(miss.task, config, codec);
560
+ scans[miss.index] = {
561
+ file: miss.task.file,
562
+ refFile: miss.task.refFile,
563
+ occurrences: result.occurrences,
564
+ diagnostics: result.diagnostics,
565
+ fromCache: false
566
+ };
567
+ if (cache !== null) cacheResult(cache, miss, result);
568
+ }
569
+ } finally {
570
+ pool?.close();
571
+ }
572
+ const fileScans = scans.filter((scan) => scan !== void 0);
573
+ if (cache !== null) {
574
+ if (options.files === void 0) cache.retain(new Set(fileScans.map((scan) => scan.file)));
575
+ await cache.save();
576
+ }
577
+ const diagnostics = projectDiagnostics(fileScans, leading);
578
+ return {
579
+ files: fileScans,
580
+ messages: aggregateOccurrences((function* () {
581
+ for (const scan of fileScans) yield* scan.occurrences;
582
+ })()),
583
+ diagnostics,
584
+ aborted: diagnostics.some((diagnostic) => ABORT_CODES.has(diagnostic.code))
585
+ };
586
+ }
587
+ /** The files a scan covers, and a diagnostic for each include entry that matched none. */
588
+ async function filesToScan(config, options, ref) {
589
+ if (options.files !== void 0) return {
590
+ files: await explicitFiles(config, options.files),
591
+ leading: []
592
+ };
593
+ const listed = await listProjectFiles(config);
594
+ return {
595
+ files: listed.files,
596
+ leading: listed.emptyRoots.map((root) => emptyRootDiagnostic(root, ref))
597
+ };
598
+ }
599
+ /**
600
+ * Fills `scans` with the cache's hits and returns the misses, read. Files
601
+ * deleted since the walk are no longer part of the project and are left out.
602
+ */
603
+ function readFiles(files, ref, cache, scans) {
604
+ const misses = [];
605
+ for (let index = 0; index < files.length; index++) {
606
+ const file = files[index];
607
+ const refFile = ref(file);
608
+ const read = readFile$1(file, cache);
609
+ if (read === null) continue;
610
+ if ("hit" in read) {
611
+ scans[index] = cachedScan(file, refFile, read.hit);
612
+ continue;
613
+ }
614
+ const { text, mtimeMs, size } = read;
615
+ misses.push({
616
+ index,
617
+ task: {
618
+ file,
619
+ refFile,
620
+ text
621
+ },
622
+ mtimeMs,
623
+ size,
624
+ contentHash: read.hash
625
+ });
626
+ }
627
+ return misses;
628
+ }
629
+ /** One file: its cache entry when its stat or content matches one, else its text; null when it is gone. */
630
+ function readFile$1(file, cache) {
631
+ let mtimeMs = 0;
632
+ let size = 0;
633
+ let text;
634
+ try {
635
+ if (cache !== null) {
636
+ const info = statSync(file);
637
+ mtimeMs = info.mtimeMs;
638
+ size = info.size;
639
+ const hit = cache.byStat(file, mtimeMs, size);
640
+ if (hit !== void 0) return { hit };
641
+ }
642
+ text = readFileSync(file, "utf8");
643
+ } catch (error) {
644
+ if (isMissing(error, NOT_A_FILE)) return null;
645
+ throw error;
646
+ }
647
+ if (cache === null) return {
648
+ text,
649
+ mtimeMs,
650
+ size,
651
+ hash: ""
652
+ };
653
+ const hash = contentHash(text);
654
+ const hit = cache.byContent(file, hash, mtimeMs, size);
655
+ return hit === void 0 ? {
656
+ text,
657
+ mtimeMs,
658
+ size,
659
+ hash
660
+ } : { hit };
661
+ }
662
+ /**
663
+ * Stores a scan in the cache. Failures are not cached: installing or
664
+ * upgrading a compiler fixes them without touching the file.
665
+ */
666
+ function cacheResult(cache, miss, result) {
667
+ if (result.aborted) {
668
+ cache.delete(miss.task.file);
669
+ return;
670
+ }
671
+ cache.set(miss.task.file, {
672
+ mtimeMs: miss.mtimeMs,
673
+ size: miss.size,
674
+ contentHash: miss.contentHash,
675
+ occurrences: result.occurrences,
676
+ diagnostics: result.diagnostics
677
+ });
678
+ }
679
+ // src/core/fs.ts
680
+ /** File writes the build side shares. */
681
+ /**
682
+ * Writes `content` through a hidden temp file beside `path` and a rename,
683
+ * into an existing directory, so a reader (an editor's TypeScript server,
684
+ * a watcher) never sees half a file. The temp file is removed when the write
685
+ * fails; its random suffix keeps concurrent writers in one process apart.
686
+ */
687
+ async function writeFileAtomic(path, content) {
688
+ const dir = dirname(path);
689
+ const temp = join(dir, `.${basename(path)}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`);
690
+ try {
691
+ await writeFile(temp, content);
692
+ await rename(temp, path);
693
+ } catch (error) {
694
+ await rm(temp, { force: true });
695
+ throw error;
696
+ }
697
+ }
698
+ // src/types-gen/gen.ts
699
+ /**
700
+ * `vi18n.gen.ts` (docs/INTERNALS.md §2.16, PLAN §5.18): the generated
701
+ * `Register` augmentation that turns `Locale` into the configured union.
702
+ * Written beside `vi18n.config.ts` by the plugin and by `vi18n init`/`extract`,
703
+ * and committed like `routeTree.gen.ts`.
704
+ */
705
+ /** The generated file's name, in the directory of `vi18n.config.ts`. */
706
+ const GEN_FILE = "vi18n.gen.ts";
707
+ /** The `locales` union: configured locales in config order, pseudo-locales left out. */
708
+ function localesUnion(config) {
709
+ const pseudo = config.pseudoLocales;
710
+ let union = "";
711
+ for (const locale of config.locales) {
712
+ if (pseudo.includes(locale)) continue;
713
+ union += (union ? " | " : "") + JSON.stringify(locale);
714
+ }
715
+ return union || "never";
716
+ }
717
+ /**
718
+ * `messages`: the manual-id messages of the packages `extraction.dependencies`
719
+ * opts in (their `vi18n.messages.json`, §2.16), by id, so `msg({ id })` is
720
+ * typed from the library's text. Empty without any.
721
+ */
722
+ function messagesMember(config) {
723
+ if (config.extraction.dependencies.length === 0) return "";
724
+ const ids = [...libraryIds(config)].sort(([a], [b]) => compareText(a, b));
725
+ if (ids.length === 0) return "";
726
+ let out = ` messages: {\n`;
727
+ for (const [id, message] of ids) out += ` ${JSON.stringify(id)}: ${JSON.stringify(message)};\n`;
728
+ return out + ` };\n`;
729
+ }
730
+ /**
731
+ * The file's exact content: configured locales in config order, pseudo-locales
732
+ * left out (they are switched on per build and never part of the app's API),
733
+ * then the opted-in packages' manual-id messages, if any.
734
+ */
735
+ function genFileContent(config) {
736
+ return `// Generated by @menapo/vi18n from ${CONFIG_FILE}. Do not edit; commit it.\nimport type {} from "@menapo/vi18n";\n\ndeclare module "@menapo/vi18n" {\n interface Register {\n locales: ${localesUnion(config)};\n` + messagesMember(config) + " }\n}\n";
737
+ }
738
+ /**
739
+ * What earlier releases wrote for the same locales (no import, `export {}`
740
+ * last). The drift checks accept it: like the catalogs' `X-Generator` line
741
+ * (INTERNALS §2.6.3), a vi18n upgrade alone must not fail `extract --check`
742
+ * or make `compile` refuse. Any write replaces it with the current content.
743
+ */
744
+ function previousGenFileContent(config) {
745
+ return `// Generated by @menapo/vi18n from ${CONFIG_FILE}. Do not edit; commit it.\ndeclare module "@menapo/vi18n" {\n interface Register {\n locales: ${localesUnion(config)};\n }\n}\nexport {};\n`;
746
+ }
747
+ /**
748
+ * Whether `text` (the file as read) is up to date for the drift checks: the
749
+ * current content or an earlier release's for the same locales. CRLF line
750
+ * ends (a checkout with `core.autocrlf`) are not drift either.
751
+ */
752
+ function genFileUpToDate(config, text) {
753
+ const normalized = text.replace(/\r\n/g, "\n");
754
+ return normalized === genFileContent(config) || normalized === previousGenFileContent(config);
755
+ }
756
+ /**
757
+ * Writes `vi18n.gen.ts` beside the config when its content changed; true when
758
+ * written. Zero-config mode (no config file) writes nothing (INTERNALS
759
+ * §2.7.1). The plugin's environments and the CLI may write concurrently, so
760
+ * the file is replaced by an atomic rename and never seen half-written by the
761
+ * editor's TypeScript server.
762
+ */
763
+ async function writeGenFile(config) {
764
+ if (config.configFile === null) return false;
765
+ const path = join(dirname(config.configFile), GEN_FILE);
766
+ const content = genFileContent(config);
767
+ let current = null;
768
+ try {
769
+ current = await readFile(path, "utf8");
770
+ } catch (error) {
771
+ if (error.code !== "ENOENT") throw error;
772
+ }
773
+ if (current !== null && current.replace(/\r\n/g, "\n") === content) return false;
774
+ await writeFileAtomic(path, content);
775
+ return true;
776
+ }
777
+ // src/core/sync.ts
778
+ /** Removals allowed without `--yes` whatever the catalog size (PLAN §5.5). */
779
+ const LIMIT_FLOOR = 50;
780
+ /** Share of a locale's translated entries one extract may clear or delete without `--yes`. */
781
+ const LIMIT_SHARE = .1;
782
+ function syncCatalogs(input) {
783
+ const { config, codec, messages, catalogs, options } = input;
784
+ const sourceCatalog = catalogs.get(config.sourceLocale)?.catalog ?? null;
785
+ const result = {
786
+ catalogs: /* @__PURE__ */ new Map(),
787
+ changed: [],
788
+ stats: {},
789
+ blocked: [],
790
+ deletedKeys: [],
791
+ diagnostics: []
792
+ };
793
+ const deleted = /* @__PURE__ */ new Set();
794
+ const limits = [];
795
+ let overLimit = false;
796
+ const coverage = libraryCoverage(catalogs, messages, config, codec);
797
+ for (const locale of config.locales) {
798
+ const loaded = catalogs.get(locale);
799
+ const read = loaded?.catalog ?? null;
800
+ const synced = syncLocale({
801
+ config,
802
+ codec,
803
+ messages,
804
+ locale,
805
+ catalog: read,
806
+ sourceCatalog,
807
+ options,
808
+ coverage
809
+ });
810
+ const file = displayPath(config.root, loaded?.path ?? catalogPath(config, locale));
811
+ for (const diagnostic of synced.diagnostics) {
812
+ diagnostic.file ??= file;
813
+ diagnostic.locale ??= locale;
814
+ result.diagnostics.push(diagnostic);
815
+ }
816
+ result.catalogs.set(locale, synced.catalog);
817
+ result.stats[locale] = synced.stats;
818
+ if (wouldChange(read, synced.catalog, locale === config.sourceLocale)) result.changed.push(locale);
819
+ for (const key of synced.deleted) deleted.add(key);
820
+ if (options.mode !== "full" || locale === config.sourceLocale) continue;
821
+ const limit = Math.max(LIMIT_FLOOR, Math.ceil(LIMIT_SHARE * translatedCount(read)));
822
+ limits.push({
823
+ locale,
824
+ removals: synced.removals,
825
+ limit
826
+ });
827
+ if (synced.removals > limit && !options.yes) {
828
+ overLimit = true;
829
+ result.diagnostics.push({
830
+ code: "catalog-safety-limit",
831
+ severity: "error",
832
+ message: `vi18n extract would clear or delete ${synced.removals} translated ${synced.removals === 1 ? "entry" : "entries"} in ${locale}, over its limit of ${limit} (10 % of its translated entries, at least ${LIMIT_FLOOR}); check the scan covers every app, then run vi18n extract --yes`,
833
+ file,
834
+ locale
835
+ });
836
+ }
837
+ }
838
+ if (overLimit) result.blocked = limits;
839
+ result.deletedKeys = [...deleted].sort(compareText);
840
+ return result;
841
+ }
842
+ /** One locale; what writers re-run inside `updateCatalogFile` when the file changed under them. */
843
+ function syncCatalog(input) {
844
+ const { catalog, stats, removals, diagnostics } = syncLocale(input);
845
+ return {
846
+ catalog,
847
+ stats,
848
+ removals,
849
+ diagnostics
850
+ };
851
+ }
852
+ function syncLocale(input) {
853
+ const { config, codec, locale } = input;
854
+ const layout = catalogLayout(config);
855
+ const messages = ownedMessages(input.messages, locale, input.catalog, input.coverage, {
856
+ sourceLocale: config.sourceLocale,
857
+ layout,
858
+ codec
859
+ });
860
+ const base = input.catalog ?? emptyCatalog(locale, layout, {
861
+ idScheme: codec.idScheme,
862
+ sourceLocale: config.sourceLocale
863
+ });
864
+ const recorded = base.header.idScheme;
865
+ const rekey = layout !== "source" && recorded !== null && recorded !== codec.idScheme;
866
+ const context = {
867
+ config,
868
+ codec,
869
+ layout,
870
+ isSource: locale === config.sourceLocale,
871
+ messages,
872
+ sourceCatalog: input.sourceCatalog,
873
+ sourceIndex: sourceIndex(input.sourceCatalog, layout, locale === config.sourceLocale),
874
+ icuFlag: config.catalogs.icuFlag && layout !== "json"
875
+ };
876
+ if (input.options.mode === "add-only") {
877
+ if (rekey) return {
878
+ catalog: base,
879
+ stats: emptyStats(),
880
+ removals: 0,
881
+ diagnostics: [schemeDiagnostic(recorded, codec)],
882
+ deleted: []
883
+ };
884
+ return addOnly(base, context);
885
+ }
886
+ return full(base, context, rekey);
887
+ }
888
+ function emptyStats() {
889
+ return {
890
+ added: 0,
891
+ deleted: 0,
892
+ cleared: 0,
893
+ moved: 0,
894
+ rekeyed: 0,
895
+ updated: 0
896
+ };
897
+ }
898
+ function addOnly(catalog, context) {
899
+ const { codec, layout, messages } = context;
900
+ const stats = emptyStats();
901
+ const index = /* @__PURE__ */ new Map();
902
+ const entries = catalog.entries;
903
+ for (let i = 0; i < entries.length; i++) {
904
+ const key = entryKey(entries[i], layout, codec);
905
+ if (key !== null && !index.has(key)) index.set(key, i);
906
+ }
907
+ let out = null;
908
+ for (const message of messages.values()) {
909
+ const at = index.get(message.id);
910
+ if (at === void 0) {
911
+ (out ??= entries.slice()).push(newEntry(message, context));
912
+ stats.added++;
913
+ continue;
914
+ }
915
+ const entry = entries[at];
916
+ if (classify(entry, message, context) !== "same") continue;
917
+ const grown = withMissingNotes(entry, message);
918
+ if (grown !== entry) {
919
+ (out ??= entries.slice())[at] = grown;
920
+ stats.updated++;
921
+ }
922
+ }
923
+ const header = completeHeader(catalog.header, context, false);
924
+ if (out === null && header === catalog.header) return {
925
+ catalog,
926
+ stats,
927
+ removals: 0,
928
+ diagnostics: [],
929
+ deleted: []
930
+ };
931
+ return {
932
+ catalog: {
933
+ ...catalog,
934
+ header,
935
+ entries: out ?? entries
936
+ },
937
+ stats,
938
+ removals: 0,
939
+ diagnostics: [],
940
+ deleted: []
941
+ };
942
+ }
943
+ /** Adds the scan's references and notes an entry lacks, keeping everything it has. */
944
+ function withMissingNotes(entry, message) {
945
+ let refs = null;
946
+ for (const ref of message.refs) if (!entry.refs.includes(ref)) (refs ??= entry.refs.slice()).push(ref);
947
+ let contexts = null;
948
+ for (const note of message.contexts) if (!entry.contexts.includes(note)) (contexts ??= entry.contexts.slice()).push(note);
949
+ if (refs === null && contexts === null) return entry;
950
+ return {
951
+ ...entry,
952
+ refs: refs === null ? entry.refs : refs.sort(compareText),
953
+ contexts: contexts ?? entry.contexts
954
+ };
955
+ }
956
+ function full(read, context, rekey) {
957
+ const stats = emptyStats();
958
+ let catalog = read;
959
+ if (rekey) {
960
+ const rekeyed = rekeyCatalog(catalog, context);
961
+ catalog = rekeyed.catalog;
962
+ stats.rekeyed = rekeyed.count;
963
+ }
964
+ catalog = mergeDuplicates(catalog, context.codec);
965
+ const { out, matched, deletions, cleared } = matchEntries(catalog, context, stats);
966
+ const additions = addMessages(matched, deletions, context, stats);
967
+ let removals = cleared;
968
+ for (const deletion of deletions) {
969
+ if (deletion.movedTo) continue;
970
+ stats.deleted++;
971
+ if (!context.isSource && hasTranslation(deletion.entry)) removals++;
972
+ }
973
+ for (const added of additions) out.push(added);
974
+ for (let i = 0; i < out.length; i++) out[i] = withIcuFlag(out[i], context.icuFlag);
975
+ const diagnostics = [];
976
+ let obsolete = catalog.obsolete;
977
+ let droppedObsolete = catalog.droppedObsolete;
978
+ if (obsolete.length > 0) {
979
+ diagnostics.push({
980
+ code: "catalog-obsolete-dropped",
981
+ severity: "info",
982
+ message: `dropped ${obsolete.length} obsolete #~ ${obsolete.length === 1 ? "entry" : "entries"}; git history keeps them`
983
+ });
984
+ obsolete = [];
985
+ droppedObsolete = 0;
986
+ }
987
+ const header = completeHeader(catalog.header, context, true);
988
+ return {
989
+ catalog: header === read.header && obsolete === read.obsolete && out.length === read.entries.length && out.every((entry, i) => entry === read.entries[i]) ? read : {
990
+ ...catalog,
991
+ header,
992
+ entries: out,
993
+ obsolete,
994
+ droppedObsolete
995
+ },
996
+ stats,
997
+ removals,
998
+ diagnostics,
999
+ deleted: deletions.map((deletion) => deletion.key)
1000
+ };
1001
+ }
1002
+ /**
1003
+ * The catalog's entries against the scan: kept, refreshed or rewritten in
1004
+ * `out`, the keys the scan `matched`, the entries to delete, and how many
1005
+ * translations a changed source cleared.
1006
+ */
1007
+ function matchEntries(catalog, context, stats) {
1008
+ const { codec, layout, messages, isSource } = context;
1009
+ const keep = new Set(context.config.extraction.keep);
1010
+ const out = [];
1011
+ const matched = /* @__PURE__ */ new Set();
1012
+ const deletions = [];
1013
+ let cleared = 0;
1014
+ for (const entry of catalog.entries) {
1015
+ const key = entryKey(entry, layout, codec);
1016
+ if (key === null) {
1017
+ out.push(entry);
1018
+ continue;
1019
+ }
1020
+ const message = messages.get(key);
1021
+ if (message === void 0) {
1022
+ if (keep.has(key)) out.push(entry);
1023
+ else deletions.push(deletion(entry, key, context));
1024
+ continue;
1025
+ }
1026
+ const kind = classify(entry, message, context);
1027
+ if (kind === "other") {
1028
+ deletions.push(deletion(entry, key, context));
1029
+ continue;
1030
+ }
1031
+ matched.add(key);
1032
+ if (kind === "changed") {
1033
+ if (!isSource && hasTranslation(entry)) {
1034
+ stats.cleared++;
1035
+ cleared++;
1036
+ }
1037
+ out.push(rewritten(entry, message, layout));
1038
+ continue;
1039
+ }
1040
+ const refreshed = refresh(entry, message, layout);
1041
+ if (refreshed.notesChanged) stats.updated++;
1042
+ out.push(refreshed.entry);
1043
+ }
1044
+ return {
1045
+ out,
1046
+ matched,
1047
+ deletions,
1048
+ cleared
1049
+ };
1050
+ }
1051
+ function deletion(entry, key, context) {
1052
+ return {
1053
+ entry,
1054
+ key,
1055
+ canonical: canonicalOf(sourceText(entry, context), context.codec),
1056
+ movedTo: false
1057
+ };
1058
+ }
1059
+ /**
1060
+ * New entries for the messages no entry matched. One deleted entry and one
1061
+ * added entry with the same canonical source are one message that changed
1062
+ * id (generated ↔ manual, or a manual rename), so the translation follows
1063
+ * it and the deletion is marked moved.
1064
+ */
1065
+ function addMessages(matched, deletions, context, stats) {
1066
+ const additions = [];
1067
+ const addedTexts = /* @__PURE__ */ new Map();
1068
+ for (const message of context.messages.values()) {
1069
+ if (matched.has(message.id)) continue;
1070
+ matched.add(message.id);
1071
+ additions.push(newEntry(message, context));
1072
+ addedTexts.set(message.canonical, (addedTexts.get(message.canonical) ?? 0) + 1);
1073
+ }
1074
+ const deletedTexts = byCanonical(deletions);
1075
+ for (let i = 0; i < additions.length; i++) {
1076
+ const added = additions[i];
1077
+ const canonical = added.source;
1078
+ const from = deletedTexts?.get(canonical);
1079
+ if (from === void 0 || from.length !== 1 || addedTexts.get(canonical) !== 1) {
1080
+ stats.added++;
1081
+ continue;
1082
+ }
1083
+ const source = from[0];
1084
+ source.movedTo = true;
1085
+ stats.moved++;
1086
+ additions[i] = {
1087
+ ...added,
1088
+ translation: source.entry.translation,
1089
+ state: source.entry.state,
1090
+ fuzzy: source.entry.fuzzy
1091
+ };
1092
+ }
1093
+ return additions;
1094
+ }
1095
+ /** Deletions by canonical source; null when none has one. */
1096
+ function byCanonical(deletions) {
1097
+ let texts = null;
1098
+ for (const deletion of deletions) {
1099
+ if (deletion.canonical === null) continue;
1100
+ texts ??= /* @__PURE__ */ new Map();
1101
+ const list = texts.get(deletion.canonical);
1102
+ if (list === void 0) texts.set(deletion.canonical, [deletion]);
1103
+ else list.push(deletion);
1104
+ }
1105
+ return texts;
1106
+ }
1107
+ /** The matched entry with refs, notes, `maxLength` and the canonical source taken from the scan. */
1108
+ function refresh(entry, message, layout) {
1109
+ const maxLength = message.maxLength ?? null;
1110
+ const notesChanged = entry.maxLength !== maxLength || !sameList(entry.refs, message.refs) || !sameList(entry.contexts, message.contexts);
1111
+ const label = layout === "id" ? message.label : entry.label;
1112
+ if (!notesChanged && entry.source === message.canonical && entry.label === label) return {
1113
+ entry,
1114
+ notesChanged
1115
+ };
1116
+ return {
1117
+ entry: {
1118
+ ...entry,
1119
+ source: message.canonical,
1120
+ label,
1121
+ refs: message.refs.slice(),
1122
+ contexts: message.contexts.slice(),
1123
+ maxLength
1124
+ },
1125
+ notesChanged
1126
+ };
1127
+ }
1128
+ /** A manual entry whose text changed: the new source, an empty translation, no `ai` or `fuzzy`. */
1129
+ function rewritten(entry, message, layout) {
1130
+ return {
1131
+ ...entry,
1132
+ source: message.canonical,
1133
+ label: layout === "id" ? message.label : entry.label,
1134
+ translation: "",
1135
+ state: "untranslated",
1136
+ fuzzy: false,
1137
+ refs: message.refs.slice(),
1138
+ contexts: message.contexts.slice(),
1139
+ maxLength: message.maxLength ?? null
1140
+ };
1141
+ }
1142
+ /** A new entry's label: the scan's under the `"id"` layout, a generated id in JSON, else none. */
1143
+ function newLabel(message, layout) {
1144
+ if (layout === "id") return message.label;
1145
+ return layout === "json" && !message.manual ? message.id : null;
1146
+ }
1147
+ function newEntry(message, context) {
1148
+ const { layout } = context;
1149
+ return createEntry({
1150
+ manualId: message.manual ? message.id : null,
1151
+ label: newLabel(message, layout),
1152
+ source: message.canonical,
1153
+ refs: message.refs.slice(),
1154
+ contexts: message.contexts.slice(),
1155
+ maxLength: message.maxLength ?? null,
1156
+ flags: context.icuFlag ? [{
1157
+ name: ICU_FLAG,
1158
+ line: "#,"
1159
+ }] : []
1160
+ });
1161
+ }
1162
+ const ICU_FLAG = "icu-message-format";
1163
+ /**
1164
+ * `catalogs.icuFlag` is vi18n's to set (PLAN §4.4): a full sync adds the
1165
+ * flag to every entry, or takes it off when the option is false, so the
1166
+ * file follows the config. A flag already present stays where it was read.
1167
+ */
1168
+ function withIcuFlag(entry, on) {
1169
+ if (entry.foreignContext !== null) return entry;
1170
+ if (entry.flags.some((flag) => flag.name === ICU_FLAG) === on) return entry;
1171
+ return {
1172
+ ...entry,
1173
+ flags: on ? [{
1174
+ name: ICU_FLAG,
1175
+ line: "#,"
1176
+ }, ...entry.flags] : entry.flags.filter((flag) => flag.name !== ICU_FLAG)
1177
+ };
1178
+ }
1179
+ /**
1180
+ * Re-key after an `ids.length` change (PLAN §5.5): each entry's text comes
1181
+ * from its own source (JSON, the source locale) or, for `"id"`-layout
1182
+ * targets, from the source locale's entry for the same old key (read at the
1183
+ * recorded length), else the target's own `#. source:` note, and its
1184
+ * label is recomputed at the new length. Translations stay, and nothing here
1185
+ * counts against the safety limit. An entry whose text cannot be recovered
1186
+ * keeps its old key, so the normal rules (and the limit) apply to it.
1187
+ */
1188
+ function rekeyCatalog(catalog, context) {
1189
+ const { codec, layout, isSource } = context;
1190
+ const joined = layout === "id" && !isSource ? oldLabelIndex(context.sourceCatalog, catalog.header.idScheme, codec) : null;
1191
+ let count = 0;
1192
+ const entries = catalog.entries.map((entry) => {
1193
+ if (entry.foreignContext !== null) return entry;
1194
+ if (layout === "json" && entry.manualId !== null) return entry;
1195
+ let text = entry.source;
1196
+ if (layout === "id" && !isSource) {
1197
+ const key = entry.manualId ?? entry.label ?? "";
1198
+ text = joined?.get(key) ?? context.sourceIndex?.get(key) ?? entry.source;
1199
+ }
1200
+ const canonical = canonicalOf(text, codec);
1201
+ if (canonical === null) return entry;
1202
+ const label = codec.label(canonical);
1203
+ if (label !== entry.label) count++;
1204
+ return {
1205
+ ...entry,
1206
+ label,
1207
+ source: canonical
1208
+ };
1209
+ });
1210
+ return {
1211
+ catalog: {
1212
+ ...catalog,
1213
+ entries,
1214
+ header: {
1215
+ ...catalog.header,
1216
+ idScheme: codec.idScheme
1217
+ }
1218
+ },
1219
+ count
1220
+ };
1221
+ }
1222
+ /**
1223
+ * The source locale's text per key at the target's recorded length: manual
1224
+ * ids as they are, generated entries by their text's hash cut to the old
1225
+ * length. Hashing rather than reading the source file's labels keeps the
1226
+ * join working when the source locale is already at the new scheme (an
1227
+ * interrupted extract, a TMS export from before the change merged back),
1228
+ * where the target's `#. source:` notes may be all that is left otherwise and
1229
+ * a key-based TMS strips them.
1230
+ */
1231
+ function oldLabelIndex(sourceCatalog, recorded, codec) {
1232
+ const old = recorded === null ? null : parseIdScheme(recorded);
1233
+ if (old === null || sourceCatalog === null) return null;
1234
+ const index = /* @__PURE__ */ new Map();
1235
+ for (const entry of sourceCatalog.entries) {
1236
+ if (entry.foreignContext !== null || entry.source === null) continue;
1237
+ let key = entry.manualId;
1238
+ if (key === null) {
1239
+ const canonical = canonicalOf(entry.source, codec);
1240
+ if (canonical === null) continue;
1241
+ key = codec.sourceHash(canonical).slice(0, old.length);
1242
+ }
1243
+ if (!index.has(key)) index.set(key, entry.source);
1244
+ }
1245
+ return index;
1246
+ }
1247
+ /**
1248
+ * How an entry found under a message's key relates to it:
1249
+ * - `same`: the entry is for the message's text;
1250
+ * - `changed`: a manual entry whose source text changed (D10);
1251
+ * - `other`: a generated entry whose recorded text is a different text with
1252
+ * the same id, i.e. a deleted message whose id the new one took.
1253
+ *
1254
+ * A generated entry's key is a fingerprint of its text, so a recorded source
1255
+ * that no longer hashes to the key (a hand-edited JSON `source`, a stale
1256
+ * `#. source:` note) is a damaged copy of the same text, not another text.
1257
+ */
1258
+ function classify(entry, message, context) {
1259
+ const { codec, layout } = context;
1260
+ if (entry.manualId !== null) {
1261
+ if (layout === "id") return entry.label === message.label ? "same" : "changed";
1262
+ if (entry.source === message.canonical) return "same";
1263
+ return canonicalOf(entry.source, codec) === message.canonical ? "same" : "changed";
1264
+ }
1265
+ const text = sourceText(entry, context);
1266
+ if (text === null || text === message.canonical) return "same";
1267
+ const canonical = canonicalOf(text, codec);
1268
+ if (canonical === null || canonical === message.canonical) return "same";
1269
+ return codec.label(canonical) === message.id ? "other" : "same";
1270
+ }
1271
+ /**
1272
+ * An entry's source text. `"id"`-layout targets only carry a translator
1273
+ * note, so the source locale's text for the same key wins when there is one.
1274
+ */
1275
+ function sourceText(entry, context) {
1276
+ if (context.sourceIndex !== null) {
1277
+ const key = entry.manualId ?? entry.label;
1278
+ const text = key === null ? void 0 : context.sourceIndex.get(key);
1279
+ if (text !== void 0) return text;
1280
+ }
1281
+ return entry.source;
1282
+ }
1283
+ function sourceIndex(sourceCatalog, layout, isSource) {
1284
+ if (layout !== "id" || isSource || sourceCatalog === null) return null;
1285
+ const index = /* @__PURE__ */ new Map();
1286
+ for (const entry of sourceCatalog.entries) {
1287
+ if (entry.foreignContext !== null || entry.source === null) continue;
1288
+ const key = entry.manualId ?? entry.label;
1289
+ if (key !== null && !index.has(key)) index.set(key, entry.source);
1290
+ }
1291
+ return index;
1292
+ }
1293
+ /** The header with the scheme (and JSON source locale) a writer records; the same object when nothing changes. */
1294
+ function completeHeader(header, context, full) {
1295
+ const { codec, layout, config } = context;
1296
+ const idScheme = full || header.idScheme === null ? codec.idScheme : header.idScheme;
1297
+ const sourceLocale = layout === "json" && (full || header.sourceLocale === null) ? config.sourceLocale : header.sourceLocale;
1298
+ if (idScheme === header.idScheme && sourceLocale === header.sourceLocale) return header;
1299
+ return {
1300
+ ...header,
1301
+ idScheme,
1302
+ sourceLocale
1303
+ };
1304
+ }
1305
+ function schemeDiagnostic(recorded, codec) {
1306
+ const old = parseIdScheme(recorded);
1307
+ return {
1308
+ code: "id-scheme-mismatch",
1309
+ severity: "error",
1310
+ message: `${old !== null ? `ids.length changed from ${old.length} to ${codec.idLength}` : `the catalog records id scheme ${JSON.stringify(recorded)}, not ${codec.idScheme}`}: run vi18n extract to re-key (until then this catalog is left untouched)`
1311
+ };
1312
+ }
1313
+ function canonicalOf(source, codec) {
1314
+ if (source === null) return null;
1315
+ try {
1316
+ return codec.canonicalize(source);
1317
+ } catch (error) {
1318
+ if (isDiagnosticError(error)) return null;
1319
+ throw error;
1320
+ }
1321
+ }
1322
+ /** Translated or `ai`: what the safety limit protects. */
1323
+ function hasTranslation(entry) {
1324
+ return entry.translation !== "" && entry.state !== "untranslated";
1325
+ }
1326
+ function translatedCount(catalog) {
1327
+ if (catalog === null) return 0;
1328
+ let count = 0;
1329
+ for (const entry of catalog.entries) if (entry.foreignContext === null && hasTranslation(entry)) count++;
1330
+ return count;
1331
+ }
1332
+ /**
1333
+ * Whether writing `next` would change the file `read` came from. Serialising
1334
+ * compares content, not object identity, and the writer unwraps wrapped
1335
+ * strings, so a wrapped file changes even when its content does not.
1336
+ */
1337
+ function wouldChange(read, next, isSourceLocale) {
1338
+ if (read === null) return true;
1339
+ if (read.entries.some((entry) => entry.wrapped)) return true;
1340
+ if (next === read) return false;
1341
+ const options = {
1342
+ isSourceLocale,
1343
+ version: VERSION
1344
+ };
1345
+ return !sameCatalogText(serializeCatalog(read, options), serializeCatalog(next, options));
1346
+ }
1347
+ function sameList(a, b) {
1348
+ if (a.length !== b.length) return false;
1349
+ for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
1350
+ return true;
1351
+ }
1352
+ export { writeGenFile as a, aggregateOccurrences as c, genFileUpToDate as i, configHash as l, syncCatalogs as n, refMapper as o, GEN_FILE as r, scanProject as s, syncCatalog as t };