import { NativeMetro } from "@effect/ui-native/node" import * as Fs from "node:fs" import * as Os from "node:os" import * as Path from "node:path" import { afterAll, assert, beforeAll, describe, it, vi } from "vitest" // Both cases build into one fixture as a release, so they run in turn. describe("NativeMetro.withEffectUi", { concurrent: false }, () => { // Vite reports real paths, as Metro does. const root = Fs.realpathSync( Fs.mkdtempSync(Path.join(Os.tmpdir(), "ui-native-prebundle-")) ) beforeAll(() => { vi.stubEnv("NODE_ENV", "production") }) afterAll(() => { vi.unstubAllEnvs() Fs.rmSync(root, { recursive: true, force: true }) }) const write = (file: string, content: string) => { Fs.mkdirSync(Path.dirname(Path.join(root, file)), { recursive: true }) Fs.writeFileSync(Path.join(root, file), content) } write("package.json", JSON.stringify({ main: "src/main" })) write( "src/main.ts", `import { Platform } from "react-native" import { title } from "./title" import { flavor } from "./flavor" import { topping } from "./topping" export default [Platform, title, flavor, topping] ` ) write("src/title.ts", `export const title = "plain title"\n`) write("src/title.native.ts", `export const title = "native title"\n`) write("src/title.android.ts", `export const title = "android title"\n`) write("src/flavor.ts", `export const flavor = "plain flavor"\n`) write("src/custom.ts", `export const flavor = "custom flavor"\n`) write("src/topping.ts", `export const topping = "plain topping"\n`) write("src/sauce.ts", `export const topping = "sauce topping"\n`) // The app's Babel transformer, which hands back what it's given. write("transformer.cjs", `module.exports = { transform: (args) => args }\n`) const transformer = { babelTransformerPath: Path.join(root, "transformer.cjs") } // The pre-bundle Metro's transformer swaps the entry for. const readBundle = async ( config: NativeMetro.MetroConfig, entry: string, platform: string ) => { const { transform } = await import( config.transformer!.babelTransformerPath! ) const { src } = transform({ filename: entry, src: "", options: { dev: false, platform, projectRoot: root } }) return Fs.readFileSync(JSON.parse(/require\((.+)\)/.exec(src)![1]!), "utf8") } it( "swaps the entry for a pre-bundle that resolves as Metro does", async () => { const config = await NativeMetro.withEffectUi({ projectRoot: root, transformer, resolver: { sourceExts: ["ts", "js"], // One alias returns a file, the other renames the import. resolveRequest: (context, moduleName, platform) => moduleName === "./flavor" ? { type: "sourceFile", filePath: Path.join(root, "src/custom.ts") } : context.resolveRequest( context, moduleName === "./topping" ? "./sauce" : moduleName, platform ) } }) // Another app's config in the same process leaves this one's alone. await NativeMetro.withEffectUi({ projectRoot: Path.join(root, "other"), transformer }, { entry: "main.ts", platforms: [] }) const android = await readBundle(config, "src/main.ts", "android") const ios = await readBundle(config, "src/main.ts", "ios") assert.include(android, "android title") assert.include(ios, "native title") assert.notInclude(ios, "plain title") assert.include(android, "custom flavor") assert.notInclude(android, "plain flavor") assert.include(android, "sauce topping") assert.notInclude(android, "plain topping") assert.match(android, /from "react-native"/) }, 30_000 ) it( "drops unused definitions, kit modules and Css helpers, and keeps opt-in networking and NativeHttpClient's URL", async () => { const link = (name: string, target: string) => { Fs.mkdirSync(Path.join(root, "node_modules", Path.dirname(name)), { recursive: true }) Fs.symlinkSync(target, Path.join(root, "node_modules", name)) } const pkg = Path.resolve(import.meta.dirname, "..") link("@effect/ui-native", pkg) link("effect", Path.join(pkg, "node_modules/effect")) // Outside the package, whose `sideEffects` would drop the whole module. write( "src/toggle.ts", `import * as Native from "@effect/ui-native/Native" export const toggle = Native.defineView(() => new Native.Element("toggle"), { viewName: "FixtureToggleView" }) ` ) const app = (imports: string, child: string) => `import * as Native from "@effect/ui-native/Native" import * as NativeApp from "@effect/ui-native/NativeApp" import * as Schema from "effect/Schema" ${imports} const App = Native.component({ name: "App", model: Schema.Number }).make({ init: () => 0, view: (h) => h.view.style({ flex: 1 }).children(${child}) }) NativeApp.register(NativeApp.mount(App, {})) ` write("src/plain.ts", app("", "")) write( "src/unused.ts", app( [ `import { clear, setSelection } from "@effect/ui-native/Native"`, `import "@effect/ui-native"`, `import { Pan, Pressable } from "@effect/ui-native/kit"`, `import "./toggle"` ].join("\n"), "" ) ) write("src/used.ts", app(`import { toggle } from "./toggle"`, "toggle")) write( "src/css.ts", app( `import { Css } from "@effect/ui-native/kit"`, `h.view.style({ transform: Css.transform("scale(2)") })` ) ) write( "src/networking.ts", app(`import "@effect/ui-native/networking"`, "") ) write( "src/http.ts", app( `import * as NativeHttpClient from "@effect/ui-native/NativeHttpClient" ;(globalThis as any).http = NativeHttpClient.layer`, "" ) ) const bundle = async (entry: string) => { const config = await NativeMetro.withEffectUi( { projectRoot: root, transformer, resolver: { sourceExts: ["ts", "js"] } }, { entry, platforms: ["android"] } ) return await readBundle(config, entry, "android") } const plain = await bundle("src/plain.ts") assert.strictEqual(await bundle("src/unused.ts"), plain) assert.notInclude(plain, "setSelection") assert.notInclude(plain, "reserved by the host") assert.notInclude(plain, "react-native/Libraries/Core/setUpXHR") assert.include(await bundle("src/used.ts"), "FixtureToggleView") // Each Css helper brings only its parser and drops unused kit controls. const css = await bundle("src/css.ts") assert.include(css, "processTransform") assert.notInclude(css, "processBoxShadow") assert.notInclude(css, "AndroidSwitch") assert.notInclude(css, "activityIndicator") const networking = await bundle("src/networking.ts") assert.include(networking, "react-native/Libraries/Core/setUpXHR") const http = await bundle("src/http.ts") assert.include(http, "react-native/Libraries/Blob/URL") assert.notInclude(http, "react-native/Libraries/Core/setUpXHR") }, 30_000 ) it( "pre-bundles the `--entry-file` of `react-native bundle --dev false`, and keys the cache on the app's transformer", async () => { vi.stubEnv("NODE_ENV", undefined) const argv = process.argv write( "src/cli.ts", `import { title } from "./title" export default ["cli entry", title] ` ) process.argv = [ ...argv, "bundle", // Relative to the project root, not the working directory. "--entry-file=src/cli.ts", "--dev", "false" ] try { const config = await NativeMetro.withEffectUi({ projectRoot: root, transformer, resolver: { sourceExts: ["ts", "js"] } }, { platforms: ["ios"] }) assert.include( await readBundle(config, "src/cli.ts", "ios"), "cli entry" ) const { transform, getCacheKey } = await import( config.transformer!.babelTransformerPath! ) // Other files go to the app's transformer as they are. const { src } = transform({ filename: "src/title.ts", src: "source", options: { dev: false, platform: "ios", projectRoot: root } }) assert.strictEqual(src, "source") const key = getCacheKey() write("transformer.cjs", `module.exports = { transform: (a) => a }\n`) assert.notStrictEqual(getCacheKey(), key) } finally { process.argv = argv vi.stubEnv("NODE_ENV", "production") } }, 30_000 ) it("falls back to the asset registry file before React Native 0.87", async () => { const config = await NativeMetro.withEffectUi( { projectRoot: root }, { prebundle: false } ) const found = config.resolver!.resolveRequest!( { resolveRequest: (_: unknown, moduleName: string) => { if (moduleName.endsWith("/asset-registry")) { throw new Error("not found") } return { type: "sourceFile", filePath: moduleName } } }, "react-native/asset-registry", "ios" ) assert.strictEqual( found.filePath, "react-native/Libraries/Image/AssetRegistry" ) }) it("fails rather than resolve an import for another platform", async () => { const error = await NativeMetro.withEffectUi({ projectRoot: root, transformer, resolver: { sourceExts: ["ts", "js"], resolveRequest: (context, moduleName, platform) => context.resolveRequest( context, moduleName, moduleName === "./title" ? null : platform ) } }, { platforms: ["android"] }).then( () => undefined, (error: Error) => error ) assert.include(error?.message, "./title on platform null") }, 30_000) it( "leaves asset imports external, preserves package asset importers, and rejects require of assets", async () => { // Scale-only relative asset, nested scale-only package assets (via export // map and via external), and a resolveRequest assetFiles alias. write("src/mark@2x.png", "png-2x") write("src/badge@2x.png", "png-badge") write( "node_modules/nested-consumer/package.json", JSON.stringify({ name: "nested-consumer", main: "index.js" }) ) write( "node_modules/nested-consumer/index.js", `import exportedIcon from "exported-images/icon.png" import externalIcon from "private-images/icon.png" export default [exportedIcon, externalIcon] ` ) write( "node_modules/nested-consumer/node_modules/exported-images/package.json", JSON.stringify({ name: "exported-images", exports: { "./icon.png": "./art/logo.png" } }) ) write( "node_modules/nested-consumer/node_modules/exported-images/art/logo@2x.png", "png-exported-2x" ) write( "node_modules/nested-consumer/node_modules/private-images/icon@2x.png", "png-external-2x" ) write( "src/assets-entry.ts", `import mark from "./mark.png" import badge from "./badge" import nestedIcons from "nested-consumer" export default [mark, badge, nestedIcons] ` ) const config = await NativeMetro.withEffectUi( { projectRoot: root, transformer, resolver: { sourceExts: ["ts", "js"], assetExts: ["png"], resolveRequest: (context, moduleName, platform) => moduleName === "./badge" ? { type: "assetFiles", filePaths: [Path.join(root, "src/badge@2x.png")] } : context.resolveRequest(context, moduleName, platform) } }, { entry: "src/assets-entry.ts", platforms: ["android"], external: ["private-images"] } ) const bundle = await readBundle(config, "src/assets-entry.ts", "android") assert.notInclude(bundle, "data:image") const imports = [...bundle.matchAll(/from "([^"]+)"/g)].map((m) => m[1]!) assert.include(imports, Path.join(root, "src/mark.png")) assert.include(imports, Path.join(root, "src/badge.png")) // Non-path asset imports resolve through Metro with their original importer. const seen: Array = [] for (const specifier of imports) { if (Path.isAbsolute(specifier)) continue config.resolver!.resolveRequest!( { dev: false, originModulePath: Path.join( root, "node_modules/.cache/@effect/ui-native/main.android.js" ), resolveRequest: ( ctx: { readonly originModulePath: string }, name: string ) => { seen.push([ctx.originModulePath, name]) return { type: "assetFiles", filePaths: [] } } }, specifier, "android" ) } const consumerPath = Path.join( root, "node_modules/nested-consumer/index.js" ) assert.deepStrictEqual(seen, [ [consumerPath, "exported-images/icon.png"], [consumerPath, "private-images/icon.png"] ]) for (const target of ["./mark.png", "expo-icons/mark.png"]) { write( "src/require-asset.ts", `declare const require: (id: string) => number export default require("${target}") ` ) const error = await NativeMetro.withEffectUi({ projectRoot: root, transformer, resolver: { sourceExts: ["ts", "js"], assetExts: ["png"] } }, { entry: "src/require-asset.ts", platforms: ["android"] }).then( () => undefined, (err: Error) => err ) assert.include(error?.message, "static `import`") } }, 30_000 ) })