@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
@@ -1,204 +1,15 @@
1
- import { a as diagnosticError, o as isDiagnosticError } from "./types-D3QGM8XO.js";
2
- import { t as createCodec } from "./codec-DuvU2VQy.js";
3
- import { r as libraryIds } from "./library-D5CWvTQs.js";
4
- import { c as unwrap, d as listImports, l as lineColumn, n as sourceSpecifiers, r as scanModule, s as keyName, t as sourceNeedles, u as locateLiteral } from "./sources-D19czDSA.js";
1
+ import { r as libraryIds } from "./library-tp_xqzSY.js";
2
+ import { p as createCodec } from "./validate-CgzaDdOY.js";
3
+ import { n as isDiagnosticError, t as diagnosticError } from "./diagnostics-LgIWyeSp.js";
4
+ import { C as langFromId, D as locateLiteral, S as armRawParsing, T as lineColumn, _ as insertImport, a as scanModule, f as TYPE_KEYS, g as forEachBindingName, k as listImports, n as sourceNeedles, r as sourceSpecifiers, v as isNode, w as parseModule, x as unwrap, y as keyName } from "./sources-DNVbYsgs.js";
5
5
  import { createRequire } from "node:module";
6
- import { dirname, join, sep } from "node:path";
6
+ import { dirname } from "node:path";
7
7
  import { hash } from "node:crypto";
8
- import { readFileSync, realpathSync, statSync } from "node:fs";
8
+ import { readFileSync, statSync } from "node:fs";
9
9
  import { pathToFileURL } from "node:url";
10
10
  import { isMainThread, parentPort, workerData } from "node:worker_threads";
11
11
  import MagicString from "magic-string";
12
- //#region src/core/extract/parser.ts
13
- /**
14
- * Parsing for extraction (INTERNALS §2.5.4–§2.5.5). The parser is Oxc as Vite
15
- * ships it (`parseSync`), so there is no parser dependency of our own (§6 D16)
16
- * and the CLI and the plugin see the same ESTree. Once raw transfer starts
17
- * ({@link armRawParsing}, {@link enableRawParsing}), the same binding parses
18
- * through it (`raw.ts`, §6 D104) when its Oxc version allows: the same tree,
19
- * faster.
20
- */
21
- let parseSync = null;
22
- /** The raw-transfer parser, once {@link enableRawParsing} found one usable. */
23
- let parseRaw = null;
24
- let rawReady = null;
25
- function loadParser(filename) {
26
- if (parseSync !== null) return parseSync;
27
- let mod;
28
- try {
29
- mod = createRequire(import.meta.url)("vite");
30
- } catch (error) {
31
- throw diagnosticError({
32
- code: "extract-parse-error",
33
- severity: "error",
34
- message: `Cannot load the parser from "vite" (${error.message}); install vite 8 as a dev dependency`,
35
- ...filename === void 0 ? {} : { file: filename }
36
- });
37
- }
38
- if (typeof mod.parseSync !== "function") throw diagnosticError({
39
- code: "extract-parse-error",
40
- severity: "error",
41
- message: `The installed "vite" does not export parseSync; install vite 8 or later`,
42
- ...filename === void 0 ? {} : { file: filename }
43
- });
44
- parseSync = mod.parseSync;
45
- return parseSync;
46
- }
47
- /**
48
- * Names of the platform packages a binding loads from. An owner's other
49
- * optional dependencies are not where its binding lives, and some load a
50
- * `.node` file of their own (`fsevents`, which Vite+ declares, on macOS).
51
- */
52
- const PLATFORM_PACKAGE = /^(?:@voidzero-dev\/vite-plus|@rolldown\/binding)-/;
53
- /**
54
- * {@link BindingOwner} of the `vite` that `from` resolves, or null when it
55
- * cannot be told for certain. Only what the owner declares counts: a
56
- * hoisted `rolldown` or `@oxc-project/types` that belongs to another package
57
- * (Astro's or Nuxt's Rolldown in the same tree) would vouch for a layout
58
- * the binding in use does not write. The owner must pin
59
- * `@oxc-project/types` exactly, and the copy it resolves must be that
60
- * version.
61
- */
62
- function bindingOwner(from = import.meta.url) {
63
- if (process.env.NAPI_RS_NATIVE_LIBRARY_PATH) return null;
64
- try {
65
- let dir = dirname(realpathSync(createRequire(from).resolve("vite/package.json")));
66
- let pkg = readPackage(dir);
67
- if (pkg.dependencies?.["@oxc-project/types"] === void 0) {
68
- if (pkg.dependencies?.rolldown === void 0) return null;
69
- dir = dirname(realpathSync(createRequire(join(dir, "package.json")).resolve("rolldown/package.json")));
70
- pkg = readPackage(dir);
71
- }
72
- const pinned = /^=?(\d+\.\d+\.\d+)$/.exec(pkg.dependencies?.["@oxc-project/types"] ?? "")?.[1];
73
- if (pinned === void 0) return null;
74
- const ownerRequire = createRequire(join(dir, "package.json"));
75
- if (ownerRequire("@oxc-project/types/package.json").version !== pinned) return null;
76
- const dirs = [dir];
77
- for (const name of Object.keys(pkg.optionalDependencies ?? {})) {
78
- if (!PLATFORM_PACKAGE.test(name)) continue;
79
- try {
80
- dirs.push(dirname(realpathSync(ownerRequire.resolve(`${name}/package.json`))));
81
- } catch {}
82
- }
83
- return {
84
- dirs,
85
- oxcVersion: pinned
86
- };
87
- } catch {
88
- return null;
89
- }
90
- }
91
- function readPackage(dir) {
92
- return JSON.parse(readFileSync(join(dir, "package.json"), "utf8"));
93
- }
94
- /**
95
- * The native binding of `owner` among the loaded native modules, if it has
96
- * raw transfer. `vite` exports no handle to it, but loading it put it in
97
- * the module cache; other bindings sit there too (another Rolldown, the
98
- * `oxc-parser` devDependency's) and are told apart by where they live, never
99
- * by load order or file name.
100
- */
101
- function ownBinding(owner, cache = createRequire(import.meta.url).cache) {
102
- for (const key in cache) {
103
- if (!key.endsWith(".node")) continue;
104
- let real;
105
- try {
106
- real = realpathSync(key);
107
- } catch {
108
- continue;
109
- }
110
- if (!owner.dirs.some((dir) => real.startsWith(dir + sep))) continue;
111
- const exports = cache[key]?.exports;
112
- if (typeof exports?.parseRawSync === "function" && typeof exports.getBufferOffset === "function" && typeof exports.rawTransferSupported === "function") return exports;
113
- }
114
- return null;
115
- }
116
- let parses = 0;
117
- let rawAfter = Infinity;
118
- /**
119
- * Starts raw transfer once {@link RAW_AFTER} (or `after`) modules more have
120
- * parsed with `parseSync`, without delaying any of them; `after` 0, or
121
- * `VI18N_RAW_PARSE=1`, starts it now. Idempotent.
122
- */
123
- function armRawParsing(after = 500) {
124
- if (rawReady !== null || process.env.VI18N_RAW_PARSE === "0") return;
125
- if (process.env.VI18N_RAW_PARSE === "1") after = 0;
126
- if (after > 0) rawAfter = Math.min(rawAfter, parses + after);
127
- else startRaw();
128
- }
129
- function startRaw() {
130
- rawReady ??= (async () => {
131
- if (process.env.VI18N_RAW_PARSE === "0") return false;
132
- try {
133
- const sync = loadParser(void 0);
134
- const owner = bindingOwner();
135
- const binding = owner === null ? null : ownBinding(owner);
136
- if (owner === null || binding === null) return false;
137
- const raw = await import("./raw-C4Y6vyGY.js");
138
- if (!raw.LAYOUT_VERSIONS.has(owner.oxcVersion)) return false;
139
- parseRaw = raw.createRawParser(binding, sync);
140
- return parseRaw !== null;
141
- } catch {
142
- return false;
143
- }
144
- })();
145
- return rawReady;
146
- }
147
- /**
148
- * The parser language for a module id, by the extension of its path (query
149
- * and `\0` prefix ignored). Framework files (`.vue`, `.svelte`, `.astro`,
150
- * `.mdx`) reach the post pass as plain JS.
151
- */
152
- function langFromId(id) {
153
- const query = id.indexOf("?");
154
- const end = query === -1 ? id.length : query;
155
- const dot = id.lastIndexOf(".", end);
156
- if (dot === -1 || id.lastIndexOf("/", end) > dot) return "js";
157
- switch (id.slice(dot + 1, end).toLowerCase()) {
158
- case "ts":
159
- case "mts":
160
- case "cts": return "ts";
161
- case "tsx": return "tsx";
162
- case "jsx": return "jsx";
163
- default: return "js";
164
- }
165
- }
166
- /**
167
- * Parses `code` as an ES module. Throws a `DiagnosticError`
168
- * (`extract-parse-error`) on the first syntax error: a partially recovered
169
- * tree could make the rewriter edit the wrong ranges.
170
- */
171
- function parseModule(code, lang, filename) {
172
- if (parseRaw === null && ++parses >= rawAfter) {
173
- rawAfter = Infinity;
174
- startRaw();
175
- }
176
- const result = (parseRaw ?? loadParser(filename))(filename ?? `module.${lang}`, code, {
177
- lang: lang === "js" ? "jsx" : lang,
178
- sourceType: "module",
179
- preserveParens: false
180
- });
181
- const first = result.errors[0];
182
- if (first !== void 0) {
183
- const offset = first.labels?.[0]?.start;
184
- throw diagnosticError({
185
- code: "extract-parse-error",
186
- severity: "error",
187
- message: `Cannot parse${filename === void 0 ? "" : ` ${filename}`}: ${first.message}`,
188
- ...filename === void 0 ? {} : { file: filename },
189
- ...offset === void 0 ? {} : lineColumn(code, offset)
190
- });
191
- }
192
- const parsed = {
193
- code,
194
- lang,
195
- program: result.program
196
- };
197
- if (result.comments !== void 0) parsed.comments = result.comments;
198
- return parsed;
199
- }
200
- //#endregion
201
- //#region src/core/extract/entities.ts
12
+ // src/core/extract/entities.ts
202
13
  /** HTML entities JSX text may spell; React and Solid decode them the same way. */
