@menapo/vi18n 0.1.1 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (118) hide show
  1. package/dist/{apply-Bre-lY9J.js → apply-FAHl1R6T.js} +69 -89
  2. package/dist/{captured-Bj8bO6vd.js → captured-CTjjDF5o.js} +196 -217
  3. package/dist/{check-BIKEuu6B.js → check-DwFwOB1d.js} +66 -84
  4. package/dist/cli.js +2 -3
  5. package/dist/{collect-Cx4_SKOe.js → collect-CYATDjdo.js} +1 -2
  6. package/dist/collisions-uMTuq36M.js +215 -0
  7. package/dist/compile-CEvH-6sY.js +240 -0
  8. package/dist/{compile-Cc97JaW2.js → compile-DqkofbiO.js} +376 -331
  9. package/dist/concurrency-BCY_4zcr.js +1 -0
  10. package/dist/concurrency-Dy2ny50V.js +107 -0
  11. package/dist/config.d.ts +1 -5
  12. package/dist/config.js +4 -5
  13. package/dist/{types-D3QGM8XO.js → diagnostics-1onDF6Ua.js} +26 -26
  14. package/dist/{dir-zw6bGMKQ.js → dir-TGLYuOZb.js} +34 -37
  15. package/dist/{duplicates-yuRljQ6h.js → duplicates-CsUXRX2J.js} +10 -27
  16. package/dist/engine-Bf7nVigL.js +556 -0
  17. package/dist/engine.d.ts +1 -5
  18. package/dist/engine.js +297 -168
  19. package/dist/exchange-DYG9RZoT.js +41 -0
  20. package/dist/{exclude-Du-Zd_qI.js → exclude-vMnm3lqU.js} +2 -3
  21. package/dist/{export-C9Sy6UWv.js → export-BYq0gfLd.js} +17 -38
  22. package/dist/{extract-C3S8btx0.js → extract-CYtuEo8u.js} +114 -82
  23. package/dist/{formats-9unqj_fZ.js → formats-ChV1LVH_.js} +352 -276
  24. package/dist/fs-ezCMZeDV.js +52 -0
  25. package/dist/i18next-1waHziMy.js +1 -0
  26. package/dist/i18next-D66Icz3L.js +1907 -0
  27. package/dist/{import-nANvQutw.js → import-BApbQlmm.js} +81 -75
  28. package/dist/index.d.ts +1 -13
  29. package/dist/index.js +14 -16
  30. package/dist/{init-C2ScuW6a.js → init-J7AwwA5e.js} +466 -501
  31. package/dist/{library-D5CWvTQs.js → library-BfSOBeBd.js} +975 -451
  32. package/dist/lingui-Ee2farVo.js +902 -0
  33. package/dist/lint.d.ts +0 -4
  34. package/dist/lint.js +68 -81
  35. package/dist/{load-gW-oJt1Q.js → load-BFLLqY8x.js} +272 -147
  36. package/dist/{load-CQRz4PpM.js → load-CMwhukZ4.js} +1211 -1115
  37. package/dist/{locales-DX4MOBFE.js → locales-DxLDrx-h.js} +271 -237
  38. package/dist/{lsp-RMMMc88P.js → lsp-BC7xDGON.js} +4 -5
  39. package/dist/{match-BGr8EXB3.js → match-BLDcj610.js} +11 -4
  40. package/dist/{mcp-CHVwBoRP.js → mcp-Cka8ywDF.js} +4 -5
  41. package/dist/{merge-driver-BTX87aVm.js → merge-driver-B04Apm29.js} +138 -122
  42. package/dist/migrate-D7TNl6SD.js +2169 -0
  43. package/dist/migrate-khCY8TE0.js +1 -0
  44. package/dist/{openai-CTaMDcl-.js → openai-RWw0YlAx.js} +128 -87
  45. package/dist/{output-DWE3SIUA.js → output-CF9uvk_-.js} +15 -9
  46. package/dist/parse.d.ts +1 -3
  47. package/dist/parse.js +7 -8
  48. package/dist/{pipeline-DbX6rlo5.js → pipeline-B30irGMD.js} +1 -1
  49. package/dist/{pipeline-C9Dbotkh.js → pipeline-sgl_q_op.js} +387 -359
  50. package/dist/project-DSzWKU3C.js +544 -0
  51. package/dist/{pseudo-DRv30iN5.js → pseudo-DNbNNVGP.js} +125 -3
  52. package/dist/{raw-C4Y6vyGY.js → raw-YsYZMS9n.js} +52 -29
  53. package/dist/react-intl-tzGIk6G3.js +634 -0
  54. package/dist/restore-BG_zMpSj.js +199 -0
  55. package/dist/rewrite-hAcRJwiZ.js +415 -0
  56. package/dist/{rich-DCUKl5HM.js → rich-ApY1Dm4S.js} +35 -28
  57. package/dist/rolldown-runtime-C1I3wEg2.js +43 -0
  58. package/dist/{rolldown-runtime-D7D4PA-g.js → rolldown-runtime-D8jQpDG7.js} +1 -2
  59. package/dist/run-CFzR3V93.js +647 -0
  60. package/dist/scan-worker.d.ts +2 -4
  61. package/dist/scan-worker.js +1 -1
  62. package/dist/{scoped-BMYpSthj.js → scoped-h3KE8XWW.js} +3 -4
  63. package/dist/{server-deBOq2vq.js → server-WlxZH0oX.js} +275 -330
  64. package/dist/{server-Da1Ot9IN.js → server-ceuzzkal.js} +292 -386
  65. package/dist/server.d.ts +1 -17
  66. package/dist/server.js +415 -381
  67. package/dist/{sitemap-DJXzKoza.js → sitemap-796jJKUT.js} +21 -33
  68. package/dist/{sources-D19czDSA.js → sources-DuOdM02f.js} +712 -373
  69. package/dist/{status-zr4jY59Y.js → status-CTH3qI-0.js} +30 -30
  70. package/dist/{stdio-FPOKQAgu.js → stdio-D9kTzyqB.js} +2 -4
  71. package/dist/{stdio-CVaJfxA7.js → stdio-FWIVU3P4.js} +1 -2
  72. package/dist/sync-CpL0Qsgw.js +1352 -0
  73. package/dist/{t-DC-c9zE5.js → t-gvEXx25s.js} +76 -53
  74. package/dist/test.d.ts +5 -16
  75. package/dist/test.js +77 -48
  76. package/dist/translate-BrfVRkjl.js +336 -0
  77. package/dist/{ts-BaU5yOf0.js → ts-BX6kwig5.js} +25 -14
  78. package/dist/{types-DtvQ7UdD.js → types-3kwyaCAm.js} +1 -2
  79. package/dist/{types-DsdWBG0b.d.ts → types-BaG1LboH.d.ts} +2 -6
  80. package/dist/{types-CgUCkFU1.d.ts → types-Cy2bPdSg.d.ts} +14 -20
  81. package/dist/types-Ds_vebja.js +41 -0
  82. package/dist/{units-CQ5Q99RC.js → units-VVLgQ7x7.js} +7 -16
  83. package/dist/{url-CRfCOhUI.js → url-Bpc6wLea.js} +24 -11
  84. package/dist/{url-CsBkRaJy.js → url-D2_VlEeH.js} +25 -12
  85. package/dist/{validate-D6DJepZv.js → validate-PGgMsasz.js} +3 -5
  86. package/dist/{validate-BxpupdAf.js → validate-zv4-IZyZ.js} +690 -377
  87. package/dist/{version-Byqi2guX.js → version-BFs370Ce.js} +3 -5
  88. package/dist/{vite-scan-CT_vsp4g.js → vite-scan-DFKSGVE9.js} +87 -92
  89. package/dist/vite.d.ts +2 -6
  90. package/dist/vite.js +6482 -6018
  91. package/dist/vue-i18n-CBmZqHbG.js +806 -0
  92. package/dist/{which-BOemZ5Q8.js → which-BpyJyBkX.js} +44 -37
  93. package/dist/{worker-84U6uYB3.js → worker-BjzVqJVO.js} +454 -608
  94. package/package.json +5 -5
  95. package/dist/check-HsmmpJZg.js +0 -1
  96. package/dist/codec-DuvU2VQy.js +0 -207
  97. package/dist/collisions-CfpZU8e4.js +0 -217
  98. package/dist/compile-BaDh0cHG.js +0 -245
  99. package/dist/concurrency-C9UUWuDC.js +0 -96
  100. package/dist/concurrency-DONL7t4V.js +0 -1
  101. package/dist/engine-C2ENBRJe.js +0 -531
  102. package/dist/i18next-9HAoxwUI.js +0 -1
  103. package/dist/i18next-BEJgv_S8.js +0 -1596
  104. package/dist/lingui-zUiCl9Um.js +0 -833
  105. package/dist/messages-BfjIExyB.js +0 -166
  106. package/dist/migrate-IpLDMXmq.js +0 -1484
  107. package/dist/migrate-rCQuOGsf.js +0 -1
  108. package/dist/project-Bw9UPIdx.js +0 -1046
  109. package/dist/project-C4GpaN-n.js +0 -381
  110. package/dist/react-intl-BP0u-D5m.js +0 -519
  111. package/dist/restore-CiYv-jxS.js +0 -175
  112. package/dist/rewrite-EsIw_lsq.js +0 -803
  113. package/dist/run-BEcnBbu-.js +0 -694
  114. package/dist/runtime-DTMmliT1.js +0 -64
  115. package/dist/sync-B9V2KFwb.js +0 -658
  116. package/dist/translate-CQnJfLjO.js +0 -299
  117. package/dist/types-wSh9fCBY.js +0 -11
  118. package/dist/vue-i18n-g0iGy6CZ.js +0 -651
