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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/dist/cjs/metro-config/getMetroConfigFromViteConfig.cjs +20 -0
  2. package/dist/cjs/metro-config/getMetroConfigFromViteConfig.native.js +20 -0
  3. package/dist/cjs/metro-config/getMetroConfigFromViteConfig.native.js.map +1 -1
  4. package/dist/cjs/metro-config/patchMetroServerWithViteConfigAndMetroPluginOptions.cjs +2 -1
  5. package/dist/cjs/metro-config/patchMetroServerWithViteConfigAndMetroPluginOptions.native.js +2 -1
  6. package/dist/cjs/metro-config/patchMetroServerWithViteConfigAndMetroPluginOptions.native.js.map +1 -1
  7. package/dist/cjs/plugins/metroPlugin.native.js.map +1 -1
  8. package/dist/cjs/transformer/metroNativeWorker.cjs +1594 -0
  9. package/dist/cjs/transformer/metroNativeWorker.native.js +2678 -0
  10. package/dist/cjs/transformer/metroNativeWorker.native.js.map +1 -0
  11. package/dist/cjs/transformer/metroNativeWorker.test.cjs +813 -0
  12. package/dist/cjs/transformer/metroNativeWorker.test.native.js +920 -0
  13. package/dist/cjs/transformer/metroNativeWorker.test.native.js.map +1 -0
  14. package/dist/esm/metro-config/getMetroConfigFromViteConfig.mjs +20 -0
  15. package/dist/esm/metro-config/getMetroConfigFromViteConfig.mjs.map +1 -1
  16. package/dist/esm/metro-config/getMetroConfigFromViteConfig.native.js +20 -0
  17. package/dist/esm/metro-config/getMetroConfigFromViteConfig.native.js.map +1 -1
  18. package/dist/esm/metro-config/patchMetroServerWithViteConfigAndMetroPluginOptions.mjs +2 -1
  19. package/dist/esm/metro-config/patchMetroServerWithViteConfigAndMetroPluginOptions.mjs.map +1 -1
  20. package/dist/esm/metro-config/patchMetroServerWithViteConfigAndMetroPluginOptions.native.js +2 -1
  21. package/dist/esm/metro-config/patchMetroServerWithViteConfigAndMetroPluginOptions.native.js.map +1 -1
  22. package/dist/esm/plugins/metroPlugin.mjs.map +1 -1
  23. package/dist/esm/plugins/metroPlugin.native.js.map +1 -1
  24. package/dist/esm/transformer/metroNativeWorker.mjs +1535 -0
  25. package/dist/esm/transformer/metroNativeWorker.mjs.map +1 -0
  26. package/dist/esm/transformer/metroNativeWorker.native.js +2616 -0
  27. package/dist/esm/transformer/metroNativeWorker.native.js.map +1 -0
  28. package/dist/esm/transformer/metroNativeWorker.test.mjs +777 -0
  29. package/dist/esm/transformer/metroNativeWorker.test.mjs.map +1 -0
  30. package/dist/esm/transformer/metroNativeWorker.test.native.js +882 -0
  31. package/dist/esm/transformer/metroNativeWorker.test.native.js.map +1 -0
  32. package/package.json +22 -3
  33. package/src/metro-config/getMetroConfigFromViteConfig.ts +42 -0
  34. package/src/metro-config/patchMetroServerWithViteConfigAndMetroPluginOptions.ts +1 -0
  35. package/src/plugins/metroPlugin.ts +22 -0
  36. package/src/transformer/__fixtures__/exampleNativeTransform.cjs +17 -0
  37. package/src/transformer/metroNativeWorker.test.ts +1138 -0
  38. package/src/transformer/metroNativeWorker.ts +2385 -0
  39. package/src/transformer/types.ts +21 -0
  40. package/types/metro-config/getMetroConfigFromViteConfig.d.ts.map +1 -1
  41. package/types/metro-config/patchMetroServerWithViteConfigAndMetroPluginOptions.d.ts.map +1 -1
  42. package/types/plugins/metroPlugin.d.ts +22 -0
  43. package/types/plugins/metroPlugin.d.ts.map +1 -1
  44. package/types/transformer/metroNativeWorker.d.ts +251 -0
  45. package/types/transformer/metroNativeWorker.d.ts.map +1 -0
  46. package/types/transformer/metroNativeWorker.test.d.ts +2 -0
  47. package/types/transformer/metroNativeWorker.test.d.ts.map +1 -0
  48. package/types/transformer/types.d.ts +17 -0
  49. package/types/transformer/types.d.ts.map +1 -1
