@demlik/tea 0.1.0 → 0.1.1

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.
Files changed (238) hide show
  1. package/LICENSE +21 -0
  2. package/dist/agent/index.d.ts +907 -0
  3. package/dist/agent/index.js +20 -0
  4. package/dist/agent/index.js.map +1 -0
  5. package/dist/authed-call/index.d.ts +119 -0
  6. package/dist/authed-call/index.js +148 -0
  7. package/dist/authed-call/index.js.map +1 -0
  8. package/dist/await-terminal/index.d.ts +99 -0
  9. package/dist/await-terminal/index.js +75 -0
  10. package/dist/await-terminal/index.js.map +1 -0
  11. package/dist/batch-window/index.d.ts +259 -0
  12. package/dist/batch-window/index.js +43 -0
  13. package/dist/batch-window/index.js.map +1 -0
  14. package/dist/cache/index.d.ts +2 -2
  15. package/dist/cache/index.js +2 -50
  16. package/dist/cache/index.js.map +1 -1
  17. package/dist/{chunk-CMG2KMWX.js → chunk-2WZHS4P2.js} +220 -177
  18. package/dist/chunk-2WZHS4P2.js.map +1 -0
  19. package/dist/chunk-2YOE5PIS.js +45 -0
  20. package/dist/chunk-2YOE5PIS.js.map +1 -0
  21. package/dist/chunk-3545BOYL.js +65 -0
  22. package/dist/chunk-3545BOYL.js.map +1 -0
  23. package/dist/chunk-5VNWZADP.js +49 -0
  24. package/dist/chunk-5VNWZADP.js.map +1 -0
  25. package/dist/{chunk-ZRUST6BK.js → chunk-7FYQGDMF.js} +2 -2
  26. package/dist/chunk-7FYQGDMF.js.map +1 -0
  27. package/dist/chunk-7VEG4KHB.js +202 -0
  28. package/dist/chunk-7VEG4KHB.js.map +1 -0
  29. package/dist/{chunk-PYBQREFU.js → chunk-A56GNPI7.js} +20 -6
  30. package/dist/chunk-A56GNPI7.js.map +1 -0
  31. package/dist/chunk-BNJYE4AU.js +157 -0
  32. package/dist/chunk-BNJYE4AU.js.map +1 -0
  33. package/dist/chunk-BYQUGDD3.js +16 -0
  34. package/dist/chunk-BYQUGDD3.js.map +1 -0
  35. package/dist/chunk-D5EQDLDV.js +186 -0
  36. package/dist/chunk-D5EQDLDV.js.map +1 -0
  37. package/dist/chunk-EDGDR5XX.js +60 -0
  38. package/dist/chunk-EDGDR5XX.js.map +1 -0
  39. package/dist/chunk-EIZJTYKR.js +93 -0
  40. package/dist/chunk-EIZJTYKR.js.map +1 -0
  41. package/dist/chunk-EQRUAP2A.js +56 -0
  42. package/dist/chunk-EQRUAP2A.js.map +1 -0
  43. package/dist/chunk-FH5RUIIL.js +61 -0
  44. package/dist/chunk-FH5RUIIL.js.map +1 -0
  45. package/dist/chunk-HJO6VNQI.js +15 -0
  46. package/dist/chunk-HJO6VNQI.js.map +1 -0
  47. package/dist/chunk-IFBQJYGI.js +132 -0
  48. package/dist/chunk-IFBQJYGI.js.map +1 -0
  49. package/dist/chunk-IN33Q4VJ.js +52 -0
  50. package/dist/chunk-IN33Q4VJ.js.map +1 -0
  51. package/dist/chunk-JELSZN25.js +47 -0
  52. package/dist/chunk-JELSZN25.js.map +1 -0
  53. package/dist/chunk-K575PT4S.js +58 -0
  54. package/dist/chunk-K575PT4S.js.map +1 -0
  55. package/dist/chunk-LEC4U6CX.js +91 -0
  56. package/dist/chunk-LEC4U6CX.js.map +1 -0
  57. package/dist/{chunk-Y5JM3UUH.js → chunk-NSDFA6M6.js} +75 -3
  58. package/dist/chunk-NSDFA6M6.js.map +1 -0
  59. package/dist/chunk-QGZW4W3E.js +20 -0
  60. package/dist/chunk-QGZW4W3E.js.map +1 -0
  61. package/dist/{chunk-PYOCUBQJ.js → chunk-RGTPPF4U.js} +22 -15
  62. package/dist/chunk-RGTPPF4U.js.map +1 -0
  63. package/dist/chunk-RVJFGRGK.js +222 -0
  64. package/dist/chunk-RVJFGRGK.js.map +1 -0
  65. package/dist/chunk-RVU3RBE6.js +31 -0
  66. package/dist/chunk-RVU3RBE6.js.map +1 -0
  67. package/dist/chunk-SC3FAFZN.js +53 -0
  68. package/dist/chunk-SC3FAFZN.js.map +1 -0
  69. package/dist/chunk-SINXE47Y.js +55 -0
  70. package/dist/chunk-SINXE47Y.js.map +1 -0
  71. package/dist/chunk-TAO4YOLO.js +87 -0
  72. package/dist/chunk-TAO4YOLO.js.map +1 -0
  73. package/dist/chunk-TC4HWABA.js +506 -0
  74. package/dist/chunk-TC4HWABA.js.map +1 -0
  75. package/dist/chunk-TGG26XMK.js +52 -0
  76. package/dist/chunk-TGG26XMK.js.map +1 -0
  77. package/dist/chunk-UV6UWGEO.js +147 -0
  78. package/dist/chunk-UV6UWGEO.js.map +1 -0
  79. package/dist/chunk-UYWUVEP6.js +158 -0
  80. package/dist/chunk-UYWUVEP6.js.map +1 -0
  81. package/dist/chunk-WUV3PSCZ.js +54 -0
  82. package/dist/chunk-WUV3PSCZ.js.map +1 -0
  83. package/dist/chunk-XRXKH7KA.js +268 -0
  84. package/dist/chunk-XRXKH7KA.js.map +1 -0
  85. package/dist/circuit-breaker/index.js +1 -51
  86. package/dist/circuit-breaker/index.js.map +1 -1
  87. package/dist/core-CymXZCeY.d.ts +178 -0
  88. package/dist/deadline/index.d.ts +24 -5
  89. package/dist/deadline/index.js +4 -18
  90. package/dist/deadline/index.js.map +1 -1
  91. package/dist/debounce/index.js +1 -54
  92. package/dist/debounce/index.js.map +1 -1
  93. package/dist/devtools/index.d.ts +1 -1
  94. package/dist/devtools/index.js +18 -6
  95. package/dist/devtools/index.js.map +1 -1
  96. package/dist/do/index.d.ts +1732 -92
  97. package/dist/do/index.js +677 -31
  98. package/dist/do/index.js.map +1 -1
  99. package/dist/durable-effects-2MDxDs45.d.ts +180 -0
  100. package/dist/extension/index.d.ts +31 -13
  101. package/dist/extension/index.js +5 -3
  102. package/dist/extension/index.js.map +1 -1
  103. package/dist/extension/react.js +8 -3
  104. package/dist/extension/react.js.map +1 -1
  105. package/dist/extension/subs/index.d.ts +2 -2
  106. package/dist/extension/subs/index.js.map +1 -1
  107. package/dist/extension/test-utils.js +11 -3
  108. package/dist/extension/test-utils.js.map +1 -1
  109. package/dist/fan-out/index.d.ts +239 -0
  110. package/dist/fan-out/index.js +5 -0
  111. package/dist/fan-out/index.js.map +1 -0
  112. package/dist/idempotency/adapter.d.ts +62 -0
  113. package/dist/idempotency/adapter.js +4 -0
  114. package/dist/idempotency/adapter.js.map +1 -0
  115. package/dist/idempotency/index.js +1 -56
  116. package/dist/idempotency/index.js.map +1 -1
  117. package/dist/idempotent-intake/index.d.ts +186 -0
  118. package/dist/idempotent-intake/index.js +7 -0
  119. package/dist/idempotent-intake/index.js.map +1 -0
  120. package/dist/index.d.ts +341 -191
  121. package/dist/index.js +2 -1
  122. package/dist/llm-call/index.d.ts +309 -0
  123. package/dist/llm-call/index.js +14 -0
  124. package/dist/llm-call/index.js.map +1 -0
  125. package/dist/machine-viz/index.d.ts +1 -1
  126. package/dist/machine-viz/index.js +1 -1
  127. package/dist/machine-viz/index.js.map +1 -1
  128. package/dist/mem/index.d.ts +1 -0
  129. package/dist/monitored-run/index.d.ts +253 -0
  130. package/dist/monitored-run/index.js +10 -0
  131. package/dist/monitored-run/index.js.map +1 -0
  132. package/dist/node/index.d.ts +5 -5
  133. package/dist/node/index.js.map +1 -1
  134. package/dist/paginated-walk/index.d.ts +234 -0
  135. package/dist/paginated-walk/index.js +15 -0
  136. package/dist/paginated-walk/index.js.map +1 -0
  137. package/dist/paginator/index.d.ts +271 -0
  138. package/dist/paginator/index.js +3 -0
  139. package/dist/paginator/index.js.map +1 -0
  140. package/dist/parity/index.d.ts +86 -0
  141. package/dist/parity/index.js +77 -0
  142. package/dist/parity/index.js.map +1 -0
  143. package/dist/pbt/arbitraries/index.d.ts +1 -1
  144. package/dist/pbt/arbitraries/index.js +1 -1
  145. package/dist/pbt/index.d.ts +1 -1
  146. package/dist/pbt/index.js +5 -4
  147. package/dist/pbt/index.js.map +1 -1
  148. package/dist/pbt/runners/index.d.ts +1 -1
  149. package/dist/pbt/runners/index.js +3 -2
  150. package/dist/poller/index.d.ts +288 -0
  151. package/dist/poller/index.js +79 -0
  152. package/dist/poller/index.js.map +1 -0
  153. package/dist/prediction/index.d.ts +109 -0
  154. package/dist/prediction/index.js +4 -0
  155. package/dist/prediction/index.js.map +1 -0
  156. package/dist/protocol-B5YmJr0d.d.ts +45 -0
  157. package/dist/pure/index.d.ts +2 -0
  158. package/dist/pure/index.js +4 -0
  159. package/dist/pure/index.js.map +1 -0
  160. package/dist/raft/demo.d.ts +105 -0
  161. package/dist/raft/demo.js +172 -0
  162. package/dist/raft/demo.js.map +1 -0
  163. package/dist/raft/index.d.ts +548 -0
  164. package/dist/raft/index.js +7 -0
  165. package/dist/raft/index.js.map +1 -0
  166. package/dist/raft/sim.d.ts +222 -0
  167. package/dist/raft/sim.js +8 -0
  168. package/dist/raft/sim.js.map +1 -0
  169. package/dist/raft/timeline.d.ts +46 -0
  170. package/dist/raft/timeline.js +62 -0
  171. package/dist/raft/timeline.js.map +1 -0
  172. package/dist/rate-limit/index.js +1 -43
  173. package/dist/rate-limit/index.js.map +1 -1
  174. package/dist/react/index.d.ts +2 -1
  175. package/dist/react/index.js +39 -20
  176. package/dist/react/index.js.map +1 -1
  177. package/dist/reconciler/index.d.ts +192 -0
  178. package/dist/reconciler/index.js +166 -0
  179. package/dist/reconciler/index.js.map +1 -0
  180. package/dist/recorder/index.d.ts +7 -3
  181. package/dist/recorder/index.js +1 -155
  182. package/dist/recorder/index.js.map +1 -1
  183. package/dist/resilient-call/index.d.ts +251 -0
  184. package/dist/resilient-call/index.js +13 -0
  185. package/dist/resilient-call/index.js.map +1 -0
  186. package/dist/retry-backoff/index.d.ts +42 -5
  187. package/dist/retry-backoff/index.js +1 -35
  188. package/dist/retry-backoff/index.js.map +1 -1
  189. package/dist/saga/index.d.ts +225 -0
  190. package/dist/saga/index.js +150 -0
  191. package/dist/saga/index.js.map +1 -0
  192. package/dist/snapshot/index.d.ts +334 -0
  193. package/dist/snapshot/index.js +5 -0
  194. package/dist/snapshot/index.js.map +1 -0
  195. package/dist/subs/index.d.ts +48 -10
  196. package/dist/subs/index.js +1 -1
  197. package/dist/testing/index.d.ts +107 -2
  198. package/dist/testing/index.js +204 -6
  199. package/dist/testing/index.js.map +1 -1
  200. package/dist/throttle/index.js +1 -52
  201. package/dist/throttle/index.js.map +1 -1
  202. package/dist/throttled-input/index.d.ts +372 -0
  203. package/dist/throttled-input/index.js +88 -0
  204. package/dist/throttled-input/index.js.map +1 -0
  205. package/dist/token-refresh/index.d.ts +215 -0
  206. package/dist/token-refresh/index.js +6 -0
  207. package/dist/token-refresh/index.js.map +1 -0
  208. package/dist/trace-replay/index.d.ts +11 -2
  209. package/dist/trace-replay/index.js +3 -55
  210. package/dist/trace-replay/index.js.map +1 -1
  211. package/dist/{types-CwBC5wMn.d.ts → types-N9LZbdnr.d.ts} +1 -1
  212. package/dist/with-deadline/index.d.ts +196 -0
  213. package/dist/with-deadline/index.js +130 -0
  214. package/dist/with-deadline/index.js.map +1 -0
  215. package/dist/with-resilience/index.d.ts +205 -0
  216. package/dist/with-resilience/index.js +274 -0
  217. package/dist/with-resilience/index.js.map +1 -0
  218. package/dist/with-telemetry/index.d.ts +149 -0
  219. package/dist/with-telemetry/index.js +95 -0
  220. package/dist/with-telemetry/index.js.map +1 -0
  221. package/dist/work-queue/adapter.d.ts +82 -0
  222. package/dist/work-queue/adapter.js +4 -0
  223. package/dist/work-queue/adapter.js.map +1 -0
  224. package/dist/work-queue/index.d.ts +25 -11
  225. package/dist/work-queue/index.js +1 -46
  226. package/dist/work-queue/index.js.map +1 -1
  227. package/dist/work-queue/ops.d.ts +69 -0
  228. package/dist/work-queue/ops.js +3 -0
  229. package/dist/work-queue/ops.js.map +1 -0
  230. package/dist/workflow/index.d.ts +444 -0
  231. package/dist/workflow/index.js +225 -0
  232. package/dist/workflow/index.js.map +1 -0
  233. package/package.json +162 -25
  234. package/dist/chunk-CMG2KMWX.js.map +0 -1
  235. package/dist/chunk-PYBQREFU.js.map +0 -1
  236. package/dist/chunk-PYOCUBQJ.js.map +0 -1
  237. package/dist/chunk-Y5JM3UUH.js.map +0 -1
  238. package/dist/chunk-ZRUST6BK.js.map +0 -1
