/** A single flow step: receives the accumulated context and returns the fields it contributes. */ export type StepFn = (ctx: In) => Out | Promise; /** A built flow ready to execute: its ordered steps, terminal handler, and a `run` entry point. */ export interface CompiledFlow { steps: { name: string; fn: StepFn }[]; handler: (ctx: Acc) => unknown; run(seed: Seed): Promise; } /** Immutable builder that chains typed steps, each widening the accumulated context type. */ export class Flow { constructor(private readonly steps: { name: string; fn: StepFn }[] = []) {} /** Appends a step and returns a new Flow whose context now includes the step's output. */ step(name: string, fn: StepFn): Flow { return new Flow([...this.steps, { name, fn }]); } /** Seals the flow with a terminal handler, producing a runnable CompiledFlow. */ handle(handler: (ctx: Acc) => unknown): CompiledFlow { const steps = this.steps; return { steps, handler, async run(seed: Seed): Promise { let ctx: any = { ...seed }; for (const step of steps) { const output = await step.fn(ctx); ctx = { ...ctx, ...output }; } return handler(ctx); }, }; } } /** Starts a new flow whose seed and initial context are the same type. */ export function flow(): Flow { return new Flow(); }