@@ -0,0 +1,634 @@
1
+ import { n as isDiagnosticError } from "./diagnostics-1onDF6Ua.js";
2
+ import { C as langFromId, w as parseModule } from "./sources-DuOdM02f.js";
3
+ import { y as printICU } from "./validate-zv4-IZyZ.js";
4
+ import { a as annotateHandlers, g as formatjsId, h as formatjsAstToIcu, l as reactTypes, t as MODULE_EXTENSIONS, v as parseJson } from "./i18next-D66Icz3L.js";
5
+ import { B as objectProperties, C as attributeString, D as inJsxChildren, E as identifierName, F as jsxNameNodes, M as jsxAttributes, P as jsxName, S as attributeExpression, V as stringValue, W as unwrap, w as childEntries, x as analyzeModule, z as memberParts } from "./migrate-D7TNl6SD.js";
6
+ import { t as ModuleBuilder } from "./rewrite-hAcRJwiZ.js";
7
+ import { extname } from "node:path";
8
+ import { readFileSync } from "node:fs";
9
+ // src/cli/commands/migrate/react-intl.ts
10
+ /**
11
+ * `vi18n migrate --from react-intl` (INTERNALS §2.14): react-intl and
12
+ * `@formatjs/intl`.
13
+ *
14
+ * Messages are ICU already. The source text is the code's `defaultMessage`
15
+ * (the source catalog's text where a descriptor has none); translations are
16
+ * the catalogs' texts by id: an explicit `id`, else the id
17
+ * `babel-plugin-formatjs` generates (`[sha512:contenthash:base64:6]`).
18
+ * Catalogs are JSON: `{ id: "text" }`, `{ id: { defaultMessage | message |
19
+ * string, description } }`, or `formatjs compile --ast` output.
20
+ * `<FormattedMessage>` and `intl.formatMessage()` become `t()` (`rich()`
21
+ * when values hold elements or tag handlers), `defineMessages` /
22
+ * `defineMessage` become `msg()`, `description` a `context` note.
23
+ * `useIntl()` bindings, imports and `<IntlProvider>` go once unused.
24
+ */
25
+ function isOldSource(source) {
26
+ return source === "react-intl" || source.startsWith("react-intl/") || source === "@formatjs/intl";
27
+ }
28
+ /** `fmt` counterparts of the formatting components and `intl.format*` methods. */
29
+ const FORMATTERS = {
30
+ FormattedNumber: "fmt.number(value, options)",
31
+ FormattedDate: "fmt.date(value, options)",
32
+ FormattedTime: "fmt.time(value, options)",
33
+ FormattedDateParts: "fmt.date(value, options)",
34
+ FormattedTimeParts: "fmt.time(value, options)",
35
+ FormattedRelativeTime: "fmt.relative(value, options)",
36
+ FormattedList: "fmt.list(values, options)",
37
+ FormattedDisplayName: "Intl.DisplayNames",
38
+ FormattedPlural: "an ICU plural: t(\"{n, plural, one {…} other {…}}\", { n })",
39
+ formatNumber: "fmt.number",
40
+ formatDate: "fmt.date",
41
+ formatTime: "fmt.time",
42
+ formatRelativeTime: "fmt.relative",
43
+ formatList: "fmt.list",
44
+ formatDisplayName: "Intl.DisplayNames",
45
+ formatPlural: "an ICU plural"
46
+ };
47
+ function createReactIntlAdapter() {
48
+ return new ReactIntlAdapter();
49
+ }
50
+ /** A catalog entry's text: a string as ICU, a compiled AST printed (or kept as unconvertible), else nothing. */
51
+ function catalogText(message, file, line) {
52
+ if (typeof message === "string") return { icu: message };
53
+ if (!Array.isArray(message)) return null;
54
+ const nodes = formatjsAstToIcu(message);
55
+ if (nodes !== null) return { icu: printICU(nodes) };
56
+ return {
57
+ unconverted: JSON.stringify(message),
58
+ reason: "a compiled message vi18n cannot print",
59
+ file,
60
+ line
61
+ };
62
+ }
63
+ /** A catalog entry's message and description: a string, or an object holding them. */
64
+ function entryParts(entry) {
65
+ if (typeof entry !== "object" || entry === null || Array.isArray(entry)) return {
66
+ message: entry,
67
+ description: null
68
+ };
69
+ const record = entry;
70
+ return {
71
+ message: record.defaultMessage ?? record.message ?? record.string ?? record.translation,
72
+ description: describe(record.description)
73
+ };
74
+ }
75
+ /** The react-intl catalogs of a run, and the messages its descriptors define. */
76
+ var ReactIntlAdapter = class {
77
+ catalogExtensions = [".json"];
78
+ catalogsRequired = false;
79
+ extensions = MODULE_EXTENSIONS;
80
+ /** locale → id → text. */
81
+ catalogs = /* @__PURE__ */ new Map();
82
+ referenced = /* @__PURE__ */ new Set();
83
+ sourceLocale = "";
84
+ mentions(text) {
85
+ return /react-intl|@formatjs\/intl|formatMessage/.test(text);
86
+ }
87
+ load(files, env) {
88
+ this.sourceLocale = env.config.sourceLocale;
89
+ for (const file of files) this.readCatalog(file, env);
90
+ }
91
+ planFile(file, text, env) {
92
+ let program;
93
+ try {
94
+ program = parseModule(text, langFromId(file), file).program;
95
+ } catch (error) {
96
+ if (!isDiagnosticError(error)) throw error;
97
+ env.diagnostics.push({
98
+ ...error.diagnostic,
99
+ file: env.rel(file)
100
+ });
101
+ return null;
102
+ }
103
+ return new ReactIntlModule(this, env, {
104
+ file,
105
+ text,
106
+ program
107
+ }).plan();
108
+ }
109
+ unusedKeys() {
110
+ return [...this.catalogs.get(this.sourceLocale)?.keys() ?? []].filter((id) => !this.referenced.has(id));
111
+ }
112
+ /** The parsed catalog object; null (reported) when it cannot be read or is not an object. */
113
+ readObject(file, env) {
114
+ let text;
115
+ try {
116
+ text = readFileSync(file.file, "utf8");
117
+ } catch (error) {
118
+ const message = `cannot read: ${error.message}`;
119
+ env.report("catalog-parse", message, { file: file.file }, "error");
120
+ return null;
121
+ }
122
+ const parsed = parseJson(text);
123
+ if (parsed.problem !== null) {
124
+ const at = {
125
+ file: file.file,
126
+ line: parsed.problem.line
127
+ };
128
+ env.report("catalog-parse", parsed.problem.message, at, "error");
129
+ return null;
130
+ }
131
+ const value = parsed.value;
132
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
133
+ env.report("catalog-parse", "a react-intl catalog is an object of messages by id", { file: file.file }, "error");
134
+ return null;
135
+ }
136
+ return {
137
+ value,
138
+ text
139
+ };
140
+ }
141
+ readCatalog(file, env) {
142
+ const read = this.readObject(file, env);
143
+ if (read === null) return;
144
+ let texts = this.catalogs.get(file.locale);
145
+ if (texts === void 0) this.catalogs.set(file.locale, texts = /* @__PURE__ */ new Map());
146
+ const lines = read.text.split("\n");
147
+ for (const [id, entry] of Object.entries(read.value)) {
148
+ const needle = `${JSON.stringify(id)}:`;
149
+ const line = lines.findIndex((l) => l.includes(needle)) + 1;
150
+ const { message, description } = entryParts(entry);
151
+ const text = catalogText(message, file.file, line);
152
+ if (text !== null) {
153
+ texts.set(id, {
154
+ text,
155
+ description,
156
+ file: file.file,
157
+ line
158
+ });
159
+ continue;
160
+ }
161
+ const at = {
162
+ file: file.file,
163
+ line
164
+ };
165
+ env.report("migrate-unconverted", `${id} holds no message text; it was skipped`, at);
166
+ }
167
+ }
168
+ /** Whether a descriptor's `defaultMessage` is the text an earlier site defined `known` with. */
169
+ sameText(env, message, known) {
170
+ if (message === null) return true;
171
+ try {
172
+ return env.codec.canonicalize(message) === known.canonical;
173
+ } catch {
174
+ return false;
175
+ }
176
+ }
177
+ /** A message for a descriptor; its registry key, or why there is none. */
178
+ define(env, descriptor, at) {
179
+ if (descriptor.id === null && descriptor.message === null) return { problem: "a descriptor without id or defaultMessage" };
180
+ const id = descriptor.id ?? formatjsId(descriptor.message, descriptor.hashed ?? descriptor.description);
181
+ this.referenced.add(id);
182
+ const known = env.message(id);
183
+ if (known !== void 0) {
184
+ if (this.sameText(env, descriptor.message, known)) return { key: id };
185
+ return { problem: `id ${id} has another defaultMessage at an earlier site (${JSON.stringify(known.source)})` };
186
+ }
187
+ const fromCatalog = this.catalogs.get(this.sourceLocale)?.get(id);
188
+ const source = this.sourceText(env, id, descriptor.message, fromCatalog);
189
+ if (typeof source !== "string") return source;
190
+ const fromFile = descriptor.message === null && fromCatalog !== void 0;
191
+ return env.define({
192
+ key: id,
193
+ named: descriptor.id !== null,
194
+ source,
195
+ context: descriptor.description ?? fromCatalog?.description ?? null,
196
+ hint: null,
197
+ translations: this.translations(id),
198
+ file: fromFile ? fromCatalog.file : at.file,
199
+ line: fromFile ? fromCatalog.line : at.line
200
+ }) ? { key: id } : { problem: `${id} could not be converted` };
201
+ }
202
+ /** The source text: the code's `defaultMessage` (reported when the catalog differs), else the catalog's. */
203
+ sourceText(env, id, message, fromCatalog) {
204
+ const { sourceLocale } = this;
205
+ if (message === null) {
206
+ if (fromCatalog === void 0) return { problem: `${id} has no defaultMessage and is in no ${sourceLocale} catalog` };
207
+ if (!("icu" in fromCatalog.text)) return { problem: `${id}: ${fromCatalog.text.reason}` };
208
+ return fromCatalog.text.icu;
209
+ }
210
+ if (fromCatalog !== void 0 && "icu" in fromCatalog.text && fromCatalog.text.icu !== message) env.report("migrate-manual", `${id}: the ${sourceLocale} catalog has ${JSON.stringify(fromCatalog.text.icu)}, the code's defaultMessage ${JSON.stringify(message)}; the defaultMessage was kept`, {
211
+ file: fromCatalog.file,
212
+ line: fromCatalog.line
213
+ });
214
+ return message;
215
+ }
216
+ translations(id) {
217
+ const translations = /* @__PURE__ */ new Map();
218
+ for (const [locale, texts] of this.catalogs) {
219
+ if (locale === this.sourceLocale) continue;
220
+ const translated = texts.get(id);
221
+ if (translated !== void 0) translations.set(locale, translated.text);
222
+ }
223
+ return translations;
224
+ }
225
+ };
226
+ function renderCall(r, { message, values, rich, types }) {
227
+ const first = "key" in message ? r.message(message.key) : r.src(message.ref.start, message.ref.end);
228
+ const rest = values === null ? "" : `, ${r.src(values.start, values.end)}`;
229
+ if (!rich) return `${r.fn.t}(${first}${rest})`;
230
+ return `${r.fn.rich}${types === null ? "" : `<${types.node}>`}(${first}${rest})`;
231
+ }
232
+ const keysOf = (message) => "key" in message ? [message.key] : [];
233
+ /** Whether a value property renders markup: an element or a tag handler. */
234
+ function isRichValue(p) {
235
+ if (p.type === "SpreadElement") return false;
236
+ const value = unwrap(p.value);
237
+ return value.type === "ArrowFunctionExpression" || value.type === "FunctionExpression" || value.type === "JSXElement" || value.type === "JSXFragment";
238
+ }
239
+ /** A descriptor field: its static text, null when absent, undefined when computed. */
240
+ function descriptorField(props, name) {
241
+ const property = props.properties.get(name);
242
+ if (property === void 0) return null;
243
+ const value = unwrap(property.value);
244
+ if (name === "description" && value.type === "ObjectExpression") return describeNode(value)?.note;
245
+ return stringValue(value) ?? void 0;
246
+ }
247
+ /** A descriptor object literal, or null when a field is not static. */
248
+ function readDescriptor(node) {
249
+ const props = objectProperties(node);
250
+ if (props === null || props.spreads.length > 0) return null;
251
+ const id = descriptorField(props, "id");
252
+ const message = descriptorField(props, "defaultMessage");
253
+ const description = descriptorField(props, "description");
254
+ if (id === void 0 || message === void 0 || description === void 0) return null;
255
+ const object = props.properties.get("description");
256
+ const value = object === void 0 ? null : unwrap(object.value);
257
+ return {
258
+ id,
259
+ message,
260
+ description,
261
+ hashed: value !== null && value.type === "ObjectExpression" ? describeNode(value)?.json ?? null : description
262
+ };
263
+ }
264
+ /** A `defineMessages()` table as code, keeping the argument's layout (one line, or one entry per line). */
265
+ function renderTable(r, text, arg, entries) {
266
+ const source = text.slice(arg.start, arg.end);
267
+ const lines = entries.map(({ property, key }) => {
268
+ const keyNode = property.key;
269
+ const name = text.slice(keyNode.start, keyNode.end);
270
+ return `${property.computed === true ? `[${name}]` : name}: ${r.fn.msg}(${r.message(key)})`;
271
+ });
272
+ if (!source.includes("\n")) return `{ ${lines.join(", ")} }`;
273
+ const indent = /\n([ \t]*)\S/.exec(source)?.[1] ?? " ";
274
+ const closing = /\n([ \t]*)\}$/.exec(source)?.[1] ?? "";
275
+ return `{\n${lines.map((l) => `${indent}${l},`).join("\n")}\n${closing}}`;
276
+ }
277
+ /** Calls whose result vi18n has another way to get, by callee import, and what to do instead. */
278
+ const SETUP_NOTES = /* @__PURE__ */ new Map([
279
+ ["injectIntl", () => "injectIntl() injects intl as a prop: drop it and call t() from @menapo/vi18n"],
280
+ ["createIntl", (c) => `${c}(): use createTranslator(locale) or withLocale() from @menapo/vi18n/server`],
281
+ ["createIntlCache", (c) => `${c}(): use createTranslator(locale) or withLocale() from @menapo/vi18n/server`]
282
+ ]);
283
+ /** One module's react-intl call sites, planned as rewrites. */
284
+ var ReactIntlModule = class {
285
+ adapter;
286
+ env;
287
+ file;
288
+ text;
289
+ program;
290
+ info;
291
+ builder;
292
+ tsx;
293
+ /** `const intl = useIntl()` and `const { formatMessage } = useIntl()`. */
294
+ intlBindings = /* @__PURE__ */ new Set();
295
+ /** Locals bound to `defineMessages()` / `defineMessage()` results: their members are `msg()` refs now. */
296
+ messageTables = /* @__PURE__ */ new Set();
297
+ relativeImports = /* @__PURE__ */ new Set();
298
+ constructor(adapter, env, { file, text, program }) {
299
+ this.adapter = adapter;
300
+ this.env = env;
301
+ this.file = file;
302
+ this.text = text;
303
+ this.program = program;
304
+ this.info = analyzeModule(program);
305
+ this.builder = new ModuleBuilder({
306
+ file,
307
+ text,
308
+ info: this.info,
309
+ isOldSource
310
+ });
311
+ this.tsx = extname(file) === ".tsx";
312
+ }
313
+ plan() {
314
+ const useIntl = this.imported("useIntl");
315
+ for (const binding of this.info.bindings) {
316
+ const callee = initCallee(binding);
317
+ if (callee === null) continue;
318
+ if (useIntl.has(callee)) {
319
+ this.builder.hooks.push(binding);
320
+ this.intlBindings.add(binding);
321
+ }
322
+ if (this.has("defineMessages", callee) || this.has("defineMessage", callee)) this.messageTables.add(binding.name);
323
+ }
324
+ for (const declaration of this.info.imports) {
325
+ if (!declaration.source.startsWith(".")) continue;
326
+ for (const s of declaration.specifiers) this.relativeImports.add(s.local);
327
+ }
328
+ this.visit(this.program);
329
+ return this.builder.finish();
330
+ }
331
+ imported(name) {
332
+ const locals = /* @__PURE__ */ new Set();
333
+ for (const declaration of this.info.imports) {
334
+ if (!isOldSource(declaration.source)) continue;
335
+ for (const s of declaration.specifiers) if (s.imported === name) locals.add(s.local);
336
+ }
337
+ return locals;
338
+ }
339
+ has(name, local) {
340
+ return this.imported(name).has(local);
341
+ }
342
+ lineOf(offset) {
343
+ return this.text.slice(0, offset).split("\n").length;
344
+ }
345
+ define(descriptor, offset) {
346
+ return this.adapter.define(this.env, descriptor, {
347
+ file: this.file,
348
+ line: this.lineOf(offset)
349
+ });
350
+ }
351
+ isIntl(name) {
352
+ return [...this.intlBindings].some((b) => b.name === name);
353
+ }
354
+ /** Whether an expression is a message the migrated code holds as a `msg()` ref. */
355
+ isMessageRef(node) {
356
+ let root = unwrap(node);
357
+ while (root.type === "MemberExpression") root = unwrap(root.object);
358
+ const name = identifierName(root);
359
+ return name !== null && (this.messageTables.has(name) || this.relativeImports.has(name));
360
+ }
361
+ /** Whether values need `rich()`: an element or a function among them, or tags in the message. */
362
+ needsRich(values, message) {
363
+ if ("key" in message) {
364
+ const defined = this.env.message(message.key);
365
+ if (defined !== void 0 && hasTag(this.env.codec.parse(defined.canonical))) return true;
366
+ }
367
+ if (values === null) return false;
368
+ return objectProperties(values)?.order.some(isRichValue) ?? false;
369
+ }
370
+ /** A call's rendering: `rich()` (its handlers typed in a `.tsx` file) when its values need it. */
371
+ callOf(message, values) {
372
+ const rich = this.needsRich(values, message);
373
+ const types = rich && this.tsx ? reactTypes(this.builder) : null;
374
+ if (types !== null && values !== null) annotateHandlers(this.builder, values, types.node);
375
+ return {
376
+ message,
377
+ values,
378
+ rich,
379
+ types
380
+ };
381
+ }
382
+ /** `<FormattedMessage>`'s message from its props; null when they are computed, "reported" when it cannot be defined. */
383
+ elementMessage(element, attributes) {
384
+ const { named, spreads } = attributes;
385
+ if (spreads.length === 1 && !named.has("id") && !named.has("defaultMessage")) {
386
+ const spread = spreads[0].argument;
387
+ return this.isMessageRef(spread) ? { ref: spread } : null;
388
+ }
389
+ if (spreads.length > 0) return null;
390
+ const attr = (name) => named.get(name)?.value ?? null;
391
+ const read = (name) => named.has(name) ? attributeString(attr(name)) ?? void 0 : null;
392
+ let description = read("description");
393
+ let hashed = description;
394
+ const descriptionExpr = attributeExpression(attr("description"));
395
+ if (description === void 0 && descriptionExpr !== null && unwrap(descriptionExpr).type === "ObjectExpression") {
396
+ const described = describeNode(unwrap(descriptionExpr));
397
+ description = described?.note;
398
+ hashed = described?.json;
399
+ }
400
+ const id = read("id");
401
+ const message = read("defaultMessage");
402
+ if (id === void 0 || message === void 0 || description === void 0) return null;
403
+ const defined = this.define({
404
+ id,
405
+ message,
406
+ description,
407
+ hashed: hashed ?? null
408
+ }, element.start);
409
+ if (!("problem" in defined)) return defined;
410
+ this.builder.note(element.start, `${defined.problem}; <FormattedMessage> was not rewritten`);
411
+ return "reported";
412
+ }
413
+ /** Why a `<FormattedMessage>`'s other props stop the rewrite; null when none do. */
414
+ elementProblem(attributes, values) {
415
+ const { named } = attributes;
416
+ if (named.has("values") && (values === null || objectProperties(values) === null)) return "<FormattedMessage values={…}> is not an object literal; not rewritten";
417
+ if (!named.has("tagName")) return null;
418
+ const tagName = attributeString(named.get("tagName")?.value ?? null);
419
+ if (tagName !== null && /^[a-z][a-z0-9-]*$/.test(tagName)) return null;
420
+ return "<FormattedMessage tagName={Component}> was not rewritten: wrap the t() call yourself";
421
+ }
422
+ formattedMessage(element) {
423
+ const attributes = jsxAttributes(element);
424
+ if (attributes.named.has("children") || element.children.length > 0) {
425
+ this.builder.note(element.start, "<FormattedMessage> with a render function child was not rewritten: call t() and render the string");
426
+ return;
427
+ }
428
+ const message = this.elementMessage(element, attributes);
429
+ if (message === "reported") return;
430
+ if (message === null) {
431
+ this.builder.note(element.start, "<FormattedMessage> with a computed id or defaultMessage was not rewritten");
432
+ return;
433
+ }
434
+ const values = attributeExpression(attributes.named.get("values")?.value ?? null);
435
+ const problem = this.elementProblem(attributes, values);
436
+ if (problem !== null) {
437
+ this.builder.note(element.start, problem);
438
+ return;
439
+ }
440
+ const tagName = attributes.named.has("tagName") ? attributeString(attributes.named.get("tagName")?.value ?? null) : null;
441
+ const call = this.callOf(message, values);
442
+ const nested = inJsxChildren(this.info, element);
443
+ this.builder.site(element, (r) => {
444
+ const code = renderCall(r, call);
445
+ if (tagName !== null) return `<${tagName}>{${code}}</${tagName}>`;
446
+ return nested ? `{${code}}` : code;
447
+ }, {
448
+ keys: keysOf(message),
449
+ uses: [call.rich ? "rich" : "t"],
450
+ consume: jsxNameNodes(element)
451
+ });
452
+ }
453
+ /** The nodes a `formatMessage` callee consumes; null when the call is not react-intl's. */
454
+ formatCallee(node) {
455
+ const callee = unwrap(node.callee);
456
+ const member = memberParts(callee);
457
+ if (member !== null && member.property === "formatMessage") {
458
+ const object = unwrap(member.object);
459
+ return object.type === "Identifier" ? [object] : [];
460
+ }
461
+ if (callee.type === "Identifier" && this.isIntl(callee.name)) return [callee];
462
+ return null;
463
+ }
464
+ /** A `formatMessage()` call's message; a string is a problem to report. */
465
+ callMessage(node, first) {
466
+ if (unwrap(first).type !== "ObjectExpression") {
467
+ if (this.isMessageRef(first)) return { ref: first };
468
+ return "formatMessage() with a descriptor vi18n migrate cannot trace was not rewritten: pass a msg() descriptor to t()";
469
+ }
470
+ const descriptor = readDescriptor(unwrap(first));
471
+ if (descriptor === null) return "formatMessage() with a computed descriptor was not rewritten";
472
+ const defined = this.define(descriptor, node.start);
473
+ if ("problem" in defined) return `${defined.problem}; formatMessage() was not rewritten`;
474
+ return defined;
475
+ }
476
+ /** `intl.formatMessage(descriptor, values)` and a destructured `formatMessage(…)`. */
477
+ formatMessage(node) {
478
+ const consume = this.formatCallee(node);
479
+ if (consume === null) return false;
480
+ const args = node.arguments;
481
+ const first = args[0];
482
+ const values = args[1] ?? null;
483
+ if (first === void 0 || first.type === "SpreadElement" || args.length > 2) return false;
484
+ const message = this.callMessage(node, first);
485
+ if (typeof message === "string") {
486
+ this.builder.note(node.start, message);
487
+ return true;
488
+ }
489
+ if (values !== null && unwrap(values).type !== "ObjectExpression" && this.needsRich(null, message)) {
490
+ this.builder.note(node.start, "formatMessage() with rich values that are not an object literal was not rewritten");
491
+ return true;
492
+ }
493
+ const call = this.callOf(message, values);
494
+ this.builder.site(node, (r) => renderCall(r, call), {
495
+ keys: keysOf(message),
496
+ uses: [call.rich ? "rich" : "t"],
497
+ consume
498
+ });
499
+ return true;
500
+ }
501
+ /** `defineMessage({ … })` → `msg(…)`. */
502
+ defineMessage(node, arg) {
503
+ const descriptor = readDescriptor(unwrap(arg));
504
+ if (descriptor === null) {
505
+ this.builder.note(node.start, "defineMessage() with a computed descriptor was not rewritten");
506
+ return;
507
+ }
508
+ const defined = this.define(descriptor, node.start);
509
+ if ("problem" in defined) {
510
+ this.builder.note(node.start, `${defined.problem}; defineMessage() was not rewritten`);
511
+ return;
512
+ }
513
+ this.builder.site(node, (r) => `${r.fn.msg}(${r.message(defined.key)})`, {
514
+ keys: [defined.key],
515
+ uses: ["msg"],
516
+ consume: [unwrap(node.callee)]
517
+ });
518
+ }
519
+ /** `defineMessages({ … })` → `{ key: msg(…) }`. */
520
+ defineMessages(node, arg) {
521
+ const props = objectProperties(arg);
522
+ if (props === null || props.spreads.length > 0) {
523
+ this.builder.note(node.start, "defineMessages() with spreads or computed keys was not rewritten");
524
+ return;
525
+ }
526
+ const entries = [];
527
+ for (const property of props.order) {
528
+ const descriptor = readDescriptor(unwrap(property.value));
529
+ const defined = descriptor === null ? null : this.define(descriptor, property.start);
530
+ if (defined === null || "problem" in defined) {
531
+ const why = defined === null ? "a computed descriptor" : defined.problem;
532
+ this.builder.note(property.start, `defineMessages(): ${why}; the table was not rewritten`);
533
+ return;
534
+ }
535
+ entries.push({
536
+ property,
537
+ key: defined.key
538
+ });
539
+ }
540
+ const text = this.text;
541
+ this.builder.site(node, (r) => renderTable(r, text, arg, entries), {
542
+ keys: entries.map((e) => e.key),
543
+ uses: ["msg"],
544
+ consume: [unwrap(node.callee)]
545
+ });
546
+ }
547
+ unwrapProvider(element) {
548
+ const opening = element.openingElement;
549
+ const closing = element.closingElement;
550
+ const children = element.children.filter((c) => !(c.type === "JSXText" && c.value.trim() === ""));
551
+ this.builder.consumeRange(opening);
552
+ this.builder.consume(jsxNameNodes(element));
553
+ const nested = inJsxChildren(this.info, element);
554
+ this.builder.replace(element, (r) => {
555
+ if (closing === null) return nested ? "" : "null";
556
+ if (nested) return r.src(opening.end, closing.start).trim();
557
+ if (children.length === 1 && children[0].type === "JSXElement") return r.src(children[0].start, children[0].end);
558
+ return `<>${r.src(opening.end, closing.start)}</>`;
559
+ });
560
+ }
561
+ element(node) {
562
+ const name = jsxName(node);
563
+ if (this.has("FormattedMessage", name)) return this.formattedMessage(node);
564
+ if (this.has("IntlProvider", name) || this.has("RawIntlProvider", name)) return this.unwrapProvider(node);
565
+ const formatter = Object.keys(FORMATTERS).find((f) => this.has(f, name));
566
+ if (formatter === void 0) return;
567
+ const message = `<${name}> is not rewritten: render ${FORMATTERS[formatter]} from @menapo/vi18n`;
568
+ this.builder.note(node.start, message);
569
+ }
570
+ call(node) {
571
+ const callee = identifierName(node.callee);
572
+ const arg = node.arguments[0];
573
+ if (callee !== null && this.has("defineMessages", callee)) {
574
+ if (arg !== void 0) this.defineMessages(node, arg);
575
+ return;
576
+ }
577
+ if (callee !== null && this.has("defineMessage", callee)) {
578
+ if (arg !== void 0) this.defineMessage(node, arg);
579
+ return;
580
+ }
581
+ const setup = callee === null ? void 0 : [...SETUP_NOTES].find(([name]) => this.has(name, callee));
582
+ if (setup !== void 0) return this.builder.note(node.start, setup[1](callee));
583
+ if (!this.formatMessage(node)) this.otherFormat(node);
584
+ }
585
+ /** `intl.formatNumber()` and the other formatters: reported with their `fmt` counterpart. */
586
+ otherFormat(node) {
587
+ const member = memberParts(node.callee);
588
+ if (member === null || !Object.hasOwn(FORMATTERS, member.property)) return;
589
+ if (!member.property.startsWith("format") || !this.isIntl(identifierName(member.object))) return;
590
+ const message = `intl.${member.property}() is not rewritten: use ${FORMATTERS[member.property]} from @menapo/vi18n`;
591
+ this.builder.note(node.start, message);
592
+ }
593
+ visit(node) {
594
+ if (node.type === "JSXElement") this.element(node);
595
+ else if (node.type === "CallExpression") this.call(node);
596
+ for (const [, child] of childEntries(node)) this.visit(child);
597
+ }
598
+ };
599
+ /** The name a binding's initializer calls (`useIntl()` → `useIntl`), or null. */
600
+ function initCallee(binding) {
601
+ const init = binding.declarator?.init;
602
+ if (init === null || init === void 0) return null;
603
+ const call = unwrap(init);
604
+ return call.type === "CallExpression" ? identifierName(call.callee) : null;
605
+ }
606
+ function hasTag(nodes) {
607
+ return nodes.some((node) => node.type === "tag" || (node.type === "plural" || node.type === "select") && node.options.some((o) => hasTag(o.value)));
608
+ }
609
+ /** A FormatJS `description` as one note: a string as is, an object as `key: value` pairs. */
610
+ function describe(value) {
611
+ if (typeof value === "string") return value === "" ? null : value;
612
+ if (typeof value !== "object" || value === null) return null;
613
+ const parts = Object.entries(value).map(([k, v]) => `${k}: ${typeof v === "string" ? v : JSON.stringify(v)}`);
614
+ return parts.length === 0 ? null : parts.join("; ");
615
+ }
616
+ /** An object `description` as a note, and as the stable JSON FormatJS hashes. */
617
+ function describeNode(node) {
618
+ const props = objectProperties(node);
619
+ if (props === null || props.spreads.length > 0) return void 0;
620
+ const out = {};
621
+ for (const [key, property] of props.properties) {
622
+ const value = unwrap(property.value);
623
+ const s = stringValue(value);
624
+ if (s !== null) out[key] = s;
625
+ else if (value.type === "Literal") out[key] = value.value;
626
+ else return void 0;
627
+ }
628
+ const sorted = Object.fromEntries(Object.keys(out).sort().map((k) => [k, out[k]]));
629
+ return {
630
+ note: describe(out),
631
+ json: JSON.stringify(sorted)
632
+ };
633
+ }
634
+ export { createReactIntlAdapter };