@vxrn/vite-plugin-metro 1.27.1 → 2.0.0-beta.101.1

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