/** * vapor-chamber - Command Bus for Vue Vapor * * Sizes are not quoted here: a hand-typed number in a source file is reached * by no generator and checked by no gate. `docs/BUNDLE-SIZES.md` is * regenerated every run and is the only place a size should be read from. * DevTools is loaded dynamically. */ import { type Lanes } from './scheduler'; import { _asLibrary, _isLibraryAction } from './library-names'; import { type BusStores } from './applied-remotely'; import { type GroupHub } from './http'; import type { ActionFilter } from './action-filter'; import { BusError, _failures, _isBug, conditionOf, conditionOfStatus, ownerOf, type BusErrorCode, type Condition, type Fail, type FailCode, type FailOptions } from './failure'; export { BusError, _failures, _isBug, conditionOf, conditionOfStatus, ownerOf, type BusErrorCode, type Condition, type Fail, type FailCode, type FailOptions }; /** * Severity level for bus diagnostics. * - `'error'`: dispatch failed, result.ok === false * - `'warn'`: recoverable issue, dispatch may succeed (e.g. naming violation) * - `'info'`: informational (e.g. handler overwrite, circuit breaker state change) */ export type BusSeverity = 'error' | 'warn' | 'info'; /** * Any failure's condition, read by contract (docs/contract.md 4, reading by contract): a library * failure's own code; an HTTP status (another client's `response.status`) through the * status table; a timeout by its name; a cancel, named `AbortError` or the * `signal`'s own reason (`_isCancel`); the Fetch standard's `TypeError` for no * response at all, `lost`. Anything else - a handler's own throw, a test * diagnostic - is `failed` (docs/contract.md rule 8). Pass the command's * `signal` to read an abort with the caller's own Error as `aborted` * (tests/abort-custom-reason.test.ts). */ export declare function failureCondition(error: unknown, signal?: AbortSignal): Condition; /** * The transient conditions: held back (`limited`) or a timeout the other side * declared (`timeout`, a 408). The async bus re-sends them for any action. * No reply (a transport's own `timeout`, a 504) and the uncertain ones * (`lost`, `failed`, `unexpected`, `unknown`: the first attempt may have * landed) it re-sends only for an idempotent action or a keyed command. The * other side's verdict, an abort and a depth bound never (docs/retry.md, * log s35.162). */ export declare const RETRYABLE_CONDITIONS: ReadonlySet; /** Automatic metadata stamped on every command. */ export type CommandMeta = { /** * Wall-clock stamp for correlation and audit - NOT a timing instrument. * * Read from `Date.now()` **once per microtask turn** and shared by every * command dispatched inside that turn. The first command of each turn carries * an exact stamp; the 2nd..nth of the same synchronous run repeat it. Since * `Date.now()` is millisecond-resolution and a typical burst is * sub-millisecond, those commands would almost always have received the same * number anyway - what is actually given up is intra-burst resolution in * bursts long enough to cross a millisecond (a thousand-command burst reads * as instantaneous). Bought ~15-25ns per dispatch; measured in * `tests/clock-source-ab.test.ts` (v1.6.0, 2026-08-24). * * **Ordering does not depend on this field.** `meta.id` is a monotonic * counter and stays unique and ordered - use it, not `ts`, to sequence * commands. * * **Do not measure durations with it, cached or not.** `Date.now()` is wall * clock: millisecond-resolution and *not monotonic*, so an NTP correction or * a clock change can move it, backwards included. That was true before this * cache and is not a consequence of it. For real timing use * `performance.now()` in a plugin; on a hot loop use `createFastLane()`, * which stamps no meta at all. */ ts: number; /** * Unique, monotonically increasing command ID - the ordering key. * * Default generator: a per-process random prefix plus an incrementing * counter (`configureUid` swaps it; `crypto.randomUUID` is the documented * opt-in for cross-process auditing, not the default). */ id: string; /** ID of the command that caused this one (set manually via payload.__causationId). */ causationId?: string; /** Correlation ID for tracing a chain of commands (propagates from parent). */ correlationId?: string; /** * Idempotency key. Transports (e.g. httpTransport) forward it as an * `Idempotency-Key` header, or that name in a batched command's or a * frame's `headers`, so the backend can reject duplicate writes. * Always present, `undefined` until the `idempotent` plugin, the outbox or * the retry (an action declared idempotent) stamps it. Never the command's * content: an app's own key as given, an outbox record's key, else this * dispatch's `id` (tests/idempotency-key.test.ts). */ idempotencyKey?: string; /** * The 2xx response a transport's reply arrived in, Fetch's members (a 202 * says accepted, not finished: RFC 9110 15.3.3). Always present, `undefined` * for a local handler; a non-2xx answer is the error's. */ response?: MetaResponse; /** * Request-level headers a plugin adds to the request a transport sends * (a W3C `traceparent`, a locale), names lowercase. Always present, * `undefined` until a plugin sets it. */ request?: MetaRequest; /** * Where the command originated. `undefined` (the default) means local user * code called dispatch directly. Apart from `'undo'` and `'redo'` (below) the * core never sets this field - dispatchers * that proxy external traffic (bridges, sync layers, replay tooling, agent * endpoints) stamp it post-hoc via plugins so downstream plugins, hooks, and * listeners can distinguish local intent from mirrored or machine-driven * commands (e.g. skip re-broadcasting a `'sync'` command, or audit-log * everything marked `'agent'`). * * Well-known values: `'user'`, `'remote'`, `'sync'`, `'replay'`, `'agent'` - * but any string is accepted for custom origins. The core stamps two of its * own: `'undo'` on every dispatch made synchronously inside * an undo handler and `'redo'` on a redo and what its handler dispatches * (`_withOriginScope`); `history()` and `useCommandHistory` record * neither, nor a `'sync'` command (a change an app's sync layer mirrored from * elsewhere). A shared store dispatches nothing for another tab's command. * * @example * bus.use({ started(cmd) { * if (cmd.meta?.origin === 'agent') console.info('LLM-driven:', cmd.action); * } }); */ origin?: 'user' | 'remote' | 'sync' | 'replay' | 'agent' | 'undo' | 'redo' | (string & {}); }; /** A response's members as Fetch names them; header names lowercase. */ export type MetaResponse = { status: number; headers: Record; url?: string; redirected?: boolean; }; /** What a plugin adds to the request a transport sends. */ export type MetaRequest = { headers: Record; }; export type Command = { readonly action: A; readonly target: T; readonly payload?: P; /** Auto-stamped metadata - timestamp, unique id, correlation/causation tracing. * Always present on commands from dispatch/query/emit. Optional on manually constructed commands. */ readonly meta?: CommandMeta; /** * The signal the work runs under. On the async bus, `bus.dispatch(..., { signal })` * sets it: async handlers may listen to `cmd.signal.aborted` / * `cmd.signal.addEventListener('abort', ...)` to short-circuit work, and * transports (HTTP) forward it to the underlying fetch. A sync dispatch * ignores its own `{ signal }` option: it is atomic. On either bus a step's * ticket (`PluginParts.begin`) may set it, combined with any already there, * so work a handler starts and does not await can be cancelled by the step * that owns the signal (tests/work-steps.test.ts). */ signal?: AbortSignal; }; /** Optional per-dispatch options: `{ signal }` for cancellation. */ export type DispatchOptions = { /** Abort the dispatch before it starts (if already aborted) or signal async * handlers and transports to cancel mid-flight. Async bus only. */ signal?: AbortSignal; }; /** * Result of a dispatch/query - a discriminated union on `ok`. * * `if (result.ok)` narrows away `error`; on the failure arm `error` is a * guaranteed `Error` (no `!` or `?.` needed). `value` stays optional on the * success arm because void commands legitimately produce no value. */ export type CommandResult = { ok: true; value?: V; error?: undefined; } | { ok: false; error: Error; value?: undefined; }; export type Handler = (cmd: Command) => R; /** An async bus's handler: a value or a promise of it. A value answers sooner (tests/async-handler-types.test.ts). */ export type AsyncHandler = (cmd: Command) => R | Promise; /** * What a plugin declares besides its function: `dispose` (the bus's dispose() * runs it), `id` (the owner of its failures), `actions` (the only actions the * bus runs it on, an {@link ActionScope}; log s35.141). * `actionFilter`: a predicate on the action name (src/action-filter.ts), ANDed * with `actions` when both are given, asked once per action (log s35.152). * `forget(cmd)`: the bus calls it on every installed plugin once an undo of * `cmd` lands, so a plugin drops what it keeps for that command (cache and * idempotent drop its stored answer) and a redo runs (log s35.181). * `attach(bus)`: called once when `use()` installs the plugin, with that bus. * What it returns runs when the function `use()` returned takes it out. A * plugin that only listens subscribes here (`revalidateRoutes`), as a * transport's `attach` gets its bus. tests/router/cache-groups.test.ts. * `settled(cmd, result)`: the bus calls it with the command state, after the * `onAfter` hooks and before the listeners, on the actions its scope covers, so * it hears every outcome, a rule's refusal included. A plugin is these parts, an object: `use()` places each of them. * tests/plugin-settled-part.test.ts. * `authorize(action)` and `validate(action)`: the action's rule, or undefined * for none, asked once per action its scope covers. The bus runs every authorize rule, then * every validate rule, after the start and before the work's steps * and the work: the first refusal is the command's answer, so it never * reaches a limit, a cache, a retry or the transport. * tests/rules-before-the-work.test.ts. * `started(cmd)`: a dispatch or a query starts, before its rules, on the * actions its scope covers. With `settled` it times every outcome * (`metrics`). Both are the bus's facts: a throw in either is logged and the * command goes on. tests/plugin-started-part.test.ts. * The work's steps, run around the action's work (its transport, its local * handler, a request's responder) on the actions its scope covers, once per * dispatch, never per retry, each kind for every plugin before the next: * `reuse(cmd)` a stored answer, the first one the command's (`cache`, * `idempotent`); `admit(cmd, fail)` a limit's refusal, a pure check, so a * refused command spends nothing (`rateLimit`, `circuitBreaker`); `begin(cmd)` * the command goes to the work, with an optional {@link WorkTicket}. A step's * throw is its plugin's `failed:plugin`. tests/work-steps.test.ts. */ export type PluginParts = { dispose?: () => void; readonly id?: string; readonly actions?: Readonly; readonly actionFilter?: ActionFilter; forget?: (cmd: Command) => void; attach?: (bus: BaseBus) => (() => void) | void; started?: (cmd: Command) => void; settled?: (cmd: Command, result: CommandResult) => void; authorize?: (action: string) => Refusal | undefined; validate?: (action: string) => Refusal | undefined; reuse?: (cmd: Command) => CommandResult | Promise | undefined; admit?: (cmd: Command, fail: Fail) => CommandResult | undefined; begin?: (cmd: Command) => WorkTicket | undefined; }; /** * What a `begin` step hands the bus for one command. `signal`: the work's * signal, in place of the caller's (a step that keeps the caller's combines * it in; several steps' signals are combined). `landed(result)`: the work's * final result, after the retry, before the settle. `answer`: the caller's * answer in place of the work's, while the work runs on for others * (`idempotent`'s join, each caller's abort its own). */ export type WorkTicket = { readonly signal?: AbortSignal; landed?(result: CommandResult): void; readonly answer?: Promise; }; /** A rule's answer to a command, through its plugin's `fail`: a refusal, or undefined to let it through. */ export type Refusal = (cmd: Command, fail: Fail) => CommandResult | undefined | Promise; /** * A transport: the work for the actions it is declared for at the async bus * (`createAsyncCommandBus({ transport })`), never a plugin, so every plugin * wraps it wherever it was installed. `send` answers one command; `local` runs * the action's local handler, for a transport that falls back to it. `id` owns * its failures; `dispose` runs at the bus's `dispose()`. `attach`, called * once at the bus's creation, gets that bus: where a transport that reads * the server's pushes delivers them (`wsTransport`, docs/contract.md 4). * `httpTransport` and `wsTransport` (vapor-chamber/transports) are two; * `defineTransport(send)` makes an app's own. */ export type Transport = { readonly id?: string; /** * Whether `send` may call `local()`, the action's local handler: declared * by the transport, never guessed. Only then is a handler registered for * one of its actions, `optimistic` aside (`register()`, * `core:invalid:handler`). Every transport of the library's sets it. */ readonly localFallback?: boolean; send(cmd: Command, local: () => Promise): CommandResult | Promise; dispose?(): void; attach?(bus: BaseBus): void; /** * Whether it can send now, for a transport that can be unable to (a * WebSocket while its socket is not open). An outbox over it holds its * commands while this is false. A transport without it can always send. */ isConnected?(): boolean; }; /** * A plugin's action filter, the `actions` option of every plugin that takes * one and the `actions` it declares to the bus: absent or `[]` is every action * (ActionScope's own rule, stated here once), each entry an action name or a pattern * (`'cart*'`, `'*'`). Read by the bus alone. Log s35.146 and s35.148, * tests/plugin-empty-list.test.ts. `string[]`, so an app edits its list; a plugin declares it * read-only (`Readonly`). tests/option-types.test-d.ts. */ export type ActionScope = string[]; /** * The scope options of a plugin or recorder that takes one: `actions` (an * {@link ActionScope}) and `actionFilter` (a predicate of the action name, * `createActionFilter`), ANDed. Read by `_scoped`, once per action. The same * two names `metrics`, `cache` and the other plugins take. */ export type ScopeOptions = { actions?: ActionScope; actionFilter?: ActionFilter; }; export type Hook = (cmd: Command, result: CommandResult) => void; export type AsyncHook = (cmd: Command, result: CommandResult) => void | Promise; /** Batch dispatch input */ export type BatchCommand = { action: string; target: any; payload?: any; }; /** Options for batch dispatch */ export type BatchOptions = { continueOnError?: boolean; /** * All-or-nothing semantics: if any command fails, automatically run the * registered undo handler for every command that already succeeded (in reverse order). * Requires undo handlers to be registered via `register(action, handler, { undo })`. * Commands without an undo handler are skipped during rollback. * Mutually exclusive with `continueOnError`. */ transactional?: boolean; /** * AbortSignal applied to the whole batch. Aborting before the batch starts * skips it entirely; aborting mid-flight stops further commands from * dispatching (the in-flight one runs to completion since per-command * abort already happened or is the handler's responsibility) and the * batch result is * `{ ok: false, error: BusError('core:aborted:dispatch'), results: [...partial] }` * - a BusError rather than the raw DOMException so the code is queryable * (see `abortedResult`; a caller-supplied `signal.reason` is passed through * unchanged). Under `transactional`, rollback runs first and * `successCount` is reported as 0. * Async bus only - sync `dispatchBatch` accepts the option for type * uniformity but ignores it. */ signal?: AbortSignal; }; /** Result of a batch dispatch */ export type BatchResult = { ok: boolean; results: CommandResult[]; error?: Error; /** Number of commands that completed successfully */ successCount: number; /** Number of commands that failed */ failCount: number; /** Results of undo handlers run during transactional rollback (reverse order). Only present when `transactional: true` and a command failed. */ rollbacks?: CommandResult[]; }; /** * Dead letter mode - what to do when a command has no registered handler. * - `'error'` (default): returns `{ ok: false, error }` * - `'throw'`: throws the error * - `'ignore'`: returns `{ ok: true, value: undefined }` * - function: called with the command, return value used as result * * To make a dispatch wait for a handler that registers later, give the bus a * `buffer` (`createBuffer`): it takes precedence for a dispatch, and a query * still answers by this mode. */ export type DeadLetterMode = 'error' | 'throw' | 'ignore' | ((cmd: Command) => CommandResult); /** * Naming convention configuration. * Enforces a regex pattern on action names at register and dispatch time. * A name containing `$` is the library's (a store's `$reset`) and is not * checked (tests/store-reset-command.test.ts). */ export type NamingConvention = { /** Regex pattern that action names must match */ pattern: RegExp; /** What to do on violation: 'warn' logs, 'throw' throws, 'ignore' skips */ onViolation?: 'warn' | 'throw' | 'ignore'; }; /** Per-command registration options */ export type RegisterOptions = { /** * Inverse handler for undo support, run by the `$undo` command. * Called with the original command, which still carries that dispatch's * `signal`: aborted when the dispatch was cancelled (by `supersede`, or by * the caller), so it cannot serve the inverse's own work. * tests/library-commands-memory.test.ts. */ undo?: Handler; /** * Whether history may still undo this recorded command. History undoes only * when true. A rollback (an `optimistic` action's failure, a transactional batch) reverses * the step that failed and does not consult it. tests/undo-check.test.ts. */ canUndo?: (cmd: Command) => boolean; /** * Called when a transport answered the command, with the answer's value. * A sent action declares it with no handler: `register(action, null, { * answer })`. It runs at the transport's level, so the plugins outside it * see what it changes. A throw fails the dispatch. A store's `answer` * option is one. tests/store-bridged-answer.test.ts. */ answer?: (cmd: Command, value: unknown) => void; /** * The command answers at once, its change already shown. On the async bus * the dispatch answers an `Accepted`, whose `done` settles with the result, * and listeners, after-hooks and history hear that result when it lands. * For an action a transport sends, the handler is the change shown: it runs * when the plugins hand on, before an `exclusive` turn is waited for, and * is the transport's local fallback, never run twice. A failure of the work * runs `undo` first (the `$undo` command). A plugin's refusal runs * nothing, so nothing is shown or undone. On the sync bus a throw runs the * undo and the failure returns. Needs `undo` and a handler (`core:invalid:option`). * tests/register-optimistic.test.ts. */ optimistic?: boolean; /** * Commands with one key never overlap: one at a time, first in first out. * The turn is taken at dispatch and held for the work and every retry, so a * retried command keeps its turn; the plugins run at once, so a refused * command never waits. A failure never stalls the key. `key` defaults to the action; one action or * several may share a key, and `null` runs a command at once. `scope: * 'cross-tab'` holds the key across every tab of the origin through Web * Locks (`lockPrefix`, default `vapor-chamber:exclusive`), and on this bus * where the API is absent. A sync handler runs to its end before the next, * so the sync bus already holds it. tests/register-exclusive.test.ts. */ exclusive?: Exclusive; /** * The cache groups a cached result of this action joins (RFC 9875 * `Cache-Groups`): `cache()` drops it when one of them goes, from any * source. tests/cache-groups-hub.test.ts. */ cacheGroups?: readonly string[]; /** * The cache groups a success of this action makes stale (RFC 9875 * `Cache-Group-Invalidation`): `cache()`, the client's stored reads and the * router hear them, as a server's answer naming them. An `Accepted` makes * them stale once its `done` settles ok. tests/cache-groups-hub.test.ts. */ cacheGroupInvalidation?: readonly string[]; }; /** `RegisterOptions.exclusive`. */ export type Exclusive = { key?: (cmd: Command) => string | number | null | undefined; scope?: 'instance' | 'cross-tab'; lockPrefix?: string; }; export type CommandBusOptions = { onMissing?: DeadLetterMode; /** Enforce naming convention on action names */ naming?: NamingConvention; /** * Hold a dispatch whose action has no handler yet, and run it when the * handler registers (`createBuffer`, buffer.ts). Built for lazy wiring: an * island or a code-split panel. A query never waits. */ buffer?: { readonly [_BUFFER]: BusBuffer; }; }; /** @internal The key of a buffer's half the bus reads (buffer.ts). */ export declare const _BUFFER: unique symbol; /** @internal What the bus needs from a buffer. */ export type BusBuffer = { /** Hold a dispatch with no handler: its answer. */ hold(cmd: Command): CommandResult; /** A handler for `action` registered: run what waited for it. */ release(action: string): void; /** The bus's clear(): settle every waiting caller. */ clear(): void; attach(bus: BaseBus): void; }; /** * What the async bus's retry does with an action (gRPC's per-method * `retryPolicy`): `'idempotent'` (running it twice is safe, so an uncertain * failure is re-sent too, under one idempotency key), `false` (never re-sent) * or an attempt count. */ export type RetryPolicy = 'idempotent' | false | number; /** The async bus's retry (docs/retry.md). Every field has a default. */ export type RetryOptions = { /** Attempts in total, the first included. Default 3, at least 1. */ maxAttempts?: number; /** The backoff's base in ms: attempt n waits up to `baseDelay * 2^(n-1)`. Default 200. */ baseDelay?: number; /** The longest wait, in ms. Default 20_000. A computed wait is capped at it; a * declared `retryIn` longer than it is not re-sent: the failure is returned. */ maxDelay?: number; /** * A policy per action name or pattern (`'cart*'`, `'*'`). The most specific * match wins, whatever the written order: the exact name, then the longest * prefix, then `*` (gRPC service config). tests/retry-action-policies.test.ts. */ actionPolicies?: Readonly>; }; export type AsyncCommandBusOptions = CommandBusOptions & { /** * The retry, on by default: a transient failure (`limited`, a 408) is * re-sent for any action. An uncertain one (no reply, a 502, 504 or 500), * or one with a declared `retryIn`, only for an action declared idempotent * or a keyed command. An unidentified command that got no reply fails with * `context.outcome: 'unknown'`. `false` turns it off. */ retry?: RetryOptions | false; /** * Where commands go over a wire: one {@link Transport} for every action, or * a map from action pattern to transport, the most specific match winning * whatever the written order (the exact name, then the longest prefix, then * `*`, as `retry.actionPolicies`). A command with a transport is sent; any * other runs its local handler. A `$` action (the library's) is always local. */ transport?: Transport | Readonly>; /** * The offline outbox (`createOutbox`): the actions it covers that have a * transport are held while offline and sent in order once online. Decided * once per action; any other action pays nothing. */ outbox?: { readonly [_OUTBOX]: BusOutbox; dispose(): void; }; }; /** @internal The key of an outbox's half the bus reads (outbox.ts). */ export declare const _OUTBOX: unique symbol; /** * @internal How an outbox sends a record: through the transport `unwrap` * gives for the action's, at the work step of the bus it is on. */ export type SendAt = (unwrap: (t: Transport) => Transport, action: string, target: unknown, payload: unknown, key: string) => Promise; /** * @internal What the bus needs from an outbox: the transport an action * resolves to (its own wrapper for an action it covers), read once per action, * and where its records go, given at creation: the async bus's state (sent by * `_sendAt`), or a transport's own send off an async bus (the test bus). */ export type BusOutbox = { adapt(action: string, transport: Transport): Transport; attach(bus: unknown | SendAt): void; /** A transport can send again (`_opened`): flush what waits. */ opened(): void; }; /** Listener callback for on() subscriptions (wildcard-capable) */ export type Listener = (cmd: Command, result: CommandResult) => void; /** * Options for `on()`/`once()` subscriptions. * The returned unsubscribe function also carries `Symbol.dispose`, so * `using off = bus.on(...)` works without an explicit `off()` call. */ export type ListenerOptions = { /** Auto-unsubscribe when the signal aborts. Already-aborted at call time * means the listener is never added - matches DOM `addEventListener`. */ signal?: AbortSignal; }; /** * Typed command map - define action names, target, payload, and result shapes. * Use with createCommandBus() for type-safe dispatch and register. * * @example * type AppCommands = { * cartAdd: { target: { id: number }; payload: { qty: number }; result: void }; * cartClear: { target: {}; result: number }; * }; * const bus = createCommandBus(); * bus.dispatch('cartAdd', { id: 1 }, { qty: 2 }); // fully typed */ export type CommandMap = Record; /** Extract the target type for action A from a CommandMap. Used in typed bus interfaces. */ export type TargetOf = M[A] extends { target: infer T; } ? T : any; /** Extract the payload type for action A from a CommandMap. */ export type PayloadOf = M[A] extends { payload: infer P; } ? P : any; /** Extract the result type for action A from a CommandMap. */ export type ResultOf = M[A] extends { result: infer R; } ? R : any; /** * Structural base interface for both sync and async buses. * Use this as the parameter type in utilities (createChamber, createWorkflow, etc.) * to avoid `as any` casts when working with either bus variant. */ export interface BaseBus { dispatch(action: string, target: any, payload?: any, options?: DispatchOptions): any; /** Read-only dispatch - runs the rules, the steps and the handler, fires afterHooks. No mutation intent. */ query(action: string, target: any, payload?: any): any; /** Fire a domain event - notifies on() listeners, no handler required, no result returned. */ emit(event: string, data?: any): void; register(action: string, handler: any, options?: RegisterOptions): () => void; use(plugin: PluginParts): () => void; onAfter(hook: any): () => void; on(pattern: string, listener: Listener, options?: ListenerOptions): () => void; once(pattern: string, listener: Listener, options?: ListenerOptions): () => void; /** Remove all `on()` listeners matching the given pattern, or all listeners if omitted. */ offAll(pattern?: string): void; hasHandler(action: string): boolean; /** Returns all registered action names. Useful for introspection and DevTools. */ registeredActions(): string[]; clear(): void; /** * Full teardown - calls clear() and cancels all pending timers/requests. Use in SSR or component-scoped buses. * A request() still waiting on its responder settles at once as * core:aborted:dispatch with its timer cleared; the responder is not told (only the caller's own signal * reaches cmd.signal, on the async bus). There is no disposed state - the bus stays usable - and * dispose() works on a sealed bus, which stays sealed. It also runs each installed plugin's * `dispose()` first (retry owns timers), before the plugins are dropped. */ dispose(): void; /** * Seal the bus - prevents further register(), use(), onAfter(), respond() calls. * Dispatch, query, emit, on(), once() still work - seal protects the handler/plugin topology, * not the observation layer. Listeners via on()/once() can still subscribe after seal. * Call after app initialization to lock down the graph in production. Throws BusError * with code 'core:refused:bus' on any mutation attempt. clear() is a mutation too and throws * on a sealed bus, since it would delete the undo handlers and plugins the seal commits: for * HMR, call unsealBus() first, then clear(). dispose() works on a sealed bus and leaves it * sealed. */ seal(): void; /** Returns true if the bus has been sealed. */ isSealed(): boolean; } export interface CommandBus extends BaseBus { /** * Sync dispatch. The optional `options.signal` is accepted for type * compatibility with `AsyncCommandBus` but **ignored at runtime** - sync * dispatches are atomic and not cancelable. Pass a signal here only if * you also use the async bus and want a uniform call site. */ dispatch(action: A, target: TargetOf, payload?: PayloadOf, options?: DispatchOptions): CommandResult>; /** Read-only dispatch - runs the rules, the steps and the handler, fires afterHooks. */ query(action: A, target: TargetOf, payload?: PayloadOf): CommandResult>; /** Fire a domain event - notifies on() listeners, no handler required, no result. */ emit(event: string, data?: any): void; dispatchBatch(commands: BatchCommand[], options?: BatchOptions): BatchResult; register(action: A, handler: (cmd: Command, PayloadOf>) => ResultOf, options?: RegisterOptions): () => void; use(plugin: PluginParts): () => void; onAfter(hook: Hook): () => void; on(pattern: string, listener: Listener, options?: ListenerOptions): () => void; /** Subscribe to the first matching command only; auto-unsubscribes after it fires. */ once(pattern: string, listener: Listener, options?: ListenerOptions): () => void; offAll(pattern?: string): void; /** * Request/response: a responder answers, a timeout (default 5000 ms) bounds the wait, and * `signal` settles the request - before the responder runs if already aborted, at once if * aborted while waiting. The sync command carries no signal (see Command.signal), so the * responder is not told; without a responder this is a dispatch. */ request(action: A, target: TargetOf, payload?: PayloadOf, options?: { timeout?: number; signal?: AbortSignal; }): Promise>>; respond(action: string, handler: (cmd: Command) => any | Promise): () => void; /** Returns true if a handler is registered for the given action. */ hasHandler(action: string): boolean; /** Returns all registered action names. */ registeredActions(): string[]; /** * @internal Used by the undo ledger to retrieve an undo handler registered alongside * a command handler. Do not call this from application code. */ getUndoHandler(action: string): Handler | undefined; /** @internal The `canUndo` registered with an action's undo, for undo history. */ getUndoCheck(action: string): ((cmd: Command) => boolean) | undefined; /** Remove all handlers, plugins, hooks, and listeners. Useful for testing and HMR. */ clear(): void; /** Freeze configuration - rejects register/use/clear after sealing. */ seal(): void; /** Returns true if the bus is sealed. */ isSealed(): boolean; /** * Teardown - runs each plugin's dispose(), clears state and settles * pending request()s as core:aborted:dispatch. There is no disposed state: the bus stays usable. */ dispose(): void; } export interface AsyncCommandBus extends BaseBus { /** * Async dispatch with optional `AbortSignal`. If `options.signal` is already * aborted at call time, resolves immediately with `core:aborted:dispatch` * without invoking the handler. If aborted mid-flight, the handler observes * `cmd.signal.aborted === true`; the HTTP transport propagates the signal * to the underlying fetch automatically. A handler or plugin that rethrows * the signal's reason gets the same `core:aborted:dispatch`. Every abort the * bus builds is a BusError named `AbortError`, with the reason as `cause`. A * custom Error reason (`ac.abort(myError)`) is never wrapped, at call time or * mid-flight: it passes through as itself. */ dispatch(action: A, target: TargetOf, payload?: PayloadOf, options?: DispatchOptions): Promise>>; /** Read-only dispatch - runs the rules, the steps and the handler, fires afterHooks. */ query(action: A, target: TargetOf, payload?: PayloadOf): Promise>>; /** Fire a domain event - notifies on() listeners, no handler required, no result. */ emit(event: string, data?: any): void; dispatchBatch(commands: BatchCommand[], options?: BatchOptions): Promise; /** `null`: the options of an action a transport sends, with no handler (`_checkHandler`). */ register(action: A, handler: ((cmd: Command, PayloadOf>) => ResultOf | Promise>) | null, options?: RegisterOptions): () => void; /** Installs a plugin: the bus places each of its parts. */ use(plugin: PluginParts): () => void; onAfter(hook: AsyncHook): () => void; on(pattern: string, listener: Listener, options?: ListenerOptions): () => void; /** Subscribe to the first matching command only; auto-unsubscribes after it fires. */ once(pattern: string, listener: Listener, options?: ListenerOptions): () => void; offAll(pattern?: string): void; /** * Request/response: a responder answers, receiving the command the plugins saw. Identical * in-flight requests (same action, target and payload) share one responder run, and each * caller keeps its own timeout (default 5000 ms) and `signal`: its abort settles its own * promise at once. The responder's cmd.signal aborts, with the caller's reason, once every * caller holding the request has aborted. Without a responder this is a dispatch. * tests/request-join.test.ts. */ request(action: A, target: TargetOf, payload?: PayloadOf, options?: { timeout?: number; signal?: AbortSignal; }): Promise>>; respond(action: string, handler: (cmd: Command) => any | Promise): () => void; /** Returns true if a handler is registered for the given action. */ hasHandler(action: string): boolean; /** Returns all registered action names. */ registeredActions(): string[]; /** * @internal Used by the undo ledger to retrieve an undo handler registered alongside * a command handler. Do not call this from application code. */ getUndoHandler(action: string): Handler | undefined; /** @internal The `canUndo` registered with an action's undo, for undo history. */ getUndoCheck(action: string): ((cmd: Command) => boolean) | undefined; /** Remove all handlers, plugins, hooks, and listeners. Useful for testing and HMR. */ clear(): void; /** Freeze configuration - rejects register/use/clear after sealing. */ seal(): void; /** Returns true if the bus is sealed. */ isSealed(): boolean; /** * Teardown - runs each plugin's dispose(), clears state and settles * pending request()s as core:aborted:dispatch. There is no disposed state: the bus stays usable. */ dispose(): void; } /** * @internal Symbol used by unsealBus() - not on the public interface. * Exported, underscored like `_stampMeta`, so createTestBus carries it too: * unsealBus() reopens a sealed TestBus as it reopens a real bus. No package * entry re-exports it. */ export declare const _UNSEAL: unique symbol; /** * @internal What a bus announces per command to its one observer slot: * `started` before the rules, `settled` after the after-hooks and * before the listeners, so a listener reads its command as settled. A query * (and a sync request's responder) starts with `queried`, which the command * state does not count, so a read never shows pending. An emit announces * nothing. A plain object, not a fast lane: a lane's one call site served the * start, the settle and the failure (polymorphic) behind a Map read per fact, * and a tracked dispatch read +16.8 ns slower than the before-hook and * `on('*')` it replaced (log 36.84). The slot holds the command state's * observer alone, or one that calls it and every plugin's `started` and * `settled` parts (`_composeFacts`). The observer catches its own throws: the * bus calls it bare. tests/command-state-lane.test.ts. */ export type Facts = { started(cmd: Command): void; queried(cmd: Command): void; settled(cmd: Command, result: CommandResult): void; }; /** * @internal One action's facts, resolved on its first dispatch, query or * request and read once per command (plan 4.1): its handler, its rules, its * work steps, and on the async bus its transport and its `declared` options. * One literal, one hidden class. Cleared by every change of what it holds: * register, its cleanup, use, its removal, clear. Listeners stay out: a * subscription touches no record. * tests/action-record.test.ts. */ type ActionRecord = { readonly handler: ((cmd: Command) => any) | undefined; readonly rules: readonly Rule[] | null; readonly steps: readonly Step[] | null; readonly transport: Transport | undefined; readonly declared: RegisterOptions | undefined; }; /** * @internal The test bus's setter of its facts observer. A real bus has none: * its observer is the `facts` slot of the state `_INSPECT` carries, so no bus * carries a setter (`_factsSetter`). commandState hands the observer over, * then hands null back on release. */ export declare const _FACTS: unique symbol; type AsyncState = { readonly opts: CommandBusOptions; handlers: Map; undoHandlers: Map; /** `RegisterOptions.answer` per action: what a transport's answer is handed to. */ answers: Map void>; /** The actions registered `optimistic` or `exclusive`, with their options: run apart. */ declared: Map; /** The keys `exclusive` holds on this bus, made by the first such command. */ lanes: Lanes | null; /** The library's own actions an app names (a form's, history's trigger), by handler: no transport sends them. */ locals: Map; /** The installed plugins, in install order: the bus places their parts. */ plugins: PluginParts[]; afterHooks: HookEntry[]; /** Exact-match listeners - O(1) lookup on the hot path. Action-keyed. */ exactListeners: Map; /** Wildcard listeners ('*' or 'foo*') - walked per dispatch with a precomputed prefix (WildcardEntry). */ wildcardListeners: WildcardEntry[]; responders: Map any | Promise>; /** The work steps, as on the sync bus. */ steps: Steps; /** Per-instance dedup map for in-flight async requests - avoids module-level singleton leak in SSR. */ pendingRequests: Map; /** Current nested dispatch depth - guards against infinite recursion. */ dispatchDepth: number; /** When true, register/use/onAfter/respond throw. */ sealed: boolean; /** One cancel per request() still waiting on its responder. dispose() runs them, so * each settles at once as core:aborted:dispatch with its timer cleared, and polices nothing * afterwards - no disposed state. Vue's EffectScope.stop() records one (active false) * but polices nothing either: run() still runs (rc.11 reactivity). * Lazily null until the first such request. */ waiting: Set<() => void> | null; /** The retry policy (budget, waits), or null when `retry: false`. */ retry: Retrier | null; /** The bus's stores and their lane, where a reply's `stores` go (`_busStores`). */ stores: BusStores; /** The declared transports by pattern, fixed at creation; empty without one. */ readonly transports: ReadonlyArray<{ pattern: string; transport: Transport; }>; /** The action's transport, resolved once per action; null on a bus with none. */ readonly transportFor: ((action: string) => Transport | undefined) | null; /** The internal observer, as on the sync bus. */ facts: Facts | null; /** The rules, as on the sync bus. */ rules: Rules; /** The records, as on the sync bus. */ records: Map; /** Each action's live registration: the one its handler, undo and options are. */ owners: Map; /** The live registrations a newer one covers, per action, null until the first. */ held: Map | null; }; /** * Swap the unique-ID generator. Call once at app setup if you need a different * format (e.g. `crypto.randomUUID` for distributed tracing). * * @example * import { configureUid } from 'vapor-chamber'; * configureUid(() => crypto.randomUUID()); */ export declare function configureUid(fn: () => string): void; /** * Put the default id generator back after `configureUid`. * * @internal - NOT public API, not exported from the barrel, like * `_configureClock`. It exists so tests/perf.bench.ts times the library's * default after a group that swapped it, not a copy of it. */ export declare function _resetUid(): void; /** * Swap the clock `stampMeta` reads. `_configureClock()` with no argument * restores the cached default. * * @internal - NOT public API, not exported from the barrel, no semver promise. * It exists so `tests/clock-source-ab.test.ts` can A/B the two clock sources * through the real dispatch path, and so * `tests/clock-source-contained.test.ts` can drive a deliberately frozen clock * to prove no TTL depends on this. Underscored for the same reason * `_stampMeta` is. * * There is deliberately no consumer-facing option. An option only earns its * place when both settings are right for different people; here the cached * clock is what essentially everyone wants, and the rare need for exact * per-command wall-clock is served by reading the clock yourself - see the * note on `CommandMeta.ts`. */ export declare function _configureClock(fn?: () => number): void; declare function okResult(value: any): CommandResult; declare function errResult(error: Error): CommandResult; declare function tryCatchHandler(handler: Handler, cmd: Command): CommandResult; /** Internal - `origin` on every dispatch `fn` makes synchronously; nests, restores on exit. */ export declare function _withOriginScope(origin: string, fn: () => T): T; /** * Internal - stamp `origin` on the meta of the FIRST dispatch `fn` makes * synchronously. Not public API; underscored like `_stampMeta`. * * The `finally` is leak protection, not a settlement guard: `validateNaming` * can throw before `stampMeta` runs, and an unconsumed slot must not bleed into * whatever dispatches next. Awaiting the result of `fn()` is fine - the slot is * already consumed by then. */ export declare function _withOrigin(origin: string, fn: () => T): T; export { _isLibraryAction, _asLibrary }; /** @internal Reverse `cmd` through its `$undo` command: origin 'undo', caused by `cmd`. */ export declare function _undo(bus: { dispatch(action: string, target: any): any; }, cmd: Command): any; /** * Internal - stamp `causationId` on the meta of the FIRST dispatch `fn` makes * synchronously, for callers whose payload cannot carry `__causationId`. * Same contract and same `finally` reasoning as `_withOrigin`. */ export declare function _withCausation(causationId: string | undefined, fn: () => T): T; /** * Stamp a command with auto-generated metadata. * * The `__`-prefixed payload keys are the established convention for * per-dispatch meta without a signature change: they travel **with** the * dispatch rather than beside it. * * `__origin` exists because of a family of four bugs that all shared one shape - * a module-level flag set before a dispatch and cleared in `finally` * (`_mcpDispatching` in mcp.ts, `receiving` in createChannel(), `paused` in redo(), * and the reaction guard). On a sync bus the dispatch completes inside the * `try`, so the flag holds and the tests pass. On an **async** bus the * dispatch returns a pending promise, its work runs a microtask later, * and `finally` has already fired - so the flag was cleared before the thing * it was guarding happened. The failure modes ranged from misattributed audit * origins to an infinite cross-tab broadcast loop. A marker on the dispatch is * race-free by construction, and one fix site serves all of them. */ declare function stampMeta(payload: any): CommandMeta; /** * Internal - exported for `testing.ts` so the TestBus stamps the same meta the * real buses do. Underscored: not public API, not in the docs, may change. * Duplicating the `__`-key convention in the double is exactly how the double * drifts from the thing it doubles. */ export { stampMeta as _stampMeta }; /** * Internal - the two result factories, for modules that build a * `CommandResult` outside the bus (transports, composables, plugins). A * hand-written `{ ok: false, error }` literal has a different hidden class from * `errResult`'s three-field one, so every `result.ok` site that sees both goes * polymorphic; tests/v8-shapes.test.ts pins the shared map. The root barrel * makes the two public as `ok` / `err` for app plugins (index.ts, * tests/plugin-result-factories.test.ts); these underscored names stay the * library's own spelling. */ export { okResult as _okResult, errResult as _errResult, tryCatchHandler as _tryCatchHandler }; export { declaredTransports as _declaredTransports, attachTransports as _attachTransports, send as _send, assertPlugin as _assertPlugin }; /** * WildcardEntry - a subscribed wildcard listener, with its match test already * reduced to data. * * `pattern` is retained verbatim because `offAll(pattern)` and `inspectBus()` * both report on it; `prefix` is what the dispatch path actually reads. It is * `pattern.slice(0, -1)`, which is correct for BOTH wildcard shapes with no * special case: `'cart*'` -> `'cart'`, and `'*'` -> `''`, where * `action.startsWith('')` is unconditionally true. So the fan-out loop is one * `startsWith` per listener with no branch, no `charCodeAt`, and no cache * lookup. * * WHY IT LIVES ON THE ENTRY rather than in `matchesPattern`'s cache. `on()` * has already classified the pattern as a wildcard to decide which bucket it * goes in, so by the time the entry exists the parse is a known result being * thrown away. Storing it is the same move Vue made in 3.6.0-rc.6's `29ed4b0` * (`parseAdoptTarget`): hoist a per-call string scan into a descriptor computed * once by the factory, then compare cheap values on the hot path. * `matchesPattern` keeps its cache - it is public API taking arbitrary * caller-supplied patterns (plugin `actions:` filters), where * nothing has classified anything in advance. * * Measured, real dispatch path, interleaved A/B - see * `tests/wildcard-prefix-ab.test.ts`. */ type WildcardEntry = { pattern: string; prefix: string; listener: Listener; off: boolean; }; /** * An exact-match listener: the same shape as a WildcardEntry (one hidden * class for both loops), its `prefix` unused. `off` is set when it is * unsubscribed, so a dispatch already walking it skips it. */ type ListenerEntry = WildcardEntry; /** * A before- or after-hook: one shape for both lists. `off` is set when it is * unsubscribed, so a dispatch already walking it skips it, as a listener's. */ type HookEntry = { fn: H; off: boolean; }; /** * Run every collected disposer in insertion order, then empty the list so a * second call is a no-op (idempotent teardown). Shared by the composables' * `dispose()` and the chamber/install + history-plugin cleanups. Cold path * (runs at unmount/disposal, never per dispatch) - a plain loop, no closure. * * No try/catch by design - settled, do not "harden". Every disposer collected * here is an internal `register`/`on`/`use`/`respond` unsub (`Map.delete` / * `Array.splice`); none can throw. A throw would mean corrupted internal state, * which should surface loudly during teardown, not be swallowed. */ export declare function disposeAll(fns: Array<() => void>): void; /** * Stable string key for a (action, target) pair. Handles circular refs safely. * Useful for cache invalidation integration (e.g. TanStack Query). * * A target keys by its value: a primitive by its String() (so `1` and `'1'` * share a key, by design - tests/isloading-keys.test.ts), an object by its * JSON with keys sorted (keyTextFor, ./canonical), a Number, String, Boolean * or BigInt object as its value. A target JSON cannot serialize does not * share one fallback string with every other: a BigInt, a NaN or an Infinity * inside it is tagged, and a circular, function or symbol target keys by its * identity (tests/commandkey-collisions.test.ts). * * An action name holding `:` can share a key with another action - * ('a:b', 'c') and ('a', 'b:c') are both `a:b:c`. Escaping the name on every * call measured 25-30% of a primitive key (v1.30.0), so it is a naming rule * instead, decided once (docs/V8-RULES.md rule 3): warned in development and * folded out of production. */ export declare function commandKey(action: string, target: any): string; /** * The target half of `commandKey`, exactly: `commandKey(a, t) === a + ':' + * _targetKey(t)`. For `commandState`'s `pending`, whose slots are a map by action, then by * this, so a tracked dispatch builds no `action:target` string. A primitive's * String() is the conversion the template does; an object takes commandKey's * own serialization, so the two cannot drift (tests/isloading-keys.test.ts). */ export declare function _targetKey(target: any): string; /** * CommandPool - pre-allocates Command objects in a circular buffer to * eliminate garbage collection pauses during dispatch bursts. When the * pool is exhausted, it wraps around and reuses the oldest slot. * * **Important**: The pool is a standalone utility - `bus.dispatch()` still * creates its own Command internally and stamps `meta` (ts, id, correlationId). * Pooled commands do NOT have `meta` set. Use `pool.acquire()` for the action/target/payload, * then pass those values to `bus.dispatch(cmd.action, cmd.target, cmd.payload)`. * The bus will create its own internal command with proper metadata. * * @example * const pool = createCommandPool(); * const cmd = pool.acquire('cartAdd', cart, { id: 1 }); * bus.dispatch(cmd.action, cmd.target, cmd.payload); // bus stamps its own meta * * pool.stats(); // { size: 64, acquired: 1, cursor: 1 } * pool.reset(); // Reset cursor and clear all slots */ export interface CommandPool { /** Acquire a command object from the pool. Reuses slots in a circular fashion. */ acquire(action: string, target: any, payload?: any): Command; /** Current pool statistics. */ stats(): { size: number; acquired: number; cursor: number; }; /** Reset the pool - clears all slots and resets cursor. */ reset(): void; /** Pool capacity. */ readonly size: number; } export declare function createCommandPool(size?: number): CommandPool; /** @internal The one reader of a declared scope: `actions` (an ActionScope) and `actionFilter`, ANDed. The outbox's too. */ export declare function _inScope(declared: { readonly actions?: Readonly; readonly actionFilter?: ActionFilter; }, action: string): boolean; /** * @internal `declared`'s scope as a predicate of the action, or null when it * declares none, so an unscoped reader pays one null check. The scope of * `logger`, `history`, `useCommandHistory` and `useCommandError`, and of a * `settled` part. `actions` are classified once, here, into exact names and * prefixes by `_patternPrefix`, so a command costs a few comparisons and no lookup: * a per-action Map cost a scoped history record +19.5 ns (V8-RULES 3). * `actionFilter` is called as it is. tests/scope-options.test.ts. */ export declare function _scoped(declared: { readonly actions?: Readonly; readonly actionFilter?: ActionFilter; }): ((action: string) => boolean) | null; /** * @internal The bus's facts slot, from the command state's observer (`own`) * and every installed plugin's `started` and `settled` parts. Nothing * observes: null, so a bare bus stays bare. The command state alone: its own * observer, unwrapped, so a tracked dispatch pays nothing for parts. * Anything more: one observer calling the command state first, then * each part in install order, inside its scope and its own try. Built at * `use()` and when a command state attaches, never per dispatch. The test * bus's too. tests/plugin-started-part.test.ts. */ export declare function _composeFacts(own: Facts | null, plugins: readonly PluginParts[]): Facts | null; /** One rule of an action: its check and its plugin's `fail`. */ type Rule = { readonly check: Refusal; readonly fail: Fail; readonly part: 'authorize' | 'validate'; }; /** @internal Each action's rules, resolved once per action; null while no installed plugin declares one. */ export type Rules = ((action: string) => readonly Rule[] | null) | null; /** * @internal The rules of each action, read from the installed plugins' parts: * every `authorize` rule, then every `validate` rule (authorization answers * before validation, plan-transport-owned.md revision 17), each kind in * install order, on the actions each part's scope covers (`_inScope`). A * part is asked once per action, and an action with none caches null. The * test bus's too. tests/rule-scope.test.ts. */ export declare function _rulesOf(plugins: readonly PluginParts[]): Rules; /** * @internal Runs an action's rules in order: the first refusal answers, and * undefined lets the command through. A rule's throw or rejection is its * plugin's `failed:plugin`. A promise only when a * rule returns one. The test bus's too. tests/rules-before-the-work.test.ts. */ export declare function _refusal(rules: readonly Rule[], cmd: Command, from?: number): CommandResult | Promise | undefined; /** One plugin's work steps for an action, with its `fail`. */ type Step = { readonly plugin: PluginParts; readonly fail: Fail; }; /** @internal Each action's steps, resolved once per action; null while no installed plugin declares one. */ export type Steps = ((action: string) => readonly Step[] | null) | null; /** * @internal The work's steps of each action, read from the installed * plugins' `reuse`, `admit` and `begin` parts, in install order, each plugin * inside its scope. Resolved once per action; an action with none caches * null. The test bus's too. */ export declare function _stepsOf(plugins: readonly PluginParts[]): Steps; /** * @internal The work behind its steps: every `reuse` (the first answer is * the command's), every `admit` (the first refusal is), every `begin`, then * the work (`run`, the retry and the work below it), then each ticket's * `landed`. A ticket's `signal` becomes the work's, combined when several * give one; a ticket's `answer` is the caller's in place of the work's. A * step's throw is its plugin's `failed:plugin`, and the tickets taken before * it land with that failure. Synchronous while every step and the work are. * The test bus's too. tests/work-steps.test.ts. */ export declare function _stepped>(steps: readonly Step[], cmd: Command, run: () => R): R | CommandResult | Promise; /** One register() call: `true` writes what it registers, `false` removes it. */ type Registration = (on: boolean) => void; /** * @internal register()'s one rule, the test bus's too: a handler is a function * where it can run, `null` where it cannot. Under the action's `transport` it * runs only as the change shown (`optimistic`) or as the fallback of a * transport that declares `localFallback`. `null` declares a sent action's * options with no handler. Anything else never runs, and is refused at the * line that registered it. Setup only. tests/register-shadow-check.test.ts. */ export declare function _checkHandler(action: string, handler: unknown, opts: RegisterOptions, transport: Transport | undefined): void; /** * @internal A bus's cache groups: the hub every source calls and every reader * listens to (a transport's client, else the first reader's own), and the * actions whose cached results join a group (`RegisterOptions.cacheGroups`), * and each `cacheGroupInvalidation` declared, whose listener waits for a hub. * Made on first need, keyed by the bus's state. */ export type BusGroups = { hub: GroupHub | null; readonly members: Map; readonly declared: Set; }; /** One `cacheGroupInvalidation`: `start` puts its listener on, `off` takes it off once on. */ type Declared = { readonly start: () => void; off: (() => void) | undefined; }; /** @internal `bus`'s cache groups (BusGroups): what a transport joins and cache() reads. */ export declare function _groupsAt(bus: BaseBus): BusGroups; /** * @internal `hub` becomes the bus's hub, and each declared action's listener * goes on. Before it nothing reads an invalidation, so a bus with no hub keeps * its bare path. Register and attach in either order end the same. * tests/cache-groups-hub.test.ts. */ export declare function _setHub(g: BusGroups, hub: GroupHub): GroupHub; /** * @internal The sync batch rule, for the bus and its test double * (`createTestBus`): one rule, so the double cannot diverge * (tests/testbus-batch.test.ts). `run` dispatches a built Command; a * transactional batch undoes the Commands that ran, newest first, through * `dispatch`, for the actions `undoable` names. */ export declare function _syncBatch(commands: BatchCommand[], opts: BatchOptions, run: (cmd: Command) => CommandResult, undoable: (action: string) => boolean, dispatch: (action: string, target: any) => CommandResult): BatchResult; /** * A transport is the work, declared at the bus, never a plugin. The test bus's rule too * (tests/transport-is-the-work.test.ts). The one rule: an object with a part * the bus places (`started`, `settled`, `authorize`, `validate`, `reuse`, * `admit`, `begin`, `attach`) and no `send` (a transport's, which may * carry `attach`); anything else is refused, a function too: no * part holds `next` (tests/plugin-declares-parts.test.ts). A plugin installs * once: a second use() would place its parts twice. Two plugins sharing an * `id` install, but their failures carry one owner, so development says it * (tests/plugin-install-once.test.ts). */ declare function assertPlugin(plugin: unknown, installed: readonly PluginParts[]): void; /** * Create a synchronous command bus. * * @example * // Basic usage * const bus = createCommandBus(); * bus.register('cart/add', (cmd) => addToCart(cmd.target, cmd.payload)); * const result = bus.dispatch('cart/add', { id: 1 }, { qty: 2 }); * if (result.ok) console.log('Added:', result.value); * * @example * // Type-safe with CommandMap * type App = { * 'cart/add': { target: { id: number }; payload: { qty: number }; result: void }; * }; * const bus = createCommandBus(); * bus.dispatch('cart/add', { id: 1 }, { qty: 2 }); // fully typed * * @example * // With plugins, hooks, and listeners * const bus = createCommandBus(); * bus.use(logger()); // plugin wraps every dispatch * bus.onAfter((cmd, res) => { }); // runs after handler * bus.on('cart/*', (cmd, res) => { }); // wildcard listener */ export declare function createCommandBus(options?: CommandBusOptions): CommandBus; type Retrier = { /** Call, and re-send by the class rule. */ run(cmd: Command, call: () => CommandResult | Promise): Promise; /** The no-step path's half of `run` before the first send: an idempotent action's key stamped. */ begin(cmd: Command): void; /** Its other half: a success as it came, a failure re-sent through the work by the class rule. */ end(result: CommandResult, cmd: Command, s: AsyncState, rec: ActionRecord, dispatching: boolean): CommandResult | Promise; /** End every wait (the bus's dispose()). */ dispose(): void; }; /** * The one rule for a command's idempotency key, decided once per dispatch: a * key already stamped stays, else the key given (an app's own, as given), else * the dispatch's id. The id is opaque and the same on every attempt, as * Idempotency-Key draft-07 2.2 recommends: a key is a header, which proxies * and logs keep, so no command content goes in it. idempotent() and the retry * stamp through it. tests/idempotency-key.test.ts. */ export declare function _keyed(meta: CommandMeta | undefined, key?: string): void; /** * @internal The other rule: an outbox record's key replaces any key stamped, * so the record's key wins wherever `idempotent` is installed. The held * command and its replay stamp through it. tests/idempotency-key.test.ts. */ export declare function _recordKeyed(cmd: Command, key: string): void; /** * Build a stable AbortError result. Prefers a user-provided explicit reason * (e.g. `ac.abort(new MyError('cancelled'))`) over the lib's BusError, but * falls back to BusError for the default `ac.abort()` case so consumers can * switch on `error.code === 'core:aborted:dispatch'`. * * After-hooks still fire from the caller, so observability is intact. * * `signal` is optional: dispose() settles a waiting request() with none, and * gets the BusError. * @internal - also used by transports.ts for mid-flight signal handling. */ export declare function abortedResult(action: string, signal?: AbortSignal): CommandResult; /** * The send, the test bus's too: the transport answers the command. A throw or * rejection is the transport's own failure (`:failed:send`), the * caller's abort excepted. Given the bus `s`, a success it carried is written * where the work is, inside the call the retry re-sends: the action's * `answer`, then each store state the reply declared, last, so what the * server named wins and every plugin outside sees it. Store ids are external * strings: own keys only, in a Map (src/dict.ts). Decided when the send * starts. One `.then` on the transport's own promise: an async frame cost a * sent dispatch about 19 ns more (log 36.45). */ declare function send(transport: Transport, cmd: Command, local: () => Promise, s?: AsyncState): Promise; /** * A request in flight that identical callers join: its dispatch, and the * controller the responder reads on cmd.signal (when the first caller gave a * signal), aborted once every caller holding the request has aborted. A * caller with no signal holds it until it lands (`live` Infinity). */ type SharedRequest = { done: Promise; ctrl: AbortController | undefined; live: number; }; /** * The bus's `transport` option as patterns: one transport is every action's * (`*`). With an outbox, an action resolves through its `adapt`, once. */ declare function declaredTransports(option: AsyncCommandBusOptions['transport'], outbox?: BusOutbox): Pick; /** * @internal A record as the command its replay sends: stamped as a * dispatch's, carrying the record's key and origin 'replay'. */ export declare function _replayOf(action: string, target: unknown, payload: unknown, key: string): Command; /** * @internal The async bus's send of an outbox record (outbox.ts): the replay * through the action's transport `unwrap` gives (the outbox's wrapper's inner * one) at the work step (`send`, `answered`), else its local handler. Not * dispatched. `bus` is the state the bus handed the outbox. */ export declare function _sendAt(bus: unknown, unwrap: (t: Transport) => Transport, action: string, target: unknown, payload: unknown, key: string): Promise; /** * Each declared transport once, however many patterns name it, given the * bus (`Transport.attach`). At creation only, the test bus's too. The push * applier stays with the transports that read pushes, so a bundle of * transports that read none never carries it. */ declare function attachTransports(bus: BaseBus, transports: AsyncState['transports']): void; /** * Create an asynchronous command bus. Handlers return Promises. * * @example * const bus = createAsyncCommandBus(); * bus.register('user/fetch', async (cmd) => { * const user = await fetch(`/api/users/${cmd.target.id}`).then(r => r.json()); * return user; * }); * const result = await bus.dispatch('user/fetch', { id: 42 }); * if (result.ok) console.log(result.value); // { name: 'Alice', ... } */ export declare function createAsyncCommandBus(options?: AsyncCommandBusOptions): AsyncCommandBus; /** * Unseal a sealed bus. **Dev/HMR only** - if your production code never imports * `unsealBus`, it gets tree-shaken out entirely, making `seal()` irreversible. * * @example * // vite-hmr.ts * import { unsealBus } from 'vapor-chamber'; * if (import.meta.hot) { * unsealBus(bus); * bus.clear(); * // re-register handlers... * bus.seal(); * } */ export declare function unsealBus(bus: BaseBus): void; /** * @internal Install the library's own observer past the seal. `seal()` protects the * handler/plugin topology, not the observation layer, so the bus is sealed * again before this returns. tests/composables-sealed-bus.test.ts. */ export declare function _pastSeal(bus: BaseBus, install: () => T): T; /** * @internal True for a bus made by createCommandBus, whose dispatches settle * in LIFO order. False for createAsyncCommandBus's, and for any bus this module * did not make (no state to read), since its order is unknown. Reads the state * `_INSPECT` carries, so inspect() stays out of a consumer that calls this. */ export declare function _isSyncBus(bus: BaseBus): boolean; /** @internal True for a bus `createAsyncCommandBus` made. */ export declare function _isAsyncBus(bus: BaseBus): boolean; /** * @internal False for an async bus that cannot reject: one that declares * neither `onMissing: 'throw'` nor a naming rule with `onViolation: 'throw'`, * both fixed at creation. True for any other bus. tests/usecommand-settles.test.ts. */ export declare function _mayReject(bus: BaseBus): boolean; /** * @internal A transport's own outbox (a `wsTransport`'s) on the bus that * declares the transport, from `Transport.attach`: on an async bus its * replays are sent at that bus's work step. False on any other bus (the test * bus), where the transport sends them itself. */ export declare function _outboxOn(bus: BaseBus, outbox: BusOutbox): boolean; /** * @internal What sets `bus`'s facts observer: the `facts` slot of a bus this * module made, the test bus's own `[_FACTS]`, else undefined (a bus this * library did not make). Read once, when a command state is made. */ export declare function _factsSetter(bus: BaseBus): ((facts: Facts | null) => void) | undefined; /** @internal A transport can send again (a socket opened): the bus's outbox flushes what it holds. */ export declare function _opened(bus: BaseBus): void; /** * Complete snapshot of a bus's internal topology. * Returned by `inspectBus()` for debugging, DevTools, and ops diagnostics. * * @example * import { inspectBus } from 'vapor-chamber'; * const info = inspectBus(bus); * console.log(info.actions); // ['cartAdd', 'cartRemove'] * console.log(info.undoActions); // ['cartAdd'] - only these can rollback * console.log(info.pluginCount); // 3 * console.log(info.sealed); // true */ export type BusInspection = { /** All registered action names. */ actions: string[]; /** Actions that have undo handlers registered. */ undoActions: string[]; /** Actions that have respond() handlers registered. */ responderActions: string[]; /** Number of installed plugins. */ pluginCount: number; /** The installed plugins in install order, each as it declares itself. */ plugins: PluginInspection[]; /** The transports declared at the bus, by pattern, as written; empty on a sync bus. */ transports: Array<{ pattern: string; id: string; }>; /** Number of afterHooks. */ afterHookCount: number; /** Pattern listeners: each entry is the pattern string. */ listenerPatterns: string[]; /** Whether the bus is sealed. */ sealed: boolean; /** Current nested dispatch depth (0 when idle). */ dispatchDepth: number; }; /** * One installed plugin in `BusInspection.plugins`: what it declares, never its * function. `id` is its declared id (`undefined` when it declares none, never * `Function.name`, which a minifier renames). `actions` is a copy of its * `actions` scope. `actionFilter` says whether it has one: a function is not * serializable. */ export type PluginInspection = { id: string | undefined; actions: string[] | undefined; actionFilter: boolean; /** The parts it declares, in the order the bus runs them. */ parts: string[]; }; /** * @internal The installed plugins in install order, as `inspectBus` reports * them; the TestBus reports through it too, so the two cannot differ. * tests/inspect-plugins.test.ts. */ export declare function _inspectPlugins(plugins: readonly PluginParts[]): PluginInspection[]; /** * Inspect a bus's full topology. **Dev/debug only** - if your production code * never imports `inspectBus`, it gets tree-shaken out entirely. * * Returns a plain snapshot object - safe to serialize, log, or send to DevTools. * * @example * import { inspectBus } from 'vapor-chamber'; * const info = inspectBus(bus); * console.table(info); * * // Check if all checkout actions have undo handlers * const missing = info.actions.filter(a => !a.includes('$') && !info.undoActions.includes(a)); // `$` names are the library's (`cartAdd$undo`) * if (missing.length) console.warn('Missing undo for:', missing); */ export declare function inspectBus(bus: BaseBus): BusInspection; //# sourceMappingURL=command-bus.d.ts.map