export type BrowserLifecyclePorts = { acquire: () => Promise; run: (context: C) => Promise; close: (context: C) => Promise; reportCleanupFailure: (error: unknown) => Promise; }; export function createBrowserLifecycle( ports: BrowserLifecyclePorts, ) { if ( !ports || [ports.acquire, ports.run, ports.close, ports.reportCleanupFailure].some( (port) => typeof port !== "function", ) ) throw new Error("BROWSER_LIFECYCLE_PORTS_REQUIRED"); return async () => { const context = await ports.acquire(); let failed = false; try { return await ports.run(context); } catch (error) { failed = true; throw error; } finally { try { await ports.close(context); } catch (error) { try { await ports.reportCleanupFailure(error); } catch {} if (!failed) throw error; } } }; }