import type { StimContext } from '@stim-cli/core'; import { operationState } from '../engine/operation-state.ts'; export function isProjectPluginFailure(error: unknown): boolean { return error instanceof Error && 'projectPluginFailure' in error && error.projectPluginFailure === true; } export interface IosOperationScope { context: StimContext; own(dispose: () => Promise): void; } export async function withIosOperationScope( context: StimContext, run: (scope: IosOperationScope) => Promise, ): Promise { const cleanups: (() => Promise)[] = []; const drain = () => { if (!cleanups.length) return; const state = operationState(context); state.handled = true; state.draining = true; }; context.signal.addEventListener('abort', drain, { once: true }); try { return await run({ context, own(dispose) { cleanups.push(dispose); if (context.signal.aborted) drain(); }, }); } finally { try { await Promise.all(cleanups.map((dispose) => dispose())); } finally { context.signal.removeEventListener('abort', drain); } } } export function scopedIosOperation( context: StimContext, run: (scope: IosOperationScope, ...args: Args) => Promise, ): (...args: Args) => Promise { return (...args) => withIosOperationScope(context, (scope) => run(scope, ...args)); }