diff --git a/src/flow.ts b/src/flow.ts new file mode 100644 index 0000000..263af84 --- /dev/null +++ b/src/flow.ts @@ -0,0 +1,35 @@ +export type StepFn = (ctx: In) => Out | Promise; + +export interface CompiledFlow { + steps: { name: string; fn: StepFn }[]; + handler: (ctx: Acc) => unknown; + run(seed: Seed): Promise; +} + +export class Flow { + constructor(private readonly steps: { name: string; fn: StepFn }[] = []) {} + + step(name: string, fn: StepFn): Flow { + return new Flow([...this.steps, { name, fn }]); + } + + handle(handler: (ctx: Acc) => unknown): CompiledFlow { + const steps = this.steps; + return { + steps, + handler, + async run(seed: Seed): Promise { + let ctx: any = { ...seed }; + for (const s of steps) { + const out = await s.fn(ctx); + ctx = { ...ctx, ...out }; + } + return handler(ctx); + }, + }; + } +} + +export function flow(): Flow { + return new Flow(); +} diff --git a/test/flow.test.ts b/test/flow.test.ts new file mode 100644 index 0000000..bc1e41f --- /dev/null +++ b/test/flow.test.ts @@ -0,0 +1,19 @@ +import { expect, test } from 'vitest'; +import { flow } from '../src/flow'; + +test('flow accumulates context and runs steps in order', async () => { + const compiled = flow<{ req: { token: string } }>() + .step('auth', (ctx) => ({ user: { id: ctx.req.token } })) + .step('load', (ctx) => ({ greeting: `hi ${ctx.user.id}` })) + .handle((ctx) => ctx.greeting); + + const result = await compiled.run({ req: { token: 'abc' } }); + expect(result).toBe('hi abc'); +}); + +test('async steps are awaited and accumulate', async () => { + const compiled = flow<{ n: number }>() + .step('double', async (ctx) => ({ doubled: ctx.n * 2 })) + .handle((ctx) => ctx.doubled); + expect(await compiled.run({ n: 21 })).toBe(42); +}); diff --git a/test/types/flow-types.test.ts b/test/types/flow-types.test.ts new file mode 100644 index 0000000..66c5c1f --- /dev/null +++ b/test/types/flow-types.test.ts @@ -0,0 +1,16 @@ +import { test, expect } from 'vitest'; +import { flow } from '../../src/flow'; + +test('type guarantee holds (this file must typecheck)', () => { + // OK: handler reads `user`, produced by the auth step. + flow<{ req: { token: string } }>() + .step('auth', (ctx) => ({ user: ctx.req.token })) + .handle((ctx) => ctx.user); + + // GUARANTEE: remove the auth step and reading `user` must NOT compile. + flow<{ req: { token: string } }>() + // @ts-expect-error — `user` is not in the accumulated context + .handle((ctx) => ctx.user); + + expect(true).toBe(true); +});