import { StandardSchemaV1 } from '@standard-schema/spec'; /** * @demlik/tea — pure-core leaf (ADR 0006). * * This is the runtime-free pure core of the substrate. It holds the * client-prediction fold seam (`foldMsgs`), the form reader * (`formOf`/`detectUpdateForm`), and the pure type vocabulary (`Machine`, * `Reducer`, `Transitions`, `Cmd`, `Sub`, `Port`, …). * * **Dependency direction (the actual decoupling):** this module imports * NOTHING from the runtime — no `run`/host/`Store`. The * runtime (`run`, the host, interpret, `Store`, subscribe — all in * `../index.ts`) imports *from* here; never the reverse. The root entry * re-exports this surface through `./index.ts`, and * `pure/import-graph.test.ts` is the regression fence asserting the pure * entrypoint's import graph never reaches `run`. * * The one external name it reaches for is the Standard Schema TYPE surface * (`import type` from `@standard-schema/spec`), erased at compile time — * `Cmd.define` accepts any Standard Schema (zod, Effect Schema through * `Schema.toStandardSchemaV1`, …), and it imports no schema library. */ /** The `E` union one Cmd can settle with; `unknown` for an untyped Cmd. */ type ErrorsOf = C extends { readonly __e?: infer E; } ? E : unknown; declare const owedBrand: unique symbol; /** A logged Cmd handed to an external owner without completing its delivery. */ type Owed = { readonly _tag: "Owed"; readonly [owedBrand]: true; }; /** End this logged invocation without a Msg or automatic delivery confirmation. */ declare function owed(): Owed; /** * The two builders the Promise engine hands a `Cmd.define`d handler on its * ctx: `ok(value)` and `err({ _tag })`, with `err` typed to the def's declared * tags. */ interface OutcomeHelpers { readonly ok: (value: Ok) => Outcome; readonly err: (error: E) => Outcome; } /** The result a `Cmd.define`d handler returns: its value, or a declared failure. */ type Outcome = { readonly _tag: "Ok"; readonly value: Ok; } | { readonly _tag: "Err"; readonly error: E; }; /** * Build an {@link Outcome} outside a handler's helpers — in a test that calls a * handler directly, or in an adapter converting another result type. */ declare const Outcome: { readonly ok: (value: Ok) => Outcome; readonly err: (error: E) => Outcome; }; /** The shape every settled failure has (ADR 0011): a plain `_tag` record. */ type Tagged = { readonly _tag: string; }; /** * One declared failure per tag. Distributive, so `TaggedError<"a" | "b">` is * the two-arm union a `switch (error._tag)` narrows; the index signature lets a * settle site carry detail beside the tag (`{ _tag: "timeout", afterMs }`). */ type TaggedError = Tag extends string ? { readonly _tag: Tag; readonly [detail: string]: unknown; } : never; /** * The kernel-minted failure: a handler returned an `Ok` value the Cmd's `ok` * schema rejects. Plain data, so it folds into Model like any settled error; * `issues` is the schema's issue list flattened to `path` + `message` strings. */ type MalformedResult = { readonly _tag: "malformed_result"; readonly issues: ReadonlyArray<{ readonly path: string; readonly message: string; }>; }; /** * A schema whose `validate` returned a Promise where the kernel needs an answer * now — the `ok` check at the interpret edge, the `args` check in a reducer. * A contract breach (ADR 0021 §5): it goes to the error sink. */ declare class AsyncSchemaError extends Error { /** What the schema was checking, e.g. `the "fetch" Cmd's ok schema`. */ readonly where: string; readonly name = "AsyncSchemaError"; readonly _tag: "AsyncSchemaError"; constructor( /** What the schema was checking, e.g. `the "fetch" Cmd's ok schema`. */ where: string); } /** * A `Cmd.define`d handler failed outside its declared channel: its `Err` carried * no `_tag`, or a tag the def does not declare. A contract breach (ADR 0011, * 0021 §4): it goes to the error sink, never to `_err`. */ declare class UndeclaredFailureError extends Error { readonly cmdType: string; /** The `error` the handler's `Err` carried, verbatim. */ readonly failure: unknown; /** The tags the def declares. */ readonly declared: readonly string[]; readonly name = "UndeclaredFailureError"; readonly _tag: "UndeclaredFailureError"; constructor(cmdType: string, /** The `error` the handler's `Err` carried, verbatim. */ failure: unknown, /** The tags the def declares. */ declared: readonly string[]); } /** * A `Cmd.define`d handler returned something the engine cannot settle: any Msg * (the engine mints the Cmd's `_ok` / `_err`, never the handler — * ADR 0021), or any other value that is neither an {@link Outcome}, the * {@link owed} marker, nor nothing. * Also thrown when such a handler dispatches its own `_ok` / `_err` Msg. */ declare class OutcomeContractError extends Error { readonly cmdType: string; readonly name = "OutcomeContractError"; readonly _tag: "OutcomeContractError"; constructor(cmdType: string, detail: string); } /** * A list of Cmd defs names one Cmd more than once: two defs built under one * name, or one def listed twice. A name keys the def's `ok` parse and the * `_ok` / `_err` Msgs minted from it, so a repeat would leave one * def answering for both. A contract breach (ADR 0011, invariant 7): it is * thrown by `defineMachine` when a machine is built and again when a machine * built by hand starts, never folded into Model. */ declare class CmdNameCollisionError extends Error { readonly cmdType: string; readonly name = "CmdNameCollisionError"; readonly _tag: "CmdNameCollisionError"; constructor(cmdType: string); } /** * The payload a constructor accepts: a plain record spread beside `_tag`. A * `_tag` key is refused at the type level — it would overwrite the discriminant. */ type CmdInput = { readonly _tag?: never; } & Record; /** The value `Cmd.define("fetch", …)` builds: `{ _tag: "fetch", ...input }`. */ type CmdValue = Cmd & Readonly; /** * The Msg the engine mints when a `Cmd.define`d Cmd's handler succeeds: * `_ok`, carrying the Cmd and its value. Handle it in `update` to fold * the result into state. */ type SettledOk = { readonly _tag: `${Name}_ok`; readonly cmd: C; readonly value: Ok; /** Stamped by the runtime at the interpret edge (`run`'s `clock`). */ readonly at: number; }; /** * The Msg the engine mints when a `Cmd.define`d Cmd's handler fails: * `_err`, carrying the Cmd and the tagged error. Handle it in `update` to * decide what a failure means. */ type SettledErr = { readonly _tag: `${Name}_err`; readonly cmd: C; readonly error: E | MalformedResult; /** Stamped by the runtime at the interpret edge (`run`'s `clock`). */ readonly at: number; }; /** * What `Cmd.define` returns: the Cmd builder itself (`fetch({ url })`), with * the minted Msg builders and the declaration hung on it. `E` here is the * DECLARED tag union; the settled `_err` arm widens it by `MalformedResult`. * * `ok` / `err` build a settled Msg for a later `dispatch` with `answerTo`, a * `replay` log, or a unit test, and take an optional `at`. A handler returns an * {@link Outcome}, and inside `run` the interpret edge mints and stamps. */ interface CmdDef { (input: Input): CmdValue; /** The `_tag` discriminant of every Cmd this builds. */ readonly cmdType: Name; readonly okType: `${Name}_ok`; readonly errType: `${Name}_err`; readonly ok: (cmd: CmdValue, value: Ok, at?: number) => SettledOk, Ok>; readonly err: (cmd: CmdValue, error: E, at?: number) => SettledErr, E>; readonly schema: { readonly input: StandardSchemaV1; readonly ok: StandardSchemaV1; }; /** The declared `_tag` list, verbatim. */ readonly errTags: ReadonlyArray; readonly settledCmd?: (cmd: CmdValue) => CmdValue; } /** * The declaration-erased view the runtime reads: which `_tag` a def builds, * which two Msg types it settles with, the `ok` schema the edge parses against * and the tags an `Err` may carry. Every `CmdDef<…>` is one of these * structurally. */ type AnyCmdDef = { readonly cmdType: string; readonly okType: string; readonly errType: string; readonly schema: { readonly ok: StandardSchemaV1; }; readonly errTags: ReadonlyArray; settledCmd?(cmd: unknown): unknown; }; /** Positive safe-integer delivery identity, increasing monotonically with optional gaps. */ type DeliveryId = number; /** Read this handler invocation's durable delivery identity, when present. */ declare function deliveryIdOf(ctx: unknown): DeliveryId | undefined; /** The Cmd value a def (or a union of defs) builds. */ type CmdOf = D extends ((input: never) => infer C extends Cmd) ? C : never; /** * The settled-Msg union a def (or a union of defs) mints: `_ok` carrying * `value`, `_err` carrying `error`. `defineMachine({ cmds })` folds this * into the machine's `M` so the user never spells the effect half of it. */ type Settled = D extends CmdDef ? SettledOk, Ok> | SettledErr, E> : never; /** The `Ok` a def's handler must produce. */ type OkOf = D extends CmdDef ? Ok : never; /** The DECLARED failure union a def's handler may settle with. */ type ErrOf = D extends CmdDef ? E : never; declare function defineCmd(name: Name, spec: { readonly input: StandardSchemaV1; readonly ok: StandardSchemaV1; readonly err: Tags; readonly settledCmd?: (cmd: CmdValue>) => CmdValue>; }): CmdDef>; /** * What an update cell returns: the `[nextState, cmds]` tuple, typed so that a * Promise cannot stand in for it. An `async` cell fails to compile against it. */ type SyncReturn = readonly [S, readonly C[]] & { readonly then?: never; }; /** * Which of the two shapes a machine's `update` takes: a flat `reducer` keyed by * Msg type, or a `transitions` table keyed by state type and then Msg type. */ type UpdateForm = "reducer" | "transitions"; /** * Work out an `update` record's `UpdateForm` from its shape. For a machine, use * `formOf`, which prefers the form `defineMachine` already recorded. * * A reducer's first own value is a function; a transitions table's is a record * of functions. An empty record can never dispatch a Msg, so it reads as * `reducer`. */ declare function detectUpdateForm(update: object): UpdateForm; /** * Read a machine's `UpdateForm`. Reach for it when code has to treat reducer * and transitions machines differently. It prefers the form `defineMachine` * recorded, and works the form out from the shape only for a machine that * never went through `defineMachine`. */ declare function formOf(machine: { update: object; __form?: UpdateForm; }): UpdateForm; /** * Thrown when a Msg is dispatched to a state that has no update cell for it. It * names the Msg type, the state, and the Msg types that state does accept. */ declare class NoCellError extends Error { readonly msgType: string; readonly stateName: string; /** The Msg types the refusing state has cells for; empty when it has none. */ readonly acceptedTypes: readonly string[]; readonly name = "NoCellError"; readonly _tag: "NoCellError"; constructor(msgType: string, stateName: string, /** The Msg types the refusing state has cells for; empty when it has none. */ acceptedTypes: readonly string[]); } /** * The Msg types this machine would accept in this state — the same set a * `NoCellError` reports, asked before anything is dispatched. Returns the * state's own row keys in transitions form and the flat table's keys in * reducer form, counting only keys whose cell is a function, and an empty * array (never `undefined`, never a throw) for a state with no cells, no row * at all, or no state value at all. */ declare function acceptedTypes(machine: { update: object; __form?: UpdateForm; }, state: S): readonly string[]; /** * Run the one update cell that matches `state` and `msg` and return its * `[nextState, cmds]`. Use it to step a machine by hand; it throws * `NoCellError` when no cell matches. */ declare function applyCell(machine: { update: object; __form?: UpdateForm; }, state: S, msg: M): readonly [S, readonly C[]]; /** * `applyCell` with the development-mode checks that catch an impure cell: the * input state is frozen and the result is asserted to be plain data. */ declare function applyCellChecked(machine: { update: object; __form?: UpdateForm; }, state: S, msg: M): readonly [S, readonly C[]]; /** * List every Msg type a machine has an update cell for, across all of its * states. */ declare function msgKeysOf(machine: { update: object; __form?: UpdateForm; }): readonly string[]; /** * What `describeMachine` returns: the Msg types a machine handles and, for a * transitions machine, its states and the Msg types each one accepts. */ type MachineShape = { readonly form: "reducer"; /** Every `Msg._tag` the flat reducer has a cell for. */ readonly msgs: readonly string[]; } | { readonly form: "transitions"; /** The union of every row's `Msg._tag` keys (see `msgKeysOf`). */ readonly msgs: readonly string[]; /** Every `state._tag` the table has a row for, in table order. */ readonly states: readonly string[]; /** `state._tag` → the `Msg._tag`s that state has a cell for. */ readonly accepts: Readonly>; }; /** * Describe a machine's update table as data: its form, its Msg types, and the * per-state accept sets of a transitions machine. Use it to build tooling, or * to ask what a machine handles without dispatching to it. */ declare function describeMachine(machine: { update: object; __form?: UpdateForm; }): MachineShape; /** * List the Msg types a machine accepts in the state named `stateType`. A * reducer machine accepts every one of its Msg types in every state, and a * `stateType` with no row in a transitions table accepts none. */ declare function acceptsOf(machine: { update: object; __form?: UpdateForm; }, stateType: string): readonly string[]; /** * The flat form of `update`: a record with one handler per Msg type, each * returning `[nextState, cmds]`. Leaving a Msg type out is a compile error. */ type Reducer = { [K in M["_tag"]]: (state: S, msg: Extract) => SyncReturn; }; /** * The state × message table form of `update`. Every state of `S` needs a row; * a cell inside a row is optional, and leaving one out DECLARES that the state * does not accept that message — the runtime refuses it with `NoCellError` * naming `acceptedTypes`. `ExhaustiveTransitions` requires every cell instead. */ type Transitions = { [P in S["_tag"]]: Partial[P]>; }; /** * `Transitions` with every cell REQUIRED — the opt-in floor for a * machine that wants the compiler to force a decision on every (state, * message) pair. An annotation on your own table, not a third update form: * `defineMachine` takes the annotated table unchanged. */ type ExhaustiveTransitions = { [P in S["_tag"]]: { [K in M["_tag"]]: (state: Extract, msg: Extract) => SyncReturn; }; }; /** * A tagged-union, one-shot effect — JSON-plain, hashable, replayable. * * `T` is the tag. `Ok` and `E` are phantom type parameters (ADR 0014): `Ok` is * the value this Cmd settles with, and `E` is the `_tag` union it can fail * with. A Cmd carries no requirements (ADR 0020) — its handler gets its * services from the plain `ctx` handed to `run`. */ type Cmd = { readonly _tag: T; /** Phantom — the value this Cmd settles with. Never assigned. */ readonly __ok?: Ok; /** Phantom — the `_tag` union this Cmd can settle with. Never assigned. */ readonly __e?: E; }; /** * The helpers for building Cmds: `Cmd.define` declares a typed Cmd constructor, * and `Cmd.none`, `Cmd.batch`, `Cmd.when` and `Cmd.whenDefined` build the Cmd * list an update cell returns. */ declare const Cmd: { /** * Declare a typed Cmd constructor (ADR 0014, 0021). Returns the builder — * `fetch({ url })` yields `{ _tag: "fetch", url }` — carrying the minted Msg * builders `fetch.ok(cmd, value)` / `fetch.err(cmd, error)` (for replay * logs and tests) and the declaration the runtime edge parses against. * `Settled` is the two-arm Msg union it settles with; * `defineMachine({ cmds: [fetch] })` folds that union into the machine's `M`. * * const fetch = Cmd.define("fetch", { * input: z.object({ url: z.string() }), * ok: z.object({ status: z.number(), body: z.string() }), * err: ["not_found", "timeout"], * }); * * `input` and `ok` take any Standard Schema whose `validate` is synchronous: * zod directly, Effect Schema through `Schema.toStandardSchemaV1(...)`. `err` * is the `_tag` list the handler may fail with; the runtime adds * `malformed_result` for an `Ok` value the `ok` schema rejects. * * The handler returns an outcome and the engine mints the Msg: * * fetch: async (cmd, { ok, err }) => * res.status === 404 ? err({ _tag: "not_found" }) : ok(await res.json()), * * A throw or an undeclared tag goes to the error sink, never to `fetch_err`. * The handler reads its services off the plain `ctx` handed to `run` (ADR * 0020). * * A Cmd must not wait; see `DepKeyedSub` for anything that watches. */ readonly define: typeof defineCmd; /** * The empty Cmd array. Typed `readonly never[]` so it's assignable to any * `readonly C[]` for any `C extends Cmd`. Use in `init` returns and * Transitions cells that emit zero effects: * * init: (loaded) => [loaded ?? initial, Cmd.none], * tick: (state) => [state, Cmd.none], * * Elm's `Cmd.none` analogue. Cultural signal alongside the runtime help: * `[state, Cmd.none]` reads as intent ("this transition emits nothing"), * `[state, []]` reads as "empty array of what". * * Frozen at runtime so a downstream consumer can't `.push()` into the * shared reference. */ readonly none: readonly never[]; /** * Flat concat of cmd arrays. Use when a cell composes effects from * multiple conditional sources: * * return [next, Cmd.batch( * Cmd.whenDefined(state.queueItemId, (id) => ({ _tag: "complete", id })), * Cmd.when(state.windowId !== undefined, { _tag: "close_window", windowId }), * [{ _tag: "detach_debugger", tabId: state.tabId }], * )]; * * `` keeps inline cmd literals' discriminants narrow (same * rationale as `when` / `whenDefined` above). */ readonly batch: (...arrs: readonly (readonly C[])[]) => readonly C[]; /** * Emit `cmd` wrapped in a single-element array iff `cond` is true. * Otherwise return the empty array. Spreads cleanly into the cmds array * returned by a Transitions cell. * * `const C` (TypeScript 5.0+) keeps the inferred `_tag:` discriminator * literal narrow when called with an object literal — so `Cmd.when(b, * { _tag: "x", ... })` infers as `{ _tag: "x", ... }`, not `{ _tag: * string, ... }`, and stays assignable to a discriminated-union arm * without `as const` at the call site. */ readonly when: (cond: boolean, cmd: C) => readonly C[]; /** * If `value` is defined, call `build(value)` and emit the resulting cmd * wrapped in a single-element array. If `value` is `undefined`, return * the empty array. `value` is narrowed to `T` inside `build`. * * `const C` on the return type keeps the callback's object-literal * `_tag:` field narrow (see `when` above for the full rationale). */ readonly whenDefined: (value: T | undefined, build: (value: T) => C) => readonly C[]; }; /** The branded string that identifies a running Sub. Build one with `subId`. */ type SubId = string & { readonly __brand: "SubId"; }; /** * Construct a `SubId` from a string. Use this everywhere a Sub literal is * built — including ids derived from runtime data (`subId(\`ws:${auditId}\`)`). * The brand is structural, not nominal, so dynamic ids are permitted; the * constructor's job is to make the identity decision explicit at every call * site so the type system can catch accidental raw-string drift. * * Strengthens invariant 7 (identity is explicit). */ declare function subId(s: string): SubId; /** * A running subscription as its runner sees it: its `_tag`, the `deps` value * the machine's `subs` entry returned, and an `id` derived from both. Use it to * declare a machine's Sub union and to type the `sub` argument of a runner. * * A machine never builds one. It declares `{ _tag, deps(state) }` in `subs` * (see `DepKeyedSub`) and the engine derives the rest. A runner reads its data * off `sub.deps`. `id` is `structuralHash({ _tag, deps })`, so it changes * exactly when the type or the deps value does, which is when the engine * restarts the runner. */ type Sub = { readonly id: SubId; readonly _tag: T; readonly deps: D; }; /** * The cleanup function a Sub runner returns. The runner opens a resource and * returns the function that closes it. The engine calls it when the Sub's * `deps` go null (turned off), when they change (restarted: the old `Dispose`, * then a fresh runner), and when the runtime stops. A returned Promise is * awaited by `stop()`, with a bound. */ type Dispose = () => void | Promise; /** The `deps` a `timer` Sub declares: fire `msg` once, `ms` after it starts. */ type TimerDeps = { readonly ms: number; readonly msg: M; }; /** The built-in `timer` Sub, as its runner sees it. */ type TimerSub = Sub<"timer", TimerDeps>; /** The Sub types every engine ships a runner for. */ type BuiltinSubType = "timer"; /** The built-in Subs a machine over `M` may declare without declaring them. */ type BuiltinSub = TimerSub; /** * The one `id` of a Sub: a structural hash of its `_tag` and its `deps` * value. Same type and same deps → same id → the running Sub is left alone. */ declare function subIdOf(type: string, deps: unknown): SubId; /** * Turn a plain-data value into a stable string that does not depend on object * key order. Use it wherever two values must compare equal by content, as the * engine does for Sub ids. */ declare function structuralHash(deps: unknown): string; /** * One entry of a machine's `subs`: a Sub `_tag` plus `deps(state)`, which * returns the data the runner needs, or `null` to keep the Sub off. */ type DepKeyedSub = U extends Sub ? { readonly _tag: T; /** * The slice of state this Sub depends on. `null` or `undefined` ⇒ off in * this state (see `depsInactive`), so `(s) => s.optionalRunId` gates * correctly. Pure (invariant 2). Plain JSON-compatible data only * (invariant 1): the structural hash THROWS on a `Date`, `Map`, `Set`, * `Error` or class instance rather than collapsing them onto one id. */ readonly deps: (state: S) => D | null | undefined; } : never; /** * A machine's optional message filter: `ofState` names the identity this * instance owns, and `ofMsg` the identity a Msg is addressed to. The engine * drops a Msg addressed to a different identity before `update` runs. */ interface Identity { /** The identity THIS instance owns. Pure (invariant 2); plain value. */ readonly ofState: (state: S) => unknown; /** * The identity a message is addressed to, or `undefined` when the message * carries no identity (lifecycle / pre-identity messages — never dropped). * Pure (invariant 2); plain value when defined. */ readonly ofMsg: (msg: M) => unknown; } /** * Return `true` when the engine would let `msg` through the identity filter, * or `false` when it would drop it. `run` applies this check for you. * `applyCell`, `tryApplyCell`, `foldMsgs` and `replay` do not, so a host that * steps a machine itself calls this first. */ declare function matchesIdentity(identity: Identity | undefined, state: S, msg: M): boolean; /** * A named, typed channel for values leaving the runtime. A Cmd handler sends on * it with `ctx.emit(port, value)` and a host listens with * `runtime.subscribePort`; create one with `definePort`. */ interface Port { readonly __brand: "port"; readonly name: string; readonly __t?: T; } /** * Augmentation injected onto `ctx` inside Cmd handlers. Handlers receive * `ctx & PortEmitter` so they can call `ctx.emit(port, value)` synchronously. * Subscribers registered via `runtime.subscribePort(port, listener)` receive * the value immediately. * * Emitting to a port with no subscribers is a no-op (does not throw). */ interface PortEmitter { emit(port: Port, value: T): void; } /** * The `Ctx` of a machine whose handlers read nothing from context. Use it in * place of `unknown` to say so on purpose. */ type NoCtx = Readonly>; type HandlerCtx = (0 extends 1 & Ctx ? Ctx : [ Ctx ] extends [void] ? unknown : Ctx) & PortEmitter; /** * The Cmd handler table an engine is handed: one async handler per Cmd type. * Leaving a Cmd type out is a compile error. */ type Interpret = { [K in C["_tag"]]: InterpretCell, Ctx>; }; /** * One cell of {@link Interpret}: the outcome-returning form for a * `Cmd.define`d Cmd, the form returning a Msg, a list of Msgs or nothing for a * hand-written one. A Cmd is `Cmd.define`d exactly when its `E` phantom is * declared (not `unknown`). A returned list is dispatched in order. */ type InterpretCell = unknown extends ErrorsOf ? (cmd: C, ctx: HandlerCtx, dispatch?: (msg: M) => void) => Promise : (cmd: C, ctx: HandlerCtx & OutcomeHelpers, DeclaredErrorsOf>, dispatch?: (msg: M) => void) => Promise, DeclaredErrorsOf> | Owed | void>; /** The value a Cmd settles with; `unknown` for a hand-written Cmd. */ type OkOfCmd = C extends { readonly __ok?: infer Ok; } ? Ok : unknown; /** The failures a `Cmd.define`d Cmd's handler may return: its declared tags. */ type DeclaredErrorsOf = Exclude, MalformedResult>; /** * A Cmd handler that reports back through a `dispatch` limited to the Msgs it * is allowed to send. Use it for work that outlives the handler call, and adapt * it into an `Interpret` cell with `wrapDetached`. * * Such a handler hands its long-running work to `ctx.waitUntil(...)` and cannot * return its terminal Msg inline, because awaiting it would deadlock the serial * dispatch tail. So it returns `Promise` and dispatches instead. * `Allowed` is the Cmd's declared result-Msg set (e.g. * `GraphFinished | GraphFailed`), and `dispatch` takes only those, so a wrong * or mistyped terminal Msg fails to compile. */ type InterpretDetached = (cmd: C, ctx: HandlerCtx, dispatch: (msg: Allowed) => void) => Promise; /** * The Sub runner table an engine is handed: one runner per Sub type. Leaving a * Sub type out is a compile error. Each runner receives the running Sub * (`{ id, _tag, deps }`), the Ctx and a `dispatch`. It opens its resource, * dispatches Msgs from it, and returns the `Dispose` the engine calls when the * Sub stops. */ type Subscribe = { [K in U["_tag"]]: (sub: Extract, ctx: Ctx, dispatch: (msg: M) => void) => Dispose; }; /** * The `interpret` option of an engine's `run`: optional for a machine that * emits no Cmd, required — one handler per Cmd variant — for one that does. */ type InterpretArg = [ C ] extends [Cmd] ? { interpret?: Interpret; } : { interpret: Interpret; }; /** * The `subscribe` option of an engine's `run`: one runner per Sub type the * machine declares, except the built-ins (`timer`) the engine already ships. * Optional when every declared type is a built-in. An entry named after a * built-in replaces it (#270 R2.1), which is how a test drives time. */ type SubscribeArg = [ Exclude ] extends [never] ? { readonly subscribe?: Partial> | BuiltinSub, Ctx>>; } : { readonly subscribe: Subscribe, Ctx> & Partial, Ctx>>; }; /** * The handlers an engine is handed beside a machine: the {@link InterpretArg} * Cmd handlers and the {@link SubscribeArg} sub runners. A machine carries * neither — it is data, and one machine file runs under any engine. */ type RunHandlers = InterpretArg & SubscribeArg; /** * A machine beside the handlers it runs under — what a wrapper, a battery's * `toMachine` or an agent host hands around, and what an engine takes apart: * `run(wired.machine, { ...wired, ctx })`. */ type Wired = { readonly machine: Machine; } & RunHandlers; /** * A machine as plain data: `init`, `update`, and optionally `subs`, `cmds` and * `identity`. Build one with `defineMachine` and hand it to an engine's `run`. */ type Machine = { /** * Boot the runtime. Called once by `run(...)` with whatever `Store.load()` * returned: `null` on fresh boot, the persisted state on rehydrate. * * Both fresh and restored init may return a new State and Cmds. Init is * pure: it describes effects; handlers perform them. The engine saves the * returned State, reconciles its Subs, then runs its Cmds. Under `run`'s * `boot: "restored"` with a loaded State the Cmds are not run (ADR 0039). * * Put state-conditional resume work here, with the in-flight phase in the * returned State so a fast Sub cannot start it again. A host Msg sent after * `ready` runs after Subs have opened and supplies no such ordering. * Recorded replay starts from captured post-init State without calling init. */ init: (loaded: S | null, ctx: Ctx) => readonly [S, readonly C[]]; /** * The typed Cmd constructors this machine emits (`Cmd.define`). Declared * through `defineMachine({ cmds })`, which derives `C` and the settled half * of `M` from them; the runtime reads the list to parse each handler's * `_ok` value against its `ok` schema and stamp `at` at the interpret edge. * A machine of hand-written Cmds omits it and runs exactly as before. */ readonly cmds?: readonly AnyCmdDef[]; update: Reducer | ([S] extends [{ _tag: string; }] ? Transitions : never); /** * The machine's Subs, as data: each entry names a Sub `_tag` and the state * slice it depends on (`deps`). The engine derives the id * (`structuralHash({ _tag, deps })`) and the gate (`deps` non-null), starts * the runner for `_tag` when an entry turns on, leaves it alone while the id * holds, restarts it when the id changes, and stops it on `null` or `stop()`. * * `U` is the machine's own Sub union (`types.sub`); the built-in `timer` * (`{ _tag: "timer", deps: (s) => ({ ms, msg }) }`) is always available. * * Strengthens invariant 4 (lifecycle owned by the substrate) and invariant 7 * (identity derived, not hand-authored). */ readonly subs?: ReadonlyArray>>; /** * Phantom — never assigned, never read. `subs` reaches `U` only through a * conditional type, which is no inference site, so this is the slot a caller * like `run(machine, …)` infers the Sub union from (and so what types its * `subscribe` runners). Same device as `Cmd`'s `__ok`. Tuple-wrapped so an * empty union (`never`) is still a candidate rather than `undefined`. */ readonly __sub?: readonly [U]; /** * Instance-identity filter. Declares THIS instance's identity once; the * substrate drops any message addressed to a DIFFERENT identity before it * reaches `update`. Replaces the per-cell `if (msg.runId !== state.runId)` * guard entirely — the reducer never sees a foreign-instance message, so no * cell needs to check. * A host that steps the machine itself with `applyCell` calls * `matchesIdentity` first. * * Opt-in: a machine that omits `identity` skips the filter (every message * reaches `update`, exactly as before). A message whose `ofMsg` returns * `undefined` is identity-agnostic and always reaches `update` (lifecycle / * pre-identity messages). * * Strengthens invariant 7 (identity is explicit — declared once, enforced by * the substrate) and invariant 6 (mis-addressed messages dropped at one * observable point, not per cell). */ identity?: Identity; /** * The update form ("reducer" | "transitions"), stamped non-enumerably by * `defineMachine` at construction (see `UpdateForm` / `formOf`). Optional in * the type so the structural `Machine` annotation form keeps accepting plain * object literals; readers go through `formOf`, which falls back to * `detectUpdateForm` when the tag is absent. Never written by hand. */ readonly __form?: UpdateForm; }; /** * Fold a machine's `update` over a list of Msgs from a starting state, and * return the final state with every Cmd the cells emitted. `replay` and * `foldMsgs` cover the common cases; use this when you need both the state and * the Cmds from a state of your choosing. */ declare function foldUpdates(machine: { update: object; __form?: UpdateForm; }, initialState: S, msgs: readonly M[]): { state: S; cmds: C[]; }; /** * Fold a machine's `update` over a list of Msgs from a base state and return * only the final state. Use it for client-side prediction: re-apply * unacknowledged inputs on top of a server snapshot without running any effect. */ declare function foldMsgs(machine: Machine, base: S, msgs: readonly M[]): S; export { UndeclaredFailureError as $, type AnyCmdDef as A, type BuiltinSub as B, type CmdOf as C, type Dispose as D, type ErrorsOf as E, type ExhaustiveTransitions as F, type Identity as G, type HandlerCtx as H, type Interpret as I, type InterpretArg as J, type InterpretCell as K, type MachineShape as L, type Machine as M, NoCellError as N, Outcome as O, type Port as P, type NoCtx as Q, type RunHandlers as R, type Subscribe as S, type TimerDeps as T, type UpdateForm as U, OutcomeContractError as V, type Wired as W, type OutcomeHelpers as X, type PortEmitter as Y, type SubscribeArg as Z, type SyncReturn as _, type CmdDef as a, acceptedTypes as a0, acceptsOf as a1, applyCell as a2, applyCellChecked as a3, deliveryIdOf as a4, describeMachine as a5, detectUpdateForm as a6, foldMsgs as a7, foldUpdates as a8, formOf as a9, matchesIdentity as aa, msgKeysOf as ab, owed as ac, structuralHash as ad, subId as ae, subIdOf as af, Cmd as b, type Sub as c, type SettledOk as d, type SettledErr as e, type TaggedError as f, type SubId as g, type DepKeyedSub as h, type DeliveryId as i, type Reducer as j, type Settled as k, type Transitions as l, type InterpretDetached as m, type TimerSub as n, type CmdValue as o, type MalformedResult as p, type OkOfCmd as q, type Owed as r, type DeclaredErrorsOf as s, type BuiltinSubType as t, type CmdInput as u, type Tagged as v, type OkOf as w, type ErrOf as x, AsyncSchemaError as y, CmdNameCollisionError as z };