@vxrn/vite-plugin-metro 1.25.13 → 1.25.16-1788753284749

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 (49) hide show
  1. package/dist/cjs/metro-config/getMetroConfigFromViteConfig.cjs +20 -0
  2. package/dist/cjs/metro-config/getMetroConfigFromViteConfig.native.js +20 -0
  3. package/dist/cjs/metro-config/getMetroConfigFromViteConfig.native.js.map +1 -1
  4. package/dist/cjs/metro-config/patchMetroServerWithViteConfigAndMetroPluginOptions.cjs +2 -1
  5. package/dist/cjs/metro-config/patchMetroServerWithViteConfigAndMetroPluginOptions.native.js +2 -1
  6. package/dist/cjs/metro-config/patchMetroServerWithViteConfigAndMetroPluginOptions.native.js.map +1 -1
  7. package/dist/cjs/plugins/metroPlugin.native.js.map +1 -1
  8. package/dist/cjs/transformer/metroNativeWorker.cjs +1594 -0
  9. package/dist/cjs/transformer/metroNativeWorker.native.js +2678 -0
  10. package/dist/cjs/transformer/metroNativeWorker.native.js.map +1 -0
  11. package/dist/cjs/transformer/metroNativeWorker.test.cjs +813 -0
  12. package/dist/cjs/transformer/metroNativeWorker.test.native.js +920 -0
  13. package/dist/cjs/transformer/metroNativeWorker.test.native.js.map +1 -0
  14. package/dist/esm/metro-config/getMetroConfigFromViteConfig.mjs +20 -0
  15. package/dist/esm/metro-config/getMetroConfigFromViteConfig.mjs.map +1 -1
  16. package/dist/esm/metro-config/getMetroConfigFromViteConfig.native.js +20 -0
  17. package/dist/esm/metro-config/getMetroConfigFromViteConfig.native.js.map +1 -1
  18. package/dist/esm/metro-config/patchMetroServerWithViteConfigAndMetroPluginOptions.mjs +2 -1
  19. package/dist/esm/metro-config/patchMetroServerWithViteConfigAndMetroPluginOptions.mjs.map +1 -1
  20. package/dist/esm/metro-config/patchMetroServerWithViteConfigAndMetroPluginOptions.native.js +2 -1
  21. package/dist/esm/metro-config/patchMetroServerWithViteConfigAndMetroPluginOptions.native.js.map +1 -1
  22. package/dist/esm/plugins/metroPlugin.mjs.map +1 -1
  23. package/dist/esm/plugins/metroPlugin.native.js.map +1 -1
  24. package/dist/esm/transformer/metroNativeWorker.mjs +1535 -0
  25. package/dist/esm/transformer/metroNativeWorker.mjs.map +1 -0
  26. package/dist/esm/transformer/metroNativeWorker.native.js +2616 -0
  27. package/dist/esm/transformer/metroNativeWorker.native.js.map +1 -0
  28. package/dist/esm/transformer/metroNativeWorker.test.mjs +777 -0
  29. package/dist/esm/transformer/metroNativeWorker.test.mjs.map +1 -0
  30. package/dist/esm/transformer/metroNativeWorker.test.native.js +882 -0
  31. package/dist/esm/transformer/metroNativeWorker.test.native.js.map +1 -0
  32. package/package.json +22 -3
  33. package/src/metro-config/getMetroConfigFromViteConfig.ts +42 -0
  34. package/src/metro-config/patchMetroServerWithViteConfigAndMetroPluginOptions.ts +1 -0
  35. package/src/plugins/metroPlugin.ts +22 -0
  36. package/src/transformer/__fixtures__/exampleNativeTransform.cjs +17 -0
  37. package/src/transformer/metroNativeWorker.test.ts +1138 -0
  38. package/src/transformer/metroNativeWorker.ts +2385 -0
  39. package/src/transformer/types.ts +21 -0
  40. package/types/metro-config/getMetroConfigFromViteConfig.d.ts.map +1 -1
  41. package/types/metro-config/patchMetroServerWithViteConfigAndMetroPluginOptions.d.ts.map +1 -1
  42. package/types/plugins/metroPlugin.d.ts +22 -0
  43. package/types/plugins/metroPlugin.d.ts.map +1 -1
  44. package/types/transformer/metroNativeWorker.d.ts +251 -0
  45. package/types/transformer/metroNativeWorker.d.ts.map +1 -0
  46. package/types/transformer/metroNativeWorker.test.d.ts +2 -0
  47. package/types/transformer/metroNativeWorker.test.d.ts.map +1 -0
  48. package/types/transformer/types.d.ts +17 -0
  49. package/types/transformer/types.d.ts.map +1 -1
