| 1 | export type CommandCancellationReason = "not-ready" | "superseded" | "disposed"; |
| 2 | export type CommandOutcome<T> = |
| 3 | | { status: "completed"; value: T } |
| 4 | | { status: "cancelled"; reason: CommandCancellationReason } |
| 5 | | { status: "failed"; error: unknown }; |
| 6 | |
| 7 | export class CommandCancelled extends Error { |
| 8 | constructor(readonly reason: CommandCancellationReason) { |
| 9 | super(reason); |
| 10 | } |
| 11 | } |
| 12 | |
| 13 | export type CommandAuthority = { |
| 14 | checkpoint(): void; |
| 15 | }; |
| 16 | |
| 17 | /** Standalone execution holds captured input, never the capture callback or DOM event. */ |
| 18 | export async function executeCapturedCommand<Input, Result, Authority extends CommandAuthority>( |
| 19 | input: Input, |
| 20 | execute: (input: Input, authority: Authority) => Result, |
| 21 | authority: Authority, |
| 22 | ): Promise<CommandOutcome<Awaited<Result>>> { |
| 23 | try { |
| 24 | authority.checkpoint(); |
| 25 | const value = await execute(input, authority); |
| 26 | authority.checkpoint(); |
| 27 | return { status: "completed", value: value as Awaited<Result> }; |
| 28 | } catch (error) { |
| 29 | try { authority.checkpoint(); } catch (cancelled) { error = cancelled; } |
| 30 | return error instanceof CommandCancelled |
| 31 | ? { status: "cancelled", reason: error.reason } |
| 32 | : { status: "failed", error }; |
| 33 | } |
| 34 | } |
| 35 |