203
14
  const ENTITIES = {
204
15
  amp: "&",
@@ -229,19 +40,12 @@ function decodeEntities(text) {
229
40
  return Object.hasOwn(ENTITIES, name) ? ENTITIES[name] : whole;
230
41
  });
231
42
  }
232
- //#endregion
233
- //#region src/core/extract/macro.ts
43
+ // src/core/extract/macro.ts
234
44
  /** The local the expansion calls, imported once per expanded module. */
235
45
  const MACRO_RICH = "__vi18nRich";
236
46
  const IMPORT = `import { rich as ${MACRO_RICH} } from "@menapo/vi18n";`;
237
47
  /** The handlers' children parameter. */
238
48
  const CHILDREN = "__vi18nChildren";
239
- const TYPE_KEYS = /* @__PURE__ */ new Set([
240
- "typeAnnotation",
241
- "typeParameters",
242
- "typeArguments",
243
- "returnType"
244
- ]);
245
49
  /** Local names bound to `T` imported from a vi18n import source. */
246
50
  function macroNames(imports, sources) {
247
51
  const names = /* @__PURE__ */ new Set();
@@ -406,8 +210,14 @@ var Expander = class {
406
210
  this.children(children, out);
407
211
  out.message += `</${name}>`;
408
212
  }
213
+ /** Line breaks in `node`'s source. */
214
+ lineBreaks(node) {
215
+ return this.code.slice(node.start, node.end).split("\n").length - 1;
216
+ }
409
217
  tagName(name) {
410
- const text = name.type === "JSXIdentifier" ? name.name : name.type === "JSXMemberExpression" ? this.code.slice(name.start, name.end) : "";
218
+ let text = "";
219
+ if (name.type === "JSXIdentifier") text = name.name;
220
+ else if (name.type === "JSXMemberExpression") text = this.code.slice(name.start, name.end);
411
221
  if (!TAG_NAME.test(text)) throw new MacroError("extract-dynamic-message", `<T> cannot name a tag after <${this.code.slice(name.start, name.end)}>: wrap it in an element or component with a plain name`, name);
412
222
  return text;
413
223
  }
@@ -419,26 +229,20 @@ var Expander = class {
419
229
  */
420
230
  function expandMacros(parsed, sink, options) {
421
231
  const code = parsed.code;
422
- const program = parsed.program;
423
232
  const expander = new Expander(code);
424
233
  const diagnostics = [];
425
- let edited = false;
426
234
  const isMacro = (node) => {
427
235
  const name = node.openingElement.name;
428
236
  return name.type === "JSXIdentifier" && options.names.has(name.name);
429
237
  };
430
- const stack = [{
431
- node: program,
432
- child: false
433
- }];
434
- for (let next = stack.pop(); next !== void 0; next = stack.pop()) {
435
- const { node, child } = next;
238
+ let edited = false;
239
+ const stack = [parsed.program];
240
+ const inJsx = [false];
241
+ for (let node = stack.pop(); node !== void 0; node = stack.pop()) {
242
+ const child = inJsx.pop() === true;
436
243
  if (node.type === "JSXElement" && isMacro(node)) {
437
244
  try {
438
- const nested = findNested(node, isMacro);
439
- if (nested !== null) throw new MacroError("extract-dynamic-message", "<T> cannot contain another <T>", nested);
440
- let call = expander.expand(node);
441
- if (options.keepLines === true) call += "\n".repeat(code.slice(node.start, node.end).split("\n").length - 1);
245
+ const call = expandOne(expander, node, isMacro, options.keepLines === true);
442
246
  sink.overwrite(node.start, node.end, child ? `{${call}}` : `<>{${call}}</>`);
443
247
  edited = true;
444
248
  } catch (error) {
@@ -453,31 +257,50 @@ function expandMacros(parsed, sink, options) {
453
257
  }
454
258
  continue;
455
259
  }
456
- const jsx = node.type === "JSXElement" || node.type === "JSXFragment";
457
- for (const key in node) {
458
- if (key === "type" || key === "start" || key === "end" || TYPE_KEYS.has(key)) continue;
459
- const value = node[key];
460
- if (value === null || typeof value !== "object") continue;
461
- const isChildren = jsx && key === "children";
462
- if (Array.isArray(value)) for (let i = value.length - 1; i >= 0; i--) {
463
- const item = value[i];
464
- if (item !== null && typeof item?.type === "string") stack.push({
465
- node: item,
466
- child: isChildren
467
- });
468
- }
469
- else if (typeof value.type === "string") stack.push({
470
- node: value,
471
- child: false
472
- });
473
- }
260
+ pushChildren(node, stack, inJsx);
474
261
  }
475
- if (edited) sink.appendLeft(afterDirectives(program), IMPORT);
262
+ if (edited) insertImport(sink, parsed, IMPORT, false);
476
263
  return {
477
264
  edited,
478
265
  diagnostics
479
266
  };
480
267
  }
268
+ /** One `<T>` as its `rich()` call, padded with the newlines it replaced when lines are kept. */
269
+ function expandOne(expander, element, isMacro, keepLines) {
270
+ const nested = findNested(element, isMacro);
271
+ if (nested !== null) throw new MacroError("extract-dynamic-message", "<T> cannot contain another <T>", nested);
272
+ const call = expander.expand(element);
273
+ if (!keepLines) return call;
274
+ return call + "\n".repeat(expander.lineBreaks(element));
275
+ }
276
+ /**
277
+ * Pushes `node`'s children onto the walk's stacks: keys in order, each array
278
+ * reversed, the order the macro diagnostics have always been reported in.
279
+ * Only a JSX parent's `children` hold JSX children; its other keys hold its
280
+ * opening and closing tags.
281
+ */
282
+ function pushChildren(node, stack, inJsx) {
283
+ const jsx = node.type === "JSXElement" || node.type === "JSXFragment";
284
+ for (const key in node) {
285
+ if (key === "type" || key === "start" || key === "end" || TYPE_KEYS.has(key)) continue;
286
+ const value = node[key];
287
+ if (value === null || typeof value !== "object") continue;
288
+ if (!Array.isArray(value)) {
289
+ if (isNode(value)) {
290
+ stack.push(value);
291
+ inJsx.push(false);
292
+ }
293
+ continue;
294
+ }
295
+ const child = jsx && key === "children";
296
+ for (let i = value.length - 1; i >= 0; i--) {
297
+ const item = value[i];
298
+ if (!isNode(item)) continue;
299
+ stack.push(item);
300
+ inJsx.push(child);
301
+ }
302
+ }
303
+ }
481
304
  /** A `<T>` inside `element`'s children, at any depth. */
482
305
  function findNested(element, isMacro) {
483
306
  const stack = [...element.children];
@@ -487,23 +310,14 @@ function findNested(element, isMacro) {
487
310
  }
488
311
  return null;
489
312
  }
490
- /** Where an import may go: after `"use client"` and other directives. */
491
- function afterDirectives(program) {
492
- let at = 0;
493
- for (const statement of program.body) {
494
- if (statement.type !== "ExpressionStatement" || typeof statement.directive !== "string") break;
495
- at = statement.end;
496
- }
497
- return at;
498
- }
499
- //#endregion
500
- //#region src/core/extract/sfc-parse.ts
313
+ // src/core/extract/sfc-parse.ts
501
314
  /** Thrown inside a walk for a shape parse-only extraction does not cover. */
502
315
  var Unproven = class extends Error {};
503
316
  function unproven(reason) {
504
317
  throw new Unproven(reason);
505
318
  }
506
- function pick$1(module, name) {
319
+ /** A named export of a compiler loaded through `import()`, ESM or CommonJS. */
320
+ function pick(module, name) {
507
321
  return module[name] ?? module.default?.[name];
508
322
  }
509
323
  /**
@@ -528,330 +342,37 @@ function blank(code, ranges) {
528
342
  }
529
343
  /** Top-level binding names of a program (imports and declarations). */
530
344
  function topLevelNames(program, into) {
531
- const pattern = (node) => {
532
- if (node === null || node === void 0) return;
533
- switch (node.type) {
534
- case "Identifier":
535
- into.add(node.name);
536
- return;
537
- case "ObjectPattern":
538
- for (const property of node.properties) pattern(property.type === "RestElement" ? property.argument : property.value);
539
- return;
540
- case "ArrayPattern":
541
- for (const element of node.elements) pattern(element);
542
- return;
543
- case "AssignmentPattern":
544
- pattern(node.left);
545
- return;
546
- case "RestElement":
547
- pattern(node.argument);
548
- return;
549
- }
345
+ const add = (name) => {
346
+ into.add(name);
550
347
  };
551
348
  for (let statement of program.body) {
552
- if ((statement.type === "ExportNamedDeclaration" || statement.type === "ExportDefaultDeclaration") && statement.declaration !== null && statement.declaration !== void 0) statement = statement.declaration;
553
- switch (statement.type) {
554
- case "ImportDeclaration":
555
- for (const specifier of statement.specifiers) into.add(specifier.local.name);
556
- break;
557
- case "VariableDeclaration":
558
- for (const declarator of statement.declarations) pattern(declarator.id);
559
- break;
560
- case "FunctionDeclaration":
561
- case "ClassDeclaration":
562
- case "TSEnumDeclaration": if (statement.id !== null && statement.id !== void 0) into.add(statement.id.name);
563
- }
564
- }
565
- }
566
- /** `@vue/compiler-core` NodeTypes and ElementTypes of the raw template AST. */
567
- const ELEMENT = 1;
568
- const TEXT = 2;
569
- const COMMENT = 3;
570
- const INTERPOLATION = 5;
571
- const ATTRIBUTE = 6;
572
- const DIRECTIVE = 7;
573
- const COMPONENT = 1;
574
- /** The setup macros whose arguments Vue moves into the component options, at module level. */
575
- const VUE_MACROS = /* @__PURE__ */ new Set([
576
- "defineProps",
577
- "withDefaults",
578
- "defineEmits",
579
- "defineOptions",
580
- "defineModel"
581
- ]);
582
- /** Components Vue resolves before setup bindings (compiler-core `resolveComponentType`). */
583
- const VUE_BUILT_INS = /* @__PURE__ */ new Set([
584
- "component",
585
- "Component",
586
- "teleport",
587
- "Teleport",
588
- "suspense",
589
- "Suspense",
590
- "keep-alive",
591
- "KeepAlive",
592
- "base-transition",
593
- "BaseTransition",
594
- "transition",
595
- "Transition",
596
- "transition-group",
597
- "TransitionGroup"
598
- ]);
599
- /** `v-on` values Vue passes as they are instead of wrapping them in `$event => (…)`. */
600
- const VUE_FN_EXPRESSION = /^\s*(?:async\s*)?(?:\([^)]*?\)|[\w$]+)\s*(?::[^=]+)?=>|^\s*(?:async\s+)?function(?:\s+[\w$]+)?\s*\(/;
601
- /** `v-for`'s `alias in source`, as compiler-core splits it. */
602
- const VUE_FOR = /([\s\S]*?)\s+(?:in|of)\s+(\S[\s\S]*)/;
603
- const camelize = (name) => name.replace(/-(\w)/g, (_all, c) => c.toUpperCase());
604
- const capitalize = (name) => name.charAt(0).toUpperCase() + name.slice(1);
605
- function modifierNames(prop) {
606
- return (prop.modifiers ?? []).map((m) => typeof m === "string" ? m : m.content);
607
- }
608
- var VueTemplate = class {
609
- out = [];
610
- /**
611
- * `bindings` holds the top-level names of `<script setup>` mode, where a
612
- * component tag naming one is that binding (`_createVNode(T, …)`); null
613
- * outside it, where Vue resolves components by name at runtime.
614
- */
615
- bindings;
616
- constructor(bindings) {
617
- this.bindings = bindings;
618
- }
619
- children(nodes) {
620
- for (const node of nodes ?? []) this.node(node);
621
- }
622
- node(node) {
623
- switch (node.type) {
624
- case TEXT:
625
- case COMMENT: return;
626
- case INTERPOLATION:
627
- this.out.push(expr(node.content.content) + ";");
628
- return;
629
- case ELEMENT:
630
- this.element(node);
631
- return;
632
- default: unproven(`vue-node-${node.type}`);
633
- }
634
- }
635
- /** The binding a component tag resolves to in `<script setup>` mode, as compiler-core finds it. */
636
- componentBinding(tag) {
637
- if (this.bindings === null || VUE_BUILT_INS.has(tag)) return null;
638
- for (const name of [
639
- tag,
640
- camelize(tag),
641
- capitalize(camelize(tag))
642
- ]) if (this.bindings.has(name)) return name;
643
- return null;
644
- }
645
- element(node) {
646
- const props = node.props ?? [];
647
- let closers = 0;
648
- for (const prop of props) if (prop.type === DIRECTIVE && (prop.name === "if" || prop.name === "else-if")) {
649
- if (prop.exp !== void 0) this.out.push(expr(prop.exp.content) + ";");
650
- }
651
- const loop = props.find((p) => p.type === DIRECTIVE && p.name === "for");
652
- if (loop !== void 0) {
653
- const match = VUE_FOR.exec(loop.exp?.content ?? "");
654
- if (match === null) unproven("vue-for");
655
- const alias = match[1].trim().replace(/^\(|\)$/g, "");
656
- this.out.push(expr(match[2].trim()) + ";");
657
- this.out.push(`((${alias}) => {`);
658
- closers++;
659
- }
660
- const component = node.tagType === COMPONENT ? this.componentBinding(node.tag) : null;
661
- if (this.bindings === null && node.tagType === COMPONENT && hasProp(props, "message")) unproven("vue-options-component");
662
- const entries = [];
663
- const statements = [];
664
- const merged = [];
665
- let slot;
666
- for (const prop of props) {
667
- if (prop.type === ATTRIBUTE) {
668
- if (component !== null) entries.push(`${JSON.stringify(prop.name)}: ${JSON.stringify(prop.value?.content ?? "")}`);
669
- continue;
670
- }
671
- if (prop.type !== DIRECTIVE) unproven(`vue-prop-${prop.type}`);
672
- const exp = prop.exp?.content;
673
- const arg = prop.arg;
674
- const dynamic = arg !== void 0 && arg.isStatic === false;
675
- if (dynamic) statements.push(expr(arg.content) + ";");
676
- switch (prop.name) {
677
- case "if":
678
- case "else-if":
679
- case "else":
680
- case "for": break;
681
- case "slot":
682
- slot = prop;
683
- break;
684
- case "bind": {
685
- if (arg === void 0) {
686
- if (exp !== void 0) merged.push(expr(exp));
687
- break;
688
- }
689
- if (dynamic) {
690
- merged.push(`{ [${expr(arg.content)}]: ${exp === void 0 ? "0" : expr(exp)} }`);
691
- break;
692
- }
693
- const modifiers = modifierNames(prop);
694
- let key = modifiers.includes("camel") ? camelize(arg.content) : arg.content;
695
- if (modifiers.includes("prop")) key = "." + key;
696
- else if (modifiers.includes("attr")) key = "^" + key;
697
- entries.push(`${JSON.stringify(key)}: ${exp === void 0 ? camelize(arg.content) : expr(exp)}`);
698
- break;
699
- }
700
- case "on": {
701
- const handler = exp === void 0 ? "null" : VUE_FN_EXPRESSION.test(exp) || /^\s*[\w$]+(?:\s*\.\s*[\w$]+)*\s*$/.test(exp) ? expr(exp) : `($event) => {\n${exp}\n}`;
702
- if (arg === void 0 || dynamic) merged.push(handler);
703
- else entries.push(`${JSON.stringify("on:" + arg.content)}: ${handler}`);
704
- break;
705
- }
706
- case "model":
707
- if (exp !== void 0) {
708
- const key = arg === void 0 || dynamic ? "modelValue" : arg.content;
709
- if (dynamic) merged.push(expr(exp));
710
- else entries.push(`${JSON.stringify(key)}: ${expr(exp)}`);
711
- }
712
- break;
713
- case "html":
714
- if (exp !== void 0) entries.push(`innerHTML: ${expr(exp)}`);
715
- break;
716
- case "text":
717
- if (exp !== void 0) entries.push(`textContent: ${expr(exp)}`);
718
- break;
719
- default: if (exp !== void 0) statements.push(expr(exp) + ";");
720
- }
721
- }
722
- let props_ = `{${entries.length === 0 ? "" : "\n" + entries.join(",\n") + "\n"}}`;
723
- if (merged.length > 0) props_ = `__vi18n_merge(${props_}, ${merged.join(", ")})`;
724
- this.out.push(component === null ? `__vi18n_node(${props_});` : `__vi18n_vnode(${component}, ${props_});`);
725
- for (const statement of statements) this.out.push(statement);
726
- if (slot?.exp !== void 0) {
727
- this.out.push(`((${slot.exp.content}) => {`);
728
- closers++;
729
- }
730
- this.children(node.children);
731
- for (let i = 0; i < closers; i++) this.out.push("});");
732
- }
733
- };
734
- function hasProp(props, name) {
735
- return props.some((p) => p.type === ATTRIBUTE ? p.name === name : p.arg !== void 0 && (p.arg.isStatic === false || camelize(p.arg.content) === name));
736
- }
737
- function vueLang(lang) {
738
- return lang === "ts" || lang === "tsx" || lang === "jsx" ? lang : "js";
739
- }
740
- /**
741
- * Script setup statements that Vue's compileScript moves: imports to module
742
- * scope, and the arguments of the options macros into the component options
743
- * (module scope too, so a call directly in them is at module scope there).
744
- */
745
- function setupLayout(setup, lang, file) {
746
- let program;
747
- try {
748
- program = parseModule(setup, lang, file).program;
749
- } catch {
750
- unproven("script-syntax");
751
- }
752
- const imports = [];
753
- const hoisted = [];
754
- const blanks = [];
755
- const macro = (node) => {
756
- if (node === null || node === void 0) return;
757
- let call = node;
758
- while (call.type === "TSAsExpression" || call.type === "TSSatisfiesExpression" || call.type === "TSNonNullExpression") call = call.expression;
759
- if (call.type !== "CallExpression") return;
760
- const callee = call.callee;
761
- if (callee.type !== "Identifier" || !VUE_MACROS.has(callee.name)) return;
762
- const args = call.arguments;
763
- if (callee.name === "withDefaults") macro(args[0]);
764
- const moved = callee.name === "withDefaults" ? args.slice(1) : args;
765
- if (moved.length === 0) return;
766
- const start = moved[0].start;
767
- const end = moved[moved.length - 1].end;
768
- hoisted.push(expr(setup.slice(start, end)) + ";");
769
- blanks.push([start, end]);
770
- };
771
- for (const statement of program.body) switch (statement.type) {
772
- case "ImportDeclaration":
773
- imports.push(setup.slice(statement.start, statement.end));
774
- blanks.push([statement.start, statement.end]);
775
- break;
776
- case "ExportNamedDeclaration":
777
- case "ExportDefaultDeclaration":
778
- case "ExportAllDeclaration":
779
- unproven("vue-setup-export");
780
- break;
781
- case "ExpressionStatement":
782
- macro(statement.expression);
783
- break;
784
- case "VariableDeclaration": for (const declarator of statement.declarations) {
785
- const init = declarator.init;
786
- const id = declarator.id;
787
- if (init !== null && id.type === "ObjectPattern" && /\b(?:defineProps|withDefaults)\s*[<(]/.test(setup.slice(init.start, init.end)) && id.properties.some((p) => p.value?.type === "AssignmentPattern")) unproven("vue-props-destructure-default");
788
- macro(init);
789
- }
790
- }
791
- return {
792
- imports,
793
- hoisted,
794
- body: blank(setup, blanks),
795
- program
796
- };
797
- }
798
- /**
799
- * The module parse-only extraction scans for a `.vue` file: `<script>` as it
800
- * is, `<script setup>` imports and macro arguments at module level, its
801
- * statements inside a setup function that ends with the template's
802
- * expressions (the inline template of a production build), or the template
803
- * in a render function of its own.
804
- */
805
- function vueParseOnly(compiler, file, code) {
806
- const parse = pick$1(compiler, "parse");
807
- if (parse === void 0) return { fallback: "vue-api" };
808
- try {
809
- const { descriptor, errors } = parse(code, {
810
- filename: file,
811
- sourceMap: false,
812
- templateParseOptions: {}
813
- });
814
- if (errors.length > 0) return { fallback: "vue-parse-error" };
815
- const { script, scriptSetup, template } = descriptor;
816
- if (script?.src !== void 0 || scriptSetup?.src !== void 0 || template?.src !== void 0) return { fallback: "vue-src" };
817
- if (template !== null && template.lang !== void 0 && template.lang !== "html") return { fallback: "vue-template-lang" };
818
- if (template !== null && template.ast === void 0) return { fallback: "vue-api" };
819
- if (template?.content.includes("vi18n-") === true) return { fallback: "template-marker" };
820
- if (script !== null && scriptSetup !== null && vueLang(script.lang) !== vueLang(scriptSetup.lang)) return { fallback: "vue-script-lang" };
821
- const lang = vueLang(scriptSetup?.lang ?? script?.lang);
822
- const parts = [];
823
- if (script !== null) parts.push(script.content);
824
- if (scriptSetup === null) {
825
- const walk = new VueTemplate(null);
826
- walk.children(template?.ast?.children);
827
- parts.push("function __vi18n_render() {", ...walk.out, "}");
828
- return {
829
- code: parts.join("\n"),
830
- lang
831
- };
832
- }
833
- const layout = setupLayout(scriptSetup.content, lang, file);
834
- const bindings = /* @__PURE__ */ new Set();
835
- topLevelNames(layout.program, bindings);
836
- if (script !== null) try {
837
- topLevelNames(parseModule(script.content, lang, file).program, bindings);
838
- } catch {
839
- return { fallback: "script-syntax" };
349
+ if ((statement.type === "ExportNamedDeclaration" || statement.type === "ExportDefaultDeclaration") && statement.declaration !== null && statement.declaration !== void 0) statement = statement.declaration;
350
+ switch (statement.type) {
351
+ case "ImportDeclaration":
352
+ for (const specifier of statement.specifiers) into.add(specifier.local.name);
353
+ break;
354
+ case "VariableDeclaration":
355
+ for (const declarator of statement.declarations) forEachBindingName(declarator.id, add);
356
+ break;
357
+ case "FunctionDeclaration":
358
+ case "ClassDeclaration":
359
+ case "TSEnumDeclaration": if (statement.id !== null && statement.id !== void 0) into.add(statement.id.name);
840
360
  }
841
- const walk = new VueTemplate(bindings);
842
- walk.children(template?.ast?.children);
843
- parts.push(...layout.imports, ...layout.hoisted);
844
- parts.push("async function __vi18n_setup() {", layout.body);
845
- parts.push("function __vi18n_render() {", ...walk.out, "}", "}");
846
- return {
847
- code: parts.join("\n"),
848
- lang
849
- };
850
- } catch (error) {
851
- if (error instanceof Unproven) return { fallback: error.message };
852
- return { fallback: "vue-parse-error" };
853
361
  }
854
362
  }
363
+ /** A script block's `lang` as the parser's language. */
364
+ function scriptLang(lang) {
365
+ return lang === "ts" || lang === "tsx" || lang === "jsx" ? lang : "js";
366
+ }
367
+ /**
368
+ * A component's props object from its `entries` (`"key": value`), merged
369
+ * with the spreads of `merged` the way the compiled component merges them.
370
+ */
371
+ function propsObject(entries, merged) {
372
+ const object = `{${entries.length === 0 ? "" : "\n" + entries.join(",\n") + "\n"}}`;
373
+ return merged.length === 0 ? object : `__vi18n_merge(${object}, ${merged.join(", ")})`;
374
+ }
375
+ // src/core/extract/sfc-svelte.ts
855
376
  /** Elements whose attributes and children are plain template code. */
856
377
  const SVELTE_ELEMENTS = /* @__PURE__ */ new Set([
857
378
  "RegularElement",
@@ -905,6 +426,11 @@ function readsStore(root) {
905
426
  function templateText(text) {
906
427
  return text.replace(/[\\`]|\$\{/g, (c) => "\\" + c);
907
428
  }
429
+ /** An attribute value's text and expression parts: Svelte gives one part bare, several as a list. */
430
+ function valueParts(attribute) {
431
+ const value = attribute.value;
432
+ return Array.isArray(value) ? value : [value];
433
+ }
908
434
  var SvelteTemplate = class {
909
435
  out = [];
910
436
  code;
@@ -997,18 +523,11 @@ var SvelteTemplate = class {
997
523
  /** An attribute's expressions, beside the element. */
998
524
  attribute(attribute) {
999
525
  switch (attribute.type) {
1000
- case "Attribute": {
1001
- const value = attribute.value;
1002
- if (value === true) return;
1003
- for (const part of Array.isArray(value) ? value : [value]) if (part.type === "ExpressionTag") this.out.push(this.expression(part.expression) + ";");
1004
- return;
1005
- }
1006
- case "StyleDirective": {
1007
- const value = attribute.value;
1008
- if (value === true) return;
1009
- for (const part of Array.isArray(value) ? value : [value]) if (part.type === "ExpressionTag") this.out.push(this.expression(part.expression) + ";");
526
+ case "Attribute":
527
+ case "StyleDirective":
528
+ if (attribute.value === true) return;
529
+ for (const part of valueParts(attribute)) if (part.type === "ExpressionTag") this.out.push(this.expression(part.expression) + ";");
1010
530
  return;
1011
- }
1012
531
  case "SpreadAttribute":
1013
532
  case "OnDirective":
1014
533
  case "BindDirective":
@@ -1022,6 +541,14 @@ var SvelteTemplate = class {
1022
541
  default: unproven(`svelte-attribute-${attribute.type}`);
1023
542
  }
1024
543
  }
544
+ /** A component attribute's value as the compiled call passes it: `true`, the expression, a string or a template literal. */
545
+ attributeValue(attribute) {
546
+ if (attribute.value === true) return "true";
547
+ const parts = valueParts(attribute);
548
+ if (parts.length === 1 && parts[0]?.type === "ExpressionTag") return this.expression(parts[0].expression);
549
+ if (parts.every((part) => part.type === "Text")) return JSON.stringify(parts.map((part) => part.data).join(""));
550
+ return "`" + parts.map((part) => part.type === "Text" ? templateText(part.data) : "${" + this.slice(part.expression) + "}").join("") + "`";
551
+ }
1025
552
  /** `T(anchor, { props })`, as Svelte calls a component it imports. */
1026
553
  component(node) {
1027
554
  const entries = [];
@@ -1030,19 +557,9 @@ var SvelteTemplate = class {
1030
557
  for (const attribute of node.attributes) {
1031
558
  const name = attribute.name;
1032
559
  switch (attribute.type) {
1033
- case "Attribute": {
1034
- const value = attribute.value;
1035
- let text;
1036
- if (value === true) text = "true";
1037
- else {
1038
- const parts = Array.isArray(value) ? value : [value];
1039
- if (parts.length === 1 && parts[0]?.type === "ExpressionTag") text = this.expression(parts[0].expression);
1040
- else if (parts.every((part) => part.type === "Text")) text = JSON.stringify(parts.map((part) => part.data).join(""));
1041
- else text = "`" + parts.map((part) => part.type === "Text" ? templateText(part.data) : "${" + this.slice(part.expression) + "}").join("") + "`";
1042
- }
1043
- entries.push(`${JSON.stringify(name)}: ${text}`);
560
+ case "Attribute":
561
+ entries.push(`${JSON.stringify(name)}: ${this.attributeValue(attribute)}`);
1044
562
  break;
1045
- }
1046
563
  case "BindDirective":
1047
564
  if (name === "this") statements.push(this.expression(attribute.expression) + ";");
1048
565
  else entries.push(`${JSON.stringify(name)}: ${this.expression(attribute.expression)}`);
@@ -1057,8 +574,7 @@ var SvelteTemplate = class {
1057
574
  default: unproven(`svelte-attribute-${attribute.type}`);
1058
575
  }
1059
576
  }
1060
- let props = `{${entries.length === 0 ? "" : "\n" + entries.join(",\n") + "\n"}}`;
1061
- if (merged.length > 0) props = `__vi18n_merge(${props}, ${merged.join(", ")})`;
577
+ const props = propsObject(entries, merged);
1062
578
  const name = node.name;
1063
579
  if (!/^[\p{L}_$][\p{L}\p{N}_$]*(?:\.[\p{L}_$][\p{L}\p{N}_$]*)*$/u.test(name)) unproven("svelte-component-name");
1064
580
  this.out.push(`${name}(null, ${props});`);
@@ -1115,8 +631,8 @@ function svelteScript(code, script, hoistImports) {
1115
631
  * with the template's expressions.
1116
632
  */
1117
633
  function svelteParseOnly(compiler, file, code) {
1118
- const parse = pick$1(compiler, "parse");
1119
- const version = pick$1(compiler, "VERSION") ?? "5";
634
+ const parse = pick(compiler, "parse");
635
+ const version = pick(compiler, "VERSION") ?? "5";
1120
636
  if (parse === void 0 || Number.parseInt(version, 10) < 5) return { fallback: "svelte-api" };
1121
637
  try {
1122
638
  let root;
@@ -1153,8 +669,334 @@ function svelteParseOnly(compiler, file, code) {
1153
669
  return { fallback: "svelte-parse-error" };
1154
670
  }
1155
671
  }
1156
- //#endregion
1157
- //#region src/core/extract/sfc.ts
672
+ // src/core/extract/sfc-vue.ts
673
+ /** `@vue/compiler-core` NodeTypes and ElementTypes of the raw template AST. */
674
+ const ELEMENT = 1;
675
+ const TEXT = 2;
676
+ const COMMENT = 3;
677
+ const INTERPOLATION = 5;
678
+ const ATTRIBUTE = 6;
679
+ const DIRECTIVE = 7;
680
+ const COMPONENT = 1;
681
+ /** The setup macros whose arguments Vue moves into the component options, at module level. */
682
+ const VUE_MACROS = /* @__PURE__ */ new Set([
683
+ "defineProps",
684
+ "withDefaults",
685
+ "defineEmits",
686
+ "defineOptions",
687
+ "defineModel"
688
+ ]);
689
+ /** Components Vue resolves before setup bindings (compiler-core `resolveComponentType`). */
690
+ const VUE_BUILT_INS = /* @__PURE__ */ new Set([
691
+ "component",
692
+ "Component",
693
+ "teleport",
694
+ "Teleport",
695
+ "suspense",
696
+ "Suspense",
697
+ "keep-alive",
698
+ "KeepAlive",
699
+ "base-transition",
700
+ "BaseTransition",
701
+ "transition",
702
+ "Transition",
703
+ "transition-group",
704
+ "TransitionGroup"
705
+ ]);
706
+ /** `v-on` values Vue passes as they are instead of wrapping them in `$event => (…)`. */
707
+ const VUE_FN_EXPRESSION = /^\s*(?:async\s*)?(?:\([^)]*?\)|[\w$]+)\s*(?::[^=]+)?=>|^\s*(?:async\s+)?function(?:\s+[\w$]+)?\s*\(/;
708
+ /** `v-for`'s `alias in source`, as compiler-core splits it. */
709
+ const VUE_FOR = /([\s\S]*?)\s+(?:in|of)\s+(\S[\s\S]*)/;
710
+ const camelize = (name) => name.replace(/-(\w)/g, (_all, c) => c.toUpperCase());
711
+ const capitalize = (name) => name.charAt(0).toUpperCase() + name.slice(1);
712
+ function modifierNames(prop) {
713
+ return (prop.modifiers ?? []).map((m) => typeof m === "string" ? m : m.content);
714
+ }
715
+ var VueTemplate = class {
716
+ out = [];
717
+ /**
718
+ * `bindings` holds the top-level names of `<script setup>` mode, where a
719
+ * component tag naming one is that binding (`_createVNode(T, …)`); null
720
+ * outside it, where Vue resolves components by name at runtime.
721
+ */
722
+ bindings;
723
+ constructor(bindings) {
724
+ this.bindings = bindings;
725
+ }
726
+ children(nodes) {
727
+ for (const node of nodes ?? []) this.node(node);
728
+ }
729
+ node(node) {
730
+ switch (node.type) {
731
+ case TEXT:
732
+ case COMMENT: return;
733
+ case INTERPOLATION:
734
+ this.out.push(expr(node.content.content) + ";");
735
+ return;
736
+ case ELEMENT:
737
+ this.element(node);
738
+ return;
739
+ default: unproven(`vue-node-${node.type}`);
740
+ }
741
+ }
742
+ /** The binding a component tag resolves to in `<script setup>` mode, as compiler-core finds it. */
743
+ componentBinding(tag) {
744
+ if (this.bindings === null || VUE_BUILT_INS.has(tag)) return null;
745
+ for (const name of [
746
+ tag,
747
+ camelize(tag),
748
+ capitalize(camelize(tag))
749
+ ]) if (this.bindings.has(name)) return name;
750
+ return null;
751
+ }
752
+ element(node) {
753
+ const props = node.props ?? [];
754
+ for (const prop of props) if (prop.type === DIRECTIVE && (prop.name === "if" || prop.name === "else-if")) {
755
+ if (prop.exp !== void 0) this.out.push(expr(prop.exp.content) + ";");
756
+ }
757
+ let closers = this.loop(props);
758
+ const component = node.tagType === COMPONENT ? this.componentBinding(node.tag) : null;
759
+ if (this.bindings === null && node.tagType === COMPONENT && hasProp(props, "message")) unproven("vue-options-component");
760
+ const read = new VueProps(component !== null);
761
+ for (const prop of props) read.prop(prop);
762
+ const object = propsObject(read.entries, read.merged);
763
+ this.out.push(component === null ? `__vi18n_node(${object});` : `__vi18n_vnode(${component}, ${object});`);
764
+ for (const statement of read.statements) this.out.push(statement);
765
+ if (read.slot?.exp !== void 0) {
766
+ this.out.push(`((${read.slot.exp.content}) => {`);
767
+ closers++;
768
+ }
769
+ this.children(node.children);
770
+ for (let i = 0; i < closers; i++) this.out.push("});");
771
+ }
772
+ /** A `v-for`'s source, and the arrow its body runs in: the closers it leaves open. */
773
+ loop(props) {
774
+ const loop = props.find((p) => p.type === DIRECTIVE && p.name === "for");
775
+ if (loop === void 0) return 0;
776
+ const match = VUE_FOR.exec(loop.exp?.content ?? "");
777
+ if (match === null) unproven("vue-for");
778
+ const alias = match[1].trim().replace(/^\(|\)$/g, "");
779
+ this.out.push(expr(match[2].trim()) + ";");
780
+ this.out.push(`((${alias}) => {`);
781
+ return 1;
782
+ }
783
+ };
784
+ /**
785
+ * An element's props as the compiled render function passes them: named
786
+ * `entries`, spread or dynamic `merged` objects, and the `statements` Vue
787
+ * evaluates beside the node (dynamic arguments, `v-show`, custom directives).
788
+ */
789
+ var VueProps = class {
790
+ entries = [];
791
+ merged = [];
792
+ statements = [];
793
+ slot;
794
+ /** Static attributes are props only on a component bound in `<script setup>`. */
795
+ attributes;
796
+ constructor(attributes) {
797
+ this.attributes = attributes;
798
+ }
799
+ prop(prop) {
800
+ if (prop.type === ATTRIBUTE) {
801
+ if (this.attributes) this.entries.push(`${JSON.stringify(prop.name)}: ${JSON.stringify(prop.value?.content ?? "")}`);
802
+ return;
803
+ }
804
+ if (prop.type !== DIRECTIVE) unproven(`vue-prop-${prop.type}`);
805
+ const exp = prop.exp?.content;
806
+ const arg = prop.arg;
807
+ const dynamic = arg !== void 0 && arg.isStatic === false;
808
+ if (dynamic) this.statements.push(expr(arg.content) + ";");
809
+ switch (prop.name) {
810
+ case "if":
811
+ case "else-if":
812
+ case "else":
813
+ case "for": return;
814
+ case "slot":
815
+ this.slot = prop;
816
+ return;
817
+ case "bind":
818
+ this.bind(prop, exp, dynamic);
819
+ return;
820
+ case "on":
821
+ this.on(arg, exp, dynamic);
822
+ return;
823
+ case "model":
824
+ this.model(arg, exp, dynamic);
825
+ return;
826
+ case "html":
827
+ if (exp !== void 0) this.entries.push(`innerHTML: ${expr(exp)}`);
828
+ return;
829
+ case "text":
830
+ if (exp !== void 0) this.entries.push(`textContent: ${expr(exp)}`);
831
+ return;
832
+ default: if (exp !== void 0) this.statements.push(expr(exp) + ";");
833
+ }
834
+ }
835
+ bind(prop, exp, dynamic) {
836
+ const arg = prop.arg;
837
+ if (arg === void 0) {
838
+ if (exp !== void 0) this.merged.push(expr(exp));
839
+ return;
840
+ }
841
+ if (dynamic) {
842
+ this.merged.push(`{ [${expr(arg.content)}]: ${exp === void 0 ? "0" : expr(exp)} }`);
843
+ return;
844
+ }
845
+ const modifiers = modifierNames(prop);
846
+ let key = modifiers.includes("camel") ? camelize(arg.content) : arg.content;
847
+ if (modifiers.includes("prop")) key = "." + key;
848
+ else if (modifiers.includes("attr")) key = "^" + key;
849
+ this.entries.push(`${JSON.stringify(key)}: ${exp === void 0 ? camelize(arg.content) : expr(exp)}`);
850
+ }
851
+ on(arg, exp, dynamic) {
852
+ const handler = vueHandler(exp);
853
+ if (arg === void 0 || dynamic) this.merged.push(handler);
854
+ else this.entries.push(`${JSON.stringify("on:" + arg.content)}: ${handler}`);
855
+ }
856
+ model(arg, exp, dynamic) {
857
+ if (exp === void 0) return;
858
+ if (dynamic) {
859
+ this.merged.push(expr(exp));
860
+ return;
861
+ }
862
+ this.entries.push(`${JSON.stringify(arg === void 0 ? "modelValue" : arg.content)}: ${expr(exp)}`);
863
+ }
864
+ };
865
+ /** A `v-on` value as Vue compiles it: a function or member path as it is, a statement inside `$event => {…}`. */
866
+ function vueHandler(exp) {
867
+ if (exp === void 0) return "null";
868
+ if (VUE_FN_EXPRESSION.test(exp) || /^\s*[\w$]+(?:\s*\.\s*[\w$]+)*\s*$/.test(exp)) return expr(exp);
869
+ return `($event) => {\n${exp}\n}`;
870
+ }
871
+ function hasProp(props, name) {
872
+ return props.some((p) => p.type === ATTRIBUTE ? p.name === name : p.arg !== void 0 && (p.arg.isStatic === false || camelize(p.arg.content) === name));
873
+ }
874
+ /**
875
+ * Script setup statements that Vue's compileScript moves: imports to module
876
+ * scope, and the arguments of the options macros into the component options
877
+ * (module scope too, so a call directly in them is at module scope there).
878
+ */
879
+ function setupLayout(setup, lang, file) {
880
+ let program;
881
+ try {
882
+ program = parseModule(setup, lang, file).program;
883
+ } catch {
884
+ unproven("script-syntax");
885
+ }
886
+ const imports = [];
887
+ const hoisted = [];
888
+ const blanks = [];
889
+ const macro = (node) => {
890
+ if (node === null || node === void 0) return;
891
+ let call = node;
892
+ while (call.type === "TSAsExpression" || call.type === "TSSatisfiesExpression" || call.type === "TSNonNullExpression") call = call.expression;
893
+ if (call.type !== "CallExpression") return;
894
+ const callee = call.callee;
895
+ if (callee.type !== "Identifier" || !VUE_MACROS.has(callee.name)) return;
896
+ const args = call.arguments;
897
+ if (callee.name === "withDefaults") macro(args[0]);
898
+ const moved = callee.name === "withDefaults" ? args.slice(1) : args;
899
+ if (moved.length === 0) return;
900
+ const start = moved[0].start;
901
+ const end = moved[moved.length - 1].end;
902
+ hoisted.push(expr(setup.slice(start, end)) + ";");
903
+ blanks.push([start, end]);
904
+ };
905
+ for (const statement of program.body) switch (statement.type) {
906
+ case "ImportDeclaration":
907
+ imports.push(setup.slice(statement.start, statement.end));
908
+ blanks.push([statement.start, statement.end]);
909
+ break;
910
+ case "ExportNamedDeclaration":
911
+ case "ExportDefaultDeclaration":
912
+ case "ExportAllDeclaration":
913
+ unproven("vue-setup-export");
914
+ break;
915
+ case "ExpressionStatement":
916
+ macro(statement.expression);
917
+ break;
918
+ case "VariableDeclaration": for (const declarator of statement.declarations) {
919
+ const init = declarator.init;
920
+ const id = declarator.id;
921
+ if (init !== null && id.type === "ObjectPattern" && /\b(?:defineProps|withDefaults)\s*[<(]/.test(setup.slice(init.start, init.end)) && id.properties.some((p) => p.value?.type === "AssignmentPattern")) unproven("vue-props-destructure-default");
922
+ macro(init);
923
+ }
924
+ }
925
+ return {
926
+ imports,
927
+ hoisted,
928
+ body: blank(setup, blanks),
929
+ program
930
+ };
931
+ }
932
+ /**
933
+ * The module parse-only extraction scans for a `.vue` file: `<script>` as it
934
+ * is, `<script setup>` imports and macro arguments at module level, its
935
+ * statements inside a setup function that ends with the template's
936
+ * expressions (the inline template of a production build), or the template
937
+ * in a render function of its own.
938
+ */
939
+ function vueParseOnly(compiler, file, code) {
940
+ const parse = pick(compiler, "parse");
941
+ if (parse === void 0) return { fallback: "vue-api" };
942
+ try {
943
+ const { descriptor, errors } = parse(code, {
944
+ filename: file,
945
+ sourceMap: false,
946
+ templateParseOptions: {}
947
+ });
948
+ if (errors.length > 0) return { fallback: "vue-parse-error" };
949
+ const fallback = vueFallback(descriptor);
950
+ if (fallback !== null) return { fallback };
951
+ return vueModule(descriptor, file);
952
+ } catch (error) {
953
+ if (error instanceof Unproven) return { fallback: error.message };
954
+ return { fallback: "vue-parse-error" };
955
+ }
956
+ }
957
+ /** Why a descriptor's layout cannot be proven equal to compiling it; null when it can. */
958
+ function vueFallback({ script, scriptSetup, template }) {
959
+ if (script?.src !== void 0 || scriptSetup?.src !== void 0 || template?.src !== void 0) return "vue-src";
960
+ if (template !== null) {
961
+ if (template.lang !== void 0 && template.lang !== "html") return "vue-template-lang";
962
+ if (template.ast === void 0) return "vue-api";
963
+ if (template.content.includes("vi18n-")) return "template-marker";
964
+ }
965
+ if (script !== null && scriptSetup !== null && scriptLang(script.lang) !== scriptLang(scriptSetup.lang)) return "vue-script-lang";
966
+ return null;
967
+ }
968
+ function vueModule({ script, scriptSetup, template }, file) {
969
+ const lang = scriptLang(scriptSetup?.lang ?? script?.lang);
970
+ const parts = [];
971
+ if (script !== null) parts.push(script.content);
972
+ if (scriptSetup === null) {
973
+ const walk = new VueTemplate(null);
974
+ walk.children(template?.ast?.children);
975
+ parts.push("function __vi18n_render() {", ...walk.out, "}");
976
+ return {
977
+ code: parts.join("\n"),
978
+ lang
979
+ };
980
+ }
981
+ const layout = setupLayout(scriptSetup.content, lang, file);
982
+ const bindings = /* @__PURE__ */ new Set();
983
+ topLevelNames(layout.program, bindings);
984
+ if (script !== null) try {
985
+ topLevelNames(parseModule(script.content, lang, file).program, bindings);
986
+ } catch {
987
+ return { fallback: "script-syntax" };
988
+ }
989
+ const walk = new VueTemplate(bindings);
990
+ walk.children(template?.ast?.children);
991
+ parts.push(...layout.imports, ...layout.hoisted);
992
+ parts.push("async function __vi18n_setup() {", layout.body);
993
+ parts.push("function __vi18n_render() {", ...walk.out, "}", "}");
994
+ return {
995
+ code: parts.join("\n"),
996
+ lang
997
+ };
998
+ }
999
+ // src/core/extract/sfc.ts
1158
1000
  /**
1159
1001
  * Framework files for the CLI scan (INTERNALS §2.5.6): `.vue`, `.svelte`,
1160
1002
  * `.astro` and `.mdx` are compiled with the project's own compilers, so the
@@ -1245,12 +1087,14 @@ async function loadCompiler(kind, file) {
1245
1087
  }
1246
1088
  return module;
1247
1089
  }
1248
- /** A named export of a compiler loaded through `import()`, ESM or CommonJS. */
1249
- function pick(module, name) {
1250
- return module[name] ?? module.default?.[name];
1090
+ /** A compiler's error as text: its own string, or the `message` of an error object. */
1091
+ function errorText(detail) {
1092
+ if (typeof detail === "string") return detail;
1093
+ if (typeof detail === "object" && detail !== null && "message" in detail) return String(detail.message);
1094
+ return String(detail);
1251
1095
  }
1252
1096
  function compileError(file, detail) {
1253
- const message = typeof detail === "string" ? detail : detail instanceof Error || typeof detail === "object" && detail !== null && "message" in detail ? String(detail.message) : String(detail);
1097
+ const message = errorText(detail);
1254
1098
  return diagnosticError({
1255
1099
  code: "extract-parse-error",
1256
1100
  severity: "error",
@@ -1266,9 +1110,6 @@ function missingCompiler(kind, file) {
1266
1110
  file
1267
1111
  });
1268
1112
  }
1269
- function scriptLang(lang) {
1270
- return lang === "ts" || lang === "tsx" || lang === "jsx" ? lang : "js";
1271
- }
1272
1113
  /**
1273
1114
  * File access for type-based `defineProps<…>()` that imports its types:
1274
1115
  * compiler-sfc resolves them through this or a registered TypeScript.
@@ -1476,8 +1317,7 @@ async function parseOnlyModule(file, code) {
1476
1317
  if (compiler === null) return { fallback: "compiler" };
1477
1318
  return kind === "vue" ? vueParseOnly(compiler, file, code) : svelteParseOnly(compiler, file, blankForeignStyles(code));
1478
1319
  }
1479
- //#endregion
1480
- //#region src/core/extract/worker.ts
1320
+ // src/core/extract/worker.ts
1481
1321
  /**
1482
1322
  * One file's scan, and the `worker_threads` entry of the scan pool
1483
1323
  * (INTERNALS §2.5.6). `scanProject` runs `scanSource` in-process for small
@@ -1487,6 +1327,13 @@ async function parseOnlyModule(file, code) {
1487
1327
  * Kept free of the cache, the config loader and `VERSION` (a JSON import),
1488
1328
  * so a worker loads only what scanning needs.
1489
1329
  */
1330
+ /** The opted-in packages' manual ids, merged once per config, as their manifests are read once. */
1331
+ const libraryIdMaps = /* @__PURE__ */ new WeakMap();
1332
+ function idsOf(config) {
1333
+ let ids = libraryIdMaps.get(config.extraction);
1334
+ if (ids === void 0) libraryIdMaps.set(config.extraction, ids = libraryIds(config));
1335
+ return ids;
1336
+ }
1490
1337
  /** The scan's part of `config`, for a worker. */
1491
1338
  function scanConfig(config) {
1492
1339
  const { root, sourceLocale, project, extraction, strict } = config;
@@ -1599,7 +1446,7 @@ async function scanSource(task, config, codec, options = {}) {
1599
1446
  warnings: true,
1600
1447
  exactPositions: !sfc,
1601
1448
  sourceLocale: config.sourceLocale,
1602
- ...config.extraction.dependencies.length === 0 ? {} : { libraryIds: libraryIds(config) }
1449
+ ...config.extraction.dependencies.length === 0 ? {} : { libraryIds: idsOf(config) }
1603
1450
  });
1604
1451
  for (const occurrence of scan.occurrences) result.occurrences.push(occurrence);
1605
1452
  for (const diagnostic of scan.diagnostics) result.diagnostics.push(diagnostic);
@@ -1652,5 +1499,4 @@ if (!isMainThread && parentPort !== null && init?.marker === "vi18n:scan-worker"
1652
1499
  })();
1653
1500
  });
1654
1501
  }
1655
- //#endregion
1656
- export { expandMacros as a, armRawParsing as c, scanSource as i, langFromId as l, WORKER_MARKER as n, macroNames as o, scanConfig as r, decodeEntities as s, ABORT_CODES as t, parseModule as u };
1502
+ export { expandMacros as a, scanSource as i, WORKER_MARKER as n, macroNames as o, scanConfig as r, decodeEntities as s, ABORT_CODES as t };