export type BrowserPrimaryFailure={error:unknown}; export type BrowserLifecyclePorts={acquire():Promise;run(context:C):Promise;close(context:C):Promise;reportResult(result:R|undefined,primary?:BrowserPrimaryFailure):Promise;reportSecondaryFailure(kind:'report'|'close',error:unknown):Promise}; // Local adaptation of the sibling acquire/run/close contract. Result reporting // occurs after close, so a failing writer cannot extend the browser lifetime. export function createBrowserLifecycle(ports:BrowserLifecyclePorts){ if(!ports||[ports.acquire,ports.run,ports.close,ports.reportResult,ports.reportSecondaryFailure].some(port=>typeof port!=='function'))throw Error('BROWSER_LIFECYCLE_PORTS_REQUIRED'); const secondary=async(kind:'report'|'close',error:unknown)=>{try{await ports.reportSecondaryFailure(kind,error)}catch{/* Secondary reporting never replaces an owned primary failure. */}}; return async()=>{ let result:R|undefined,primary:unknown,cleanup:unknown,failed=false,cleanupFailed=false; const context=await ports.acquire(); try{try{result=await ports.run(context)}catch(error){primary=error;failed=true}} finally{try{await ports.close(context)}catch(error){cleanup=error;cleanupFailed=true}} if(cleanupFailed)await secondary('close',cleanup); try{await ports.reportResult(result,failed?{error:primary}:undefined)}catch(error){await secondary('report',error);if(!failed&&!cleanupFailed){primary=error;failed=true}} if(failed)throw primary; if(cleanupFailed)throw cleanup; return result as R; }; }