UNPKG

histoire

Version:

A fast story book powered by Vite

51 lines (50 loc) • 2.01 kB
import { setTimeout as delay } from 'node:timers/promises'; import { ExecutionError } from '../runtime/execution-types.js'; import { forceKillPlaywrightBrowser, getPlaywrightBrowserProcess } from './playwright-kill.js'; /** Probe only captured browser process, never global Chromium counts. */ function processExited(child) { if (!child?.pid) return false; if (child.exitCode !== null && child.exitCode !== undefined) return true; if (child.signalCode) return true; try { process.kill(child.pid, 0); return false; } catch (error) { return error.code === 'ESRCH'; } } /** Signal owned process and require observed exit, including after concurrent close. */ export async function terminatePlaywrightBrowser(browser, timeoutMs = 2500, capturedProcess) { const child = (capturedProcess ?? getPlaywrightBrowserProcess(browser)); forceKillPlaywrightBrowser(browser, child); const until = Date.now() + Math.max(1, timeoutMs); do { if (processExited(child)) return 'forced'; await delay(20); } while (Date.now() < until); throw new ExecutionError('CLEANUP_UNCONFIRMED', 'Playwright browser cleanup could not be confirmed'); } /** Bound graceful close and confirm a signalled fallback really exited. */ export async function closePlaywrightBrowser(browser, timeoutMs = 5000) { const child = getPlaywrightBrowserProcess(browser); let timer; const closing = Promise.resolve().then(() => browser.close()); void closing.catch(() => { }); try { const result = await Promise.race([ closing.then(() => true, () => false), new Promise((resolve) => { timer = setTimeout(() => resolve(false), Math.max(1, Math.floor(timeoutMs / 2))); }), ]); if (result) return 'graceful'; } finally { clearTimeout(timer); } return terminatePlaywrightBrowser(browser, Math.max(1, Math.floor(timeoutMs / 2)), child); }