@expressive/steps 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/steps.ts"],"sourcesContent":["import { get, has, map, Model, unbind } from '@expressive/mvc';\nimport { event, listener, touch, watch } from '@expressive/mvc/observable';\n\ntype Collection = has.List<unknown> | has.Pool<unknown> | map.Managed<unknown, unknown>;\ntype Change = [out: unknown, changed: boolean, undo?: () => void, lost?: boolean];\ntype Mutator = (...args: any[]) => Change;\n\ntype Log = [key: string, undo: () => void][];\n\ninterface Held {\n prior: Record<string, unknown>;\n log: Log;\n}\n\ninterface Ticket {\n args: unknown[];\n promise: Promise<unknown>;\n resolve(value: unknown): void;\n reject(error: unknown): void;\n awaited?: boolean;\n}\n\ninterface Answer {\n frame: Promise<Frame | undefined>;\n done(): void;\n fail(error: unknown): void;\n}\n\ntype Kind = 'reset' | 'catch' | 'abort' | 'close';\ntype Mode = 'error' | 'abort' | 'stop';\n\ninterface Handler {\n kind: Kind;\n node: Steps.Node;\n bare?: boolean;\n}\n\ninterface Rescue {\n key?: string;\n fn?: Function;\n}\n\ntype Restore = (into?: Frame, all?: boolean, within?: string) => void;\n\ninterface Unwound {\n undone: Steps.Entry[];\n kept: Set<string>;\n failed?: { cause: unknown };\n}\n\ninterface Branch {\n failed?: { cause: unknown };\n}\n\ninterface Lineage {\n restore: Restore;\n caught: Steps.Node;\n}\n\ninterface Gate {\n held: Set<Hold>;\n queue: Waiter[];\n}\n\ninterface Hold {\n run: Run;\n from: string;\n}\n\ninterface Slot {\n max: number | ((...args: any[]) => number);\n key: unknown;\n}\n\ninterface Waiter {\n hold: Hold;\n max(): number;\n grant(): void;\n}\n\nconst HOOKS = new Set(['before', 'after']);\nconst KEYS = ['status', 'active', 'queue', 'waiting', 'runs', 'error'] as const;\nconst SLACK = 8;\nconst LONGEST = 2 ** 31 - 1;\nconst GATES = new WeakMap<object, Gate>();\nconst UNCAUGHT = ['gate', 'end'];\nconst UNPLANNED = ['end', 'gate', 'wait'];\nconst RESERVED = ['then', 'end', 'gate', 'wait'];\nconst REFRESH = Symbol.for('@expressive/mvc.refresh');\nconst ISSUED = new WeakMap<object, Frame>();\nconst RETRY = new WeakSet<Function>();\nconst RULES = new WeakSet<Error>();\nconst KINDS: Kind[] = ['reset', 'catch', 'abort', 'close'];\nconst MODES = { failed: 'error', aborted: 'abort', stopped: 'stop' } as const;\nconst UNITS: Record<string, number> = { ms: 1, sec: 1e3, min: 6e4, hr: 36e5, day: 864e5 };\n\nconst TOKEN = {\n catch(this: Steps.Node, handler?: unknown) {\n return ISSUED.get(this)!.rescue(this, handler);\n }\n};\n\ndeclare namespace Steps {\n /**\n * Where the instance stands - reactive through `then.status`.\n *\n * `idle` - no run, or the last ended cleanly. `running`. `waiting` - parked on an open wait.\n * `stopped`, `aborted`, `failed` - how the last run ended; held until the next one starts.\n */\n type Status = 'idle' | 'running' | 'waiting' | 'stopped' | 'aborted' | 'failed';\n\n /** The run's result - what `run` resolves with; types `x.run()` and `await x`. */\n type Result<T> = T extends { run(...args: any[]): infer R } ? Awaited<R> : unknown;\n\n /** A planned item: a step, a parallel group (`group`), or a wait (`answers`). */\n interface Node {\n id: string;\n key: string;\n /** Arguments - a duration wait's milliseconds. */\n args: unknown[];\n group?: Node[];\n /** Keys of the steps which may answer this wait - none for a duration. */\n answers?: string[];\n /** Steps raced against the answers - cancelled once one answers. */\n race?: Node;\n /** Caught by `.catch()`: a step given the error (its key), `then` for a function, or `true` for none. */\n rescue?: string | true;\n }\n\n /** What calling a step inside a step returns - inert, not awaitable; scheduled once the caller settles. */\n type Token = Readonly<Node>;\n\n /**\n * A committed step, as `after` receives it - keys and arguments, no values.\n *\n * `id` is `key#n`, e.g. `pay#1`. The Runner keeps no journal - collect entries in `after`.\n */\n interface Entry {\n id: string;\n key: string;\n args: unknown[];\n /** What the step scheduled. */\n next: Node[];\n /** Fields the step wrote, collections changed in place included. */\n wrote: string[];\n /** Handlers the step registered with `then.on()`, by outcome, in order: a step method given uncalled or steps called for one (by key), or `then` for a function. */\n on?: { [K in keyof On]?: Node[] };\n /** Taken back by an unwind - resets run, fields restored; `'failed'` when a handler threw. */\n unwound?: true | 'failed';\n /** Id of the wait this step answered. */\n wake?: string;\n /** How many times `then.retry()` replayed the step, when past its first run. */\n retried?: number;\n /** What the step threw - a caught failure, or one which kept its writes. */\n error?: unknown;\n /** Collections changed in a way no restore can undo - the unwind stops here. */\n irreversible?: string[];\n /** The step called `then.commit()` - not retried, restored or undone; the unwind stops here. */\n committed?: true;\n /** The unwind stopped at this entry; it and every entry before it stay applied. */\n halted?: true;\n /** An `end` the runtime added - the plan drained without one. */\n implicit?: true;\n }\n\n /** An open wait, as listed by `then.waiting`. */\n interface Wait {\n id: string;\n /** Key of the step which opened the wait. */\n step: string;\n /** Arguments of the step which opened the wait. */\n args: unknown[];\n /** Keys of the steps which may answer it. */\n answers: string[];\n /** When a duration wait closes, in epoch milliseconds. */\n until?: number;\n }\n\n /**\n * A `then.on` handler.\n *\n * A function - given the error, or nothing on a cancellation; process-local. For a durable run:\n * a step method uncalled - given the same, recorded - or steps called for it, an array a group.\n */\n type Handler = { handler(reason?: unknown): unknown }['handler'] | Promise<void> | readonly Promise<void>[];\n\n /**\n * Handlers for the outcomes of a step and everything it schedules.\n *\n * Per step they fire `catch`, `abort`, `reset`, `close`; across steps deepest first, newest first.\n * Handlers run before fields are restored and see the step's partial writes; keys they write are kept.\n */\n interface On {\n /**\n * The step is taken back - reset its effects.\n *\n * A failure leaving its subtree, `abort()`, a lost race; not `stop()`. Fields are restored after it.\n */\n reset?: Handler;\n /**\n * A failure below that no closer `.catch` took - return to recover, throw to pass it on.\n *\n * Recovering unwinds the failed part of the subtree; the step's own effects stay and its `reset`\n * does not run; steps it schedules replace the rest. One per step; runs before a `.catch` on the\n * step's call. `then.retry()` replays the step.\n */\n catch?: Handler;\n /**\n * The subtree ended without completing - `commit()`'s counterpart.\n *\n * Given the error of a failure no `catch` recovered; nothing for a cancellation (`abort()`, `stop()`,\n * a lost race) - `then.status` tells which. Skips a clean end, a recovered failure and `then.end()`.\n */\n abort?: Handler;\n /** The subtree ended, any way - a finally over it, last. */\n close?: Handler;\n }\n\n /** Why a run or subtree ended: `abort()`, or a lost race. */\n type Aborted = InstanceType<typeof Steps.Aborted>;\n /** Why a run or subtree ended: `stop()`. */\n type Stopped = InstanceType<typeof Steps.Stopped>;\n\n /** A plain copy of the controller's reactive fields - `then.get()`. */\n interface Snapshot {\n status: Status;\n active: string | undefined;\n queue: unknown[][];\n waiting: Wait[];\n runs: number;\n error: unknown;\n }\n\n interface Controller<T extends Model = Model> {\n /**\n * Inside a step: park the plan for a duration - units summed.\n *\n * A wait nothing answers, journaled `wait#n` with `args: [ms]`. The next step in sequence runs once\n * it passes - backoff, timeouts, nudges.\n *\n * @example\n * this.then({ sec: 30 });\n * this.retryUpload();\n */\n <This>(this: This, duration: { ms?: number; sec?: number; min?: number; hr?: number; day?: number }): Promise<void>;\n\n /**\n * Inside a step: one parallel group of `each`, called per item.\n *\n * `each` is a function issuing a step, or a step itself. The next step in sequence runs once every\n * member, and all it schedules, is done.\n *\n * @example\n * this.then(this.files, this.upload);\n * this.then(this.sites, (site) => this.scan(site, 'deep'));\n */\n <I, This>(this: This, items: Iterable<I>, each: (item: I, index: number) => unknown): Promise<void>;\n\n /**\n * Inside a step: park the plan until one of these steps is called.\n *\n * Status `waiting`. Answering steps read `undefined` from outside unless an open wait accepts them.\n * An outside call answers the wait whose opening step's first argument `===` its own, else the\n * oldest; its Promise resolves when that answer's subtree is done. A call no wait accepts throws.\n *\n * @example\n * this.then(this.approve, this.reject);\n */\n <This>(this: This, ...steps: ((...args: any[]) => unknown)[]): Promise<void>;\n\n /**\n * Inside a step: run these tokens as one parallel group.\n *\n * The next step in sequence runs once every member, and all it schedules, is done. Beside steps\n * uncalled, each called step is a racer, started when the plan reaches the wait: the first answer\n * wins and keeps all it did; losers' signals abort, what they scheduled drops, and each losing\n * branch unwinds - resets run, fields restored.\n *\n * @example\n * this.then(this.ship(order), this.receipt(order));\n * this.then(this.allow, this.deny, this.timeout(call));\n */\n <This>(this: This, ...steps: unknown[]): Promise<void>;\n\n /** The instance this controller runs. */\n readonly self: T;\n /** Where the instance stands - see {@link Steps.Status}. */\n readonly status: Steps.Status;\n /** Key of a step in flight - the latest invoked, with a group in flight. */\n readonly active: string | undefined;\n /** Arguments of each `run()` waiting for the active run to finish. */\n readonly queue: readonly unknown[][];\n /** Open waits, oldest first - durations included. */\n readonly waiting: readonly Steps.Wait[];\n /** Runs finished - ended, failed, stopped or aborted. */\n readonly runs: number;\n /** What failed the last run; cleared when the next starts. */\n readonly error: unknown;\n\n /** A plain snapshot of status, active, queue, waiting, runs and error. */\n get(): Steps.Snapshot;\n\n /**\n * End the run early, keeping everything.\n *\n * Inside a step, where the plan reaches it; from outside, now. Steps in flight settle, what they\n * schedule drops, only `close` fires; `run`'s tail then builds the result from fields. Takes no\n * value - write why it ended to a field first. To halt now, `stop()` or `abort()`.\n *\n * @example\n * if (this.found) this.then.end();\n * else this.next();\n */\n end(): void;\n\n /**\n * Inside a step: a gate - only `max` at once; what the step schedules after it holds a slot until done.\n *\n * Queues FIFO. `max` as a function of `$`, the tracking proxy, is re-read live; `0` pauses. `key`\n * shares the queue: an object across groups and instances (`only(1, this.manager)` is a mutex), any\n * other value across this instance. Default: the enclosing group's, else the instance's. A delay\n * before queueing is a duration ahead of it.\n *\n * @example\n * this.then.only(($) => $.concurrency);\n * this.upload(file);\n */\n only(max: number | (($: T) => number), key?: unknown): void;\n\n /**\n * Halt, keeping what was done - status `stopped`.\n *\n * Pending steps and queued runs drop; in-flight steps settle and commit. The run, the queue and\n * in-flight signals reject with a `Steps.Stopped` - `reason` as its `cause`, and its message when a string.\n * `set(null)` on the instance stops too.\n */\n stop(reason?: unknown): void;\n\n /**\n * Halt and unwind, as a failure would - status `aborted`.\n *\n * The run's resets run, newest first, and fields are restored. The run and queue reject with a\n * `Steps.Aborted`, `reason` as for `stop`. A reset which throws fails the run: its error, given the\n * `Steps.Aborted` as `cause`.\n */\n abort(reason?: unknown): void;\n\n /**\n * Inside a step: a point of no return.\n *\n * The step is not caught, retried, restored or undone; an unwind stops here and what came before stands.\n */\n commit(): void;\n\n /**\n * Inside a step: handlers for the outcomes of this step and all it schedules - see {@link Steps.On}.\n *\n * Register right after the effect it undoes. An unknown key throws.\n *\n * @example\n * const hold = await inventory.hold(this.cart.items);\n *\n * this.then.on({ reset: () => inventory.release(hold) });\n * this.pay();\n */\n on(handlers: Steps.On): void;\n\n /** Inside a `.catch` handler: restore the caught branch's fields now; writes after it stand. */\n restore(): void;\n\n /**\n * Inside a step: its `AbortSignal` - pass it to the call the step awaits.\n *\n * Aborted on `stop()` or `abort()`, an outside `end`, a failure elsewhere, a race lost, and once the\n * step settles. A step rejecting with its reason is not a failure.\n *\n * @example\n * this.page = await fetch(this.url, { signal: this.then.signal });\n */\n readonly signal: AbortSignal;\n\n /** Inside a step: how many times `then.retry()` replayed it - `0` on a first run. In a handler, the failed one's. */\n readonly retried: number;\n\n /**\n * Inside a `.catch` handler: schedule what the catch is attached to again, under the same handler.\n *\n * The failed step or the whole group, with its recorded args. The handler holds the policy; backoff\n * belongs in the retried step. Throws outside a handler.\n *\n * @example\n * this.scan(site).catch((error) => {\n * if (this.then.retried >= 3) throw error;\n * this.then.retry();\n * });\n */\n retry(): void;\n }\n\n interface Thenable<T extends Model = Model> {\n /**\n * Join the active run - or, idle, call `run()`; settles with the last queued run's result.\n *\n * Rejects if idle and `run` takes arguments - give an optional one a default.\n */\n <R1 = Steps.Result<T>, R2 = never>(\n onfulfilled?: ((value: Steps.Result<T>) => R1 | PromiseLike<R1>) | null,\n onrejected?: ((reason: unknown) => R2 | PromiseLike<R2>) | null\n ): Promise<R1 | R2>;\n\n then: Steps.Runner<T>;\n }\n\n /** The controller, and a thenable - so the instance, with it as `then`, is awaitable. */\n type Runner<T extends Model = Model> = Controller<T> & Thenable<T>;\n}\n\nfunction install<T extends Steps>(self: T) {\n const runner = function (onfulfilled?: unknown, onrejected?: unknown) {\n if (onfulfilled && typeof onfulfilled == 'object') throw rule('then(steps) must be called inside a step.');\n\n return control.settled().then(onfulfilled as any, onrejected as any);\n } as Steps.Runner<T>;\n\n const control = Control.new({ _self: self, _runner: runner });\n\n const read: Record<(typeof KEYS)[number], () => unknown> = {\n status: () => control.status,\n active: () => control.active,\n queue: () => control.queue.map((ticket) => ticket.args),\n waiting: () => control.run.waits.map(({ id, step, args, answers, until }) => ({ id, step, args, answers, ...until !== undefined && { until } })),\n runs: () => control.runs,\n error: () => control.error\n };\n\n for (const key of KEYS)\n Object.defineProperty(runner, key, {\n enumerable: true,\n get(this: object) {\n return touch(this, key, read[key]());\n }\n });\n\n Object.defineProperties(runner, {\n then: { value: runner },\n self: { value: self },\n get: { value: () => Object.fromEntries(KEYS.map((key) => [key, read[key]()])) },\n end: { value: (...value: unknown[]) => void (valueless(value), control.conclude()) },\n stop: { value: (reason?: unknown) => control.stop(false, reason) },\n abort: { value: (reason?: unknown) => control.stop(true, reason) },\n only: { value: () => outside('only') },\n commit: { value: () => outside('commit') },\n on: { value: () => outside('on') },\n restore: { value: () => outside('restore') },\n signal: { get: () => outside('signal', 'read') },\n retry: { value: () => outside('retry') },\n retried: { get: () => outside('retried', 'read') }\n });\n\n event(runner);\n\n Object.defineProperty(self, 'then', {\n configurable: true,\n get(this: object) {\n const view = touch(this, 'then', runner);\n\n return view === runner ? runner : Object.setPrototypeOf((...args: [any?, any?]) => runner(...args), view);\n }\n });\n\n const { _hooks: hooks, _steps: steps } = control;\n\n const wire = () => {\n for (const key of steps.keys()) delete (self as any)[key];\n\n steps.clear();\n hooks.clear();\n\n for (let proto = Object.getPrototypeOf(self); proto !== Model.prototype; proto = Object.getPrototypeOf(proto))\n for (const [key, desc] of Object.entries(Object.getOwnPropertyDescriptors(proto))) {\n let method = desc.get && unbind(desc.get) !== desc.get;\n let skip = !method || key == 'new' || key[0] == '_' || Object.hasOwn(self, key);\n\n if (skip) continue;\n\n if (key == 'end') throw rule(`${self.constructor.name} declares end; return the result from run, end early with this.then.end().`);\n if (RESERVED.includes(key)) throw rule(`${self.constructor.name} declares ${key}; then, end, gate and wait name plan tokens - rename the step.`);\n\n if (HOOKS.has(key)) {\n if (!hooks.has(key)) hooks.set(key, unbind(desc.get!));\n continue;\n }\n\n const step = (...args: unknown[]) => control.call(key, args);\n\n steps.set(key, unbind(desc.get!));\n Object.defineProperty(\n self,\n key,\n key == 'run'\n ? { value: step, writable: true, configurable: true }\n : {\n configurable: true,\n get(this: object) {\n touch(this, key);\n return control.accepts(key) ? step : undefined;\n }\n }\n );\n }\n };\n\n wire();\n listener(self, (key) => void (key === REFRESH && wire()));\n\n self.get(null, () => control.stop());\n}\n\nclass Aborted extends Error {\n override name = 'Aborted';\n}\n\nclass Stopped extends Error {\n override name = 'Stopped';\n}\n\n/**\n * A runnable Model: every method is a step, a step schedules the next by calling it.\n *\n * Fields carry data between steps. Each step is atomic and registers its own reset; a failure unwinds\n * what committed. `run()` starts a run; awaiting the instance joins it. In-process only.\n *\n * @example\n * class Checkout extends Steps {\n * cart!: Cart;\n * charge?: Charge = undefined;\n *\n * async run() {\n * this.pay();\n * await this;\n * return this.charge!.id;\n * }\n *\n * protected async pay() {\n * this.charge = await stripe.charge(this.cart.total);\n * this.then.on({ reset: () => stripe.refund(this.charge!.id) });\n * }\n * }\n *\n * const id = await Checkout.new({ cart });\n */\nclass Steps extends Model {\n /** Why a run or subtree ended: `abort()`, or a lost race. */\n static readonly Aborted = Aborted;\n /** Why a run or subtree ended: `stop()`. */\n static readonly Stopped = Stopped;\n\n /**\n * The controller - plan tokens inside a step, status and control from outside.\n *\n * Its fields are reactive through the instance: `x.get(($) => $.then.status)`, or read in a render.\n * Enumerable - `{ ...x.then }` snapshots; not in `instance.get()`. Awaiting the instance awaits it.\n */\n declare readonly then: Steps.Runner<this>;\n\n constructor(...args: Model.Args) {\n super(...args);\n install(this);\n }\n\n /**\n * The entry - starts a run, or queues one while a run is active; settles with what it returns.\n *\n * Must be `async`; the only step callable from outside. Before `await this`: field writes and step\n * calls only. After it, the tail: read fields, return or throw - step calls throw. Without `await this`\n * it settles at once. `return await this` is a TS circularity - return from fields. Inside a step,\n * `this.run()` throws.\n *\n * @example\n * async run(url: string) {\n * this.fetch(url);\n * await this;\n * return this.rows;\n * }\n */\n run?(...args: any[]): Promise<unknown>;\n\n /** Hook: before each step. Synchronous, the raw instance as `this`; writes are unjournaled. */\n protected before?(step: string, args: unknown[]): void;\n\n /**\n * Hook: after each step commits, given its entry - the only journal there is.\n *\n * Synchronous, the raw instance as `this`; writes are unjournaled. A try a catch took, and the failure\n * ending the run, arrive with `entry.error`; a called `end` arrives too, an implicit one does not.\n *\n * @example\n * protected after(step: string, entry: Steps.Entry) {\n * this.log.push(entry);\n * }\n */\n protected after?(step: string, entry: Steps.Entry): void;\n}\n\nclass Control extends Model {\n status: Steps.Status = 'idle';\n active: string | undefined = undefined;\n runs = 0;\n error: unknown = undefined;\n queue = has<Ticket>();\n run = new Run();\n\n _self!: Model;\n _runner!: object;\n _steps = new Map<string, Function>();\n _hooks = new Map<string, Function>();\n _gates = new Map<unknown, Gate>();\n _current?: Run = undefined;\n\n protected new() {\n const { _runner } = this;\n\n listener(this.queue, (key) => {\n if (signal(key)) event(this, 'queue');\n });\n\n return this.set((key) => void event(_runner, key as string));\n }\n\n call(key: string, args: unknown[]) {\n if (key == 'run') return this.start(args);\n\n const { _current: current } = this;\n const wait = current && current.route(key, args);\n\n if (wait) return current!.wake(wait, key, args);\n\n throw rule(`${key} cannot be called from outside; call run() to start a run.`);\n }\n\n accepts(key: string) {\n return !!this._current?.accepts(key);\n }\n\n hook(key: string, ...args: unknown[]) {\n return this._hooks.get(key)?.apply(this._self, args);\n }\n\n start(args: unknown[]) {\n const ticket = { args } as Ticket;\n\n ticket.promise = new Promise((resolve, reject) => {\n ticket.resolve = resolve;\n ticket.reject = reject;\n });\n\n ticket.promise.catch(() => {});\n\n if (this._current) this.queue.push(ticket);\n else this.begin(ticket);\n\n return handle(ticket, (resolve, reject) => ticket.promise.then(resolve, reject));\n }\n\n begin(ticket: Ticket) {\n const run = new Run({ _ticket: ticket });\n\n this._current = this.run = run;\n this.error = undefined;\n this.status = 'running';\n\n run.start();\n }\n\n advance() {\n const next = this.queue.pop(0);\n\n if (next) this.begin(next);\n }\n\n tail() {\n return this.queue.get(-1) || this.run._ticket;\n }\n\n settled() {\n if (!this._current) {\n if (this._steps.get('run')?.length)\n return Promise.reject(new Error(`${this._self} is idle. run() takes arguments; call it to start a run.`));\n\n this.start([]);\n }\n\n return this.join();\n }\n\n join(): Promise<unknown> {\n const ticket = this.tail()!;\n const tickets = [this._current?._ticket, ...this.queue, ticket].filter(Boolean) as Ticket[];\n\n for (const each of tickets) each.awaited = true;\n\n return ticket.promise.then(\n (value) => (this.tail() === ticket ? value : this.join()),\n (error) => (this.tail() === ticket ? Promise.reject(error) : this.join())\n );\n }\n\n conclude() {\n const { _current: run } = this;\n\n if (run && !run.stale()) run.terminate(run.node('end', []));\n }\n\n stop(undo?: boolean, reason?: unknown) {\n const { _current: current, queue } = this;\n\n if (!current) return;\n\n const message = typeof reason == 'string' ? reason : `${this._self} was ${undo ? 'aborted' : 'stopped'}.`;\n const stopped = new (undo ? Aborted : Stopped)(message, reason === undefined ? undefined : { cause: reason });\n\n for (const ticket of queue) ticket.reject(stopped);\n\n queue.clear();\n\n current._stopped = stopped;\n current.release();\n current.halt(undo ? 'aborted' : 'stopped');\n }\n}\n\nclass Run extends Model {\n control = get(Control);\n frames = has(Frame);\n waits = has(Wait);\n\n _ticket!: Ticket;\n _entries: Steps.Entry[] = [];\n _counts = new Map<string, number>();\n _on = new Map<string, Handler[]>();\n _finished = new Set<string>();\n _reset = new Set<string>();\n _writer = new Map<string, string>();\n _lost = new Set<string>();\n _losing = new Map<string, Promise<unknown>>();\n _held = new Map<string, Held>();\n _inline = new Map<string, Function>();\n _errors = new Map<string, unknown>();\n _owner = new Map<string, Frame>();\n _parent = new Map<string, string>();\n _slots = new Map<string, Slot>();\n _catches = new Map<string, Rescue>();\n _branches = new Map<string, Branch>();\n _lineage = new Map<string, Lineage>();\n _retried = new Map<string, number>();\n _gates = new Map<string, Gate>();\n _groups = new Set<string>();\n _pending = new Map<string, () => void>();\n _holding = new Map<() => void, string>();\n _dropped = new Set<string>();\n _spent = new Set<string>();\n _unwinding?: Promise<unknown> = undefined;\n _drained: (() => void)[] = [];\n _quiet = new Set<() => void>();\n _halted?: 'failed' | 'stopped' | 'aborted' = undefined;\n _ending?: boolean = undefined;\n _settling?: boolean = undefined;\n _error?: unknown = undefined;\n _stopped?: Error = undefined;\n _root?: string = undefined;\n _result?: unknown = undefined;\n _tail?: Promise<unknown> = undefined;\n _await?: { resolve(value?: unknown): void; reject(error: unknown): void } = undefined;\n\n protected new() {\n const { control } = this;\n\n listener(this.waits, (key) => {\n let current = signal(key) && control._current === this;\n\n if (!current) return;\n\n event(control, 'waiting');\n\n control.status = this.waits.size ? 'waiting' : this._halted || 'running';\n });\n }\n\n start() {\n const node = this.node('run', this._ticket.args);\n\n this._root = node.id;\n this.exec(node).then(() => {\n if (!this._halted && !this._ending) this.end();\n });\n }\n\n node(key: string, args: unknown[]): Steps.Node {\n const count = (this._counts.get(key) || 0) + 1;\n\n this._counts.set(key, count);\n\n return Object.assign(Object.create(TOKEN), { id: `${key}#${count}`, key, args }) as Steps.Node;\n }\n\n route(key: string, args: unknown[], from?: Frame) {\n const open = this.waits.filter((wait) => wait.answers.includes(key));\n\n return open.find((wait) => wait._from === from) || open.find((wait) => wait.args[0] === args[0]) || open[0];\n }\n\n accepts(key: string, except?: Wait) {\n return this.waits.any((wait) => wait !== except && wait._open && wait.answers.includes(key));\n }\n\n flight() {\n return this.frames.filter((frame) => !frame._undo);\n }\n\n stale() {\n return !!(this._halted || this._ending);\n }\n\n dropped(id: string) {\n return this.line(id).some((at) => this._dropped.has(at) || (at !== id && this._dropped.has(at + '^')));\n }\n\n line(id: string) {\n const ids: string[] = [];\n\n for (let at: string | undefined = id; at; at = this._parent.get(at)) ids.push(at);\n\n return ids;\n }\n\n async exec(item: Steps.Node, from?: Frame): Promise<void> {\n if (this.stale() || this.dropped(item.id)) return;\n\n const rescue = this._catches.get(item.id);\n\n if (rescue && !this._branches.has(item.id)) return this.guard(item, from!, rescue);\n\n if (item.group) {\n await Promise.all(item.group.map((member) => this.exec(member, from)));\n return;\n }\n\n if (item.answers) {\n const answer = await this.park(item, from!);\n\n if (answer) {\n const frame = await answer.frame;\n\n await this.cover(frame);\n await this.complete(frame);\n answer.done();\n }\n }\n else if (item.key == 'end') await this.terminate(item);\n else {\n const wait = this.racing(item);\n\n if (wait) return void this.wake(wait, item.key, item.args, item);\n\n const frame = await this.invoke(item);\n\n await this.cover(frame, item);\n await this.complete(frame);\n }\n }\n\n async cover(frame?: Frame, item?: Steps.Node) {\n const handler = frame && this._on.get(frame.id)?.find(({ kind }) => kind == 'catch');\n\n if (!handler) return this.descend(frame);\n\n const { id, key, args, _failed: failed } = frame!;\n const shield = id + '^';\n const branch: Branch = { failed };\n\n item ||= Object.assign(Object.create(TOKEN), { id, key, args });\n\n if (!failed) {\n this._branches.set(shield, branch);\n await this.descend(frame);\n this._branches.delete(shield);\n }\n\n if (!branch.failed) return;\n\n const { cause } = branch.failed;\n const restore = await this.serial(() => (failed ? this.rewind(id, cause) : this.recover(item!, cause, 'error', false)));\n\n this._dropped.delete(shield);\n\n if (this.stale()) return restore();\n\n const node = this.given(handler, cause);\n\n this._parent.set(node.id, id);\n this._lineage.set(node.id, { restore, caught: item! });\n this._retried.set(node.id, this.retried(item!));\n\n await this.exec(node, frame);\n restore();\n }\n\n async rewind(id: string, cause: unknown): Promise<Restore> {\n const entry = this._entries.find((each) => each.id == id)!;\n const { prior, log } = this._held.get(id)!;\n const kept = new Set<string>();\n\n this._reset.add(id);\n this._held.delete(id);\n\n try {\n await this.fire(this._on.get(id), 'reset', undefined, kept);\n entry.unwound = true;\n } catch (thrown) {\n entry.unwound = 'failed';\n this.halt('failed', thrown);\n }\n\n const self = this.control._self as any;\n let done = false;\n\n return (into, all) => {\n if (done) return;\n\n done = true;\n\n for (const key in prior) {\n const wrote = into?._wrote.has(key);\n\n if (wrote) into!._prior[key] = prior[key];\n if (all || (!wrote && !kept.has(key))) self[key] = prior[key];\n }\n\n for (const [key, undo] of [...log].reverse()) if (all || !into?._changed.has(key)) undo();\n };\n }\n\n async complete(frame?: Frame) {\n const on = frame && this._on.get(frame.id);\n\n if (!on) return;\n\n const { id } = frame!;\n const losing = [...this._losing].filter(([racer]) => this.line(racer).includes(id));\n\n await Promise.all(losing.map(([, unwind]) => unwind));\n\n if (this.stale() || this.dropped(id)) return;\n\n this._finished.add(id);\n\n try {\n await this.fire(on, 'close', undefined, new Set());\n } catch (error) {\n if (!this.caught(error, id)) this.halt('failed', error);\n }\n }\n\n async fire(on: Handler[] | undefined, kind: Kind, cause: unknown, kept: Set<string>) {\n for (const handler of [...(on || [])].reverse())\n if (handler.kind == kind) await this.compensate(this.given(handler, cause), cause, kept, kind == 'reset' || kind == 'close' || cause === undefined);\n }\n\n given({ node, bare, kind }: Handler, cause: unknown) {\n if (bare && (kind == 'catch' || (kind == 'abort' && cause !== undefined))) {\n node.args = [serial(cause)];\n this._errors.set(node.id, cause);\n }\n else if (kind == 'catch' && this._inline.has(node.id)) node.args = [cause];\n\n return node;\n }\n\n racing(item: Steps.Node) {\n const line = this.line(item.id);\n\n return this.waits.filter((wait) => !!wait._race && line.includes(wait.id) && wait.answers.includes(item.key))[0];\n }\n\n lose(wait: Wait, won: string[], answer: Steps.Node) {\n const race = wait._race!;\n const losers = (race.group || [race]).filter((racer) => !won.includes(racer.id));\n const cause = new Aborted(`${answer.key} answered ${wait.id}.`);\n\n for (const racer of losers) {\n this._dropped.add(racer.id);\n this._lost.add(racer.id);\n }\n\n for (const frame of this.discard()) frame._abort.abort(cause);\n for (const [release, from] of this._holding) if (this.dropped(from)) release();\n\n for (const racer of losers)\n this._losing.set(\n racer.id,\n this.serial(async () => {\n await this.quiet(racer.id);\n (await this.recover(racer, cause, 'abort'))(undefined, false, racer.id);\n })\n );\n }\n\n quiet(id: string) {\n const busy = () => this.flight().some((frame) => this.line(frame.id).includes(id));\n\n return new Promise<void>((resolve) => {\n const check = () => {\n if (busy()) return;\n\n this._quiet.delete(check);\n resolve();\n };\n\n this._quiet.add(check);\n check();\n });\n }\n\n terminate(item: Steps.Node) {\n this.release();\n\n return this.end(item);\n }\n\n serial<T>(task: () => Promise<T>) {\n const prior = this._unwinding;\n const next = (async () => {\n await prior;\n return task();\n })();\n\n this._unwinding = next;\n\n return next;\n }\n\n async guard(item: Steps.Node, from: Frame, rescue: Rescue) {\n const branch: Branch = {};\n\n this._branches.set(item.id, branch);\n\n await this.exec(item, from);\n\n this._branches.delete(item.id);\n\n if (!branch.failed) return;\n\n const { cause } = branch.failed;\n const restore = await this.serial(() => this.recover(item, cause, 'error'));\n const { key, fn } = rescue;\n const parent = this._parent.get(item.id)!;\n\n if (this.stale() || !fn) return restore();\n\n const node = this.node(key || 'then', key ? [serial(cause)] : [cause]);\n\n if (key) this._errors.set(node.id, cause);\n\n this._parent.set(node.id, parent);\n this._lineage.set(node.id, { restore, caught: item });\n this._retried.set(node.id, this.retried(item));\n\n if (!key) {\n this._inline.set(node.id, fn!);\n this._owner.set(node.id, from);\n }\n\n await this.exec(node, from);\n restore();\n }\n\n retried(item: Steps.Node) {\n return this._retried.get(item.id) || 0;\n }\n\n copy(item: Steps.Node, retried = this.retried(item) + 1): Steps.Node {\n const { id, key, args, group, answers, race } = item;\n const node = this.node(key, args);\n const rescue = this._catches.get(id);\n\n this._retried.set(node.id, retried);\n\n if (group) {\n node.group = group.map((member) => this.copy(member, retried));\n this._groups.add(node.id);\n adopt(this._parent, node.group, node.id);\n }\n\n if (answers) node.answers = answers;\n\n if (race) {\n node.race = this.copy(race, retried);\n adopt(this._parent, [node.race], node.id);\n }\n\n if (rescue) {\n node.rescue = item.rescue;\n this._catches.set(node.id, rescue);\n }\n\n return node;\n }\n\n async recover(item: Steps.Node, cause: unknown, mode: Mode, own = true): Promise<Restore> {\n const ids = this._entries.filter((entry) => !this._spent.has(entry.id) && (own || entry.id != item.id) && this.line(entry.id).includes(item.id));\n const unwound = await this.unwind(cause, mode, new Set(ids.map((entry) => entry.id)));\n let done = false;\n\n const restore: Restore = (into, all, within) => {\n if (done) return;\n\n done = true;\n this.refill(unwound, into, all, within);\n };\n\n if (unwound.failed) {\n const { cause: thrown } = unwound.failed;\n\n restore();\n\n if (mode == 'abort') chain(thrown, cause);\n\n this.halt('failed', thrown);\n }\n\n return restore;\n }\n\n caught(error: unknown, id: string) {\n if (this.stale() || RULES.has(error as Error)) return false;\n\n let at: string | undefined;\n\n for (const each of this.line(id))\n if (each != id && this._branches.has((at = each + '^'))) break;\n else if (this._branches.has((at = each))) break;\n else at = undefined;\n\n if (!at) return false;\n\n const branch = this._branches.get(at)!;\n\n if (branch.failed) return true;\n\n branch.failed = { cause: error };\n this._dropped.add(at);\n\n for (const frame of this.discard()) frame._abort.abort();\n\n return true;\n }\n\n discard() {\n for (const wait of this.waits.filter((wait) => this.dropped(wait.id))) this.waits.delete(wait);\n for (const [id, cancel] of this._pending) if (this.dropped(id)) cancel();\n\n return this.flight().filter((frame) => this.dropped(frame.id));\n }\n\n async descend(frame?: Frame) {\n if (frame) await this.sequence(frame._items, frame);\n }\n\n async sequence(items: Steps.Node[], from: Frame): Promise<void> {\n for (const [index, item] of items.entries()) {\n if (item.key != 'gate') {\n await this.exec(item, from);\n continue;\n }\n\n const release = await this.acquire(item, from);\n\n if (!release) return;\n\n try {\n await this.sequence(items.slice(index + 1), from);\n } finally {\n release();\n }\n\n return;\n }\n }\n\n acquire(item: Steps.Node, from: Frame) {\n if (this.stale() || this.dropped(item.id)) return;\n\n const { id } = item;\n const { max, key } = this._slots.get(id)!;\n const gate = this.gate(from, key);\n const line = this.line(from.id);\n const hold: Hold = { run: this, from: from.id };\n const inside = [...gate.held].some((each) => each.run === this && line.includes(each.from));\n const self = this.control._self;\n\n return new Promise<(() => void) | undefined>((resolve) => {\n let quiet: (() => void) | undefined;\n let limit = 0;\n let over = false;\n\n const finish = (release?: () => void) => {\n over = true;\n quiet?.();\n this._pending.delete(id);\n resolve(release);\n };\n\n const release = () => {\n if (!gate.held.delete(hold)) return;\n\n this._holding.delete(release);\n pump(gate);\n };\n\n const waiter: Waiter = {\n hold,\n max: typeof max != 'function' ? () => max : max.length ? () => limit : (max as () => number),\n grant: () => {\n this._holding.set(release, from.id);\n finish(release);\n }\n };\n\n if (inside) return finish(() => {});\n\n this._pending.set(id, () => {\n gate.queue = gate.queue.filter((each) => each !== waiter);\n finish();\n });\n\n if (typeof max == 'function')\n quiet = max.length\n ? watch(self, ($) => {\n limit = max($);\n pump(gate);\n\n return over ? null : undefined;\n })\n : listener(self, (key) => void (signal(key) && pump(gate)));\n\n gate.queue.push(waiter);\n pump(gate);\n });\n }\n\n gate(from: Frame, key: unknown) {\n const { control } = this;\n\n if (key instanceof Object) return gate(GATES, key);\n if (key !== undefined) return gate(control._gates, key);\n\n const group = this.line(from.id).find((id) => this._groups.has(id));\n\n return group ? gate(this._gates, group) : gate(control._gates, control);\n }\n\n park(item: Steps.Node, from: Frame) {\n return new Promise<Answer | undefined>((resolve) => {\n const { id, answers, race, args } = item;\n const until = answers!.length ? undefined : Date.now() + (args[0] as number);\n\n this.waits.add({ id, step: from.key, args: from.args, answers, until, _race: race, _from: from, _park: resolve });\n\n if (race) void this.exec(race, from);\n });\n }\n\n wake(wait: Wait, key: string, args: unknown[], node = this.node(key, args)) {\n const { _ticket } = this;\n let done!: () => void;\n let fail!: (error: unknown) => void;\n\n const answered = handle<void>(_ticket, (res, rej) => {\n done = res;\n fail = rej;\n });\n\n const answer = { done: () => (this._halted ? fail(this.reason()) : done()), fail } as Answer;\n const won = this.line(node.id);\n\n wait._answer = answer;\n this._parent.set(node.id, wait.id);\n this.waits.delete(wait);\n\n if (wait._race) this.lose(wait, won, node);\n\n answer.frame = this.invoke(node, wait.id);\n\n return answered;\n }\n\n release() {\n this.waits.clear();\n\n for (const cancel of this._pending.values()) cancel();\n for (const release of this._holding.keys()) release();\n }\n\n async invoke(node: Steps.Node, wake?: string, undo?: boolean): Promise<Frame | undefined> {\n const { control } = this;\n const { id, key, args } = node;\n const inline = this._inline.get(id);\n const lineage = this._lineage.get(id);\n const fn = inline || control._steps.get(key)!;\n const frame = this.frames.add({ id, key, args, _wake: wake, _undo: undo, _owner: this._owner.get(id), _retried: this.retried(node), ...lineage && { _restore: lineage.restore, _caught: lineage.caught } });\n const input = this._errors.has(id) ? [this._errors.get(id)] : args;\n let body = false;\n\n control.active = key;\n\n try {\n control.hook('before', key, args);\n\n if (!fn) throw rule(key == 'run' ? `${control._self} declares no run - add async run() to start a run.` : `${key} was removed by a hot update.`);\n\n for (;;)\n try {\n const call = inline ? fn(...input) : fn.apply(frame._proxy, input);\n const out = id == this._root ? await frame.open(call) : await call;\n\n frame._settled = true;\n\n const entry = frame.commit(out);\n\n frame._restore?.(frame);\n control.hook('after', key, entry);\n\n return frame;\n } catch (thrown) {\n if (frame._entry) throw thrown;\n\n let error = thrown;\n let irreversible = [...frame._lost];\n let fixed = irreversible.length || frame._committed;\n\n body = !frame._settled;\n\n if (error instanceof Promise && body && !fixed) {\n await this.fire(frame._on, 'reset', undefined, new Set());\n\n this.reset(frame);\n\n const failed = await frame.pause(error);\n\n if (!failed) continue;\n\n error = failed.cause;\n }\n\n if (fixed) this._entries.push((frame._fixed = { ...frame.journal(), error, ...irreversible.length && { irreversible } }));\n\n throw error;\n }\n } catch (error) {\n if (frame._entry && !undo) {\n frame._restore?.();\n return void this.halt('failed', error);\n }\n\n const { signal } = frame._abort;\n const fixed = frame._lost.size || frame._committed;\n const lost = this.line(id).some((at) => this._lost.has(at));\n const aborted = signal.aborted && error === signal.reason;\n const on = !fixed && !undo && frame._on.length ? frame._on : undefined;\n const defer = on && !aborted && !this.stale();\n const entry: Steps.Entry = { id, key, args, next: [], wrote: [], error, ...wake && { wake }, ...frame._retried && { retried: frame._retried } };\n\n frame._settled = true;\n\n if (!fixed && !defer) this.restore(frame._prior, frame._log);\n\n frame._restore?.();\n\n if (undo) throw error;\n\n if (on) {\n entry.on = grouped(on);\n this._on.set(id, on);\n this._entries.push(entry);\n }\n\n if (defer) this._held.set(id, { prior: frame._prior, log: frame._log });\n if (aborted) return;\n\n let own = body && !fixed && !lost && !this.stale() && !RULES.has(error as Error) && !!on?.some(({ kind }) => kind == 'catch');\n\n if (own) {\n frame._failed = { cause: error };\n\n try {\n control.hook('after', key, entry);\n } catch (thrown) {\n this.halt('failed', thrown);\n }\n\n return frame;\n }\n\n if (body && !fixed && (lost || this.caught(error, id))) {\n if (!on) this._entries.push(entry);\n\n try {\n control.hook('after', key, entry);\n } catch (thrown) {\n this.halt('failed', thrown);\n }\n } else this.fault(frame._fixed || entry, !on && !frame._fixed, error);\n } finally {\n this.frames.delete(frame);\n control.active = this.flight().at(-1)?.key;\n\n for (const check of [...this._quiet]) check();\n\n if (!this.flight().length) for (const resolve of this._drained.splice(0)) resolve();\n }\n }\n\n fault(entry: Steps.Entry, push: boolean, error: unknown) {\n if (push) this._entries.push(entry);\n\n try {\n this.control.hook('after', entry.key, entry);\n } catch (thrown) {\n error = thrown;\n }\n\n this.halt('failed', error);\n }\n\n reset(frame: Frame) {\n this.restore(frame._prior, frame._log);\n frame._armed++;\n\n Object.assign(frame, {\n _wrappers: new Map(),\n _log: [],\n _changed: new Set(),\n _items: [],\n _wrote: new Set(),\n _prior: {},\n _on: [],\n _violation: undefined,\n _late: undefined\n });\n }\n\n async end(item?: Steps.Node) {\n this._ending = true;\n\n await this.drain();\n\n if (this._unwinding) await this._unwinding;\n if (this._halted) return;\n\n const open = this._entries.filter((entry) => this._on.has(entry.id) && !this._finished.has(entry.id) && !this._spent.has(entry.id));\n\n for (const entry of open.reverse())\n try {\n this._finished.add(entry.id);\n await this.fire(this._on.get(entry.id), 'close', undefined, new Set());\n } catch (thrown) {\n return this.halt('failed', thrown);\n }\n\n const { id } = item || this.node('end', []);\n const entry = { id, key: 'end', args: [], next: [], wrote: [], ...!item && { implicit: true as const } };\n\n this._entries.push(entry);\n\n if (item)\n try {\n this.control.hook('after', 'end', entry);\n } catch (thrown) {\n return this.halt('failed', thrown);\n }\n\n this.finish();\n }\n\n drain() {\n if (this.flight().length) return new Promise<void>((resolve) => this._drained.push(resolve));\n }\n\n finish() {\n const { _tail: tail } = this;\n\n this._settling = true;\n\n if (!tail) return this.settle(this._result);\n\n this._await!.resolve();\n tail.then((value) => this.settle(value), (error) => this.broke(error));\n }\n\n broke(error: unknown) {\n this.blame(error);\n this.control.status = 'failed';\n this.reject();\n }\n\n settle(value: unknown) {\n const { control } = this;\n\n this.close();\n control.status = 'idle';\n this._ticket.resolve(value);\n control.advance();\n }\n\n close() {\n const { control } = this;\n\n control._current = undefined;\n control.runs++;\n this._entries = [];\n this._held.clear();\n this._on.clear();\n this.frames.clear();\n this.waits.clear();\n }\n\n halt(status: 'failed' | 'stopped' | 'aborted', error?: unknown) {\n const { control } = this;\n\n if (this._halted || this._settling) return;\n\n this._halted = status;\n control.status = status;\n\n for (const frame of this.flight()) frame._abort.abort(status == 'failed' ? undefined : this._stopped);\n\n if (status == 'failed') {\n this._error = error;\n control.error = error;\n }\n\n this.release();\n this.finalize(MODES[status]);\n }\n\n async finalize(mode: Mode) {\n await this.drain();\n\n if (this._unwinding) await this._unwinding;\n\n const unwound = await this.unwind(this.reason(), mode);\n\n this.refill(unwound);\n\n if (unwound.failed) {\n const { cause } = unwound.failed;\n\n if (mode != 'error') {\n chain(cause, this._stopped);\n this.control.status = 'failed';\n }\n\n this.blame(cause);\n }\n\n const { _tail: tail } = this;\n\n if (!tail) return this.reject();\n\n this._await!.reject(this.reason());\n\n try {\n this.salvage(await tail);\n } catch (thrown) {\n this.reject(thrown);\n }\n }\n\n salvage(value: unknown) {\n this.close();\n this._ticket.resolve(value);\n this.control.advance();\n }\n\n reason() {\n const { _error: error } = this;\n\n return error === undefined ? this._stopped : error;\n }\n\n reject(reason = this.reason()) {\n const { _ticket } = this;\n let stopped = reason === this._stopped;\n\n this.close();\n _ticket.reject(reason);\n\n if (!stopped)\n queueMicrotask(() => queueMicrotask(() => {\n if (!_ticket.awaited) throw reason;\n }));\n\n this.control.advance();\n }\n\n async unwind(cause: unknown, mode: Mode, ids?: Set<string>): Promise<Unwound> {\n const { control, _entries: entries } = this;\n const pending = entries.filter((entry) => (ids ? ids.has(entry.id) : !this._spent.has(entry.id)));\n const kept = new Set<string>();\n const undone: Steps.Entry[] = [];\n let halted = mode == 'stop';\n\n for (const entry of pending.reverse()) {\n const on = this._on.get(entry.id);\n const open = !this._finished.has(entry.id);\n\n if (ids && this._halted) break;\n if (entry.unwound == 'failed') break;\n\n if (!halted && (entry.irreversible || entry.committed)) {\n entry.halted = halted = true;\n\n if (entry.irreversible)\n console.warn(`${control._self} stopped unwinding at ${entry.id}: ${entry.irreversible.join(', ')} cannot be restored.`);\n }\n\n if (!on && 'error' in entry) continue;\n\n try {\n if (open) await this.fire(on, 'abort', mode == 'error' ? cause : undefined, kept);\n if (!halted && !this._reset.has(entry.id)) await this.fire(on, 'reset', undefined, kept);\n\n this._finished.add(entry.id);\n\n if (open) await this.fire(on, 'close', undefined, kept);\n } catch (thrown) {\n entry.unwound = 'failed';\n return { undone, kept, failed: { cause: thrown } };\n }\n\n this._spent.add(entry.id);\n\n if (halted) continue;\n if (on?.some((handler) => handler.kind == 'reset') || (this._held.has(entry.id) && entry.wrote.length)) entry.unwound = true;\n\n undone.push(entry);\n }\n\n return { undone, kept };\n }\n\n async compensate(item: Steps.Node, cause: unknown, kept: Set<string>, bare?: boolean) {\n const fn = this._inline.get(item.id);\n\n if (!fn) return this.undo([item], kept);\n\n const frame = this.frames.add({ id: item.id, key: item.key, args: item.args, _undo: true, _owner: this._owner.get(item.id) });\n try {\n await (bare ? fn() : fn(cause));\n } finally {\n this.frames.delete(frame);\n for (const key of frame._wrote) kept.add(key);\n }\n\n await this.undo(frame._items, kept);\n }\n\n async undo(items: Steps.Node[], kept: Set<string>): Promise<void> {\n for (const item of items)\n if (item.group) await Promise.all(item.group.map((member) => this.undo([member], kept)));\n else {\n const frame = (await this.invoke(item, undefined, true))!;\n\n for (const key of frame._wrote) kept.add(key);\n\n await this.undo(frame._items, kept);\n }\n }\n\n refill({ undone, kept }: Unwound, into?: Frame, all?: boolean, within?: string) {\n const self = this.control._self as any;\n const prior = new Map<string, unknown>();\n const log: Log = [];\n\n for (const entry of undone) {\n const held = this._held.get(entry.id);\n\n if (!held) continue;\n\n for (const key in held.prior) prior.set(key, held.prior[key]);\n\n log.push(...[...held.log].reverse());\n }\n\n const since = (key: string) => !!within && !this.line(this._writer.get(key)!).includes(within);\n\n for (const [key, value] of prior) {\n const wrote = into?._wrote.has(key);\n\n if (wrote) into!._prior[key] = value;\n if (all || (!wrote && !kept.has(key) && !since(key))) self[key] = value;\n }\n\n for (const [key, undo] of log) if (all || (!into?._changed.has(key) && !since(key))) undo();\n }\n\n blame(cause: unknown) {\n this._error = cause;\n this.control.error = cause;\n }\n\n restore(prior: Record<string, unknown>, log: Log) {\n const self = this.control._self as any;\n\n for (const key in prior) self[key] = prior[key];\n for (const [, undo] of [...log].reverse()) undo();\n }\n}\n\nclass Frame extends Model {\n run = get(Run);\n id = '';\n key = '';\n args: unknown[] = [];\n\n _proxy!: Model;\n _owner?: Frame = undefined;\n _view?: Steps.Controller = undefined;\n _refs = new Map<string, Function>();\n _abort = new AbortController();\n _items: Steps.Node[] = [];\n _wrote = new Set<string>();\n _prior: Record<string, unknown> = {};\n _wrappers = new Map<Collection, Collection>();\n _log: Log = [];\n _on: Handler[] = [];\n _changed = new Set<string>();\n _lost = new Set<string>();\n _wake?: string = undefined;\n _undo?: boolean = undefined;\n _retried = 0;\n _restore?: Restore = undefined;\n _caught?: Steps.Node = undefined;\n _failed?: { cause: unknown } = undefined;\n _committed?: boolean = undefined;\n _entry?: Steps.Entry = undefined;\n _fixed?: Steps.Entry = undefined;\n _violation?: string = undefined;\n _late?: boolean = undefined;\n _armed = 0;\n _settled?: boolean = undefined;\n _point?: (done: (value?: unknown) => void, fail: (error: unknown) => void) => void = undefined;\n\n protected new() {\n const { _self: self, _steps, _runner } = this.run.control;\n\n this._proxy = new Proxy(self, {\n get: (target, prop) => {\n const live = this._settled && this.live();\n\n if (live) return Reflect.get(live._proxy, prop);\n if (_steps.has(prop as string)) return this.ref(prop as string);\n\n const value = Reflect.get(target, prop, target);\n\n if (value === _runner) return this.view();\n\n let managed = !this._undo && !this._settled && collection(value);\n\n return managed ? this.wrap(prop as string, value) : value;\n },\n set: (target, prop, value) => {\n const key = String(prop);\n\n if (this._settled) {\n const live = this.live();\n\n return live ? Reflect.set(live._proxy, prop, value) : Reflect.set(target, prop, value, target);\n }\n\n if (!this._wrote.has(key)) {\n this._prior[key] = Reflect.get(target, prop, target);\n this._wrote.add(key);\n }\n\n if (this._items.length) this._violation ||= key;\n\n this.run._writer.set(key, this.id);\n\n return Reflect.set(target, prop, value, target);\n }\n });\n\n return () => this._abort.abort();\n }\n\n live() {\n const { run } = this;\n\n if (run.waits.any((wait) => wait._from === this)) return;\n\n const live = [...run.frames].filter((frame) => frame.within(this));\n\n return live.length == 1 ? live[0] : undefined;\n }\n\n within(owner: Frame) {\n for (let at = this._owner; at; at = at._owner) if (at === owner) return true;\n\n return false;\n }\n\n ref(key: string) {\n let ref = this._refs.get(key);\n\n if (!ref) this._refs.set(key, (ref = (...args: unknown[]) => (this._settled ? this.answer(key, args) : this.issue(key, args))));\n\n return ref;\n }\n\n keyOf(fn: unknown) {\n for (const [key, ref] of this._refs) if (ref === fn) return key;\n }\n\n issue(key: string, args: unknown[]) {\n const { run } = this;\n\n if (this._undo && UNPLANNED.includes(key)) throw rule(`${named(key)} cannot run in an undo.`);\n if (this._settled) throw rule(`${this.key} has settled; ${key} cannot run.`);\n if (key == 'run') throw rule('run is the entry - loop with a step: a step which schedules itself again.');\n\n const token = run.node(key, args);\n\n ISSUED.set(token, this);\n this._items.push(token);\n this.arm();\n\n return token;\n }\n\n answer(key: string, args: unknown[]) {\n const { run } = this;\n let live = run.control._current === run;\n const wait = live && run.route(key, args, this);\n\n if (wait) return run.wake(wait, key, args);\n\n throw rule(`${this.key} has settled; ${key} cannot run.`);\n }\n\n async pause(pending: Promise<unknown>) {\n const { signal } = this._abort;\n const abort = new Promise((resolve) => signal.addEventListener('abort', resolve, { once: true }));\n let failed: { cause: unknown } | undefined;\n\n if (!signal.aborted) await Promise.race([pending, abort]).catch((cause) => (failed = { cause }));\n if (signal.aborted) throw signal.reason;\n\n return failed;\n }\n\n open(call: unknown) {\n const { run } = this;\n const body = Promise.resolve(call);\n\n body.catch(() => {});\n this.arm();\n\n return new Promise((resolve, reject) => {\n this._point = (done, fail) => {\n if (this._late) {\n const error = rule('run awaited work before its plan - it takes arguments, calls steps and awaits this.');\n\n fail(error);\n return reject(error);\n }\n\n run._await = { resolve: done, reject: fail };\n run._tail = body;\n resolve(undefined);\n };\n\n body.then(\n (value) => {\n if (run._tail) return;\n\n run._result = value;\n resolve(undefined);\n },\n (error) => {\n if (!run._tail) reject(error);\n }\n );\n });\n }\n\n arm() {\n const armed = ++this._armed;\n let hops = SLACK;\n\n const tick = () => {\n if (this._settled || this._armed != armed) return;\n if (--hops) queueMicrotask(tick);\n else this._late = true;\n };\n\n queueMicrotask(tick);\n }\n\n view(): Steps.Controller {\n if (this._view) return this._view;\n\n const retry = () => this.retry();\n\n RETRY.add(retry);\n\n const view = (...args: unknown[]) => {\n const [items, each] = args as [unknown, (item: unknown, index: number) => unknown];\n const fns = args.filter((arg) => typeof arg == 'function');\n const refs = fns.map((fn) => this.keyOf(fn)).filter(Boolean) as string[];\n const tokens = args.filter((arg) => arg && typeof arg == 'object');\n let timed = args.some(plain);\n let mapped = args.length == 2 && iterable(items) && typeof each == 'function';\n let grouped = args.length && tokens.length == args.length;\n let waits = refs.length && refs.length == fns.length && refs.length + tokens.length == args.length;\n\n if (timed && args.length > 1) throw rule('then() takes a duration alone - this.then({ sec: 10 }).');\n if (timed) return this.delay(items as Record<string, unknown>);\n if (mapped) return this.group(Array.from(items as Iterable<unknown>, each));\n if (grouped) return this.group(args);\n if (waits) return this.wait(refs, tokens);\n if (refs.length) throw rule('then() takes steps uncalled to answer and called ones to race - not other functions.');\n if (fns.length == 2 && args.length == 2 && this._point && !this._settled) return this._point(fns[0] as any, fns[1] as any);\n if (fns.length == 1) throw rule('then() takes steps, not a function - declare the work as a step.');\n\n throw rule('a step cannot await its own run.');\n };\n\n Object.setPrototypeOf(view, this.run.control._runner);\n Object.defineProperties(view, {\n then: { value: view },\n end: { value: (...value: unknown[]) => (valueless(value), this.issue('end', [])) },\n signal: { get: () => this._abort.signal },\n retried: { get: () => this._retried },\n retry: { value: retry },\n only: { value: (max: unknown, key?: unknown) => this.slot(max, key) },\n on: { value: (handlers: unknown) => this.handle(handlers) },\n restore: {\n value: () => {\n if (!this._restore) throw rule('restore() must be called in a .catch handler.');\n\n this._restore(this, true);\n }\n },\n commit: {\n value: () => {\n if (this._settled) throw rule(`${this.key} has settled; commit cannot run.`);\n\n this._committed = true;\n }\n }\n });\n\n return (this._view = view as unknown as Steps.Controller);\n }\n\n handle(handlers: unknown) {\n const { run } = this;\n const usage = 'then.on() takes steps called for it - { reset: this.release(id) } - or a function.';\n\n if (this.id == run._root) throw rule('run cleans up in its tail - try/catch around await this.');\n if (this._undo) throw rule('then.on() cannot run in a handler step - use try/finally inside it.');\n if (this._settled) throw rule(`${this.key} has settled; on cannot run.`);\n if (!plain(handlers)) throw rule(usage);\n\n for (const [kind, value] of Object.entries(handlers as object)) {\n if (!KINDS.includes(kind as Kind)) throw rule(`then.on() takes reset, catch, abort and close - got ${kind}.`);\n if (value === undefined) continue;\n if (kind == 'catch' && this._on.some((handler) => handler.kind == 'catch')) throw rule('then.on() takes one catch per step.');\n\n const step = typeof value == 'function' && this.keyOf(value);\n let node: Steps.Node;\n\n if (step) node = run.node(step, []);\n else if (typeof value == 'function') {\n node = run.node('then', []);\n run._inline.set(node.id, value);\n run._owner.set(node.id, this);\n }\n else [node] = this.claimed(Array.isArray(value) ? value : [value], usage, 'then.on()');\n\n this._on.push({ kind: kind as Kind, node, bare: !!step });\n }\n }\n\n claimed(args: unknown[], usage: string, verb = 'then()') {\n const { _steps } = this.run.control;\n const fns = args.filter((arg) => typeof arg == 'function');\n const steps = args.every((arg) => {\n const node = arg as Steps.Node;\n\n return this._items.includes(node) && !UNPLANNED.includes(node.key) && (node.group || _steps.has(node.key));\n });\n\n if (fns.length && fns.length < args.length) throw rule(`${verb} takes called steps or step references, not both.`);\n if (!args.length || !steps) throw rule(usage);\n\n return this.claim([args.length > 1 ? this.group(args) : (args[0] as Steps.Node)]);\n }\n\n claim(nodes: Steps.Node[]) {\n this._items = this._items.filter((item) => !nodes.includes(item));\n\n if (this._items.length) this.arm();\n else {\n this._armed++;\n this._late = undefined;\n }\n\n return nodes;\n }\n\n rescue(token: Steps.Node, handler: unknown) {\n const key = this.keyOf(handler);\n\n if (UNCAUGHT.includes(token.key)) throw rule(`${named(token.key)} cannot be caught.`);\n if (handler && typeof handler != 'function') throw rule('catch() takes a step, a function or nothing.');\n if (RETRY.has(handler as Function))\n throw rule('catch() retries from a handler: .catch(this.rescan), rescan(error) { if (this.then.retried >= 3) throw error; this.then.retry(); }');\n\n token.rescue = handler ? key || 'then' : true;\n this.run._catches.set(token.id, { key, fn: handler as Function | undefined });\n\n return token;\n }\n\n retry() {\n const { run, _caught: caught } = this;\n\n if (!caught) throw rule('retry() must be called in a .catch handler.');\n if (this._settled) throw rule(`${this.key} has settled; retry cannot run.`);\n\n this._items.push(run.copy(caught));\n this.arm();\n }\n\n slot(max: unknown, key: unknown) {\n if (typeof max != 'number' && typeof max != 'function') throw rule('only() takes a count, or a function returning one.');\n\n const token = this.issue('gate', []);\n\n this.run._slots.set(token.id, { max: max as Slot['max'], key });\n }\n\n delay(duration: Record<string, unknown>) {\n let ms = 0;\n\n if (!Object.keys(duration).length) throw rule('then() takes a duration of ms, sec, min, hr and day as numbers - got none.');\n\n for (const [unit, value] of Object.entries(duration))\n if (!Object.hasOwn(UNITS, unit) || typeof value != 'number' || !(value >= 0))\n throw rule(`then() takes a duration of ms, sec, min, hr and day as numbers - got ${unit}.`);\n else ms += value * UNITS[unit];\n\n return Object.assign(this.issue('wait', [ms]), { answers: [] });\n }\n\n group(members: unknown[]) {\n for (const member of members as Steps.Node[])\n if (!this._items.includes(member)) throw rule(`then() takes steps called by ${this.key}.`);\n\n const group = Object.assign(this.run.node('then', []), { group: members as Steps.Node[] });\n\n ISSUED.set(group, this);\n this.run._groups.add(group.id);\n\n this._items = this._items.filter((item) => !members.includes(item));\n this._items.push(group);\n this.arm();\n\n return group;\n }\n\n wait(answers: string[], racers: unknown[]) {\n for (const key of answers) if (key == 'run') throw rule('run cannot answer a wait.');\n\n const [race] = racers.length ? this.claimed(racers, 'then() races steps called for it - this.then(this.allow, this.timeout(call)).') : [];\n const token = Object.assign(this.issue('wait', []), { answers }, race && { race });\n\n if (race) adopt(this.run._parent, [race], token.id);\n\n return token;\n }\n\n commit(out: unknown) {\n const { run, id, key, _items: items, _violation, _late, _wake, _lost, _on } = this;\n\n if (_violation) throw rule(`${key} wrote ${_violation} after scheduling ${items[0].key}.`);\n if (_late && !items.length) throw rule('run awaited work before its plan - it takes arguments, calls steps and awaits this.');\n if (_late) throw rule(`${key} kept working after scheduling ${items[0].key}.`);\n\n const root = id == run._root;\n\n if (!root && out !== undefined) throw rule(`${key} returned a value; a step returns nothing - its undo is this.then.on({ reset }).`);\n\n const end = items.findIndex((item) => item.key == 'end');\n\n if (end >= 0 && end < items.length - 1) throw rule('end must be the last call in a step.');\n\n adopt(run._parent, items, id);\n\n const entry: Steps.Entry = { ...this.journal(), next: items };\n\n if (_wake) entry.wake = _wake;\n if (this._retried) entry.retried = this._retried;\n\n if (_on.length) {\n entry.on = grouped(_on);\n run._on.set(id, _on);\n }\n\n if (_lost.size && !_on.some((handler) => handler.kind == 'reset')) entry.irreversible = [..._lost];\n\n if (!root) run._held.set(id, { prior: this._prior, log: this._log });\n if (this._undo) run._spent.add(id);\n\n run._entries.push(entry);\n this._entry = entry;\n\n return entry;\n }\n\n journal(): Steps.Entry {\n const { id, key, args, _wrote, _changed, _committed } = this;\n const entry: Steps.Entry = { id, key, args, next: [], wrote: [...new Set([..._wrote, ..._changed])] };\n\n if (_committed) entry.committed = true;\n\n return entry;\n }\n\n wrap(key: string, value: Collection) {\n let wrapper = this._wrappers.get(value);\n\n if (wrapper) return wrapper;\n\n const ops = mutators(value);\n\n wrapper = new Proxy(value, {\n get: (target, prop) => {\n const op = ops[prop as string];\n\n if (op)\n return (...args: unknown[]) => {\n const out = this.change(key, () => op(...args));\n\n return out === target ? wrapper : out;\n };\n\n const got = Reflect.get(target, prop, target);\n\n return typeof got == 'function' ? got.bind(target) : got;\n }\n });\n\n this._wrappers.set(value, wrapper);\n\n return wrapper;\n }\n\n change(key: string, op: () => Change) {\n const at = this._settled ? this.live() : this;\n\n if (!at) return op()[0];\n\n const [out, changed, undo, lost] = op();\n\n if (!changed) return out;\n if (at._items.length) at._violation ||= key;\n if (undo) at._log.push([key, undo]);\n if (lost) at._lost.add(key);\n\n at._changed.add(key);\n at.run._writer.set(key, at.id);\n\n return out;\n }\n}\n\nclass Wait extends Model {\n run = get(Run);\n id = '';\n step = '';\n args: unknown[] = [];\n answers: string[] = [];\n until?: number = undefined;\n\n _from!: Frame;\n _park!: (answer?: Answer) => void;\n _answer?: Answer = undefined;\n _race?: Steps.Node = undefined;\n _open = true;\n\n protected new() {\n const { run, answers, until } = this;\n const { _self: self } = run.control;\n let timer: ReturnType<typeof setTimeout> | undefined;\n\n const arm = () => {\n const left = until! - Date.now();\n\n timer = setTimeout(left > LONGEST ? arm : () => run.waits.delete(this), Math.min(left, LONGEST));\n };\n\n if (until !== undefined) arm();\n\n for (const key of answers) if (!run.accepts(key, this)) event(self, key);\n\n return () => {\n this._open = false;\n clearTimeout(timer);\n\n for (const key of answers) if (!run.accepts(key)) event(self, key);\n\n this._park(this._answer);\n };\n }\n}\n\nfunction chain(error: unknown, cause: unknown) {\n if (error instanceof Error && error.cause === undefined) error.cause = cause;\n}\n\nfunction grouped(on: Handler[]) {\n const out: NonNullable<Steps.Entry['on']> = {};\n\n for (const { kind, node } of on) (out[kind] ||= []).push(node);\n\n return out;\n}\n\nfunction serial(error: unknown) {\n if (!(error instanceof Error)) return error;\n\n const { name, message, cause } = error;\n\n return { name, message, ...cause !== undefined && { cause } };\n}\n\nfunction rule(message: string) {\n const error = new Error(message);\n\n RULES.add(error);\n\n return error;\n}\n\nfunction named(key: string) {\n return key == 'gate' ? 'a gate' : `${key}()`;\n}\n\nfunction plain(value: unknown) {\n if (!value || typeof value != 'object') return false;\n\n const proto = Object.getPrototypeOf(value);\n\n return proto === Object.prototype || proto === null;\n}\n\nfunction signal(key: unknown) {\n return typeof key != 'boolean' && key !== null;\n}\n\nfunction iterable(value: unknown): value is Iterable<unknown> {\n return value != null && typeof (value as Iterable<unknown>)[Symbol.iterator] == 'function';\n}\n\nfunction valueless(args: unknown[]) {\n if (args.length) throw rule('end() takes no value; the result is what run returns.');\n}\n\nfunction outside(key: string, verb = 'called'): never {\n throw rule(`${key} must be ${verb} inside a step.`);\n}\n\nclass Handled<T> extends Promise<T> {\n static get [Symbol.species]() {\n return Promise;\n }\n\n declare _ticket: Ticket;\n\n then<A = T, B = never>(...args: Parameters<Promise<T>['then']>): Promise<A | B> {\n this._ticket.awaited = true;\n return super.then(...args) as Promise<A | B>;\n }\n}\n\nfunction handle<T>(ticket: Ticket, executor: ConstructorParameters<typeof Promise<T>>[0]) {\n const handled = new Handled<T>(executor);\n\n handled._ticket = ticket;\n Promise.prototype.then.call(handled, undefined, () => {});\n\n return handled;\n}\n\nfunction gate<K>(gates: { get(key: K): Gate | undefined; set(key: K, gate: Gate): unknown }, key: K) {\n let gate = gates.get(key);\n\n if (!gate) gates.set(key, (gate = { held: new Set(), queue: [] }));\n\n return gate;\n}\n\nfunction pump(gate: Gate) {\n for (let next = gate.queue[0]; next && gate.held.size < next.max(); next = gate.queue[0]) {\n gate.queue.shift();\n gate.held.add(next.hold);\n next.grant();\n }\n}\n\nfunction adopt(parents: Map<string, string>, items: Steps.Node[], parent: string) {\n for (const item of items) {\n parents.set(item.id, parent);\n\n if (item.group) adopt(parents, item.group, item.id);\n }\n}\n\nfunction collection(value: unknown): value is Collection {\n return value instanceof has.List || value instanceof has.Pool || value instanceof map.Managed;\n}\n\nfunction dead(value: unknown) {\n return value instanceof Model && value.get(null);\n}\n\nfunction mutators(value: Collection): Record<string, Mutator> {\n if (value instanceof has.List) return listOps(value);\n if (value instanceof has.Pool) return poolOps(value);\n\n return mapOps(value);\n}\n\nfunction listOps(list: has.List<unknown>): Record<string, Mutator> {\n const at = (index: number, size: number) => (index < 0 ? Math.max(size + index, 0) : Math.min(index, size));\n\n const unput = (start: number, values: unknown[]) => () => {\n for (let i = values.length - 1; i >= 0; i--) {\n const found = near(list, values[i], start + i);\n\n if (found >= 0) list.pop(found);\n }\n };\n\n return {\n push: (...values: unknown[]) => {\n const start = list.size;\n\n return [list.push(...values), values.length > 0, unput(start, values)];\n },\n put: (index: number, ...values: unknown[]) => {\n const start = at(index, list.size);\n\n list.put(index, ...values);\n\n return [undefined, values.length > 0, unput(start, values)];\n },\n pop: (index = -1, count?: number) => {\n const before = list.get(0, list.size);\n const start = at(index, before.length);\n const removed = before.slice(start, start + (count ?? 1));\n const out = count === undefined ? list.pop(index) : list.pop(index, count);\n\n return [out, removed.length > 0, () => list.put(start, ...removed)];\n },\n set: (index: number, value: unknown) => {\n const before = list.get(0, list.size);\n const start = index < 0 ? before.length + index : index;\n const prior = before[start];\n\n list.set(index, value);\n\n const restore = () => {\n const found = near(list, value, start);\n\n if (found >= 0) list.set(found, prior);\n };\n\n return [undefined, start >= 0 && start < before.length && prior !== value, restore];\n },\n clear: () => {\n const removed = list.get(0, list.size);\n\n list.clear();\n\n return [undefined, removed.length > 0, () => list.put(0, ...removed)];\n }\n };\n}\n\nfunction poolOps(pool: has.Pool<unknown>): Record<string, Mutator> {\n const added = new Set<unknown>();\n\n const lost = (members: unknown[]) => members.filter((member) => !added.delete(member)).length > 0;\n\n return {\n add: (...args: unknown[]) => {\n const size = pool.size;\n const made = pool.add(...args);\n const fresh = pool.size > size;\n\n if (fresh) added.add(made);\n\n return [made, fresh, () => pool.delete(made)];\n },\n delete: (member: unknown) => {\n const had = pool.delete(member);\n\n return [had, had, undefined, had && lost([member])];\n },\n clear: () => {\n const members = [...pool];\n\n pool.clear();\n\n return [undefined, members.length > 0, undefined, lost(members)];\n }\n };\n}\n\nfunction mapOps(map: map.Managed<unknown, unknown>): Record<string, Mutator> {\n const added = new Set<unknown>();\n\n const removed = (entries: [unknown, unknown][]): Change => {\n const kept = entries.filter(([, value]) => !dead(value));\n const lost = entries.some(([key, value]) => dead(value) && !added.has(key));\n\n const restore = () => {\n for (const [key, value] of kept) if (!map.has(key)) map.set(key, value);\n };\n\n return [undefined, entries.length > 0, restore, lost];\n };\n\n return {\n set: (key: unknown, ...rest: unknown[]) => {\n const had = map.has(key);\n const prior = map.get(key);\n const own = !had || added.has(key);\n\n map.set(key, ...rest);\n\n const value = map.get(key);\n const gone = had && dead(prior);\n\n const restore = () => {\n if (map.get(key) !== value) return;\n if (had && !gone) map.set(key, prior);\n else if (own) map.delete(key);\n };\n\n added.add(key);\n\n return [map, !had || value !== prior, restore, gone && !own];\n },\n delete: (key: unknown) => {\n const entry: [unknown, unknown] = [key, map.get(key)];\n const had = map.delete(key);\n const change = removed(had ? [entry] : []);\n\n change[0] = had;\n\n return change;\n },\n clear: () => {\n const entries = [...map.entries()];\n\n map.clear();\n\n return removed(entries);\n }\n };\n}\n\nfunction near(list: has.List<unknown>, value: unknown, at: number) {\n let found = -1;\n\n list.get(0, list.size).forEach((item, index) => {\n if (item ===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AAM,MAAM,CAAC,OAAO,MAAM,IAAI,IAAI;AAElC,OAAI,IAAI,KAAK,GAAG,KAAK;GAErB,MAAM,QAAQ,IAAI,IAAI,IAAI;GAC1B,MAAM,OAAO,OAAO,KAAK,MAAM;GAE/B,MAAM,gBAAgB;AACpB,QAAI,IAAI,IAAI,IAAI,KAAK,MAAO;AAC5B,QAAI,OAAO,CAAC,KAAM,KAAI,IAAI,KAAK,MAAM;aAC5B,IAAK,KAAI,OAAO,IAAI;;AAG/B,SAAM,IAAI,IAAI;AAEd,UAAO;IAAC;IAAK,CAAC,OAAO,UAAU;IAAO;IAAS,QAAQ,CAAC;IAAI;;EAE9D,SAAS,QAAiB;GACxB,MAAM,QAA4B,CAAC,KAAK,IAAI,IAAI,IAAI,CAAC;GACrD,MAAM,MAAM,IAAI,OAAO,IAAI;GAC3B,MAAM,SAAS,QAAQ,MAAM,CAAC,MAAM,GAAG,EAAE,CAAC;AAE1C,UAAO,KAAK;AAEZ,UAAO;;EAET,aAAa;GACX,MAAM,UAAU,CAAC,GAAG,IAAI,SAAS,CAAC;AAElC,OAAI,OAAO;AAEX,UAAO,QAAQ,QAAQ;;EAE1B;;AAGH,SAAS,KAAK,MAAyB,OAAgB,IAAY;CACjE,IAAI,QAAQ;AAEZ,MAAK,IAAI,GAAG,KAAK,KAAK,CAAC,SAAS,MAAM,UAAU;AAC9C,MAAI,SAAS,UAAU,QAAQ,KAAK,KAAK,IAAI,QAAQ,GAAG,GAAG,KAAK,IAAI,QAAQ,GAAG,EAAG,SAAQ;GAC1F;AAEF,QAAO"}
package/package.json CHANGED
@@ -1,6 +1,56 @@
1
1
  {
2
2
  "name": "@expressive/steps",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Runnable Models: every method a step, fields the data between them - with rollback, waits and an awaitable result.",
5
+ "keywords": [
6
+ "expressive",
7
+ "mvc",
8
+ "workflow",
9
+ "steps",
10
+ "rollback",
11
+ "state"
12
+ ],
13
+ "license": "MIT",
14
+ "author": {
15
+ "name": "Gabe Klein",
16
+ "email": "gabe@expressive.dev",
17
+ "url": "https://github.com/gabeklein"
18
+ },
19
+ "repository": {
20
+ "type": "git",
21
+ "url": "git+https://github.com/gabeklein/expressive.git"
22
+ },
23
+ "files": [
24
+ "dist",
25
+ "skills"
26
+ ],
27
+ "type": "module",
28
+ "sideEffects": false,
29
+ "main": "dist/index.js",
30
+ "types": "dist/index.d.ts",
31
+ "exports": {
32
+ ".": {
33
+ "types": "./dist/index.d.ts",
34
+ "default": "./dist/index.js"
35
+ }
36
+ },
37
+ "engines": {
38
+ "node": ">=20"
39
+ },
40
+ "publishConfig": {
41
+ "access": "public"
42
+ },
43
+ "scripts": {
44
+ "build": "tsdown",
45
+ "typecheck": "tsc --noEmit --incremental",
46
+ "coverage": "vitest run --coverage",
47
+ "test": "bun run typecheck && bun run coverage"
48
+ },
49
+ "devDependencies": {
50
+ "@expressive/mvc": "workspace:*",
51
+ "tsdown": "^0.20.1"
52
+ },
53
+ "peerDependencies": {
54
+ "@expressive/mvc": "^0.94.2"
55
+ }
56
+ }
@@ -0,0 +1,234 @@
1
+ ---
2
+ name: expressive-steps
3
+ description: Multi-step processes as Expressive Models (@expressive/steps) - class X extends Steps, every method a step, atomic steps that unwind on failure, waits, retries, gates, durations, racers. Use when writing, reviewing or testing a Steps class or modelling a workflow, wizard, saga or job with @expressive/steps.
4
+ ---
5
+
6
+ # Steps
7
+
8
+ `@expressive/steps` - multi-step processes as Models. `class X extends Steps`: every method is a step, a step schedules the next by calling it, fields carry data between steps. Each step is atomic and registers its own reset; a failure unwinds what committed. Runs repeat, queue, and park on waits answered from outside. `0.1`, in-process only - nothing persists across a restart.
9
+
10
+ ```bash
11
+ npm install @expressive/steps @expressive/mvc
12
+ ```
13
+
14
+ Per-member contract - signatures, defaults, edge cases, examples - is JSDoc on hover, or `node_modules/@expressive/steps/dist/index.d.ts`. This skill covers how the pieces compose. A Steps class is a `Model` - fields, `has`, `map`, `set`, `get` and `this.is` are [expressive-mvc](../expressive-mvc/SKILL.md)'s.
15
+
16
+ ## Shape
17
+
18
+ ```ts
19
+ import { Steps } from '@expressive/steps';
20
+
21
+ class SubmitOrder extends Steps {
22
+ cart!: Cart;
23
+ charge?: Charge = undefined;
24
+ tracking = '';
25
+
26
+ async run() {
27
+ this.reserve(); // schedule
28
+
29
+ await this; // the run, to the end
30
+
31
+ return { orderId: this.charge!.id, tracking: this.tracking };
32
+ }
33
+
34
+ protected async reserve() {
35
+ const hold = await inventory.hold(this.cart.items); // the step's work
36
+
37
+ this.then.on({ reset: () => inventory.release(hold) }); // right after the effect - runs only when taken back
38
+ this.pay().catch(this.noCourier); // then hand off
39
+ }
40
+
41
+ protected async noCourier(error: unknown) { // pay's branch failed and was unwound
42
+ if (!(error instanceof NoCourier)) throw error;
43
+ this.backorder();
44
+ }
45
+
46
+ protected async pay() {
47
+ this.charge = await stripe.charge(this.cart.total);
48
+ this.then.on({ reset: () => stripe.refund(this.charge!.id) });
49
+
50
+ this.then(this.ship(this.charge.id), this.receipt(this.charge.receiptUrl));
51
+ }
52
+
53
+ protected async ship(chargeId: string) {
54
+ const booking = await courier.book(this.cart, chargeId);
55
+
56
+ if (!booking) throw new NoCourier();
57
+ this.tracking = booking.id;
58
+ }
59
+
60
+ protected async receipt(url: string) {
61
+ await mail.send(this.cart.email, url);
62
+ }
63
+
64
+ protected async backorder() {
65
+ await mail.send(this.cart.email, backorderUrl(this.cart));
66
+ }
67
+ }
68
+
69
+ const order = SubmitOrder.new({ cart });
70
+ const { orderId } = await order; // runs run(), typed by its return
71
+ order.then.status; // reactive
72
+ ```
73
+
74
+ Inputs are fields (`X.new({ cart })`) or `run`'s arguments. Nothing starts on its own; `new()` stays mvc's setup hook.
75
+
76
+ ## `run` - the entry
77
+
78
+ - The only step callable from outside: `x.run(args)` starts a run and returns its Promise. While a run is active it queues one, FIFO (`then.queue`); each call settles with its own run.
79
+ - `await x` on an idle instance calls `run()` with no arguments - rejects if `run` declares parameters (`run.length`; give an optional one a default). Otherwise it joins: settles with the last queued run.
80
+ - Must be `async` (a sync `run` is a type error).
81
+ - `await this` inside `run` is its settle point. Before it: field writes and step calls only - awaiting anything else fails the run (`run awaited work before its plan…`). After it, the tail: read fields, return the result or throw. Step calls there throw; writes are unmanaged.
82
+ - The run settles with what `run` returns or throws - that types `x.run()` and `await x`. `then.status`/`then.error` record what the plan did, so a tail catching a failure resolves the run while status stays `failed`.
83
+ - Without `await this`, `run` settles at once - result `void` (chained style).
84
+ - `return await this` is a TS circularity (TS7023) - return from fields.
85
+ - Cleanup on every outcome - done, failed, stopped - is `try`/`catch`/`finally` around `await this`. A run failing before `await this`, or without it, has no tail; that cleanup belongs in a step's reset.
86
+ - `run` is entry only - inside a step `this.run()` throws; a loop is a step scheduling itself.
87
+
88
+ ## A step body is a plan
89
+
90
+ - Calling a step inside a step does not run it: it returns an inert token (not awaitable - `await this.a()` does nothing), scheduled after the caller settles cleanly. A caller that throws schedules nothing.
91
+ - Tokens run in issue order, depth-first: each with everything it schedules, before the next sibling.
92
+ - Inputs and shared state are ordinary fields. `_` fields are unmanaged - not restored, not observable, not in `wrote`, not checkpointed by a future durable host: only for process-local values like a cache or a handle.
93
+ - Step arguments are journaled: pass only need-to-know handoffs - what differs between calls, or a value one step found and hands the next. State shared across steps or read from outside is a field. Secrets are neither - pass a reference and resolve it in the step that uses it (`const token = await vault.get(cardRef)`).
94
+ - **The first call ends the step's work.** After its first token a step may only issue tokens and return. A write after it fails the run; settling more than a few microtasks after the last token fails it too. A sync side effect after scheduling is invisible to the guard - side effects are steps.
95
+ - Loops are plain loops, or a step scheduling itself.
96
+
97
+ `this.then` inside a step, by argument:
98
+
99
+ | call | meaning |
100
+ | --- | --- |
101
+ | `this.then(this.a(x), this.b(y))` | parallel group - members run concurrently, the group completes when all have |
102
+ | `this.then(items, this.step)` / `(items, (item) => this.step(item))` | mapped group |
103
+ | `this.then(this.allow, this.deny, this.timeout(x)?)` | wait - parks until one of those steps is called; called steps race it |
104
+ | `this.then({ min: 1 })` | duration - parks for `ms`/`sec`/`min`/`hr`/`day`, summed |
105
+ | `this.then.only(2)` / `.only(1, lock)` | gate - only so many at once |
106
+ | `this.then.end()` | end the run here - pending discarded; takes no value |
107
+ | `this.then.on({ reset: () => release(hold) })` | handlers for this step's subtree - `reset`, `catch`, `abort`, `close` |
108
+ | `this.then.commit()` | point of no return |
109
+ | `this.then.signal` | this step's `AbortSignal` - pass it to the call it awaits |
110
+
111
+ A plain function fails the run - work is a step. Every token takes `.catch(handler?)`.
112
+
113
+ ## Outcomes - `then.on`
114
+
115
+ A step returns nothing - a value fails the run. `this.then.on({ … })` registers handlers for the step and everything it schedules (its subtree) - right after the effect, usually just above scheduling. A handler is an arrow, writing through the step's `this` - one line an expression, more an async arrow with `await`.
116
+
117
+ ```ts
118
+ this.then.on({
119
+ reset: () => stripe.refund(chargeId), // the step is taken back - reset its effect
120
+ catch: (error) => { // a failure below - return recovers, throw passes on
121
+ if (!(error instanceof Busy)) throw error;
122
+ this.later();
123
+ },
124
+ abort: async (error) => { // ended without completing - the error, or none if cancelled
125
+ if (!error) await Image.delete(this.name);
126
+ },
127
+ close: () => this.preview.close() // a finally over the subtree
128
+ });
129
+ ```
130
+
131
+ | key | fires (deepest step first, newest first) | function gets |
132
+ | --- | --- | --- |
133
+ | `catch` | a step below failed, no `.catch` closer took it - return recovers, throw passes on | the error |
134
+ | `abort` | ended without completing - a failure no `catch` recovered, `abort()`, a lost race, `stop()`; `commit()`'s counterpart | the error of a failure; nothing for a cancellation (`then.status` tells `aborted` from `stopped`) |
135
+ | `reset` | the step is taken back - a failure leaving the subtree, `abort()`, a lost race; not `stop()` | nothing |
136
+ | `close` | subtree ended any way, last - a finally; alone on a clean finish | nothing |
137
+
138
+ - One step's order: `catch` → `abort` → `reset` → `close`. `abort` skips a clean end, a recovered failure and `then.end()`; it reaches a subtree still unfinished - a step that completed earlier and is taken back gets `reset` only.
139
+ - `reset` takes back the step's effects; `this.then.restore()` puts a caught branch's fields back now.
140
+ - `catch` returning recovers at its step: the failed part of the subtree unwinds, the step's effects stay, its `reset` does not run; steps it schedules replace the rest. It covers from registration on, the rest of the step's own body included (a throw there runs its resets, then `catch` sees the failed values, restored once it returns); one per step; it runs before a `.catch` on the step's call (inner first); `this.then.retry()` replays the step.
141
+ - Every step is atomic: one that throws or is aborted has its own writes restored, fields and `has`/`map` changes alike.
142
+ - Unwind order: failure → handlers newest first back to the nearest catch holding it → that catch's handler → no catch, the run fails. Then the fields of every step taken back are restored; `run`'s never are.
143
+ - Registered before its step fails, handlers run for that failure too and see the step's partial writes. They run before fields are restored; keys they write are kept. An unknown key throws. `run` registers none - clean up in its tail.
144
+ - Durable runs (future): a handler whose external effect must survive a restart is a step: a method uncalled - `{ catch: this.fallback, abort: this.settle }`, run with the error as its only argument (recorded as `{ name, message, cause }`; a cancellation, `reset` and `close` get none) - or one called for it, `{ reset: this.release(hold) }`, an array a group, with args recorded. Claimed, not scheduled; reaching `before`/`after`. `end`, gates and waits throw in handlers.
145
+ - `this.then.commit()` - the step's failure is not caught and the unwind stops at it (`halted`): what came before stands - e.g. a transcript the run is building.
146
+ - Removing a pool member or destroying a map value the step did not add is irreversible: the unwind stops there and warns.
147
+ - Whole-run undo is `abort()`; partial is a [catch](#catch-and-retry).
148
+ - Plain arrays/objects mutated in place are invisible - assign, or use `has`/`map`.
149
+
150
+ ## Waits
151
+
152
+ ```ts
153
+ protected async tool(call: ToolCall) {
154
+ let allowed = this.mode === 'yolo';
155
+
156
+ if (allowed) this.exec(call);
157
+ else this.then(this.allow, this.deny, this.timeout(call));
158
+ }
159
+
160
+ protected async timeout(call: ToolCall) { // a racer - starts with the wait
161
+ this.then({ min: 1 });
162
+ this.deny(call); // answers the wait it races
163
+ }
164
+
165
+ async allow(call: ToolCall) { this.exec(call); }
166
+ async deny(call: ToolCall) { this.messages.push(denied(call)); }
167
+ ```
168
+
169
+ - Status `waiting`; `then.waiting` lists `{ id, step, args, answers, until? }`, reactive - durations included.
170
+ - Answering steps are public and read `undefined` from outside unless an open wait accepts them - the read tracks, so a view shows a button only while it applies: `agent.allow && <button onClick={() => agent.allow(call)} />`.
171
+ - An outside call answers the wait whose opening step's first argument `===` its own, else the oldest. Its Promise resolves when that answer's subtree is done.
172
+ - A step called beside the answers is a racer: claimed, started when the plan reaches the wait. Inside it, a call to an answer answers that wait. The first answer closes the wait; the racer that answered keeps all it did. The rest lose: signals aborted, unscheduled work dropped, gates released; a step in flight settles, then each losing branch unwinds - resets run, fields restored. Effects without a reset stay. One settling without answering leaves the wait open (a nudge).
173
+ - `this.then({ ms, sec, min, hr, day })` - a duration: a wait nothing answers, journaled `wait#n` with `args: [ms]`. Backoff, timeouts, nudges.
174
+ - Nothing is buffered: an outside call no wait accepts throws.
175
+
176
+ ## Catch and retry
177
+
178
+ ```ts
179
+ this.scan(site).catch((error) => {
180
+ if (this.then.retried >= 3) throw error;
181
+ this.then.retry(); // replay scan(site), args recorded
182
+ });
183
+
184
+ protected async scan(site: string) { // backoff lives in the retried step
185
+ if (this.then.retried) this.then({ sec: this.then.retried });
186
+ this.fetch(site);
187
+ }
188
+ ```
189
+
190
+ - A failure in the token's branch (it and its subtree): failing step restored, rest of the branch discarded, the branch's resets run - then the handler runs in its place and the plan continues.
191
+ - Handlers replace the branch - retry, fall back, rethrow. `.catch()` skips.
192
+ - `.catch((error) => { … })` - a function, the default: `Promise.catch` semantics, its step calls scheduled; process-local - dropped on restart, so there the run fails instead of recovering.
193
+ - `.catch(this.noCourier)` - a step method, for a durable run whose recovery must survive a restart: runs given the error; recorded with it as `{ name, message, cause }` (an Error; anything else as thrown).
194
+ - The handler sees the branch's failed state; once its body returns, the branch's fields are restored except keys it wrote, then what it scheduled runs. `this.then.restore()` restores early.
195
+ - It recovers by scheduling, or throws to keep failing - an expected failure is a typed error (`throw new NoCourier()`) the handler checks, rethrowing the rest. A wait in a handler asks for another try; put it under a caught step to catch the next failure too.
196
+ - `this.then.retry()` in a handler replays what the catch is attached to - the failed step or the whole group - with its recorded args, under the same handler. The handler holds the policy; past it, throw or fall back. Throws outside a handler; `.catch(this.then.retry)` throws.
197
+ - `this.then.retried` - replays so far, `0` on a first run; a handler reads the failed one's. Calling a step again from a handler is a new step - `0`.
198
+ - Not caught: rule violations, past `commit()`/irreversible, aborts, failures while stopping or ending.
199
+ - `catch` replaces a failed attempt; its resets have already run. To keep partial work, handle the error inside the step with `try`/`catch`.
200
+ - Choosing a catch form: a called step (`on({ catch })` only) - a fixed fallback, args known now, recorded, never sees the error, always recovers unless it fails; a step method - a fallback depending on the error, recorded; a function - judgement, may rethrow or `retry()`, process-local.
201
+
202
+ ## Stop and end
203
+
204
+ `then.stop()` halts keeping what was done; `then.abort()` halts and unwinds - `commit`'s counterpart; `then.end()` ends early, keeping everything. Contracts on each.
205
+
206
+ A failed run nobody awaited throws uncaught two microtasks later.
207
+
208
+ ## Hooks
209
+
210
+ Only `before` and `after` are hooks - any other name is a step; `then`, `end`, `gate`, `wait` are reserved for plan tokens and throw. `after` gets each committed `Steps.Entry` - the Runner keeps no journal, so a log is `this.log.push(entry)`.
211
+
212
+ ## Conventions
213
+
214
+ - Steps are `protected async`; `run` and answering steps public. `_`-prefixed methods are helpers, not steps - they run on the instance, unmanaged.
215
+ - **Coordination first.** A `Steps` class is the process's template. Each step awaits the one call doing its work, then schedules, groups, gates or catches what follows. Request building, stream handling, parsing, choosing between sources go in functions or in a Model the run owns, finds with `get()`, or reports to.
216
+ - Report fields (progress, a status line) are ordinary fields written in steps; the UI subscribes. A failed try restores them - that try did not happen. To keep a value across a failed try write it unmanaged (`this.is.progress = p`, a `_` helper, an owned Model), in a handler of `then.on` or a catch, or in `run`'s tail. UI text is derived from state, not stored.
217
+ - A class already extending another Model or a `Component` holds a `Steps` model as a field (`pull = new Pull()`), which reaches its owner with `get(Owner)`.
218
+ - Effects on `then` wait for the instance to be ready (and a component's host to commit); runs do not.
219
+
220
+ ## Testing
221
+
222
+ ```ts
223
+ const order = SubmitOrder.new({ cart });
224
+
225
+ await expect(order.run()).resolves.toEqual({ orderId: 'ch_42', tracking: 'trk_1' });
226
+
227
+ vi.spyOn(courier, 'book').mockRejectedValueOnce(new Error('no courier'));
228
+ await expect(SubmitOrder.new({ cart }).run()).rejects.toThrow('no courier');
229
+ expect(stripe.refund).toHaveBeenCalledWith('ch_42'); // the unwind ran
230
+ ```
231
+
232
+ Collect entries for assertions with an `after` hook on a test subclass.
233
+
234
+ Under bun's test runner, assert a rejection with `await job.run().catch((e) => e)`, not `expect(p).rejects` - bun inspects the promise without calling `.then`, so Steps reports it unawaited.