/** * vapor-chamber - Offline outbox * * Hold commands durably while offline, replay them in order on reconnect, * and deduplicate server-side via the Idempotency-Key header. * * The outbox composes existing primitives: * - a key per record (the record's id), stamped onto * `cmd.meta.idempotencyKey` on every replay, * - the HTTP transport, which forwards `meta.idempotencyKey` as an * `Idempotency-Key` header so the backend can reject duplicate writes, * - the store's state half (`_stateHalf`): the queue is state, saved by * `saveTo` and shared across tabs by whole states (`_shareStates`). * * A bus option (`createAsyncCommandBus({ outbox })`): it wraps the transports * of the actions it covers, below every plugin, so no install order exists. */ import type { ActionScope, BusOutbox, Command } from './command-bus'; import type { ActionFilter } from './action-filter'; import { _OUTBOX } from './command-bus'; import type { Signal } from './signal'; import { type PersistStorage } from './store-persist'; /** * A queued command awaiting replay. JSON-serializable by design - `target` and * `payload` round-trip through the storage, so keep them plain data (no * functions, no DOM nodes) for actions routed through the outbox. */ export type OutboxRecord = { /** Unique record ID (distinct from the command's `meta.id`, which is re-stamped on replay). */ id: string; /** * The tab that sends it: the one whose caller holds its `done`, or the one * that took it over when that tab closed. Read only by the outbox. */ tab: string; /** The command's action name. */ action: string; /** The command's target, exactly as dispatched. */ target: any; /** The command's payload, exactly as dispatched. */ payload?: any; /** * The idempotency key derived at ENQUEUE time. Replays stamp this original * key onto `cmd.meta.idempotencyKey`, so the backend sees the same * `Idempotency-Key` header for every delivery attempt of this command. */ key: string; /** * When the command was queued: an RFC 3339 timestamp in UTC, millisecond * precision (`new Date().toISOString()`, e.g. `2026-10-02T17:41:19.250Z`). * Text, not epoch ms, because the record crosses a boundary (storage, or a * backend a custom storage syncs to) and the text names its unit and zone. * The outbox never reads it; `Date.parse(record.queuedAt)` gives ms. */ queuedAt: string; }; export type OutboxOptions = { /** Which actions to hold. Glob patterns supported: '*', 'cart*'. An {@link ActionScope}. */ actions?: ActionScope; /** Selects actions by name, ANDed with `actions`: an {@link ActionFilter} (`createActionFilter`). Log s35.152. */ actionFilter?: ActionFilter; /** * The queue's name: the key it is saved under, the channel its tabs share * it on, and the prefix of its Web Locks. Default: `'vc:outbox'`. Two * outboxes on one page need two names. */ name?: string; /** * Where the queue is saved, read when the outbox is created: a store's * `PersistStorage` (`localStorage`'s two methods, each may answer a * promise). Default: `localStorage`. `indexedDbStorage()` for IndexedDB. * `null`: this tab's memory only, not shared with other tabs. */ storage?: PersistStorage | null; /** * Whether the app can send now, read on every send of a covered action. * Default: a flag the window's `online` and `offline` events keep, read * from `navigator.onLine` when the outbox is created; online with no window (SSR). */ isOnline?: () => boolean; /** * Flush on the window's `'online'` event, and once the stored queue has * loaded while online. Default: true. No polling. One timer, * and only when a replay's answer declared a `Retry-After`: the outbox * flushes again then, no sooner than a second later. While the answer * repeats, the wait doubles (1 s, 2 s, 4 s, ...) up to 30 s; a longer * declared wait wins; a successful replay starts it over at 1 s. * `dispose()` removes the listeners and ends that wait. */ autoFlush?: boolean; /** * Derive the idempotency key stored on each record and replayed to the * backend, sent as given. Default: the record's id, so each queued write is * its own request, and the header carries no command content * (Idempotency-Key draft-07 2.2). A stored record replays its stored key. * A key of unreserved characters (letters, digits, `-`, `_`, `.`, `~`) goes * out as it is. Any other key is percent-encoded on every send: about * 110 ns a command on an Apple M3, Node 24.21.0 (log 36.48). * tests/idempotency-key.test.ts. */ key?: (cmd: Command) => string; /** * Max queued records - bounded memory. When exceeded, the OLDEST record is * dropped with a warning report, and its caller's `done` settles with * `outbox:exceeded:queue`. Default: 200. */ maxSize?: number; /** * The longest, in ms, a command held this session waits to be sent. Past * it, the record is dropped and its caller's `done` settles with * `outbox:timeout:queue`. Default: none, it waits for its flush. A * `wsTransport`'s own outbox passes its reply timeout. */ ttl?: number; /** * Whether a failed replay is worth trying again later. `true` keeps the * record at the head and stops the flush, so order is preserved and the * next flush retries from the same spot. `false` means the answer is final * (the server refused it, or a validator rejected it): the record is * dropped, its caller's `done` settles with the failure (a record no caller * waits on goes to `rejected`), and the flush moves on. * * Default: final only for a verdict on this command. From the SERVER, a 4xx * other than 401 / 419 (a session to renew), 408 (timeout) and 429 (rate * limit), as the response's status or as a problem's own `status` inside a * 2xx: the conditions `invalid`, `refused`, `missing`, `already`, `conflict`, * and only when the answer declared no `Retry-After`. * From the library, only `invalid`: it gives the same answer on every * flush. Everything else is kept: a 5xx, a problem with no status, a network * failure, and every other error the library raised (a handler not * registered yet), because dropping a queued command over a client-side * failure loses the user's data. Pass `() => true` to block on every * failure, or your own rule in your backend's codes (`error.code`). * * WHY IT EXISTS: if every failure blocked, one record the server refuses * would hold the whole queue for good - each flush re-sends it, gets the * same answer, and the records behind it never leave. */ isRetryable?: (error: Error, record: OutboxRecord) => boolean; }; /** * What one `flush()` did. `failed` is 0 or 1: a retryable failure stops the * flush. `rejected` counts records dropped as final (see `isRetryable`). */ export type OutboxFlushSummary = { replayed: number; failed: number; rejected: number; }; /** A final refusal of a record no caller waits on (one a closed tab or a previous session queued). */ export type OutboxRejection = { record: OutboxRecord; error: Error; }; /** The object returned by {@link createOutbox}. Pass it to `createAsyncCommandBus({ outbox })`. */ export type Outbox = { /** * Replay this tab's records sequentially (strict FIFO). Each record is sent * through its action's transport with its ORIGINAL idempotency key and * origin `'replay'`, not dispatched: no plugin or listener sees it, and a * store's `answer` applies. The first retryable failure stops the flush - * that record and everything after it stay queued. Re-entrant calls join * the flush in progress. */ flush(): Promise; /** Reactive queue depth, every tab's records - bindable in templates ("3 changes pending sync"). */ pending: Signal; /** Final refusals of records no caller waits on (a closed tab's, a previous session's). */ rejected: Signal; /** Drop every queued record, in every tab sharing the queue. A waiting `done` settles with `outbox:aborted:clear`. */ clear(): Promise; /** Remove the window listeners, end a Retry-After wait, release this tab's locks. Idempotent; the bus's `dispose()` runs it. */ dispose(): void; /** @internal The bus's half: `createAsyncCommandBus({ outbox })` calls it once. */ readonly [_OUTBOX]: BusOutbox; }; /** * createOutbox - offline outbox: hold commands durably while offline, replay * them in order on reconnect, deduplicate server-side via Idempotency-Key. * * The bus takes it as an option and wraps the transports of the actions it * covers, decided once per action, so any other action pays nothing. While * offline, while the stored queue loads, or while this tab's records wait (a * later command must not overtake them), a covered command is held: * recorded, saved, stamped with its key, and answered `{ ok: true, value }` * with `value` an `Accepted` whose `done` settles with the replay's result. * On reconnect (the window's `'online'` event, or `flush()`), records go out * one at a time through their transports. A retryable failure stops the * flush and keeps the order; a final one drops the record and moves on. * * The queue is state on a store's state half: saved under `name`, and in a * page shared with the other tabs of the origin (`shareTabs`). Sending is * the tab's that dispatched, where its caller waits: each tab sends only its * own records. Each tab holds the Web Lock `vapor-chamber:outbox::tab:` * for its life and waits on the lock of every other tab named in the queue. * When a tab closes, the first tab waiting takes its lock over and sends its * records: no record is sent by two tabs, and none waits for a reload. A * record taken over has no caller here: its final verdict goes to `rejected`. * tests/outbox-tabs.test.ts. * * SSR-safe: no window access at module load; the listeners are only attached * when a window exists, and `dispose()` removes them. * * @example * const outbox = createOutbox({ actions: ['cart*', 'order*'] }); * const bus = createAsyncCommandBus({ transport: httpTransport({ endpoint: '/api/vc' }), outbox }); * const result = await bus.dispatch('cartAdd', { id: 1 }, { qty: 2 }); * if (result.ok && result.value instanceof Accepted) { * toast(`Saved offline - ${outbox.pending.value} pending`); * const end = await result.value.done; // the server's answer, once sent * } */ export declare function createOutbox(options?: OutboxOptions): Outbox; //# sourceMappingURL=outbox.d.ts.map