const fs = require('fs'); const os = require('os'); const path = require('path'); const { execSync, spawn } = require('child_process'); const { promisify } = require('util'); const execFile = promisify(require('child_process').execFile); const { foreignHolderError, recordPid, recordedLivePids } = require('../tests/e2e/runRecord'); let macOsRetries = 0; const SERIAL_JET_PORT = 8090; const SERIAL_METRO_PORT = 8081; const DEFAULT_MACOS_PRODUCT_NAME = 'io.invertase.testing'; function macOsProductName() { return process.env.RNFB_MACOS_PRODUCT_NAME || DEFAULT_MACOS_PRODUCT_NAME; } function macOsBundleIdentifier() { if (process.env.RNFB_MACOS_BUNDLE_IDENTIFIER) { return process.env.RNFB_MACOS_BUNDLE_IDENTIFIER; } // Match Xcode $(PRODUCT_NAME:rfc1034identifier) — dots → hyphens. return `org.reactjs.native.${macOsProductName().replace(/\./g, '-')}`; } function macOsBundleQuery() { // Bundle IDs are ascii; keep hyphens literal in the Metro query string. return ( 'platform=macos&dev=true&lazy=true&minify=false&inlineSourceMap=true&modulesOnly=false&runModule=true&app=' + macOsBundleIdentifier() ); } function macOsBinaryPath() { const name = macOsProductName(); return `./macos/build/Build/Products/Debug/${name}.app/Contents/MacOS/${name}`; } function shellSingleQuote(value) { return `'${String(value).replace(/'/g, `'\\''`)}'`; } function parseEnvPort(value) { if (value === undefined || value === null || value === '') { return null; } const n = parseInt(value, 10); return Number.isFinite(n) ? n : null; } function readJetPort() { const fromLocal = parseEnvPort(process.env.JET_REMOTE_PORT); if (fromLocal != null) { return fromLocal; } const prefixed = parseEnvPort(process.env.RNFB_MACOS_JET_PORT); return prefixed != null ? prefixed : SERIAL_JET_PORT; } function readMetroPort() { const fromLocal = parseEnvPort(process.env.RCT_METRO_PORT) ?? parseEnvPort(process.env.RNFB_METRO_PORT); if (fromLocal != null) { return fromLocal; } const prefixed = parseEnvPort(process.env.RNFB_MACOS_METRO_PORT); return prefixed != null ? prefixed : SERIAL_METRO_PORT; } // Any process with the product name — may belong to another owner (diagnostics only). function macOsTestAppPidsByName() { try { return execSync(`pgrep -x ${shellSingleQuote(macOsProductName())}`, { encoding: 'utf8' }) .split(/\s+/) .filter(pid => /^\d+$/.test(pid)) .map(Number); } catch (_e) { return []; } } // Jet loads this config in the process that listens on the Jet and control ports (under // --coverage, nyc's child). Record it so an interrupted run's Jet stays owned and the // default yarn tests:e2e:release frees its ports; the app it spawns is owned through it. function recordJetProcess(jetPort) { recordPid(process.pid, `jet:${jetPort}`); } let currentMacApp = null; function macOsAppRecordLabel() { return `macos-app:${macOsProductName()}`; } function pidAlive(pid) { try { process.kill(pid, 0); return true; } catch (_e) { return false; } } // The app this process spawned plus any this checkout's runs recorded (interrupted runs). function ownMacOsAppPids() { const pids = new Set(recordedLivePids(macOsAppRecordLabel())); if (currentMacApp?.pid && currentMacApp.exitCode == null && currentMacApp.signalCode == null) { pids.add(currentMacApp.pid); } return [...pids].filter(pidAlive); } function isMacOsTestAppRunning() { return ownMacOsAppPids().length > 0; } function signalPids(pids, signal) { for (const pid of pids) { try { process.kill(pid, signal); } catch (_e) { // already gone } } } function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } // Never killall by name: only own pids, so another checkout's macOS run survives. async function killMacOsTestApp() { const name = macOsProductName(); if (!isMacOsTestAppRunning()) { return; } signalPids(ownMacOsAppPids(), 'SIGTERM'); await sleep(500); if (isMacOsTestAppRunning()) { signalPids(ownMacOsAppPids(), 'SIGKILL'); } const deadline = Date.now() + 2000; while (Date.now() < deadline && isMacOsTestAppRunning()) { await sleep(250); } if (isMacOsTestAppRunning()) { console.warn(`[rnfb-e2e] ${name} still running after SIGKILL — tee/pipe may not close`); } } let macOsExitHandlersRegistered = false; function registerMacOsExitHandlers() { if (macOsExitHandlersRegistered) { return; } macOsExitHandlersRegistered = true; const cleanup = () => { signalPids(ownMacOsAppPids(), 'SIGKILL'); }; process.on('exit', cleanup); process.on('SIGINT', () => { cleanup(); process.exit(130); }); process.on('SIGTERM', () => { cleanup(); process.exit(143); }); } async function assertMetroBundleInlinesJetPort(bundlePath, jetPort) { // Serial default 8090 is also packages/app/e2e/helpers.js DEFAULT_JET_SERIAL — // the numeric literal is always in the bundle. Babel inline of process.env is // only required when the active Jet port differs from that default (slotted). if (String(jetPort) === String(SERIAL_JET_PORT)) { return; } try { await execFile('grep', ['-q', '-F', `"${jetPort}"`, bundlePath]); } catch (_e) { throw new Error( `Metro bundle does not inline Jet port ${jetPort} (babel env missing on the packager process?). ` + `Restart with: eval "$(yarn tests:e2e:export-slot-env macos )" && yarn tests:macos:packager:jet-reset-cache`, ); } } async function waitForMetroMacosBundle(metroPort = 8081, timeoutMs = 600000) { const host = '127.0.0.1'; const statusUrl = `http://${host}:${metroPort}/status`; const bundleUrl = `http://${host}:${metroPort}/index.bundle?${macOsBundleQuery()}`; const started = Date.now(); const statusTimeoutMs = 120000; let statusOk = false; while (Date.now() - started < statusTimeoutMs) { try { const { stdout } = await execFile('curl', ['-sf', statusUrl]); if (stdout.includes('packager-status:running')) { statusOk = true; break; } } catch (_e) { // Metro still starting. } await new Promise(resolve => setTimeout(resolve, 2000)); } if (!statusOk) { throw new Error( `Metro not responding with packager-status:running on 127.0.0.1:${metroPort} after ${statusTimeoutMs}ms`, ); } while (Date.now() - started < timeoutMs) { const remainingSec = Math.max(30, Math.ceil((timeoutMs - (Date.now() - started)) / 1000)); const sliceSec = Math.min(120, remainingSec); const bundlePath = path.join( os.tmpdir(), `rnfb-macos-bundle-prefetch-${metroPort}-${Date.now()}.js`, ); try { try { await execFile('curl', [ '-sf', '--max-time', String(sliceSec), '-o', bundlePath, bundleUrl, ]); await assertMetroBundleInlinesJetPort(bundlePath, String(readJetPort())); console.warn(`[rnfb-e2e] macOS Metro bundle prefetched from ${bundleUrl}`); return; } finally { try { fs.unlinkSync(bundlePath); } catch (_e) { // temp bundle already removed } } } catch (err) { if (String(err?.message || err).includes('does not inline Jet port')) { throw err; } // curl 18 = partial transfer; 28 = timeout while Metro is still compiling. console.warn(`[rnfb-e2e] macOS Metro bundle prefetch retry (code=${err?.code ?? 'unknown'})`); } await new Promise(resolve => setTimeout(resolve, 3000)); } throw new Error(`macOS Metro bundle not available at ${bundleUrl} after ${timeoutMs}ms`); } module.exports = { recordJetProcess, config: { port: parseEnvPort(process.env.JET_REMOTE_PORT) ?? SERIAL_JET_PORT, slow: 3000, reporter: 'spec', timeout: 420000, // 7 minutes - fetchAndActivate takes 5+ sometimes exitOnError: true, reconnectGraceMs: 30000, coverage: true, }, targets: { macos: { async before(config) { await killMacOsTestApp(); const foreignPids = macOsTestAppPidsByName(); if (foreignPids.length > 0) { throw foreignHolderError(`macOS app ${macOsProductName()}`, foreignPids, 'macos-app'); } registerMacOsExitHandlers(); const metroPort = readMetroPort(); const jetPort = readJetPort(); config.metroPort = metroPort; config.port = jetPort; recordJetProcess(jetPort); console.warn(`[rnfb-e2e] macos Jet port=${jetPort} metro=${metroPort}`); await waitForMetroMacosBundle(metroPort); const macBinary = macOsBinaryPath(); console.warn(`[rnfb-e2e] spawning macOS app ${macBinary} (${macOsBundleIdentifier()})`); const macApp = spawn(macBinary, [], { // 'ignore' (not 'inherit'): inherited stdio hands the app the // write end of the agent's stdout/stderr pipe (e.g. `| tee`), so // the pipe never sees EOF and the shell hangs after the suite // finishes even though the app has nothing left to print. stdio: ['ignore', 'ignore', 'ignore'], env: { ...process.env, RCT_METRO_PORT: String(metroPort), JET_REMOTE_PORT: String(jetPort), }, }); currentMacApp = macApp; macApp.on('close', (code, signal) => { if (code === 0 || (code == null && signal)) { return; } if (isMacOsTestAppRunning()) { return; } if (macOsRetries < 3) { macOsRetries++; // eslint-disable-next-line no-console console.log('App crashed, retrying macOS app tests...'); this.before(config); return; } else { // eslint-disable-next-line no-console console.error('macOS app failed to start, exiting...'); process.exit(1); } }); macApp.on('spawn', () => { recordPid(macApp.pid, macOsAppRecordLabel()); // eslint-disable-next-line no-console console.log('[💻] macOS app started'); }); return config; }, async after(_config) { await killMacOsTestApp(); if (isMacOsTestAppRunning()) { console.warn(`[rnfb-e2e] macOS app teardown FAILED — ${macOsProductName()} still alive`); } else { console.warn('[rnfb-e2e] macOS app teardown complete'); } }, }, }, };