@demlik/tea 0.1.1 → 0.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent/index.d.ts +2 -2
- package/dist/agent/index.js +8 -8
- package/dist/authed-call/index.d.ts +3 -3
- package/dist/authed-call/index.js +5 -5
- package/dist/await-terminal/index.d.ts +1 -1
- package/dist/await-terminal/index.js +2 -2
- package/dist/batch-window/index.d.ts +2 -2
- package/dist/batch-window/index.js +4 -4
- package/dist/cache/index.d.ts +2 -2
- package/dist/{chunk-RVJFGRGK.js → chunk-27N2SPTN.js} +4 -4
- package/dist/chunk-27N2SPTN.js.map +1 -0
- package/dist/{chunk-FH5RUIIL.js → chunk-3XJWC7VW.js} +3 -3
- package/dist/{chunk-FH5RUIIL.js.map → chunk-3XJWC7VW.js.map} +1 -1
- package/dist/{chunk-IFBQJYGI.js → chunk-5DEQ5I3U.js} +3 -3
- package/dist/{chunk-IFBQJYGI.js.map → chunk-5DEQ5I3U.js.map} +1 -1
- package/dist/{chunk-XRXKH7KA.js → chunk-6RGBKODV.js} +3 -3
- package/dist/{chunk-XRXKH7KA.js.map → chunk-6RGBKODV.js.map} +1 -1
- package/dist/{chunk-D5EQDLDV.js → chunk-7W4LMPUW.js} +4 -4
- package/dist/{chunk-D5EQDLDV.js.map → chunk-7W4LMPUW.js.map} +1 -1
- package/dist/{chunk-A56GNPI7.js → chunk-DILMKOZ7.js} +5 -23
- package/dist/chunk-DILMKOZ7.js.map +1 -0
- package/dist/{chunk-EIZJTYKR.js → chunk-EHIX7NYZ.js} +4 -4
- package/dist/{chunk-EIZJTYKR.js.map → chunk-EHIX7NYZ.js.map} +1 -1
- package/dist/{chunk-WUV3PSCZ.js → chunk-HCEVHFJ7.js} +2 -2
- package/dist/chunk-HCEVHFJ7.js.map +1 -0
- package/dist/{chunk-EQRUAP2A.js → chunk-J6527VRQ.js} +2 -2
- package/dist/chunk-J6527VRQ.js.map +1 -0
- package/dist/{chunk-QGZW4W3E.js → chunk-K7Q23EQ4.js} +3 -3
- package/dist/{chunk-QGZW4W3E.js.map → chunk-K7Q23EQ4.js.map} +1 -1
- package/dist/{chunk-RGTPPF4U.js → chunk-LP7VQBRG.js} +3 -3
- package/dist/{chunk-RGTPPF4U.js.map → chunk-LP7VQBRG.js.map} +1 -1
- package/dist/{chunk-2WZHS4P2.js → chunk-MMH7CW5K.js} +4 -16
- package/dist/chunk-MMH7CW5K.js.map +1 -0
- package/dist/{chunk-EDGDR5XX.js → chunk-ON24RKSE.js} +3 -3
- package/dist/{chunk-EDGDR5XX.js.map → chunk-ON24RKSE.js.map} +1 -1
- package/dist/{chunk-TAO4YOLO.js → chunk-PS23H6KQ.js} +3 -3
- package/dist/{chunk-TAO4YOLO.js.map → chunk-PS23H6KQ.js.map} +1 -1
- package/dist/{chunk-BNJYE4AU.js → chunk-QLA76GIT.js} +21 -16
- package/dist/chunk-QLA76GIT.js.map +1 -0
- package/dist/{chunk-TC4HWABA.js → chunk-S3FQN4SL.js} +7 -7
- package/dist/{chunk-TC4HWABA.js.map → chunk-S3FQN4SL.js.map} +1 -1
- package/dist/{chunk-RVU3RBE6.js → chunk-SQTCS44W.js} +6 -4
- package/dist/chunk-SQTCS44W.js.map +1 -0
- package/dist/{chunk-7VEG4KHB.js → chunk-VLGARN6H.js} +3 -3
- package/dist/{chunk-7VEG4KHB.js.map → chunk-VLGARN6H.js.map} +1 -1
- package/dist/{core-CymXZCeY.d.ts → core-BoB6t7dB.d.ts} +11 -1
- package/dist/deadline/index.d.ts +2 -2
- package/dist/deadline/index.js +3 -3
- package/dist/debounce/index.d.ts +6 -0
- package/dist/debounce/index.js +1 -1
- package/dist/do/index.d.ts +15 -24
- package/dist/do/index.js +9 -13
- package/dist/do/index.js.map +1 -1
- package/dist/{durable-effects-2MDxDs45.d.ts → durable-effects-CO9Uh971.d.ts} +1 -1
- package/dist/extension/index.d.ts +1 -1
- package/dist/extension/index.js +3 -3
- package/dist/extension/react.js +3 -3
- package/dist/extension/subs/index.d.ts +2 -2
- package/dist/fan-out/index.d.ts +1 -1
- package/dist/idempotent-intake/index.d.ts +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.js +2 -2
- package/dist/llm-call/index.d.ts +2 -2
- package/dist/llm-call/index.js +5 -5
- package/dist/machine-viz/index.d.ts +4 -4
- package/dist/machine-viz/index.js +4 -8
- package/dist/machine-viz/index.js.map +1 -1
- package/dist/mem/index.d.ts +1 -1
- package/dist/monitored-run/index.d.ts +2 -2
- package/dist/monitored-run/index.js +5 -5
- package/dist/node/index.d.ts +1 -1
- package/dist/paginated-walk/index.d.ts +2 -2
- package/dist/paginated-walk/index.js +5 -5
- package/dist/parity/index.d.ts +10 -4
- package/dist/parity/index.js +6 -5
- package/dist/parity/index.js.map +1 -1
- package/dist/pbt/arbitraries/index.d.ts +1 -1
- package/dist/pbt/index.d.ts +15 -8
- package/dist/pbt/index.js +5 -11
- package/dist/pbt/index.js.map +1 -1
- package/dist/pbt/runners/index.d.ts +1 -1
- package/dist/pbt/runners/index.js +3 -3
- package/dist/poller/index.d.ts +2 -2
- package/dist/poller/index.js +3 -3
- package/dist/prediction/index.d.ts +23 -2
- package/dist/prediction/index.js +2 -2
- package/dist/pure/index.d.ts +2 -2
- package/dist/pure/index.js +2 -2
- package/dist/raft/demo.d.ts +2 -2
- package/dist/raft/demo.js +5 -5
- package/dist/raft/index.d.ts +3 -3
- package/dist/raft/index.js +4 -4
- package/dist/raft/sim.d.ts +2 -2
- package/dist/raft/sim.js +5 -5
- package/dist/raft/timeline.d.ts +2 -2
- package/dist/react/index.d.ts +1 -1
- package/dist/react/index.js +8 -4
- package/dist/react/index.js.map +1 -1
- package/dist/reconciler/index.d.ts +2 -2
- package/dist/reconciler/index.js +5 -5
- package/dist/recorder/index.d.ts +1 -1
- package/dist/resilient-call/index.d.ts +45 -2
- package/dist/resilient-call/index.js +4 -4
- package/dist/retry-to-success/index.d.ts +109 -0
- package/dist/retry-to-success/index.js +35 -0
- package/dist/retry-to-success/index.js.map +1 -0
- package/dist/saga/index.d.ts +14 -1
- package/dist/saga/index.js.map +1 -1
- package/dist/snapshot/index.d.ts +1 -1
- package/dist/snapshot/index.js +3 -3
- package/dist/subs/index.d.ts +2 -2
- package/dist/testing/index.d.ts +1 -1
- package/dist/testing/index.js +2 -2
- package/dist/throttle/index.d.ts +9 -0
- package/dist/throttle/index.js +1 -1
- package/dist/throttled-input/index.d.ts +10 -2
- package/dist/throttled-input/index.js +6 -6
- package/dist/throttled-input/index.js.map +1 -1
- package/dist/token-refresh/index.d.ts +1 -1
- package/dist/token-refresh/index.js +3 -3
- package/dist/trace-replay/index.d.ts +1 -1
- package/dist/trace-replay/index.js +3 -3
- package/dist/{types-N9LZbdnr.d.ts → types-B-8bcAp8.d.ts} +1 -1
- package/dist/with-deadline/index.d.ts +1 -1
- package/dist/with-deadline/index.js +5 -24
- package/dist/with-deadline/index.js.map +1 -1
- package/dist/with-resilience/index.d.ts +2 -2
- package/dist/with-resilience/index.js +13 -36
- package/dist/with-resilience/index.js.map +1 -1
- package/dist/with-telemetry/index.d.ts +1 -1
- package/dist/with-telemetry/index.js +4 -29
- package/dist/with-telemetry/index.js.map +1 -1
- package/dist/work-queue/adapter.d.ts +1 -1
- package/dist/work-queue/index.d.ts +1 -1
- package/dist/work-queue/ops.d.ts +1 -1
- package/dist/workflow/index.d.ts +16 -10
- package/dist/workflow/index.js.map +1 -1
- package/package.json +8 -2
- package/dist/chunk-2WZHS4P2.js.map +0 -1
- package/dist/chunk-A56GNPI7.js.map +0 -1
- package/dist/chunk-BNJYE4AU.js.map +0 -1
- package/dist/chunk-EQRUAP2A.js.map +0 -1
- package/dist/chunk-RVJFGRGK.js.map +0 -1
- package/dist/chunk-RVU3RBE6.js.map +0 -1
- package/dist/chunk-WUV3PSCZ.js.map +0 -1
package/dist/saga/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/saga/index.ts"],"names":[],"mappings":";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AA,CAAM,KAAA,EAAO,KAAA,CAAM,UAAU,QAAQ,CAAA;AAC7D,IAAA,OAAO;AAAA,MACL;AAAA,QACE,GAAG,KAAA;AAAA,QACH,KAAA;AAAA,QACA,iBAAA,EAAmB,KAAA;AAAA,QACnB,KAAA,EAAO;AAAA,OACT;AAAA,MACA;AAAC,KACH;AAAA,EACF;AAEA,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,QAAA;AAAA,IACN,KAAA;AAAA,IACA,MAAA;AAAA,IACA,OAAA;AAAA,IACA,MAAA;AAAA,IACA,OAAA;AAAA,IACA,WAAA;AAAA,IACA,SAAA;AAAA,IACA,oBAAA;AAAA,IACA;AAAA,GACF;AACF","file":"index.js","sourcesContent":["/**\n * @demlik/tea/saga — a forward-then-compensate transaction over an ordered list\n * of reversible steps.\n *\n * The Level-2 combinator for \"run these N steps in order; if any step fails,\n * undo the steps that already succeeded, in reverse.\" It is the distributed-\n * transaction / compensation knob: each step is a `{ do, undo }` pair of Cmds,\n * the saga drives `do` forward one step at a time, and on the first failure it\n * pivots and drives `undo` backward over exactly the steps that completed.\n *\n * The recipe (which bricks it composes):\n * - `../work-queue/adapter` — the saga's forward progress IS a work-queue\n * lifecycle. Each step's record carries the same `{ id, status, input }`\n * vocabulary (`pending → running → done | failed | cancelled`), so the step\n * taxonomy is the substrate's status enum rather than a parallel invention.\n * We reuse the pure `QueueItem` / `QueueItemStatus` types AND delegate every\n * status flip to the `QueueAdapter` verbs: `wq.enqueue` stamps each fresh\n * ledger record, and `wq.patch` performs every\n * `pending → running → done | failed | cancelled` transition. The status\n * transitions are NOT re-rolled here — they live in exactly one place\n * behind the adapter, per the package's one-shape rule. The async\n * `createQueue(store)` adapter is NOT used: its `load → mutate → save` reads\n * the clock and lives at an I/O boundary, while a combinator's verbs must be\n * pure (invariant 2). We bind the same ops to the in-Model ledger instead —\n * durable + replayable, the two non-negotiables every knob preserves.\n *\n * The compensation log is the spec's `done: StepId[]` — the indices of the\n * steps that completed forward, in the order they completed. On `stepErr` the\n * saga walks that log in reverse, emitting one `undo` per `undoOk`, so the\n * unwind is the exact mirror of the wind. If an `undo` ITSELF fails, `undoErr`\n * pivots to the terminal `compensation_failed` phase: a failed compensation is\n * a real-world fact (a refund that bounced, a hold that won't release) that the\n * consumer must see and reconcile by hand — never a saga wedged in\n * `compensating` forever.\n *\n * Typical wiring (combinator form — splice the hooks into your machine):\n *\n * const saga = createSaga<BookFlight | ChargeCard | ..., Cancel | Refund | ...>({\n * steps: [\n * { do: { type: \"book_flight\" }, undo: { type: \"cancel_flight\" } },\n * { do: { type: \"charge_card\" }, undo: { type: \"refund_card\" } },\n * { do: { type: \"reserve_hotel\" },undo: { type: \"release_hotel\" } },\n * ],\n * });\n *\n * // in `update`:\n * begin: (s) => lift(s, saga.start(s.saga)),\n * step_ok: (s) => lift(s, saga.stepOk(s.saga)),\n * step_err: (s, m) => lift(s, saga.stepErr(s.saga, m.error)),\n * undo_ok: (s) => lift(s, saga.undoOk(s.saga)),\n * undo_err: (s, m) => lift(s, saga.undoErr(s.saga, m.error)),\n *\n * Every verb is PURE: it returns a NEW slice plus the Cmds to perform (the next\n * `do` going forward, or the next `undo` rolling back). The reducer never reads\n * a clock or RNG — step identity is positional (the index into `config.steps`),\n * so progress survives a round-trip through the durable slice and resumes\n * exactly where it left off after a DO eviction.\n *\n * There is no `subs` and no `handlers`: a saga runs no timers, and the `do` /\n * `undo` Cmds are fully caller-defined (the consumer's own `interpret` performs\n * each effect and routes Ok/Err back to the `stepOk` / `stepErr` / `undoOk`\n * verbs — the same shape `resilient-fetch` uses with `tryInterpret`). The saga\n * owns the ORDER; the consumer owns the I/O. Pure-ops module, like\n * `retry-backoff`.\n *\n * NOT a substrate primitive: it depends only on `../work-queue`'s pure types\n * and `../index`'s `Cmd` type. Consumers reach it via the `@demlik/tea/saga`\n * subpath.\n */\n\nimport type { Cmd } from \"../index\";\nimport type { QueueItem, QueueItemStatus } from \"../work-queue\";\nimport { queueAdapter } from \"../work-queue/adapter\";\n\n/**\n * A step's stable identity. Positional: the 0-based index into\n * `config.steps`. Positional ids are PURE (no clock, no RNG) and survive a\n * round-trip through the durable slice, so `done` can be replayed to resume an\n * interrupted saga exactly. The compensation log is a list of these.\n */\nexport type StepId = number;\n\n/**\n * One step of the saga: the forward effect and its compensating inverse, both\n * as data (plain Cmds). `do` runs while winding forward; `undo` runs while\n * unwinding after a failure. The pair is the unit of reversibility — a step\n * that completed (`do` succeeded) is exactly a step whose `undo` must run if a\n * later step fails.\n */\nexport interface SagaStep<D extends Cmd, U extends Cmd> {\n /** The forward effect, performed while the saga winds forward. */\n readonly do: D;\n /** The compensating inverse, performed (in reverse) while the saga unwinds. */\n readonly undo: U;\n}\n\n/**\n * The knob. The ordered list of reversible steps. The list is fixed for the\n * life of one saga instance (a saga drives a known transaction); per-run inputs\n * ride on the consumer's Msgs, not here.\n */\nexport interface SagaConfig<D extends Cmd, U extends Cmd> {\n /** The steps, in forward order. `do` runs `0 → n-1`; `undo` runs the completed prefix `n-1 → 0`. */\n readonly steps: readonly SagaStep<D, U>[];\n}\n\n/**\n * The lifecycle phase of a saga, narrowed at the type level so a consumer can\n * branch on `state.phase` (and a Transitions-table reducer can key on it).\n *\n * - `\"idle\"` — created, not started. No step has run.\n * - `\"running\"` — winding forward; `position` is the in-flight step.\n * - `\"compensating\"` — a step failed; unwinding `done` in reverse.\n * - `\"committed\"` — every step completed forward. Terminal success.\n * - `\"aborted\"` — compensation finished (every completed step undone, or\n * the first step itself failed with nothing to undo).\n * Terminal failure, fully unwound.\n * - `\"compensation_failed\"` — an `undo` itself failed mid-rollback. Terminal\n * failure, PARTIALLY unwound: the steps still in `done`\n * were never compensated and must be reconciled by hand.\n * Distinguished from `aborted` precisely so a stuck\n * rollback is visible state, not a saga wedged in\n * `compensating` forever.\n */\nexport type SagaPhase =\n | \"idle\"\n | \"running\"\n | \"compensating\"\n | \"committed\"\n | \"aborted\"\n | \"compensation_failed\";\n\n/**\n * The slice this knob owns.\n *\n * The spec's three fields are load-bearing:\n * - `position` — the index of the step currently in flight while `running`,\n * or the index being compensated while `compensating`. Survives eviction,\n * so `boot` resumes mid-saga from the durable slice.\n * - `done` — the compensation log: the ids of steps that completed forward,\n * in completion order. `undo` walks this in reverse. This is the single\n * source of truth for what must be unwound.\n * - `compensating` — the direction bit. `false` while winding forward, `true`\n * once a failure has pivoted the saga into rollback.\n *\n * Plus:\n * - `phase` — the derived lifecycle tag (see `SagaPhase`). Kept in the slice\n * (not recomputed) so a consumer's view and Transitions reducer can key on\n * `state.phase` directly, and the terminal states (`committed` / `aborted`)\n * are explicit facts rather than \"position past the end\" arithmetic.\n * - `error` — the forward failure that triggered compensation, carried\n * forward verbatim (`unknown`) for the consumer to read, never interpreted\n * (same discipline as `retry-backoff`'s `lastError` and `fan-out`'s\n * `error`).\n * - `compensationError` — the failure of an `undo` itself, set only when the\n * saga reaches `compensation_failed`. Kept distinct from `error` (the\n * forward failure) so a consumer reconciling a stuck rollback can read both\n * \"what broke the transaction\" and \"which compensation then bounced\".\n * Carried verbatim, never interpreted, same as `error`.\n * - `items` — the work-queue ledger, one `QueueItem` per step, keyed by the\n * step's positional id. The single source of truth for each step's status;\n * `phase` / `position` / `done` are the projection the verbs keep in\n * lockstep with it.\n *\n * Every field is `readonly` and JSON-serializable (plain numbers, arrays, and\n * the work-queue's plain `QueueItem` records), so the slice round-trips through\n * a consumer's `Store<S>` unchanged — durable across DO eviction.\n */\nexport interface SagaState<I = StepId> {\n /** The step in flight (`running`) or being compensated (`compensating`). */\n readonly position: number;\n /** The compensation log: ids of completed-forward steps, in completion order. */\n readonly done: readonly StepId[];\n /** Direction bit: `false` winding forward, `true` unwinding. */\n readonly compensating: boolean;\n /** The derived lifecycle tag (see `SagaPhase`). */\n readonly phase: SagaPhase;\n /** The forward failure that triggered compensation, if any. Carried, never interpreted. */\n readonly error?: unknown;\n /** The failure of an `undo` itself (only when `compensation_failed`). Carried, never interpreted. */\n readonly compensationError?: unknown;\n /** The work-queue ledger: one record per step, keyed by positional id. */\n readonly items: readonly QueueItem<I>[];\n}\n\n/** Whether the saga has terminated successfully (every step committed). */\nexport function isCommitted<I>(state: SagaState<I>): boolean {\n return state.phase === \"committed\";\n}\n\n/** Whether the saga has terminated in failure, fully unwound (every completed step undone). */\nexport function isAborted<I>(state: SagaState<I>): boolean {\n return state.phase === \"aborted\";\n}\n\n/**\n * Whether the saga has terminated in failure with an UNFINISHED rollback: an\n * `undo` itself failed, so some completed steps were never compensated and need\n * hand reconciliation. Terminal, but distinct from `aborted` (fully unwound).\n */\nexport function isCompensationFailed<I>(state: SagaState<I>): boolean {\n return state.phase === \"compensation_failed\";\n}\n\n/**\n * Whether the saga has reached a terminal phase (success, fully-unwound\n * failure, or compensation-failed). Derived — reads the slice, never mutates.\n * Consumers branch their own phase off this; no further verb has any effect\n * once it holds (the verbs guard on phase and no-op).\n */\nexport function isSettled<I>(state: SagaState<I>): boolean {\n return (\n state.phase === \"committed\" ||\n state.phase === \"aborted\" ||\n state.phase === \"compensation_failed\"\n );\n}\n\n/**\n * The starting slice: idle, nothing run, winding-forward direction. `items` is\n * empty until `start` stamps one ledger record per configured step — the slice\n * is generic in the ledger payload `I`, defaulting to the positional `StepId`\n * since a saga's \"input\" per step is just its index (the consumer's real inputs\n * ride on its own Msgs).\n */\nexport function initSaga<I = StepId>(): SagaState<I> {\n return {\n position: 0,\n done: [],\n compensating: false,\n phase: \"idle\",\n items: [],\n };\n}\n\n/**\n * Build the saga knob from `config`. Returns the uniform combinator contract:\n * `init` for the owned slice and the five lifecycle verbs (`start`, `stepOk`,\n * `stepErr`, `undoOk`, `undoErr`).\n *\n * No `subs` and no `handlers` — a saga runs no timers, and each step's `do` /\n * `undo` effect is owned by the consumer's `interpret` (the saga emits the Cmd;\n * the consumer performs it and routes the outcome back to a verb). The saga's\n * sole job is the ORDER: which Cmd to emit next, and when to pivot from winding\n * to unwinding (and when a failed `undo` ends the rollback). Pure-ops module —\n * matches `retry-backoff`'s shape.\n */\nexport function createSaga<D extends Cmd, U extends Cmd>(\n config: SagaConfig<D, U>,\n) {\n // The ledger seam, bound once. The saga delegates ledger construction to\n // `wq.enqueue` and every status flip to `wq.patch`, so the `QueueItem<StepId>`\n // shape stays insulated behind the verbs.\n const wq = queueAdapter<StepId>();\n\n /**\n * One ledger record per configured step, keyed by its positional id. Each\n * record is stamped by the `QueueAdapter`'s `enqueue` (the saga delegates\n * ledger construction to the verb rather than building records inline).\n *\n * The positional id is stringified — `QueueItem.id` is a string, the saga's\n * step identity is the index; `String(index)` keeps both the ledger's\n * string-id contract and the positional identity. `enqueuedAt` is `0`: saga\n * verbs are pure and the saga makes no timestamp-based decision (ordering is\n * positional), so there is no clock to read here.\n */\n function freshLedger(): QueueItem<StepId>[] {\n let items: QueueItem<StepId>[] = [];\n config.steps.forEach((_step, index) => {\n items = wq.enqueue(items, index, 0, String(index)).next;\n });\n return items;\n }\n\n /**\n * Flip the ledger record for step `index` to `status`, delegating the\n * transition to the `QueueAdapter`'s `patch` (keyed by the record's string\n * id, `String(index)`) so the status flip is NOT re-rolled here. PURE —\n * `patch` returns a new array; an unknown id returns a copy unchanged (the\n * verbs guard against out-of-range, but the helper is total).\n */\n function setStatus(\n items: readonly QueueItem<StepId>[],\n index: number,\n status: QueueItemStatus,\n ): QueueItem<StepId>[] {\n return wq.patch(items, String(index), (item) => ({\n ...item,\n status,\n })).next;\n }\n\n /**\n * The step at `index`, or `undefined` if out of range. Centralizes the bounds\n * check so the verbs read a step through a narrowing guard instead of a\n * non-null assertion: `const step = stepAt(i); if (step === undefined) …`.\n */\n function stepAt(index: number): SagaStep<D, U> | undefined {\n return config.steps[index];\n }\n\n /** The most-recently-completed step id (tail of `done`), or `undefined` if the log is empty. */\n function lastDone(done: readonly StepId[]): StepId | undefined {\n return done[done.length - 1];\n }\n\n /**\n * Begin the saga: stamp a `pending` ledger record per step, mark step 0\n * `running`, and emit step 0's `do` Cmd. PURE.\n *\n * A saga with zero configured steps commits immediately (nothing to do, so\n * the empty transaction trivially succeeds) and emits no Cmd. Calling `start`\n * on an already-started saga (phase ≠ `\"idle\"`) is a no-op: the slice is\n * returned unchanged with no Cmds, so a stray re-`start` after a boot/replay\n * can't relaunch step 0 on top of an in-flight saga.\n */\n function start(\n state: SagaState<StepId>,\n ): readonly [SagaState<StepId>, readonly D[]] {\n if (state.phase !== \"idle\") return [state, []];\n\n const items = freshLedger();\n const first = stepAt(0);\n if (first === undefined) {\n // Empty transaction: trivially committed, no effect.\n return [{ ...state, phase: \"committed\", items }, []];\n }\n\n const next: SagaState<StepId> = {\n ...state,\n position: 0,\n phase: \"running\",\n items: setStatus(items, 0, \"running\"),\n };\n return [next, [first.do]];\n }\n\n /**\n * Record the in-flight step as committed and advance. PURE.\n *\n * Flips the current step's ledger record `running → done`, appends its id to\n * the compensation log, and:\n * - if a next step exists, marks it `running` and emits its `do` Cmd;\n * - if this was the last step, transitions to `committed` (terminal\n * success) and emits no Cmd.\n *\n * `stepOk` while not `running` (idle, compensating, or already terminal) is a\n * no-op — the runtime's serial dispatch makes a true double-`stepOk`\n * impossible, but a stale success Msg after a boot/replay is real, and\n * swallowing it is the safe direction (the step's outcome is already recorded\n * in the ledger).\n */\n function stepOk(\n state: SagaState<StepId>,\n ): readonly [SagaState<StepId>, readonly D[]] {\n if (state.phase !== \"running\") return [state, []];\n\n const completed = state.position;\n const itemsDone = setStatus(state.items, completed, \"done\");\n const done = [...state.done, completed];\n const nextPosition = completed + 1;\n const nextStep = stepAt(nextPosition);\n\n if (nextStep === undefined) {\n // No next step — the last step committed, so the whole transaction\n // succeeded.\n return [{ ...state, done, items: itemsDone, phase: \"committed\" }, []];\n }\n\n const next: SagaState<StepId> = {\n ...state,\n position: nextPosition,\n done,\n items: setStatus(itemsDone, nextPosition, \"running\"),\n };\n return [next, [nextStep.do]];\n }\n\n /**\n * Pivot from winding to unwinding: the in-flight step failed. PURE.\n *\n * Flips the failed step's ledger record `running → failed`, records the\n * `error`, sets the direction bit, and begins compensation by emitting the\n * `undo` of the MOST-recently-completed step (the tail of the compensation\n * log) — rollback is the mirror of progress, so the last step that succeeded\n * is the first to be undone.\n *\n * If nothing completed forward (the first step itself failed), there is\n * nothing to compensate: the saga goes straight to `aborted` (terminal\n * failure) and emits no `undo`.\n *\n * `stepErr` while not `running` is a no-op (same stale-Msg reasoning as\n * `stepOk`): once a saga is already compensating or terminal, a late failure\n * Msg for an old step must not restart or re-pivot the unwind.\n */\n function stepErr(\n state: SagaState<StepId>,\n error: unknown,\n ): readonly [SagaState<StepId>, readonly U[]] {\n if (state.phase !== \"running\") return [state, []];\n\n const failed = state.position;\n const items = setStatus(state.items, failed, \"failed\");\n\n // Compensate the most-recently-completed step first. `lastDone === undefined`\n // means nothing completed forward (the first step itself failed) — there is\n // nothing to undo, so the saga aborts straight away. The guard narrows\n // `undoIndex` to `StepId` and `undoStep` to a present step without a\n // non-null assertion.\n const undoIndex = lastDone(state.done);\n const undoStep = undoIndex === undefined ? undefined : stepAt(undoIndex);\n if (undoIndex === undefined || undoStep === undefined) {\n return [\n { ...state, items, error, compensating: true, phase: \"aborted\" },\n [],\n ];\n }\n\n const next: SagaState<StepId> = {\n ...state,\n items,\n error,\n compensating: true,\n phase: \"compensating\",\n position: undoIndex,\n };\n return [next, [undoStep.undo]];\n }\n\n /**\n * Continue the rollback: the `undo` for the current compensation position\n * succeeded. PURE.\n *\n * Pops the just-undone step off the tail of the compensation log (flipping\n * its ledger record `done → cancelled` to mark it rolled back), and:\n * - if more completed steps remain, emits the next one's `undo` (continuing\n * in reverse) and moves `position` to it;\n * - if the log is now empty, transitions to `aborted` (terminal failure —\n * the saga is fully unwound) and emits no Cmd.\n *\n * `undoOk` while not `compensating` is a no-op (same stale-Msg reasoning as\n * the forward verbs): an `undo`-success Msg that arrives after the saga has\n * already finished unwinding must not pop a step that isn't there.\n */\n function undoOk(\n state: SagaState<StepId>,\n ): readonly [SagaState<StepId>, readonly U[]] {\n if (state.phase !== \"compensating\") return [state, []];\n\n // The tail of the log is the step we just compensated — mark it cancelled.\n // `undone === undefined` cannot happen while `compensating` (the phase is\n // only entered with a non-empty log), but the guard keeps the lookup total\n // and narrows `undone` to `StepId` without a non-null assertion.\n const undone = lastDone(state.done);\n if (undone === undefined) return [state, []];\n const remaining = state.done.slice(0, -1);\n const items = setStatus(state.items, undone, \"cancelled\");\n\n // The next step to compensate is the new tail of the log. `nextUndo`\n // narrows to `StepId` here and to a present step via `stepAt`, so the\n // continue-vs-terminate branch needs no non-null assertion.\n const nextUndo = lastDone(remaining);\n const nextStep = nextUndo === undefined ? undefined : stepAt(nextUndo);\n if (nextUndo === undefined || nextStep === undefined) {\n // Fully unwound — terminal failure.\n return [{ ...state, done: remaining, items, phase: \"aborted\" }, []];\n }\n\n const next: SagaState<StepId> = {\n ...state,\n done: remaining,\n items,\n position: nextUndo,\n };\n return [next, [nextStep.undo]];\n }\n\n /**\n * Halt the rollback: the `undo` for the current compensation position itself\n * FAILED. PURE.\n *\n * A failed compensation is a real-world fact — a refund that bounced, a hold\n * that won't release — and it must become visible terminal state, never leave\n * the saga wedged in `compensating` forever waiting for an `undoOk` that will\n * never come. So `undoErr`:\n * - flips the in-flight compensation step's ledger record `done → failed`\n * (its `undo` did not take, so it is NOT `cancelled`);\n * - records the undo failure in `compensationError` (distinct from `error`,\n * the forward failure that started the rollback);\n * - transitions to the terminal `compensation_failed` phase and emits no\n * Cmd. The compensation log is LEFT INTACT (`done` keeps the steps that\n * were never rolled back) so the consumer can see exactly which steps\n * still need hand reconciliation.\n *\n * `undoErr` while not `compensating` is a no-op (same stale-Msg reasoning as\n * the other verbs): an `undo`-failure Msg that arrives after the saga has\n * already settled must not re-pivot a terminal saga.\n */\n function undoErr(\n state: SagaState<StepId>,\n error: unknown,\n ): readonly [SagaState<StepId>, readonly U[]] {\n if (state.phase !== \"compensating\") return [state, []];\n\n // The step whose `undo` just failed is the current compensation position.\n // Its forward effect stands un-reversed, so its record goes `done → failed`,\n // not `cancelled`.\n const items = setStatus(state.items, state.position, \"failed\");\n return [\n {\n ...state,\n items,\n compensationError: error,\n phase: \"compensation_failed\",\n },\n [],\n ];\n }\n\n return {\n init: initSaga<StepId>,\n start,\n stepOk,\n stepErr,\n undoOk,\n undoErr,\n isCommitted,\n isAborted,\n isCompensationFailed,\n isSettled,\n };\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/saga/index.ts"],"names":[],"mappings":";;;;AAuMO,SAAS,YAAe,KAAA,EAA8B;AAC3D,EAAA,OAAO,MAAM,KAAA,KAAU,WAAA;AACzB;AAGO,SAAS,UAAa,KAAA,EAA8B;AACzD,EAAA,OAAO,MAAM,KAAA,KAAU,SAAA;AACzB;AAOO,SAAS,qBAAwB,KAAA,EAA8B;AACpE,EAAA,OAAO,MAAM,KAAA,KAAU,qBAAA;AACzB;AAQO,SAAS,UAAa,KAAA,EAA8B;AACzD,EAAA,OACE,MAAM,KAAA,KAAU,WAAA,IAChB,MAAM,KAAA,KAAU,SAAA,IAChB,MAAM,KAAA,KAAU,qBAAA;AAEpB;AASO,SAAS,QAAA,GAAqC;AACnD,EAAA,OAAO;AAAA,IACL,QAAA,EAAU,CAAA;AAAA,IACV,MAAM,EAAC;AAAA,IACP,YAAA,EAAc,KAAA;AAAA,IACd,KAAA,EAAO,MAAA;AAAA,IACP,OAAO;AAAC,GACV;AACF;AAcO,SAAS,WACd,MAAA,EACA;AAIA,EAAA,MAAM,KAAK,YAAA,EAAqB;AAahC,EAAA,SAAS,WAAA,GAAmC;AAC1C,IAAA,IAAI,QAA6B,EAAC;AAClC,IAAA,MAAA,CAAO,KAAA,CAAM,OAAA,CAAQ,CAAC,KAAA,EAAO,KAAA,KAAU;AACrC,MAAA,KAAA,GAAQ,EAAA,CAAG,QAAQ,KAAA,EAAO,KAAA,EAAO,GAAG,MAAA,CAAO,KAAK,CAAC,CAAA,CAAE,IAAA;AAAA,IACrD,CAAC,CAAA;AACD,IAAA,OAAO,KAAA;AAAA,EACT;AASA,EAAA,SAAS,SAAA,CACP,KAAA,EACA,KA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AAC,IAAA,EAAM,CAAC,QAAA,CAAS,IAAI,CAAC,CAAA;AAAA,EAC/B;AAuBA,EAAA,SAAS,OAAA,CACP,OACA,KAAA,EAC4C;AAC5C,IAAA,IAAI,MAAM,KAAA,KAAU,cAAA,SAAuB,CAAC,KAAA,EAAO,EAAE,CAAA;AAKrD,IAAA,MAAM,QAAQ,SAAA,CAAU,KAAA,CAAM,KAAA,EAAO,KAAA,CAAM,UAAU,QAAQ,CAAA;AAC7D,IAAA,OAAO;AAAA,MACL;AAAA,QACE,GAAG,KAAA;AAAA,QACH,KAAA;AAAA,QACA,iBAAA,EAAmB,KAAA;AAAA,QACnB,KAAA,EAAO;AAAA,OACT;AAAA,MACA;AAAC,KACH;AAAA,EACF;AAEA,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,QAAA;AAAA,IACN,KAAA;AAAA,IACA,MAAA;AAAA,IACA,OAAA;AAAA,IACA,MAAA;AAAA,IACA,OAAA;AAAA,IACA,WAAA;AAAA,IACA,SAAA;AAAA,IACA,oBAAA;AAAA,IACA;AAAA,GACF;AACF","file":"index.js","sourcesContent":["/**\n * @demlik/tea/saga — a forward-then-compensate transaction over an ordered list\n * of reversible steps.\n *\n * The Level-2 combinator for \"run these N steps in order; if any step fails,\n * undo the steps that already succeeded, in reverse.\" It is the distributed-\n * transaction / compensation knob: each step is a `{ do, undo }` pair of Cmds,\n * the saga drives `do` forward one step at a time, and on the first failure it\n * pivots and drives `undo` backward over exactly the steps that completed.\n *\n * **Boundary with `@demlik/tea/workflow` — the compensation test.** Both drive\n * an ordered multi-step transaction with reverse-order compensation; the line\n * between them is whether every step carries a true inverse. Here\n * `SagaStep<D, U>` REQUIRES both `do` and `undo` — a step without its inverse\n * is unrepresentable, so full reversibility is a type-level guarantee.\n * Workflow's `WorkflowStep.compensation` is OPTIONAL — an irreversible step (a\n * sent email) is skipped during the unwind. Pick by the test: **every step\n * must be reversible → saga; some steps are irreversible but the run must\n * finish → workflow.** Cross to workflow when the transaction includes steps\n * that can't be undone (or when you want each activity recorded as a durable\n * owed effect on the `../do` ledger); stay here when the type system should\n * enforce that every step can be undone.\n *\n * The recipe (which bricks it composes):\n * - `../work-queue/adapter` — the saga's forward progress IS a work-queue\n * lifecycle. Each step's record carries the same `{ id, status, input }`\n * vocabulary (`pending → running → done | failed | cancelled`), so the step\n * taxonomy is the substrate's status enum rather than a parallel invention.\n * We reuse the pure `QueueItem` / `QueueItemStatus` types AND delegate every\n * status flip to the `QueueAdapter` verbs: `wq.enqueue` stamps each fresh\n * ledger record, and `wq.patch` performs every\n * `pending → running → done | failed | cancelled` transition. The status\n * transitions are NOT re-rolled here — they live in exactly one place\n * behind the adapter, per the package's one-shape rule. The async\n * `createQueue(store)` adapter is NOT used: its `load → mutate → save` reads\n * the clock and lives at an I/O boundary, while a combinator's verbs must be\n * pure (invariant 2). We bind the same ops to the in-Model ledger instead —\n * durable + replayable, the two non-negotiables every knob preserves.\n *\n * The compensation log is the spec's `done: StepId[]` — the indices of the\n * steps that completed forward, in the order they completed. On `stepErr` the\n * saga walks that log in reverse, emitting one `undo` per `undoOk`, so the\n * unwind is the exact mirror of the wind. If an `undo` ITSELF fails, `undoErr`\n * pivots to the terminal `compensation_failed` phase: a failed compensation is\n * a real-world fact (a refund that bounced, a hold that won't release) that the\n * consumer must see and reconcile by hand — never a saga wedged in\n * `compensating` forever.\n *\n * Typical wiring (combinator form — splice the hooks into your machine):\n *\n * const saga = createSaga<BookFlight | ChargeCard | ..., Cancel | Refund | ...>({\n * steps: [\n * { do: { type: \"book_flight\" }, undo: { type: \"cancel_flight\" } },\n * { do: { type: \"charge_card\" }, undo: { type: \"refund_card\" } },\n * { do: { type: \"reserve_hotel\" },undo: { type: \"release_hotel\" } },\n * ],\n * });\n *\n * // in `update`:\n * begin: (s) => lift(s, saga.start(s.saga)),\n * step_ok: (s) => lift(s, saga.stepOk(s.saga)),\n * step_err: (s, m) => lift(s, saga.stepErr(s.saga, m.error)),\n * undo_ok: (s) => lift(s, saga.undoOk(s.saga)),\n * undo_err: (s, m) => lift(s, saga.undoErr(s.saga, m.error)),\n *\n * Every verb is PURE: it returns a NEW slice plus the Cmds to perform (the next\n * `do` going forward, or the next `undo` rolling back). The reducer never reads\n * a clock or RNG — step identity is positional (the index into `config.steps`),\n * so progress survives a round-trip through the durable slice and resumes\n * exactly where it left off after a DO eviction.\n *\n * There is no `subs` and no `handlers`: a saga runs no timers, and the `do` /\n * `undo` Cmds are fully caller-defined (the consumer's own `interpret` performs\n * each effect and routes Ok/Err back to the `stepOk` / `stepErr` / `undoOk`\n * verbs — the same shape `resilient-fetch` uses with `tryInterpret`). The saga\n * owns the ORDER; the consumer owns the I/O. Pure-ops module, like\n * `retry-backoff`.\n *\n * NOT a substrate primitive: it depends only on `../work-queue`'s pure types\n * and `../index`'s `Cmd` type. Consumers reach it via the `@demlik/tea/saga`\n * subpath.\n */\n\nimport type { Cmd } from \"../index\";\nimport type { QueueItem, QueueItemStatus } from \"../work-queue\";\nimport { queueAdapter } from \"../work-queue/adapter\";\n\n/**\n * A step's stable identity. Positional: the 0-based index into\n * `config.steps`. Positional ids are PURE (no clock, no RNG) and survive a\n * round-trip through the durable slice, so `done` can be replayed to resume an\n * interrupted saga exactly. The compensation log is a list of these.\n */\nexport type StepId = number;\n\n/**\n * One step of the saga: the forward effect and its compensating inverse, both\n * as data (plain Cmds). `do` runs while winding forward; `undo` runs while\n * unwinding after a failure. The pair is the unit of reversibility — a step\n * that completed (`do` succeeded) is exactly a step whose `undo` must run if a\n * later step fails.\n */\nexport interface SagaStep<D extends Cmd, U extends Cmd> {\n /** The forward effect, performed while the saga winds forward. */\n readonly do: D;\n /** The compensating inverse, performed (in reverse) while the saga unwinds. */\n readonly undo: U;\n}\n\n/**\n * The knob. The ordered list of reversible steps. The list is fixed for the\n * life of one saga instance (a saga drives a known transaction); per-run inputs\n * ride on the consumer's Msgs, not here.\n */\nexport interface SagaConfig<D extends Cmd, U extends Cmd> {\n /** The steps, in forward order. `do` runs `0 → n-1`; `undo` runs the completed prefix `n-1 → 0`. */\n readonly steps: readonly SagaStep<D, U>[];\n}\n\n/**\n * The lifecycle phase of a saga, narrowed at the type level so a consumer can\n * branch on `state.phase` (and a Transitions-table reducer can key on it).\n *\n * - `\"idle\"` — created, not started. No step has run.\n * - `\"running\"` — winding forward; `position` is the in-flight step.\n * - `\"compensating\"` — a step failed; unwinding `done` in reverse.\n * - `\"committed\"` — every step completed forward. Terminal success.\n * - `\"aborted\"` — compensation finished (every completed step undone, or\n * the first step itself failed with nothing to undo).\n * Terminal failure, fully unwound.\n * - `\"compensation_failed\"` — an `undo` itself failed mid-rollback. Terminal\n * failure, PARTIALLY unwound: the steps still in `done`\n * were never compensated and must be reconciled by hand.\n * Distinguished from `aborted` precisely so a stuck\n * rollback is visible state, not a saga wedged in\n * `compensating` forever.\n */\nexport type SagaPhase =\n | \"idle\"\n | \"running\"\n | \"compensating\"\n | \"committed\"\n | \"aborted\"\n | \"compensation_failed\";\n\n/**\n * The slice this knob owns.\n *\n * The spec's three fields are load-bearing:\n * - `position` — the index of the step currently in flight while `running`,\n * or the index being compensated while `compensating`. Survives eviction,\n * so `boot` resumes mid-saga from the durable slice.\n * - `done` — the compensation log: the ids of steps that completed forward,\n * in completion order. `undo` walks this in reverse. This is the single\n * source of truth for what must be unwound.\n * - `compensating` — the direction bit. `false` while winding forward, `true`\n * once a failure has pivoted the saga into rollback.\n *\n * Plus:\n * - `phase` — the derived lifecycle tag (see `SagaPhase`). Kept in the slice\n * (not recomputed) so a consumer's view and Transitions reducer can key on\n * `state.phase` directly, and the terminal states (`committed` / `aborted`)\n * are explicit facts rather than \"position past the end\" arithmetic.\n * - `error` — the forward failure that triggered compensation, carried\n * forward verbatim (`unknown`) for the consumer to read, never interpreted\n * (same discipline as `retry-backoff`'s `lastError` and `fan-out`'s\n * `error`).\n * - `compensationError` — the failure of an `undo` itself, set only when the\n * saga reaches `compensation_failed`. Kept distinct from `error` (the\n * forward failure) so a consumer reconciling a stuck rollback can read both\n * \"what broke the transaction\" and \"which compensation then bounced\".\n * Carried verbatim, never interpreted, same as `error`.\n * - `items` — the work-queue ledger, one `QueueItem` per step, keyed by the\n * step's positional id. The single source of truth for each step's status;\n * `phase` / `position` / `done` are the projection the verbs keep in\n * lockstep with it.\n *\n * Every field is `readonly` and JSON-serializable (plain numbers, arrays, and\n * the work-queue's plain `QueueItem` records), so the slice round-trips through\n * a consumer's `Store<S>` unchanged — durable across DO eviction.\n */\nexport interface SagaState<I = StepId> {\n /** The step in flight (`running`) or being compensated (`compensating`). */\n readonly position: number;\n /** The compensation log: ids of completed-forward steps, in completion order. */\n readonly done: readonly StepId[];\n /** Direction bit: `false` winding forward, `true` unwinding. */\n readonly compensating: boolean;\n /** The derived lifecycle tag (see `SagaPhase`). */\n readonly phase: SagaPhase;\n /** The forward failure that triggered compensation, if any. Carried, never interpreted. */\n readonly error?: unknown;\n /** The failure of an `undo` itself (only when `compensation_failed`). Carried, never interpreted. */\n readonly compensationError?: unknown;\n /** The work-queue ledger: one record per step, keyed by positional id. */\n readonly items: readonly QueueItem<I>[];\n}\n\n/** Whether the saga has terminated successfully (every step committed). */\nexport function isCommitted<I>(state: SagaState<I>): boolean {\n return state.phase === \"committed\";\n}\n\n/** Whether the saga has terminated in failure, fully unwound (every completed step undone). */\nexport function isAborted<I>(state: SagaState<I>): boolean {\n return state.phase === \"aborted\";\n}\n\n/**\n * Whether the saga has terminated in failure with an UNFINISHED rollback: an\n * `undo` itself failed, so some completed steps were never compensated and need\n * hand reconciliation. Terminal, but distinct from `aborted` (fully unwound).\n */\nexport function isCompensationFailed<I>(state: SagaState<I>): boolean {\n return state.phase === \"compensation_failed\";\n}\n\n/**\n * Whether the saga has reached a terminal phase (success, fully-unwound\n * failure, or compensation-failed). Derived — reads the slice, never mutates.\n * Consumers branch their own phase off this; no further verb has any effect\n * once it holds (the verbs guard on phase and no-op).\n */\nexport function isSettled<I>(state: SagaState<I>): boolean {\n return (\n state.phase === \"committed\" ||\n state.phase === \"aborted\" ||\n state.phase === \"compensation_failed\"\n );\n}\n\n/**\n * The starting slice: idle, nothing run, winding-forward direction. `items` is\n * empty until `start` stamps one ledger record per configured step — the slice\n * is generic in the ledger payload `I`, defaulting to the positional `StepId`\n * since a saga's \"input\" per step is just its index (the consumer's real inputs\n * ride on its own Msgs).\n */\nexport function initSaga<I = StepId>(): SagaState<I> {\n return {\n position: 0,\n done: [],\n compensating: false,\n phase: \"idle\",\n items: [],\n };\n}\n\n/**\n * Build the saga knob from `config`. Returns the uniform combinator contract:\n * `init` for the owned slice and the five lifecycle verbs (`start`, `stepOk`,\n * `stepErr`, `undoOk`, `undoErr`).\n *\n * No `subs` and no `handlers` — a saga runs no timers, and each step's `do` /\n * `undo` effect is owned by the consumer's `interpret` (the saga emits the Cmd;\n * the consumer performs it and routes the outcome back to a verb). The saga's\n * sole job is the ORDER: which Cmd to emit next, and when to pivot from winding\n * to unwinding (and when a failed `undo` ends the rollback). Pure-ops module —\n * matches `retry-backoff`'s shape.\n */\nexport function createSaga<D extends Cmd, U extends Cmd>(\n config: SagaConfig<D, U>,\n) {\n // The ledger seam, bound once. The saga delegates ledger construction to\n // `wq.enqueue` and every status flip to `wq.patch`, so the `QueueItem<StepId>`\n // shape stays insulated behind the verbs.\n const wq = queueAdapter<StepId>();\n\n /**\n * One ledger record per configured step, keyed by its positional id. Each\n * record is stamped by the `QueueAdapter`'s `enqueue` (the saga delegates\n * ledger construction to the verb rather than building records inline).\n *\n * The positional id is stringified — `QueueItem.id` is a string, the saga's\n * step identity is the index; `String(index)` keeps both the ledger's\n * string-id contract and the positional identity. `enqueuedAt` is `0`: saga\n * verbs are pure and the saga makes no timestamp-based decision (ordering is\n * positional), so there is no clock to read here.\n */\n function freshLedger(): QueueItem<StepId>[] {\n let items: QueueItem<StepId>[] = [];\n config.steps.forEach((_step, index) => {\n items = wq.enqueue(items, index, 0, String(index)).next;\n });\n return items;\n }\n\n /**\n * Flip the ledger record for step `index` to `status`, delegating the\n * transition to the `QueueAdapter`'s `patch` (keyed by the record's string\n * id, `String(index)`) so the status flip is NOT re-rolled here. PURE —\n * `patch` returns a new array; an unknown id returns a copy unchanged (the\n * verbs guard against out-of-range, but the helper is total).\n */\n function setStatus(\n items: readonly QueueItem<StepId>[],\n index: number,\n status: QueueItemStatus,\n ): QueueItem<StepId>[] {\n return wq.patch(items, String(index), (item) => ({\n ...item,\n status,\n })).next;\n }\n\n /**\n * The step at `index`, or `undefined` if out of range. Centralizes the bounds\n * check so the verbs read a step through a narrowing guard instead of a\n * non-null assertion: `const step = stepAt(i); if (step === undefined) …`.\n */\n function stepAt(index: number): SagaStep<D, U> | undefined {\n return config.steps[index];\n }\n\n /** The most-recently-completed step id (tail of `done`), or `undefined` if the log is empty. */\n function lastDone(done: readonly StepId[]): StepId | undefined {\n return done[done.length - 1];\n }\n\n /**\n * Begin the saga: stamp a `pending` ledger record per step, mark step 0\n * `running`, and emit step 0's `do` Cmd. PURE.\n *\n * A saga with zero configured steps commits immediately (nothing to do, so\n * the empty transaction trivially succeeds) and emits no Cmd. Calling `start`\n * on an already-started saga (phase ≠ `\"idle\"`) is a no-op: the slice is\n * returned unchanged with no Cmds, so a stray re-`start` after a boot/replay\n * can't relaunch step 0 on top of an in-flight saga.\n */\n function start(\n state: SagaState<StepId>,\n ): readonly [SagaState<StepId>, readonly D[]] {\n if (state.phase !== \"idle\") return [state, []];\n\n const items = freshLedger();\n const first = stepAt(0);\n if (first === undefined) {\n // Empty transaction: trivially committed, no effect.\n return [{ ...state, phase: \"committed\", items }, []];\n }\n\n const next: SagaState<StepId> = {\n ...state,\n position: 0,\n phase: \"running\",\n items: setStatus(items, 0, \"running\"),\n };\n return [next, [first.do]];\n }\n\n /**\n * Record the in-flight step as committed and advance. PURE.\n *\n * Flips the current step's ledger record `running → done`, appends its id to\n * the compensation log, and:\n * - if a next step exists, marks it `running` and emits its `do` Cmd;\n * - if this was the last step, transitions to `committed` (terminal\n * success) and emits no Cmd.\n *\n * `stepOk` while not `running` (idle, compensating, or already terminal) is a\n * no-op — the runtime's serial dispatch makes a true double-`stepOk`\n * impossible, but a stale success Msg after a boot/replay is real, and\n * swallowing it is the safe direction (the step's outcome is already recorded\n * in the ledger).\n */\n function stepOk(\n state: SagaState<StepId>,\n ): readonly [SagaState<StepId>, readonly D[]] {\n if (state.phase !== \"running\") return [state, []];\n\n const completed = state.position;\n const itemsDone = setStatus(state.items, completed, \"done\");\n const done = [...state.done, completed];\n const nextPosition = completed + 1;\n const nextStep = stepAt(nextPosition);\n\n if (nextStep === undefined) {\n // No next step — the last step committed, so the whole transaction\n // succeeded.\n return [{ ...state, done, items: itemsDone, phase: \"committed\" }, []];\n }\n\n const next: SagaState<StepId> = {\n ...state,\n position: nextPosition,\n done,\n items: setStatus(itemsDone, nextPosition, \"running\"),\n };\n return [next, [nextStep.do]];\n }\n\n /**\n * Pivot from winding to unwinding: the in-flight step failed. PURE.\n *\n * Flips the failed step's ledger record `running → failed`, records the\n * `error`, sets the direction bit, and begins compensation by emitting the\n * `undo` of the MOST-recently-completed step (the tail of the compensation\n * log) — rollback is the mirror of progress, so the last step that succeeded\n * is the first to be undone.\n *\n * If nothing completed forward (the first step itself failed), there is\n * nothing to compensate: the saga goes straight to `aborted` (terminal\n * failure) and emits no `undo`.\n *\n * `stepErr` while not `running` is a no-op (same stale-Msg reasoning as\n * `stepOk`): once a saga is already compensating or terminal, a late failure\n * Msg for an old step must not restart or re-pivot the unwind.\n */\n function stepErr(\n state: SagaState<StepId>,\n error: unknown,\n ): readonly [SagaState<StepId>, readonly U[]] {\n if (state.phase !== \"running\") return [state, []];\n\n const failed = state.position;\n const items = setStatus(state.items, failed, \"failed\");\n\n // Compensate the most-recently-completed step first. `lastDone === undefined`\n // means nothing completed forward (the first step itself failed) — there is\n // nothing to undo, so the saga aborts straight away. The guard narrows\n // `undoIndex` to `StepId` and `undoStep` to a present step without a\n // non-null assertion.\n const undoIndex = lastDone(state.done);\n const undoStep = undoIndex === undefined ? undefined : stepAt(undoIndex);\n if (undoIndex === undefined || undoStep === undefined) {\n return [\n { ...state, items, error, compensating: true, phase: \"aborted\" },\n [],\n ];\n }\n\n const next: SagaState<StepId> = {\n ...state,\n items,\n error,\n compensating: true,\n phase: \"compensating\",\n position: undoIndex,\n };\n return [next, [undoStep.undo]];\n }\n\n /**\n * Continue the rollback: the `undo` for the current compensation position\n * succeeded. PURE.\n *\n * Pops the just-undone step off the tail of the compensation log (flipping\n * its ledger record `done → cancelled` to mark it rolled back), and:\n * - if more completed steps remain, emits the next one's `undo` (continuing\n * in reverse) and moves `position` to it;\n * - if the log is now empty, transitions to `aborted` (terminal failure —\n * the saga is fully unwound) and emits no Cmd.\n *\n * `undoOk` while not `compensating` is a no-op (same stale-Msg reasoning as\n * the forward verbs): an `undo`-success Msg that arrives after the saga has\n * already finished unwinding must not pop a step that isn't there.\n */\n function undoOk(\n state: SagaState<StepId>,\n ): readonly [SagaState<StepId>, readonly U[]] {\n if (state.phase !== \"compensating\") return [state, []];\n\n // The tail of the log is the step we just compensated — mark it cancelled.\n // `undone === undefined` cannot happen while `compensating` (the phase is\n // only entered with a non-empty log), but the guard keeps the lookup total\n // and narrows `undone` to `StepId` without a non-null assertion.\n const undone = lastDone(state.done);\n if (undone === undefined) return [state, []];\n const remaining = state.done.slice(0, -1);\n const items = setStatus(state.items, undone, \"cancelled\");\n\n // The next step to compensate is the new tail of the log. `nextUndo`\n // narrows to `StepId` here and to a present step via `stepAt`, so the\n // continue-vs-terminate branch needs no non-null assertion.\n const nextUndo = lastDone(remaining);\n const nextStep = nextUndo === undefined ? undefined : stepAt(nextUndo);\n if (nextUndo === undefined || nextStep === undefined) {\n // Fully unwound — terminal failure.\n return [{ ...state, done: remaining, items, phase: \"aborted\" }, []];\n }\n\n const next: SagaState<StepId> = {\n ...state,\n done: remaining,\n items,\n position: nextUndo,\n };\n return [next, [nextStep.undo]];\n }\n\n /**\n * Halt the rollback: the `undo` for the current compensation position itself\n * FAILED. PURE.\n *\n * A failed compensation is a real-world fact — a refund that bounced, a hold\n * that won't release — and it must become visible terminal state, never leave\n * the saga wedged in `compensating` forever waiting for an `undoOk` that will\n * never come. So `undoErr`:\n * - flips the in-flight compensation step's ledger record `done → failed`\n * (its `undo` did not take, so it is NOT `cancelled`);\n * - records the undo failure in `compensationError` (distinct from `error`,\n * the forward failure that started the rollback);\n * - transitions to the terminal `compensation_failed` phase and emits no\n * Cmd. The compensation log is LEFT INTACT (`done` keeps the steps that\n * were never rolled back) so the consumer can see exactly which steps\n * still need hand reconciliation.\n *\n * `undoErr` while not `compensating` is a no-op (same stale-Msg reasoning as\n * the other verbs): an `undo`-failure Msg that arrives after the saga has\n * already settled must not re-pivot a terminal saga.\n */\n function undoErr(\n state: SagaState<StepId>,\n error: unknown,\n ): readonly [SagaState<StepId>, readonly U[]] {\n if (state.phase !== \"compensating\") return [state, []];\n\n // The step whose `undo` just failed is the current compensation position.\n // Its forward effect stands un-reversed, so its record goes `done → failed`,\n // not `cancelled`.\n const items = setStatus(state.items, state.position, \"failed\");\n return [\n {\n ...state,\n items,\n compensationError: error,\n phase: \"compensation_failed\",\n },\n [],\n ];\n }\n\n return {\n init: initSaga<StepId>,\n start,\n stepOk,\n stepErr,\n undoOk,\n undoErr,\n isCommitted,\n isAborted,\n isCompensationFailed,\n isSettled,\n };\n}\n"]}
|
package/dist/snapshot/index.d.ts
CHANGED
package/dist/snapshot/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
export { createSnapshot, snapshotFailed, snapshotLoadFailed, snapshotLoaded, snapshotSaved } from '../chunk-
|
|
2
|
-
import '../chunk-
|
|
3
|
-
import '../chunk-
|
|
1
|
+
export { createSnapshot, snapshotFailed, snapshotLoadFailed, snapshotLoaded, snapshotSaved } from '../chunk-EHIX7NYZ.js';
|
|
2
|
+
import '../chunk-MMH7CW5K.js';
|
|
3
|
+
import '../chunk-QLA76GIT.js';
|
|
4
4
|
//# sourceMappingURL=index.js.map
|
|
5
5
|
//# sourceMappingURL=index.js.map
|
package/dist/subs/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { S as Sub, P as Port } from '../core-
|
|
2
|
-
import { S as SubscribeHandler } from '../types-
|
|
1
|
+
import { S as Sub, P as Port } from '../core-BoB6t7dB.js';
|
|
2
|
+
import { S as SubscribeHandler } from '../types-B-8bcAp8.js';
|
|
3
3
|
import { Runtime } from '../index.js';
|
|
4
4
|
|
|
5
5
|
interface MinimalEvent {
|
package/dist/testing/index.d.ts
CHANGED
package/dist/testing/index.js
CHANGED
package/dist/throttle/index.d.ts
CHANGED
|
@@ -13,6 +13,15 @@
|
|
|
13
13
|
* - **throttle** enforces a rate — fires AT MOST once per `ms` while the
|
|
14
14
|
* burst is ongoing, dropping the calls in between.
|
|
15
15
|
*
|
|
16
|
+
* Layering with `@demlik/tea/throttled-input`: `throttle` and `debounce` are
|
|
17
|
+
* the two host-boundary PRIMITIVES — two distinct algorithms
|
|
18
|
+
* (at-most-once-per-window vs collapse-a-burst) behind one signature shape.
|
|
19
|
+
* `throttled-input` is NOT a third primitive: it is a TEA machine composed
|
|
20
|
+
* OVER them (the same semantics, reimplemented as pure, durable Model state)
|
|
21
|
+
* that re-exports both. Wrapping a raw host event → these primitives; durable, replayable
|
|
22
|
+
* gating inside a machine → `throttled-input` (see its module doc for the full
|
|
23
|
+
* layering map).
|
|
24
|
+
*
|
|
16
25
|
* WHAT THIS IS NOT — and why it lives outside `update`:
|
|
17
26
|
*
|
|
18
27
|
* - NOT a reducer / Transitions cell. Reducers are PURE (invariant 2 — same
|
package/dist/throttle/index.js
CHANGED
|
@@ -1,16 +1,24 @@
|
|
|
1
1
|
import { TtlCache } from '../cache/index.js';
|
|
2
2
|
import { DeadlineSub } from '../deadline/index.js';
|
|
3
3
|
export { DeadlineExceeded as ThrottledInputSettled, subscribeDeadline as subscribeThrottledInput, deadlineExceeded as throttledInputSettled } from '../deadline/index.js';
|
|
4
|
-
import { C as Cmd, S as Sub } from '../core-
|
|
4
|
+
import { C as Cmd, S as Sub } from '../core-BoB6t7dB.js';
|
|
5
5
|
export { Debounced, debounce } from '../debounce/index.js';
|
|
6
6
|
export { Throttled, throttle } from '../throttle/index.js';
|
|
7
|
-
import '../types-
|
|
7
|
+
import '../types-B-8bcAp8.js';
|
|
8
8
|
|
|
9
9
|
/**
|
|
10
10
|
* @demlik/tea/throttled-input — gate a high-frequency input stream into a
|
|
11
11
|
* SETTLED, RATE-CAPPED, optionally DEDUPED sequence of emits, as a TEA knob: one
|
|
12
12
|
* config object + a few pre-wired hooks you spread into your machine.
|
|
13
13
|
*
|
|
14
|
+
* Layering (the throttle-family map): `../throttle` and `../debounce` are the
|
|
15
|
+
* two host-boundary PRIMITIVES — two distinct algorithms
|
|
16
|
+
* (at-most-once-per-window vs collapse-a-burst) behind one signature shape.
|
|
17
|
+
* THIS module is the third name but NOT a third primitive: a TEA machine
|
|
18
|
+
* composed OVER them that re-exports both. Three exports, one layering — not
|
|
19
|
+
* duplication. The reuse list below spells out composition vs reimplemented
|
|
20
|
+
* semantic per sibling.
|
|
21
|
+
*
|
|
14
22
|
* What it reuses, and HOW (composition vs. reimplemented semantic — the two are
|
|
15
23
|
* not the same, so this list keeps them apart):
|
|
16
24
|
*
|
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
export { debounce } from '../chunk-
|
|
2
|
-
export { throttle } from '../chunk-
|
|
3
|
-
import { deadlineSub } from '../chunk-
|
|
4
|
-
export { subscribeDeadline as subscribeThrottledInput, deadlineExceeded as throttledInputSettled } from '../chunk-
|
|
1
|
+
export { debounce } from '../chunk-J6527VRQ.js';
|
|
2
|
+
export { throttle } from '../chunk-HCEVHFJ7.js';
|
|
3
|
+
import { deadlineSub } from '../chunk-K7Q23EQ4.js';
|
|
4
|
+
export { subscribeDeadline as subscribeThrottledInput, deadlineExceeded as throttledInputSettled } from '../chunk-K7Q23EQ4.js';
|
|
5
5
|
import { initCache, get, set } from '../chunk-IN33Q4VJ.js';
|
|
6
6
|
import '../chunk-NSDFA6M6.js';
|
|
7
7
|
import '../chunk-2YFLOCWX.js';
|
|
8
|
-
import '../chunk-
|
|
9
|
-
import '../chunk-
|
|
8
|
+
import '../chunk-MMH7CW5K.js';
|
|
9
|
+
import '../chunk-QLA76GIT.js';
|
|
10
10
|
|
|
11
11
|
// src/throttled-input/index.ts
|
|
12
12
|
var DEFAULT_SUB_ID = "throttled-input:settle";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/throttled-input/index.ts"],"names":[],"mappings":";;;;;;;;;;;AA0PA,IAAM,cAAA,GAAiB,wBAAA;AAOhB,SAAS,kBAAA,GAA2C;AACzD,EAAA,OAAO,EAAE,MAAA,EAAQ,IAAA,EAAM,OAAA,EAAS,IAAA,EAAK;AACvC;AASA,SAAS,KAAA,CACP,QACA,KAAA,EACQ;AACR,EAAA,OAAO,MAAA,CAAO,SAAS,KAAK,CAAA;AAC9B;AASA,SAAS,WAAA,CACP,QACA,KAAA,EACsC;AACtC,EAAA,OAAO,OAAO,UAAA,KAAe,MAAA,IAAa,KAAA,CAAM,KAAA,KAAU,SACtD,MAAA,GACA,IAAA;AACN;AAQA,SAAS,UAAA,CACP,MAAA,EACA,KAAA,EACA,KAAA,EACA,EAAA,EACS;AACT,EAAA,MAAM,MAAA,GAAS,WAAA,CAAY,MAAA,EAAQ,KAAK,CAAA;AACxC,EAAA,IAAI,MAAA,KAAW,IAAA,IAAQ,KAAA,CAAM,KAAA,KAAU,QAAW,OAAO,KAAA;AACzD,EAAA,OAAO,GAAA,CAAS,MAAM,KAAA,EAAO,KAAA,CAAM,QAAQ,KAAK,CAAA,EAAG,EAAE,CAAA,KAAM,MAAA;AAC7D;AAcA,SAAS,UAAA,CACP,MAAA,EACA,KAAA,EACA,KAAA,EACA,EAAA,EAC4C;AAC5C,EAAA,MAAM,MAAA,GAAS,WAAA,CAAY,MAAA,EAAQ,KAAK,CAAA;AACxC,EAAA,MAAM,KAAA,GACJ,MAAA,KAAW,IAAA,IAAQ,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AO,SAAA,EAAa,EAAE,GACjC,IAAA;AAAA,EACN;AAEA,EAAA,OAAO;AAAA,IACL,IAAA;AAAA,IACA,KAAA,EAAO,CAAC,KAAA,EAAO,KAAA,EAAO,OAAO,KAAA,CAAM,MAAA,EAAQ,KAAA,EAAO,KAAA,EAAO,EAAE,CAAA;AAAA,IAC3D,SAAS,CAAC,KAAA,EAAO,OAAO,OAAA,CAAQ,MAAA,EAAQ,OAAO,EAAE,CAAA;AAAA,IACjD,MAAM,CAAC,KAAA,EAAO,OAAO,OAAA,CAAQ,MAAA,EAAQ,OAAO,EAAE;AAAA,GAChD;AACF","file":"index.js","sourcesContent":["/**\n * @demlik/tea/throttled-input — gate a high-frequency input stream into a\n * SETTLED, RATE-CAPPED, optionally DEDUPED sequence of emits, as a TEA knob: one\n * config object + a few pre-wired hooks you spread into your machine.\n *\n * What it reuses, and HOW (composition vs. reimplemented semantic — the two are\n * not the same, so this list keeps them apart):\n *\n * - `../cache` — COMPOSED directly. The DEDUPE / memoize layer is `../cache`'s\n * `TtlCache` plus its `get` / `set` / `initCache` ops, called at runtime —\n * not reinvented. While `cacheTtlMs` is set, an input whose `cacheKey` is\n * already cached and unexpired is served from the cache and emits NOTHING\n * (the downstream effect ran once for that key within its TTL); a fresh emit\n * writes the value into the cache so the next identical input within\n * `cacheTtlMs` is suppressed. The optional eviction Sub is the consumer's to\n * wire if they want memory reclaim (this knob's correctness needs only TTL\n * reads).\n * - `../deadline` — COMPOSED directly. The settle timer IS a `../deadline`\n * Sub: `subsFor` builds it via `deadlineSub`, and the subscribe cell +\n * Msg constructor are RE-EXPORTS of `../deadline`'s own (`subscribeDeadline`\n * → `subscribeThrottledInput`, `deadlineExceeded` → `throttledInputSettled`).\n * The timer lifecycle stays owned by `../deadline`; this knob redraws none\n * of it.\n * - `../throttle` / `../debounce` — TYPE + SEMANTIC reuse only, NOT composed.\n * Those siblings are host-boundary SINK transformers that hold a live\n * `setTimeout`; a `setTimeout` in a closure is exactly what a durable,\n * replayable knob must NOT hold. So their CODE is never called here. Instead\n * the RATE-cap semantic (\"at most once per `ms`\", leading-edge) and the\n * SETTLE semantic (\"wait until quiet\", trailing-edge) are REIMPLEMENTED as\n * pure Model state: `lastAt` is the durable rate cursor (half-open cutoff\n * `at - lastAt >= throttleMs`), and `pending` + the `../deadline` Sub realize\n * the debounce window inside `update`. The `throttle` / `debounce`\n * transformers themselves are RE-EXPORTED (the only reuse of their actual\n * code) so a consumer can pre-throttle / pre-coalesce a genuinely bursty\n * HOST event at the boundary BEFORE it ever becomes an `input` Msg — a\n * separate, optional escape hatch, not part of this knob's gates.\n *\n * \"Omit a brick, omit its gate\" (the resilient-call config rule): every gate\n * field is optional. Omit `throttleMs` → no rate cap (every input passes the\n * rate gate). Omit `debounceMs` → no settle wait (an input that clears the rate\n * gate emits IMMEDIATELY rather than being held). Omit `cacheTtlMs` → no cache\n * slice at all (the `cache` field is absent; no dedupe). A config with all three\n * omitted is a pass-through: `input` always emits.\n *\n * Why this is a knob and not hand-wired logic: the managed state (`lastAt`,\n * `pending`, `cache`) lives in the Model, so it survives DO eviction / reload\n * (durable) and every transition is still a Msg through `update` (replayable). A\n * closure holding a `setTimeout` and a mutable \"last value\" would break both —\n * banned. `input` / `onFlush` are PURE: time arrives as an `at` parameter, never\n * `Date.now()`; they return NEW slice values, never mutate.\n *\n * Typical wiring (combinator form):\n *\n * const search = createThrottledInput<string, Msg>({\n * debounceMs: 200, // wait for the user to stop typing\n * throttleMs: 1_000, // but never fire more than 1/s during a long burst\n * cacheTtlMs: 30_000, // skip a query repeated within 30s\n * cacheKey: (q) => q,\n * emit: (q) => ({ type: \"RunSearch\", query: q }),\n * });\n *\n * // Model: { search: ThrottledInput<string>, ... }\n * // init: (loaded) => [loaded ?? { search: search.init(), ... }, []]\n * // update cells:\n * // QueryTyped: (s, m) => mapInput(s, search.input(s.search, m.value, m.at))\n * // SettleFired: (s, m) => mapInput(s, search.onFlush(s.search, m.atMs))\n * // subscriptions: (s) => search.subs(s.search)\n * // subscribe: { ...search.handlers() }\n *\n * where `mapInput(s, [slice, cmds]) => [{ ...s, search: slice }, cmds]` lifts the\n * slice transition into the consumer's Model. The `RunSearch` Cmd's interpret\n * handler is the consumer's — it is where the settled input meets I/O.\n *\n * NOT a substrate primitive: it depends only on sibling subpaths (`../throttle`,\n * `../debounce`, `../cache`, `../deadline`) and the core `Cmd` / `Sub` types.\n * Consumers reach it via the `@demlik/tea/throttled-input` subpath; the L1\n * escape hatch is those sibling subpaths threaded by hand. NOT exported from the\n * package root — same one-shape-per-package rule as `batch-window` and `poller`.\n */\n\nimport {\n get as cacheGet,\n set as cacheSet,\n initCache,\n type TtlCache,\n} from \"../cache\";\nimport { type DeadlineSub, deadlineSub } from \"../deadline\";\nimport type { Cmd, Sub } from \"../index\";\n\n// `../throttle` + `../debounce` — host-boundary pre-transformers (see file\n// header). Re-exported so a consumer that wants to throttle/debounce a bursty\n// HOST source BEFORE it becomes an `input` Msg reaches them from the same\n// import as the durable gate.\nexport { type Debounced, debounce } from \"../debounce\";\nexport { type Throttled, throttle } from \"../throttle\";\n\n/**\n * The gate fields every throttled-input config shares, regardless of whether\n * dedupe is on. The two dedupe variants below extend this with mutually\n * exclusive cache fields.\n *\n * `emit` is a pure Cmd CONSTRUCTOR, not a closure-with-state: it maps a settled\n * value to the single Cmd the runtime performs when the gates let a value\n * through. Keeping it `(value) => Cmd` (not `(value) => void`) is what keeps the\n * trigger replayable — the emit is a Cmd in the transition's output, never a\n * side effect inside the verb (mirrors `batch-window`'s `flush`).\n */\ninterface ThrottledInputGates<V, C extends Cmd> {\n /**\n * Rate cap, in milliseconds. An input that lands within `throttleMs` of the\n * last EMIT (`at - lastAt < throttleMs`) is dropped from immediate firing —\n * the leading-edge \"at most once per `throttleMs`\" rate-cap rule, applied to\n * emits. The half-open cutoff (`>=` passes) matches `../throttle` and\n * `../cache`'s window-edge convention. Omit for no rate cap.\n *\n * Interacts with `debounceMs`: when both are set, a rate-blocked input is\n * still HELD as `pending` (so the settle timer eventually trails it out at a\n * legal moment) rather than silently dropped — the trailing-edge guarantee\n * that the FINAL sample of a window is never lost.\n */\n readonly throttleMs?: number;\n /**\n * Settle wait, in milliseconds. An input that clears the rate gate is not\n * emitted immediately; it is held as `pending` and a debounce deadline is\n * armed at `pendingAt + debounceMs`. A fresh input re-arms (slides) the\n * window. `onFlush` emits the pending value when the window finally expires.\n * Omit for no settle wait — a passing input emits on arrival.\n */\n readonly debounceMs?: number;\n /**\n * Map a settled value to the single Cmd the runtime performs. Called with the\n * value the gates let through; the returned Cmd is what `input` / `onFlush`\n * emit. PURE constructor — no I/O, no clock; the I/O happens later in the\n * consumer's interpret handler for the returned Cmd.\n */\n readonly emit: (value: V) => C;\n}\n\n/**\n * Configuration for a throttled input — the knob. Pure config, no mutable state\n * (the `ThrottledInput<V>` slice carries that). One config object is shared\n * across every input of one logical stream (often a module-scope const).\n *\n * A DISCRIMINATED UNION on the presence of dedupe, so the type system makes a\n * cache-key collision UNREPRESENTABLE (\"omit a brick, omit its gate\"):\n *\n * - **No dedupe** (`ThrottledInputNoCache`): `cacheTtlMs` absent ⇒ no cache\n * slice, no dedupe. `cacheKey` is statically forbidden here (`never`) — a\n * key with no cache to feed is dead config, so the type rejects it rather\n * than silently ignoring it.\n * - **Dedupe** (`ThrottledInputWithCache`): `cacheTtlMs` set ⇒ `cacheKey` is\n * REQUIRED. There is no `String(value)` default to fall back to, so a\n * structured value can NEVER collapse two distinct values to one slot (the\n * `\"[object Object]\"` collision). The consumer must state the identity that\n * keys the cache; a primitive stream still trivially passes `(v) => v` /\n * `String`, but it does so EXPLICITLY.\n */\nexport type ThrottledInputConfig<V, C extends Cmd> =\n | ThrottledInputNoCache<V, C>\n | ThrottledInputWithCache<V, C>;\n\n/**\n * The no-dedupe config variant: gates only, no cache. `cacheTtlMs` is absent\n * and `cacheKey` is statically `never` so a stray key (which would feed no\n * cache) is a type error, not a silently-ignored field.\n */\nexport interface ThrottledInputNoCache<V, C extends Cmd>\n extends ThrottledInputGates<V, C> {\n readonly cacheTtlMs?: undefined;\n readonly cacheKey?: never;\n}\n\n/**\n * The dedupe config variant: a per-entry TTL plus a REQUIRED `cacheKey`. An\n * input whose `cacheKey` is already cached and unexpired emits NOTHING (the\n * downstream effect ran once for that key within its TTL); a fresh emit writes\n * the value into the cache.\n *\n * `cacheKey` is required (no `String(value)` default) precisely so a structured\n * value cannot silently collide — the consumer names the identity, the cache\n * keys on exactly that.\n */\nexport interface ThrottledInputWithCache<V, C extends Cmd>\n extends ThrottledInputGates<V, C> {\n /**\n * Dedupe / memoize TTL, in milliseconds. An input whose `cacheKey` is already\n * cached and unexpired emits NOTHING; a fresh emit writes the value into the\n * cache so the next identical input within `cacheTtlMs` is suppressed.\n */\n readonly cacheTtlMs: number;\n /**\n * Key a value for the dedupe cache. REQUIRED whenever `cacheTtlMs` is set:\n * there is no `String(value)` fallback, so a structured value's identity is\n * always the consumer's explicit choice and two distinct values can never\n * collapse to one slot. A primitive stream passes `(v) => v` / `String`.\n */\n readonly cacheKey: (value: V) => string;\n}\n\n/**\n * The Model slice a throttled input owns — its visible slice (the knob\n * principle: managed state lives in the Model, never a closure, so it is durable\n * and replayable).\n *\n * - `lastAt` — the `at` of the most recent EMIT, or `null` before the first\n * emit. The `../throttle` rate cap measures against it: an input\n * within `throttleMs` of `lastAt` is rate-blocked. Persisted so a\n * resumed gate keeps its rate cursor.\n * - `pending` — the value HELD for the settle (debounce) window, paired with the\n * `at` it was held (the anchor the deadline targets), or `null`\n * when nothing is waiting. The single source of truth for \"is a\n * settle window open?\" — the debounce timer Sub arms iff this is\n * non-null.\n * - `cache` — the `../cache` TTL store backing dedupe, present IFF\n * `cacheTtlMs` is configured. Absent (the field omitted) for a\n * gate with no dedupe — no per-op cost, nothing to serialize.\n */\nexport interface ThrottledInput<V> {\n readonly lastAt: number | null;\n readonly pending: PendingInput<V> | null;\n readonly cache?: TtlCache<V>;\n}\n\n/**\n * A value held for the settle window: the `value` itself and the `at` it was\n * held (the anchor the debounce deadline targets, `at + debounceMs`). A distinct\n * type (not a bare `V`) because `V` may itself be `null` — a present-but-null\n * value is still a real pending input, distinct from \"nothing pending\", exactly\n * the `null`-sentinel discipline `../throttle` / `../debounce` use for their\n * `pendingArgs`.\n */\nexport interface PendingInput<V> {\n readonly value: V;\n readonly at: number;\n}\n\n/**\n * The Sub variant a throttled input's settle timer produces — a `../deadline`\n * Sub (so the window fires at the correct ABSOLUTE moment even after a late\n * subscribe / rehydrate, and so a consumer running several gates routes each by\n * `id`). `atMs` is the absolute settle-by instant (`pendingAt + debounceMs`).\n */\nexport type ThrottledInputSub = DeadlineSub;\n\n/**\n * The stable Sub id the gate arms its settle deadline under. A single gate arms\n * exactly one settle timer at a time, so one id suffices; a consumer running\n * several gates on one machine namespaces them by composing the knob under\n * distinct slices with distinct ids (the `subs(state, id)` parameter).\n */\nconst DEFAULT_SUB_ID = \"throttled-input:settle\";\n\n/**\n * The starting slice: no prior emit, nothing pending. The `cache` field is\n * seeded only when `cacheTtlMs` is configured (see `createThrottledInput`); the\n * free `initThrottledInput` leaves it absent (the no-dedupe shape).\n */\nexport function initThrottledInput<V>(): ThrottledInput<V> {\n return { lastAt: null, pending: null };\n}\n\n/**\n * Resolve a value's cache key under a DEDUPE config. PURE. Takes the narrowed\n * `ThrottledInputWithCache` (not the union) because `cacheKey` is only present —\n * and only meaningful — when dedupe is on; there is no `String(value)` default\n * to fall back to, so a structured value's identity is always the consumer's\n * explicit choice and two distinct values can never collapse to one slot.\n */\nfunction keyOf<V, C extends Cmd>(\n config: ThrottledInputWithCache<V, C>,\n value: V,\n): string {\n return config.cacheKey(value);\n}\n\n/**\n * Narrow `config` to its dedupe variant iff a cache slice is actually wired —\n * `cacheTtlMs` set AND a `cache` store present. Returns the narrowed config\n * (carrying the required `cacheKey`) or `null` when no dedupe is configured.\n * The single place the union is discriminated, so `isCacheHit` / `commitEmit`\n * share one narrowing rather than re-deriving the predicate.\n */\nfunction cacheConfig<V, C extends Cmd>(\n config: ThrottledInputConfig<V, C>,\n state: ThrottledInput<V>,\n): ThrottledInputWithCache<V, C> | null {\n return config.cacheTtlMs !== undefined && state.cache !== undefined\n ? config\n : null;\n}\n\n/**\n * Whether `value` is a cache HIT under `config` at `at` — present and unexpired.\n * PURE — reads only. Always `false` when `cacheTtlMs` is unset or no `cache`\n * slice exists (no dedupe configured), so the dedupe gate is a no-op for an\n * unconfigured gate.\n */\nfunction isCacheHit<V, C extends Cmd>(\n config: ThrottledInputConfig<V, C>,\n state: ThrottledInput<V>,\n value: V,\n at: number,\n): boolean {\n const cached = cacheConfig(config, state);\n if (cached === null || state.cache === undefined) return false;\n return cacheGet(state.cache, keyOf(cached, value), at) !== undefined;\n}\n\n/**\n * Emit `value` at clock `at`: bump the rate cursor, refresh the dedupe cache,\n * and clear any pending hold. PURE. The single place an emit's bookkeeping\n * lives, shared by `input` (immediate emit) and `onFlush` (trailing emit) so the\n * two paths can never drift on what an emit updates.\n *\n * - `lastAt` advances to `at` — the next input is rate-measured against this\n * emit, the `../throttle` window cursor.\n * - `cache` (when configured) records `value` under its key with `cacheTtlMs`\n * from `at` — so the next identical input within the TTL is suppressed.\n * - `pending` clears — the value just went out; nothing is waiting.\n */\nfunction commitEmit<V, C extends Cmd>(\n config: ThrottledInputConfig<V, C>,\n state: ThrottledInput<V>,\n value: V,\n at: number,\n): readonly [ThrottledInput<V>, readonly C[]] {\n const cached = cacheConfig(config, state);\n const cache =\n cached !== null && state.cache !== undefined\n ? cacheSet(\n state.cache,\n keyOf(cached, value),\n value,\n at,\n cached.cacheTtlMs,\n )\n : state.cache;\n const next: ThrottledInput<V> = {\n ...state,\n lastAt: at,\n pending: null,\n ...(cache !== undefined ? { cache } : {}),\n };\n return [next, [config.emit(value)]];\n}\n\n/**\n * Feed a new input `value` arriving at clock `at` through the gates. PURE.\n *\n * The gate order is DEDUPE → RATE → SETTLE (each skipped when its config field\n * is omitted), the same cache-first-then-gate order `resilient-call` uses (a hit\n * short-circuits before the expensive path):\n *\n * 1. **Dedupe** (`cacheTtlMs` set): if `value`'s key is cached and unexpired,\n * suppress — return the slice UNCHANGED (no emit, no pending, no re-arm).\n * The downstream effect already ran for this key within its TTL.\n * 2. **Rate** (`throttleMs` set): if `at` is within `throttleMs` of the last\n * emit (`at - lastAt < throttleMs`), this input is rate-blocked.\n * - With `debounceMs` set → HOLD it as `pending` (the trailing edge: the\n * settle timer will emit it at a legal moment, so the final sample is\n * never lost). The deadline `subs` arms targets `at + debounceMs`.\n * - Without `debounceMs` → DROP it (pure rate cap, no catch-up).\n * 3. **Settle** (`debounceMs` set): the input cleared the rate gate. HOLD it\n * as `pending` and let the debounce window slide; `onFlush` emits it once\n * the window expires. A fresh input before expiry overwrites `pending` (the\n * trailing edge fires with the LAST value, the `../debounce` default).\n * 4. **Pass-through**: no `debounceMs`, cleared the rate gate → EMIT now.\n *\n * @param config the knob (the three optional gates + `emit`)\n * @param state the current slice\n * @param value the input value\n * @param at the arrival instant (epoch ms) — the caller stamps it; the verb\n * never reads the clock\n */\nexport function input<V, C extends Cmd>(\n config: ThrottledInputConfig<V, C>,\n state: ThrottledInput<V>,\n value: V,\n at: number,\n): readonly [ThrottledInput<V>, readonly C[]] {\n // 1. Dedupe gate — a cached, unexpired key short-circuits everything.\n if (isCacheHit(config, state, value, at)) {\n return [state, []];\n }\n\n // 2. Rate gate — half-open cutoff (`>=` passes). `lastAt === null` (no prior\n // emit) always passes: the first input is never rate-blocked. Shared with\n // `onFlush` via `rateBlockedAt` so the arrival and trailing-edge paths agree\n // on the window.\n if (rateBlockedAt(config, state, at)) {\n // With a settle window, a rate-blocked input is HELD (trailing edge) so it\n // emits at the next legal moment; without one, it is a pure drop.\n if (config.debounceMs !== undefined) {\n return [{ ...state, pending: { value, at } }, []];\n }\n return [state, []];\n }\n\n // 3. Settle gate — passed the rate gate; if a debounce window is configured,\n // hold the value and (re)arm the settle deadline rather than emit now.\n if (config.debounceMs !== undefined) {\n return [{ ...state, pending: { value, at } }, []];\n }\n\n // 4. Pass-through — no settle wait, cleared the rate gate: emit immediately.\n return commitEmit(config, state, value, at);\n}\n\n/**\n * Whether emitting at clock `at` would breach the rate cap — `at` lands within\n * `throttleMs` of the last emit (`at - lastAt < throttleMs`). PURE — reads only.\n * Always `false` when `throttleMs` is unset (no rate cap) or before the first\n * emit (`lastAt === null`), so an unconfigured / never-fired gate never holds on\n * the rate gate. The single rate-gate predicate, shared by `input` (drop / hold\n * on arrival) and `onFlush` (re-hold a still-early trailing edge) so the two\n * paths can never drift on what \"within the rate window\" means.\n */\nfunction rateBlockedAt<V, C extends Cmd>(\n config: ThrottledInputConfig<V, C>,\n state: ThrottledInput<V>,\n at: number,\n): boolean {\n return (\n config.throttleMs !== undefined &&\n state.lastAt !== null &&\n at - state.lastAt < config.throttleMs\n );\n}\n\n/**\n * Emit the pending value because the settle (debounce) window closed. PURE.\n *\n * - Pending present, rate gate CLEAR → emit `config.emit(pending.value)`,\n * advance the rate cursor (`lastAt = at`), refresh the dedupe cache, and clear\n * `pending`. The trailing edge of `../debounce` realized as a Model transition.\n * - Pending present, rate gate STILL BLOCKED → re-HOLD: return the slice with\n * `pending` intact and NO Cmds. A settle Msg can fire at `pending.at +\n * debounceMs`, which may still be inside the rate window (`lastAt +\n * throttleMs`) — emitting then would breach the headline \"at most once per\n * `throttleMs`\" cap. Re-holding keeps the value waiting; `subs` re-arms the\n * deadline at `max(pending.at + debounceMs, lastAt + throttleMs)` so the next\n * timer fires at a LEGAL moment and the trailing edge is deferred, never lost.\n * - Pending absent → no-op: return the same slice and no Cmds. Guards the race\n * where an `input` already emitted (or a dedupe hit cleared interest) before\n * the settle timer's Msg lands — a stale `onFlush` must NOT emit. Symmetric\n * with `batch-window`'s closed-window guard.\n *\n * `at` is the firing instant the settle Msg carried (the caller stamps it; the\n * verb never reads the clock). It becomes the new rate cursor and the cache\n * write's `nowMs`, so a settled emit rate-blocks subsequent inputs from its\n * actual fire moment, not the moment the value was first held.\n *\n * @param config the knob (`throttleMs`, `emit`, cache config)\n * @param state the current slice\n * @param at the settle-timer firing instant (epoch ms)\n */\nexport function onFlush<V, C extends Cmd>(\n config: ThrottledInputConfig<V, C>,\n state: ThrottledInput<V>,\n at: number,\n): readonly [ThrottledInput<V>, readonly C[]] {\n // No pending value = an immediate emit already fired, or a dedupe hit cleared\n // interest. A stale timer Msg must not emit — return the slice untouched.\n if (state.pending === null) return [state, []];\n // Rate gate re-check: a settle Msg can land before the rate window opens (its\n // naive deadline is pending.at + debounceMs, which `subs` lifts to a legal\n // target — but a stale / early timer can still arrive). Emitting now would\n // breach \"at most once per throttleMs\", so re-hold and let `subs` re-arm at\n // the legal moment. The value stays pending; nothing is dropped.\n if (rateBlockedAt(config, state, at)) return [state, []];\n return commitEmit(config, state, state.pending.value, at);\n}\n\n/**\n * The settle timer Sub, derived from the slice. PURE.\n *\n * Returns the single `../deadline` Sub while a value is held AND a settle window\n * is configured, or `[]` otherwise. The deadline target is the LATER of two\n * constraints (so the timer never fires before BOTH are satisfied):\n *\n * - `pending.at + debounceMs` — the settle (debounce) deadline: the value has\n * stopped sliding, the burst has gone quiet.\n * - `lastAt + throttleMs` — the rate cap: emitting earlier would breach \"at\n * most once per `throttleMs`\". Only applies once a prior emit exists\n * (`lastAt !== null`) and a rate cap is configured (`throttleMs` set).\n *\n * `max(settleAt, rateAt)` is the earliest LEGAL trailing-edge moment. Anchoring\n * the timer here — rather than the naive `pending.at + debounceMs` — is what\n * keeps the rate cap intact across the trailing edge: a value held while still\n * inside the rate window arms its timer at `lastAt + throttleMs`, so `onFlush`\n * fires at a moment the rate gate already permits. (`onFlush` re-checks the gate\n * anyway and re-holds if an early/stale timer slips through, so the cap holds\n * even if a timer fires ahead of this target.)\n *\n * The substrate's reconcile pass arms the timer when the array gains the Sub and\n * disarms it (clearing the pending `setTimeout`) when the array loses it — so an\n * `onFlush` (or a dedupe hit) that clears `pending` auto-cancels the now-stale\n * settle timer on the next transition, and a sliding input that re-stamps\n * `pending.at` re-arms a fresh absolute target.\n *\n * `debounceMs` undefined ⇒ no settle window ⇒ `[]` even with a `pending` value\n * (an unconfigured settle never holds, but the guard keeps `subs` total).\n *\n * @param config the knob (`debounceMs`, `throttleMs`)\n * @param state the current slice\n * @param id stable identity for this gate's settle timer (default\n * `\"throttled-input:settle\"`); pass a distinct id per gate when a\n * machine runs several so the dispatched Msg routes distinctly.\n */\nexport function subsFor<V, C extends Cmd>(\n config: ThrottledInputConfig<V, C>,\n state: ThrottledInput<V>,\n id = DEFAULT_SUB_ID,\n): readonly ThrottledInputSub[] {\n if (config.debounceMs === undefined || state.pending === null) return [];\n const settleAt = state.pending.at + config.debounceMs;\n // The rate floor: the earliest moment the rate cap permits an emit. Absent\n // when no rate cap is configured or no prior emit set a cursor — then the\n // settle deadline alone governs.\n const rateAt =\n config.throttleMs !== undefined && state.lastAt !== null\n ? state.lastAt + config.throttleMs\n : settleAt;\n return [deadlineSub(id, Math.max(settleAt, rateAt))];\n}\n\n/**\n * The bound knob returned by `createThrottledInput`. `init` + the two pure verbs\n * + `subs`, all closing over one `ThrottledInputConfig`. The verbs return\n * `readonly [ThrottledInput<V>, readonly C[]]`: the next slice and the Cmds to\n * emit (one `emit` Cmd when a value passes, none while held / dropped / deduped).\n *\n * Pure-ops + subs module: there is no `handlers(ports)` cell. The settle timer's\n * subscribe cell IS `../deadline`'s `subscribeDeadline` (re-exported below) —\n * the consumer wires it into `subscribe` directly; the knob redraws no timer\n * lifecycle of its own. (Compare `poller`, identical: it too reuses\n * `../deadline`'s cell and ships no `handlers`.)\n */\nexport interface ThrottledInputKnob<V, C extends Cmd> {\n /** Seed the Model slice (with a cache iff `cacheTtlMs` is configured). */\n init(): ThrottledInput<V>;\n /**\n * Feed a new input through the dedupe → rate → settle gates. See `input`.\n */\n input(\n state: ThrottledInput<V>,\n value: V,\n at: number,\n ): readonly [ThrottledInput<V>, readonly C[]];\n /**\n * Emit the held value because the settle window closed. See `onFlush`.\n */\n onFlush(\n state: ThrottledInput<V>,\n at: number,\n ): readonly [ThrottledInput<V>, readonly C[]];\n /**\n * The settle timer Sub, armed only while a value is held. See `subsFor`.\n * `id` keys the deadline so several gates on one machine route distinctly.\n */\n subs(state: ThrottledInput<V>, id?: string): readonly Sub[];\n}\n\n/**\n * Build a throttled-input knob from `config`. Combinator form (the default L2\n * ergonomic): hand it the config, splice the returned hooks into your machine.\n * The pure verbs (`input` / `onFlush`) close over the config so the consumer's\n * reducer cells stay a uniform `(state, ...args)` shape; `subs` pre-wires the\n * settle timer.\n *\n * `init()` seeds a `cache` slice IFF `cacheTtlMs` is configured — an unconfigured\n * gate carries no cache field (nothing to serialize, no dedupe). Pure factory —\n * no clock read, no timer; everything happens when the consumer calls the\n * returned verbs / `subs` with an injected `at`.\n *\n * @typeParam V the input value type\n * @typeParam C the Cmd type `config.emit` returns\n */\nexport function createThrottledInput<V, C extends Cmd>(\n config: ThrottledInputConfig<V, C>,\n): ThrottledInputKnob<V, C> {\n function init(): ThrottledInput<V> {\n const base = initThrottledInput<V>();\n // Seed the cache only when dedupe is configured — an unconfigured gate\n // carries no cache field at all (the no-dedupe shape).\n return config.cacheTtlMs !== undefined\n ? { ...base, cache: initCache<V>() }\n : base;\n }\n\n return {\n init,\n input: (state, value, at) => input(config, state, value, at),\n onFlush: (state, at) => onFlush(config, state, at),\n subs: (state, id) => subsFor(config, state, id),\n };\n}\n\n/**\n * The settle-timer wiring, RE-EXPORTED from `../deadline` (not redrawn) so the\n * timer lifecycle stays owned there. Consolidated into one `export ... from`:\n *\n * - `subscribeThrottledInput` (= `../deadline`'s `subscribeDeadline`) — the\n * `subscribe[\"deadline\"]` cell. Arms a one-shot timer for `max(0, atMs -\n * now)`, dispatches the deadline Msg, returns a cleanup that clears it. The\n * consumer assigns it: `subscribe: { deadline: subscribeThrottledInput }`.\n * - `throttledInputSettled` (= `../deadline`'s `deadlineExceeded`) +\n * `ThrottledInputSettled` (= `DeadlineExceeded`) — the settle-timer Msg\n * constructor and type the consumer handles via `onFlush`. Sharing one\n * constructor with the subscribe cell keeps the two from drifting; the\n * reducer reads `msg.atMs` as the `at` it threads into `onFlush`.\n */\nexport {\n type DeadlineExceeded as ThrottledInputSettled,\n deadlineExceeded as throttledInputSettled,\n subscribeDeadline as subscribeThrottledInput,\n} from \"../deadline\";\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/throttled-input/index.ts"],"names":[],"mappings":";;;;;;;;;;;AAkQA,IAAM,cAAA,GAAiB,wBAAA;AAOhB,SAAS,kBAAA,GAA2C;AACzD,EAAA,OAAO,EAAE,MAAA,EAAQ,IAAA,EAAM,OAAA,EAAS,IAAA,EAAK;AACvC;AASA,SAAS,KAAA,CACP,QACA,KAAA,EACQ;AACR,EAAA,OAAO,MAAA,CAAO,SAAS,KAAK,CAAA;AAC9B;AASA,SAAS,WAAA,CACP,QACA,KAAA,EACsC;AACtC,EAAA,OAAO,OAAO,UAAA,KAAe,MAAA,IAAa,KAAA,CAAM,KAAA,KAAU,SACtD,MAAA,GACA,IAAA;AACN;AAQA,SAAS,UAAA,CACP,MAAA,EACA,KAAA,EACA,KAAA,EACA,EAAA,EACS;AACT,EAAA,MAAM,MAAA,GAAS,WAAA,CAAY,MAAA,EAAQ,KAAK,CAAA;AACxC,EAAA,IAAI,MAAA,KAAW,IAAA,IAAQ,KAAA,CAAM,KAAA,KAAU,QAAW,OAAO,KAAA;AACzD,EAAA,OAAO,GAAA,CAAS,MAAM,KAAA,EAAO,KAAA,CAAM,QAAQ,KAAK,CAAA,EAAG,EAAE,CAAA,KAAM,MAAA;AAC7D;AAcA,SAAS,UAAA,CACP,MAAA,EACA,KAAA,EACA,KAAA,EACA,EAAA,EAC4C;AAC5C,EAAA,MAAM,MAAA,GAAS,WAAA,CAAY,MAAA,EAAQ,KAAK,CAAA;AACxC,EAAA,MAAM,KAAA,GACJ,MAAA,KAAW,IAAA,IAAQ,KAAA,CAAM,UAAU,MAAA,GAC/B,GAAA;AAAA,IACE,KAAA,CAAM,KAAA;AAAA,IACN,KAAA,CAAM,QAAQ,K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AAO,CAAC,KAAA,EAAO,KAAA,EAAO,OAAO,KAAA,CAAM,MAAA,EAAQ,KAAA,EAAO,KAAA,EAAO,EAAE,CAAA;AAAA,IAC3D,SAAS,CAAC,KAAA,EAAO,OAAO,OAAA,CAAQ,MAAA,EAAQ,OAAO,EAAE,CAAA;AAAA,IACjD,MAAM,CAAC,KAAA,EAAO,OAAO,OAAA,CAAQ,MAAA,EAAQ,OAAO,EAAE;AAAA,GAChD;AACF","file":"index.js","sourcesContent":["/**\n * @demlik/tea/throttled-input — gate a high-frequency input stream into a\n * SETTLED, RATE-CAPPED, optionally DEDUPED sequence of emits, as a TEA knob: one\n * config object + a few pre-wired hooks you spread into your machine.\n *\n * Layering (the throttle-family map): `../throttle` and `../debounce` are the\n * two host-boundary PRIMITIVES — two distinct algorithms\n * (at-most-once-per-window vs collapse-a-burst) behind one signature shape.\n * THIS module is the third name but NOT a third primitive: a TEA machine\n * composed OVER them that re-exports both. Three exports, one layering — not\n * duplication. The reuse list below spells out composition vs reimplemented\n * semantic per sibling.\n *\n * What it reuses, and HOW (composition vs. reimplemented semantic — the two are\n * not the same, so this list keeps them apart):\n *\n * - `../cache` — COMPOSED directly. The DEDUPE / memoize layer is `../cache`'s\n * `TtlCache` plus its `get` / `set` / `initCache` ops, called at runtime —\n * not reinvented. While `cacheTtlMs` is set, an input whose `cacheKey` is\n * already cached and unexpired is served from the cache and emits NOTHING\n * (the downstream effect ran once for that key within its TTL); a fresh emit\n * writes the value into the cache so the next identical input within\n * `cacheTtlMs` is suppressed. The optional eviction Sub is the consumer's to\n * wire if they want memory reclaim (this knob's correctness needs only TTL\n * reads).\n * - `../deadline` — COMPOSED directly. The settle timer IS a `../deadline`\n * Sub: `subsFor` builds it via `deadlineSub`, and the subscribe cell +\n * Msg constructor are RE-EXPORTS of `../deadline`'s own (`subscribeDeadline`\n * → `subscribeThrottledInput`, `deadlineExceeded` → `throttledInputSettled`).\n * The timer lifecycle stays owned by `../deadline`; this knob redraws none\n * of it.\n * - `../throttle` / `../debounce` — TYPE + SEMANTIC reuse only, NOT composed.\n * Those siblings are host-boundary SINK transformers that hold a live\n * `setTimeout`; a `setTimeout` in a closure is exactly what a durable,\n * replayable knob must NOT hold. So their CODE is never called here. Instead\n * the RATE-cap semantic (\"at most once per `ms`\", leading-edge) and the\n * SETTLE semantic (\"wait until quiet\", trailing-edge) are REIMPLEMENTED as\n * pure Model state: `lastAt` is the durable rate cursor (half-open cutoff\n * `at - lastAt >= throttleMs`), and `pending` + the `../deadline` Sub realize\n * the debounce window inside `update`. The `throttle` / `debounce`\n * transformers themselves are RE-EXPORTED (the only reuse of their actual\n * code) so a consumer can pre-throttle / pre-coalesce a genuinely bursty\n * HOST event at the boundary BEFORE it ever becomes an `input` Msg — a\n * separate, optional escape hatch, not part of this knob's gates.\n *\n * \"Omit a brick, omit its gate\" (the resilient-call config rule): every gate\n * field is optional. Omit `throttleMs` → no rate cap (every input passes the\n * rate gate). Omit `debounceMs` → no settle wait (an input that clears the rate\n * gate emits IMMEDIATELY rather than being held). Omit `cacheTtlMs` → no cache\n * slice at all (the `cache` field is absent; no dedupe). A config with all three\n * omitted is a pass-through: `input` always emits.\n *\n * Why this is a knob and not hand-wired logic: the managed state (`lastAt`,\n * `pending`, `cache`) lives in the Model, so it survives DO eviction / reload\n * (durable) and every transition is still a Msg through `update` (replayable). A\n * closure holding a `setTimeout` and a mutable \"last value\" would break both —\n * banned. `input` / `onFlush` are PURE: time arrives as an `at` parameter, never\n * `Date.now()`; they return NEW slice values, never mutate.\n *\n * Typical wiring (combinator form):\n *\n * const search = createThrottledInput<string, Msg>({\n * debounceMs: 200, // wait for the user to stop typing\n * throttleMs: 1_000, // but never fire more than 1/s during a long burst\n * cacheTtlMs: 30_000, // skip a query repeated within 30s\n * cacheKey: (q) => q,\n * emit: (q) => ({ type: \"RunSearch\", query: q }),\n * });\n *\n * // Model: { search: ThrottledInput<string>, ... }\n * // init: (loaded) => [loaded ?? { search: search.init(), ... }, []]\n * // update cells:\n * // QueryTyped: (s, m) => mapInput(s, search.input(s.search, m.value, m.at))\n * // SettleFired: (s, m) => mapInput(s, search.onFlush(s.search, m.atMs))\n * // subscriptions: (s) => search.subs(s.search)\n * // subscribe: { ...search.handlers() }\n *\n * where `mapInput(s, [slice, cmds]) => [{ ...s, search: slice }, cmds]` lifts the\n * slice transition into the consumer's Model. The `RunSearch` Cmd's interpret\n * handler is the consumer's — it is where the settled input meets I/O.\n *\n * NOT a substrate primitive: it depends only on sibling subpaths (`../throttle`,\n * `../debounce`, `../cache`, `../deadline`) and the core `Cmd` / `Sub` types.\n * Consumers reach it via the `@demlik/tea/throttled-input` subpath; the L1\n * escape hatch is those sibling subpaths threaded by hand. NOT exported from the\n * package root — same one-shape-per-package rule as `batch-window` and `poller`.\n */\n\nimport {\n get as cacheGet,\n set as cacheSet,\n initCache,\n type TtlCache,\n} from \"../cache\";\nimport { type DeadlineSub, deadlineSub } from \"../deadline\";\nimport type { Cmd, Sub } from \"../index\";\n\n// `../throttle` + `../debounce` — host-boundary pre-transformers (see file\n// header). Re-exported so a consumer that wants to throttle/debounce a bursty\n// HOST source BEFORE it becomes an `input` Msg reaches them from the same\n// import as the durable gate.\nexport { type Debounced, debounce } from \"../debounce\";\nexport { type Throttled, throttle } from \"../throttle\";\n\n/**\n * The gate fields every throttled-input config shares, regardless of whether\n * dedupe is on. The two dedupe variants below extend this with mutually\n * exclusive cache fields.\n *\n * `emit` is a pure Cmd CONSTRUCTOR, not a closure-with-state: it maps a settled\n * value to the single Cmd the runtime performs when the gates let a value\n * through. Keeping it `(value) => Cmd` (not `(value) => void`) is what keeps the\n * trigger replayable — the emit is a Cmd in the transition's output, never a\n * side effect inside the verb (mirrors `batch-window`'s `flush`).\n */\ninterface ThrottledInputGates<V, C extends Cmd> {\n /**\n * Rate cap, in milliseconds. An input that lands within `throttleMs` of the\n * last EMIT (`at - lastAt < throttleMs`) is dropped from immediate firing —\n * the leading-edge \"at most once per `throttleMs`\" rate-cap rule, applied to\n * emits. The half-open cutoff (`>=` passes) matches `../throttle` and\n * `../cache`'s window-edge convention. Omit for no rate cap.\n *\n * Interacts with `debounceMs`: when both are set, a rate-blocked input is\n * still HELD as `pending` (so the settle timer eventually trails it out at a\n * legal moment) rather than silently dropped — the trailing-edge guarantee\n * that the FINAL sample of a window is never lost.\n */\n readonly throttleMs?: number;\n /**\n * Settle wait, in milliseconds. An input that clears the rate gate is not\n * emitted immediately; it is held as `pending` and a debounce deadline is\n * armed at `pendingAt + debounceMs`. A fresh input re-arms (slides) the\n * window. `onFlush` emits the pending value when the window finally expires.\n * Omit for no settle wait — a passing input emits on arrival.\n */\n readonly debounceMs?: number;\n /**\n * Map a settled value to the single Cmd the runtime performs. Called with the\n * value the gates let through; the returned Cmd is what `input` / `onFlush`\n * emit. PURE constructor — no I/O, no clock; the I/O happens later in the\n * consumer's interpret handler for the returned Cmd.\n */\n readonly emit: (value: V) => C;\n}\n\n/**\n * Configuration for a throttled input — the knob. Pure config, no mutable state\n * (the `ThrottledInput<V>` slice carries that). One config object is shared\n * across every input of one logical stream (often a module-scope const).\n *\n * A DISCRIMINATED UNION on the presence of dedupe, so the type system makes a\n * cache-key collision UNREPRESENTABLE (\"omit a brick, omit its gate\"):\n *\n * - **No dedupe** (`ThrottledInputNoCache`): `cacheTtlMs` absent ⇒ no cache\n * slice, no dedupe. `cacheKey` is statically forbidden here (`never`) — a\n * key with no cache to feed is dead config, so the type rejects it rather\n * than silently ignoring it.\n * - **Dedupe** (`ThrottledInputWithCache`): `cacheTtlMs` set ⇒ `cacheKey` is\n * REQUIRED. There is no `String(value)` default to fall back to, so a\n * structured value can NEVER collapse two distinct values to one slot (the\n * `\"[object Object]\"` collision). The consumer must state the identity that\n * keys the cache; a primitive stream still trivially passes `(v) => v` /\n * `String`, but it does so EXPLICITLY.\n */\nexport type ThrottledInputConfig<V, C extends Cmd> =\n | ThrottledInputNoCache<V, C>\n | ThrottledInputWithCache<V, C>;\n\n/**\n * The no-dedupe config variant: gates only, no cache. `cacheTtlMs` is absent\n * and `cacheKey` is statically `never` so a stray key (which would feed no\n * cache) is a type error, not a silently-ignored field.\n */\nexport interface ThrottledInputNoCache<V, C extends Cmd>\n extends ThrottledInputGates<V, C> {\n readonly cacheTtlMs?: undefined;\n readonly cacheKey?: never;\n}\n\n/**\n * The dedupe config variant: a per-entry TTL plus a REQUIRED `cacheKey`. An\n * input whose `cacheKey` is already cached and unexpired emits NOTHING (the\n * downstream effect ran once for that key within its TTL); a fresh emit writes\n * the value into the cache.\n *\n * `cacheKey` is required (no `String(value)` default) precisely so a structured\n * value cannot silently collide — the consumer names the identity, the cache\n * keys on exactly that.\n */\nexport interface ThrottledInputWithCache<V, C extends Cmd>\n extends ThrottledInputGates<V, C> {\n /**\n * Dedupe / memoize TTL, in milliseconds. An input whose `cacheKey` is already\n * cached and unexpired emits NOTHING; a fresh emit writes the value into the\n * cache so the next identical input within `cacheTtlMs` is suppressed.\n */\n readonly cacheTtlMs: number;\n /**\n * Key a value for the dedupe cache. REQUIRED whenever `cacheTtlMs` is set:\n * there is no `String(value)` fallback, so a structured value's identity is\n * always the consumer's explicit choice and two distinct values can never\n * collapse to one slot. A primitive stream passes `(v) => v` / `String`.\n */\n readonly cacheKey: (value: V) => string;\n}\n\n/**\n * The Model slice a throttled input owns — its visible slice (the knob\n * principle: managed state lives in the Model, never a closure, so it is durable\n * and replayable).\n *\n * - `lastAt` — the `at` of the most recent EMIT, or `null` before the first\n * emit. The `../throttle` rate cap measures against it: an input\n * within `throttleMs` of `lastAt` is rate-blocked. Persisted so a\n * resumed gate keeps its rate cursor.\n * - `pending` — the value HELD for the settle (debounce) window, paired with the\n * `at` it was held (the anchor the deadline targets), or `null`\n * when nothing is waiting. The single source of truth for \"is a\n * settle window open?\" — the debounce timer Sub arms iff this is\n * non-null.\n * - `cache` — the `../cache` TTL store backing dedupe, present IFF\n * `cacheTtlMs` is configured. Absent (the field omitted) for a\n * gate with no dedupe — no per-op cost, nothing to serialize.\n */\nexport interface ThrottledInput<V> {\n readonly lastAt: number | null;\n readonly pending: PendingInput<V> | null;\n readonly cache?: TtlCache<V>;\n}\n\n/**\n * A value held for the settle window: the `value` itself and the `at` it was\n * held (the anchor the debounce deadline targets, `at + debounceMs`). A distinct\n * type (not a bare `V`) because `V` may itself be `null` — a present-but-null\n * value is still a real pending input, distinct from \"nothing pending\", exactly\n * the `null`-sentinel discipline `../throttle` / `../debounce` use for their\n * `pendingArgs`.\n */\nexport interface PendingInput<V> {\n readonly value: V;\n readonly at: number;\n}\n\n/**\n * The Sub variant a throttled input's settle timer produces — a `../deadline`\n * Sub (so the window fires at the correct ABSOLUTE moment even after a late\n * subscribe / rehydrate, and so a consumer running several gates routes each by\n * `id`). `atMs` is the absolute settle-by instant (`pendingAt + debounceMs`).\n */\nexport type ThrottledInputSub = DeadlineSub;\n\n/**\n * The stable Sub id the gate arms its settle deadline under. A single gate arms\n * exactly one settle timer at a time, so one id suffices; a consumer running\n * several gates on one machine namespaces them by composing the knob under\n * distinct slices with distinct ids (the `subs(state, id)` parameter).\n */\nconst DEFAULT_SUB_ID = \"throttled-input:settle\";\n\n/**\n * The starting slice: no prior emit, nothing pending. The `cache` field is\n * seeded only when `cacheTtlMs` is configured (see `createThrottledInput`); the\n * free `initThrottledInput` leaves it absent (the no-dedupe shape).\n */\nexport function initThrottledInput<V>(): ThrottledInput<V> {\n return { lastAt: null, pending: null };\n}\n\n/**\n * Resolve a value's cache key under a DEDUPE config. PURE. Takes the narrowed\n * `ThrottledInputWithCache` (not the union) because `cacheKey` is only present —\n * and only meaningful — when dedupe is on; there is no `String(value)` default\n * to fall back to, so a structured value's identity is always the consumer's\n * explicit choice and two distinct values can never collapse to one slot.\n */\nfunction keyOf<V, C extends Cmd>(\n config: ThrottledInputWithCache<V, C>,\n value: V,\n): string {\n return config.cacheKey(value);\n}\n\n/**\n * Narrow `config` to its dedupe variant iff a cache slice is actually wired —\n * `cacheTtlMs` set AND a `cache` store present. Returns the narrowed config\n * (carrying the required `cacheKey`) or `null` when no dedupe is configured.\n * The single place the union is discriminated, so `isCacheHit` / `commitEmit`\n * share one narrowing rather than re-deriving the predicate.\n */\nfunction cacheConfig<V, C extends Cmd>(\n config: ThrottledInputConfig<V, C>,\n state: ThrottledInput<V>,\n): ThrottledInputWithCache<V, C> | null {\n return config.cacheTtlMs !== undefined && state.cache !== undefined\n ? config\n : null;\n}\n\n/**\n * Whether `value` is a cache HIT under `config` at `at` — present and unexpired.\n * PURE — reads only. Always `false` when `cacheTtlMs` is unset or no `cache`\n * slice exists (no dedupe configured), so the dedupe gate is a no-op for an\n * unconfigured gate.\n */\nfunction isCacheHit<V, C extends Cmd>(\n config: ThrottledInputConfig<V, C>,\n state: ThrottledInput<V>,\n value: V,\n at: number,\n): boolean {\n const cached = cacheConfig(config, state);\n if (cached === null || state.cache === undefined) return false;\n return cacheGet(state.cache, keyOf(cached, value), at) !== undefined;\n}\n\n/**\n * Emit `value` at clock `at`: bump the rate cursor, refresh the dedupe cache,\n * and clear any pending hold. PURE. The single place an emit's bookkeeping\n * lives, shared by `input` (immediate emit) and `onFlush` (trailing emit) so the\n * two paths can never drift on what an emit updates.\n *\n * - `lastAt` advances to `at` — the next input is rate-measured against this\n * emit, the `../throttle` window cursor.\n * - `cache` (when configured) records `value` under its key with `cacheTtlMs`\n * from `at` — so the next identical input within the TTL is suppressed.\n * - `pending` clears — the value just went out; nothing is waiting.\n */\nfunction commitEmit<V, C extends Cmd>(\n config: ThrottledInputConfig<V, C>,\n state: ThrottledInput<V>,\n value: V,\n at: number,\n): readonly [ThrottledInput<V>, readonly C[]] {\n const cached = cacheConfig(config, state);\n const cache =\n cached !== null && state.cache !== undefined\n ? cacheSet(\n state.cache,\n keyOf(cached, value),\n value,\n at,\n cached.cacheTtlMs,\n )\n : state.cache;\n const next: ThrottledInput<V> = {\n ...state,\n lastAt: at,\n pending: null,\n ...(cache !== undefined ? { cache } : {}),\n };\n return [next, [config.emit(value)]];\n}\n\n/**\n * Feed a new input `value` arriving at clock `at` through the gates. PURE.\n *\n * The gate order is DEDUPE → RATE → SETTLE (each skipped when its config field\n * is omitted), the same cache-first-then-gate order `resilient-call` uses (a hit\n * short-circuits before the expensive path):\n *\n * 1. **Dedupe** (`cacheTtlMs` set): if `value`'s key is cached and unexpired,\n * suppress — return the slice UNCHANGED (no emit, no pending, no re-arm).\n * The downstream effect already ran for this key within its TTL.\n * 2. **Rate** (`throttleMs` set): if `at` is within `throttleMs` of the last\n * emit (`at - lastAt < throttleMs`), this input is rate-blocked.\n * - With `debounceMs` set → HOLD it as `pending` (the trailing edge: the\n * settle timer will emit it at a legal moment, so the final sample is\n * never lost). The deadline `subs` arms targets `at + debounceMs`.\n * - Without `debounceMs` → DROP it (pure rate cap, no catch-up).\n * 3. **Settle** (`debounceMs` set): the input cleared the rate gate. HOLD it\n * as `pending` and let the debounce window slide; `onFlush` emits it once\n * the window expires. A fresh input before expiry overwrites `pending` (the\n * trailing edge fires with the LAST value, the `../debounce` default).\n * 4. **Pass-through**: no `debounceMs`, cleared the rate gate → EMIT now.\n *\n * @param config the knob (the three optional gates + `emit`)\n * @param state the current slice\n * @param value the input value\n * @param at the arrival instant (epoch ms) — the caller stamps it; the verb\n * never reads the clock\n */\nexport function input<V, C extends Cmd>(\n config: ThrottledInputConfig<V, C>,\n state: ThrottledInput<V>,\n value: V,\n at: number,\n): readonly [ThrottledInput<V>, readonly C[]] {\n // 1. Dedupe gate — a cached, unexpired key short-circuits everything.\n if (isCacheHit(config, state, value, at)) {\n return [state, []];\n }\n\n // 2. Rate gate — half-open cutoff (`>=` passes). `lastAt === null` (no prior\n // emit) always passes: the first input is never rate-blocked. Shared with\n // `onFlush` via `rateBlockedAt` so the arrival and trailing-edge paths agree\n // on the window.\n if (rateBlockedAt(config, state, at)) {\n // With a settle window, a rate-blocked input is HELD (trailing edge) so it\n // emits at the next legal moment; without one, it is a pure drop.\n if (config.debounceMs !== undefined) {\n return [{ ...state, pending: { value, at } }, []];\n }\n return [state, []];\n }\n\n // 3. Settle gate — passed the rate gate; if a debounce window is configured,\n // hold the value and (re)arm the settle deadline rather than emit now.\n if (config.debounceMs !== undefined) {\n return [{ ...state, pending: { value, at } }, []];\n }\n\n // 4. Pass-through — no settle wait, cleared the rate gate: emit immediately.\n return commitEmit(config, state, value, at);\n}\n\n/**\n * Whether emitting at clock `at` would breach the rate cap — `at` lands within\n * `throttleMs` of the last emit (`at - lastAt < throttleMs`). PURE — reads only.\n * Always `false` when `throttleMs` is unset (no rate cap) or before the first\n * emit (`lastAt === null`), so an unconfigured / never-fired gate never holds on\n * the rate gate. The single rate-gate predicate, shared by `input` (drop / hold\n * on arrival) and `onFlush` (re-hold a still-early trailing edge) so the two\n * paths can never drift on what \"within the rate window\" means.\n */\nfunction rateBlockedAt<V, C extends Cmd>(\n config: ThrottledInputConfig<V, C>,\n state: ThrottledInput<V>,\n at: number,\n): boolean {\n return (\n config.throttleMs !== undefined &&\n state.lastAt !== null &&\n at - state.lastAt < config.throttleMs\n );\n}\n\n/**\n * Emit the pending value because the settle (debounce) window closed. PURE.\n *\n * - Pending present, rate gate CLEAR → emit `config.emit(pending.value)`,\n * advance the rate cursor (`lastAt = at`), refresh the dedupe cache, and clear\n * `pending`. The trailing edge of `../debounce` realized as a Model transition.\n * - Pending present, rate gate STILL BLOCKED → re-HOLD: return the slice with\n * `pending` intact and NO Cmds. A settle Msg can fire at `pending.at +\n * debounceMs`, which may still be inside the rate window (`lastAt +\n * throttleMs`) — emitting then would breach the headline \"at most once per\n * `throttleMs`\" cap. Re-holding keeps the value waiting; `subs` re-arms the\n * deadline at `max(pending.at + debounceMs, lastAt + throttleMs)` so the next\n * timer fires at a LEGAL moment and the trailing edge is deferred, never lost.\n * - Pending absent → no-op: return the same slice and no Cmds. Guards the race\n * where an `input` already emitted (or a dedupe hit cleared interest) before\n * the settle timer's Msg lands — a stale `onFlush` must NOT emit. Symmetric\n * with `batch-window`'s closed-window guard.\n *\n * `at` is the firing instant the settle Msg carried (the caller stamps it; the\n * verb never reads the clock). It becomes the new rate cursor and the cache\n * write's `nowMs`, so a settled emit rate-blocks subsequent inputs from its\n * actual fire moment, not the moment the value was first held.\n *\n * @param config the knob (`throttleMs`, `emit`, cache config)\n * @param state the current slice\n * @param at the settle-timer firing instant (epoch ms)\n */\nexport function onFlush<V, C extends Cmd>(\n config: ThrottledInputConfig<V, C>,\n state: ThrottledInput<V>,\n at: number,\n): readonly [ThrottledInput<V>, readonly C[]] {\n // No pending value = an immediate emit already fired, or a dedupe hit cleared\n // interest. A stale timer Msg must not emit — return the slice untouched.\n if (state.pending === null) return [state, []];\n // Rate gate re-check: a settle Msg can land before the rate window opens (its\n // naive deadline is pending.at + debounceMs, which `subs` lifts to a legal\n // target — but a stale / early timer can still arrive). Emitting now would\n // breach \"at most once per throttleMs\", so re-hold and let `subs` re-arm at\n // the legal moment. The value stays pending; nothing is dropped.\n if (rateBlockedAt(config, state, at)) return [state, []];\n return commitEmit(config, state, state.pending.value, at);\n}\n\n/**\n * The settle timer Sub, derived from the slice. PURE.\n *\n * Returns the single `../deadline` Sub while a value is held AND a settle window\n * is configured, or `[]` otherwise. The deadline target is the LATER of two\n * constraints (so the timer never fires before BOTH are satisfied):\n *\n * - `pending.at + debounceMs` — the settle (debounce) deadline: the value has\n * stopped sliding, the burst has gone quiet.\n * - `lastAt + throttleMs` — the rate cap: emitting earlier would breach \"at\n * most once per `throttleMs`\". Only applies once a prior emit exists\n * (`lastAt !== null`) and a rate cap is configured (`throttleMs` set).\n *\n * `max(settleAt, rateAt)` is the earliest LEGAL trailing-edge moment. Anchoring\n * the timer here — rather than the naive `pending.at + debounceMs` — is what\n * keeps the rate cap intact across the trailing edge: a value held while still\n * inside the rate window arms its timer at `lastAt + throttleMs`, so `onFlush`\n * fires at a moment the rate gate already permits. (`onFlush` re-checks the gate\n * anyway and re-holds if an early/stale timer slips through, so the cap holds\n * even if a timer fires ahead of this target.)\n *\n * The substrate's reconcile pass arms the timer when the array gains the Sub and\n * disarms it (clearing the pending `setTimeout`) when the array loses it — so an\n * `onFlush` (or a dedupe hit) that clears `pending` auto-cancels the now-stale\n * settle timer on the next transition, and a sliding input that re-stamps\n * `pending.at` re-arms a fresh absolute target.\n *\n * `debounceMs` undefined ⇒ no settle window ⇒ `[]` even with a `pending` value\n * (an unconfigured settle never holds, but the guard keeps `subs` total).\n *\n * @param config the knob (`debounceMs`, `throttleMs`)\n * @param state the current slice\n * @param id stable identity for this gate's settle timer (default\n * `\"throttled-input:settle\"`); pass a distinct id per gate when a\n * machine runs several so the dispatched Msg routes distinctly.\n */\nexport function subsFor<V, C extends Cmd>(\n config: ThrottledInputConfig<V, C>,\n state: ThrottledInput<V>,\n id = DEFAULT_SUB_ID,\n): readonly ThrottledInputSub[] {\n if (config.debounceMs === undefined || state.pending === null) return [];\n const settleAt = state.pending.at + config.debounceMs;\n // The rate floor: the earliest moment the rate cap permits an emit. Absent\n // when no rate cap is configured or no prior emit set a cursor — then the\n // settle deadline alone governs.\n const rateAt =\n config.throttleMs !== undefined && state.lastAt !== null\n ? state.lastAt + config.throttleMs\n : settleAt;\n return [deadlineSub(id, Math.max(settleAt, rateAt))];\n}\n\n/**\n * The bound knob returned by `createThrottledInput`. `init` + the two pure verbs\n * + `subs`, all closing over one `ThrottledInputConfig`. The verbs return\n * `readonly [ThrottledInput<V>, readonly C[]]`: the next slice and the Cmds to\n * emit (one `emit` Cmd when a value passes, none while held / dropped / deduped).\n *\n * Pure-ops + subs module: there is no `handlers(ports)` cell. The settle timer's\n * subscribe cell IS `../deadline`'s `subscribeDeadline` (re-exported below) —\n * the consumer wires it into `subscribe` directly; the knob redraws no timer\n * lifecycle of its own. (Compare `poller`, identical: it too reuses\n * `../deadline`'s cell and ships no `handlers`.)\n */\nexport interface ThrottledInputKnob<V, C extends Cmd> {\n /** Seed the Model slice (with a cache iff `cacheTtlMs` is configured). */\n init(): ThrottledInput<V>;\n /**\n * Feed a new input through the dedupe → rate → settle gates. See `input`.\n */\n input(\n state: ThrottledInput<V>,\n value: V,\n at: number,\n ): readonly [ThrottledInput<V>, readonly C[]];\n /**\n * Emit the held value because the settle window closed. See `onFlush`.\n */\n onFlush(\n state: ThrottledInput<V>,\n at: number,\n ): readonly [ThrottledInput<V>, readonly C[]];\n /**\n * The settle timer Sub, armed only while a value is held. See `subsFor`.\n * `id` keys the deadline so several gates on one machine route distinctly.\n */\n subs(state: ThrottledInput<V>, id?: string): readonly Sub[];\n}\n\n/**\n * Build a throttled-input knob from `config`. Combinator form (the default L2\n * ergonomic): hand it the config, splice the returned hooks into your machine.\n * The pure verbs (`input` / `onFlush`) close over the config so the consumer's\n * reducer cells stay a uniform `(state, ...args)` shape; `subs` pre-wires the\n * settle timer.\n *\n * `init()` seeds a `cache` slice IFF `cacheTtlMs` is configured — an unconfigured\n * gate carries no cache field (nothing to serialize, no dedupe). Pure factory —\n * no clock read, no timer; everything happens when the consumer calls the\n * returned verbs / `subs` with an injected `at`.\n *\n * @typeParam V the input value type\n * @typeParam C the Cmd type `config.emit` returns\n */\nexport function createThrottledInput<V, C extends Cmd>(\n config: ThrottledInputConfig<V, C>,\n): ThrottledInputKnob<V, C> {\n function init(): ThrottledInput<V> {\n const base = initThrottledInput<V>();\n // Seed the cache only when dedupe is configured — an unconfigured gate\n // carries no cache field at all (the no-dedupe shape).\n return config.cacheTtlMs !== undefined\n ? { ...base, cache: initCache<V>() }\n : base;\n }\n\n return {\n init,\n input: (state, value, at) => input(config, state, value, at),\n onFlush: (state, at) => onFlush(config, state, at),\n subs: (state, id) => subsFor(config, state, id),\n };\n}\n\n/**\n * The settle-timer wiring, RE-EXPORTED from `../deadline` (not redrawn) so the\n * timer lifecycle stays owned there. Consolidated into one `export ... from`:\n *\n * - `subscribeThrottledInput` (= `../deadline`'s `subscribeDeadline`) — the\n * `subscribe[\"deadline\"]` cell. Arms a one-shot timer for `max(0, atMs -\n * now)`, dispatches the deadline Msg, returns a cleanup that clears it. The\n * consumer assigns it: `subscribe: { deadline: subscribeThrottledInput }`.\n * - `throttledInputSettled` (= `../deadline`'s `deadlineExceeded`) +\n * `ThrottledInputSettled` (= `DeadlineExceeded`) — the settle-timer Msg\n * constructor and type the consumer handles via `onFlush`. Sharing one\n * constructor with the subscribe cell keeps the two from drifting; the\n * reducer reads `msg.atMs` as the `at` it threads into `onFlush`.\n */\nexport {\n type DeadlineExceeded as ThrottledInputSettled,\n deadlineExceeded as throttledInputSettled,\n subscribeDeadline as subscribeThrottledInput,\n} from \"../deadline\";\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
export { createTokenRefresh, initTokenRefresh, refreshTokenCmd, tokenRefreshFailedMsg, tokenRefreshedMsg } from '../chunk-
|
|
1
|
+
export { createTokenRefresh, initTokenRefresh, refreshTokenCmd, tokenRefreshFailedMsg, tokenRefreshedMsg } from '../chunk-3XJWC7VW.js';
|
|
2
2
|
import '../chunk-JELSZN25.js';
|
|
3
|
-
import '../chunk-
|
|
4
|
-
import '../chunk-
|
|
3
|
+
import '../chunk-MMH7CW5K.js';
|
|
4
|
+
import '../chunk-QLA76GIT.js';
|
|
5
5
|
//# sourceMappingURL=index.js.map
|
|
6
6
|
//# sourceMappingURL=index.js.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
export { deepEqual, replayTrace } from '../chunk-
|
|
2
|
-
import '../chunk-
|
|
3
|
-
import '../chunk-
|
|
1
|
+
export { deepEqual, replayTrace } from '../chunk-ON24RKSE.js';
|
|
2
|
+
import '../chunk-MMH7CW5K.js';
|
|
3
|
+
import '../chunk-QLA76GIT.js';
|
|
4
4
|
//# sourceMappingURL=index.js.map
|
|
5
5
|
//# sourceMappingURL=index.js.map
|
|
@@ -1,34 +1,16 @@
|
|
|
1
1
|
import { fromTimeout } from '../chunk-2YFLOCWX.js';
|
|
2
|
-
import '../chunk-
|
|
3
|
-
import {
|
|
2
|
+
import '../chunk-MMH7CW5K.js';
|
|
3
|
+
import { msgKeysOf, applyCell, subId } from '../chunk-QLA76GIT.js';
|
|
4
4
|
|
|
5
5
|
// src/with-deadline/index.ts
|
|
6
6
|
function deadlineExceededMsg(seq) {
|
|
7
7
|
return { type: "$deadline:exceeded", seq };
|
|
8
8
|
}
|
|
9
|
-
function runBaseUpdate(update, form, state, msg) {
|
|
10
|
-
if (form === "reducer") {
|
|
11
|
-
const record = update;
|
|
12
|
-
return record[msg.type](state, msg);
|
|
13
|
-
}
|
|
14
|
-
const table = update;
|
|
15
|
-
const stateKey = state.type;
|
|
16
|
-
return table[stateKey][msg.type](state, msg);
|
|
17
|
-
}
|
|
18
|
-
function deadlineMsgKeys(update, form) {
|
|
19
|
-
const keys = Object.keys(update);
|
|
20
|
-
const firstKey = keys[0];
|
|
21
|
-
if (firstKey === void 0) return [];
|
|
22
|
-
if (form === "reducer") return keys;
|
|
23
|
-
const firstValue = update[firstKey];
|
|
24
|
-
return Object.keys(firstValue);
|
|
25
|
-
}
|
|
26
9
|
function withDeadline(base, config) {
|
|
27
10
|
const windowMs = config.ms;
|
|
28
11
|
const isProgress = config.progress;
|
|
29
12
|
const update = {};
|
|
30
|
-
const
|
|
31
|
-
const baseMsgKeys = deadlineMsgKeys(base.update, baseForm);
|
|
13
|
+
const baseMsgKeys = msgKeysOf(base);
|
|
32
14
|
for (const key of baseMsgKeys) {
|
|
33
15
|
if (key.startsWith("$deadline:")) {
|
|
34
16
|
throw new Error(
|
|
@@ -38,9 +20,8 @@ function withDeadline(base, config) {
|
|
|
38
20
|
}
|
|
39
21
|
for (const key of baseMsgKeys) {
|
|
40
22
|
update[key] = (state, msg) => {
|
|
41
|
-
const [nextBase, baseCmds] =
|
|
42
|
-
base
|
|
43
|
-
baseForm,
|
|
23
|
+
const [nextBase, baseCmds] = applyCell(
|
|
24
|
+
base,
|
|
44
25
|
state.base,
|
|
45
26
|
msg
|
|
46
27
|
);
|