import { i as DeliveryId, b as Cmd, c as Sub, R as RunHandlers, M as Machine, P as Port, N as NoCellError, j as Reducer, A as AnyCmdDef, k as Settled, C as CmdOf, l as Transitions, B as BuiltinSub, U as UpdateForm, O as Outcome, m as InterpretDetached, H as HandlerCtx } from './core-sEWVgnpI.js'; /** * @demlik/tea/do — the durable pending-effects ledger (substrate primitive #1). * * Durable *state* and durable *effects* are different problems. An * event-sourced actor rebuilds its STATE by folding the event log * (`doEventSourcedStore`, sibling file). But an outbound side effect — a tool * round-trip, a message to a sibling grain — is fire-and-forget: if the actor * interprets the `Cmd` inside an activation that hibernates mid-flight, the * effect is lost, yet nothing in the replayed state records that it is still * OWED. This is the one real tax of the event-sourced-virtual-actor target * (ADR 0003 primitive #1): "I owe this effect" must itself be part of the * folded state. * * Akka's classic `AtLeastOnceDelivery` solves it with a ledger of unconfirmed * deliveries kept AS PART OF the persisted state: each `deliver` adds an entry * keyed by a monotonic `deliveryId`; each `confirmDelivery` removes it. On * recovery the ledger is rebuilt from the SAME events, and any surviving entry * is re-sent. At-least-once ⇒ a confirmed-but-not-yet-persisted delivery WILL * be re-sent after a crash, so the receiver must deduplicate by id. * * ## The load-bearing rule (do not violate) * * The ledger is a PURE FOLD over the same kind of event stream the actor * already replays — it is **NOT** a separately-persisted side table: * * - `effect_owed` — `{ id, effect }` ADDS an entry to the ledger. * - `effect_confirmed`— `{ id }` REMOVES the entry. * * `foldLedger(events)` is `events.reduce(applyEffectEvent, empty())` — the same * fold shape `replay` / `foldEvents` / the recorder use. Persist these two * events into the SAME log `doEventSourcedStore` already appends (they are just * Msg variants), and the ledger is rebuilt for free on the next activation: * `foldLedger(log)` after eviction equals `foldLedger(log)` never-evicted, by * construction (a pure fold over identical input). * * On activation (replay completion), `survivingEffects(ledger)` returns the * owed-but-unconfirmed entries to re-fire, ordered by their monotonic id. The * re-fire is a SIDE EFFECT DERIVED from the surviving ledger — never stored * separately, never fired during replay (recovery.md: add to the ledger during * recovery; let recovery-END re-emit the survivors). * * Anti-patterns this file refuses (mirroring durable-effects.md): * - A side-table ledger persisted apart from the events. The events ARE the * ledger; the Map is rebuilt by folding them. * - Re-firing every historical effect during replay. Only `survivingEffects` * (post-fold) re-emits. * - Assuming the receiver gets each effect exactly once. At-least-once: dedup * by `id` at the receiver (`isOwed` here is the sender's view; the receiver * owns its own dedup). */ /** * An effect is now OWED: it has been decided but its delivery is not yet * confirmed. Adds `{ id → effect }` to the ledger when folded. * * Persist this BEFORE interpreting the effect (durable-effects.md rule: * "persist the intent before deliver"). A crash between persist and deliver is * fine — the surviving entry re-fires on activation. A crash before the persist * means the effect was never owed, so nothing is lost that the actor promised. */ interface EffectOwed extends Cmd<"effect_owed"> { readonly id: DeliveryId; readonly effect: E; } /** * An owed effect has been CONFIRMED delivered. Removes its entry from the * ledger when folded. Persist this BEFORE acting on the confirmation * ("persist the confirmation before confirmDelivery"). */ interface EffectConfirmed extends Cmd<"effect_confirmed"> { readonly id: DeliveryId; } /** The event union the ledger folds over. `E` is the consumer's effect type. */ type EffectLedgerEvent = EffectOwed | EffectConfirmed; /** * The pending-effects ledger: owed-but-unconfirmed effects keyed by their * monotonic delivery id. A pure value reconstructed by `foldLedger` — it is * never persisted on its own; the events are. * * `ReadonlyMap` preserves insertion order, which (because ids are appended * monotonically) is exactly id order — so iteration yields the survivors * oldest-first with no sort. */ type PendingEffectsLedger = ReadonlyMap; /** A single surviving entry to re-emit: its id and the effect it owes. */ interface OwedEffect { readonly id: DeliveryId; readonly effect: E; } /** The empty ledger — the fold's starting value (a fresh actor owes nothing). */ declare function emptyLedger(): PendingEffectsLedger; /** * Apply ONE ledger event — the reducer at the heart of the fold. * * - `effect_owed` → add `{ id → effect }`. * - `effect_confirmed` → remove `id` (no-op if already absent: a duplicate * confirm, or a confirm for an id evicted with the actor — at-least-once * tolerates both). * * Pure: returns a NEW ledger, never mutates the input — so folding the same * events twice (live and post-eviction) yields equal results, and a caller may * keep the prior ledger value. */ declare function applyEffectEvent(ledger: PendingEffectsLedger, event: EffectLedgerEvent): PendingEffectsLedger; /** * THE FOLD. Rebuild the ledger from an event stream — the same fold shape * `replay` uses for state. After a simulated eviction this is called over the * persisted log and yields a ledger byte-for-byte equal to the never-evicted * one, because a pure fold over identical input is identical. * * This is the function that proves "no side table": the ledger is `events` * reduced, nothing more. */ declare function foldLedger(events: Iterable>): PendingEffectsLedger; /** * RE-EMIT ON ACTIVATION. Given the rebuilt ledger, the owed-but-unconfirmed * effects to re-fire — ordered oldest-first by monotonic id. On a fresh / * fully-confirmed actor this is empty (nothing re-emitted). * * Idempotency is the RECEIVER's job: it must dedup by `id`, because * at-least-once means a re-emitted already-handled id WILL arrive again * (e.g. an effect confirmed in the activation that hibernated before the * `effect_confirmed` event was persisted). Re-firing the same id is therefore * a no-op AT THE RECEIVER, not here. */ declare function survivingEffects(ledger: PendingEffectsLedger): readonly OwedEffect[]; /** Is this id still owed (unconfirmed) in the ledger? Sender-side view. */ declare function isOwed(ledger: PendingEffectsLedger, id: DeliveryId): boolean; /** * A live, monotonic-id-issuing ledger recorder. * * - `owe(effect)` — allocate the next `deliveryId`, return the * `effect_owed` event to PERSIST plus the allocated `id`. Folding the event * into the recorder's mirror is done for you; the caller persists it. * - `confirm(id)` — return the `effect_confirmed` event to PERSIST, and `true` * iff the id was owed (a duplicate confirm returns `false` — the boolean is * itself a dedup signal, exactly Akka `confirmDelivery`). * - `surviving()` — the current owed-but-unconfirmed effects (for re-emit on * activation). * - `ledger()` — the current folded ledger value. * - `lastId()` — the highest id issued (so a host can seed the counter from a * rebuilt ledger after eviction; see `restore`). */ interface PendingEffectsRecorder { owe(effect: E): { id: DeliveryId; event: EffectOwed; }; confirm(id: DeliveryId): { confirmed: boolean; event: EffectConfirmed; }; surviving(): readonly OwedEffect[]; ledger(): PendingEffectsLedger; lastId(): DeliveryId; } /** * Build a live recorder. `restore` rehydrates it after an eviction: pass the * events read back from the log (or the rebuilt ledger's survivors) so the * monotonic counter resumes WITHOUT gaps and the mirror reflects the surviving * owed set. Omit `restore` for a fresh actor. * * Counter seeding rule: the next id is `max(seen ids) + 1`. Restoring only the * survivors is sufficient for correctness of re-emit, but to keep ids gap-free * across confirmed-and-pruned entries the host should pass `lastId` explicitly * when it has it (e.g. persisted alongside the snapshot). When only survivors * are known, the counter resumes from the highest surviving id — a confirmed id * higher than every survivor could in principle be reissued, so a host that * needs strict global monotonicity persists `lastId`. */ declare function pendingEffectsLedger(restore?: { readonly events?: Iterable>; readonly lastId?: DeliveryId; }): PendingEffectsRecorder; /** * @demlik/tea runtime interface surface + pure helpers — the public types, * interfaces, and construction/composition helpers the runtime (`./run`) * implements against: `Store`, the error-sink and supervision contracts, the * engine-neutral `RunHandle` / `BootedRunHandle` host adapters are typed on, * the Promise engine's `RuntimeRef` / `BootingRuntime` / `Runtime` handle * hierarchy that widens it, `definePort`, the * identity-typed constructors `defineMachine` / `asReducer`, and the pure tools * `replay` (compose without running) and `tryInterpret` (Railway). */ declare const ReducerBrand: unique symbol; /** * A `Reducer` or `Transitions` value that went through `asReducer` or * `defineMachine`. It carries the phantom brand and otherwise behaves exactly * like the unbranded value. */ type Branded = T & { readonly [ReducerBrand]: true; }; /** * Compile-time exhaustiveness assertion for default branches of switches over * discriminated unions narrowed by hand (Sub handlers, message-bridge * dispatchers, port fanouts) — TS narrows the operand to `never` only if every * variant is covered, so adding one produces a compile error at the `absurd(x)` * site. Strengthens invariant 7 (identity is explicit). * * @example * ```ts * import { absurd } from "@demlik/tea"; * * type Msg = { _tag: "a" } | { _tag: "b" }; * * function label(msg: Msg): string { * switch (msg._tag) { * case "a": return "A"; * case "b": return "B"; * default: return absurd(msg); // compile error if a "c" is added * } * } * ``` */ declare function absurd(x: never): never; /** * An update cell that ignores its Msg: it returns the state unchanged, with no * Cmds. Use it to say a state deliberately does nothing for a Msg. */ declare const noop: (state: S, _msg: M) => readonly [S, readonly C[]]; /** * Thrown by `definePort` when a name has already been registered in the current * process. It mechanizes invariant 7 (identity is explicit) at the runtime * layer the type system cannot reach (string names compared at runtime). */ declare class PortNameCollisionError extends Error { readonly name = "PortNameCollisionError"; readonly _tag: "PortNameCollisionError"; constructor(portName: string); } /** * Test-only escape hatch — clears the module-level port-name registry so the * collision assert in `definePort` doesn't false-positive across vitest's * non-isolated runs. Production code MUST NOT call this. * * @internal test-only */ declare function __resetPortRegistry(): void; /** * Which otherwise-unattributable runtime path produced an error. Every fanout is * throw-isolated so one bad consumer never strands its siblings, and the * isolated throw routes to the `OnError` sink rather than a bare `console.error`. * * - `"follow-up"` — a Msg sent with `tell`, by a Sub, or by a Cmd rejected with * no caller to receive the rejection. A reducer's thrown object is already * reported under `"reduce"`, and a Sub runner's throw as it starts under * `"sub"`; neither is reported again here. Primitive throws * cannot be tracked by identity and still reach both phases. * A rejection caused by `stop()`'s own teardown is NOT this phase — see * `"discard"`. * - `"interpret"` — a `Cmd.define`d handler failed outside its declared * channel (ADR 0021): it threw, returned an `Err` whose tag it does not * declare (`UndeclaredFailureError`), or returned something the engine cannot * mint (`OutcomeContractError`, `AsyncSchemaError`). No `_err` Msg is * dispatched, and the dispatch that emitted the Cmd still resolves. * - `"stop-save"` — the final `store.save(state)` inside `stop()` threw * (`stop()` resolves regardless, so without the sink this was silent loss). * - `"reduce"` — the pure `update` (reducer) threw synchronously; the configured * `Supervision` strategy decides what happens next, but the throw is surfaced * here as data first. * - `"listener"` — a `runtime.subscribe(...)` listener threw during fanout. * - `"observer"` — a `runtime.observe(...)` observer threw during fanout, or * the `telemetry` sink threw or rejected. * - `"event"` — the `events` projector or an `on(type, ...)` handler threw. * - `"boot"` — an `onBoot` handler threw (boot fanout, or a late registration), * or the `agent_boot` dispatch `createAgentHost` queues for a restored run * rejected, for example because its save failed. * - `"port-emit"` — a `subscribePort` listener threw during a port emission. * - `"sub-cleanup"` — a subscription's cleanup threw (reconcile-removal or * `stop()` teardown). * - `"sub"` — a running Sub failed with an error it did not turn into a Msg: * its runner threw while starting, or (Effect engine) its Stream failed. The * run stops — on the Effect engine by closing its Scope with the failure. A * Sub that expects an error maps it to a Msg itself; there is no hook for it * here. * - `"discard"` — work lost to a teardown the host asked for. Four witnesses, * each carrying a `RuntimeDiscardNotice`: `stop()` was called while interpret * handlers were still awaiting (`RuntimeDiscardedError`), a Msg that * arrived DURING `stop()`'s drain, or from a handler `stop()` gave up on, and * so could not be delivered (`DispatchDiscardedError`), a drain that did not * finish inside `disposeTimeoutMs`, which also counts the Msgs that were still * queued (`DrainTimeoutNotice`), and teardown work that did not settle inside * `disposeTimeoutMs` * (`DisposeTimeoutNotice`). The one phase that is a * LIFECYCLE report rather than a failure: legal, merely lossy. * - `"identity-drop"` — the `Identity` filter dropped a message addressed to a * different instance (`IdentityDropNotice`). Its own phase rather than * `"discard"`: the loss is the FILTER WORKING, not a teardown, and a host * routing it (a metric, a 409 back to the caller) wants it apart from * unmount-time noise. Warn-only, like every `RuntimeDiscardNotice`. * * The phase never decides fatality — the ERROR CLASS does (`RuntimeDiscardNotice` * warns, everything else rethrows). A phase is attached by the report site, so a * consumer sink that throws while handling a `"discard"` report inherits that * phase; keying the warn-only path on it would make the sink's own defect vanish. */ type RuntimeErrorPhase = "follow-up" | "interpret" | "stop-save" | "reduce" | "listener" | "observer" | "event" | "boot" | "port-emit" | "sub-cleanup" | "sub" | "discard" | "identity-drop"; /** * What the `telemetry` sink passed to `run` receives, once per APPLIED * transition. Plain data, so a recorded stream stays durable. */ interface TelemetryEvent { /** This run's applied transitions so far, counted from 1. Boot is not one. */ readonly seq: number; /** The `Msg._tag` that drove the transition. */ readonly msgType: string; /** When the transition committed, read off `run`'s `clock` (ms since epoch). */ readonly at: number; } /** * The `telemetry` option of `run`: a fire-and-forget sink. The run never waits * on it, and a throw or rejection reaches `onError` under `"observer"` without * touching the run. */ type TelemetrySink = (event: TelemetryEvent) => void | Promise; /** Context handed to an `OnError` sink alongside the error itself. */ interface RuntimeErrorContext { readonly phase: RuntimeErrorPhase; } /** * Sink for runtime failures that have no caller to reject at. Configured via * `run(machine, { onError })`. Should be total — a throw inside the sink is * itself surfaced via the default sink, so it can never re-introduce a silent * failure. * * Optional, except beside a fenced store (see {@link StoreAndOnError}): there it * does not compile without one, and a run whose store is fenced at runtime is * refused at start without one, whatever its type says. With no * sink a `RuntimeDiscardNotice` is warned, and every other failure is rethrown on * a fresh macrotask, which ends a Node process and every run in it. That includes * a failing Sub (`"sub"`). A host running several machines in one process passes * a sink that decides what one run's failure means for the rest. */ type OnError = (error: unknown, context: RuntimeErrorContext) => void; /** The three declared reducer-throw supervision strategies. */ type SupervisionStrategy = "stop" | "escalate" | "restart"; /** * Declared supervision policy for a reducer (`update`) throw, at * `run(machine, { supervision })`. The bare-string shorthands (`"stop"` / * `"escalate"`) are accepted for the two strategies that need no host data; * `restart` MUST be the object form because it carries the `rehydrate` callback, * which MUST return a valid `S` synchronously (the reducer is synchronous, so * recovery is too — no suspension across the single-writer slot). */ type Supervision = "stop" | "escalate" | { /** * The default. A reducer throw stops the run by itself, the same stop a * Sub failure starts: the Msgs already in line fold, then the Subs close, * the final save runs and, on the Effect engine, the run's own Scope * closes, so a run `spawn` started leaves the host's table and its * `notify` runs. `done()` fails with the throw. A later `stop()` from the * host does nothing more. */ readonly strategy: "stop"; } | { readonly strategy: "escalate"; } | { readonly strategy: "restart"; /** * Host-provided rehydration to last-known-good state. Invoked when the * reducer throws; its return value becomes the new state and the transition * continues from there. Receives the pre-throw `state`, the `msg` that * triggered the throw, and the thrown `error` so the host can route by * cause. */ readonly rehydrate: (state: S, msg: M, error: unknown) => S; }; /** * What `done()` rejects with once a Sub's failure the Sub did not map to a Msg * has stopped the run, which can then never reach a terminal State. `cause` is * what the Sub failed with, the same value `onError` heard under `"sub"`. */ declare class SubFailedError extends Error { readonly cause: unknown; readonly name = "SubFailedError"; readonly _tag: "SubFailedError"; constructor(cause: unknown); } /** * Raised by `idle()` when the quiescence wait hits its iteration cap without the * dispatch tail stabilizing — `idle()` REJECTS rather than silently resolving, * so a livelocking machine surfaces instead of masquerading as quiescent. * Mechanizes invariant 6 at the runtime layer, the role `PortNameCollisionError` * plays for invariant 7. */ declare class QuiescenceTimeoutError extends Error { readonly iterations: number; readonly name = "QuiescenceTimeoutError"; readonly _tag: "QuiescenceTimeoutError"; constructor(iterations: number); } /** * Raised by `driveToDone` when the drive ends on a State its `failed` predicate * marks as a failure. Carries that final State so the caller reads the failure * off the Model the machine owns — never off a message string. A rejection, not * a resolve, so a failed run cannot be mistaken for a finished one at the * caller boundary (invariant 6). */ declare class DriveFailedError extends Error { readonly state: S; readonly name = "DriveFailedError"; readonly _tag: "DriveFailedError"; constructor(state: S); } /** * Raised by `driveToDone` when `start`'s follow-up chain quiesces on a State * that is neither terminal nor `failed` AND nothing in the runtime can still * transition it — no live Sub, no in-flight Cmd. Waiting * past that point is not the Sub-driven contract, it is a leak: no transition is * coming, so the drive would hang with the runtime alive and `stop()` never * reached. The rejection carries the stalled State on `error.state`, sibling to * `DriveFailedError`, so the caller reads where the machine parked off the * Model rather than off a message string (invariant 6). * * A machine that CAN still move — a Sub that will deliver the terminal Msg after * the dispatch quiesces — is not stalled and the drive keeps waiting; this names * only the case where the runtime itself can prove nothing is coming. When a Cmd * handler's failure is what left the run with nothing to do, the drive rejects * with that failure itself instead. */ declare class DriveStalledError extends Error { readonly state: S; readonly name = "DriveStalledError"; readonly _tag: "DriveStalledError"; constructor(state: S); } /** * Base of the LOSSY-BUT-LEGAL teardown facts: work the host discarded by letting * go of a runtime that still had something outstanding. Reported under * `phase: "discard"`, never raised. * * It exists so "is this fatal?" has ONE definition — `error instanceof * RuntimeDiscardNotice` — that the default sink can ask about any error from any * site. The phase cannot answer it: a report site attaches the phase, so a * consumer sink that throws while handling a `"discard"` report carries that * phase into the sink-failure path, and a phase-keyed warn branch would swallow * the sink's own defect. Sub-classing is how a new teardown fact opts into the * warn-only treatment; nothing else can. */ declare abstract class RuntimeDiscardNotice extends Error { } /** * Reported to the `OnError` sink under `phase: "discard"` when `stop()` is * called while `interpret` handlers are still awaiting. The host is dropping * its only handle on that work: `stop()` drains the tail, up to * `disposeTimeoutMs`, but the listeners, * observers and event handlers that would have consumed the resulting * transitions are gone, so the Cmds' results reach nobody. * * The motivating shape is `@demlik/tea/react`'s `useMachine`, which memoizes on * `[machine, ctx, store]` — a ctx re-derived mid-flight replaces the runtime, * and the in-flight mutation's response arrives for a runtime the UI no longer * renders, silently rewinding the visible state. Never a throw: tearing a * runtime down mid-flight is legal (a navigation does it every time), so this * is surfaced as data, not raised. Mechanizes invariant 6 (no silent failures) * at the teardown seam, the role `QuiescenceTimeoutError` plays for `idle()`. */ declare class RuntimeDiscardedError extends RuntimeDiscardNotice { readonly pendingCmds: number; readonly name = "RuntimeDiscardedError"; readonly _tag: "RuntimeDiscardedError"; constructor(pendingCmds: number); } /** * Reported to the `OnError` sink under `phase: "identity-drop"` when the * `Identity` filter drops a message addressed to a different instance. * * The drop itself is the feature — it is what lets a reducer stop repeating * `if (msg.runId !== state.runId) return`. What was missing is that it was * INVISIBLE: the dispatch resolved exactly like an applied one, so a reusable * Durable Object serving run A and then run B lost every run-B message and * reported success to each caller. The comment claiming "the one observable * enforcement point" described this notice before it existed. * * Never fatal (`RuntimeDiscardNotice`): a mis-addressed message is a normal * consequence of instance reuse, not a defect. A host that wants to act on it * — a metric, a 409 to the caller, a re-route — reads `phase: "identity-drop"` * in its own sink. */ declare class IdentityDropNotice extends RuntimeDiscardNotice { readonly msgType: string; readonly name = "IdentityDropNotice"; readonly _tag: "IdentityDropNotice"; constructor(msgType: string); } /** * Reported to the `OnError` sink under `phase: "discard"` when `stop()`'s wait * for async teardown work hits `disposeTimeoutMs`. * * `stop()` awaits the disposals it started so `await runtime.stop()` can mean * "safe to evict". A `release` that never settles must not turn that guarantee * into a host that never shuts down, so the wait is bounded and expiry is * REPORTED rather than silently tolerated — the resource is genuinely still * open at that point, and only the host can decide what that costs. */ declare class DisposeTimeoutNotice extends RuntimeDiscardNotice { readonly pendingDisposals: number; readonly timeoutMs: number; readonly name = "DisposeTimeoutNotice"; readonly _tag: "DisposeTimeoutNotice"; constructor(pendingDisposals: number, timeoutMs: number); } /** * Reported to the `OnError` sink under `phase: "discard"` when `stop()`'s wait * for the queue hits `disposeTimeoutMs` (ADR 0025): a Cmd handler, a save or * detached work had not returned. * * `stop()` resolves by contract, so it gives up on that work instead of waiting * for it without limit. It then stops the Subs and runs the final save as it * always does. The work it gave up on is not recalled — a Promise cannot be * cancelled — so a handler may still be running after `stop()` has returned. * Whatever it returns later is dropped, and so are the Msgs queued behind it. * The rest of its step's Cmds are skipped: no handler starts for them, and they * get no notice of their own. None of it is saved. * * `droppedMsgs` is how a host learns what it lost. It counts the Msgs queued * behind the stuck work when `stop()` gave up, per Msg type: Msgs handed to * `dispatch` or `tell`, and those a handler or a Sub sent. It carries types and * counts only, never a payload, so a sink can log it. It is read once and does * not change. A Msg it counts is not reported again: if the handler returns * late, a `dispatch` caller's promise rejects with a `DispatchDiscardedError`, * and a Msg with no caller reaches the sink no second time. If the handler * never returns, those promises never settle, and this count is the only word. * * tea starts no store call after `stop()` has returned. A store call already * under way when `stop()` gave up is not cancelled and can finish afterwards. * A fenced store refuses that late save, and so does `doEventSourcedStore` * once a newer run has loaded its log; a custom plain store that waits before * it writes takes it over what a newer run saved. * * `cmdTypes` names the Cmd of each handler call still awaiting, one entry per * call. `pendingCmds` counts those plus any detached work, the same count * `RuntimeDiscardedError` carries. */ declare class DrainTimeoutNotice extends RuntimeDiscardNotice { readonly cmdTypes: readonly string[]; readonly pendingCmds: number; readonly timeoutMs: number; readonly droppedMsgs: Readonly>; readonly name = "DrainTimeoutNotice"; readonly _tag: "DrainTimeoutNotice"; constructor(cmdTypes: readonly string[], pendingCmds: number, timeoutMs: number, droppedMsgs?: Readonly>); } /** * The rejection of a dispatch that arrived DURING `stop()`'s drain — an in-flight * interpret handler's follow-up Msg, a detached handler's terminal Msg, or a Sub * that is still live because subs are torn down only after the drain. The stop * barrier is absolute (the Msg is refused, never folded), so this names the loss. * * It is also the rejection of the work `stop()` gave up on (see * `DrainTimeoutNotice`): a Msg a stuck handler produces after `stop()` has * returned, and a Msg that was accepted before `stop()` and was still queued * behind that handler. * * It is the SECOND witness of `RuntimeDiscardedError`'s fact, and it is why the * drain window is a distinct runtime state rather than a plain `stopped` flag: * a Msg refused inside the window was discarded BY the teardown, while the same * refusal after `stop()` has returned is a consumer dispatching into a runtime it * already retired — a real error, and still loud (`phase: "follow-up"`, or the * caller's own rejection). The distinction is the state at refusal time, never * the message text. */ declare class DispatchDiscardedError extends RuntimeDiscardNotice { readonly msgType: string; readonly name = "DispatchDiscardedError"; readonly _tag: "DispatchDiscardedError"; constructor(msgType: string); } /** * Define a typed port. `name` is metadata (devtools / debug logs); port identity * is by reference. Each definePort call must use a unique `name` — a second call * with the same name throws `PortNameCollisionError`. Use ports for "data leaving * the runtime selectively" (cursor announcements, DOM-mutation broadcasts, * telemetry) that should NOT be folded into State. Strengthens invariant 7. */ declare function definePort(name: string): Port; /** * Where an engine loads and saves a machine's state. Implement `load`, `save` * and `migrate` to persist to your own storage, or use a store an adapter * ships. * * `save` receives the Msg whose transition produced `state`, as an optional * second argument. The engine awaits `save` before it starts that transition's * Cmds, so a store that records the Msg has it durable before any effect runs. * A store that keeps only the State can ignore it. The boot save and the final * flush at `stop()` carry no Msg, and a transition that folds to `null` is not * saved at all. * * The third argument, {@link SaveBoundary}, says which boundary the save is: * the State `init` produced and the Cmds it starts, an applied Msg's * transition and its Cmds, or the flush at `stop()`. A recording store keeps * the evidence it carries; others ignore it. */ interface Store { load(): Promise; save(state: S, msg?: unknown, boundary?: SaveBoundary): Promise; migrate(raw: unknown): Migrated; } /** * Which boundary a {@link Store.save} records. `init` is the State `init` * produced at boot, with the Cmds the engine starts for it (`[]` when it * starts none). `step` is an applied Msg's transition, with the Cmds it * starts. `stop` is the final flush. */ type SaveBoundary = { readonly _tag: "init"; readonly cmds: readonly unknown[]; } | { readonly _tag: "step"; readonly cmds: readonly unknown[]; } | { readonly _tag: "stop"; }; /** * What `Store.migrate` answers: the parsed `S`, `null` when nothing was saved, * or a {@link Refusal} for saved bytes it cannot read. */ type Migrated = S | null | Refusal; /** * `migrate`'s answer for saved bytes it cannot read. Build one with * {@link refuse}. A class, so no plain State object can pass for one. */ declare class Refusal { readonly reason: string; readonly _tag: "refusal"; constructor(reason: string); } /** * Refuse saved bytes from `Store.migrate`. `run` then fails with a * {@link StoreRefusedError} carrying `reason`, and writes nothing to the store. * * ```ts * migrate: (raw) => { * if (raw === null) return null; // nothing saved: boot fresh * return isState(raw) ? raw : refuse("not a saved State"); * } * ``` */ declare function refuse(reason: string): Refusal; /** * `ready` rejects with this when the saved state could not be restored: * `migrate` returned {@link refuse}, or `load` / `migrate` threw (that throw is * the `cause`). The run never booted and wrote nothing, so the stored bytes are * unchanged. * * A host that wants a "couldn't restore" view catches it and starts its own run * with no store; tea has no placeholder mode. */ declare class StoreRefusedError extends Error { readonly reason: string; readonly name = "StoreRefusedError"; readonly _tag: "store_refused"; constructor(reason: string, options?: { readonly cause?: unknown; }); } /** * What a fenced store's `loadFenced` returns: the raw saved value and the * version it was written at. */ interface FencedRead { /** Raw bytes at the key, the `Store.load` contract unchanged. */ readonly raw: unknown; /** The version those bytes were written at. A never-written key reads `0`. */ readonly version: number; } /** * A `Store` that can refuse a second live writer. * * `run` fences automatically when it is handed one of these: it reads the * version at boot and compare-and-swaps on every save, so a second process that * started from the same version is refused at its first write with a * {@link StoreConflictError}. Hand `run` a plain `Store` and it stays exactly * as it was — the last writer wins, and single-writer is your precondition to * keep (see `docs/explanation/durability-model.md`). * * Fencing is opt-in at 0.x: every shipped factory that can fence takes an * explicit `{ fenced: true }` and returns this type; the unfenced call is * byte-for-byte the old behaviour. */ interface FencedStore extends Store { /** Discriminant — the one thing {@link isFencedStore} reads. */ readonly fenced: true; /** `load`, plus the version those bytes carry. */ loadFenced(): Promise; /** * Compare-and-swap save. Writes `state` only if the stored version is still * `expectedVersion`, and resolves with the NEW version to swap on next time. * Throws {@link StoreConflictError} when it is not. `msg` is the same * optional applied Msg {@link Store.save} receives; absent at boot and at the * final flush. */ saveFenced(state: S, expectedVersion: number, msg?: unknown): Promise; } /** A committed timer decision. */ interface LoggedTimer { readonly id: string; readonly subId: string; readonly at: number; readonly msg: M; readonly fired: boolean; } /** A canonical admitted message, saved before reduction. */ interface LogMessage { readonly _tag: "message"; readonly id: string; readonly at: number; readonly msg: M; /** This admitted answer also confirms the named delivery, in the same write. */ readonly answerTo?: DeliveryId; } /** The durable result of consuming a message. */ type LogDisposition = "applied" | "ignored" | "rejected"; /** A reducer refusal retained with its source receipt. */ interface LogFailure { readonly kind: "no_cell" | "reduce"; readonly message: string; } /** The atomic records retained by a durable log. */ type LogRecord = { readonly _tag: "birth"; readonly at: number; readonly state: S; readonly owed: readonly EffectOwed[]; readonly timers: readonly LoggedTimer[]; } | LogMessage | { readonly _tag: "applied"; readonly sourceId: string; readonly state: S; readonly owed: readonly EffectOwed[]; readonly timers: readonly LoggedTimer[]; } | { readonly _tag: "receipt"; readonly sourceId: string; readonly disposition: "ignored" | "rejected"; readonly failure?: LogFailure; } | { readonly _tag: "confirmed"; readonly event: EffectConfirmed; }; /** A protocol record with its namespace-local sequence. */ interface PersistedLogRecord { readonly seq: number; readonly record: R; } /** A coherent validated log and its derived checkpoint. */ interface LogRead { readonly version: number; readonly records: readonly PersistedLogRecord>[]; readonly snapshot: { readonly through: number; readonly state: S; } | null; readonly timers: readonly LoggedTimer[]; } /** The canonical admission and whether it was newly appended. */ interface LogAppend { readonly version: number; readonly appended: boolean; readonly entry: PersistedLogRecord>; } /** An atomic birth or source transition request. */ type LogStep = { readonly _tag: "birth"; readonly at: number; readonly state: S; readonly cmds: readonly C[]; readonly timers: readonly LoggedTimer[]; } | { readonly _tag: "applied"; readonly sourceId: string; readonly state: S; readonly cmds: readonly C[]; readonly timers: readonly LoggedTimer[]; } | Extract, { _tag: "receipt"; }>; /** The decoded State and deliveries returned by a committed transition. */ interface LogCommit { readonly version: number; /** The current decoded State, unchanged by a receipt. */ readonly state: S; readonly owed: readonly OwedEffect[]; } /** The result of acknowledging an owed delivery. */ interface LogConfirmation { readonly version: number; readonly confirmed: boolean; } /** An optional store capability for engine-owned durable execution. */ interface LoggedStore extends Store { readonly logged: true; readLog(): Promise>; appendMessage(message: LogMessage): Promise>; commitStep(step: LogStep): Promise>; confirmEffect(id: DeliveryId): Promise; checkpoint(): Promise; } /** Recognize the optional durable log capability. */ declare function isLoggedStore(store: Store): store is LoggedStore; /** Schemas and namespace for a durable log store. */ interface EventSourcedOptions { readonly state: Schema; readonly message: Schema; readonly command: Schema; readonly key?: string; readonly snapshotEvery?: number; } /** * A `Store` that can remove what it saved — how a host forgets a run. * * The same optional widening as {@link FencedStore} (ADR 0017): `Store` is * unchanged, so every external implementor still compiles. `fileStore`, * `memoryStore` and `doStore` return one, fenced and unfenced alike. * * After `delete()`, `load()` returns what a never-saved store returns, so the * next `run` boots fresh. The store stays dumb about who deletes: an unfenced * `save` after `delete()` simply writes the state again. A fenced store drops * its version with the state, so a run still live on it is refused with a * {@link StoreConflictError} at its next save. Deleting under a live run is the * host's mistake to avoid. */ interface DeletableStore extends Store { /** Remove the saved state. Idempotent: deleting nothing resolves. */ delete(): Promise; } /** Narrow a `Store` to a {@link FencedStore} — what `run` uses to decide. */ declare function isFencedStore(store: Store): store is FencedStore; /** * A `Store` whose type says it is not fenced. A plain `Store` fits it and * a {@link FencedStore} does not. It is what lets {@link StoreAndOnError} tell the * two apart, because a `FencedStore` is otherwise also a `Store`. */ type UnfencedStore = Store & { readonly fenced?: never; }; /** * The `store` and `onError` options of a run: a fenced store needs an `onError`, * and the mistake does not compile (ADR 0031). * * Losing a fence is routine for a host that moves runs between processes, and * with no `onError` the default sink rethrows the conflict and ends the process, * along with every other run in it. A conflict can reach the sink at any save * with no caller to reject at: `"stop-save"` from `stop()`, `"follow-up"` from a * Msg a Sub or a Cmd sent. So the sink is required at the type, not left to be * remembered. * * It reads a store's declared type. A fenced store first assigned to a variable * typed plain `Store` has given that type up, so it compiles with no * `onError`. Both engines then refuse it at start, before anything is loaded: * the Promise engine's `run` throws, and the Effect engine's dies. A JavaScript * caller is refused the same way. */ type StoreAndOnError = { readonly store?: UnfencedStore; readonly onError?: OnError; } | { readonly store: Store; readonly onError: OnError; }; /** * Thrown when a fenced save finds a version other than the one it expected — * another live writer has this run. * * A throw, not a settled failure Msg (ADR 0017, following ADR 0011): a second * claimant is a contract breach of the single-writer promise, not a state this * run can fold and continue from. There is no correct way for the loser to * carry on, so it stops where it stands. */ declare class StoreConflictError extends Error { readonly expectedVersion: number; readonly actualVersion: number; readonly name = "StoreConflictError"; readonly _tag: "store_conflict"; constructor(expectedVersion: number, actualVersion: number); } /** * The minimal validator shape `schemaMigrate` accepts: an object with * `safeParse`. A zod schema satisfies it. */ interface Schema { safeParse(raw: unknown): { success: true; data: S; } | { success: false; }; } /** * Build a `Store.migrate` from a schema (job 1) and an optional thin `upcast` * (job 2). `upcast` maps a recognized-but-OLD raw shape forward into the shape * the schema validates; it defaults to identity (no version migration yet). * * Never throws. Nothing saved (`null` or `undefined`) returns `null`, the * fresh-boot path. Saved bytes the schema rejects, or that make `upcast` throw, * return a {@link refuse}, so `run` fails instead of booting fresh over them. */ declare function schemaMigrate(schema: Schema, upcast?: (raw: unknown) => unknown): (raw: unknown) => Migrated; /** * How long a `dispatch` waits before it resolves: `quiescent`, the default, * waits for every follow-up Msg to drain, and `once` waits for the single * transition. */ type DispatchSettle = "quiescent" | "once"; /** Dispatch metadata, including a stable caller identity for logged admission. */ interface DispatchOptions { readonly settle?: DispatchSettle; readonly id?: string; /** Answer a logged Cmd with its own builder; cannot be combined with `id`. */ readonly answerTo?: DeliveryId; } /** * The dispatch-only view of a runtime. Use it as the type of a handle one * runtime holds in order to send Msgs to another. */ interface RuntimeRef { /** * Put a Msg in the runtime's inbox and resolve once processed. Runs to * QUIESCENCE by default: settles only after the dispatched Msg AND every * transitive interpret follow-up has drained. Pass `{ settle: "once" }` (or * call `dispatchOnce`) for the single-step case. * * Rejection ordering: the ONE dispatched transition's own failure surfaces * first, here. If it succeeds but the follow-up chain never stabilizes, the * quiescent drain rejects with `QuiescenceTimeoutError`. Follow-up Msg * rejections themselves route to the `onError` sink, never here. */ dispatch(msg: M, opts?: DispatchOptions): Promise; /** * Dispatch `msg` and resolve after exactly ONE transition's effects settle, * WITHOUT draining the follow-up chain — equivalent to * `dispatch(msg, { settle: "once" })`. Prefer plain `dispatch` unless you will * `await runtime.idle()` yourself; the un-awaited follow-up chain is the * footgun the quiescent default removed. */ dispatchOnce(msg: M, opts?: DispatchOptions): Promise; } /** * A running machine's handle: queue a Msg, listen, wait for boot, stop. * `getState` is not here — there is no State until boot runs, so it lives on * the {@link BootedRunHandle} that `ready` resolves to. `E` is the machine's * semantic event union (see `on`); `never` when the run projects none. */ interface RunHandle { /** Put a Msg in the inbox; resolves once the engine has processed it. */ dispatch(msg: M): Promise; /** * A zero-arg change notifier, fired for each applied transition after its * save and before its first Cmd's handler starts. */ subscribe(listener: () => void): () => void; /** * A `(msg, state, cmds)` hook, fired after each applied transition's Cmds, * with the Cmds that transition started. */ observe(observer: (msg: M, state: S, cmds?: readonly Cmd[]) => void): () => void; /** Fires once with the initial State — at once if boot already ran. */ onBoot(handler: (state: S) => void): () => void; /** Subscribe to the semantic event of `_tag` the run's `events` projects. */ on(type: K, handler: (event: Extract) => void): () => void; /** Resolves to the booted handle once boot completes. */ readonly ready: Promise>; /** Stop the run; resolves once the engine has torn it down. */ stop(): Promise; } /** A {@link RunHandle} whose boot has completed, so its State exists. */ interface BootedRunHandle extends RunHandle { /** The current State. Total. */ getState(): S; readonly ready: Promise>; } /** * What an engine's handler tables look like, as a function of the machine's * types. The Promise engine's `interpret` cells return Promises and its * `subscribe` runners return a `Dispose`; the Effect engine's return an `Effect` * and a `Stream`, and a host adapter that takes either engine's `run` cannot * name those types. So the engine names them: a family is an interface whose * `handlers` is written against `this["M"]`, `this["C"]`, `this["U"]` and * `this["Ctx"]`, and {@link HandlersFor} fills those in for one machine. A * `run` says which family it takes by its `"~demlik/tea/handlers"` type, which * is how `useMachine` types the handlers beside the `run` it is handed. * * ```ts * interface PromiseHandlers extends HandlerFamily { * readonly handlers: RunHandlers; * } * ``` */ interface HandlerFamily { readonly M: { _tag: string; }; readonly C: Cmd; readonly U: Sub; readonly Ctx: unknown; /** The `interpret` and `subscribe` options, for the machine `HandlersFor` names. */ readonly handlers: unknown; } /** The handler options of family `F`, for a machine of these types. */ type HandlersFor = (F & { readonly M: M; readonly C: C; readonly U: U; readonly Ctx: Ctx; })["handlers"]; /** The Promise engine's handler tables: what `RunHandlers` says. The default family. */ interface PromiseHandlers extends HandlerFamily { readonly handlers: RunHandlers; } /** * The options every engine's `run` accepts: the `ctx`, the handlers the * machine runs under, an optional `store` with the `onError` a fenced one needs, * and the `events` projector that feeds `on`. An engine may take more; a host * adapter hands only these. `F` is the family of handlers the engine takes, the * Promise engine's unless said otherwise. */ type RunOptions = CtxArg & HandlersFor & StoreAndOnError & { readonly events?: (msg: M, state: S) => readonly E[]; }; /** * An engine's `run`, seen from a host adapter: a machine and its * {@link RunOptions} in, a {@link RunHandle} out. `useMachine` and * `createAgentHost` take one — `run` from `@demlik/tea/promise` fits it as it * is. A `run` that takes another family of handlers says so at * `"~demlik/tea/handlers"`, and a host adapter then types the handlers it is * handed to match; `run` from `@demlik/tea/promise` says nothing and is the * default {@link PromiseHandlers}. The property is a type and is never set. */ type EngineRun = ((machine: Machine, opts: RunOptions) => RunHandle) & { readonly "~demlik/tea/handlers"?: F; }; /** * What the Promise engine's `run` returns, the instant it is called, while boot * is still in flight: its {@link RunHandle}, widened with Ports and * `dispatchOnce`. It exposes exactly the surface total before boot — queue a * dispatch, subscribe, observe, wire a Port, stop. Reading State (`getState`) * and waiting for quiescence (`idle`) need the initial State to exist, so they * live on the {@link Runtime} that `ready` resolves to; "read State before boot" * is a compile error, not a runtime throw. * * `subscribe` is the React-shaped change notifier (zero-arg, paired with * `getState()`). `observe` is the devtools-shaped trace hook — `(msg, state)` * for every applied transition; boot is delivered via `onBoot` instead, so * `observe`'s `msg` is total (never `null`). `on(type, handler)` is the semantic * event channel: only the public, `_tag`-narrowed events a machine projects, * never its private Msg vocabulary. `E` defaults to `never` (no projector → `on` * uncallable). */ interface BootingRuntime extends RuntimeRef, RunHandle { dispatch(msg: M, opts?: DispatchOptions): Promise; dispatchOnce(msg: M, opts?: DispatchOptions): Promise; /** * Register a zero-arg change notifier, fired once for every applied * transition, after its save and before its first Cmd's handler starts, so a * view shows the State while that State's Cmds run. `getState()` inside the * listener reads the new State, not the State before. A failed save fires * nothing. The listener does not mean the Cmds are done: `observe`, `on` and * `done()` hear after them. A `dispatch` issued from the listener is SCHEDULED * onto the serial tail behind the fold that fired it, never folded re-entrantly * and never discarded, so it needs no `setTimeout(fn, 0)` deferral; it folds * ahead of what that fold's Cmds return, and two listeners issuing in order * fold in that order. */ subscribe(listener: () => void): () => void; /** * Register a `(msg, state, cmds)` trace hook, fired for every applied * transition with the fold's committed State and the Cmds it started. A `dispatch` issued from the observer is * SCHEDULED onto the serial tail behind the fold that fired it, never folded * re-entrantly and never discarded, so it needs no `setTimeout(fn, 0)` * deferral; two listeners issuing in order fold in that order. */ observe(observer: (msg: M, state: S, cmds?: readonly Cmd[]) => void): () => void; /** * Subscribe to the INITIAL State — the boot transition. Fires exactly once: * immediately if boot already completed (so a late subscriber never misses * it), otherwise on the boot fanout. Returns a cleanup (a no-op once fired). */ onBoot(handler: (state: S) => void): () => void; /** * Subscribe to a SEMANTIC event of `_tag`. The handler receives exactly the * `E` member whose `_tag` matches `K`, so a consumer never touches another * event's shape and never references the machine's PRIVATE Msg names. Multiple * handlers per type; fanout is synchronous and throw-isolated. Fires only when * the machine's `events` projector (wired on `run`) emits that type. */ on(type: K, handler: (event: Extract) => void): () => void; /** * Subscribe to a typed Port. Multiple listeners per port; fanout is synchronous * and isolated. Ports are for "data leaving the runtime selectively" (see * `definePort`) — distinct from `observe` (every transition) and State. */ subscribePort(port: Port, listener: (value: T) => void): () => void; /** * Emit a value on a Port from OUTSIDE an interpret handler — same synchronous * fanout as `ctx.emit`. The canonical use is `observe`-driven emission (one * runtime publishing a state-derived signal another subscribes to via * `subscribePort`) without spawning a "tell the outside world" Cmd per * transition. */ emitPort(port: Port, value: T): void; /** * Resolves to the booted `Runtime` after boot completes (or rejects with * the boot error). This is the ONLY way to obtain a `Runtime` — and a * `Runtime` is the only handle whose `getState()` is total. Awaiting `ready` is * the single gate between "boot in flight" and "State exists": * * ```ts * const runtime = await run(machine, opts).ready; * runtime.getState(); // total — never throws-before-boot * ``` * * Idempotent — the same settled promise, resolving to the same `Runtime`, comes * back on every read. Expresses canon §2.3 (boot is a named, awaitable moment). */ ready: Promise>; stop(): Promise; } /** * The Promise engine's booted handle — what {@link BootingRuntime}'s `ready` * resolves to once boot completes. It adds the members only meaningful once the * initial State exists — `getState()` (total), `idle()` (quiescence), and the * `result()` / `done()` reads of the terminal State — and narrows `ready` to * resolve to itself. You never construct one directly; you obtain it via * `await bootingRuntime.ready`, which makes "read State before boot" * unrepresentable rather than merely discouraged. */ interface Runtime extends BootingRuntime { /** * The current State. TOTAL — never throws. Obtaining a `Runtime` requires * awaiting `ready`, which only resolves AFTER boot has run `init` and set the * initial State. */ getState(): S; /** Resolves to this same `Runtime` once boot completes. Idempotent. */ ready: Promise>; /** * Resolves once the runtime has reached QUIESCENCE — every dispatched Msg AND * every transitive interpret follow-up has been processed, with no further step * pending on the tail. Since plain `dispatch` already runs to quiescence, this * is mainly for follow-ups left by a `dispatchOnce` single step, or a chain * kicked off by a Sub / boot `init` cmds with no `dispatch` to await. * * Idempotent and re-entrant-safe. Tail rejections are NOT surfaced here (a * failing dispatch surfaces on its OWN promise; follow-up rejections route to * `onError`). The one rejection `idle()` produces is `QuiescenceTimeoutError` * on hitting the iteration cap — so a livelock stays distinguishable from a * genuine quiesce (invariant 6). A poll is still correct when waiting on an * EXTERNAL event the runtime cannot enqueue itself. */ idle(): Promise; /** * The saved terminal State of the run, or `undefined` while in flight — "terminal" * per the `terminal` predicate passed to `run()` (no predicate → never * terminal → always `undefined`). The first-class result read: the run's * product off the State the machine already owns, NOT scraped off the `observe` * firehose by matching an internal Msg name. With a store, returns `undefined` * until the current State's save succeeds, including after a failed save. * Without a store, answers as soon as State is set. Total — never throws, so a * run a failure closed reads `undefined` here; `done()` says why. */ result(): S | undefined; /** * Resolves with the terminal State only once it is saved (per the `terminal` * predicate). If ALREADY saved and terminal, resolves immediately; otherwise * on that terminal commit. Rejects with the save failure if a terminal State * cannot be saved, for both waiting and later callers. When a failure closes * the run short of a terminal State, it rejects for both waiting and later * callers too: with `SubFailedError` for a Sub failure the Sub did not map to * a Msg, and with what was thrown for a reducer throw under the `stop` * strategy. It answers that only after the Msgs already in line have folded, * because one of them can still reach a terminal State, and then the State is * the answer. A `stop()` with no failure leaves it pending. Without a store, * answers as soon as State is set. The awaitable companion to `result()`. With * no predicate this resolves never, and rejects only on those failures. * Idempotent and multi-caller safe. */ done(): Promise; } /** * The `types` option: the slots of a machine's shape that no value in the * object can imply, declared once as phantom values (`{} as Model`). * * `model` and `msg` are always named. `cmd` is named only by a machine whose * Cmds are hand-written records rather than `Cmd.define` constructors listed * under `cmds`; `sub` only by one that declares Subs other than the built-in * `timer` (its union of `Sub`); `ctx` only by one whose `init` * reads a `Ctx` or whose handlers are typed against one. */ type MachineTypes = { readonly model: S; readonly msg: M; readonly cmd?: C; readonly sub?: U; readonly ctx?: Ctx; }; /** * Define a machine: its `init`, its `update` (a reducer or a transitions * table), and optionally its `subs`, `cmds` and `identity`. Every tea program * starts here; the result is plain data you hand to an engine's `run`. */ declare function defineMachine, Ctx = unknown>(m: NoInfer, CmdOf, U, Ctx>, "cmds">> & { readonly types: MachineTypes, U, Ctx>; readonly cmds: readonly D[]; }): Machine, CmdOf, U, Ctx>; declare function defineMachine, U extends Sub = Sub, Ctx = unknown>(m: NoInfer> & { readonly types: MachineTypes; }): Machine; declare function defineMachine(m: Omit, CmdOf, U, Ctx>, "update" | "cmds"> & { readonly cmds: readonly D[]; update: [S] extends [{ _tag: string; }] ? Transitions, CmdOf> : never; }): Machine, CmdOf, U, Ctx>; declare function defineMachine(m: Omit, CmdOf, U, Ctx>, "update" | "cmds"> & { readonly cmds: readonly D[]; update: Reducer, CmdOf>; }): Machine, CmdOf, U, Ctx>; declare function defineMachine(m: Omit, "update"> & { update: [S] extends [{ _tag: string; }] ? Transitions : never; }): Machine; declare function defineMachine(m: Omit, "update"> & { update: Reducer; }): Machine; /** * Type-check a standalone reducer record and return it branded. Use it when you * write `update` apart from `defineMachine`. */ declare function asReducer(reducer: Reducer): Branded>; /** * The `ctx` field of an engine's options: optional when the machine's `Ctx` is * empty, required otherwise. */ type CtxArg = [Record] extends [Ctx] ? { ctx?: Ctx; } : { ctx: Ctx; }; /** * Run a machine's `init` and then its `update` over a list of Msgs, with no * engine, store or effects. Use it in unit tests to assert the final state, the * Cmds emitted, and the Subs that would be running. * * It composes `init(loaded ?? null, ctx)` and then `update(state, msg)` for each * Msg. Restored init may change State and emit Cmds; those Cmds are collected * alongside update Cmds. No handler, Store or Sub runner is called. * Recorded traces instead use `replayTrace` to fold their captured post-init State. * * `subs` is each `machine.subs` entry that is on at the final state, as its * runner would see it: `{ id, _tag, deps }`, the id derived exactly as the * engine derives it, deduplicated by id the way the engine runs them. So a test * asserts "the retry timer is armed in `waiting`" without wiring a runner. */ declare function replay(machine: Machine, opts: { msgs: readonly M[]; ctx: Ctx; loaded?: S | null; }): { state: S; cmds: C[]; subs: (U | BuiltinSub)[]; }; /** * Adapt an `InterpretDetached` handler into an ordinary `interpret` cell. Use * it for a Cmd whose work finishes after the handler returns and reports back * through `dispatch`. */ declare function wrapDetached(handler: InterpretDetached): (cmd: C, ctx: HandlerCtx, dispatch?: (msg: M) => void) => Promise; /** * `applyCell`, with "no handler for this Msg" moved into the return type * instead of a throw. * * `Ok` carries the handler's `[nextState, cmds]` verbatim; `Err` carries the same * `NoCellError` (msg._tag + state name + accepted set) `applyCell` would have * thrown — both read one `lookupCell`, so neither can under-report. Dispatch * inside `run` keeps using the throwing `applyCell` — this is for callers that * step a machine themselves. */ declare function tryApplyCell(machine: { update: object; __form?: UpdateForm; }, state: S, msg: M): Outcome; /** * The refusal `tryFoldMsgs` reports: WHICH msg in the log had no handler, where. * * A plain record, not a new `Error` subclass — it is an `Outcome` payload, never * thrown, and the actual error is the existing `NoCellError` it carries. The * package's thrown-error idiom (`class extends Error` + `_tag`, pinned by * `error-idiom.test.ts`) applies to errors raised at the runtime edge; this one * is never raised, so adding a class would state a promise it does not make. */ interface FoldRefusal { /** Index into the `msgs` array the fold was given. */ readonly index: number; /** The offending Msg itself — so the caller can print it, not just point. */ readonly msg: M; /** The underlying cell-lookup failure: msg._tag + state name + accepted set. */ readonly error: NoCellError; } /** * `foldMsgs`, with the "no handler for this Msg" case in the return type, * INCLUDING which message failed. * * The motivating use is "this persisted log does not replay — tell the user * where". A bare `Outcome` cannot: the error names the msg._tag * and the state, but a log usually contains that type many times, so the * INDEX is the load-bearing fact. The fold stops at the first refusal (state * past that point is not defined) and returns it. * * Shares `foldMsgs`' dev-mode discipline: `deepFreeze` the input state, * `assertPureResult` the handler's return. Both compile out of production. */ declare function tryFoldMsgs(machine: { update: object; __form?: UpdateForm; }, base: S, msgs: readonly M[]): Outcome>; /** * Wrap a function that may throw into a Cmd handler that never rejects: success * maps to one Msg through `onOk`, failure to another through `onErr`. Use it * for a hand-written Cmd; a `Cmd.define`d Cmd does not need it, because its * handler returns an `Outcome` and the engine mints the Msg (ADR 0021). * * A rejection and a synchronous throw both reach `onErr(error, cmd)`, with the * original error untouched so `instanceof` checks inside `onErr` hold. The * never-rejects promise assumes `onOk` and `onErr` do not throw. */ declare function tryInterpret(work: (cmd: C, ctx: Ctx) => Promise, onOk: (value: Ok, cmd: C) => M, onErr: (error: unknown, cmd: C) => M): (cmd: C, ctx: Ctx) => Promise; export { type LogRecord as $, DisposeTimeoutNotice as A, type BootingRuntime as B, type CtxArg as C, type DeletableStore as D, type EngineRun as E, type FencedStore as F, DrainTimeoutNotice as G, type HandlerFamily as H, DriveFailedError as I, DriveStalledError as J, type FencedRead as K, type LoggedStore as L, type Migrated as M, type FoldRefusal as N, type OnError as O, type PromiseHandlers as P, IdentityDropNotice as Q, type Runtime as R, type Store as S, type TelemetrySink as T, type UnfencedStore as U, type LogAppend as V, type LogCommit as W, type LogConfirmation as X, type LogDisposition as Y, type LogFailure as Z, type LogMessage as _, type StoreAndOnError as a, type LogStep as a0, type LoggedTimer as a1, type PersistedLogRecord as a2, PortNameCollisionError as a3, QuiescenceTimeoutError as a4, RuntimeDiscardNotice as a5, RuntimeDiscardedError as a6, type RuntimeErrorContext as a7, type RuntimeErrorPhase as a8, type RuntimeRef as a9, type SaveBoundary as aa, type Schema as ab, StoreConflictError as ac, StoreRefusedError as ad, SubFailedError as ae, type SupervisionStrategy as af, type TelemetryEvent as ag, __resetPortRegistry as ah, absurd as ai, asReducer as aj, defineMachine as ak, definePort as al, isFencedStore as am, isLoggedStore as an, noop as ao, refuse as ap, replay as aq, schemaMigrate as ar, tryApplyCell as as, tryFoldMsgs as at, tryInterpret as au, wrapDetached as av, type Supervision as b, type HandlersFor as c, type DispatchOptions as d, type MachineTypes as e, type RunOptions as f, type RunHandle as g, type EventSourcedOptions as h, Refusal as i, type EffectLedgerEvent as j, type EffectConfirmed as k, type EffectOwed as l, emptyLedger as m, type BootedRunHandle as n, type PendingEffectsRecorder as o, type OwedEffect as p, type PendingEffectsLedger as q, applyEffectEvent as r, foldLedger as s, isOwed as t, pendingEffectsLedger as u, survivingEffects as v, type LogRead as w, type Branded as x, DispatchDiscardedError as y, type DispatchSettle as z };