import { w as LogRead, o as PendingEffectsRecorder, B as BootingRuntime, R as Runtime } from './runtime-types-f231H8Gq.js'; export { n as BootedRunHandle, x as Branded, C as CtxArg, D as DeletableStore, y as DispatchDiscardedError, d as DispatchOptions, z as DispatchSettle, A as DisposeTimeoutNotice, G as DrainTimeoutNotice, I as DriveFailedError, J as DriveStalledError, k as EffectConfirmed, j as EffectLedgerEvent, l as EffectOwed, E as EngineRun, h as EventSourcedOptions, K as FencedRead, F as FencedStore, N as FoldRefusal, H as HandlerFamily, c as HandlersFor, Q as IdentityDropNotice, V as LogAppend, W as LogCommit, X as LogConfirmation, Y as LogDisposition, Z as LogFailure, _ as LogMessage, $ as LogRecord, a0 as LogStep, L as LoggedStore, a1 as LoggedTimer, e as MachineTypes, M as Migrated, O as OnError, p as OwedEffect, q as PendingEffectsLedger, a2 as PersistedLogRecord, a3 as PortNameCollisionError, P as PromiseHandlers, a4 as QuiescenceTimeoutError, i as Refusal, g as RunHandle, f as RunOptions, a5 as RuntimeDiscardNotice, a6 as RuntimeDiscardedError, a7 as RuntimeErrorContext, a8 as RuntimeErrorPhase, a9 as RuntimeRef, aa as SaveBoundary, ab as Schema, S as Store, a as StoreAndOnError, ac as StoreConflictError, ad as StoreRefusedError, ae as SubFailedError, b as Supervision, af as SupervisionStrategy, ag as TelemetryEvent, T as TelemetrySink, U as UnfencedStore, ah as __resetPortRegistry, ai as absurd, r as applyEffectEvent, aj as asReducer, ak as defineMachine, al as definePort, m as emptyLedger, s as foldLedger, am as isFencedStore, an as isLoggedStore, t as isOwed, ao as noop, u as pendingEffectsLedger, ap as refuse, aq as replay, ar as schemaMigrate, v as survivingEffects, as as tryApplyCell, at as tryFoldMsgs, au as tryInterpret, av as wrapDetached } from './runtime-types-f231H8Gq.js'; export { A as AppliedEffects, a as AppliedEffectsEvent, b as AppliedEffectsGuard, E as EffectApplied, c as EffectForgotten, d as EffectKey, I as IdempotentEffect, e as IdempotentOutcome, f as appliedEffects, g as applyAppliedEvent, h as emptyApplied, i as foldApplied, j as idempotentEffect, k as isApplied } from './idempotent-effect-BhlYUVBf.js'; import { b as Cmd, c as Sub, M as Machine, P as Port, h as DepKeyedSub, D as Dispose } from './core-sEWVgnpI.js'; export { A as AnyCmdDef, y as AsyncSchemaError, B as BuiltinSub, t as BuiltinSubType, a as CmdDef, u as CmdInput, z as CmdNameCollisionError, C as CmdOf, o as CmdValue, s as DeclaredErrorsOf, i as DeliveryId, x as ErrOf, E as ErrorsOf, F as ExhaustiveTransitions, G as Identity, I as Interpret, J as InterpretArg, K as InterpretCell, m as InterpretDetached, L as MachineShape, p as MalformedResult, N as NoCellError, Q as NoCtx, w as OkOf, q as OkOfCmd, O as Outcome, V as OutcomeContractError, X as OutcomeHelpers, r as Owed, Y as PortEmitter, j as Reducer, R as RunHandlers, k as Settled, e as SettledErr, d as SettledOk, g as SubId, S as Subscribe, Z as SubscribeArg, _ as SyncReturn, v as Tagged, f as TaggedError, T as TimerDeps, n as TimerSub, l as Transitions, $ as UndeclaredFailureError, U as UpdateForm, W as Wired, a0 as acceptedTypes, a1 as acceptsOf, a2 as applyCell, a3 as applyCellChecked, a4 as deliveryIdOf, a5 as describeMachine, a6 as detectUpdateForm, a7 as foldMsgs, a8 as foldUpdates, a9 as formOf, aa as matchesIdentity, ab as msgKeysOf, ac as owed, ad as structuralHash, ae as subId, af as subIdOf } from './core-sEWVgnpI.js'; import { S as SubscribeHandler } from './types-CtM4tWPp.js'; import '@standard-schema/spec'; /** * @packageDocumentation * The composition seam — the layer between a battery and a subpath. * * A battery is pure state plus verbs over that state. A subpath holds several * batteries side by side in one Model. Everything between those two facts was, * until now, hand-written at every consumer: the one-key record rebuild that * threads a verb's `[slice, cmds]` result back into the host state, and the * statement order that decides which slice wins a derived read. * * Two helpers cover it, and neither is an optics kit. {@link liftSlice} is the * record rebuild with the key checked by the type system; {@link readInOrder} * turns a read's precedence from statement order into a value you can name, * export and assert on. ADR 0001 (no off-the-shelf resilience) and ADR 0014 * (Effect's types, never its runtime values) between them settle why this is * forty lines here rather than a dependency. * * `docs/how-to/compose-two-battery-slices.md` wires both end to end over a * two-battery subpath, and its `ts` blocks are compiled and run as * `src/docs/how-to/compose-slices.test.ts`. * * Both are pure: no clock, no RNG, no storage, nothing captured. A `liftSlice` * result is a fresh record and a Cmd array, so ADR 0014's journal/hash promise * over a reducer's return value is untouched. */ /** * Lift a battery verb's result into the host state that carries its slice. * * `liftSlice("resilience", state, knob.attempt(state.resilience, …))` is the * `{ ...state, resilience: slice }` every consumer writes by hand, with the key * checked: `key` must be a key of `S`, and the slice the verb returned must be * assignable to the type that key carries — so naming the wrong field, or * threading one battery's slice into another's key, is a compile error rather * than a state shape nothing reads correctly. * * PURE — a fresh record and the verb's own Cmds, unchanged. */ declare function liftSlice(key: K, state: S, [slice, cmds]: readonly [S[K], readonly C[]]): readonly [S, readonly C[]]; /** * One step of a composed read: the slice it consults, under the name that slice * goes by. `read` returns `undefined` for "this slice has nothing to say", * which is what hands the read on to the next step. */ interface ReadStep { /** The slice this step consults — `"cache"`, `"failed"`, `"inFlight"`. */ readonly name: string; /** What this slice says about `input`, or `undefined` to defer. */ readonly read: (input: In) => Out | undefined; } /** * Run a composed read through `order` and return the first answer any step * gives, or `absent` when every one defers. * * The point is that `order` is a VALUE. A derived read over three battery * slices otherwise states its precedence as the order of three `if` statements, * where it is invisible to the type system, unnameable in a test and one * innocent-looking reshuffle away from being wrong — which is exactly the * defect that escaped `classify-batch`'s per-battery test suites. Written as * data, the precedence can be exported, printed and asserted on directly. * * PURE — it evaluates `read` in order and stores nothing. */ declare function readInOrder(input: In, order: readonly ReadStep[], absent: Out): Out; /** Restore the single delivery ledger, including its consumed high-water mark. */ declare function logLedger(log: LogRead): PendingEffectsRecorder; /** Query applied sources in commit order with inclusive, gap-free query positions. */ declare function logUpdates(log: LogRead, range?: { readonly fromSeq?: number; readonly toSeq?: number; }): readonly { readonly seq: number; readonly event: M; readonly state: S; }[]; /** * A bounded log of a runtime's recent `(msg, state)` transitions, returned by * `historyTracker`. Use it to feed a debug inspector. */ interface HistoryTracker { /** * Snapshot of recorded transitions, oldest first. Each entry is * `{ msg, state }`: `msg` is `null` for the boot transition (recorded via * `onBoot`) and the applied Msg for every other (recorded via `observe`). * * Returns a shallow copy: the array is fresh on every call (callers may * iterate, slice, or replay without affecting the tracker's buffer). * Entry values are references to the originals (TEA states/msgs are * conventionally immutable; do not mutate them if your S/M is not). */ snapshot(): readonly { readonly msg: M | null; readonly state: S; }[]; /** * Detach the underlying observer. After `stop()`: * - No new transitions are recorded. * - `snapshot()` continues to work and returns the buffer's contents * at the moment of stop (useful for post-hoc inspection in tests). * - The tracker holds no references that would prevent GC of the * `runtime` argument other than the entries already buffered. * * Idempotent — subsequent calls are no-ops. */ stop(): void; } /** * Create a bounded history tracker over a Runtime. The tracker subscribes to * the runtime via `observe(...)` and retains the last `size` `(msg, state)` * transitions in a FIFO ring buffer. * * @param runtime Any `BootingRuntime` (a full `Runtime` satisfies it). * The tracker uses only `observe`, which is total before boot — * attach it to the synchronous `run()` handle to record the * boot transition. * @param size Buffer cap. `size <= 0` produces an inert no-op tracker: * no observer is attached to the runtime, `snapshot()` is * always `[]`, and `stop()` is a no-op. */ declare function historyTracker(runtime: BootingRuntime, size: number): HistoryTracker; /** * internal/prediction — the client-prediction ack primitive (epic #186, facet 2). * Internal since #49 — not published on any subpath of its own; the * client-safe barrel `src/pure/` re-exports the public surface, and the root * `@demlik/tea` entry publishes it. * * The contract the Gambetta/Valve authoritative-server netcode loop needs: * **command-seq-in → last-applied-seq-out.** A client tags each predicted * command/`Msg` with a monotonic `seq`; the authoritative side replies with the * `lastAppliedSeq` it has processed. `partitionByAck` then splits the client's * pending buffer into the inputs the server has ACKED (`seq <= lastAppliedSeq`) * and those still PENDING (`seq > lastAppliedSeq`) — the un-acked tail the * reconciliation pass (#214) replays over the authoritative snapshot via * `foldMsgs` (#211, the client-safe barrel `src/pure/`). * * Deliberately **Model-shape-agnostic** (ADR 0006): the ack is a standalone * value, NOT a field this module requires on the consumer's `State`. It * generalizes the `lastAckedSeq`-on-the-Model + `seq`-threaded-through-the-Msg * pattern vortex hand-rolled (epic #186). It is a LEAF module — pure and * runtime-free, importing nothing from the tea core or host, so it can never * drag `run`/the host into a client bundle. * * This is the read/ack side of the primitive; `tagSeq`/`nextSeq` are the write * side, letting a client mint monotonic seqs from its pending buffer alone — * again with no counter field on the Model. * * `reconcile` (the read side's payoff, #214) composes this ack partition with * the pure fold seam `foldMsgs` to perform the whole Gambetta/Valve * reconciliation step in one call. The `foldMsgs` import is the ONLY dependency * this leaf takes, and it reaches into the pure-core leaf (`../pure/core`) — NOT * the runtime root — so the module stays runtime-free and the client-safe * import-graph guard (ADR 0006, #213) still holds. */ /** * A monotonic, non-negative sequence number tagging one client-predicted * command. Monotonicity is the client's contract (mint successive seqs with * `nextSeq`); this module only ever *compares* seqs. */ type Seq = number; /** A command (or `Msg`) tagged with the `seq` the client assigned it. */ interface SeqTagged { readonly seq: Seq; readonly value: T; } /** Tag a command/`Msg` with its sequence number. */ declare const tagSeq: (seq: Seq, value: T) => SeqTagged; /** * The authoritative side's acknowledgement: the highest `seq` it has applied. * Everything with `seq <= lastAppliedSeq` is settled; everything above is still * in flight. This *is* the whole "ack from the authoritative side" — a value * the consumer carries however it likes (a wire field, a message payload), * never a shape this module imposes on the Model. */ interface Ack { readonly lastAppliedSeq: Seq; } /** Construct an `Ack` for a last-applied sequence number. */ declare const ack: (lastAppliedSeq: Seq) => Ack; /** * The "nothing applied yet" cursor — the ack value for a server that has applied * no client input at all. Because `nextSeq` mints **0-based** seqs and * `partitionByAck` acks **inclusively** (`seq <= lastAppliedSeq`), the pre-first * cursor must sit strictly *below* seq 0: `lastAppliedSeq = 0` would falsely ack * the seq-0 input before the server ever saw it. `-1` is "before any seq", and * `partitionByAck(buffer, NO_ACK)` therefore leaves the whole buffer PENDING. * * This names the boundary value on the seam so no consumer has to re-discover it * as a magic number: it is the primitive's own design (0-based mint + inclusive * partition) that creates the trap, so it is the primitive's job to name the * escape. Pair with {@link initAck} when an {@link Ack} is wanted instead of the * bare `Seq`. */ declare const NO_ACK: Seq; /** * The `Ack` for a server that has applied nothing yet — `ack(NO_ACK)`. The `Ack` * counterpart to the {@link NO_ACK} `Seq` sentinel, for a consumer that carries * an `Ack` rather than a bare `lastAppliedSeq`. */ declare const initAck: () => Ack; /** The result of splitting a seq-tagged buffer against an ack. */ interface AckPartition { /** Inputs the authoritative side has applied (`seq <= lastAppliedSeq`). */ readonly acked: readonly SeqTagged[]; /** Inputs still in flight / un-acked (`seq > lastAppliedSeq`) — the replay tail. */ readonly pending: readonly SeqTagged[]; } /** * Partition a buffer of seq-tagged commands into ACKED and PENDING against the * authoritative `lastAppliedSeq`. Pure and total: every item lands in exactly * one bucket, input order is preserved within each bucket, and the boundary * `seq == lastAppliedSeq` is ACKED (inclusive `<=`). Routing is by `seq` value, * not buffer position, so an out-of-order or duplicate-seq buffer partitions * correctly. Accepts either an {@link Ack} or a bare `lastAppliedSeq` number, so * a caller passes whichever it holds. */ declare const partitionByAck: (buffer: readonly SeqTagged[], ackOrSeq: Ack | Seq) => AckPartition; /** * The next sequence number to assign: one past the highest `seq` in the buffer, * or `0` for an empty buffer. Lets a client mint monotonic seqs from its pending * buffer alone — no counter field on the Model — and is tolerant of an unordered * buffer (it takes the max, not the last element). */ declare const nextSeq: (buffer: readonly SeqTagged[]) => Seq; /** * The client prediction/reconciliation helper — the Gambetta/Valve * authoritative-server loop's reconcile step, generalized. * * Given the latest `authoritativeState` from the server, the server's * `lastAppliedSeq` ack, and the client's `pending` buffer of seq-tagged inputs, * it returns the corrected predicted state: drop the inputs the server has * already applied (`seq <= lastAppliedSeq`) and replay ONLY the un-acked tail * (`seq > lastAppliedSeq`) over the authoritative snapshot. * * It is **composed, not re-derived** (ADR 0006): the drop is {@link partitionByAck} * (the ack primitive, #212) and the replay is `foldMsgs` (the pure fold seam, * #211) — there is no second copy of the partition logic and no second copy of * the fold. `lastAppliedSeq` accepts either an {@link Ack} or a bare `Seq`, so a * caller passes whichever it holds, matching `partitionByAck`. * * Pure and host-agnostic: it takes the `machine` (which `foldMsgs` needs to * dispatch `update`) but touches no `Store`, `interpret`, or subscription, and * imports nothing from the runtime — so it ships through the client-safe * umbrella without dragging `run` into a client bundle. */ declare function reconcile(machine: Machine, authoritativeState: S, lastAppliedSeq: Ack | Seq, pending: readonly SeqTagged[]): S; /** * The imperative listener target, expressed as the `add`/`remove` pair the * substrate pairs into a reconciled resource. Both halves receive the SAME * `listener` reference — the substrate builds it once — so `remove` can never * be handed a different function than `add` saw. * * `add`/`remove` also receive `(sub, ctx)` so the target may be resolved from * `ctx` (a runtime, a port, a DOM node looked up lazily) or keyed on the Sub * (an alarm name, a channel name). Resolving the target inside `add` and * closing over nothing but the listener keeps a target swap from leaking the * old target's listener — same rationale as `fromEventTarget`'s captured * target. * * `Args` is the tuple the platform invokes the listener with — `[Alarm]` for * `chrome.alarms.onAlarm`, `[message, sender, sendResponse]` for * `chrome.runtime.onMessage`, `[changes, areaName]` for * `chrome.storage.onChanged`. The substrate builds ONE function of this exact * shape and threads the IDENTICAL reference to both `add` and `remove` — so a * platform that matches `removeListener` by reference (every chrome surface) * removes exactly what it added. A consumer that wrapped the listener inside * `add` would break reference identity (leak #2 above); carrying the native * `Args` on the listener itself removes the need for any wrapper. */ interface ListenerTarget { add: (listener: (...args: Args) => void, sub: S, ctx: Ctx) => void; remove: (listener: (...args: Args) => void, sub: S, ctx: Ctx) => void; } /** * Build a listener-backed Sub factory whose cleanup is mandatory and derived. * * `Args`, `S`, `Ctx` are fixed when the target is defined — they describe the * one listener topology this factory owns (the platform arg tuple, which Sub * shape it filters on, what context resolves it). `M` is supplied at the * runner because the same listener feeds different Msgs in different * machines. Pinning `S` here (rather than at the `msgFn` step) lets * `add`/`remove` read the concrete Sub's deps — `sub.deps.alarmName`, * `sub.deps.channel` — with NO cast at the substrate edge: the narrowing * happens in author-land where the Sub shape is in scope. * * The returned function is a `SubscribeHandler` factory in the exact shape of * every other Sub factory in `src/subs/`: supply the `msgFn` projection, get a * `(sub, ctx, dispatch) => cleanup` runner for the `subscribe` table `run` * takes. * The cleanup the author NEVER writes is `() => remove(listener, sub, ctx)`, * with `listener` the identical reference passed to `add`. */ declare function defineListener(target: ListenerTarget): (msgFn: (sub: S, ...args: Args) => M | null) => SubscribeHandler; interface MinimalEvent { readonly type: string; } interface MinimalMessageEvent extends MinimalEvent { readonly data: unknown; } interface MinimalEventTarget { addEventListener(type: string, listener: (event: MinimalEvent) => void): void; removeEventListener(type: string, listener: (event: MinimalEvent) => void): void; } interface MinimalCloseEvent extends MinimalEvent { readonly code: number; readonly reason: string; } interface MinimalWebSocket { close(code?: number, reason?: string): void; onopen: ((event: MinimalEvent) => void) | null; onmessage: ((event: MinimalMessageEvent) => void) | null; onerror: ((event: MinimalEvent) => void) | null; onclose: ((event: MinimalCloseEvent) => void) | null; } type BroadcastSubData = { readonly channelName: string; }; /** * Build a Sub runner that listens on the `BroadcastChannel` named by * `sub.deps.channelName` and dispatches `msgFn(event, sub)` for each message. * Returning `null` from `msgFn` drops the event. */ declare function fromBroadcastChannel, M>(msgFn: (event: MinimalMessageEvent, sub: S) => M | null): SubscribeHandler; type EventSourceSubData = { readonly url: string; }; /** * Options for `fromEventSource`: map each server-sent message, error and open * event to a Msg, or to `null` to drop it. */ interface EventSourceFactoryOpts { onMessage: (data: string, sub: S) => M | null; onError?: (event: MinimalEvent, sub: S) => M | null; onOpen?: (sub: S) => M | null; } /** * Build a Sub runner that opens an `EventSource` on `sub.deps.url` and * dispatches a Msg for each server-sent event. */ declare function fromEventSource, M>(opts: EventSourceFactoryOpts): SubscribeHandler; /** * Build a Sub runner that listens for `eventName` on a DOM-style event target * and dispatches `msgFn(event, sub)` for each event. */ declare function fromEventTarget(getTarget: () => MinimalEventTarget, eventName: string, msgFn: (event: MinimalEvent, sub: S) => M | null): SubscribeHandler; type IntervalSubData = { readonly intervalMs: number; }; /** * Build a Sub runner that dispatches `msgFn(sub)` every `sub.deps.intervalMs` * milliseconds while the Sub is on. */ declare function fromInterval, M>(msgFn: (sub: S) => M): SubscribeHandler; /** * Build a Sub runner that listens to a `Port` on another runtime and dispatches * `msgFn(value, sub)` for each value emitted. Use it to let one machine react * to another's announcements. */ declare function fromPort(selectRuntime: (ctx: Ctx) => Runtime, port: Port, msgFn: (value: T, sub: S) => M | null): SubscribeHandler; /** The `deps` a WebSocket Sub carries: the `wsUrl` to connect to. */ type WebSocketSubData = { readonly wsUrl: string; }; /** * Options for `fromWebSocket`: map each message, open, error and close event to * a Msg, or to `null` to drop it. */ interface WebSocketFactoryOpts { onMessage: (data: unknown, sub: S) => M | null; onOpen?: (sub: S) => M | null; onError?: (event: MinimalEvent, sub: S) => M | null; onClose?: (code: number, reason: string, sub: S) => M | null; } /** * Build a Sub runner that opens a WebSocket to `sub.deps.wsUrl` and dispatches * a Msg for each socket event. It does not reconnect; use * `fromReconnectingWebSocket` for that. */ declare function fromWebSocket, M>(opts: WebSocketFactoryOpts): SubscribeHandler; /** Cancels a scheduled reconnect timer (the inverse of `schedule`). */ type CancelTimer = () => void; /** * Options for `fromReconnectingWebSocket`: the event-to-Msg mappers, the * backoff settings, and an injectable `connect` and `schedule` for tests. */ interface ReconnectingWebSocketFactoryOpts { onMessage: (data: unknown, sub: S) => M | null; onOpen?: (sub: S) => M | null; onError?: (event: MinimalEvent, sub: S) => M | null; onClose?: (code: number, reason: string, sub: S) => M | null; /** * Fires when a reconnection (any open after the first) succeeds, carrying the * 1-based reconnect count — the resync hook. Omitting drops reconnect events * silently. */ onReconnect?: (attempt: number, sub: S) => M | null; /** First backoff delay in ms (doubles each failed attempt). Default 250. */ backoffBaseMs?: number; /** Backoff ceiling in ms. Default 5000. */ backoffMaxMs?: number; /** Inject the socket constructor (defaults to the global `WebSocket`); the test seam. */ connect?: (url: string) => MinimalWebSocket; /** Inject the timer (defaults to `setTimeout`/`clearTimeout`); the test seam. */ schedule?: (fn: () => void, ms: number) => CancelTimer; } /** * Build a Sub runner that keeps a WebSocket to `sub.deps.wsUrl` open, * reconnecting with backoff when it drops. */ declare function fromReconnectingWebSocket, M>(opts: ReconnectingWebSocketFactoryOpts): SubscribeHandler; type TimeoutSubData = { readonly delayMs: number; }; /** * Build a Sub runner that dispatches `msgFn(sub)` once, `sub.deps.delayMs` * milliseconds after the Sub turns on. Turning the Sub off first cancels it. */ declare function fromTimeout, M>(msgFn: (sub: S) => M): SubscribeHandler; /** * The running Sub of a managed resource named `N`: its `deps` is the lifetime * key. The consumer's Sub union (`types.sub`) includes it directly. */ type ManagedResourceSub = Sub; /** * Options for `defineManagedResource`: the resource's `name`, how to `acquire` * it for a key, and how to `release` the handle. */ interface DefineManagedResourceOpts { /** * A short, stable name — and the resource's Sub `_tag`. The machine's * `subscribe` table holds this battery's runner under it, so it must be * unique among the machine's Sub types. */ readonly name: N; /** * Build the resource. Runs when the resource's `deps` turns non-null. * The returned Handle is the ONLY thing `release` receives — capture * everything teardown needs into it. If `acquire` throws, the engine does * NOT register the Sub and `release` is never called (no dangling * half-built resource). */ readonly acquire: (key: TKey, ctx: Ctx) => Handle; /** * Tear the resource down. Runs when the key goes null (phase exited) or * changes. MANDATORY — the guaranteed teardown is the reason this battery * exists. * * May be sync or async, and an async one is really awaited: the promise is * returned to the substrate, which tracks it and drains it inside `stop()` * (bounded by `run({ disposeTimeoutMs })`). So `await runtime.stop()` means * the release finished — the reading a host evicting an isolate acts on. * MID-RUN teardown (a phase exit, a key change) is still fire-and-forget * (Rule 2): the reconcile pass is synchronous by construction, so it starts * the release and moves on. A rejection is never a Msg — it reaches the * runtime's `onError` sink under `phase: "sub-cleanup"`. */ readonly release: (handle: Handle) => void | Promise; } /** * What the battery returns: a `.depKeyed(when)` entry for the machine's * `subs`, the `.subscribe` runner for the `subscribe` table handed to `run`, * and a `.get(key)` accessor so Cmd handlers can reach the live Handle while * the resource is held. */ interface ManagedResourceBattery { /** The battery's Sub type — its `name`. */ readonly _tag: N; /** * The `subs` entry. `when(state)` returns the resource's KEY when it should * be held, or `null` when it should be torn down. The key is the Sub's * `deps`, so the engine derives the id from it: an unchanged key leaves the * resource alone, a changed key releases the old one and acquires anew. * Plain JSON-compatible data only — the id hash throws on anything else. */ readonly depKeyed: (when: (state: S) => TKey | null) => DepKeyedSub>; /** * The runner for this battery's Sub type — hand it to `run` as * `subscribe: { [battery._tag]: battery.subscribe }`. Runs `acquire` on * start, holds the Handle in the battery's handle table, and returns a * cleanup that runs `release` (and forgets the Handle) on stop. */ readonly subscribe: (sub: ManagedResourceSub, ctx: Ctx, dispatch: (msg: never) => void) => Dispose; /** * Accessor for the live Handle, keyed on `key` (the author's key, never the * derived Sub id). Returns `undefined` when the resource is not currently * held — the caller decides whether that is an error. A Cmd handler wires * its `ctx.getX(key)` through this, so the handler reads the SAME owner the * reconciler holds, never a hand-built duplicate. */ readonly get: (key: TKey) => Handle | undefined; } /** * Build the battery. One call per managed resource at the machine's host * file. * * @example * ```ts * import { * defineMachine, * defineManagedResource, * type Interpret, * type ManagedResourceSub, * type Reducer, * } from "@demlik/tea"; * import { run } from "@demlik/tea/promise"; * * type RunId = string; * type State = { _tag: "idle" } | { _tag: "running"; runId: RunId }; * type Msg = { _tag: "start"; runId: RunId } | { _tag: "stop" }; * type Cmd = { _tag: "start_graph"; runId: RunId }; * interface Ctx { readonly storage: Storage; readonly bucket: string } * declare class CheckpointSaver { * constructor(opts: { storage: Storage; bucket: string; runId: RunId }); * save(step: string): Promise; * clear(): Promise; * } * declare const update: Reducer; * declare const ctx: Ctx; * * const checkpointStore = defineManagedResource<"checkpoint", RunId, CheckpointSaver, Ctx>({ * name: "checkpoint", * acquire: (runId, ctx) => * new CheckpointSaver({ storage: ctx.storage, bucket: ctx.bucket, runId }), * release: (saver) => saver.clear(), * }); * * // In the machine: * const machine = defineMachine({ * types: { * model: {} as State, * msg: {} as Msg, * cmd: {} as Cmd, * sub: {} as ManagedResourceSub<"checkpoint", RunId>, * ctx: {} as Ctx, * }, * init: (loaded) => [loaded ?? { _tag: "idle" }, []], * update, * subs: [ * checkpointStore.depKeyed((s: State) => * s._tag === "running" ? s.runId : null, * ), * ], * }); * * // In interpret (read the live handle the reconciler holds): * const interpret: Interpret = { * start_graph: async (cmd) => { * const saver = checkpointStore.get(cmd.runId); // same owner, no rebuild * await saver?.save("started"); * }, * }; * * // At run: * run(machine, { ctx, interpret, subscribe: { checkpoint: checkpointStore.subscribe } }); * ``` */ declare function defineManagedResource(opts: DefineManagedResourceOpts): ManagedResourceBattery; /** * Duplex transport. The host (DO, worker thread, in-process bus) constructs * one from whatever the platform offers. `fromTransport` does not know what * a WebSocket is — it knows `send`, `onMessage`, `onClose`. */ interface Transport { /** Send a string frame. Best-effort; failures are logged at the boundary. */ send(data: string): void; /** * Subscribe to inbound frames. Returns a cleanup that removes the listener. * The battery wires this in its runner; cleanup runs when the seam's key * goes null or changes. */ onMessage(listener: (data: string) => void): () => void; /** * Subscribe to a one-shot close. Returns a cleanup that removes the * listener. The battery dispatches `lostMsg` on close. */ onClose(listener: () => void): () => void; /** Close the underlying channel cleanly. Called by the Sub cleanup. */ close(): void; } /** * Factory the consumer wires to a platform-specific transport. The battery * passes the seam's key (`runId`, or whatever identity is on the phase) so * per-run transports can be addressed. */ type TransportFactory = (key: K) => Transport; /** * The running Sub of a seam named `N`: its `deps` is the seam key. The * consumer's Sub union (`types.sub`) includes it directly. */ type TransportSub = Sub; /** * Options for `fromTransport`: the seam's `name`, how to open the transport, * and how inbound values, outbound values and a dropped connection map to and * from Msgs. */ interface FromTransportOpts { /** * A short, stable name for this seam — and its Sub `_tag`. The machine's * `subscribe` table holds the seam's runner under it, so it must be unique * among the machine's Sub types. */ readonly name: N; /** * Build the transport. The battery owns the lifetime; the factory is the * platform-specific constructor (`new WebSocket(...)` adapter on a DO, * `MessagePort` adapter in a worker, in-memory stub in tests). */ readonly openTransport: (key: TKey, ctx: Ctx) => Transport; /** * Parse one inbound frame. The battery hands `unknown` through (boundary * parse is the consumer's responsibility per invariant 8). Returning * `null` drops the frame silently — useful for frames the seam doesn't * recognize at this layer (e.g. transport-level keepalive). */ readonly parseInbound: (raw: string, key: TKey) => Inbound | null; /** * Map a parsed inbound to a domain Msg. Returning `null` drops the * dispatch (e.g. a transport-level pong that doesn't change domain state). */ readonly onInbound: (inbound: Inbound, key: TKey) => M | null; /** * The Msg dispatched when the transport closes (peer gone, network * dropped, normal close). ONE Msg arm, not a Sub, not a heartbeat-derived * deadline — the transport's own close signal is the truth. */ readonly lostMsg: (key: TKey) => M; /** * Serialize an outbound. Called by the Cmd handler the battery wires. * Pure data → string at the seam boundary. */ readonly serializeOutbound: (outbound: Outbound) => string; } /** * What the battery returns: a `.depKeyed(when)` entry for the machine's * `subs`, the `.subscribe` runner for the `subscribe` table handed to `run`, * and a `send(key, outbound)` helper the consumer's Cmd handler calls. */ interface TransportBattery { /** The seam's Sub type — its `name`. */ readonly _tag: N; /** * The `subs` entry. `when(state)` returns the seam's KEY when it should be * open, or `null` when it should be torn down. The key is the Sub's `deps`, * so the engine derives the id from it: an unchanged key leaves the seam * open, a changed key closes it and opens a fresh one. Plain * JSON-compatible data only — the id hash throws on anything else. */ readonly depKeyed: (when: (state: S) => TKey | null) => DepKeyedSub>; /** * The runner for this seam's Sub type — hand it to `run` as * `subscribe: { [seam._tag]: seam.subscribe }`. Wires inbound + close in * one shot and publishes the live transport to the outbound handle table. */ readonly subscribe: (sub: TransportSub, ctx: Ctx, dispatch: (msg: M) => void) => Dispose; /** * Outbound send, addressed by the seam's key (never the derived Sub id, * which the caller cannot know). The Cmd handler calls this; the battery's * handle table (built when the runner started) routes to the live * transport. If the seam is closed (no running Sub), the send is dropped * honestly (logged, not thrown — the reducer already moved past caring, * same shape as Rule 2 fire-and-forget Cmds). */ readonly send: (key: TKey, outbound: Outbound) => void; } /** * Build the battery. One call per seam at the machine's host file. * * @example * ```ts * import { * defineMachine, * fromTransport, * type Interpret, * type Reducer, * type Transport, * type TransportSub, * } from "@demlik/tea"; * import { run } from "@demlik/tea/promise"; * * type RunId = string; * type HandsInbound = { kind: "said"; text: string }; * type HandsOutbound = { kind: "do"; action: string }; * type State = { _tag: "idle" } | { _tag: "auditing"; runId: RunId }; * type Msg = * | { _tag: "hands_said"; runId: RunId; inbound: HandsInbound } * | { _tag: "hands_lost"; runId: RunId }; * type Cmd = { _tag: "send_hands"; runId: RunId; outbound: HandsOutbound }; * interface Ctx { readonly openHandsWs: (runId: RunId) => Transport } * declare function parseHandsInbound(json: unknown): HandsInbound | null; * declare const update: Reducer; * declare const ctx: Ctx; * * const handsSeam = fromTransport<"hands", RunId, HandsInbound, HandsOutbound, Msg, Ctx>({ * name: "hands", * openTransport: (runId, ctx) => ctx.openHandsWs(runId), * parseInbound: (raw) => parseHandsInbound(JSON.parse(raw)), * onInbound: (inbound, runId) => ({ _tag: "hands_said", runId, inbound }), * lostMsg: (runId) => ({ _tag: "hands_lost", runId }), * serializeOutbound: (out) => JSON.stringify(out), * }); * * // In the machine: * const machine = defineMachine({ * types: { * model: {} as State, * msg: {} as Msg, * cmd: {} as Cmd, * sub: {} as TransportSub<"hands", RunId>, * ctx: {} as Ctx, * }, * init: (loaded) => [loaded ?? { _tag: "idle" }, []], * update, * subs: [ * handsSeam.depKeyed((s: State) => * s._tag === "auditing" ? s.runId : null, * ), * ], * }); * * // In interpret: * const interpret: Interpret = { * send_hands: async (cmd) => { handsSeam.send(cmd.runId, cmd.outbound); }, * }; * * // At run: * run(machine, { ctx, interpret, subscribe: { hands: handsSeam.subscribe } }); * ``` */ declare function fromTransport(opts: FromTransportOpts): TransportBattery; export { type Ack, type AckPartition, BootingRuntime, type CancelTimer, Cmd, type DefineManagedResourceOpts, DepKeyedSub, Dispose, type EventSourceFactoryOpts, type FromTransportOpts, type HistoryTracker, type ListenerTarget, LogRead, Machine, type ManagedResourceBattery, type ManagedResourceSub, NO_ACK, PendingEffectsRecorder, Port, type ReadStep, type ReconnectingWebSocketFactoryOpts, Runtime, type Seq, type SeqTagged, Sub, SubscribeHandler, type Transport, type TransportBattery, type TransportFactory, type TransportSub, type WebSocketFactoryOpts, type WebSocketSubData, ack, defineListener, defineManagedResource, fromBroadcastChannel, fromEventSource, fromEventTarget, fromInterval, fromPort, fromReconnectingWebSocket, fromTimeout, fromTransport, fromWebSocket, historyTracker, initAck, liftSlice, logLedger, logUpdates, nextSeq, partitionByAck, readInOrder, reconcile, tagSeq };