@@ -0,0 +1,225 @@
1
+ import { C as Cmd } from '../core-CymXZCeY.js';
2
+ import { QueueItem } from '../work-queue/index.js';
3
+ import '../index.js';
4
+
5
+ /**
6
+ * @demlik/tea/saga — a forward-then-compensate transaction over an ordered list
7
+ * of reversible steps.
8
+ *
9
+ * The Level-2 combinator for "run these N steps in order; if any step fails,
10
+ * undo the steps that already succeeded, in reverse." It is the distributed-
11
+ * transaction / compensation knob: each step is a `{ do, undo }` pair of Cmds,
12
+ * the saga drives `do` forward one step at a time, and on the first failure it
13
+ * pivots and drives `undo` backward over exactly the steps that completed.
14
+ *
15
+ * The recipe (which bricks it composes):
16
+ * - `../work-queue/adapter` — the saga's forward progress IS a work-queue
17
+ * lifecycle. Each step's record carries the same `{ id, status, input }`
18
+ * vocabulary (`pending → running → done | failed | cancelled`), so the step
19
+ * taxonomy is the substrate's status enum rather than a parallel invention.
20
+ * We reuse the pure `QueueItem` / `QueueItemStatus` types AND delegate every
21
+ * status flip to the `QueueAdapter` verbs: `wq.enqueue` stamps each fresh
22
+ * ledger record, and `wq.patch` performs every
23
+ * `pending → running → done | failed | cancelled` transition. The status
24
+ * transitions are NOT re-rolled here — they live in exactly one place
25
+ * behind the adapter, per the package's one-shape rule. The async
26
+ * `createQueue(store)` adapter is NOT used: its `load → mutate → save` reads
27
+ * the clock and lives at an I/O boundary, while a combinator's verbs must be
28
+ * pure (invariant 2). We bind the same ops to the in-Model ledger instead —
29
+ * durable + replayable, the two non-negotiables every knob preserves.
30
+ *
31
+ * The compensation log is the spec's `done: StepId[]` — the indices of the
32
+ * steps that completed forward, in the order they completed. On `stepErr` the
33
+ * saga walks that log in reverse, emitting one `undo` per `undoOk`, so the
34
+ * unwind is the exact mirror of the wind. If an `undo` ITSELF fails, `undoErr`
35
+ * pivots to the terminal `compensation_failed` phase: a failed compensation is
36
+ * a real-world fact (a refund that bounced, a hold that won't release) that the
37
+ * consumer must see and reconcile by hand — never a saga wedged in
38
+ * `compensating` forever.
39
+ *
40
+ * Typical wiring (combinator form — splice the hooks into your machine):
41
+ *
42
+ * const saga = createSaga<BookFlight | ChargeCard | ..., Cancel | Refund | ...>({
43
+ * steps: [
44
+ * { do: { type: "book_flight" }, undo: { type: "cancel_flight" } },
45
+ * { do: { type: "charge_card" }, undo: { type: "refund_card" } },
46
+ * { do: { type: "reserve_hotel" },undo: { type: "release_hotel" } },
47
+ * ],
48
+ * });
49
+ *
50
+ * // in `update`:
51
+ * begin: (s) => lift(s, saga.start(s.saga)),
52
+ * step_ok: (s) => lift(s, saga.stepOk(s.saga)),
53
+ * step_err: (s, m) => lift(s, saga.stepErr(s.saga, m.error)),
54
+ * undo_ok: (s) => lift(s, saga.undoOk(s.saga)),
55
+ * undo_err: (s, m) => lift(s, saga.undoErr(s.saga, m.error)),
56
+ *
57
+ * Every verb is PURE: it returns a NEW slice plus the Cmds to perform (the next
58
+ * `do` going forward, or the next `undo` rolling back). The reducer never reads
59
+ * a clock or RNG — step identity is positional (the index into `config.steps`),
60
+ * so progress survives a round-trip through the durable slice and resumes
61
+ * exactly where it left off after a DO eviction.
62
+ *
63
+ * There is no `subs` and no `handlers`: a saga runs no timers, and the `do` /
64
+ * `undo` Cmds are fully caller-defined (the consumer's own `interpret` performs
65
+ * each effect and routes Ok/Err back to the `stepOk` / `stepErr` / `undoOk`
66
+ * verbs — the same shape `resilient-fetch` uses with `tryInterpret`). The saga
67
+ * owns the ORDER; the consumer owns the I/O. Pure-ops module, like
68
+ * `retry-backoff`.
69
+ *
70
+ * NOT a substrate primitive: it depends only on `../work-queue`'s pure types
71
+ * and `../index`'s `Cmd` type. Consumers reach it via the `@demlik/tea/saga`
72
+ * subpath.
73
+ */
74
+
75
+ /**
76
+ * A step's stable identity. Positional: the 0-based index into
77
+ * `config.steps`. Positional ids are PURE (no clock, no RNG) and survive a
78
+ * round-trip through the durable slice, so `done` can be replayed to resume an
79
+ * interrupted saga exactly. The compensation log is a list of these.
80
+ */
81
+ type StepId = number;
82
+ /**
83
+ * One step of the saga: the forward effect and its compensating inverse, both
84
+ * as data (plain Cmds). `do` runs while winding forward; `undo` runs while
85
+ * unwinding after a failure. The pair is the unit of reversibility — a step
86
+ * that completed (`do` succeeded) is exactly a step whose `undo` must run if a
87
+ * later step fails.
88
+ */
89
+ interface SagaStep<D extends Cmd, U extends Cmd> {
90
+ /** The forward effect, performed while the saga winds forward. */
91
+ readonly do: D;
92
+ /** The compensating inverse, performed (in reverse) while the saga unwinds. */
93
+ readonly undo: U;
94
+ }
95
+ /**
96
+ * The knob. The ordered list of reversible steps. The list is fixed for the
97
+ * life of one saga instance (a saga drives a known transaction); per-run inputs
98
+ * ride on the consumer's Msgs, not here.
99
+ */
100
+ interface SagaConfig<D extends Cmd, U extends Cmd> {
101
+ /** The steps, in forward order. `do` runs `0 → n-1`; `undo` runs the completed prefix `n-1 → 0`. */
102
+ readonly steps: readonly SagaStep<D, U>[];
103
+ }
104
+ /**
105
+ * The lifecycle phase of a saga, narrowed at the type level so a consumer can
106
+ * branch on `state.phase` (and a Transitions-table reducer can key on it).
107
+ *
108
+ * - `"idle"` — created, not started. No step has run.
109
+ * - `"running"` — winding forward; `position` is the in-flight step.
110
+ * - `"compensating"` — a step failed; unwinding `done` in reverse.
111
+ * - `"committed"` — every step completed forward. Terminal success.
112
+ * - `"aborted"` — compensation finished (every completed step undone, or
113
+ * the first step itself failed with nothing to undo).
114
+ * Terminal failure, fully unwound.
115
+ * - `"compensation_failed"` — an `undo` itself failed mid-rollback. Terminal
116
+ * failure, PARTIALLY unwound: the steps still in `done`
117
+ * were never compensated and must be reconciled by hand.
118
+ * Distinguished from `aborted` precisely so a stuck
119
+ * rollback is visible state, not a saga wedged in
120
+ * `compensating` forever.
121
+ */
122
+ type SagaPhase = "idle" | "running" | "compensating" | "committed" | "aborted" | "compensation_failed";
123
+ /**
124
+ * The slice this knob owns.
125
+ *
126
+ * The spec's three fields are load-bearing:
127
+ * - `position` — the index of the step currently in flight while `running`,
128
+ * or the index being compensated while `compensating`. Survives eviction,
129
+ * so `boot` resumes mid-saga from the durable slice.
130
+ * - `done` — the compensation log: the ids of steps that completed forward,
131
+ * in completion order. `undo` walks this in reverse. This is the single
132
+ * source of truth for what must be unwound.
133
+ * - `compensating` — the direction bit. `false` while winding forward, `true`
134
+ * once a failure has pivoted the saga into rollback.
135
+ *
136
+ * Plus:
137
+ * - `phase` — the derived lifecycle tag (see `SagaPhase`). Kept in the slice
138
+ * (not recomputed) so a consumer's view and Transitions reducer can key on
139
+ * `state.phase` directly, and the terminal states (`committed` / `aborted`)
140
+ * are explicit facts rather than "position past the end" arithmetic.
141
+ * - `error` — the forward failure that triggered compensation, carried
142
+ * forward verbatim (`unknown`) for the consumer to read, never interpreted
143
+ * (same discipline as `retry-backoff`'s `lastError` and `fan-out`'s
144
+ * `error`).
145
+ * - `compensationError` — the failure of an `undo` itself, set only when the
146
+ * saga reaches `compensation_failed`. Kept distinct from `error` (the
147
+ * forward failure) so a consumer reconciling a stuck rollback can read both
148
+ * "what broke the transaction" and "which compensation then bounced".
149
+ * Carried verbatim, never interpreted, same as `error`.
150
+ * - `items` — the work-queue ledger, one `QueueItem` per step, keyed by the
151
+ * step's positional id. The single source of truth for each step's status;
152
+ * `phase` / `position` / `done` are the projection the verbs keep in
153
+ * lockstep with it.
154
+ *
155
+ * Every field is `readonly` and JSON-serializable (plain numbers, arrays, and
156
+ * the work-queue's plain `QueueItem` records), so the slice round-trips through
157
+ * a consumer's `Store<S>` unchanged — durable across DO eviction.
158
+ */
159
+ interface SagaState<I = StepId> {
160
+ /** The step in flight (`running`) or being compensated (`compensating`). */
161
+ readonly position: number;
162
+ /** The compensation log: ids of completed-forward steps, in completion order. */
163
+ readonly done: readonly StepId[];
164
+ /** Direction bit: `false` winding forward, `true` unwinding. */
165
+ readonly compensating: boolean;
166
+ /** The derived lifecycle tag (see `SagaPhase`). */
167
+ readonly phase: SagaPhase;
168
+ /** The forward failure that triggered compensation, if any. Carried, never interpreted. */
169
+ readonly error?: unknown;
170
+ /** The failure of an `undo` itself (only when `compensation_failed`). Carried, never interpreted. */
171
+ readonly compensationError?: unknown;
172
+ /** The work-queue ledger: one record per step, keyed by positional id. */
173
+ readonly items: readonly QueueItem<I>[];
174
+ }
175
+ /** Whether the saga has terminated successfully (every step committed). */
176
+ declare function isCommitted<I>(state: SagaState<I>): boolean;
177
+ /** Whether the saga has terminated in failure, fully unwound (every completed step undone). */
178
+ declare function isAborted<I>(state: SagaState<I>): boolean;
179
+ /**
180
+ * Whether the saga has terminated in failure with an UNFINISHED rollback: an
181
+ * `undo` itself failed, so some completed steps were never compensated and need
182
+ * hand reconciliation. Terminal, but distinct from `aborted` (fully unwound).
183
+ */
184
+ declare function isCompensationFailed<I>(state: SagaState<I>): boolean;
185
+ /**
186
+ * Whether the saga has reached a terminal phase (success, fully-unwound
187
+ * failure, or compensation-failed). Derived — reads the slice, never mutates.
188
+ * Consumers branch their own phase off this; no further verb has any effect
189
+ * once it holds (the verbs guard on phase and no-op).
190
+ */
191
+ declare function isSettled<I>(state: SagaState<I>): boolean;
192
+ /**
193
+ * The starting slice: idle, nothing run, winding-forward direction. `items` is
194
+ * empty until `start` stamps one ledger record per configured step — the slice
195
+ * is generic in the ledger payload `I`, defaulting to the positional `StepId`
196
+ * since a saga's "input" per step is just its index (the consumer's real inputs
197
+ * ride on its own Msgs).
198
+ */
199
+ declare function initSaga<I = StepId>(): SagaState<I>;
200
+ /**
201
+ * Build the saga knob from `config`. Returns the uniform combinator contract:
202
+ * `init` for the owned slice and the five lifecycle verbs (`start`, `stepOk`,
203
+ * `stepErr`, `undoOk`, `undoErr`).
204
+ *
205
+ * No `subs` and no `handlers` — a saga runs no timers, and each step's `do` /
206
+ * `undo` effect is owned by the consumer's `interpret` (the saga emits the Cmd;
207
+ * the consumer performs it and routes the outcome back to a verb). The saga's
208
+ * sole job is the ORDER: which Cmd to emit next, and when to pivot from winding
209
+ * to unwinding (and when a failed `undo` ends the rollback). Pure-ops module —
210
+ * matches `retry-backoff`'s shape.
211
+ */
212
+ declare function createSaga<D extends Cmd, U extends Cmd>(config: SagaConfig<D, U>): {
213
+ init: () => SagaState<number>;
214
+ start: (state: SagaState<StepId>) => readonly [SagaState<StepId>, readonly D[]];
215
+ stepOk: (state: SagaState<StepId>) => readonly [SagaState<StepId>, readonly D[]];
216
+ stepErr: (state: SagaState<StepId>, error: unknown) => readonly [SagaState<StepId>, readonly U[]];
217
+ undoOk: (state: SagaState<StepId>) => readonly [SagaState<StepId>, readonly U[]];
218
+ undoErr: (state: SagaState<StepId>, error: unknown) => readonly [SagaState<StepId>, readonly U[]];
219
+ isCommitted: typeof isCommitted;
220
+ isAborted: typeof isAborted;
221
+ isCompensationFailed: typeof isCompensationFailed;
222
+ isSettled: typeof isSettled;
223
+ };
224
+
225
+ export { type SagaConfig, type SagaPhase, type SagaState, type SagaStep, type StepId, createSaga, initSaga, isAborted, isCommitted, isCompensationFailed, isSettled };
@@ -0,0 +1,150 @@
1
+ import { queueAdapter } from '../chunk-HJO6VNQI.js';
2
+ import '../chunk-TGG26XMK.js';
3
+
4
+ // src/saga/index.ts
5
+ function isCommitted(state) {
6
+ return state.phase === "committed";
7
+ }
8
+ function isAborted(state) {
9
+ return state.phase === "aborted";
10
+ }
11
+ function isCompensationFailed(state) {
12
+ return state.phase === "compensation_failed";
13
+ }
14
+ function isSettled(state) {
15
+ return state.phase === "committed" || state.phase === "aborted" || state.phase === "compensation_failed";
16
+ }
17
+ function initSaga() {
18
+ return {
19
+ position: 0,
20
+ done: [],
21
+ compensating: false,
22
+ phase: "idle",
23
+ items: []
24
+ };
25
+ }
26
+ function createSaga(config) {
27
+ const wq = queueAdapter();
28
+ function freshLedger() {
29
+ let items = [];
30
+ config.steps.forEach((_step, index) => {
31
+ items = wq.enqueue(items, index, 0, String(index)).next;
32
+ });
33
+ return items;
34
+ }
35
+ function setStatus(items, index, status) {
36
+ return wq.patch(items, String(index), (item) => ({
37
+ ...item,
38
+ status
39
+ })).next;
40
+ }
41
+ function stepAt(index) {
42
+ return config.steps[index];
43
+ }
44
+ function lastDone(done) {
45
+ return done[done.length - 1];
46
+ }
47
+ function start(state) {
48
+ if (state.phase !== "idle") return [state, []];
49
+ const items = freshLedger();
50
+ const first = stepAt(0);
51
+ if (first === void 0) {
52
+ return [{ ...state, phase: "committed", items }, []];
53
+ }
54
+ const next = {
55
+ ...state,
56
+ position: 0,
57
+ phase: "running",
58
+ items: setStatus(items, 0, "running")
59
+ };
60
+ return [next, [first.do]];
61
+ }
62
+ function stepOk(state) {
63
+ if (state.phase !== "running") return [state, []];
64
+ const completed = state.position;
65
+ const itemsDone = setStatus(state.items, completed, "done");
66
+ const done = [...state.done, completed];
67
+ const nextPosition = completed + 1;
68
+ const nextStep = stepAt(nextPosition);
69
+ if (nextStep === void 0) {
70
+ return [{ ...state, done, items: itemsDone, phase: "committed" }, []];
71
+ }
72
+ const next = {
73
+ ...state,
74
+ position: nextPosition,
75
+ done,
76
+ items: setStatus(itemsDone, nextPosition, "running")
77
+ };
78
+ return [next, [nextStep.do]];
79
+ }
80
+ function stepErr(state, error) {
81
+ if (state.phase !== "running") return [state, []];
82
+ const failed = state.position;
83
+ const items = setStatus(state.items, failed, "failed");
84
+ const undoIndex = lastDone(state.done);
85
+ const undoStep = undoIndex === void 0 ? void 0 : stepAt(undoIndex);
86
+ if (undoIndex === void 0 || undoStep === void 0) {
87
+ return [
88
+ { ...state, items, error, compensating: true, phase: "aborted" },
89
+ []
90
+ ];
91
+ }
92
+ const next = {
93
+ ...state,
94
+ items,
95
+ error,
96
+ compensating: true,
97
+ phase: "compensating",
98
+ position: undoIndex
99
+ };
100
+ return [next, [undoStep.undo]];
101
+ }
102
+ function undoOk(state) {
103
+ if (state.phase !== "compensating") return [state, []];
104
+ const undone = lastDone(state.done);
105
+ if (undone === void 0) return [state, []];
106
+ const remaining = state.done.slice(0, -1);
107
+ const items = setStatus(state.items, undone, "cancelled");
108
+ const nextUndo = lastDone(remaining);
109
+ const nextStep = nextUndo === void 0 ? void 0 : stepAt(nextUndo);
110
+ if (nextUndo === void 0 || nextStep === void 0) {
111
+ return [{ ...state, done: remaining, items, phase: "aborted" }, []];
112
+ }
113
+ const next = {
114
+ ...state,
115
+ done: remaining,
116
+ items,
117
+ position: nextUndo
118
+ };
119
+ return [next, [nextStep.undo]];
120
+ }
121
+ function undoErr(state, error) {
122
+ if (state.phase !== "compensating") return [state, []];
123
+ const items = setStatus(state.items, state.position, "failed");
124
+ return [
125
+ {
126
+ ...state,
127
+ items,
128
+ compensationError: error,
129
+ phase: "compensation_failed"
130
+ },
131
+ []
132
+ ];
133
+ }
134
+ return {
135
+ init: initSaga,
136
+ start,
137
+ stepOk,
138
+ stepErr,
139
+ undoOk,
140
+ undoErr,
141
+ isCommitted,
142
+ isAborted,
143
+ isCompensationFailed,
144
+ isSettled
145
+ };
146
+ }
147
+
148
+ export { createSaga, initSaga, isAborted, isCommitted, isCompensationFailed, isSettled };
149
+ //# sourceMappingURL=index.js.map
150
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/saga/index.ts"],"names":[],"mappings":";;;;AA0LO,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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AA,MAAM,QAAA,GAAW,SAAS,SAAS,CAAA;AACnC,IAAA,MAAM,QAAA,GAAW,QAAA,KAAa,MAAA,GAAY,MAAA,GAAY,OAAO,QAAQ,CAAA;AACrE,IAAA,IAAI,QAAA,KAAa,MAAA,IAAa,QAAA,KAAa,MAAA,EAAW;AAEpD,MAAA,OAAO,CAAC,EAAE,GAAG,KAAA,EAAO,IAAA,EAAM,SAAA,EAAW,KAAA,EAAO,KAAA,EAAO,SAAA,EAAU,EAAG,EAAE,CAAA;AAAA,IACpE;AAEA,IAAA,MAAM,IAAA,GAA0B;AAAA,MAC9B,GAAG,KAAA;AAAA,MACH,IAAA,EAAM,SAAA;AAAA,MACN,KAAA;AAAA,MACA,QAAA,EAAU;AAAA,KACZ;AACA,IAAA,OAAO,CAAC,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 * 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"]}