import { createRequire } from 'node:module' import { join } from 'node:path' import { delay } from './async.mjs' import { childrenOf, killAll, treeOf } from './proc.mjs' import { startWatchdog } from './watchdog.mjs' /** * Playwright stays outside the repository: PLAYWRIGHT_NODE_MODULES names a * node_modules that holds playwright-core (no project dependency), as for * docker/csp-proof/app-image.sh. Browsers come from its own cache * (~/.cache/ms-playwright). */ export const ENGINES = ['chromium', 'firefox', 'webkit'] const CLOSE_TIMEOUT_MS = 15_000 function modulesDir() { const dir = process.env.PLAYWRIGHT_NODE_MODULES if (!dir) { throw new Error( 'set PLAYWRIGHT_NODE_MODULES to a node_modules holding playwright-core', ) } return dir } export function loadPlaywright() { const require = createRequire(import.meta.url) const dir = modulesDir() const pw = require(join(dir, 'playwright-core')) const { version } = require(join(dir, 'playwright-core/package.json')) return { pw, version } } /** The one child process `launch` started: the root of the browser's tree. */ function newChild(before) { const fresh = childrenOf(process.pid).filter((pid) => !before.has(pid)) if (fresh.length !== 1) { throw new Error(`expected one new browser process, found ${fresh.length}`) } return fresh[0] } /** * Launches one headless browser under its watchdog. Fails closed: a browser * whose process tree cannot be identified is closed, never run unwatched. */ export async function launchEngine(pw, engine) { const before = new Set(childrenOf(process.pid)) const browser = await pw[engine].launch({ headless: true }) let rootPid try { rootPid = newChild(before) } catch (error) { await browser.close() throw error } const watchdog = startWatchdog({ rootPid }) await watchdog.ready return { engine, browser, rootPid, version: browser.version(), watchdog } } /** Closes the browser; one that hangs is killed, its own tree only. */ export async function closeEngine(session) { const closed = session.browser.close().then( () => true, () => true, ) const timedOut = delay(CLOSE_TIMEOUT_MS).then(() => false) if (!(await Promise.race([closed, timedOut]))) { killAll(treeOf(session.rootPid)) } await session.watchdog.stop() }