Files
mtusi2026lab6/scripts/lib/browser-lifecycle.ts

20 lines
1.5 KiB
TypeScript

export type BrowserPrimaryFailure={error:unknown};
export type BrowserLifecyclePorts<C,R>={acquire():Promise<C>;run(context:C):Promise<R>;close(context:C):Promise<void>;reportResult(result:R|undefined,primary?:BrowserPrimaryFailure):Promise<void>;reportSecondaryFailure(kind:'report'|'close',error:unknown):Promise<void>};
// 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<C,R>(ports:BrowserLifecyclePorts<C,R>){
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;
};
}