@@ -0,0 +1,1594 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __export = (target, all) => {
8
+ for (var name in all) __defProp(target, name, {
9
+ get: all[name],
10
+ enumerable: true
11
+ });
12
+ };
13
+ var __copyProps = (to, from, except, desc) => {
14
+ if (from && typeof from === "object" || typeof from === "function") {
15
+ for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
16
+ get: () => from[key],
17
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
18
+ });
19
+ }
20
+ return to;
21
+ };
22
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
23
+ // If the importer is in node compatibility mode or this is not an ESM
24
+ // file that has been converted to a CommonJS file using a Babel-
25
+ // compatible transform (i.e. "__esModule" has not been set), then set
26
+ // "default" to the CommonJS "module.exports" for node compatibility.
27
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
28
+ value: mod,
29
+ enumerable: true
30
+ }) : target, mod));
31
+ var __toCommonJS = mod => __copyProps(__defProp({}, "__esModule", {
32
+ value: true
33
+ }), mod);
34
+ var metroNativeWorker_exports = {};
35
+ __export(metroNativeWorker_exports, {
36
+ ScopeTracker: () => ScopeTracker,
37
+ applyEnvironmentGuard: () => applyEnvironmentGuard,
38
+ applyInlineEnvVars: () => applyInlineEnvVars,
39
+ applyModuleResolverAliases: () => applyModuleResolverAliases,
40
+ applyOneRouterMetro: () => applyOneRouterMetro,
41
+ assertNoUnportedBabelPlugins: () => assertNoUnportedBabelPlugins,
42
+ collectBlockBindings: () => collectBlockBindings,
43
+ collectHoistedBindings: () => collectHoistedBindings,
44
+ collectPatternNames: () => collectPatternNames,
45
+ convertSourceMapToMetroRawMappings: () => convertSourceMapToMetroRawMappings,
46
+ countLinesAndTerminateMap: () => countLinesAndTerminateMap,
47
+ default: () => metroNativeWorker_default,
48
+ extractDependencies: () => extractDependencies,
49
+ getCacheKey: () => getCacheKey,
50
+ getDependencyKey: () => getDependencyKey,
51
+ getImportMetaEnv: () => getImportMetaEnv,
52
+ getModuleResolverAliases: () => getModuleResolverAliases,
53
+ getOneRouterMetroOptions: () => getOneRouterMetroOptions,
54
+ getRemoveServerCodeRouterRoot: () => getRemoveServerCodeRouterRoot,
55
+ resolveAliasSpecifier: () => resolveAliasSpecifier,
56
+ rewriteDependencyCalls: () => rewriteDependencyCalls,
57
+ transform: () => transform,
58
+ wrapJson: () => wrapJson,
59
+ wrapModule: () => wrapModule
60
+ });
61
+ module.exports = __toCommonJS(metroNativeWorker_exports);
62
+ var import_node_crypto = __toESM(require("node:crypto"), 1);
63
+ var import_node_module = require("node:module");
64
+ var import_node_fs = __toESM(require("node:fs"), 1);
65
+ var import_node_path = __toESM(require("node:path"), 1);
66
+ var import_oxc_parser = require("oxc-parser");
67
+ var import_magic_string = __toESM(require("magic-string"), 1);
68
+ var import_remapping = __toESM(require("@jridgewell/remapping"), 1);
69
+ var import_trace_mapping = require("@jridgewell/trace-mapping");
70
+ var import_compiler = require("@vxrn/compiler");
71
+ var import_platformEnv = require("../env/platformEnv.cjs");
72
+ const HERMES_UNSUPPORTED_ASYNC_RE = /\basync\s+function\s*\*|\basync\s*\*\s*[\w$[]|\bfor\s+await\s*\(/;
73
+ function collectModuleLiteralBindings(program) {
74
+ const reassigned = /* @__PURE__ */new Set();
75
+ const declCount = /* @__PURE__ */new Map();
76
+ (function findReassignments(node) {
77
+ if (!node || typeof node !== "object") return;
78
+ if (Array.isArray(node)) {
79
+ for (const child of node) findReassignments(child);
80
+ return;
81
+ }
82
+ if (node.type === "AssignmentExpression" && node.left?.type === "Identifier") {
83
+ reassigned.add(node.left.name);
84
+ } else if (node.type === "UpdateExpression" && node.argument?.type === "Identifier") {
85
+ reassigned.add(node.argument.name);
86
+ }
87
+ for (const key in node) {
88
+ if (key === "type" || key === "start" || key === "end") continue;
89
+ findReassignments(node[key]);
90
+ }
91
+ })(program);
92
+ for (const stmt of program.body || []) {
93
+ if (stmt.type !== "VariableDeclaration") continue;
94
+ for (const decl of stmt.declarations || []) {
95
+ if (decl.id?.type === "Identifier") {
96
+ declCount.set(decl.id.name, (declCount.get(decl.id.name) || 0) + 1);
97
+ }
98
+ }
99
+ }
100
+ const bindings = /* @__PURE__ */new Map();
101
+ for (const stmt of program.body || []) {
102
+ if (stmt.type !== "VariableDeclaration") continue;
103
+ for (const decl of stmt.declarations || []) {
104
+ if (decl.id?.type === "Identifier" && decl.init?.type === "Literal" && !reassigned.has(decl.id.name) && declCount.get(decl.id.name) === 1) {
105
+ bindings.set(decl.id.name, decl.init);
106
+ }
107
+ }
108
+ }
109
+ return bindings;
110
+ }
111
+ const WORKER_CACHE_KEY_VERSION = "3";
112
+ const FLOW_FILE_PATTERN = /node_modules[\\/](?:react-native|@react-native)[\\/].*\.js$/;
113
+ function langForFilename(filename) {
114
+ if (filename.endsWith(".tsx")) return "tsx";
115
+ if (filename.endsWith(".ts")) return "ts";
116
+ return "jsx";
117
+ }
118
+ function getOneRouterMetroOptions(options) {
119
+ const plugins = options.customTransformOptions?.vite?.babelConfig?.plugins;
120
+ if (!Array.isArray(plugins)) return void 0;
121
+ for (const plugin of plugins) {
122
+ if (Array.isArray(plugin) && typeof plugin[0] === "string" && plugin[0].includes("one-router-metro")) {
123
+ return plugin[1];
124
+ }
125
+ }
126
+ return void 0;
127
+ }
128
+ function getRemoveServerCodeRouterRoot(options) {
129
+ const plugins = options.customTransformOptions?.vite?.babelConfig?.plugins;
130
+ if (!Array.isArray(plugins)) return void 0;
131
+ for (const plugin of plugins) {
132
+ if (Array.isArray(plugin) && typeof plugin[0] === "string" && plugin[0].includes("remove-server-code")) {
133
+ return plugin[1]?.routerRoot ?? "app";
134
+ }
135
+ }
136
+ return void 0;
137
+ }
138
+ const importMetaEnvCache = /* @__PURE__ */new WeakMap();
139
+ function getImportMetaEnv(options) {
140
+ const plugins = options.customTransformOptions?.vite?.babelConfig?.plugins;
141
+ const platform = options.platform ?? "";
142
+ let byPlatform = Array.isArray(plugins) ? importMetaEnvCache.get(plugins) : void 0;
143
+ const cached = byPlatform?.get(platform);
144
+ if (cached) return cached;
145
+ let env = {};
146
+ if (Array.isArray(plugins)) {
147
+ for (const plugin of plugins) {
148
+ if (Array.isArray(plugin) && typeof plugin[0] === "string" && plugin[0].includes("import-meta-env-plugin")) {
149
+ const found = plugin[1]?.env;
150
+ if (found && typeof found === "object") env = found;
151
+ }
152
+ }
153
+ }
154
+ const merged = {
155
+ ...env,
156
+ ...(0, import_platformEnv.getPlatformEnv)((0, import_platformEnv.metroPlatformToViteEnvironment)(options.platform))
157
+ };
158
+ if (Array.isArray(plugins)) {
159
+ if (!byPlatform) {
160
+ byPlatform = /* @__PURE__ */new Map();
161
+ importMetaEnvCache.set(plugins, byPlatform);
162
+ }
163
+ byPlatform.set(platform, merged);
164
+ }
165
+ return merged;
166
+ }
167
+ const PORTED_BABEL_PLUGINS = ["import-meta-env-plugin", "one-router-metro", "remove-server-code", "module-resolver", "environment-guard", "inline-one-server-url",
168
+ // the worklets transform is a native oxc port, so both plugin names it can
169
+ // arrive under are covered.
170
+ "react-native-worklets/plugin", "react-native-reanimated/plugin", "babel-plugin-react-compiler"];
171
+ const unportedPluginCache = /* @__PURE__ */new WeakMap();
172
+ const loadedNativeTransforms = /* @__PURE__ */new Map();
173
+ function getNativeTransforms(options, projectRoot) {
174
+ const ids = options.customTransformOptions?.vite?.nativeTransformModules;
175
+ if (!Array.isArray(ids) || !ids.length) return [];
176
+ const req = (0, import_node_module.createRequire)(import_node_path.default.join(projectRoot, "package.json"));
177
+ return ids.map(id => {
178
+ const cached = loadedNativeTransforms.get(id);
179
+ if (cached) return cached;
180
+ let mod;
181
+ try {
182
+ mod = req(id);
183
+ } catch (err) {
184
+ throw new Error(`[vxrn/metro] Could not load the native transform "${id}" from ${projectRoot}: ${err.message}`);
185
+ }
186
+ const fn = mod?.default ?? mod;
187
+ if (typeof fn !== "function") {
188
+ throw new Error(`[vxrn/metro] The native transform "${id}" must default-export a function (code, ctx) => string.`);
189
+ }
190
+ loadedNativeTransforms.set(id, fn);
191
+ return fn;
192
+ });
193
+ }
194
+ function isReactCompilerCandidate(filename) {
195
+ if (!/\.tsx?$/.test(filename)) return false;
196
+ if (filename.includes("node_modules")) return false;
197
+ if (filename.includes("+api.")) return false;
198
+ return true;
199
+ }
200
+ function hasBabelPlugin(options, id) {
201
+ const plugins = options.customTransformOptions?.vite?.babelConfig?.plugins;
202
+ if (!Array.isArray(plugins)) return false;
203
+ return plugins.some(plugin => (Array.isArray(plugin) ? plugin[0] : plugin) === id);
204
+ }
205
+ function assertNoUnportedBabelPlugins(options) {
206
+ const plugins = options.customTransformOptions?.vite?.babelConfig?.plugins;
207
+ if (!Array.isArray(plugins)) return;
208
+ let unported = unportedPluginCache.get(plugins);
209
+ if (!unported) {
210
+ unported = [];
211
+ for (const plugin of plugins) {
212
+ const id = Array.isArray(plugin) ? plugin[0] : plugin;
213
+ if (typeof id !== "string") {
214
+ unported.push("(a function or object plugin, which cannot be ported)");
215
+ continue;
216
+ }
217
+ if (!PORTED_BABEL_PLUGINS.some(ported => id.includes(ported))) {
218
+ unported.push(id);
219
+ }
220
+ }
221
+ unportedPluginCache.set(plugins, unported);
222
+ }
223
+ if (unported.length) {
224
+ throw new Error(`[vxrn/metro] the native transform path runs no babel, so these babel plugins would be silently ignored:
225
+ ` + unported.map(id => ` - ${id}`).join("\n") + `
226
+
227
+ Port each one to a native transform and list it in bundlerOptions.nativeTransformModules, remove it from bundlerOptions.babelConfigOverrides, or set bundlerOptions.nativeTransforms: false (or ONE_METRO_NATIVE_TRANSFORMS=0) to go back to the babel transformer.`);
228
+ }
229
+ }
230
+ function getModuleResolverAliases(options) {
231
+ const plugins = options.customTransformOptions?.vite?.babelConfig?.plugins;
232
+ if (!Array.isArray(plugins)) return void 0;
233
+ for (const plugin of plugins) {
234
+ if (Array.isArray(plugin) && typeof plugin[0] === "string" && plugin[0].includes("module-resolver")) {
235
+ const alias = plugin[1]?.alias;
236
+ if (alias && typeof alias === "object") return alias;
237
+ }
238
+ }
239
+ return void 0;
240
+ }
241
+ function resolveAliasSpecifier(specifier, filename, projectRoot, aliases) {
242
+ for (const [rawKey, value] of Object.entries(aliases)) {
243
+ let target;
244
+ if (rawKey.endsWith("$")) {
245
+ if (specifier === rawKey.slice(0, -1)) target = value;
246
+ } else if (specifier === rawKey || specifier.startsWith(`${rawKey}/`)) {
247
+ target = value + specifier.slice(rawKey.length);
248
+ }
249
+ if (target === void 0) continue;
250
+ const abs = import_node_path.default.resolve(projectRoot, target);
251
+ let rel = import_node_path.default.relative(import_node_path.default.dirname(filename), abs).split(import_node_path.default.sep).join("/");
252
+ if (!rel.startsWith(".")) rel = `./${rel}`;
253
+ return rel;
254
+ }
255
+ return void 0;
256
+ }
257
+ function applyModuleResolverAliases(code, filename, projectRoot, aliases) {
258
+ const parsed = (0, import_oxc_parser.parseSync)(filename, code, {
259
+ lang: langForFilename(filename)
260
+ });
261
+ if (parsed?.errors?.length) {
262
+ throw new Error(`[vxrn/metro] Failed to parse ${filename} for alias resolution: ${parsed.errors[0].message}`);
263
+ }
264
+ if (!parsed?.program) return code;
265
+ const ms = new import_magic_string.default(code);
266
+ let changed = false;
267
+ function rewrite(sourceNode) {
268
+ if (sourceNode?.type !== "Literal" || typeof sourceNode.value !== "string") return;
269
+ const resolved = resolveAliasSpecifier(sourceNode.value, filename, projectRoot, aliases);
270
+ if (resolved === void 0) return;
271
+ ms.overwrite(sourceNode.start, sourceNode.end, JSON.stringify(resolved));
272
+ changed = true;
273
+ }
274
+ function walk(node) {
275
+ if (!node || typeof node !== "object") return;
276
+ if (node.type === "ImportDeclaration" || node.type === "ExportNamedDeclaration" || node.type === "ExportAllDeclaration" || node.type === "ImportExpression") {
277
+ rewrite(node.source);
278
+ } else if (node.type === "CallExpression" && node.callee?.type === "Identifier" && node.callee.name === "require") {
279
+ rewrite(node.arguments?.[0]);
280
+ }
281
+ for (const k of Object.keys(node)) {
282
+ if (k === "start" || k === "end" || k === "loc" || k === "range" || k === "parent" || k === "comments") continue;
283
+ const child = node[k];
284
+ if (Array.isArray(child)) {
285
+ for (const item of child) walk(item);
286
+ } else if (child && typeof child === "object") {
287
+ walk(child);
288
+ }
289
+ }
290
+ }
291
+ walk(parsed.program);
292
+ return changed ? ms.toString() : code;
293
+ }
294
+ function applyInlineEnvVars(code, filename, isProduction, env = {}) {
295
+ const parsed = (0, import_oxc_parser.parseSync)(filename, code, {
296
+ lang: langForFilename(filename)
297
+ });
298
+ if (parsed?.errors?.length) {
299
+ throw new Error(`[vxrn/metro] Failed to parse ${filename} for env inlining: ${parsed.errors[0].message}`);
300
+ }
301
+ if (!parsed?.program) return code;
302
+ const ms = new import_magic_string.default(code);
303
+ let needsEnvImport = false;
304
+ const edits = [];
305
+ const known = /* @__PURE__ */new Map();
306
+ function replace(node, value) {
307
+ const text = value === void 0 ? "undefined" : JSON.stringify(value);
308
+ edits.push({
309
+ start: node.start,
310
+ end: node.end,
311
+ text
312
+ });
313
+ known.set(node, value);
314
+ }
315
+ function keyOf(prop, computed) {
316
+ if (!computed && prop?.type === "Identifier") return prop.name;
317
+ if (prop?.type === "Literal" && typeof prop.value === "string") return prop.value;
318
+ return void 0;
319
+ }
320
+ function isImportMeta(node) {
321
+ return node?.type === "MetaProperty" && node.meta?.name === "import" && node.property?.name === "meta";
322
+ }
323
+ function walk(node, parent) {
324
+ if (!node || typeof node !== "object") return;
325
+ if (node.type === "MemberExpression" || node.type === "OptionalMemberExpression") {
326
+ const obj = node.object;
327
+ const isMember = obj?.type === "MemberExpression" || obj?.type === "OptionalMemberExpression";
328
+ const isProcessEnv = isMember && obj.object?.type === "Identifier" && obj.object.name === "process" && keyOf(obj.property, obj.computed) === "env";
329
+ const isAssignmentTarget = parent?.type === "AssignmentExpression" && parent.left === node;
330
+ const key = keyOf(node.property, node.computed);
331
+ if (isProcessEnv && !isAssignmentTarget && key === "ONE_SERVER_URL") {
332
+ replace(node, process.env.ONE_SERVER_URL || "");
333
+ return;
334
+ }
335
+ if (isProcessEnv && !isAssignmentTarget && key?.startsWith("EXPO_PUBLIC_")) {
336
+ if (isProduction) {
337
+ replace(node, process.env[key] ?? void 0);
338
+ } else {
339
+ edits.push({
340
+ start: node.start,
341
+ end: node.end,
342
+ text: `_$$_EXPO_ENV.${key}`
343
+ });
344
+ needsEnvImport = true;
345
+ }
346
+ return;
347
+ }
348
+ if (!isAssignmentTarget && isMember && isImportMeta(obj.object) && keyOf(obj.property, obj.computed) === "env" && key !== void 0) {
349
+ replace(node, env[key]);
350
+ return;
351
+ }
352
+ if (!isAssignmentTarget && isImportMeta(obj) && key === "env") {
353
+ edits.push({
354
+ start: node.start,
355
+ end: node.end,
356
+ text: JSON.stringify(env)
357
+ });
358
+ return;
359
+ }
360
+ if (isProcessEnv && !isAssignmentTarget && key !== void 0 && key in env) {
361
+ replace(node, env[key]);
362
+ return;
363
+ }
364
+ }
365
+ for (const k of Object.keys(node)) {
366
+ if (k === "start" || k === "end" || k === "loc" || k === "range" || k === "parent" || k === "comments") continue;
367
+ const child = node[k];
368
+ if (Array.isArray(child)) {
369
+ for (const item of child) walk(item, node);
370
+ } else if (child && typeof child === "object") {
371
+ walk(child, node);
372
+ }
373
+ }
374
+ }
375
+ walk(parsed.program, null);
376
+ function testValue(node) {
377
+ if (known.has(node)) return !!known.get(node);
378
+ if (node?.type === "UnaryExpression" && node.operator === "!") {
379
+ const inner = testValue(node.argument);
380
+ return inner === void 0 ? void 0 : !inner;
381
+ }
382
+ if (node?.type === "BinaryExpression" && (node.operator === "===" || node.operator === "!==")) {
383
+ const left = known.has(node.left) ? known.get(node.left) : void 0;
384
+ const right = node.right?.type === "Literal" ? node.right.value : void 0;
385
+ if (!known.has(node.left) || node.right?.type !== "Literal") return void 0;
386
+ return node.operator === "===" ? left === right : left !== right;
387
+ }
388
+ return void 0;
389
+ }
390
+ const dead = [];
391
+ (function foldWalk(node) {
392
+ if (!node || typeof node !== "object") return;
393
+ if (Array.isArray(node)) {
394
+ for (const child of node) foldWalk(child);
395
+ return;
396
+ }
397
+ if (node.type === "IfStatement" || node.type === "ConditionalExpression") {
398
+ const value = testValue(node.test);
399
+ if (value !== void 0) {
400
+ const kept = value ? node.consequent : node.alternate;
401
+ if (!kept) {
402
+ dead.push({
403
+ start: node.start,
404
+ end: node.end,
405
+ text: ";"
406
+ });
407
+ return;
408
+ }
409
+ dead.push({
410
+ start: node.start,
411
+ end: kept.start,
412
+ text: ""
413
+ });
414
+ if (kept.end < node.end) {
415
+ dead.push({
416
+ start: kept.end,
417
+ end: node.end,
418
+ text: ""
419
+ });
420
+ }
421
+ foldWalk(kept);
422
+ return;
423
+ }
424
+ }
425
+ for (const k of Object.keys(node)) {
426
+ if (k === "start" || k === "end" || k === "loc" || k === "range" || k === "parent" || k === "comments") continue;
427
+ foldWalk(node[k]);
428
+ }
429
+ })(parsed.program);
430
+ for (const range of dead) {
431
+ ms.overwrite(range.start, range.end, range.text);
432
+ }
433
+ for (const edit of edits) {
434
+ if (dead.some(d => edit.start >= d.start && edit.end <= d.end)) continue;
435
+ ms.overwrite(edit.start, edit.end, edit.text);
436
+ }
437
+ if (needsEnvImport) {
438
+ ms.prepend(`import { env as _$$_EXPO_ENV } from "expo/virtual/env";
439
+ `);
440
+ }
441
+ return ms.hasChanged() ? ms.toString() : code;
442
+ }
443
+ const GUARD_SPECIFIERS = /* @__PURE__ */new Set(["server-only", "client-only", "web-only"]);
444
+ function applyEnvironmentGuard(code, filename) {
445
+ const parsed = (0, import_oxc_parser.parseSync)(filename, code, {
446
+ lang: langForFilename(filename)
447
+ });
448
+ if (parsed?.errors?.length) {
449
+ throw new Error(`[vxrn/metro] Failed to parse ${filename} for environment guards: ${parsed.errors[0].message}`);
450
+ }
451
+ const body = parsed?.program?.body;
452
+ if (!body) return code;
453
+ const ms = new import_magic_string.default(code);
454
+ let changed = false;
455
+ for (const node of body) {
456
+ if (node.type !== "ImportDeclaration") continue;
457
+ const source = node.source?.value;
458
+ if (source === "native-only") {
459
+ ms.remove(node.start, node.end);
460
+ changed = true;
461
+ } else if (GUARD_SPECIFIERS.has(source)) {
462
+ ms.overwrite(node.start, node.end, `throw new Error(${JSON.stringify(`${source} cannot be imported in a native environment`)});`);
463
+ changed = true;
464
+ }
465
+ }
466
+ return changed ? ms.toString() : code;
467
+ }
468
+ function applyOneRouterMetro(code, filename, options) {
469
+ const isMetroEntry = filename.endsWith("metro-entry.js");
470
+ const isEntryCtx = filename.endsWith("metro-entry-ctx.js");
471
+ if (!isMetroEntry && !isEntryCtx) return code;
472
+ const parsed = (0, import_oxc_parser.parseSync)(filename, code, {
473
+ lang: langForFilename(filename)
474
+ });
475
+ if (parsed?.errors?.length) {
476
+ throw new Error(`[vxrn/metro] Failed to parse ${filename} for one-router-metro: ${parsed.errors[0].message}`);
477
+ }
478
+ if (!parsed?.program) return code;
479
+ const ms = new import_magic_string.default(code);
480
+ let lastImportEnd = -1;
481
+ function replacementFor(key) {
482
+ if (key.startsWith("ONE_ROUTER_APP_ROOT_RELATIVE_TO_ENTRY")) {
483
+ return JSON.stringify(options.ONE_ROUTER_APP_ROOT_RELATIVE_TO_ENTRY);
484
+ }
485
+ if (key.startsWith("ONE_ROUTER_ROOT_FOLDER_NAME")) {
486
+ return JSON.stringify(options.ONE_ROUTER_ROOT_FOLDER_NAME);
487
+ }
488
+ if (key.startsWith("ONE_ROUTER_REQUIRE_CONTEXT_REGEX")) {
489
+ return `/${options.ONE_ROUTER_REQUIRE_CONTEXT_REGEX_STRING}/`;
490
+ }
491
+ if (key === "ONE_ROUTER_LINKING_CONFIG") {
492
+ return isMetroEntry ? JSON.stringify(options.ONE_ROUTER_LINKING_CONFIG ?? null) : void 0;
493
+ }
494
+ if (key === "ONE_SETUP_FILE_NATIVE") {
495
+ return options.ONE_SETUP_FILE_NATIVE ? JSON.stringify(options.ONE_SETUP_FILE_NATIVE) : "undefined";
496
+ }
497
+ return void 0;
498
+ }
499
+ function walk(node, parent) {
500
+ if (!node || typeof node !== "object") return;
501
+ if (node.type === "ImportDeclaration" && parent === parsed.program) {
502
+ lastImportEnd = Math.max(lastImportEnd, node.end);
503
+ }
504
+ if (node.type === "MemberExpression" && node.object?.type === "MemberExpression" && !node.object.computed && node.object.object?.type === "Identifier" && node.object.object.name === "process" && node.object.property?.type === "Identifier" && node.object.property.name === "env") {
505
+ const key = node.computed ? node.property?.type === "Literal" && typeof node.property.value === "string" ? node.property.value : void 0 : node.property?.type === "Identifier" ? node.property.name : void 0;
506
+ const isAssignTarget = parent?.type === "AssignmentExpression" && parent.left === node;
507
+ if (key && !isAssignTarget) {
508
+ const replacement = replacementFor(key);
509
+ if (replacement !== void 0) {
510
+ ms.overwrite(node.start, node.end, replacement);
511
+ }
512
+ }
513
+ }
514
+ for (const k of Object.keys(node)) {
515
+ if (k === "start" || k === "end" || k === "loc" || k === "range" || k === "parent" || k === "comments") continue;
516
+ const child = node[k];
517
+ if (Array.isArray(child)) {
518
+ for (const item of child) walk(item, node);
519
+ } else if (child && typeof child === "object") {
520
+ walk(child, node);
521
+ }
522
+ }
523
+ }
524
+ walk(parsed.program, parsed.program);
525
+ if (isMetroEntry && options.ONE_SETUP_FILE_NATIVE) {
526
+ const stmt = `
527
+ import ${JSON.stringify(options.ONE_SETUP_FILE_NATIVE)};`;
528
+ if (lastImportEnd >= 0) {
529
+ ms.appendRight(lastImportEnd, stmt);
530
+ } else {
531
+ ms.prepend(`${stmt}
532
+ `);
533
+ }
534
+ }
535
+ return ms.toString();
536
+ }
537
+ function collectPatternNames(pattern, names) {
538
+ if (!pattern) return;
539
+ if (pattern.type === "Identifier") {
540
+ names.add(pattern.name);
541
+ } else if (pattern.type === "AssignmentPattern") {
542
+ collectPatternNames(pattern.left, names);
543
+ } else if (pattern.type === "ObjectPattern") {
544
+ for (const prop of pattern.properties || []) {
545
+ if (prop.type === "Property") collectPatternNames(prop.value, names);else if (prop.type === "RestElement") collectPatternNames(prop.argument, names);
546
+ }
547
+ } else if (pattern.type === "ArrayPattern") {
548
+ for (const elem of pattern.elements || []) {
549
+ if (elem) collectPatternNames(elem, names);
550
+ }
551
+ } else if (pattern.type === "RestElement") {
552
+ collectPatternNames(pattern.argument, names);
553
+ }
554
+ }
555
+ function collectHoistedBindings(node, names) {
556
+ function traverse(n) {
557
+ if (!n || typeof n !== "object") return;
558
+ if (n === node) {} else if (n.type === "FunctionDeclaration" || n.type === "FunctionExpression" || n.type === "ArrowFunctionExpression") {
559
+ if (n.type === "FunctionDeclaration" && n.id?.name) {
560
+ names.add(n.id.name);
561
+ }
562
+ return;
563
+ }
564
+ if (n.type === "VariableDeclaration" && n.kind === "var") {
565
+ for (const decl of n.declarations || []) {
566
+ collectPatternNames(decl.id, names);
567
+ }
568
+ }
569
+ for (const key of Object.keys(n)) {
570
+ if (key === "start" || key === "end" || key === "loc" || key === "range" || key === "parent" || key === "comments") continue;
571
+ const child = n[key];
572
+ if (Array.isArray(child)) {
573
+ for (const item of child) traverse(item);
574
+ } else if (child && typeof child === "object") {
575
+ traverse(child);
576
+ }
577
+ }
578
+ }
579
+ traverse(node);
580
+ }
581
+ function collectBlockBindings(statements, names) {
582
+ if (!Array.isArray(statements)) return;
583
+ for (const stmt of statements) {
584
+ if (!stmt) continue;
585
+ if (stmt.type === "VariableDeclaration" && stmt.kind !== "var") {
586
+ for (const decl of stmt.declarations || []) {
587
+ collectPatternNames(decl.id, names);
588
+ }
589
+ } else if (stmt.type === "ClassDeclaration" && stmt.id?.name) {
590
+ names.add(stmt.id.name);
591
+ } else if (stmt.type === "FunctionDeclaration" && stmt.id?.name) {
592
+ names.add(stmt.id.name);
593
+ }
594
+ }
595
+ }
596
+ class ScopeTracker {
597
+ stack = [/* @__PURE__ */new Set()];
598
+ enter(initialBindings) {
599
+ this.stack.push(new Set(initialBindings));
600
+ }
601
+ exit() {
602
+ if (this.stack.length > 1) {
603
+ this.stack.pop();
604
+ }
605
+ }
606
+ add(name) {
607
+ this.stack[this.stack.length - 1].add(name);
608
+ }
609
+ currentScope() {
610
+ return this.stack[this.stack.length - 1];
611
+ }
612
+ addPattern(pattern) {
613
+ collectPatternNames(pattern, this.currentScope());
614
+ }
615
+ isShadowed(name) {
616
+ for (let i = this.stack.length - 1; i >= 0; i--) {
617
+ if (this.stack[i].has(name)) return true;
618
+ }
619
+ return false;
620
+ }
621
+ }
622
+ function getCacheKey(config = {}, opts) {
623
+ const hash = import_node_crypto.default.createHash("sha256");
624
+ hash.update("metroNativeWorker");
625
+ hash.update(WORKER_CACHE_KEY_VERSION);
626
+ if (config.globalPrefix) {
627
+ hash.update(config.globalPrefix);
628
+ }
629
+ if (config.unstable_dependencyMapReservedName) {
630
+ hash.update(config.unstable_dependencyMapReservedName);
631
+ }
632
+ if (config.minifierPath) {
633
+ hash.update(config.minifierPath);
634
+ }
635
+ if (opts?.projectRoot) {
636
+ hash.update(opts.projectRoot);
637
+ }
638
+ return hash.digest("hex");
639
+ }
640
+ function convertSourceMapToMetroRawMappings(composedMap) {
641
+ if (!composedMap) return [];
642
+ const tracer = new import_trace_mapping.TraceMap(composedMap);
643
+ const rawMappings = [];
644
+ (0, import_trace_mapping.eachMapping)(tracer, m => {
645
+ if (m.originalLine == null) {
646
+ rawMappings.push([m.generatedLine, m.generatedColumn]);
647
+ } else if (m.name == null) {
648
+ rawMappings.push([m.generatedLine, m.generatedColumn, m.originalLine, m.originalColumn]);
649
+ } else {
650
+ rawMappings.push([m.generatedLine, m.generatedColumn, m.originalLine, m.originalColumn, m.name]);
651
+ }
652
+ });
653
+ rawMappings.sort((a, b) => {
654
+ if (a[0] !== b[0]) return a[0] - b[0];
655
+ return a[1] - b[1];
656
+ });
657
+ const deduped = [];
658
+ for (const mapping of rawMappings) {
659
+ const prev = deduped[deduped.length - 1];
660
+ if (prev && prev[0] === mapping[0] && prev[1] === mapping[1]) {
661
+ continue;
662
+ }
663
+ deduped.push(mapping);
664
+ }
665
+ return deduped;
666
+ }
667
+ function countLinesAndTerminateMap(code, map = []) {
668
+ const NEWLINE = /\r\n?|\n|\u2028|\u2029/g;
669
+ let lineCount = 1;
670
+ let lastLineStart = 0;
671
+ for (const match of code.matchAll(NEWLINE)) {
672
+ lineCount++;
673
+ lastLineStart = match.index + match[0].length;
674
+ }
675
+ const lastLineLength = code.length - lastLineStart;
676
+ const lastLineIndex1Based = lineCount;
677
+ const lastLineNextColumn0Based = lastLineLength;
678
+ const lastMapping = map[map.length - 1];
679
+ const terminatingMapping = [lastLineIndex1Based, lastLineNextColumn0Based];
680
+ if (!lastMapping || lastMapping[0] !== terminatingMapping[0] || lastMapping[1] !== terminatingMapping[1]) {
681
+ return {
682
+ lineCount,
683
+ map: map.concat([terminatingMapping])
684
+ };
685
+ }
686
+ return {
687
+ lineCount,
688
+ map: [...map]
689
+ };
690
+ }
691
+ function wrapJson(source, options) {
692
+ const globalPrefix = options?.globalPrefix || "";
693
+ const factory = ["function (global, require, _importDefaultUnused, _importAllUnused, module, exports, _dependencyMapUnused) {", ` module.exports = ${source};`, "}"].join("\n");
694
+ if (options?.moduleId !== void 0) {
695
+ const depIds = options.dependencyIds ? JSON.stringify(options.dependencyIds) : "[]";
696
+ return `${globalPrefix}__d(${factory}, ${JSON.stringify(options.moduleId)}, ${depIds});`;
697
+ }
698
+ return `${globalPrefix}__d(${factory});`;
699
+ }
700
+ function wrapModule(code, options) {
701
+ const globalPrefix = options?.globalPrefix || "";
702
+ const depMap = options?.dependencyMapName || "_dependencyMap";
703
+ const header = `function (global, _$$_REQUIRE, _$$_IMPORT_DEFAULT, _$$_IMPORT_ALL, module, exports, ${depMap}) {`;
704
+ const requireAlias = options?.requireAlias !== false ? "var require = _$$_REQUIRE;\n" : "";
705
+ const footer = `}`;
706
+ if (options?.moduleId !== void 0) {
707
+ const depIds = options.dependencyIds ? JSON.stringify(options.dependencyIds) : "[]";
708
+ return `${globalPrefix}__d(${header}
709
+ ${requireAlias}${code}
710
+ ${footer}, ${JSON.stringify(options.moduleId)}, ${depIds});`;
711
+ }
712
+ return `${globalPrefix}__d(${header}
713
+ ${requireAlias}${code}
714
+ ${footer});`;
715
+ }
716
+ function getDependencyKey(name, isESM, asyncType = null, contextParams) {
717
+ let key = `${name}\0${isESM ? "import" : "require"}`;
718
+ if (asyncType != null) {
719
+ key += `\0${asyncType}`;
720
+ }
721
+ if (contextParams) {
722
+ key += ["", "context", String(contextParams.recursive), String(contextParams.filter.pattern), String(contextParams.filter.flags), contextParams.mode].join("\0");
723
+ }
724
+ return key;
725
+ }
726
+ function rewriteDependencyCalls(code, dependencies, depMapName = "_dependencyMap", filename = "module.js", asyncRequirePath = "metro-runtime/src/modules/asyncRequire") {
727
+ const ms = new import_magic_string.default(code);
728
+ const emptyResult = {
729
+ code,
730
+ map: ms.generateMap({
731
+ source: filename,
732
+ hires: true,
733
+ includeContent: true
734
+ }),
735
+ toString() {
736
+ return code;
737
+ }
738
+ };
739
+ if (dependencies.length === 0) return emptyResult;
740
+ let parsed;
741
+ try {
742
+ parsed = (0, import_oxc_parser.parseSync)(filename, code, {
743
+ lang: langForFilename(filename)
744
+ });
745
+ } catch (err) {
746
+ throw new Error(`[vxrn/metro] Failed to parse ${filename} for dependency rewriting: ${err.message || err}`);
747
+ }
748
+ if (parsed?.errors?.length) {
749
+ throw new Error(`[vxrn/metro] Failed to parse ${filename} for dependency rewriting: ${parsed.errors[0].message}`);
750
+ }
751
+ if (!parsed?.program) return emptyResult;
752
+ const contextLiteralBindings = collectModuleLiteralBindings(parsed.program);
753
+ const scopeTracker = new ScopeTracker();
754
+ collectHoistedBindings(parsed.program, scopeTracker.currentScope());
755
+ collectBlockBindings(parsed.program.body, scopeTracker.currentScope());
756
+ for (const stmt of parsed.program.body || []) {
757
+ if (stmt.type === "ImportDeclaration") {
758
+ for (const spec of stmt.specifiers || []) {
759
+ if (spec.local?.name) {
760
+ scopeTracker.add(spec.local.name);
761
+ }
762
+ }
763
+ }
764
+ }
765
+ function walk(node) {
766
+ if (!node || typeof node !== "object") return;
767
+ let pushedScope = false;
768
+ if (node.type === "FunctionDeclaration" || node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression") {
769
+ scopeTracker.enter();
770
+ pushedScope = true;
771
+ for (const param of node.params || []) {
772
+ scopeTracker.addPattern(param);
773
+ }
774
+ if (node.type === "FunctionExpression" && node.id?.name) {
775
+ scopeTracker.add(node.id.name);
776
+ }
777
+ if (node.body) {
778
+ collectHoistedBindings(node.body, scopeTracker.currentScope());
779
+ }
780
+ } else if (node.type === "BlockStatement") {
781
+ scopeTracker.enter();
782
+ pushedScope = true;
783
+ collectBlockBindings(node.body, scopeTracker.currentScope());
784
+ } else if (node.type === "CatchClause") {
785
+ scopeTracker.enter();
786
+ pushedScope = true;
787
+ if (node.param) {
788
+ scopeTracker.addPattern(node.param);
789
+ }
790
+ } else if (node.type === "ForStatement" || node.type === "ForInStatement" || node.type === "ForOfStatement") {
791
+ const decl = node.type === "ForStatement" ? node.init : node.left;
792
+ if (decl?.type === "VariableDeclaration" && decl.kind !== "var") {
793
+ scopeTracker.enter();
794
+ pushedScope = true;
795
+ for (const d of decl.declarations || []) {
796
+ scopeTracker.addPattern(d.id);
797
+ }
798
+ }
799
+ }
800
+ if (node.type === "ImportExpression" && node.source?.type === "Literal" && typeof node.source.value === "string") {
801
+ const depName = node.source.value;
802
+ const depKey = getDependencyKey(depName, true, "async");
803
+ const dep = dependencies.find(d => d.data.key === depKey) || dependencies.find(d => d.name === depName && d.data.asyncType === "async");
804
+ const asyncKey = getDependencyKey(asyncRequirePath, false, null);
805
+ const asyncDep = dependencies.find(d => d.data.key === asyncKey) || dependencies.find(d => d.name === asyncRequirePath && d.data.asyncType == null);
806
+ if (dep && asyncDep) {
807
+ const depIndex = dep.data.index ?? dependencies.indexOf(dep);
808
+ const asyncIndex = asyncDep.data.index ?? dependencies.indexOf(asyncDep);
809
+ ms.overwrite(node.start, node.end, `require(${depMapName}[${asyncIndex}], ${JSON.stringify(asyncRequirePath)})(${depMapName}[${depIndex}], ${depMapName}.paths, ${JSON.stringify(depName)})`);
810
+ }
811
+ } else if (node.type === "CallExpression" && node.callee?.type === "Identifier" && node.callee.name === "require" && !scopeTracker.isShadowed("require") && node.arguments?.length >= 1) {
812
+ const arg = node.arguments[0];
813
+ if (arg.type === "Literal" && typeof arg.value === "string") {
814
+ const depKey = getDependencyKey(arg.value, false, null);
815
+ const dep = dependencies.find(d => d.data.key === depKey) || dependencies.find(d => d.name === arg.value && d.data.asyncType == null);
816
+ if (dep) {
817
+ const index = dep.data.index ?? dependencies.indexOf(dep);
818
+ ms.overwrite(arg.start, arg.end, `${depMapName}[${index}], ${JSON.stringify(arg.value)}`);
819
+ }
820
+ }
821
+ } else if (
822
+ // metro rewrites require.context(dir, ...) down to a plain require of the
823
+ // single context module it registered for that directory.
824
+ node.type === "CallExpression" && node.callee?.type === "MemberExpression" && !node.callee.computed && node.callee.object?.type === "Identifier" && node.callee.object.name === "require" && node.callee.property?.type === "Identifier" && node.callee.property.name === "context" && !scopeTracker.isShadowed("require") && node.arguments?.length >= 1) {
825
+ const arg = node.arguments[0]?.type === "Identifier" ? contextLiteralBindings.get(node.arguments[0].name) : node.arguments[0];
826
+ if (arg?.type === "Literal" && typeof arg.value === "string") {
827
+ const dep = dependencies.find(d => d.name === arg.value && d.data.contextParams != null);
828
+ if (dep) {
829
+ const index = dep.data.index ?? dependencies.indexOf(dep);
830
+ ms.overwrite(node.start, node.end, `require(${depMapName}[${index}], ${JSON.stringify(arg.value)})`);
831
+ }
832
+ }
833
+ }
834
+ for (const key of Object.keys(node)) {
835
+ if (key === "start" || key === "end" || key === "loc" || key === "range" || key === "parent" || key === "comments") continue;
836
+ const child = node[key];
837
+ if (Array.isArray(child)) {
838
+ for (const item of child) walk(item);
839
+ } else if (child && typeof child === "object") {
840
+ walk(child);
841
+ }
842
+ }
843
+ if (pushedScope) {
844
+ scopeTracker.exit();
845
+ }
846
+ }
847
+ walk(parsed.program);
848
+ const resultString = ms.toString();
849
+ const map = ms.generateMap({
850
+ source: filename,
851
+ hires: true,
852
+ includeContent: true
853
+ });
854
+ return {
855
+ code: resultString,
856
+ map,
857
+ toString() {
858
+ return resultString;
859
+ }
860
+ };
861
+ }
862
+ function extractDependencies(code, filename, options) {
863
+ const asyncRequirePath = options?.asyncRequireModulePath || "metro-runtime/src/modules/asyncRequire";
864
+ const allowOptionalDependencies = options?.allowOptionalDependencies;
865
+ const lineOffsets = [0];
866
+ for (let i = 0; i < code.length; i++) {
867
+ if (code[i] === "\n") {
868
+ lineOffsets.push(i + 1);
869
+ }
870
+ }
871
+ function offsetToLoc(pos) {
872
+ let low = 0;
873
+ let high = lineOffsets.length - 1;
874
+ while (low <= high) {
875
+ const mid = low + high >> 1;
876
+ if (lineOffsets[mid] <= pos) {
877
+ low = mid + 1;
878
+ } else {
879
+ high = mid - 1;
880
+ }
881
+ }
882
+ const line = high + 1;
883
+ const column = pos - lineOffsets[high];
884
+ return {
885
+ line,
886
+ column
887
+ };
888
+ }
889
+ let parseResult;
890
+ try {
891
+ parseResult = (0, import_oxc_parser.parseSync)(filename, code, {
892
+ lang: langForFilename(filename)
893
+ });
894
+ } catch (err) {
895
+ throw new Error(`[vxrn/metro] Failed to parse ${filename} for dependency extraction: ${err.message || err}`);
896
+ }
897
+ if (parseResult?.errors?.length) {
898
+ throw new Error(`[vxrn/metro] Failed to parse ${filename} for dependency extraction: ${parseResult.errors[0].message}`);
899
+ }
900
+ if (!parseResult?.program) {
901
+ return [];
902
+ }
903
+ const depMap = /* @__PURE__ */new Map();
904
+ function addDep(name, isESM, asyncType, start, end, contextParams, isOptional) {
905
+ const key = getDependencyKey(name, isESM, asyncType, contextParams);
906
+ let entry = depMap.get(key);
907
+ const loc = {
908
+ start: offsetToLoc(start),
909
+ end: offsetToLoc(end)
910
+ };
911
+ if (!entry) {
912
+ entry = {
913
+ name,
914
+ data: {
915
+ key,
916
+ asyncType,
917
+ locs: [loc],
918
+ isESMImportAtSource: isESM,
919
+ isESMImport: isESM,
920
+ index: depMap.size,
921
+ ...(contextParams ? {
922
+ contextParams
923
+ } : {}),
924
+ ...(isOptional ? {
925
+ isOptional: true
926
+ } : {})
927
+ }
928
+ };
929
+ depMap.set(key, entry);
930
+ } else {
931
+ entry.data.locs.push(loc);
932
+ }
933
+ }
934
+ const moduleConsts = collectModuleLiteralBindings(parseResult.program);
935
+ function resolveConst(node) {
936
+ if (node?.type === "Identifier") return moduleConsts.get(node.name);
937
+ return node;
938
+ }
939
+ const ancestors = [];
940
+ function isOptionalHere(name) {
941
+ if (!allowOptionalDependencies) return false;
942
+ if (Array.isArray(allowOptionalDependencies.exclude)) {
943
+ if (allowOptionalDependencies.exclude.includes(name)) return false;
944
+ }
945
+ let sCount = 0;
946
+ for (let i = ancestors.length - 1; i >= 0 && sCount < 3; i--) {
947
+ const n = ancestors[i];
948
+ const isStatement = /(?:Statement|Declaration)$/.test(n.type);
949
+ if (!isStatement) continue;
950
+ if (n.type === "BlockStatement") {
951
+ const parent = ancestors[i - 1];
952
+ return parent?.type === "TryStatement" && parent.block === n;
953
+ }
954
+ sCount += 1;
955
+ }
956
+ return false;
957
+ }
958
+ const scopeTracker = new ScopeTracker();
959
+ collectHoistedBindings(parseResult.program, scopeTracker.currentScope());
960
+ collectBlockBindings(parseResult.program.body, scopeTracker.currentScope());
961
+ for (const stmt of parseResult.program.body || []) {
962
+ if (stmt.type === "ImportDeclaration") {
963
+ for (const spec of stmt.specifiers || []) {
964
+ if (spec.local?.name) {
965
+ scopeTracker.add(spec.local.name);
966
+ }
967
+ }
968
+ }
969
+ }
970
+ function walk(node) {
971
+ if (!node || typeof node !== "object") return;
972
+ let pushedScope = false;
973
+ ancestors.push(node);
974
+ if (node.type === "FunctionDeclaration" || node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression") {
975
+ scopeTracker.enter();
976
+ pushedScope = true;
977
+ for (const param of node.params || []) {
978
+ scopeTracker.addPattern(param);
979
+ }
980
+ if (node.type === "FunctionExpression" && node.id?.name) {
981
+ scopeTracker.add(node.id.name);
982
+ }
983
+ if (node.body) {
984
+ collectHoistedBindings(node.body, scopeTracker.currentScope());
985
+ }
986
+ } else if (node.type === "BlockStatement") {
987
+ scopeTracker.enter();
988
+ pushedScope = true;
989
+ collectBlockBindings(node.body, scopeTracker.currentScope());
990
+ } else if (node.type === "CatchClause") {
991
+ scopeTracker.enter();
992
+ pushedScope = true;
993
+ if (node.param) {
994
+ scopeTracker.addPattern(node.param);
995
+ }
996
+ } else if (node.type === "ForStatement" || node.type === "ForInStatement" || node.type === "ForOfStatement") {
997
+ const decl = node.type === "ForStatement" ? node.init : node.left;
998
+ if (decl?.type === "VariableDeclaration" && decl.kind !== "var") {
999
+ scopeTracker.enter();
1000
+ pushedScope = true;
1001
+ for (const d of decl.declarations || []) {
1002
+ scopeTracker.addPattern(d.id);
1003
+ }
1004
+ }
1005
+ }
1006
+ if (node.type === "ImportDeclaration" && node.source?.value) {
1007
+ if (node.importKind !== "type") {
1008
+ const hasValueSpecifier = !node.specifiers?.length || node.specifiers.some(s => s.importKind !== "type");
1009
+ if (hasValueSpecifier) {
1010
+ addDep(node.source.value, true, null, node.start, node.end);
1011
+ }
1012
+ }
1013
+ } else if ((node.type === "ExportNamedDeclaration" || node.type === "ExportAllDeclaration") && node.source?.value) {
1014
+ if (node.exportKind !== "type") {
1015
+ addDep(node.source.value, true, null, node.start, node.end);
1016
+ }
1017
+ } else if (node.type === "ImportExpression") {
1018
+ if (node.source?.type === "Literal" && typeof node.source.value === "string") {
1019
+ addDep(node.source.value, true, "async", node.start, node.end);
1020
+ addDep(asyncRequirePath, false, null, node.start, node.end);
1021
+ } else {
1022
+ throw new Error(`[vxrn/metro] Dynamic import with non-string literal is not supported by Metro in ${filename}`);
1023
+ }
1024
+ } else if (node.type === "CallExpression" && node.callee?.type === "Identifier" && node.callee.name === "require" && !scopeTracker.isShadowed("require")) {
1025
+ if (node.arguments?.[0]?.type === "Literal" && typeof node.arguments[0].value === "string") {
1026
+ addDep(node.arguments[0].value, false, null, node.start, node.end, void 0, node.arguments[0].value !== asyncRequirePath && isOptionalHere(node.arguments[0].value));
1027
+ }
1028
+ } else if (
1029
+ // require.context(dir, recursive?, filter?, mode?) registers a whole
1030
+ // directory as one dependency. one's router entry uses it for the route
1031
+ // tree, so dropping it silently omits every route from the bundle.
1032
+ node.type === "CallExpression" && node.callee?.type === "MemberExpression" && !node.callee.computed && node.callee.object?.type === "Identifier" && node.callee.object.name === "require" && node.callee.property?.type === "Identifier" && node.callee.property.name === "context" && !scopeTracker.isShadowed("require")) {
1033
+ const args = node.arguments || [];
1034
+ const dir = resolveConst(args[0]);
1035
+ if (dir?.type !== "Literal" || typeof dir.value !== "string") {
1036
+ throw new Error(`[vxrn/metro] First argument of require.context must be a string literal in ${filename}`);
1037
+ }
1038
+ if (args.length > 4) {
1039
+ throw new Error(`[vxrn/metro] Too many arguments provided to require.context in ${filename}. Expected 4, got: ${args.length}`);
1040
+ }
1041
+ let recursive = true;
1042
+ const recursiveArg = resolveConst(args[1]);
1043
+ if (recursiveArg) {
1044
+ if (recursiveArg.type !== "Literal" || typeof recursiveArg.value !== "boolean") {
1045
+ throw new Error(`[vxrn/metro] Second argument of require.context must be an optional boolean literal in ${filename}`);
1046
+ }
1047
+ recursive = recursiveArg.value;
1048
+ }
1049
+ let filter = {
1050
+ pattern: ".*",
1051
+ flags: ""
1052
+ };
1053
+ const filterArg = resolveConst(args[2]);
1054
+ if (filterArg) {
1055
+ if (filterArg.type !== "Literal" || !filterArg.regex) {
1056
+ throw new Error(`[vxrn/metro] Third argument of require.context must be an optional RegExp literal in ${filename}, instead found node of type: ${filterArg.type}`);
1057
+ }
1058
+ filter = {
1059
+ pattern: filterArg.regex.pattern,
1060
+ flags: filterArg.regex.flags || ""
1061
+ };
1062
+ }
1063
+ let mode = "sync";
1064
+ const modeArg = resolveConst(args[3]);
1065
+ if (modeArg) {
1066
+ const m = modeArg.type === "Literal" ? modeArg.value : void 0;
1067
+ if (m !== "sync" && m !== "eager" && m !== "lazy" && m !== "lazy-once") {
1068
+ throw new Error(`[vxrn/metro] require.context mode must be one of sync, eager, lazy, lazy-once in ${filename}`);
1069
+ }
1070
+ mode = m;
1071
+ }
1072
+ addDep(dir.value, false, null, node.start, node.end, {
1073
+ recursive,
1074
+ filter,
1075
+ mode
1076
+ });
1077
+ }
1078
+ for (const key of Object.keys(node)) {
1079
+ if (key === "start" || key === "end" || key === "loc" || key === "range" || key === "parent" || key === "comments") continue;
1080
+ const child = node[key];
1081
+ if (Array.isArray(child)) {
1082
+ for (const item of child) walk(item);
1083
+ } else if (child && typeof child === "object") {
1084
+ walk(child);
1085
+ }
1086
+ }
1087
+ ancestors.pop();
1088
+ if (pushedScope) {
1089
+ scopeTracker.exit();
1090
+ }
1091
+ }
1092
+ walk(parseResult.program);
1093
+ return Array.from(depMap.values());
1094
+ }
1095
+ function checkReservedStrings(sourceCode, config, options) {
1096
+ const reservedStrings = [];
1097
+ if (options.customTransformOptions?.unstable_staticHermesOptimizedRequire === true) {
1098
+ reservedStrings.push("_$$_METRO_MODULE_ID");
1099
+ }
1100
+ if (config.unstable_dependencyMapReservedName != null) {
1101
+ reservedStrings.push(config.unstable_dependencyMapReservedName);
1102
+ }
1103
+ for (const reservedString of reservedStrings) {
1104
+ const position = sourceCode.indexOf(reservedString);
1105
+ if (position > -1) {
1106
+ throw new SyntaxError("Source code contains the reserved string `" + reservedString + "` at character offset " + position);
1107
+ }
1108
+ }
1109
+ }
1110
+ let workletsConfigured = false;
1111
+ let oneNativeTransforms;
1112
+ function loadOneNativeTransforms(projectRoot) {
1113
+ if (oneNativeTransforms !== void 0) return oneNativeTransforms;
1114
+ try {
1115
+ const req = (0, import_node_module.createRequire)(import_node_path.default.resolve(projectRoot, "package.json"));
1116
+ oneNativeTransforms = req("one/native-transforms");
1117
+ } catch {
1118
+ oneNativeTransforms = null;
1119
+ }
1120
+ return oneNativeTransforms;
1121
+ }
1122
+ async function configureWorkletsForWorker(projectRoot) {
1123
+ if (workletsConfigured) return;
1124
+ workletsConfigured = true;
1125
+ if (!projectRoot) return;
1126
+ const req = (0, import_node_module.createRequire)(import_node_path.default.resolve(projectRoot, "package.json"));
1127
+ let hasReanimated = false;
1128
+ try {
1129
+ req.resolve("react-native-reanimated/package.json");
1130
+ hasReanimated = true;
1131
+ } catch {
1132
+ try {
1133
+ req.resolve("react-native-worklets/package.json");
1134
+ hasReanimated = true;
1135
+ } catch {}
1136
+ }
1137
+ const {
1138
+ configureVXRNCompilerPlugin
1139
+ } = await import("@vxrn/compiler");
1140
+ configureVXRNCompilerPlugin({
1141
+ enableReanimated: hasReanimated
1142
+ });
1143
+ }
1144
+ async function transform(config, projectRoot, filename, data, options) {
1145
+ assertNoUnportedBabelPlugins(options);
1146
+ let sourceCode = typeof data === "string" ? data : data.toString("utf8");
1147
+ const environment = options.customTransformOptions?.environment;
1148
+ const isClientEnvironment = environment !== "node" && environment !== "react-server";
1149
+ if (isClientEnvironment && /[\\/]expo[\\/]virtual[\\/]env\.js$/.test(filename)) {
1150
+ if (options.dev) {
1151
+ const rel = import_node_path.default.relative(import_node_path.default.dirname(filename), projectRoot).split(import_node_path.default.sep).join("/");
1152
+ sourceCode = `const dotEnvModules = require.context(${JSON.stringify(rel)},false,/^\\.\\/\\.env/);
1153
+ export const env = !dotEnvModules.keys().length ? process.env : { ...process.env, ...['.env', '.env.development', '.env.local', '.env.development.local'].reduce((acc, file) => {
1154
+ return { ...acc, ...(dotEnvModules(file)?.default ?? {}) };
1155
+ }, {}) };`;
1156
+ } else {
1157
+ sourceCode = `export const env = new Proxy({}, {
1158
+ get(target, key) {
1159
+ throw new Error(\`Attempting to access internal environment variable "\${String(key)}" is not supported in production bundles.\`);
1160
+ },
1161
+ });`;
1162
+ }
1163
+ } else if (/(^|[\\/])\.env(\.(local|(development|production)(\.local)?))?$/.test(filename)) {
1164
+ const {
1165
+ parseEnvFile
1166
+ } = await import("@expo/metro-config/build/transform-worker/dot-env-development");
1167
+ sourceCode = `export default ${JSON.stringify(parseEnvFile(sourceCode, isClientEnvironment))};`;
1168
+ }
1169
+ checkReservedStrings(sourceCode, config, options);
1170
+ if (filename.endsWith(".json")) {
1171
+ try {
1172
+ JSON.parse(sourceCode);
1173
+ } catch (err) {
1174
+ throw new Error(`[vxrn/metro] JSON parse error in ${filename}: ${err.message || err}`);
1175
+ }
1176
+ let code2 = config.unstable_disableModuleWrapping === true ? `module.exports = ${sourceCode};` : wrapJson(sourceCode, {
1177
+ globalPrefix: config.globalPrefix,
1178
+ moduleId: options.moduleId,
1179
+ dependencyIds: options.dependencyIds
1180
+ });
1181
+ if (options.minify && options.unstable_transformProfile !== "hermes-canary" && options.unstable_transformProfile !== "hermes-stable" && config.minifierPath) {
1182
+ try {
1183
+ const minifier = require(config.minifierPath);
1184
+ const minified = await minifier({
1185
+ code: code2,
1186
+ config: config.minifierConfig,
1187
+ filename,
1188
+ map: []
1189
+ });
1190
+ code2 = minified.code;
1191
+ } catch (err) {
1192
+ throw new Error(`[vxrn/metro] Minifier failed for ${filename}: ${err.message || err}`);
1193
+ }
1194
+ }
1195
+ const {
1196
+ lineCount: lineCount2,
1197
+ map: map2
1198
+ } = countLinesAndTerminateMap(code2, []);
1199
+ const outputType = options.type === "asset" ? "js/module/asset" : options.type === "script" ? "js/script" : "js/module";
1200
+ return {
1201
+ dependencies: [],
1202
+ output: [{
1203
+ data: {
1204
+ code: code2,
1205
+ lineCount: lineCount2,
1206
+ map: map2,
1207
+ functionMap: null
1208
+ },
1209
+ type: outputType
1210
+ }]
1211
+ };
1212
+ }
1213
+ if (options.type === "asset") {
1214
+ const assetRegistryPath = config.assetRegistryPath || "react-native/Libraries/Image/AssetRegistry";
1215
+ let properDescriptor = null;
1216
+ const absolutePath = import_node_path.default.resolve(projectRoot, filename);
1217
+ if (import_node_fs.default.existsSync(absolutePath)) {
1218
+ try {
1219
+ let getAssetData;
1220
+ try {
1221
+ getAssetData = require("metro/private/Assets").getAssetData;
1222
+ } catch {
1223
+ getAssetData = require("metro/src/Assets").getAssetData;
1224
+ }
1225
+ if (typeof getAssetData === "function") {
1226
+ const rawData = await getAssetData(absolutePath, filename, config.assetPlugins || [], options.platform || "", config.publicPath || "/assets");
1227
+ const copied = {
1228
+ ...rawData
1229
+ };
1230
+ delete copied.files;
1231
+ delete copied.fileSystemLocation;
1232
+ delete copied.path;
1233
+ properDescriptor = copied;
1234
+ }
1235
+ } catch (err) {
1236
+ throw new Error(`[vxrn/metro] Asset resolution failed for ${filename}: ${err.message || err}`);
1237
+ }
1238
+ }
1239
+ if (!properDescriptor) {
1240
+ const ext = import_node_path.default.extname(filename).slice(1);
1241
+ const name = import_node_path.default.basename(filename, "." + ext);
1242
+ properDescriptor = {
1243
+ __packager_asset: true,
1244
+ httpServerLocation: config.publicPath || "/assets",
1245
+ width: void 0,
1246
+ height: void 0,
1247
+ scales: [1],
1248
+ hash: import_node_crypto.default.createHash("md5").update(sourceCode).digest("hex"),
1249
+ name,
1250
+ type: ext
1251
+ };
1252
+ }
1253
+ const assetDepMapName = config.unstable_dependencyMapReservedName || "_dependencyMap";
1254
+ const assetCode = `module.exports = require(${assetDepMapName}[0], ${JSON.stringify(assetRegistryPath)}).registerAsset(${JSON.stringify(properDescriptor)});`;
1255
+ let code2 = config.unstable_disableModuleWrapping === true ? assetCode : wrapModule(assetCode, {
1256
+ globalPrefix: config.globalPrefix,
1257
+ moduleId: options.moduleId,
1258
+ dependencyIds: options.dependencyIds,
1259
+ dependencyMapName: config.unstable_dependencyMapReservedName
1260
+ });
1261
+ const dependencies2 = [{
1262
+ name: assetRegistryPath,
1263
+ data: {
1264
+ key: getDependencyKey(assetRegistryPath, false, null),
1265
+ asyncType: null,
1266
+ locs: [],
1267
+ isESMImportAtSource: false,
1268
+ isESMImport: false,
1269
+ index: 0
1270
+ }
1271
+ }];
1272
+ const {
1273
+ lineCount: lineCount2,
1274
+ map: map2
1275
+ } = countLinesAndTerminateMap(code2, []);
1276
+ return {
1277
+ dependencies: dependencies2,
1278
+ output: [{
1279
+ data: {
1280
+ code: code2,
1281
+ lineCount: lineCount2,
1282
+ map: map2,
1283
+ functionMap: null
1284
+ },
1285
+ type: "js/module/asset"
1286
+ }]
1287
+ };
1288
+ }
1289
+ let code = sourceCode;
1290
+ const intermediateMaps = [];
1291
+ for (const nativeTransform of getNativeTransforms(options, projectRoot)) {
1292
+ const out = nativeTransform(code, {
1293
+ // absolute, unlike metro's own project-relative name. a transform that
1294
+ // matches on paths (include/exclude lists, node_modules skips) or stamps
1295
+ // a location into the output would otherwise get a different answer here
1296
+ // than the babel plugin it replaced, which is handed an absolute path.
1297
+ filename: import_node_path.default.isAbsolute(filename) ? filename : import_node_path.default.resolve(projectRoot, filename),
1298
+ platform: options.platform,
1299
+ dev: options.dev,
1300
+ projectRoot
1301
+ });
1302
+ if (typeof out === "string") code = out;
1303
+ }
1304
+ const oneRouterOptions = getOneRouterMetroOptions(options);
1305
+ if (oneRouterOptions) {
1306
+ code = applyOneRouterMetro(code, filename, oneRouterOptions);
1307
+ }
1308
+ try {
1309
+ const codegenRes = (0, import_compiler.transformReactNativeCodegen)(code, filename, projectRoot);
1310
+ if (codegenRes?.code) {
1311
+ code = codegenRes.code;
1312
+ if (codegenRes.map) {
1313
+ intermediateMaps.push(codegenRes.map);
1314
+ }
1315
+ }
1316
+ } catch (err) {
1317
+ throw new Error(`[vxrn/metro] React Native codegen failed for ${filename}: ${err.message || err}`);
1318
+ }
1319
+ const hasFlowPragma = code.includes("@flow");
1320
+ const isFlowCandidate = (filename.endsWith(".js") || filename.endsWith(".jsx")) && (hasFlowPragma || FLOW_FILE_PATTERN.test(filename) || code.includes("import type"));
1321
+ if (isFlowCandidate) {
1322
+ try {
1323
+ const fft = await import("fast-flow-transform");
1324
+ const flowTransform = fft.default || fft;
1325
+ const flowResult = await flowTransform({
1326
+ filename,
1327
+ source: code,
1328
+ sourcemap: true,
1329
+ dialect: "flow",
1330
+ format: "pretty"
1331
+ });
1332
+ if (flowResult?.code) {
1333
+ code = flowResult.code;
1334
+ if (flowResult.map) {
1335
+ intermediateMaps.push(typeof flowResult.map === "string" ? JSON.parse(flowResult.map) : flowResult.map);
1336
+ }
1337
+ }
1338
+ } catch (err) {
1339
+ throw new Error(`[vxrn/metro] Flow transform failed for ${filename}: ${err.message || err}`);
1340
+ }
1341
+ }
1342
+ const asyncRequirePath = config.asyncRequireModulePath || "metro-runtime/src/modules/asyncRequire";
1343
+ const aliases = getModuleResolverAliases(options);
1344
+ if (aliases && projectRoot) {
1345
+ const aliasKeys = Object.keys(aliases);
1346
+ if (aliasKeys.some(k => code.includes(k.endsWith("$") ? k.slice(0, -1) : k))) {
1347
+ code = applyModuleResolverAliases(code, filename, projectRoot, aliases);
1348
+ }
1349
+ }
1350
+ if (code.includes("process.env") || code.includes("import.meta")) {
1351
+ code = applyInlineEnvVars(code, filename, !options.dev, getImportMetaEnv(options));
1352
+ }
1353
+ if (code.includes("-only")) {
1354
+ code = applyEnvironmentGuard(code, filename);
1355
+ }
1356
+ const serverCodeRouterRoot = getRemoveServerCodeRouterRoot(options);
1357
+ if (serverCodeRouterRoot && projectRoot && !filename.includes("node_modules")) {
1358
+ const oneNativeTransforms2 = loadOneNativeTransforms(projectRoot);
1359
+ if (oneNativeTransforms2) {
1360
+ const shaken = await oneNativeTransforms2.transformTreeShakeClient(code, filename, projectRoot, serverCodeRouterRoot);
1361
+ if (shaken?.code) {
1362
+ code = shaken.code;
1363
+ }
1364
+ }
1365
+ }
1366
+ const dependencies = extractDependencies(code, filename, {
1367
+ asyncRequireModulePath: asyncRequirePath,
1368
+ allowOptionalDependencies: config.allowOptionalDependencies
1369
+ });
1370
+ const shouldRunReactCompiler = Boolean(options.customTransformOptions?.reactCompiler) || hasBabelPlugin(options, "babel-plugin-react-compiler") && isReactCompilerCandidate(filename) || code.includes('"use memo"') || code.includes("'use memo'");
1371
+ if (shouldRunReactCompiler) {
1372
+ try {
1373
+ const {
1374
+ transformOxcReactCompiler
1375
+ } = await import("@vxrn/compiler");
1376
+ const compilerRes = await transformOxcReactCompiler(filename, code, "19");
1377
+ if (compilerRes?.code) {
1378
+ code = compilerRes.code;
1379
+ if (compilerRes.map) {
1380
+ intermediateMaps.push(typeof compilerRes.map === "string" ? JSON.parse(compilerRes.map) : compilerRes.map);
1381
+ }
1382
+ }
1383
+ } catch (err) {
1384
+ throw new Error(`[vxrn/metro] React Compiler failed for ${filename}: ${err.message || err}`);
1385
+ }
1386
+ }
1387
+ await configureWorkletsForWorker(projectRoot);
1388
+ let shouldRunWorklets = Boolean(options.customTransformOptions?.worklets);
1389
+ if (!shouldRunWorklets) {
1390
+ const {
1391
+ shouldTransformWorklets
1392
+ } = await import("@vxrn/compiler");
1393
+ shouldRunWorklets = shouldTransformWorklets({
1394
+ id: filename,
1395
+ code
1396
+ });
1397
+ }
1398
+ if (shouldRunWorklets) {
1399
+ try {
1400
+ const {
1401
+ transformWorklets
1402
+ } = await import("@vxrn/compiler");
1403
+ const workletRes = await transformWorklets(filename, code, true, {
1404
+ projectRoot
1405
+ });
1406
+ if (workletRes?.code) {
1407
+ code = workletRes.code;
1408
+ if (workletRes.map) {
1409
+ intermediateMaps.push(typeof workletRes.map === "string" ? JSON.parse(workletRes.map) : workletRes.map);
1410
+ }
1411
+ }
1412
+ } catch (err) {
1413
+ throw new Error(`[vxrn/metro] Worklets transform failed for ${filename}: ${err.message || err}`);
1414
+ }
1415
+ }
1416
+ const lang = langForFilename(filename);
1417
+ const {
1418
+ transformSync: oxcTransform
1419
+ } = await import("oxc-transform");
1420
+ let oxcRes;
1421
+ try {
1422
+ oxcRes = oxcTransform(filename, code, {
1423
+ lang,
1424
+ // Hermes supports BigInt but not async generators or for-await-of, and no
1425
+ // single oxc target expresses that: es2020 keeps BigInt and leaves async
1426
+ // generators in, es2017 lowers them but rejects BigInt literals. oxc's
1427
+ // `hermes*` targets claim async generators are supported, which the device
1428
+ // disproves. So the level is chosen per module. A module using both is
1429
+ // vanishingly rare and fails loudly here rather than at runtime.
1430
+ target: HERMES_UNSUPPORTED_ASYNC_RE.test(code) ? "es2017" : "es2020",
1431
+ assumptions: {
1432
+ setPublicClassFields: true
1433
+ },
1434
+ jsx: {
1435
+ runtime: "automatic",
1436
+ development: Boolean(options.dev)
1437
+ },
1438
+ sourcemap: true
1439
+ });
1440
+ } catch (err) {
1441
+ throw new Error(`[vxrn/metro] Oxc transform failed for ${filename}: ${err.message || err}`);
1442
+ }
1443
+ if (oxcRes.errors?.length) {
1444
+ throw new Error(`[vxrn/metro] Oxc transform failed for ${filename}: ${oxcRes.errors[0].message || oxcRes.errors[0]}`);
1445
+ }
1446
+ code = oxcRes.code || code;
1447
+ if (oxcRes.map) {
1448
+ intermediateMaps.push(typeof oxcRes.map === "string" ? JSON.parse(oxcRes.map) : oxcRes.map);
1449
+ }
1450
+ if (options.type !== "script") {
1451
+ try {
1452
+ const esbuild = await import("esbuild");
1453
+ const esbuildRes = esbuild.transformSync(code, {
1454
+ loader: "js",
1455
+ format: "cjs",
1456
+ target: "es2020",
1457
+ sourcemap: true,
1458
+ sourcefile: filename
1459
+ });
1460
+ code = esbuildRes.code;
1461
+ if (esbuildRes.map) {
1462
+ intermediateMaps.push(typeof esbuildRes.map === "string" ? JSON.parse(esbuildRes.map) : esbuildRes.map);
1463
+ }
1464
+ } catch (err) {
1465
+ throw new Error(`[vxrn/metro] esbuild CJS lowering failed for ${filename}: ${err.message || err}`);
1466
+ }
1467
+ }
1468
+ try {
1469
+ const loopsRes = (0, import_compiler.transformHermesLoops)(code, filename);
1470
+ if (loopsRes) {
1471
+ code = loopsRes.code;
1472
+ for (const map2 of loopsRes.maps) {
1473
+ intermediateMaps.push(map2);
1474
+ }
1475
+ }
1476
+ } catch (err) {
1477
+ throw new Error(`[vxrn/metro] Hermes loop-binding transform failed for ${filename}: ${err.message || err}`);
1478
+ }
1479
+ const finalDeps = extractDependencies(code, filename, {
1480
+ asyncRequireModulePath: asyncRequirePath,
1481
+ allowOptionalDependencies: config.allowOptionalDependencies
1482
+ });
1483
+ const finalNames = new Set(finalDeps.map(d => d.name));
1484
+ const reconciled = dependencies.filter(d => finalNames.has(d.name));
1485
+ for (const injected of finalDeps) {
1486
+ if (reconciled.some(d => d.name === injected.name)) continue;
1487
+ reconciled.push(injected);
1488
+ }
1489
+ dependencies.length = 0;
1490
+ for (const dep of reconciled) {
1491
+ dependencies.push({
1492
+ ...dep,
1493
+ data: {
1494
+ ...dep.data,
1495
+ index: dependencies.length
1496
+ }
1497
+ });
1498
+ }
1499
+ const depMapName = config.unstable_dependencyMapReservedName || "_dependencyMap";
1500
+ if (options.type === "script") {
1501
+ const msScript = new import_magic_string.default(code);
1502
+ msScript.prepend(`(function (global) {
1503
+ `);
1504
+ msScript.append(`
1505
+ })(typeof globalThis !== 'undefined' ? globalThis : typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : this);`);
1506
+ code = msScript.toString();
1507
+ intermediateMaps.push(msScript.generateMap({
1508
+ source: filename,
1509
+ hires: true,
1510
+ includeContent: true
1511
+ }));
1512
+ } else if (config.unstable_disableModuleWrapping === true) {
1513
+ const rewriteRes = rewriteDependencyCalls(code, dependencies, depMapName, filename, asyncRequirePath);
1514
+ code = rewriteRes.code;
1515
+ if (rewriteRes.map) {
1516
+ intermediateMaps.push(rewriteRes.map);
1517
+ }
1518
+ } else {
1519
+ const rewriteRes = rewriteDependencyCalls(code, dependencies, depMapName, filename, asyncRequirePath);
1520
+ if (rewriteRes.map) {
1521
+ intermediateMaps.push(rewriteRes.map);
1522
+ }
1523
+ const msWrap = new import_magic_string.default(rewriteRes.code);
1524
+ const globalPrefix = config.globalPrefix || "";
1525
+ const header = `function (global, _$$_REQUIRE, _$$_IMPORT_DEFAULT, _$$_IMPORT_ALL, module, exports, ${depMapName}) {
1526
+ var require = _$$_REQUIRE;
1527
+ `;
1528
+ const footer = `
1529
+ }`;
1530
+ msWrap.prepend(`${globalPrefix}__d(${header}`);
1531
+ if (options.moduleId !== void 0) {
1532
+ const depIds = options.dependencyIds ? JSON.stringify(options.dependencyIds) : "[]";
1533
+ msWrap.append(`${footer}, ${JSON.stringify(options.moduleId)}, ${depIds});`);
1534
+ } else {
1535
+ msWrap.append(`${footer});`);
1536
+ }
1537
+ code = msWrap.toString();
1538
+ intermediateMaps.push(msWrap.generateMap({
1539
+ source: filename,
1540
+ hires: true,
1541
+ includeContent: true
1542
+ }));
1543
+ }
1544
+ if (options.minify && options.unstable_transformProfile !== "hermes-canary" && options.unstable_transformProfile !== "hermes-stable" && config.minifierPath) {
1545
+ try {
1546
+ const minifier = require(config.minifierPath);
1547
+ const minified = await minifier({
1548
+ code,
1549
+ config: config.minifierConfig,
1550
+ filename,
1551
+ map: []
1552
+ });
1553
+ code = minified.code;
1554
+ if (minified.map) {
1555
+ intermediateMaps.push(typeof minified.map === "string" ? JSON.parse(minified.map) : minified.map);
1556
+ }
1557
+ } catch (err) {
1558
+ throw new Error(`[vxrn/metro] Minifier failed for ${filename}: ${err.message || err}`);
1559
+ }
1560
+ }
1561
+ let rawMappings = [];
1562
+ if (intermediateMaps.length > 0) {
1563
+ const cleanMaps = intermediateMaps.map(m => typeof m === "string" ? JSON.parse(m) : m).filter(Boolean);
1564
+ if (cleanMaps.length > 0) {
1565
+ const composed = cleanMaps.length === 1 ? cleanMaps[0] : (0, import_remapping.default)(cleanMaps.slice().reverse(), () => null);
1566
+ rawMappings = convertSourceMapToMetroRawMappings(composed);
1567
+ }
1568
+ }
1569
+ const {
1570
+ lineCount,
1571
+ map
1572
+ } = countLinesAndTerminateMap(code, rawMappings);
1573
+ return {
1574
+ dependencies,
1575
+ output: [{
1576
+ data: {
1577
+ code,
1578
+ lineCount,
1579
+ map,
1580
+ functionMap: null
1581
+ },
1582
+ type: options.type === "script" ? "js/script" : "js/module"
1583
+ }]
1584
+ };
1585
+ }
1586
+ var metroNativeWorker_default = {
1587
+ transform,
1588
+ getCacheKey,
1589
+ wrapModule,
1590
+ wrapJson,
1591
+ extractDependencies,
1592
+ rewriteDependencyCalls,
1593
+ convertSourceMapToMetroRawMappings
1594
+ };