@vxrn/vite-plugin-metro 1.25.16 → 1.26.0

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