@@ -0,0 +1,1138 @@
1
+ import { beforeEach, describe, expect, it, vi } from 'vitest'
2
+ import * as babel from '@babel/core'
3
+ import * as vm from 'node:vm'
4
+ import { parseSync } from 'oxc-parser'
5
+ import * as fs from 'node:fs'
6
+ import * as path from 'node:path'
7
+ import {
8
+ transform,
9
+ getCacheKey,
10
+ wrapModule,
11
+ wrapJson,
12
+ extractDependencies,
13
+ rewriteDependencyCalls,
14
+ countLinesAndTerminateMap,
15
+ applyInlineEnvVars,
16
+ assertNoUnportedBabelPlugins,
17
+ applyEnvironmentGuard,
18
+ getRemoveServerCodeRouterRoot,
19
+ } from './metroNativeWorker'
20
+ import { buildMetroConfigInputFromViteConfig } from '../metro-config/getMetroConfigFromViteConfig'
21
+
22
+ const babelCalls = {
23
+ transform: 0,
24
+ transformSync: 0,
25
+ transformAsync: 0,
26
+ transformFromAstSync: 0,
27
+ parse: 0,
28
+ parseSync: 0,
29
+ }
30
+
31
+ vi.mock('@babel/core', async (importOriginal) => {
32
+ const actual = await importOriginal<typeof import('@babel/core')>()
33
+ return {
34
+ ...actual,
35
+ transform: vi.fn((...args: any[]) => {
36
+ babelCalls.transform++
37
+ return (actual.transform as any)(...args)
38
+ }),
39
+ transformSync: vi.fn((...args: any[]) => {
40
+ babelCalls.transformSync++
41
+ return (actual.transformSync as any)(...args)
42
+ }),
43
+ transformAsync: vi.fn((...args: any[]) => {
44
+ babelCalls.transformAsync++
45
+ return (actual.transformAsync as any)(...args)
46
+ }),
47
+ transformFromAstSync: vi.fn((...args: any[]) => {
48
+ babelCalls.transformFromAstSync++
49
+ return (actual.transformFromAstSync as any)(...args)
50
+ }),
51
+ parse: vi.fn((...args: any[]) => {
52
+ babelCalls.parse++
53
+ return (actual.parse as any)(...args)
54
+ }),
55
+ parseSync: vi.fn((...args: any[]) => {
56
+ babelCalls.parseSync++
57
+ return (actual.parseSync as any)(...args)
58
+ }),
59
+ }
60
+ })
61
+
62
+ // module scope so every describe in this file can assert it, not just the first
63
+ beforeEach(() => {
64
+ babelCalls.transform = 0
65
+ babelCalls.transformSync = 0
66
+ babelCalls.transformAsync = 0
67
+ babelCalls.transformFromAstSync = 0
68
+ babelCalls.parse = 0
69
+ babelCalls.parseSync = 0
70
+ })
71
+
72
+ function assertZeroBabelCalls() {
73
+ expect(babelCalls.transform).toBe(0)
74
+ expect(babelCalls.transformSync).toBe(0)
75
+ expect(babelCalls.transformAsync).toBe(0)
76
+ expect(babelCalls.transformFromAstSync).toBe(0)
77
+ expect(babelCalls.parse).toBe(0)
78
+ expect(babelCalls.parseSync).toBe(0)
79
+ }
80
+
81
+ describe('metroNativeWorker', () => {
82
+ it('extracts all dependencies with oxc-parser and zero Babel', () => {
83
+ const code = `
84
+ import React, { useState } from 'react'
85
+ import * as RN from 'react-native'
86
+ import './global.css'
87
+ import type { UserType } from './user-types'
88
+ export { Button } from './Button'
89
+ export * from './icons'
90
+ export type { ThemeType } from './theme-types'
91
+ const helper = require('./helper')
92
+ async function loadAsync() {
93
+ const dyn = await import('./dynamic-module')
94
+ }
95
+ `
96
+
97
+ const deps = extractDependencies(code, 'TestComponent.tsx')
98
+ assertZeroBabelCalls()
99
+
100
+ const names = deps.map((d) => d.name)
101
+ expect(names).toContain('react')
102
+ expect(names).toContain('react-native')
103
+ expect(names).toContain('./global.css')
104
+ expect(names).toContain('./Button')
105
+ expect(names).toContain('./icons')
106
+ expect(names).toContain('./helper')
107
+ expect(names).toContain('./dynamic-module')
108
+
109
+ // Type-only imports and exports should NOT be extracted as runtime dependencies
110
+ expect(names).not.toContain('./user-types')
111
+ expect(names).not.toContain('./theme-types')
112
+
113
+ // ESM import flags
114
+ const reactDep = deps.find((d) => d.name === 'react')!
115
+ expect(reactDep.data.isESMImportAtSource).toBe(true)
116
+ expect(reactDep.data.asyncType).toBeNull()
117
+ expect(reactDep.data.locs.length).toBeGreaterThan(0)
118
+ // metro's unable-to-resolve error path reads loc.start.line and loc.end.line,
119
+ // so a flat {line, column} makes that error throw and hide the real failure.
120
+ const loc = reactDep.data.locs[0]
121
+ expect(loc.start.line).toBeGreaterThan(0)
122
+ expect(loc.start.column).toBeGreaterThanOrEqual(0)
123
+ expect(loc.end.line).toBeGreaterThanOrEqual(loc.start.line)
124
+ expect(loc.end.column).toBeGreaterThanOrEqual(0)
125
+
126
+ // CJS require flag
127
+ const helperDep = deps.find((d) => d.name === './helper')!
128
+ expect(helperDep.data.isESMImportAtSource).toBe(false)
129
+ expect(helperDep.data.asyncType).toBeNull()
130
+
131
+ // Dynamic import flag
132
+ const dynamicDep = deps.find((d) => d.name === './dynamic-module')!
133
+ expect(dynamicDep.data.asyncType).toBe('async')
134
+ })
135
+
136
+ it('marks requires inside a try block optional', () => {
137
+ // optional native modules are required exactly this way. without
138
+ // data.isOptional metro fails the whole build when one is absent.
139
+ const code = `
140
+ let worklets
141
+ try {
142
+ worklets = require('react-native-worklets-core')
143
+ } catch {}
144
+ const always = require('./always-there')
145
+ `
146
+
147
+ const off = extractDependencies(code, 'setup.js')
148
+ expect(off.find((d) => d.name === 'react-native-worklets-core')!.data.isOptional).toBeUndefined()
149
+
150
+ const on = extractDependencies(code, 'setup.js', { allowOptionalDependencies: true })
151
+ expect(on.find((d) => d.name === 'react-native-worklets-core')!.data.isOptional).toBe(true)
152
+ expect(on.find((d) => d.name === './always-there')!.data.isOptional).toBeUndefined()
153
+
154
+ const excluded = extractDependencies(code, 'setup.js', {
155
+ allowOptionalDependencies: { exclude: ['react-native-worklets-core'] },
156
+ })
157
+ expect(
158
+ excluded.find((d) => d.name === 'react-native-worklets-core')!.data.isOptional
159
+ ).toBeUndefined()
160
+ })
161
+
162
+ it('wraps modules in Metro CommonJS format with and without moduleId', () => {
163
+ const code = 'exports.val = 123;'
164
+
165
+ const wrappedWithoutId = wrapModule(code)
166
+ expect(wrappedWithoutId).toContain(
167
+ '__d(function (global, _$$_REQUIRE, _$$_IMPORT_DEFAULT, _$$_IMPORT_ALL, module, exports, _dependencyMap) {'
168
+ )
169
+ expect(wrappedWithoutId).toContain('var require = _$$_REQUIRE;')
170
+ expect(wrappedWithoutId).toContain('exports.val = 123;')
171
+ expect(wrappedWithoutId.endsWith(');')).toBe(true)
172
+
173
+ const wrappedWithId = wrapModule(code, {
174
+ moduleId: 99,
175
+ dependencyIds: [1, 2, 3],
176
+ })
177
+ expect(wrappedWithId).toContain(', 99, [1,2,3]);')
178
+ })
179
+
180
+ it('transforms TSX with React JSX, Hermes lowering, and ZERO Babel', async () => {
181
+ const sourceCode = `
182
+ import React from 'react'
183
+ import { View, Text } from 'react-native'
184
+ const helper = require('./helper')
185
+
186
+ export class Greeter extends React.Component {
187
+ greeting = 'Hello from Native'
188
+
189
+ async fetchGreeting() {
190
+ return this.greeting
191
+ }
192
+
193
+ render() {
194
+ return (
195
+ <View testID="greeter">
196
+ <Text>{this.greeting}</Text>
197
+ </View>
198
+ )
199
+ }
200
+ }
201
+ `
202
+
203
+ const result = await transform(
204
+ {},
205
+ '/project',
206
+ 'Greeter.tsx',
207
+ Buffer.from(sourceCode, 'utf8'),
208
+ { dev: true, platform: 'ios', type: 'module' }
209
+ )
210
+
211
+ // Verify ZERO Babel calls
212
+ assertZeroBabelCalls()
213
+
214
+ expect(result.output).toHaveLength(1)
215
+ const output = result.output[0]
216
+ expect(output.type).toBe('js/module')
217
+ expect(output.data.lineCount).toBeGreaterThan(0)
218
+ expect(output.data.map.length).toBeGreaterThan(0)
219
+
220
+ const code = output.data.code
221
+
222
+ // Module wrapping check
223
+ expect(code).toContain(
224
+ '__d(function (global, _$$_REQUIRE, _$$_IMPORT_DEFAULT, _$$_IMPORT_ALL, module, exports, _dependencyMap) {'
225
+ )
226
+ expect(code).toContain('var require = _$$_REQUIRE;')
227
+
228
+ // JSX transformed (no raw JSX tags remain)
229
+ expect(code).not.toContain('<View')
230
+ expect(code).not.toContain('<Text')
231
+
232
+ // Hermes lowering applied (class field property lowered to constructor)
233
+ expect(code).toContain('this.greeting = "Hello from Native"')
234
+
235
+ // Dependencies extracted
236
+ const depNames = result.dependencies.map((d) => d.name)
237
+ expect(depNames).toContain('react')
238
+ expect(depNames).toContain('react-native')
239
+ expect(depNames).toContain('./helper')
240
+ expect(depNames).toContain('react/jsx-dev-runtime')
241
+ })
242
+
243
+ it('lowers async generators, including the method shorthand Hermes also rejects', async () => {
244
+ // each form goes through on its own, so a detector that misses one cannot be
245
+ // covered for by another form sharing the module.
246
+ const sources = {
247
+ // the shorthand the device caught: `async *name()` in a class body.
248
+ 'cursor.ts': `
249
+ export class Cursor {
250
+ async *rows() {
251
+ yield await Promise.resolve(1)
252
+ }
253
+ }
254
+ `,
255
+ 'stream.ts': `
256
+ export async function* stream() {
257
+ yield 1
258
+ }
259
+ `,
260
+ 'drain.ts': `
261
+ export async function drain(src) {
262
+ for await (const x of src) {
263
+ console.log(x)
264
+ }
265
+ }
266
+ `,
267
+ }
268
+
269
+ for (const [filename, sourceCode] of Object.entries(sources)) {
270
+ const result = await transform(
271
+ {},
272
+ '/project',
273
+ filename,
274
+ Buffer.from(sourceCode, 'utf8'),
275
+ { dev: true, platform: 'ios', type: 'module' }
276
+ )
277
+
278
+ assertZeroBabelCalls()
279
+
280
+ const code = result.output[0].data.code
281
+ // hermes rejects all three of these at parse time, so none may survive.
282
+ expect(code, filename).not.toMatch(/\basync\s+function\s*\*/)
283
+ expect(code, filename).not.toMatch(/\basync\s*\*\s*[\w$[]/)
284
+ expect(code, filename).not.toMatch(/\bfor\s+await\s*\(/)
285
+ }
286
+ })
287
+
288
+ it('handles JSON files without Babel', async () => {
289
+ const jsonSource = JSON.stringify({ name: 'my-package', version: '1.0.0' })
290
+ const result = await transform(
291
+ {},
292
+ '/project',
293
+ 'package.json',
294
+ Buffer.from(jsonSource, 'utf8'),
295
+ { dev: true, platform: 'ios', type: 'module' }
296
+ )
297
+
298
+ assertZeroBabelCalls()
299
+ expect(result.dependencies).toEqual([])
300
+ expect(result.output).toHaveLength(1)
301
+ expect(result.output[0].type).toBe('js/module')
302
+ expect(result.output[0].data.code).toContain('module.exports = {"name":"my-package","version":"1.0.0"}')
303
+ expect(result.output[0].data.code).toContain('__d(function (global, require')
304
+ })
305
+
306
+ it('handles Asset files without Babel', async () => {
307
+ const result = await transform(
308
+ {
309
+ assetRegistryPath: 'react-native/Libraries/Image/AssetRegistry',
310
+ publicPath: '/assets',
311
+ },
312
+ '/project',
313
+ 'logo.png',
314
+ Buffer.from('fake-png-binary-data', 'utf8'),
315
+ { dev: true, platform: 'ios', type: 'asset' }
316
+ )
317
+
318
+ assertZeroBabelCalls()
319
+ expect(result.output[0].type).toBe('js/module/asset')
320
+ expect(result.output[0].data.code).toContain('registerAsset(')
321
+ expect(result.output[0].data.code).toContain('__d(function')
322
+
323
+ const depNames = result.dependencies.map((d) => d.name)
324
+ expect(depNames).toContain('react-native/Libraries/Image/AssetRegistry')
325
+ })
326
+
327
+ it('handles Flow files by stripping types without Babel', async () => {
328
+ const flowSource = `
329
+ // @flow
330
+ function add(a: number, b: number): number {
331
+ return a + b;
332
+ }
333
+ export default add;
334
+ `
335
+
336
+ const result = await transform(
337
+ {},
338
+ '/project',
339
+ 'math.js',
340
+ Buffer.from(flowSource, 'utf8'),
341
+ { dev: false, platform: 'ios', type: 'module' }
342
+ )
343
+
344
+ assertZeroBabelCalls()
345
+ expect(result.output[0].data.code).not.toContain(': number')
346
+ expect(result.output[0].data.code).toContain('function add(a, b)')
347
+ })
348
+
349
+ it('generates a deterministic cache key without Babel', () => {
350
+ const key1 = getCacheKey({ globalPrefix: '__one_', minifierPath: 'terser' }, { projectRoot: '/app' })
351
+ const key2 = getCacheKey({ globalPrefix: '__one_', minifierPath: 'terser' }, { projectRoot: '/app' })
352
+ const key3 = getCacheKey({ globalPrefix: '__other_' }, { projectRoot: '/app' })
353
+
354
+ assertZeroBabelCalls()
355
+ expect(key1).toBe(key2)
356
+ expect(key1).not.toBe(key3)
357
+ expect(typeof key1).toBe('string')
358
+ expect(key1.length).toBe(64) // SHA-256 hex
359
+ })
360
+
361
+ it('correctly sets transformerPath in buildMetroConfigInputFromViteConfig when active', async () => {
362
+ const mockViteConfig = { root: process.cwd() } as any
363
+
364
+ // transformerPath is read by metro at the top level of the config. asserting
365
+ // it under `transformer` passes while metro silently keeps its own worker,
366
+ // so both the presence and the nesting are checked here.
367
+
368
+ // Default: the no-babel worker, with nothing configured.
369
+ delete process.env.ONE_METRO_NATIVE_TRANSFORMS
370
+ const configDefault = await buildMetroConfigInputFromViteConfig(mockViteConfig, {})
371
+ expect(configDefault.defaultConfig.transformerPath).toContain('metroNativeWorker')
372
+ expect(configDefault.defaultConfig.transformer.transformerPath).toBeUndefined()
373
+
374
+ // Opting back into babel via metroPluginOptions leaves expo's default
375
+ // worker in the key, which is itself proof that top level is where metro
376
+ // reads it from.
377
+ const configOptOff = await buildMetroConfigInputFromViteConfig(mockViteConfig, {
378
+ nativeTransforms: false,
379
+ })
380
+ expect(configOptOff.defaultConfig.transformerPath).not.toContain('metroNativeWorker')
381
+
382
+ // Opting back into babel for one run via the environment variable
383
+ process.env.ONE_METRO_NATIVE_TRANSFORMS = '0'
384
+ const configEnvOff = await buildMetroConfigInputFromViteConfig(mockViteConfig, {})
385
+ expect(configEnvOff.defaultConfig.transformerPath).not.toContain('metroNativeWorker')
386
+
387
+ // and the env var wins over an option that asked for babel
388
+ process.env.ONE_METRO_NATIVE_TRANSFORMS = '1'
389
+ const configEnvOn = await buildMetroConfigInputFromViteConfig(mockViteConfig, {
390
+ nativeTransforms: false,
391
+ })
392
+ expect(configEnvOn.defaultConfig.transformerPath).toContain('metroNativeWorker')
393
+ delete process.env.ONE_METRO_NATIVE_TRANSFORMS
394
+ })
395
+
396
+ it('transforms and executes a real 2-module Metro bundle through metro-runtime require polyfill', async () => {
397
+ // Probe 1 verification:
398
+ // Module 2 (dep.js): exports a value
399
+ // Module 1 (a.js): requires dep.js using Metro dependency ABI and exports computed result
400
+ const depSource = 'exports.value = 42;'
401
+ const aSource = 'const dep = require("./dep"); module.exports = { doubled: dep.value * 2 };'
402
+
403
+ // Transform dep.js (Module 2)
404
+ const depRes = await transform(
405
+ {},
406
+ '/project',
407
+ 'dep.js',
408
+ Buffer.from(depSource, 'utf8'),
409
+ {
410
+ dev: false,
411
+ platform: 'ios',
412
+ type: 'module',
413
+ moduleId: 2,
414
+ dependencyIds: [],
415
+ } as any
416
+ )
417
+
418
+ // Transform a.js (Module 1) which depends on dep.js (dependency slot 0 -> moduleId 2)
419
+ const aRes = await transform(
420
+ {},
421
+ '/project',
422
+ 'a.js',
423
+ Buffer.from(aSource, 'utf8'),
424
+ {
425
+ dev: false,
426
+ platform: 'ios',
427
+ type: 'module',
428
+ moduleId: 1,
429
+ dependencyIds: [2],
430
+ } as any
431
+ )
432
+
433
+ assertZeroBabelCalls()
434
+
435
+ // Verify dependency extraction
436
+ expect(aRes.dependencies).toHaveLength(1)
437
+ expect(aRes.dependencies[0].name).toBe('./dep')
438
+
439
+ // Verify dependency call rewriting to Metro ABI
440
+ const aEmittedCode = aRes.output[0].data.code
441
+ expect(aEmittedCode).toContain('require(_dependencyMap[0], "./dep")')
442
+
443
+ // Execute through REAL Metro runtime polyfill
444
+ const polyfillPath = require.resolve('metro-runtime/src/polyfills/require.js')
445
+ const polyfillCode = fs.readFileSync(polyfillPath, 'utf8')
446
+
447
+ const contextObj = {
448
+ __DEV__: false,
449
+ __METRO_GLOBAL_PREFIX__: '',
450
+ console: console,
451
+ } as any
452
+ contextObj.global = contextObj
453
+ vm.createContext(contextObj)
454
+ vm.runInContext(polyfillCode, contextObj)
455
+
456
+ // Register module 2 and module 1 in the Metro runtime
457
+ vm.runInContext(depRes.output[0].data.code, contextObj)
458
+ vm.runInContext(aEmittedCode, contextObj)
459
+
460
+ // Execute Module 1 via Metro's require entrypoint
461
+ const executedExports = vm.runInContext('global.__r(1)', contextObj)
462
+ expect(executedExports).toEqual({ doubled: 84 })
463
+ })
464
+
465
+ it('transforms and executes a 2-module Metro bundle with ESM imports in dev mode', async () => {
466
+ const depSource = 'export const greeting = "Hello Metro Native";'
467
+ const aSource = 'import { greeting } from "./dep"; export const message = greeting.toUpperCase();'
468
+
469
+ // Transform dep.js (Module 2)
470
+ const depRes = await transform(
471
+ {},
472
+ '/project',
473
+ 'dep.js',
474
+ Buffer.from(depSource, 'utf8'),
475
+ {
476
+ dev: true,
477
+ platform: 'ios',
478
+ type: 'module',
479
+ moduleId: 2,
480
+ dependencyIds: [],
481
+ } as any
482
+ )
483
+
484
+ // Transform a.js (Module 1) depending on dep.js (dependency slot 0 -> moduleId 2)
485
+ const aRes = await transform(
486
+ {},
487
+ '/project',
488
+ 'a.js',
489
+ Buffer.from(aSource, 'utf8'),
490
+ {
491
+ dev: true,
492
+ platform: 'ios',
493
+ type: 'module',
494
+ moduleId: 1,
495
+ dependencyIds: [2],
496
+ } as any
497
+ )
498
+
499
+ assertZeroBabelCalls()
500
+
501
+ const polyfillPath = require.resolve('metro-runtime/src/polyfills/require.js')
502
+ const polyfillCode = fs.readFileSync(polyfillPath, 'utf8')
503
+
504
+ const contextObj = {
505
+ __DEV__: true,
506
+ __METRO_GLOBAL_PREFIX__: '',
507
+ console: console,
508
+ } as any
509
+ contextObj.global = contextObj
510
+ vm.createContext(contextObj)
511
+ vm.runInContext(polyfillCode, contextObj)
512
+
513
+ vm.runInContext(depRes.output[0].data.code, contextObj)
514
+ vm.runInContext(aRes.output[0].data.code, contextObj)
515
+
516
+ const executedExports = vm.runInContext('global.__r(1)', contextObj)
517
+ expect(executedExports.message).toBe('HELLO METRO NATIVE')
518
+ })
519
+
520
+ it('respects lexical scope shadowing for require calls (Astra probe)', async () => {
521
+ // Exact probe from Astra:
522
+ // function f(require){return require("./local")}; module.exports=f(x=>x);
523
+ // require is shadowed by parameter: must NOT extract ./local, and must NOT rewrite require
524
+ const input = 'function f(require){return require("./local")}; module.exports=f(x=>x);'
525
+
526
+ const res = await transform(
527
+ {},
528
+ '/project',
529
+ 'shadowed.js',
530
+ Buffer.from(input, 'utf8'),
531
+ {
532
+ dev: false,
533
+ platform: 'ios',
534
+ type: 'module',
535
+ moduleId: 1,
536
+ dependencyIds: [],
537
+ } as any
538
+ )
539
+
540
+ assertZeroBabelCalls()
541
+
542
+ // 1. Dependency must NOT be extracted
543
+ expect(res.dependencies).toHaveLength(0)
544
+
545
+ // 2. Emitted code must NOT rewrite local require to _dependencyMap
546
+ const emitted = res.output[0].data.code
547
+ expect(emitted).not.toContain('_dependencyMap[0]')
548
+ expect(emitted).toMatch(/require\d*\("\.\/local"\)/)
549
+
550
+ // 3. Bundled execution through Metro runtime returns the string without missing-module error
551
+ const polyfillPath = require.resolve('metro-runtime/src/polyfills/require.js')
552
+ const polyfillCode = fs.readFileSync(polyfillPath, 'utf8')
553
+
554
+ const contextObj = {
555
+ __DEV__: false,
556
+ __METRO_GLOBAL_PREFIX__: '',
557
+ console: console,
558
+ } as any
559
+ contextObj.global = contextObj
560
+ vm.createContext(contextObj)
561
+ vm.runInContext(polyfillCode, contextObj)
562
+
563
+ vm.runInContext(emitted, contextObj)
564
+ const result = vm.runInContext('global.__r(1)', contextObj)
565
+ expect(result).toBe('./local')
566
+ })
567
+
568
+ it('preserves distinct indexed identity for duplicate and mixed sync/async dependencies', async () => {
569
+ const code = `
570
+ const a = require('./dep');
571
+ const b = require('./dep');
572
+ async function load() {
573
+ const c = await import('./dep');
574
+ }
575
+ `
576
+ const res = await transform(
577
+ {},
578
+ '/project',
579
+ 'index.js',
580
+ Buffer.from(code, 'utf8'),
581
+ { dev: false, platform: 'ios', type: 'module' }
582
+ )
583
+
584
+ assertZeroBabelCalls()
585
+
586
+ // Key format separates sync require from async import
587
+ const depNames = res.dependencies.map((d) => d.name)
588
+ expect(depNames).toContain('./dep')
589
+
590
+ const syncDep = res.dependencies.find((d) => d.name === './dep' && d.data.asyncType === null)!
591
+ const asyncDep = res.dependencies.find((d) => d.name === './dep' && d.data.asyncType === 'async')!
592
+ expect(syncDep).toBeDefined()
593
+ expect(asyncDep).toBeDefined()
594
+ expect(syncDep.data.index).not.toEqual(asyncDep.data.index)
595
+
596
+ // Rewritten code points both sync require calls to the sync dependency slot index
597
+ const emitted = res.output[0].data.code
598
+ const syncIndex = syncDep.data.index
599
+ expect(emitted).toContain(`require(_dependencyMap[${syncIndex}], "./dep")`)
600
+ })
601
+
602
+ it('conforms to Metro map ABI with raw mapping segment tuples and accurate symbolication', async () => {
603
+ const sourceCode = `
604
+ export function add(a: number, b: number): number {
605
+ return a + b;
606
+ }
607
+ `
608
+
609
+ const res = await transform(
610
+ {},
611
+ '/project',
612
+ 'math.ts',
613
+ Buffer.from(sourceCode, 'utf8'),
614
+ { dev: false, platform: 'ios', type: 'module' }
615
+ )
616
+
617
+ assertZeroBabelCalls()
618
+
619
+ const map = res.output[0].data.map
620
+ expect(Array.isArray(map)).toBe(true)
621
+ expect(map.length).toBeGreaterThan(0)
622
+
623
+ // Verify Metro Raw Mapping Segment Tuples:
624
+ // Every element must be an array tuple [line, column, origLine?, origCol?, name?]
625
+ // No SourceMapV3 objects embedded
626
+ for (const tuple of map) {
627
+ expect(Array.isArray(tuple)).toBe(true)
628
+ expect(typeof tuple[0]).toBe('number') // generated line (1-based)
629
+ expect(typeof tuple[1]).toBe('number') // generated column (0-based)
630
+ expect(tuple).not.toHaveProperty('version')
631
+ expect(tuple).not.toHaveProperty('mappings')
632
+ }
633
+
634
+ // Verify with Metro's own fromRawMappings and Consumer
635
+ const msm = await import('metro-source-map')
636
+ const fullMap = (msm.fromRawMappings as any)([
637
+ {
638
+ code: res.output[0].data.code,
639
+ source: 'math.ts',
640
+ map,
641
+ },
642
+ ]).toMap()
643
+
644
+ const consumer = new msm.Consumer(fullMap)
645
+ // Find generated line for function add
646
+ const lines = res.output[0].data.code.split('\n')
647
+ const addLineIndex = lines.findIndex((l) => l.includes('function add'))
648
+ expect(addLineIndex).toBeGreaterThan(0)
649
+
650
+ const pos = consumer.originalPositionFor({
651
+ line: (addLineIndex + 1) as any,
652
+ column: 16 as any,
653
+ })
654
+
655
+ expect(pos.line).toBe(2)
656
+ })
657
+
658
+ it('models JS hoisting in ScopeTracker for functions and vars (Astra probe)', async () => {
659
+ // Exact probe from Astra:
660
+ // function f(){const x=require("./local"); function require(x){return x}; return x} module.exports=f();
661
+ // function require is hoisted to f's function scope, so require("./local") is a local call and needs no module.
662
+ const input = 'function f(){const x=require("./local"); function require(x){return x}; return x} module.exports=f();'
663
+
664
+ const res = await transform(
665
+ {},
666
+ '/project',
667
+ 'hoisted.js',
668
+ Buffer.from(input, 'utf8'),
669
+ {
670
+ dev: false,
671
+ platform: 'ios',
672
+ type: 'module',
673
+ moduleId: 1,
674
+ dependencyIds: [],
675
+ } as any
676
+ )
677
+
678
+ assertZeroBabelCalls()
679
+
680
+ // 1. Dependency must NOT be extracted
681
+ expect(res.dependencies).toHaveLength(0)
682
+
683
+ // 2. Emitted code must NOT rewrite require("./local") to _dependencyMap
684
+ const emitted = res.output[0].data.code
685
+ expect(emitted).not.toContain('_dependencyMap[0]')
686
+ expect(emitted).toMatch(/require\d*\("\.\/local"\)/)
687
+
688
+ // 3. Bundled execution through Metro runtime returns "./local" without missing-module error
689
+ const polyfillPath = require.resolve('metro-runtime/src/polyfills/require.js')
690
+ const polyfillCode = fs.readFileSync(polyfillPath, 'utf8')
691
+
692
+ const contextObj = {
693
+ __DEV__: false,
694
+ __METRO_GLOBAL_PREFIX__: '',
695
+ console: console,
696
+ } as any
697
+ contextObj.global = contextObj
698
+ vm.createContext(contextObj)
699
+ vm.runInContext(polyfillCode, contextObj)
700
+
701
+ vm.runInContext(emitted, contextObj)
702
+ const result = vm.runInContext('global.__r(1)', contextObj)
703
+ expect(result).toBe('./local')
704
+ })
705
+
706
+ it('rewrites dynamic import to Metro asyncRequire and executes promise resolution in dev and release', async () => {
707
+ // Exact probe from Astra:
708
+ // transform of module.exports = () => import("./dep");
709
+ // Emitted __d wrapper must rewrite to require(asyncRequire)(_dependencyMap[dep], _dependencyMap.paths, "./dep")
710
+ // and resolve promise through real Metro runtime.
711
+ const depSource = 'exports.message = "hello dynamic";'
712
+ const mainSource = 'module.exports = () => import("./dep");'
713
+
714
+ const depRes = await transform(
715
+ {},
716
+ '/project',
717
+ 'dep.js',
718
+ Buffer.from(depSource, 'utf8'),
719
+ {
720
+ dev: true,
721
+ platform: 'ios',
722
+ type: 'module',
723
+ moduleId: 2,
724
+ dependencyIds: [],
725
+ } as any
726
+ )
727
+
728
+ const mainRes = await transform(
729
+ {},
730
+ '/project',
731
+ 'main.js',
732
+ Buffer.from(mainSource, 'utf8'),
733
+ {
734
+ dev: true,
735
+ platform: 'ios',
736
+ type: 'module',
737
+ moduleId: 0,
738
+ dependencyIds: [2, 1], // slot 0 -> module 2 (dep), slot 1 -> module 1 (asyncRequire)
739
+ } as any
740
+ )
741
+
742
+ assertZeroBabelCalls()
743
+
744
+ // 1. Dependencies include ./dep (async) and asyncRequire (sync)
745
+ const depNames = mainRes.dependencies.map((d) => d.name)
746
+ expect(depNames).toContain('./dep')
747
+ expect(depNames).toContain('metro-runtime/src/modules/asyncRequire')
748
+
749
+ const dynDep = mainRes.dependencies.find((d) => d.name === './dep')!
750
+ expect(dynDep.data.asyncType).toBe('async')
751
+
752
+ // 2. Emitted code must rewrite import("./dep") to asyncRequire call
753
+ const emittedMain = mainRes.output[0].data.code
754
+ expect(emittedMain).not.toContain('import("./dep")')
755
+ expect(emittedMain).toContain(
756
+ 'require(_dependencyMap[1], "metro-runtime/src/modules/asyncRequire")(_dependencyMap[0], _dependencyMap.paths, "./dep")'
757
+ )
758
+
759
+ // 3. Test Metro VM runtime execution in DEV and RELEASE modes
760
+ const polyfillPath = require.resolve('metro-runtime/src/polyfills/require.js')
761
+ const polyfillCode = fs.readFileSync(polyfillPath, 'utf8')
762
+ const asyncRequirePath = require.resolve('metro-runtime/src/modules/asyncRequire.js')
763
+ const asyncRequireSource = fs.readFileSync(asyncRequirePath, 'utf8')
764
+ const wrappedAsyncRequire = wrapModule(asyncRequireSource, { moduleId: 1, dependencyIds: [] })
765
+
766
+ for (const isDev of [true, false]) {
767
+ const contextObj = {
768
+ __DEV__: isDev,
769
+ __METRO_GLOBAL_PREFIX__: '',
770
+ console: console,
771
+ } as any
772
+ contextObj.global = contextObj
773
+ vm.createContext(contextObj)
774
+ vm.runInContext(polyfillCode, contextObj)
775
+
776
+ // Register asyncRequire (1), dep (2), and main (0)
777
+ vm.runInContext(wrappedAsyncRequire, contextObj)
778
+ vm.runInContext(depRes.output[0].data.code, contextObj)
779
+ vm.runInContext(emittedMain, contextObj)
780
+
781
+ const mainFn = vm.runInContext('global.__r(0)', contextObj)
782
+ expect(typeof mainFn).toBe('function')
783
+
784
+ const promise = mainFn()
785
+ expect(promise instanceof Promise || (promise && typeof promise.then === 'function')).toBe(true)
786
+
787
+ const resolved = await promise
788
+ expect(resolved.message).toBe('hello dynamic')
789
+ expect(resolved.default.message).toBe('hello dynamic')
790
+ }
791
+ })
792
+
793
+ it('preserves accurate sourcemap for tokens after rewritten require calls on the same line', async () => {
794
+ // Exact probe from Astra:
795
+ // rewriteDependencyCalls returns { code, map }
796
+ // Trace a source location AFTER a rewritten require on the same generated line
797
+ const sourceCode = 'const a = require("./dep"), b = 42;'
798
+
799
+ // Transform with module wrapping (standard mode)
800
+ const resWrapped = await transform(
801
+ {},
802
+ '/project',
803
+ 'app.js',
804
+ Buffer.from(sourceCode, 'utf8'),
805
+ {
806
+ dev: false,
807
+ platform: 'ios',
808
+ type: 'module',
809
+ } as any
810
+ )
811
+
812
+ assertZeroBabelCalls()
813
+
814
+ const msm = await import('metro-source-map')
815
+ const fullMapWrapped = (msm.fromRawMappings as any)([
816
+ {
817
+ code: resWrapped.output[0].data.code,
818
+ source: 'app.js',
819
+ map: resWrapped.output[0].data.map,
820
+ },
821
+ ]).toMap()
822
+
823
+ const consumerWrapped = new msm.Consumer(fullMapWrapped)
824
+ const linesWrapped = resWrapped.output[0].data.code.split('\n')
825
+ const lineIndexWrapped = linesWrapped.findIndex((l) => l.includes('b = 42'))
826
+ expect(lineIndexWrapped).toBeGreaterThanOrEqual(0)
827
+
828
+ const generatedColWrapped = linesWrapped[lineIndexWrapped].indexOf('b = 42')
829
+ expect(generatedColWrapped).toBeGreaterThan(0)
830
+
831
+ const posWrapped = consumerWrapped.originalPositionFor({
832
+ line: (lineIndexWrapped + 1) as any,
833
+ column: generatedColWrapped as any,
834
+ })
835
+
836
+ // Original position of 'b = 42' in sourceCode: line 1, column 28
837
+ expect(posWrapped.line).toBe(1)
838
+ expect(posWrapped.column).toBe(28)
839
+ expect(sourceCode.slice(Number(posWrapped.column))).toContain('b = 42;')
840
+
841
+ // Also test unwrapped mode: unstable_disableModuleWrapping: true
842
+ const resUnwrapped = await transform(
843
+ { unstable_disableModuleWrapping: true },
844
+ '/project',
845
+ 'app.js',
846
+ Buffer.from(sourceCode, 'utf8'),
847
+ {
848
+ dev: false,
849
+ platform: 'ios',
850
+ type: 'module',
851
+ } as any
852
+ )
853
+
854
+ const fullMapUnwrapped = (msm.fromRawMappings as any)([
855
+ {
856
+ code: resUnwrapped.output[0].data.code,
857
+ source: 'app.js',
858
+ map: resUnwrapped.output[0].data.map,
859
+ },
860
+ ]).toMap()
861
+
862
+ const consumerUnwrapped = new msm.Consumer(fullMapUnwrapped)
863
+ const linesUnwrapped = resUnwrapped.output[0].data.code.split('\n')
864
+ const lineIndexUnwrapped = linesUnwrapped.findIndex((l) => l.includes('b = 42'))
865
+ expect(lineIndexUnwrapped).toBeGreaterThanOrEqual(0)
866
+
867
+ const generatedColUnwrapped = linesUnwrapped[lineIndexUnwrapped].indexOf('b = 42')
868
+ const posUnwrapped = consumerUnwrapped.originalPositionFor({
869
+ line: (lineIndexUnwrapped + 1) as any,
870
+ column: generatedColUnwrapped as any,
871
+ })
872
+
873
+ expect(posUnwrapped.line).toBe(1)
874
+ expect(posUnwrapped.column).toBe(28)
875
+ })
876
+
877
+ it('routes a require.context whose directory is held in a variable through the dependency map', async () => {
878
+ // one's router entry reads its route root into a binding and passes that to
879
+ // require.context. if the call is not rewritten it survives into the bundle
880
+ // and reaches metro's fallbackRequireContext, which throws at startup.
881
+ const sourceCode = `
882
+ const routeRoot = './app'
883
+ export const ctx = require.context(routeRoot, true, /\\.tsx$/)
884
+ `
885
+
886
+ const result = await transform({}, '/project', 'entry.js', Buffer.from(sourceCode, 'utf8'), {
887
+ dev: true,
888
+ platform: 'ios',
889
+ type: 'module',
890
+ })
891
+
892
+ const contextDep = result.dependencies.find((d) => d.data.contextParams != null)
893
+ expect(contextDep?.name).toBe('./app')
894
+
895
+ const calls: any[] = []
896
+ let ctx: any
897
+ const sandbox: any = {
898
+ __d: (factory: any) => {
899
+ const module = { exports: {} as any }
900
+ const req: any = (...args: any[]) => {
901
+ calls.push(args)
902
+ return { keys: () => [] }
903
+ }
904
+ // reaching this means the call was left as a runtime require.context
905
+ req.context = () => {
906
+ throw new Error('fallbackRequireContext reached')
907
+ }
908
+ factory({}, req, () => ({}), () => ({}), module, module.exports, ['./app'])
909
+ ctx = module.exports.ctx
910
+ },
911
+ }
912
+
913
+ vm.runInNewContext(result.output[0].data.code, sandbox)
914
+
915
+ expect(ctx).toBeDefined()
916
+ expect(calls[0][1]).toBe('./app')
917
+ })
918
+
919
+ it('gives loop bodies per-iteration bindings that survive a runtime without them', async () => {
920
+ const sourceCode = `
921
+ export function collect() {
922
+ const out = []
923
+ for (let i = 0; i < 2; i++) out.push(() => i)
924
+ for (const label of ['a', 'b']) out.push(() => label)
925
+ for (const key in { x: 1, y: 2 }) out.push(() => key)
926
+ return out.map((f) => f())
927
+ }
928
+ `
929
+
930
+ const result = await transform({}, '/project', 'loops.ts', Buffer.from(sourceCode, 'utf8'), {
931
+ dev: true,
932
+ platform: 'ios',
933
+ type: 'module',
934
+ })
935
+
936
+ const code = result.output[0].data.code
937
+
938
+ // Hermes emits one CreateFunctionEnvironment before a loop rather than one
939
+ // per iteration, so a `let` loop head behaves exactly like `var` there.
940
+ // Rewriting the heads that way reproduces Hermes on a runtime that is
941
+ // otherwise spec-correct, which is what makes this assertion meaningful:
942
+ // the untransformed source returns 2,2,b,b,y,y under it.
943
+ const asHermesWouldSeeIt = code.replace(
944
+ /\bfor\s*\(\s*(let|const)\b/g,
945
+ 'for (var'
946
+ )
947
+
948
+ let collect: any
949
+ const sandbox: any = {
950
+ __d: (factory: any) => {
951
+ const module = { exports: {} as any }
952
+ factory({}, () => ({}), () => ({}), () => ({}), module, module.exports, [])
953
+ collect = module.exports.collect
954
+ },
955
+ }
956
+ vm.runInNewContext(asHermesWouldSeeIt, sandbox)
957
+
958
+ expect(collect()).toEqual([0, 1, 'a', 'b', 'x', 'y'])
959
+ })
960
+ })
961
+
962
+ describe('one native transform ports', () => {
963
+ it('inlines process.env.ONE_SERVER_URL so a native bundle can find its loaders', () => {
964
+ // without this a native prod bundle keeps a `process.env` read that has
965
+ // nothing behind it at runtime, and every loader fetch goes to undefined.
966
+ process.env.ONE_SERVER_URL = 'https://example.test'
967
+ try {
968
+ const out = applyInlineEnvVars(
969
+ 'export const url = process.env.ONE_SERVER_URL;',
970
+ 'loader.ts',
971
+ false
972
+ )
973
+ expect(out).toBe('export const url = "https://example.test";')
974
+ } finally {
975
+ process.env.ONE_SERVER_URL = undefined
976
+ }
977
+ })
978
+
979
+ it('leaves ONE_SERVER_URL alone when it is only a string', () => {
980
+ const src = 'export const key = "process.env.ONE_SERVER_URL";'
981
+ expect(applyInlineEnvVars(src, 'a.ts', false)).toBe(src)
982
+ })
983
+
984
+ it('inlines import.meta.env reads, which oxc otherwise lowers to an empty object', () => {
985
+ // oxc's CJS lowering emits `var import_meta = {}`, so an untouched
986
+ // `import.meta.env.X` silently reads undefined in every native bundle.
987
+ const env = { DEV: false, VITE_POSTHOG_API_KEY: 'pk_live', TAMAGUI_TARGET: 'native' }
988
+ const out = applyInlineEnvVars(
989
+ `export const key = import.meta.env.VITE_POSTHOG_API_KEY;
990
+ export const target = import.meta.env?.TAMAGUI_TARGET;
991
+ export const missing = import.meta.env.NOT_SET;
992
+ export const all = { ...import.meta.env };`,
993
+ 'env.ts',
994
+ true,
995
+ env
996
+ )
997
+ expect(out).toContain('export const key = "pk_live";')
998
+ expect(out).toContain('export const target = "native";')
999
+ expect(out).toContain('export const missing = undefined;')
1000
+ expect(out).toContain('"VITE_POSTHOG_API_KEY":"pk_live"')
1001
+ expect(out).not.toContain('import.meta')
1002
+ })
1003
+
1004
+ it('inlines process.env keys the vite env map defines', () => {
1005
+ const out = applyInlineEnvVars(
1006
+ 'export const t = process.env.TAMAGUI_TARGET; export const u = process.env.UNKNOWN_THING;',
1007
+ 'env.ts',
1008
+ true,
1009
+ { TAMAGUI_TARGET: 'native' }
1010
+ )
1011
+ expect(out).toContain('export const t = "native";')
1012
+ // a key the map does not define is left for the runtime, not guessed at.
1013
+ expect(out).toContain('process.env.UNKNOWN_THING')
1014
+ })
1015
+
1016
+ it('never rewrites an env read in an assignment target', () => {
1017
+ const src = 'process.env.VITE_ENVIRONMENT = "ssr";'
1018
+ expect(applyInlineEnvVars(src, 'a.ts', true, { VITE_ENVIRONMENT: 'ios' })).toBe(src)
1019
+ })
1020
+
1021
+ it('folds branches the inlining made constant so metro never resolves dead imports', () => {
1022
+ const out = applyInlineEnvVars(
1023
+ `if (import.meta.env.SSR) { require('./server-only-thing') } else { load(import.meta.env.API) }`,
1024
+ 'branch.ts',
1025
+ true,
1026
+ { SSR: false, API: 'https://api.test' }
1027
+ )
1028
+ expect(out).not.toContain('server-only-thing')
1029
+ // the surviving branch still gets its own inlining, which a fold that
1030
+ // copied original source would have thrown away.
1031
+ expect(out).toContain('load("https://api.test")')
1032
+ })
1033
+
1034
+ it('folds a ternary and keeps a branch it cannot resolve', () => {
1035
+ expect(
1036
+ applyInlineEnvVars('const a = import.meta.env.DEV ? x : y;', 'a.ts', true, { DEV: false })
1037
+ ).toContain('const a = y;')
1038
+ const dynamic = 'const a = flag ? x : y;'
1039
+ expect(applyInlineEnvVars(dynamic, 'a.ts', true, { DEV: false })).toBe(dynamic)
1040
+ })
1041
+
1042
+ it('runs the user native transforms that stand in for their babel plugins', async () => {
1043
+ // takeout's OTA plugin rewrites a bare `__HOT_UPDATER_BUNDLE_ID` that is
1044
+ // otherwise undeclared, so without a way to run it the bundle throws a
1045
+ // ReferenceError at module load. this is that way.
1046
+ const result = await transform(
1047
+ {},
1048
+ import.meta.dirname,
1049
+ 'ota.ts',
1050
+ Buffer.from(
1051
+ 'export const id = __EXAMPLE_BUILD_ID; export const from = __EXAMPLE_FILENAME;',
1052
+ 'utf8'
1053
+ ),
1054
+ {
1055
+ dev: true,
1056
+ platform: 'ios',
1057
+ type: 'module',
1058
+ customTransformOptions: {
1059
+ vite: {
1060
+ nativeTransformModules: ['./__fixtures__/exampleNativeTransform.cjs'],
1061
+ },
1062
+ },
1063
+ } as any
1064
+ )
1065
+
1066
+ assertZeroBabelCalls()
1067
+ expect(result.output[0].data.code).toContain('"ios-build"')
1068
+ expect(result.output[0].data.code).not.toContain('__EXAMPLE_BUILD_ID')
1069
+ // the transform is handed an absolute path, not metro's relative one
1070
+ expect(result.output[0].data.code).toContain(
1071
+ JSON.stringify(path.join(import.meta.dirname, 'ota.ts'))
1072
+ )
1073
+ })
1074
+
1075
+ it('refuses to build when a user babel plugin has no native port', () => {
1076
+ // this worker runs no babel, so an unrecognized plugin does nothing at all.
1077
+ // takeout adds `hot-updater/babel-plugin` for OTA; dropping it silently
1078
+ // would ship a build whose updates never apply.
1079
+ const withPlugins = (plugins: any[]) =>
1080
+ ({ customTransformOptions: { vite: { babelConfig: { plugins } } } }) as any
1081
+
1082
+ expect(() =>
1083
+ assertNoUnportedBabelPlugins(
1084
+ withPlugins([
1085
+ ['@vxrn/vite-plugin-metro/babel-plugins/import-meta-env-plugin', { env: {} }],
1086
+ 'one/babel-plugin-environment-guard',
1087
+ 'hot-updater/babel-plugin',
1088
+ ])
1089
+ )
1090
+ ).toThrow(/hot-updater\/babel-plugin/)
1091
+
1092
+ expect(() =>
1093
+ assertNoUnportedBabelPlugins(
1094
+ withPlugins([
1095
+ ['@vxrn/vite-plugin-metro/babel-plugins/import-meta-env-plugin', { env: {} }],
1096
+ 'one/babel-plugin-environment-guard',
1097
+ ['one/babel-plugin-remove-server-code', { routerRoot: 'app' }],
1098
+ ['babel-plugin-module-resolver', { alias: {} }],
1099
+ ['one/babel-plugin-one-router-metro', {}],
1100
+ 'one/babel-plugin-inline-one-server-url',
1101
+ 'babel-plugin-react-compiler',
1102
+ 'react-native-reanimated/plugin',
1103
+ ])
1104
+ )
1105
+ ).not.toThrow()
1106
+ })
1107
+
1108
+ it('turns a server-only import into a throw and drops native-only', () => {
1109
+ const out = applyEnvironmentGuard(
1110
+ `import 'native-only'\nimport 'server-only'\nexport const a = 1`,
1111
+ 'route.ts'
1112
+ )
1113
+ expect(out).not.toContain('native-only')
1114
+ expect(out).toContain('server-only cannot be imported in a native environment')
1115
+ // the throw has to replace the import as a STATEMENT. an expression left in
1116
+ // its place is a syntax error, which would fail the whole bundle to parse.
1117
+ const parsed = parseSync('route.ts', out, { lang: 'ts' })
1118
+ expect(parsed.errors).toEqual([])
1119
+ expect(parsed.program.body.map((n: any) => n.type)).toContain('ThrowStatement')
1120
+ })
1121
+
1122
+ it('reads the router root off one\'s remove-server-code plugin entry', () => {
1123
+ const options: any = {
1124
+ customTransformOptions: {
1125
+ vite: {
1126
+ babelConfig: {
1127
+ plugins: [['one/babel-plugin-remove-server-code', { routerRoot: 'src/app' }]],
1128
+ },
1129
+ },
1130
+ },
1131
+ }
1132
+ expect(getRemoveServerCodeRouterRoot(options)).toBe('src/app')
1133
+ // absent means one did not ask for it, which must not be read as 'app'
1134
+ expect(getRemoveServerCodeRouterRoot({ customTransformOptions: {} } as any)).toBe(
1135
+ undefined
1136
+ )
1137
+ })
1138
+ })