@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.
Files changed (145) hide show
  1. package/dist/agent/index.d.ts +2 -2
  2. package/dist/agent/index.js +8 -8
  3. package/dist/authed-call/index.d.ts +3 -3
  4. package/dist/authed-call/index.js +5 -5
  5. package/dist/await-terminal/index.d.ts +1 -1
  6. package/dist/await-terminal/index.js +2 -2
  7. package/dist/batch-window/index.d.ts +2 -2
  8. package/dist/batch-window/index.js +4 -4
  9. package/dist/cache/index.d.ts +2 -2
  10. package/dist/{chunk-RVJFGRGK.js → chunk-27N2SPTN.js} +4 -4
  11. package/dist/chunk-27N2SPTN.js.map +1 -0
  12. package/dist/{chunk-FH5RUIIL.js → chunk-3XJWC7VW.js} +3 -3
  13. package/dist/{chunk-FH5RUIIL.js.map → chunk-3XJWC7VW.js.map} +1 -1
  14. package/dist/{chunk-IFBQJYGI.js → chunk-5DEQ5I3U.js} +3 -3
  15. package/dist/{chunk-IFBQJYGI.js.map → chunk-5DEQ5I3U.js.map} +1 -1
  16. package/dist/{chunk-XRXKH7KA.js → chunk-6RGBKODV.js} +3 -3
  17. package/dist/{chunk-XRXKH7KA.js.map → chunk-6RGBKODV.js.map} +1 -1
  18. package/dist/{chunk-D5EQDLDV.js → chunk-7W4LMPUW.js} +4 -4
  19. package/dist/{chunk-D5EQDLDV.js.map → chunk-7W4LMPUW.js.map} +1 -1
  20. package/dist/{chunk-A56GNPI7.js → chunk-DILMKOZ7.js} +5 -23
  21. package/dist/chunk-DILMKOZ7.js.map +1 -0
  22. package/dist/{chunk-EIZJTYKR.js → chunk-EHIX7NYZ.js} +4 -4
  23. package/dist/{chunk-EIZJTYKR.js.map → chunk-EHIX7NYZ.js.map} +1 -1
  24. package/dist/{chunk-WUV3PSCZ.js → chunk-HCEVHFJ7.js} +2 -2
  25. package/dist/chunk-HCEVHFJ7.js.map +1 -0
  26. package/dist/{chunk-EQRUAP2A.js → chunk-J6527VRQ.js} +2 -2
  27. package/dist/chunk-J6527VRQ.js.map +1 -0
  28. package/dist/{chunk-QGZW4W3E.js → chunk-K7Q23EQ4.js} +3 -3
  29. package/dist/{chunk-QGZW4W3E.js.map → chunk-K7Q23EQ4.js.map} +1 -1
  30. package/dist/{chunk-RGTPPF4U.js → chunk-LP7VQBRG.js} +3 -3
  31. package/dist/{chunk-RGTPPF4U.js.map → chunk-LP7VQBRG.js.map} +1 -1
  32. package/dist/{chunk-2WZHS4P2.js → chunk-MMH7CW5K.js} +4 -16
  33. package/dist/chunk-MMH7CW5K.js.map +1 -0
  34. package/dist/{chunk-EDGDR5XX.js → chunk-ON24RKSE.js} +3 -3
  35. package/dist/{chunk-EDGDR5XX.js.map → chunk-ON24RKSE.js.map} +1 -1
  36. package/dist/{chunk-TAO4YOLO.js → chunk-PS23H6KQ.js} +3 -3
  37. package/dist/{chunk-TAO4YOLO.js.map → chunk-PS23H6KQ.js.map} +1 -1
  38. package/dist/{chunk-BNJYE4AU.js → chunk-QLA76GIT.js} +21 -16
  39. package/dist/chunk-QLA76GIT.js.map +1 -0
  40. package/dist/{chunk-TC4HWABA.js → chunk-S3FQN4SL.js} +7 -7
  41. package/dist/{chunk-TC4HWABA.js.map → chunk-S3FQN4SL.js.map} +1 -1
  42. package/dist/{chunk-RVU3RBE6.js → chunk-SQTCS44W.js} +6 -4
  43. package/dist/chunk-SQTCS44W.js.map +1 -0
  44. package/dist/{chunk-7VEG4KHB.js → chunk-VLGARN6H.js} +3 -3
  45. package/dist/{chunk-7VEG4KHB.js.map → chunk-VLGARN6H.js.map} +1 -1
  46. package/dist/{core-CymXZCeY.d.ts → core-BoB6t7dB.d.ts} +11 -1
  47. package/dist/deadline/index.d.ts +2 -2
  48. package/dist/deadline/index.js +3 -3
  49. package/dist/debounce/index.d.ts +6 -0
  50. package/dist/debounce/index.js +1 -1
  51. package/dist/do/index.d.ts +15 -24
  52. package/dist/do/index.js +9 -13
  53. package/dist/do/index.js.map +1 -1
  54. package/dist/{durable-effects-2MDxDs45.d.ts → durable-effects-CO9Uh971.d.ts} +1 -1
  55. package/dist/extension/index.d.ts +1 -1
  56. package/dist/extension/index.js +3 -3
  57. package/dist/extension/react.js +3 -3
  58. package/dist/extension/subs/index.d.ts +2 -2
  59. package/dist/fan-out/index.d.ts +1 -1
  60. package/dist/idempotent-intake/index.d.ts +1 -1
  61. package/dist/index.d.ts +2 -2
  62. package/dist/index.js +2 -2
  63. package/dist/llm-call/index.d.ts +2 -2
  64. package/dist/llm-call/index.js +5 -5
  65. package/dist/machine-viz/index.d.ts +4 -4
  66. package/dist/machine-viz/index.js +4 -8
  67. package/dist/machine-viz/index.js.map +1 -1
  68. package/dist/mem/index.d.ts +1 -1
  69. package/dist/monitored-run/index.d.ts +2 -2
  70. package/dist/monitored-run/index.js +5 -5
  71. package/dist/node/index.d.ts +1 -1
  72. package/dist/paginated-walk/index.d.ts +2 -2
  73. package/dist/paginated-walk/index.js +5 -5
  74. package/dist/parity/index.d.ts +10 -4
  75. package/dist/parity/index.js +6 -5
  76. package/dist/parity/index.js.map +1 -1
  77. package/dist/pbt/arbitraries/index.d.ts +1 -1
  78. package/dist/pbt/index.d.ts +15 -8
  79. package/dist/pbt/index.js +5 -11
  80. package/dist/pbt/index.js.map +1 -1
  81. package/dist/pbt/runners/index.d.ts +1 -1
  82. package/dist/pbt/runners/index.js +3 -3
  83. package/dist/poller/index.d.ts +2 -2
  84. package/dist/poller/index.js +3 -3
  85. package/dist/prediction/index.d.ts +23 -2
  86. package/dist/prediction/index.js +2 -2
  87. package/dist/pure/index.d.ts +2 -2
  88. package/dist/pure/index.js +2 -2
  89. package/dist/raft/demo.d.ts +2 -2
  90. package/dist/raft/demo.js +5 -5
  91. package/dist/raft/index.d.ts +3 -3
  92. package/dist/raft/index.js +4 -4
  93. package/dist/raft/sim.d.ts +2 -2
  94. package/dist/raft/sim.js +5 -5
  95. package/dist/raft/timeline.d.ts +2 -2
  96. package/dist/react/index.d.ts +1 -1
  97. package/dist/react/index.js +8 -4
  98. package/dist/react/index.js.map +1 -1
  99. package/dist/reconciler/index.d.ts +2 -2
  100. package/dist/reconciler/index.js +5 -5
  101. package/dist/recorder/index.d.ts +1 -1
  102. package/dist/resilient-call/index.d.ts +45 -2
  103. package/dist/resilient-call/index.js +4 -4
  104. package/dist/retry-to-success/index.d.ts +109 -0
  105. package/dist/retry-to-success/index.js +35 -0
  106. package/dist/retry-to-success/index.js.map +1 -0
  107. package/dist/saga/index.d.ts +14 -1
  108. package/dist/saga/index.js.map +1 -1
  109. package/dist/snapshot/index.d.ts +1 -1
  110. package/dist/snapshot/index.js +3 -3
  111. package/dist/subs/index.d.ts +2 -2
  112. package/dist/testing/index.d.ts +1 -1
  113. package/dist/testing/index.js +2 -2
  114. package/dist/throttle/index.d.ts +9 -0
  115. package/dist/throttle/index.js +1 -1
  116. package/dist/throttled-input/index.d.ts +10 -2
  117. package/dist/throttled-input/index.js +6 -6
  118. package/dist/throttled-input/index.js.map +1 -1
  119. package/dist/token-refresh/index.d.ts +1 -1
  120. package/dist/token-refresh/index.js +3 -3
  121. package/dist/trace-replay/index.d.ts +1 -1
  122. package/dist/trace-replay/index.js +3 -3
  123. package/dist/{types-N9LZbdnr.d.ts → types-B-8bcAp8.d.ts} +1 -1
  124. package/dist/with-deadline/index.d.ts +1 -1
  125. package/dist/with-deadline/index.js +5 -24
  126. package/dist/with-deadline/index.js.map +1 -1
  127. package/dist/with-resilience/index.d.ts +2 -2
  128. package/dist/with-resilience/index.js +13 -36
  129. package/dist/with-resilience/index.js.map +1 -1
  130. package/dist/with-telemetry/index.d.ts +1 -1
  131. package/dist/with-telemetry/index.js +4 -29
  132. package/dist/with-telemetry/index.js.map +1 -1
  133. package/dist/work-queue/adapter.d.ts +1 -1
  134. package/dist/work-queue/index.d.ts +1 -1
  135. package/dist/work-queue/ops.d.ts +1 -1
  136. package/dist/workflow/index.d.ts +16 -10
  137. package/dist/workflow/index.js.map +1 -1
  138. package/package.json +8 -2
  139. package/dist/chunk-2WZHS4P2.js.map +0 -1
  140. package/dist/chunk-A56GNPI7.js.map +0 -1
  141. package/dist/chunk-BNJYE4AU.js.map +0 -1
  142. package/dist/chunk-EQRUAP2A.js.map +0 -1
  143. package/dist/chunk-RVJFGRGK.js.map +0 -1
  144. package/dist/chunk-RVU3RBE6.js.map +0 -1
  145. package/dist/chunk-WUV3PSCZ.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/with-deadline/index.ts"],"names":[],"mappings":";;;;;AAuIO,SAAS,oBAAoB,GAAA,EAAkC;AACpE,EAAA,OAAO,EAAE,IAAA,EAAM,oBAAA,EAAsB,GAAA,EAAI;AAC3C;AA0EA,SAAS,aAAA,CAIP,MAAA,EAEA,IAAA,EACA,KAAA,EACA,GAAA,EAC4B;AAC5B,EAAA,IAAI,SAAS,SAAA,EAAW;AAEtB,IAAA,MAAM,MAAA,GAAS,MAAA;AAEf,IAAA,OAAO,MAAA,CAAO,GAAA,CAAI,IAAI,CAAA,CAAG,OAAO,GAAG,CAAA;AAAA,EACrC;AAEA,EAAA,MAAM,KAAA,GAAQ,MAAA;AAId,EAAA,MAAM,WAAY,KAAA,CAAsC,IAAA;AAExD,EAAA,OAAO,MAAM,QAAQ,CAAA,CAAG,IAAI,IAAI,CAAA,CAAG,OAAO,GAAG,CAAA;AAC/C;AAMA,SAAS,eAAA,CAAgB,QAAgB,IAAA,EAAqC;AAC5E,EAAA,MAAM,IAAA,GAAO,MAAA,CAAO,IAAA,CAAK,MAAM,CAAA;AAC/B,EAAA,MAAM,QAAA,GAAW,KAAK,CAAC,CAAA;AACvB,EAAA,IAAI,QAAA,KAAa,MAAA,EAAW,OAAO,EAAC;AACpC,EAAA,IAAI,IAAA,KAAS,WAAW,OAAO,IAAA;AAC/B,EAAA,MAAM,UAAA,GAAc,OAAmC,QAAQ,CAAA;AAC/D,EAAA,OAAO,MAAA,CAAO,KAAK,UAAoB,CAAA;AACzC;AA4BO,SAAS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AC,KAAA,EAAO,IAAI,IAAI,IAAA,CAAK,IAAA,CAAK,MAAM,GAAG,CAAA;AACzC,MAAA,MAAM,KAAA,GAA0B;AAAA,QAC9B,IAAA,EAAM,KAAA;AAAA,QACN,SAAA,EAAW,EAAE,KAAA,EAAO,OAAA,EAAS,KAAK,CAAA;AAAE,OACtC;AAGA,MAAA,OAAO,CAAC,OAAO,IAAI,CAAA;AAAA,IACrB,CAAA;AAAA,IACA,MAAA;AAAA,IAKA,aAAA;AAAA,IACA,SAAA;AAAA,IACA;AAAA,GACF;AAOF","file":"index.js","sourcesContent":["/**\n * @demlik/tea/with-deadline — auto-fail a wrapped machine at T+N, re-arm on\n * progress. A **pure function over machine data**: `withDeadline(base, config)`\n * takes any `Machine<S, M, C, U, Ctx>` and returns a NEW `Machine` over the\n * composed Model `{ base, $deadline }`. You `run()` / `replay()` the result\n * exactly like any other machine — there is no new runtime, no privileged\n * interception path.\n *\n * ## What it does\n *\n * The wrapper watches the base Msg stream. While the deadline is `armed`, a\n * RELATIVE timeout Sub counts down `config.ms`. Every base Msg the\n * `config.progress` predicate accepts (default: every base Msg) is treated as\n * activity: the wrapper bumps a numeric `seq`, which CHANGES the timer Sub's id,\n * so the substrate's reconcile pass retires the old countdown and starts a fresh\n * one — \"re-arm on progress\". If `config.ms` elapses with NO accepted progress,\n * the timeout Sub dispatches `$deadline:exceeded`; the merged `update` folds it\n * by flipping `phase` to `exceeded`, and from then on `subscriptions` returns no\n * timer (the machine has auto-failed). The expiry is a slice transition visible\n * in the Msg log — the auto-fail is never an off-ledger side effect.\n *\n * This is an OBSERVE-ONLY wrapper in the same sense as `withTelemetry`: it never\n * intercepts a base Cmd and never gates a base Msg. `state.base` after wrapping\n * is BYTE-IDENTICAL to running the base alone, so the shared\n * `assertWrapperFaithful` gate passes with the deadline bolted on.\n *\n * ## The 5 rules it satisfies (from the wrapper-tier contract)\n *\n * 1. **Named, serializable slice.** Wrapper state lives at `model.$deadline`,\n * a plain `{ phase, seq }` — JSON-serializable, never a closure. There is\n * NO absolute timestamp in the slice: the clock is never read in `update`.\n * 2. **Retag-and-re-emit, never swallow.** The merged `update` runs the base\n * reducer, passes its Cmds through UNCHANGED, and APPENDS its own\n * `$deadline:rearm` / `$deadline:expire` decision Cmd. No base Cmd ever\n * vanishes; nothing is gated.\n * 3. **Every decision is a Msg/Cmd.** Re-arm is a `$deadline:rearm` Cmd; the\n * auto-fail expiry is the `$deadline:exceeded` Msg the Sub delivers, folded\n * into the slice and echoed as a `$deadline:expire` Cmd. \"Why did this\n * fire\" is answerable from reducer + log alone.\n * 4. **Subs merge by id.** `subscriptions = [...base, ...deadlineSubs]`; the\n * timeout id is `$deadline:timeout:{seq}`, so a progress bump (seq+1)\n * yields a NEW id — the substrate retires the old timer and arms a fresh\n * one. When `exceeded`, no deadline sub is returned.\n * 5. **Clock out of update.** The countdown is a relative-timeout Sub; the\n * clock is read at subscribe time inside the Sub (`setTimeout`), NEVER in a\n * verb. The slice carries `seq`, not a deadline timestamp.\n *\n * ## Typical wiring\n *\n * const guarded = withDeadline(baseMachine, {\n * ms: 900_000, // auto-fail after 15 minutes of inactivity\n * progress: (msg) => msg.type !== \"heartbeat\", // heartbeats don't re-arm\n * });\n * const runtime = run(guarded, { ctx: baseCtx });\n */\n\nimport {\n type Cmd,\n formOf,\n type Interpret,\n type Machine,\n type Reducer,\n type Sub,\n type Subscribe,\n subId,\n type UpdateForm,\n} from \"../index\";\nimport { fromTimeout } from \"../subs/from-timeout\";\n\n// ===========================================================================\n// The slice + the Sub + the Msg + the Cmds — the deadline vocabulary.\n// ===========================================================================\n\n/**\n * The wrapper's Model slice. `phase` is the lifecycle (`armed` while the\n * countdown runs, `exceeded` once the deadline fired); `seq` is the monotonic\n * re-arm counter that keys the timer Sub's id so each accepted progress Msg\n * retires the old timer and starts a fresh one.\n *\n * PURE and SERIALIZABLE: there is deliberately NO absolute timestamp here. A\n * deadline timestamp would force the merged `update` to read the wall clock to\n * compute it, which the conformance gate (property 2 — two replays under\n * distinct ambient clocks) is built to catch. Instead, the timer arms a fresh\n * full `ms` countdown per generation; no remaining-delay computation and no\n * clock read occur in the slice or `update` — the only clock is `setTimeout`\n * inside the Sub.\n */\nexport interface DeadlineSlice {\n /** `armed` while the countdown is live; `exceeded` once the deadline fired. */\n readonly phase: \"armed\" | \"exceeded\";\n /**\n * Monotonic re-arm counter. Starts at 0; each accepted progress Msg (while\n * armed) bumps it by one. Folds into the timer Sub's id, so a bump = a new id\n * = the substrate retires the old timer and arms a fresh `ms` countdown.\n */\n readonly seq: number;\n}\n\n/**\n * The composed Model. The base machine's state is nested under `base`; the\n * wrapper's state lives in the NAMED `$deadline` slice — never hidden in a\n * closure. Both fields are plain data, so the whole composed Model round-trips\n * through `JSON.parse(JSON.stringify(...))` iff the base state does.\n */\nexport interface DeadlineModel<S> {\n readonly base: S;\n readonly $deadline: DeadlineSlice;\n}\n\n/**\n * The relative-timeout Sub the wrapper arms while `phase === \"armed\"`. `delayMs`\n * is the window `config.ms`; the id is `$deadline:timeout:{seq}`, so each\n * progress bump produces a distinct id and the reconcile pass churns the timer.\n * Same `delayMs`-on-the-Sub shape `fromTimeout` consumes.\n */\nexport type DeadlineTimeoutSub = Sub<\"$deadline:timeout\"> & {\n readonly delayMs: number;\n};\n\n/**\n * The Msg the timeout Sub dispatches when `config.ms` elapses with no accepted\n * progress. `seq` echoes the re-arm generation the timer was armed against, so a\n * stale timer's Msg (one whose id was already retired) is identifiable; the\n * merged `update` only honors it when it matches the current slice `seq`.\n */\nexport interface DeadlineExceededMsg {\n readonly type: \"$deadline:exceeded\";\n /** The re-arm generation this timer was armed against. */\n readonly seq: number;\n}\n\n/**\n * Construct the deadline-exceeded Msg. Exported so the subscribe cell and tests\n * share one constructor rather than two literals that can drift.\n */\nexport function deadlineExceededMsg(seq: number): DeadlineExceededMsg {\n return { type: \"$deadline:exceeded\", seq };\n}\n\n/**\n * The fire-and-forget decision Cmd the merged `update` appends on every\n * transition, so the wrapper's choice is visible in the replayed Cmd log\n * (rule 3) — `rearm` when an accepted progress Msg bumped `seq`, `expire` when\n * the deadline-exceeded Msg flipped the phase, `idle` otherwise (a non-progress\n * Msg, or a Msg after the machine already auto-failed). Plain data; its\n * interpret handler is a no-op (the decision is the Cmd's presence in the log,\n * not a side effect).\n */\nexport type DeadlineDecisionCmd = Cmd<\"$deadline:decision\"> & {\n readonly decision: \"rearm\" | \"expire\" | \"idle\";\n /** The slice `seq` AFTER this transition (the re-arm generation now armed). */\n readonly seq: number;\n};\n\n/**\n * A predicate over a Msg that decides whether it re-arms the deadline.\n *\n * The argument is `Readonly<M>` and the result is `boolean`: this is the\n * STRONGEST purity TS can express here. `Readonly<M>` removes the most common\n * impurity at compile time — the predicate cannot reassign the Msg's own\n * fields — and `boolean` pins the return so a side-effecting `(msg) => { … }`\n * with an implicit `undefined`/`void` return is rejected.\n *\n * What the type system CANNOT encode (TS has no effect tracking): observational\n * purity. A body that reads `Date.now()`, calls `Math.random()`, performs IO,\n * or closes over and mutates external state still type-checks. Those remain a\n * CONVENTION enforced by review, not the compiler — the predicate runs inside\n * the pure merged `update` (invariant 2), so it must be a pure function of the\n * Msg alone: no clock, no RNG, no IO, no captured mutable state.\n */\nexport type ProgressPredicate<M extends { type: string }> = (\n msg: Readonly<M>,\n) => boolean;\n\n/**\n * The deadline knob. `ms` is the inactivity window; `progress` is an OPTIONAL\n * predicate picking which base Msgs count as activity (default: EVERY base Msg\n * re-arms). The predicate runs INSIDE the pure merged `update`, so it must be a\n * pure function of the Msg — see {@link ProgressPredicate} for what the type\n * enforces vs. what stays a convention.\n */\nexport interface DeadlineConfig<M extends { type: string }> {\n /** The inactivity window in milliseconds. Auto-fail after `ms` with no progress. */\n readonly ms: number;\n /**\n * Predicate picking which base Msgs re-arm the timer. Default: every base Msg\n * counts as progress. Pure — a function of the Msg alone (see\n * {@link ProgressPredicate}).\n */\n readonly progress?: ProgressPredicate<M>;\n}\n\n// ===========================================================================\n// update-form dispatch — run the base reducer regardless of its shape.\n// ===========================================================================\n\n// The base `update` is either a Reducer (flat record keyed by Msg.type) or a\n// Transitions table (keyed by state.type then Msg.type). The merged machine is\n// always a Reducer over the NON-discriminated `DeadlineModel<S>`, so the merged\n// reducer must invoke the base's update through whichever shape it has. Mirrors\n// `withTelemetry`'s inline form-branching (kept standalone, not pre-abstracted).\ntype BaseCellFn<S, M, C extends Cmd> = (\n state: S,\n msg: M,\n) => readonly [S, readonly C[]];\n\n/**\n * Invoke the base machine's `update` for `msg` against base `state`, returning\n * the base's `[nextBase, baseCmds]` UNCHANGED. Pure — it only routes to the\n * base cell; it never reads the clock, allocates an Error, or mutates state.\n */\nfunction runBaseUpdate<S, M extends { type: string }, C extends Cmd>(\n // Typed `object` (not `Machine[...][\"update\"]`) because the field is inspected\n // structurally and re-cast; the precise union (Reducer | Transitions)\n // collapses under the substrate's conditional `update` type.\n update: object,\n // The base's update form, read once via `formOf(base)` — no local heuristic.\n form: UpdateForm,\n state: S,\n msg: M,\n): readonly [S, readonly C[]] {\n if (form === \"reducer\") {\n // Reducer form: `update[msg.type](state, msg)`.\n const record = update as unknown as Record<string, BaseCellFn<S, M, C>>;\n // biome-ignore lint/style/noNonNullAssertion: the base machine's Reducer guarantees a cell for every dispatched Msg.type; `!` required under noUncheckedIndexedAccess and cannot miss for a Msg the base accepts\n return record[msg.type]!(state, msg);\n }\n // Transitions form: `update[state.type][msg.type](state, msg)`.\n const table = update as unknown as Record<\n string,\n Record<string, BaseCellFn<S, M, C>>\n >;\n const stateKey = (state as unknown as { type: string }).type;\n // biome-ignore lint/style/noNonNullAssertion: the base machine's Transitions table guarantees every (state.type × msg.type) cell exists; `!` required under noUncheckedIndexedAccess and cannot miss at runtime\n return table[stateKey]![msg.type]!(state, msg);\n}\n\n// Recover the base Msg.type set from either update form. A Reducer's own keys\n// ARE the Msg.type set. A Transitions table's keys are state.type; its INNER\n// keys are the Msg.type set (uniform across phases), so we read the first\n// phase's inner keys. An empty update (`M` is `never`) yields `[]`.\nfunction deadlineMsgKeys(update: object, form: UpdateForm): readonly string[] {\n const keys = Object.keys(update);\n const firstKey = keys[0];\n if (firstKey === undefined) return [];\n if (form === \"reducer\") return keys;\n const firstValue = (update as Record<string, unknown>)[firstKey];\n return Object.keys(firstValue as object);\n}\n\n// ===========================================================================\n// withDeadline — the wrapper.\n// ===========================================================================\n\n/**\n * Wrap `base` with an inactivity deadline. Returns a NEW `Machine` over the\n * composed Model `{ base, $deadline }`, with the base's Msgs/Cmds/Subs extended\n * by the wrapper's own (`$deadline:exceeded` Msg, `$deadline:decision` Cmd,\n * `$deadline:timeout` Sub).\n *\n * The composed machine:\n * - `init` rehydrates the base (honoring the `[loaded, []]` contract) and\n * seeds `$deadline: { phase: \"armed\", seq: 0 }`. Base init Cmds pass\n * through unchanged.\n * - `update` (Reducer form) runs the base reducer for base Msgs — base Cmds\n * pass through UNCHANGED — and on an accepted progress Msg bumps `seq`\n * (re-arm). The `$deadline:exceeded` Msg cell flips `phase` to `exceeded`.\n * Every transition appends a `$deadline:decision` marker Cmd.\n * - `subscriptions` is the base's, plus a `$deadline:timeout` Sub keyed on\n * `seq` while `phase === \"armed\"`.\n * - `subscribe` is the base's, plus the `$deadline:timeout` cell.\n * - `interpret` is the base's, plus a no-op `$deadline:decision` handler.\n *\n * @param base any `Machine<S, M, C, U, Ctx>`.\n * @param config the deadline knob (`ms` window + optional `progress` predicate).\n */\nexport function withDeadline<\n S,\n M extends { type: string },\n C extends Cmd,\n U extends Sub,\n Ctx,\n>(\n base: Machine<S, M, C, U, Ctx>,\n config: DeadlineConfig<M>,\n): Machine<\n DeadlineModel<S>,\n M | DeadlineExceededMsg,\n C | DeadlineDecisionCmd,\n U | DeadlineTimeoutSub,\n Ctx\n> {\n const windowMs = config.ms;\n const isProgress = config.progress;\n\n // The merged update is a flat Reducer over the composed Model. The composed\n // Model is NOT discriminated on `.type`, so every (base Msg variant + the\n // wrapper's own `$deadline:exceeded`) gets exactly one cell.\n type Next = readonly [DeadlineModel<S>, readonly (C | DeadlineDecisionCmd)[]];\n const update = {} as Record<\n string,\n (state: DeadlineModel<S>, msg: M | DeadlineExceededMsg) => Next\n >;\n\n // Namespace guard for the Msg/update surface (mirrors the interpret +\n // subscribe guards below). The `$deadline:exceeded` cell is assigned into\n // `update` after this loop; if a base Msg.type already lives in the\n // `$deadline:` namespace, that assignment — or this loop — would SILENTLY\n // clobber / be clobbered by a base cell. The `$deadline:` Msg namespace is\n // the wrapper's: refuse to wrap a base that squats on it.\n // The base's update form, read ONCE from the `__form` tag (see `formOf`) and\n // threaded into the per-form helpers — no structural re-derivation here.\n const baseForm = formOf(base);\n const baseMsgKeys = deadlineMsgKeys(base.update, baseForm);\n for (const key of baseMsgKeys) {\n if (key.startsWith(\"$deadline:\")) {\n throw new Error(\n `withDeadline: the base machine declares a reserved \"${key}\" update ` +\n 'cell — the wrapper owns the \"$deadline:\" Msg namespace. ' +\n \"Rename the base Msg.\",\n );\n }\n }\n\n for (const key of baseMsgKeys) {\n update[key] = (state, msg) => {\n // 1) Run the base reducer — its result passes through UNCHANGED.\n const [nextBase, baseCmds] = runBaseUpdate<S, M, C>(\n base.update,\n baseForm,\n state.base,\n msg as M,\n );\n // 2) Re-arm decision: a progress Msg WHILE armed bumps `seq` (new timer\n // id → fresh countdown). After auto-fail, or for a non-progress Msg,\n // the slice is unchanged and the decision is `idle`.\n const armed = state.$deadline.phase === \"armed\";\n const counts =\n armed && (isProgress === undefined || isProgress(msg as M));\n const $deadline: DeadlineSlice = counts\n ? { phase: \"armed\", seq: state.$deadline.seq + 1 }\n : state.$deadline;\n const next: DeadlineModel<S> = { base: nextBase, $deadline };\n // 3) Append the visible decision marker. Base Cmds come FIRST, unchanged.\n const decision: DeadlineDecisionCmd = {\n type: \"$deadline:decision\",\n decision: counts ? \"rearm\" : \"idle\",\n seq: $deadline.seq,\n };\n return [next, [...baseCmds, decision]];\n };\n }\n\n // The wrapper's own Msg cell. The timeout Sub delivers `$deadline:exceeded`\n // carrying the `seq` it was armed against. Honor it ONLY while armed and ONLY\n // when the `seq` matches the current generation — a stale timer's Msg (from a\n // generation already retired by a re-arm, or arriving after auto-fail) is a\n // no-op that still records a visible `idle` decision. The expiry flips `phase`\n // to `exceeded`; the slice transition IS the auto-fail, visible in the log.\n update[\"$deadline:exceeded\"] = (state, msg) => {\n const m = msg as DeadlineExceededMsg;\n const fires =\n state.$deadline.phase === \"armed\" && m.seq === state.$deadline.seq;\n const $deadline: DeadlineSlice = fires\n ? { phase: \"exceeded\", seq: state.$deadline.seq }\n : state.$deadline;\n const next: DeadlineModel<S> = { base: state.base, $deadline };\n const decision: DeadlineDecisionCmd = {\n type: \"$deadline:decision\",\n decision: fires ? \"expire\" : \"idle\",\n seq: $deadline.seq,\n };\n return [next, [decision]];\n };\n\n // The base's interpret, extended with the one no-op decision handler. The\n // `$deadline:decision` Cmd has no I/O — its purpose is log visibility (rule 3),\n // so the handler returns void and dispatches nothing. Namespace guard mirrors\n // withTelemetry: refuse to wrap a base that squats on the reserved Cmd key.\n const baseInterpret =\n (base as { interpret?: Interpret<M, C, Ctx> }).interpret ??\n ({} as Interpret<M, C, Ctx>);\n if (Object.hasOwn(baseInterpret as object, \"$deadline:decision\")) {\n throw new Error(\n 'withDeadline: the base machine declares a reserved \"$deadline:decision\" ' +\n 'interpret handler — the wrapper owns the \"$deadline:\" Cmd namespace. ' +\n \"Rename the base handler.\",\n );\n }\n const interpret = {\n ...(baseInterpret as Record<string, unknown>),\n \"$deadline:decision\": async (): Promise<void> => {},\n } as Interpret<M | DeadlineExceededMsg, C | DeadlineDecisionCmd, Ctx>;\n\n // Subs merge by id: the base's, plus the deadline countdown while armed. The\n // timeout id folds in `seq`, so each progress bump yields a NEW id and the\n // reconcile pass retires the old timer + arms a fresh `ms` countdown. When\n // exceeded, no deadline sub is returned (the machine has auto-failed).\n const baseSubscriptions = base.subscriptions;\n const subscriptions = (\n state: DeadlineModel<S>,\n ): readonly (U | DeadlineTimeoutSub)[] => {\n const baseSubs = baseSubscriptions ? baseSubscriptions(state.base) : [];\n if (state.$deadline.phase !== \"armed\") return baseSubs;\n const timeout: DeadlineTimeoutSub = {\n id: subId(`$deadline:timeout:${state.$deadline.seq}`),\n type: \"$deadline:timeout\",\n delayMs: windowMs,\n };\n return [...baseSubs, timeout];\n };\n\n // The base's subscribe cells, plus the timeout cell. The clock is read here —\n // at subscribe time, inside the Sub's `setTimeout` — NEVER in a verb. The\n // dispatched Msg carries the `seq` the timer was armed against so the merged\n // update can reject a stale generation.\n const baseSubscribe =\n (base as { subscribe?: Subscribe<M, U, Ctx> }).subscribe ??\n ({} as Subscribe<M, U, Ctx>);\n if (Object.hasOwn(baseSubscribe as object, \"$deadline:timeout\")) {\n throw new Error(\n 'withDeadline: the base machine declares a reserved \"$deadline:timeout\" ' +\n 'subscribe handler — the wrapper owns the \"$deadline:\" Sub namespace. ' +\n \"Rename the base handler.\",\n );\n }\n const timeoutCell = fromTimeout<DeadlineTimeoutSub, DeadlineExceededMsg>(\n (sub) => {\n // The sub id is `$deadline:timeout:{seq}`; recover the generation it was\n // armed against so a stale timer's Msg is identifiable in the reducer.\n const seq = Number(sub.id.slice(sub.id.lastIndexOf(\":\") + 1));\n return deadlineExceededMsg(seq);\n },\n );\n const subscribe = {\n ...(baseSubscribe as Record<string, unknown>),\n \"$deadline:timeout\": timeoutCell,\n } as Subscribe<M | DeadlineExceededMsg, U | DeadlineTimeoutSub, Ctx>;\n\n return {\n init: (loaded, ctx) => {\n // Rehydrate path: `loaded !== null` MUST return `[loaded, []]` (no Cmds) —\n // the substrate's replay enforces this. We split the composed loaded Model\n // into its base slice and feed the base its own loaded snapshot.\n if (loaded !== null) {\n return [loaded, []];\n }\n const [base0, cmds] = base.init(null, ctx);\n const model: DeadlineModel<S> = {\n base: base0,\n $deadline: { phase: \"armed\", seq: 0 },\n };\n // Base init Cmds pass through unchanged; no deadline Cmd on boot (boot is\n // not a base Msg transition, so it does not re-arm).\n return [model, cmds];\n },\n update: update as unknown as Reducer<\n DeadlineModel<S>,\n M | DeadlineExceededMsg,\n C | DeadlineDecisionCmd\n >,\n subscriptions,\n subscribe,\n interpret,\n } as Machine<\n DeadlineModel<S>,\n M | DeadlineExceededMsg,\n C | DeadlineDecisionCmd,\n U | DeadlineTimeoutSub,\n Ctx\n >;\n}\n"]}
1
+ {"version":3,"sources":["../../src/with-deadline/index.ts"],"names":[],"mappings":";;;;;AAuIO,SAAS,oBAAoB,GAAA,EAAkC;AACpE,EAAA,OAAO,EAAE,IAAA,EAAM,oBAAA,EAAsB,GAAA,EAAI;AAC3C;AAiFO,SAAS,YAAA,CAOd,MACA,MAAA,EAOA;AACA,EAAA,MAAM,WAAW,MAAA,CAAO,EAAA;AACxB,EAAA,MAAM,aAAa,MAAA,CAAO,QAAA;AAM1B,EAAA,MAAM,SAAS,EAAC;AAahB,EAAA,MAAM,WAAA,GAAc,UAAU,IAAI,CAAA;AAClC,EAAA,KAAA,MAAW,OAAO,WAAA,EAAa;AAC7B,IAAA,IAAI,GAAA,CAAI,UAAA,CAAW,YAAY,CAAA,EAAG;AAChC,MAAA,MAAM,IAAI,KAAA;AAAA,QACR,uDAAuD,GAAG,CAAA,0FAAA;AAAA,OAG5D;AAAA,IACF;AAAA,EACF;AAEA,EAAA,KAAA,MAAW,OAAO,WAAA,EAAa;AAC7B,IAAA,MAAA,CAAO,GAAG,CAAA,GAAI,CAAC,KAAA,EAAO,GAAA,KAAQ;AAE5B,MAAA,MAAM,CAAC,QAAA,EAAU,QAAQ,CAAA,GAAI,SAAA;AAAA,QAC3B,IAAA;AAAA,QACA,KAAA,CAAM,IAAA;AAAA,QACN;AAAA,OACF;AAIA,MAAA,MAAM,KAAA,GAAQ,KAAA,CAAM,SAAA,CAAU,KAAA,KAAU,OAAA;AACxC,MAAA,MAAM,MAAA,GACJ,KAAA,KAAU,UAAA,KAAe,MAAA,IAAa,WAAW,GAAQ,CAAA,CAAA;AAC3D,MAAA,MAAM,SAAA,GAA2B,MAAA,GAC7B,EAAE,KAAA,EAAO,OAAA,EA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AAA;AAAA,IACJ,mBAAA,EAAqB;AAAA,GACvB;AAEA,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,CAAC,MAAA,EAAQ,GAAA,KAAQ;AAIrB,MAAA,IAAI,WAAW,IAAA,EAAM;AACnB,QAAA,OAAO,CAAC,MAAA,EAAQ,EAAE,CAAA;AAAA,MACpB;AACA,MAAA,MAAM,CAAC,KAAA,EAAO,IAAI,IAAI,IAAA,CAAK,IAAA,CAAK,MAAM,GAAG,CAAA;AACzC,MAAA,MAAM,KAAA,GAA0B;AAAA,QAC9B,IAAA,EAAM,KAAA;AAAA,QACN,SAAA,EAAW,EAAE,KAAA,EAAO,OAAA,EAAS,KAAK,CAAA;AAAE,OACtC;AAGA,MAAA,OAAO,CAAC,OAAO,IAAI,CAAA;AAAA,IACrB,CAAA;AAAA,IACA,MAAA;AAAA,IAKA,aAAA;AAAA,IACA,SAAA;AAAA,IACA;AAAA,GACF;AAOF","file":"index.js","sourcesContent":["/**\n * @demlik/tea/with-deadline — auto-fail a wrapped machine at T+N, re-arm on\n * progress. A **pure function over machine data**: `withDeadline(base, config)`\n * takes any `Machine<S, M, C, U, Ctx>` and returns a NEW `Machine` over the\n * composed Model `{ base, $deadline }`. You `run()` / `replay()` the result\n * exactly like any other machine — there is no new runtime, no privileged\n * interception path.\n *\n * ## What it does\n *\n * The wrapper watches the base Msg stream. While the deadline is `armed`, a\n * RELATIVE timeout Sub counts down `config.ms`. Every base Msg the\n * `config.progress` predicate accepts (default: every base Msg) is treated as\n * activity: the wrapper bumps a numeric `seq`, which CHANGES the timer Sub's id,\n * so the substrate's reconcile pass retires the old countdown and starts a fresh\n * one — \"re-arm on progress\". If `config.ms` elapses with NO accepted progress,\n * the timeout Sub dispatches `$deadline:exceeded`; the merged `update` folds it\n * by flipping `phase` to `exceeded`, and from then on `subscriptions` returns no\n * timer (the machine has auto-failed). The expiry is a slice transition visible\n * in the Msg log — the auto-fail is never an off-ledger side effect.\n *\n * This is an OBSERVE-ONLY wrapper in the same sense as `withTelemetry`: it never\n * intercepts a base Cmd and never gates a base Msg. `state.base` after wrapping\n * is BYTE-IDENTICAL to running the base alone, so the shared\n * `assertWrapperFaithful` gate passes with the deadline bolted on.\n *\n * ## The 5 rules it satisfies (from the wrapper-tier contract)\n *\n * 1. **Named, serializable slice.** Wrapper state lives at `model.$deadline`,\n * a plain `{ phase, seq }` — JSON-serializable, never a closure. There is\n * NO absolute timestamp in the slice: the clock is never read in `update`.\n * 2. **Retag-and-re-emit, never swallow.** The merged `update` runs the base\n * reducer, passes its Cmds through UNCHANGED, and APPENDS its own\n * `$deadline:rearm` / `$deadline:expire` decision Cmd. No base Cmd ever\n * vanishes; nothing is gated.\n * 3. **Every decision is a Msg/Cmd.** Re-arm is a `$deadline:rearm` Cmd; the\n * auto-fail expiry is the `$deadline:exceeded` Msg the Sub delivers, folded\n * into the slice and echoed as a `$deadline:expire` Cmd. \"Why did this\n * fire\" is answerable from reducer + log alone.\n * 4. **Subs merge by id.** `subscriptions = [...base, ...deadlineSubs]`; the\n * timeout id is `$deadline:timeout:{seq}`, so a progress bump (seq+1)\n * yields a NEW id — the substrate retires the old timer and arms a fresh\n * one. When `exceeded`, no deadline sub is returned.\n * 5. **Clock out of update.** The countdown is a relative-timeout Sub; the\n * clock is read at subscribe time inside the Sub (`setTimeout`), NEVER in a\n * verb. The slice carries `seq`, not a deadline timestamp.\n *\n * ## Typical wiring\n *\n * const guarded = withDeadline(baseMachine, {\n * ms: 900_000, // auto-fail after 15 minutes of inactivity\n * progress: (msg) => msg.type !== \"heartbeat\", // heartbeats don't re-arm\n * });\n * const runtime = run(guarded, { ctx: baseCtx });\n */\n\nimport {\n applyCell,\n type Cmd,\n type Interpret,\n type Machine,\n msgKeysOf,\n type Reducer,\n type Sub,\n type Subscribe,\n subId,\n} from \"../index\";\nimport { fromTimeout } from \"../subs/from-timeout\";\n\n// ===========================================================================\n// The slice + the Sub + the Msg + the Cmds — the deadline vocabulary.\n// ===========================================================================\n\n/**\n * The wrapper's Model slice. `phase` is the lifecycle (`armed` while the\n * countdown runs, `exceeded` once the deadline fired); `seq` is the monotonic\n * re-arm counter that keys the timer Sub's id so each accepted progress Msg\n * retires the old timer and starts a fresh one.\n *\n * PURE and SERIALIZABLE: there is deliberately NO absolute timestamp here. A\n * deadline timestamp would force the merged `update` to read the wall clock to\n * compute it, which the conformance gate (property 2 — two replays under\n * distinct ambient clocks) is built to catch. Instead, the timer arms a fresh\n * full `ms` countdown per generation; no remaining-delay computation and no\n * clock read occur in the slice or `update` — the only clock is `setTimeout`\n * inside the Sub.\n */\nexport interface DeadlineSlice {\n /** `armed` while the countdown is live; `exceeded` once the deadline fired. */\n readonly phase: \"armed\" | \"exceeded\";\n /**\n * Monotonic re-arm counter. Starts at 0; each accepted progress Msg (while\n * armed) bumps it by one. Folds into the timer Sub's id, so a bump = a new id\n * = the substrate retires the old timer and arms a fresh `ms` countdown.\n */\n readonly seq: number;\n}\n\n/**\n * The composed Model. The base machine's state is nested under `base`; the\n * wrapper's state lives in the NAMED `$deadline` slice — never hidden in a\n * closure. Both fields are plain data, so the whole composed Model round-trips\n * through `JSON.parse(JSON.stringify(...))` iff the base state does.\n */\nexport interface DeadlineModel<S> {\n readonly base: S;\n readonly $deadline: DeadlineSlice;\n}\n\n/**\n * The relative-timeout Sub the wrapper arms while `phase === \"armed\"`. `delayMs`\n * is the window `config.ms`; the id is `$deadline:timeout:{seq}`, so each\n * progress bump produces a distinct id and the reconcile pass churns the timer.\n * Same `delayMs`-on-the-Sub shape `fromTimeout` consumes.\n */\nexport type DeadlineTimeoutSub = Sub<\"$deadline:timeout\"> & {\n readonly delayMs: number;\n};\n\n/**\n * The Msg the timeout Sub dispatches when `config.ms` elapses with no accepted\n * progress. `seq` echoes the re-arm generation the timer was armed against, so a\n * stale timer's Msg (one whose id was already retired) is identifiable; the\n * merged `update` only honors it when it matches the current slice `seq`.\n */\nexport interface DeadlineExceededMsg {\n readonly type: \"$deadline:exceeded\";\n /** The re-arm generation this timer was armed against. */\n readonly seq: number;\n}\n\n/**\n * Construct the deadline-exceeded Msg. Exported so the subscribe cell and tests\n * share one constructor rather than two literals that can drift.\n */\nexport function deadlineExceededMsg(seq: number): DeadlineExceededMsg {\n return { type: \"$deadline:exceeded\", seq };\n}\n\n/**\n * The fire-and-forget decision Cmd the merged `update` appends on every\n * transition, so the wrapper's choice is visible in the replayed Cmd log\n * (rule 3) — `rearm` when an accepted progress Msg bumped `seq`, `expire` when\n * the deadline-exceeded Msg flipped the phase, `idle` otherwise (a non-progress\n * Msg, or a Msg after the machine already auto-failed). Plain data; its\n * interpret handler is a no-op (the decision is the Cmd's presence in the log,\n * not a side effect).\n */\nexport type DeadlineDecisionCmd = Cmd<\"$deadline:decision\"> & {\n readonly decision: \"rearm\" | \"expire\" | \"idle\";\n /** The slice `seq` AFTER this transition (the re-arm generation now armed). */\n readonly seq: number;\n};\n\n/**\n * A predicate over a Msg that decides whether it re-arms the deadline.\n *\n * The argument is `Readonly<M>` and the result is `boolean`: this is the\n * STRONGEST purity TS can express here. `Readonly<M>` removes the most common\n * impurity at compile time — the predicate cannot reassign the Msg's own\n * fields — and `boolean` pins the return so a side-effecting `(msg) => { … }`\n * with an implicit `undefined`/`void` return is rejected.\n *\n * What the type system CANNOT encode (TS has no effect tracking): observational\n * purity. A body that reads `Date.now()`, calls `Math.random()`, performs IO,\n * or closes over and mutates external state still type-checks. Those remain a\n * CONVENTION enforced by review, not the compiler — the predicate runs inside\n * the pure merged `update` (invariant 2), so it must be a pure function of the\n * Msg alone: no clock, no RNG, no IO, no captured mutable state.\n */\nexport type ProgressPredicate<M extends { type: string }> = (\n msg: Readonly<M>,\n) => boolean;\n\n/**\n * The deadline knob. `ms` is the inactivity window; `progress` is an OPTIONAL\n * predicate picking which base Msgs count as activity (default: EVERY base Msg\n * re-arms). The predicate runs INSIDE the pure merged `update`, so it must be a\n * pure function of the Msg — see {@link ProgressPredicate} for what the type\n * enforces vs. what stays a convention.\n */\nexport interface DeadlineConfig<M extends { type: string }> {\n /** The inactivity window in milliseconds. Auto-fail after `ms` with no progress. */\n readonly ms: number;\n /**\n * Predicate picking which base Msgs re-arm the timer. Default: every base Msg\n * counts as progress. Pure — a function of the Msg alone (see\n * {@link ProgressPredicate}).\n */\n readonly progress?: ProgressPredicate<M>;\n}\n\n// ===========================================================================\n// withDeadline — the wrapper.\n// ===========================================================================\n\n/**\n * Wrap `base` with an inactivity deadline. Returns a NEW `Machine` over the\n * composed Model `{ base, $deadline }`, with the base's Msgs/Cmds/Subs extended\n * by the wrapper's own (`$deadline:exceeded` Msg, `$deadline:decision` Cmd,\n * `$deadline:timeout` Sub).\n *\n * The composed machine:\n * - `init` rehydrates the base (honoring the `[loaded, []]` contract) and\n * seeds `$deadline: { phase: \"armed\", seq: 0 }`. Base init Cmds pass\n * through unchanged.\n * - `update` (Reducer form) runs the base reducer for base Msgs — base Cmds\n * pass through UNCHANGED — and on an accepted progress Msg bumps `seq`\n * (re-arm). The `$deadline:exceeded` Msg cell flips `phase` to `exceeded`.\n * Every transition appends a `$deadline:decision` marker Cmd.\n * - `subscriptions` is the base's, plus a `$deadline:timeout` Sub keyed on\n * `seq` while `phase === \"armed\"`.\n * - `subscribe` is the base's, plus the `$deadline:timeout` cell.\n * - `interpret` is the base's, plus a no-op `$deadline:decision` handler.\n *\n * @param base any `Machine<S, M, C, U, Ctx>`.\n * @param config the deadline knob (`ms` window + optional `progress` predicate).\n */\nexport function withDeadline<\n S,\n M extends { type: string },\n C extends Cmd,\n U extends Sub,\n Ctx,\n>(\n base: Machine<S, M, C, U, Ctx>,\n config: DeadlineConfig<M>,\n): Machine<\n DeadlineModel<S>,\n M | DeadlineExceededMsg,\n C | DeadlineDecisionCmd,\n U | DeadlineTimeoutSub,\n Ctx\n> {\n const windowMs = config.ms;\n const isProgress = config.progress;\n\n // The merged update is a flat Reducer over the composed Model. The composed\n // Model is NOT discriminated on `.type`, so every (base Msg variant + the\n // wrapper's own `$deadline:exceeded`) gets exactly one cell.\n type Next = readonly [DeadlineModel<S>, readonly (C | DeadlineDecisionCmd)[]];\n const update = {} as Record<\n string,\n (state: DeadlineModel<S>, msg: M | DeadlineExceededMsg) => Next\n >;\n\n // Namespace guard for the Msg/update surface (mirrors the interpret +\n // subscribe guards below). The `$deadline:exceeded` cell is assigned into\n // `update` after this loop; if a base Msg.type already lives in the\n // `$deadline:` namespace, that assignment — or this loop — would SILENTLY\n // clobber / be clobbered by a base cell. The `$deadline:` Msg namespace is\n // the wrapper's: refuse to wrap a base that squats on it.\n // Base Msg keys enumerated via `msgKeysOf(base)` — keyed on the\n // authoritative `__form` tag, no structural re-derivation here (#275).\n const baseMsgKeys = msgKeysOf(base);\n for (const key of baseMsgKeys) {\n if (key.startsWith(\"$deadline:\")) {\n throw new Error(\n `withDeadline: the base machine declares a reserved \"${key}\" update ` +\n 'cell — the wrapper owns the \"$deadline:\" Msg namespace. ' +\n \"Rename the base Msg.\",\n );\n }\n }\n\n for (const key of baseMsgKeys) {\n update[key] = (state, msg) => {\n // 1) Run the base reducer — its result passes through UNCHANGED.\n const [nextBase, baseCmds] = applyCell<S, M, C>(\n base,\n state.base,\n msg as M,\n );\n // 2) Re-arm decision: a progress Msg WHILE armed bumps `seq` (new timer\n // id → fresh countdown). After auto-fail, or for a non-progress Msg,\n // the slice is unchanged and the decision is `idle`.\n const armed = state.$deadline.phase === \"armed\";\n const counts =\n armed && (isProgress === undefined || isProgress(msg as M));\n const $deadline: DeadlineSlice = counts\n ? { phase: \"armed\", seq: state.$deadline.seq + 1 }\n : state.$deadline;\n const next: DeadlineModel<S> = { base: nextBase, $deadline };\n // 3) Append the visible decision marker. Base Cmds come FIRST, unchanged.\n const decision: DeadlineDecisionCmd = {\n type: \"$deadline:decision\",\n decision: counts ? \"rearm\" : \"idle\",\n seq: $deadline.seq,\n };\n return [next, [...baseCmds, decision]];\n };\n }\n\n // The wrapper's own Msg cell. The timeout Sub delivers `$deadline:exceeded`\n // carrying the `seq` it was armed against. Honor it ONLY while armed and ONLY\n // when the `seq` matches the current generation — a stale timer's Msg (from a\n // generation already retired by a re-arm, or arriving after auto-fail) is a\n // no-op that still records a visible `idle` decision. The expiry flips `phase`\n // to `exceeded`; the slice transition IS the auto-fail, visible in the log.\n update[\"$deadline:exceeded\"] = (state, msg) => {\n const m = msg as DeadlineExceededMsg;\n const fires =\n state.$deadline.phase === \"armed\" && m.seq === state.$deadline.seq;\n const $deadline: DeadlineSlice = fires\n ? { phase: \"exceeded\", seq: state.$deadline.seq }\n : state.$deadline;\n const next: DeadlineModel<S> = { base: state.base, $deadline };\n const decision: DeadlineDecisionCmd = {\n type: \"$deadline:decision\",\n decision: fires ? \"expire\" : \"idle\",\n seq: $deadline.seq,\n };\n return [next, [decision]];\n };\n\n // The base's interpret, extended with the one no-op decision handler. The\n // `$deadline:decision` Cmd has no I/O — its purpose is log visibility (rule 3),\n // so the handler returns void and dispatches nothing. Namespace guard mirrors\n // withTelemetry: refuse to wrap a base that squats on the reserved Cmd key.\n const baseInterpret =\n (base as { interpret?: Interpret<M, C, Ctx> }).interpret ??\n ({} as Interpret<M, C, Ctx>);\n if (Object.hasOwn(baseInterpret as object, \"$deadline:decision\")) {\n throw new Error(\n 'withDeadline: the base machine declares a reserved \"$deadline:decision\" ' +\n 'interpret handler — the wrapper owns the \"$deadline:\" Cmd namespace. ' +\n \"Rename the base handler.\",\n );\n }\n const interpret = {\n ...(baseInterpret as Record<string, unknown>),\n \"$deadline:decision\": async (): Promise<void> => {},\n } as Interpret<M | DeadlineExceededMsg, C | DeadlineDecisionCmd, Ctx>;\n\n // Subs merge by id: the base's, plus the deadline countdown while armed. The\n // timeout id folds in `seq`, so each progress bump yields a NEW id and the\n // reconcile pass retires the old timer + arms a fresh `ms` countdown. When\n // exceeded, no deadline sub is returned (the machine has auto-failed).\n const baseSubscriptions = base.subscriptions;\n const subscriptions = (\n state: DeadlineModel<S>,\n ): readonly (U | DeadlineTimeoutSub)[] => {\n const baseSubs = baseSubscriptions ? baseSubscriptions(state.base) : [];\n if (state.$deadline.phase !== \"armed\") return baseSubs;\n const timeout: DeadlineTimeoutSub = {\n id: subId(`$deadline:timeout:${state.$deadline.seq}`),\n type: \"$deadline:timeout\",\n delayMs: windowMs,\n };\n return [...baseSubs, timeout];\n };\n\n // The base's subscribe cells, plus the timeout cell. The clock is read here —\n // at subscribe time, inside the Sub's `setTimeout` — NEVER in a verb. The\n // dispatched Msg carries the `seq` the timer was armed against so the merged\n // update can reject a stale generation.\n const baseSubscribe =\n (base as { subscribe?: Subscribe<M, U, Ctx> }).subscribe ??\n ({} as Subscribe<M, U, Ctx>);\n if (Object.hasOwn(baseSubscribe as object, \"$deadline:timeout\")) {\n throw new Error(\n 'withDeadline: the base machine declares a reserved \"$deadline:timeout\" ' +\n 'subscribe handler — the wrapper owns the \"$deadline:\" Sub namespace. ' +\n \"Rename the base handler.\",\n );\n }\n const timeoutCell = fromTimeout<DeadlineTimeoutSub, DeadlineExceededMsg>(\n (sub) => {\n // The sub id is `$deadline:timeout:{seq}`; recover the generation it was\n // armed against so a stale timer's Msg is identifiable in the reducer.\n const seq = Number(sub.id.slice(sub.id.lastIndexOf(\":\") + 1));\n return deadlineExceededMsg(seq);\n },\n );\n const subscribe = {\n ...(baseSubscribe as Record<string, unknown>),\n \"$deadline:timeout\": timeoutCell,\n } as Subscribe<M | DeadlineExceededMsg, U | DeadlineTimeoutSub, Ctx>;\n\n return {\n init: (loaded, ctx) => {\n // Rehydrate path: `loaded !== null` MUST return `[loaded, []]` (no Cmds) —\n // the substrate's replay enforces this. We split the composed loaded Model\n // into its base slice and feed the base its own loaded snapshot.\n if (loaded !== null) {\n return [loaded, []];\n }\n const [base0, cmds] = base.init(null, ctx);\n const model: DeadlineModel<S> = {\n base: base0,\n $deadline: { phase: \"armed\", seq: 0 },\n };\n // Base init Cmds pass through unchanged; no deadline Cmd on boot (boot is\n // not a base Msg transition, so it does not re-arm).\n return [model, cmds];\n },\n update: update as unknown as Reducer<\n DeadlineModel<S>,\n M | DeadlineExceededMsg,\n C | DeadlineDecisionCmd\n >,\n subscriptions,\n subscribe,\n interpret,\n } as Machine<\n DeadlineModel<S>,\n M | DeadlineExceededMsg,\n C | DeadlineDecisionCmd,\n U | DeadlineTimeoutSub,\n Ctx\n >;\n}\n"]}
@@ -1,7 +1,7 @@
1
- import { C as Cmd, S as Sub, M as Machine } from '../core-CymXZCeY.js';
1
+ import { C as Cmd, S as Sub, M as Machine } from '../core-BoB6t7dB.js';
2
2
  import { ResilientConfig, ResilientState } from '../resilient-call/index.js';
3
3
  import '../cache/index.js';
4
- import '../types-N9LZbdnr.js';
4
+ import '../types-B-8bcAp8.js';
5
5
  import '../circuit-breaker/index.js';
6
6
  import '../deadline/index.js';
7
7
  import '../protocol-B5YmJr0d.js';
@@ -1,14 +1,14 @@
1
- import { createResilientCall } from '../chunk-RVJFGRGK.js';
1
+ import { createResilientCall } from '../chunk-27N2SPTN.js';
2
2
  import { MsgType } from '../chunk-JELSZN25.js';
3
- import { subscribeDeadline } from '../chunk-QGZW4W3E.js';
3
+ import { subscribeDeadline } from '../chunk-K7Q23EQ4.js';
4
4
  import '../chunk-5VNWZADP.js';
5
5
  import '../chunk-2YOE5PIS.js';
6
6
  import '../chunk-SC3FAFZN.js';
7
7
  import '../chunk-IN33Q4VJ.js';
8
8
  import '../chunk-NSDFA6M6.js';
9
9
  import '../chunk-2YFLOCWX.js';
10
- import { tryInterpret } from '../chunk-2WZHS4P2.js';
11
- import { formOf, subId } from '../chunk-BNJYE4AU.js';
10
+ import { tryInterpret } from '../chunk-MMH7CW5K.js';
11
+ import { msgKeysOf, applyCell, subId, formOf } from '../chunk-QLA76GIT.js';
12
12
 
13
13
  // src/with-resilience/index.ts
14
14
  var RC_RETRY_PREFIX = "resilient:retry:";
@@ -29,33 +29,12 @@ function toRcTimerId(wxId) {
29
29
  return RC_DEADLINE_PREFIX + wxId.slice(WX_DEADLINE_PREFIX.length);
30
30
  return wxId;
31
31
  }
32
- function runBaseUpdate(update, form, state, msg) {
33
- if (form === "reducer") {
34
- const record = update;
35
- return record[msg.type](state, msg);
32
+ function updateDeclaresMsgKey(machine, key) {
33
+ if (formOf(machine) === "reducer") {
34
+ return Object.hasOwn(machine.update, key);
36
35
  }
37
- const table = update;
38
- const stateKey = state.type;
39
- return table[stateKey][msg.type](state, msg);
40
- }
41
- function baseMsgKeys(update, form) {
42
- const keys = Object.keys(update);
43
- const firstKey = keys[0];
44
- if (firstKey === void 0) return [];
45
- if (form === "reducer") return keys;
46
- const firstValue = update[firstKey];
47
- return Object.keys(firstValue);
48
- }
49
- function updateDeclaresMsgKey(update, form, key) {
50
- const keys = Object.keys(update);
51
- const firstKey = keys[0];
52
- if (firstKey === void 0) return false;
53
- if (form === "reducer") {
54
- return Object.hasOwn(update, key);
55
- }
56
- for (const stateKey of keys) {
57
- const innerTable = update[stateKey];
58
- if (innerTable !== null && typeof innerTable === "object" && Object.hasOwn(innerTable, key)) {
36
+ for (const innerTable of Object.values(machine.update)) {
37
+ if (innerTable !== null && (typeof innerTable === "object" || typeof innerTable === "function") && Object.hasOwn(innerTable, key)) {
59
38
  return true;
60
39
  }
61
40
  }
@@ -73,12 +52,10 @@ function withResilience(base, config, rng = Math.random) {
73
52
  const atOf = config.at ?? (() => 0);
74
53
  const rc = createResilientCall(config, rng);
75
54
  const update = {};
76
- const baseForm = formOf(base);
77
- for (const key of baseMsgKeys(base.update, baseForm)) {
55
+ for (const key of msgKeysOf(base)) {
78
56
  update[key] = (state, msg) => {
79
- const [nextBase, baseCmds] = runBaseUpdate(
80
- base.update,
81
- baseForm,
57
+ const [nextBase, baseCmds] = applyCell(
58
+ base,
82
59
  state.base,
83
60
  msg
84
61
  );
@@ -163,7 +140,7 @@ function withResilience(base, config, rng = Math.random) {
163
140
  const surfaces = [
164
141
  {
165
142
  name: "update",
166
- declares: (reserved) => updateDeclaresMsgKey(base.update, baseForm, reserved)
143
+ declares: (reserved) => updateDeclaresMsgKey(base, reserved)
167
144
  },
168
145
  {
169
146
  name: "interpret",
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AA,YACX,OAAO,KAAA,CAAM;AAAA,WACd,CAAA;AAAA,QACH;AAAA,MACF;AACA,MAAA,MAAM,KAAA,GAAY,EAAE,IAAA,EAAM,KAAA,EAAO,aAAa,UAAA,EAAW;AACzD,MAAA,OAAO,CAAC,OAAO,QAAQ,CAAA;AAAA,IACzB,CAAA;AAAA,IACA,MAAA;AAAA,IACA,aAAA;AAAA,IACA,SAAA,EAAW,YAAA;AAAA,IAOX;AAAA,GACF;AACF","file":"index.js","sourcesContent":["/**\n * @demlik/tea/with-resilience — the INTERCEPTING wrapper of the wrapper tier.\n *\n * `withResilience(base, config)` is a **pure function over machine data**: it\n * takes any `Machine<S, M, C, U, Ctx>`, a chosen TARGET base Cmd type, and a\n * resilience knob, and returns a NEW `Machine` over the composed Model\n * `{ base, $resilience }`. You `run()` / `replay()` the result exactly like any\n * other machine — there is no new runtime, no privileged interception path.\n *\n * This is the HARDEST wrapper. `withTelemetry` only OBSERVES; this one\n * INTERCEPTS. It bolts the resilient-call concern (cache → circuit-breaker →\n * rate-limit → exponential-backoff retry, with a deadline cap) onto a chosen\n * base Cmd WITHOUT the base authoring any of it. The base keeps emitting its\n * plain effect Cmd; the wrapper diverts each one through the resilience gate.\n *\n * ## Retag, never swallow (rule 2 — the whole danger)\n *\n * The merged `update` delegates to `base.update`, then PARTITIONS the base Cmds\n * by type:\n *\n * - A NON-target base Cmd passes through UNCHANGED — byte-identical, in the\n * same slot. The wrapper does not touch effects it was not asked to harden.\n * - A TARGET base Cmd is RETAGGED: it becomes the `input` payload of a\n * `$resilience:run` carrier Cmd (when the gate admits it), OR its gating is\n * RECORDED as a `$resilience:*` decision in the SAME transition (cache hit,\n * circuit-open fast-fail, rate-limited backoff). It is NEVER emitted raw,\n * and it NEVER vanishes without a `$resilience:*` Cmd recording where it\n * went. That recorded divergence is exactly what the conformance gate's\n * `intercepting` option verifies.\n *\n * The resilient-call result Msgs route back through the merged `update`:\n * `$resilience:ok` → `succeed` (close the breaker, fill the cache, reset the\n * retry run), `$resilience:err` → `fail` (trip the breaker, then back off or\n * settle), `$resilience:timer` → `onTimer` (a retry timer re-runs the gate; a\n * deadline timer settles the call failed). Every decision is a Msg/Cmd through\n * the reducer + log — \"why did this fire\" is answerable from the log alone.\n *\n * ## The slice + verbs are REUSED, not reinvented\n *\n * The `$resilience` slice IS resilient-call's `ResilientState<I, R>` (per-key\n * call / retry / circuit / bucket / cache), and the gate / backoff / breaker\n * logic IS its `attempt` / `succeed` / `fail` / `onTimer` verbs + `subs`. The\n * wrapper only ADAPTS the boundary: the verb's `input` is the ORIGINAL base\n * Cmd, the verb's `resilient_run` carrier is renamed to `$resilience:run`, and\n * the sub / timer ids are re-keyed into the `$resilience:` namespace (rule 4).\n *\n * ## The 5 rules it satisfies\n *\n * 1. **Named, serializable slice.** `model.$resilience` is resilient-call's\n * plain-data `ResilientState` — JSON-serializable (the deadline error is a\n * `{_tag,...}` sentinel, never a `new Error`), never a closure.\n * 2. **Retag-and-re-emit, never swallow.** See above — a target base Cmd is\n * always inside a `$resilience:run` inner payload or recorded by a\n * `$resilience:*` divergence Cmd in the same transition.\n * 3. **Every decision is a Msg/Cmd.** Gate / retry-schedule / fast-fail /\n * settle are all `$resilience:*` Cmds and Msgs through the merged `update`.\n * 4. **Subs merge by id.** Base subs ⧺ resilient-call retry/deadline timers,\n * re-keyed `$resilience:retry:{key}` / `$resilience:deadline:{key}`.\n * 5. **Clock out of update.** Backoff jitter RNG is injected at construction;\n * the only clock read is `Date.now()` at the interpret boundary (the\n * `$resilience:run` handler stamps the ok/err Msg `at`) and in the timer\n * Sub. The merged `update` is PURE — `at` arrives as Msg data.\n */\n\nimport { type DeadlineSub, subscribeDeadline } from \"../deadline\";\nimport type {\n Cmd,\n Interpret,\n Machine,\n Reducer,\n Sub,\n UpdateForm,\n} from \"../index\";\nimport { formOf, subId, tryInterpret } from \"../index\";\nimport { MsgType } from \"../protocol\";\nimport {\n createResilientCall,\n type ResilientConfig,\n type ResilientState,\n} from \"../resilient-call\";\n\n// ===========================================================================\n// Config — the target + the resilience knob + an optional key deriver.\n// ===========================================================================\n\n/**\n * The `withResilience` knob. Extends resilient-call's `ResilientConfig` (every\n * brick optional — omit a brick, omit its gate) with the two fields the wrapper\n * needs that the bare knob does not:\n *\n * - `target` — the `Cmd.type` discriminant of the ONE base Cmd this wrapper\n * hardens. Every other base Cmd passes through untouched.\n * - `keyOf` — OPTIONAL. Derives the per-call resilience `key` from the target\n * base Cmd, so distinct logical calls (distinct urls, distinct ids) get\n * independent retry / cache state. Pure — it runs inside the merged\n * `update`, so it must NOT read the clock / RNG. Defaults to a single\n * shared key (`target`), i.e. one logical call at a time.\n */\nexport interface ResilienceConfig<TC extends Cmd, TM extends { type: string }>\n extends ResilientConfig {\n /** The base `Cmd.type` to make resilient. */\n readonly target: TC[\"type\"];\n /** Optional per-call key deriver. Pure. Defaults to the target type itself. */\n readonly keyOf?: (cmd: TC) => string;\n /**\n * Extracts the real wall-clock time (ms) the TRIGGERING base Msg carries as\n * data — the time-as-data convention `resilient-call` expects on `attempt`.\n *\n * The merged `update` is PURE: it cannot read `Date.now()` (rule 5). The COLD\n * attempt's gate (the very first `attempt` for a target Cmd in a transition)\n * still needs a real instant — the breaker compares `at` against its recorded\n * `openedAtMs`, the cache against its write `at`, the bucket against its last\n * refill `at`, and the deadline cap anchors at `at + deadline.ms`. Fabricating\n * `at = 0` is the betrayal: a cold attempt after a real-time breaker trip then\n * computes cooldown = `0 - realTripTime < 0` forever, so the breaker NEVER\n * recovers, and a `0`-anchored deadline brick fires immediately.\n *\n * So the base Msg that drove this transition MUST carry its own wall time as\n * data, and `at` reads it off that Msg. The merged update passes\n * `at(currentBaseMsg)` into `rc.attempt` for every target Cmd that transition\n * emitted — real time enters the cold gate as Msg data, never `0`.\n *\n * REQUIRED whenever any time-sensitive brick (`circuit`, `rateLimit`, `cache`,\n * `deadline`) is configured — `withResilience` THROWS at construction if such\n * a brick is set and `at` is absent (errors are data: the cold gate needs real\n * time, refuse to build a breaker that can never recover). OPTIONAL when only\n * `retry` is configured: retry backoff reads its time off the result / timer\n * Msgs (`$resilience:err.at`, `$resilience:timer.atMs`), never the cold attempt\n * — so a `0` cold `at` is harmless there. Pure: it runs inside the merged\n * `update`, so it must NOT read the clock / RNG.\n */\n readonly at?: (msg: TM) => number;\n}\n\n// ===========================================================================\n// The slice + the wrapper Cmds/Msgs/Subs/Ports vocabulary.\n// ===========================================================================\n\n/**\n * The composed Model. The base machine's state nests under `base`; the wrapper\n * owns the NAMED `$resilience` slice — resilient-call's `ResilientState` keyed\n * by the per-call `key`, with `I = TC` (the original target base Cmd is the\n * port input) and `R = unknown` (the base interpret handler's result is opaque\n * to the wrapper — it only routes Ok/Err). Plain data → round-trips through\n * `JSON.parse(JSON.stringify(...))` iff the base state does.\n */\nexport interface ResilienceModel<S, TC extends Cmd> {\n readonly base: S;\n readonly $resilience: ResilientState<TC, unknown>;\n}\n\n/**\n * The carrier Cmd the wrapper emits when the gate ADMITS a target base Cmd. It\n * RETAGS the original base Cmd into `input` — the base Cmd is plain data, so no\n * closure (invariant 3). The interpret handler unwraps `input` and runs it\n * through the BASE interpret for that Cmd type. `key` indexes the resilient\n * call this run belongs to.\n */\nexport type ResilienceRunCmd<TC extends Cmd> = Cmd<\"$resilience:run\"> & {\n readonly key: string;\n /** The ORIGINAL base Cmd, retagged — never swallowed. */\n readonly input: TC;\n};\n\n/**\n * The success Msg the `$resilience:run` handler dispatches back when the base\n * interpret resolved OK. Routes to `succeed`. `at` is stamped at the interpret\n * boundary (the one permitted clock read).\n */\nexport type ResilienceOkMsg = {\n readonly type: \"$resilience:ok\";\n readonly key: string;\n readonly result: unknown;\n readonly at: number;\n};\n\n/**\n * The error Msg the `$resilience:run` handler dispatches back when the base\n * interpret threw / rejected. Routes to `fail` (trip the breaker, then back off\n * or settle). `at` is stamped at the interpret boundary.\n */\nexport type ResilienceErrMsg = {\n readonly type: \"$resilience:err\";\n readonly key: string;\n readonly error: unknown;\n readonly at: number;\n};\n\n/**\n * The retry / deadline timer Msg the `$resilience:timer` Sub dispatches when\n * the wall clock crosses the armed instant. Routes to `onTimer`. `id` is the\n * `$resilience:`-namespaced timer id; `atMs` is the fire instant (Msg data, the\n * clock that drove it lives in the Sub).\n */\nexport type ResilienceTimerMsg = {\n readonly type: \"$resilience:timer\";\n readonly id: string;\n readonly atMs: number;\n};\n\n/** Every Msg the wrapper adds to the base's Msg union. */\nexport type ResilienceMsg =\n | ResilienceOkMsg\n | ResilienceErrMsg\n | ResilienceTimerMsg;\n\n/** Every Cmd the wrapper adds to the base's Cmd union. */\nexport type ResilienceCmd<TC extends Cmd> = ResilienceRunCmd<TC>;\n\n/** The Sub the wrapper adds — a deadline-style timer in the `$resilience` family. */\nexport type ResilienceTimerSub = Sub<\"$resilience:timer\"> & {\n readonly atMs: number;\n};\n\n// ===========================================================================\n// Boundary re-keying — the resilient-call namespace ↔ the `$resilience` one.\n// ===========================================================================\n\n// resilient-call emits its carrier as `resilient_run` and keys its timer Subs\n// `resilient:retry:{key}` / `resilient:deadline:{key}`. The wrapper presents the\n// `$resilience:` namespace to the outside world (rule 4) while REUSING the\n// unmodified verbs underneath. These two pure string maps are the only seam:\n// rename the carrier on the way OUT, re-key the timer id on the way IN.\n\nconst RC_RETRY_PREFIX = \"resilient:retry:\";\nconst RC_DEADLINE_PREFIX = \"resilient:deadline:\";\nconst WX_RETRY_PREFIX = \"$resilience:retry:\";\nconst WX_DEADLINE_PREFIX = \"$resilience:deadline:\";\n\n/** resilient-call internal sub id → the `$resilience:`-namespaced public id. */\nfunction toWrapperTimerId(rcId: string): string {\n if (rcId.startsWith(RC_RETRY_PREFIX))\n return WX_RETRY_PREFIX + rcId.slice(RC_RETRY_PREFIX.length);\n if (rcId.startsWith(RC_DEADLINE_PREFIX))\n return WX_DEADLINE_PREFIX + rcId.slice(RC_DEADLINE_PREFIX.length);\n return rcId;\n}\n\n/** The `$resilience:`-namespaced timer id → the resilient-call internal id. */\nfunction toRcTimerId(wxId: string): string {\n if (wxId.startsWith(WX_RETRY_PREFIX))\n return RC_RETRY_PREFIX + wxId.slice(WX_RETRY_PREFIX.length);\n if (wxId.startsWith(WX_DEADLINE_PREFIX))\n return RC_DEADLINE_PREFIX + wxId.slice(WX_DEADLINE_PREFIX.length);\n return wxId;\n}\n\n// ===========================================================================\n// update-form dispatch — run the base reducer regardless of its shape.\n// (Mirrors withTelemetry's inline form-branching so the wrapper stays\n// standalone; the composed Model is never discriminated on `.type`.)\n// ===========================================================================\n\ntype BaseCellFn<S, M, C extends Cmd> = (\n state: S,\n msg: M,\n) => readonly [S, readonly C[]];\n\n/**\n * Invoke the base machine's `update` for `msg` against base `state`, returning\n * the base's `[nextBase, baseCmds]` UNCHANGED. Pure — routes to the base cell;\n * never reads the clock, allocates an Error, or mutates state.\n */\nfunction runBaseUpdate<S, M extends { type: string }, C extends Cmd>(\n update: object,\n // The base's update form, read once via `formOf(base)` — no local heuristic.\n form: UpdateForm,\n state: S,\n msg: M,\n): readonly [S, readonly C[]] {\n if (form === \"reducer\") {\n const record = update as unknown as Record<string, BaseCellFn<S, M, C>>;\n // biome-ignore lint/style/noNonNullAssertion: the base Reducer guarantees a cell for every dispatched Msg.type; `!` is required under noUncheckedIndexedAccess and cannot miss for a Msg the base accepts\n return record[msg.type]!(state, msg);\n }\n const table = update as unknown as Record<\n string,\n Record<string, BaseCellFn<S, M, C>>\n >;\n const stateKey = (state as unknown as { type: string }).type;\n // biome-ignore lint/style/noNonNullAssertion: the base Transitions table guarantees every (state.type × msg.type) cell exists; `!` is required under noUncheckedIndexedAccess and cannot miss at runtime\n return table[stateKey]![msg.type]!(state, msg);\n}\n\n/** Recover the base Msg.type set from either update form (see withTelemetry). */\nfunction baseMsgKeys(update: object, form: UpdateForm): readonly string[] {\n const keys = Object.keys(update);\n const firstKey = keys[0];\n if (firstKey === undefined) return [];\n if (form === \"reducer\") return keys;\n const firstValue = (update as Record<string, unknown>)[firstKey];\n return Object.keys(firstValue as object);\n}\n\n/**\n * Does `update` declare `key` as a Msg.type cell, in EITHER update form? The\n * reserved-namespace guard checks the correct level per form (the same\n * detection `baseMsgKeys` / `runBaseUpdate` use):\n *\n * - Reducer form (`{ [msgType]: cell }`, values are functions) — the\n * msg-type keys live at the TOP level, so `Object.hasOwn(update, key)`.\n * - Transitions form (`{ [stateType]: { [msgType]: cell } }`, values are\n * records) — the msg-type keys live in the INNER tables, one per state.\n * A reserved msg-type can hide in ANY inner table, so scan EVERY inner\n * table; a collision in even one inner cell would let a transitions-form\n * base squat on e.g. an inner `$resilience:ok` cell that the wrapper's\n * merged update would silently clobber. Top-level `Object.hasOwn` (the\n * old check) only sees state-type keys here and would MISS it entirely.\n */\nfunction updateDeclaresMsgKey(\n update: object,\n form: UpdateForm,\n key: string,\n): boolean {\n const keys = Object.keys(update);\n const firstKey = keys[0];\n if (firstKey === undefined) return false;\n if (form === \"reducer\") {\n // Reducer form — msg-type keys at the top level.\n return Object.hasOwn(update, key);\n }\n // Transitions form — msg-type keys live in each inner state-type table.\n for (const stateKey of keys) {\n const innerTable = (update as Record<string, unknown>)[stateKey];\n if (\n innerTable !== null &&\n typeof innerTable === \"object\" &&\n Object.hasOwn(innerTable, key)\n ) {\n return true;\n }\n }\n return false;\n}\n\n// ===========================================================================\n// withResilience — the wrapper.\n// ===========================================================================\n\n/**\n * Wrap `base` so its `config.target` Cmd is run through the resilient-call\n * concern (cache → circuit → rate-limit → retry, deadline-capped). Returns a\n * NEW `Machine` over the composed Model `{ base, $resilience }`, with the\n * base's Msgs/Cmds/Subs/Ctx extended by the wrapper's own.\n *\n * @param base any `Machine<S, M, C, U, Ctx>`.\n * @param config the resilience knob: `target`, the optional bricks, `keyOf`.\n * @param rng injected backoff jitter source. Pass a fixed `() => 0.5` in\n * tests to pin retry delays; defaults to `Math.random` (read only\n * at the verb boundary, never inside the merged `update`).\n */\nexport function withResilience<\n S,\n M extends { type: string },\n C extends Cmd,\n U extends Sub,\n Ctx,\n>(\n base: Machine<S, M, C, U, Ctx>,\n config: ResilienceConfig<C, M>,\n rng: () => number = Math.random,\n): Machine<\n ResilienceModel<S, C>,\n M | ResilienceMsg,\n C | ResilienceCmd<C>,\n U | ResilienceTimerSub,\n Ctx\n> {\n type WM = ResilienceModel<S, C>;\n type WMsg = M | ResilienceMsg;\n type WCmd = C | ResilienceCmd<C>;\n\n const { target } = config;\n const keyOf = config.keyOf ?? (() => target);\n\n // A time-sensitive brick gates the COLD attempt against real wall time read\n // off the triggering base Msg (`config.at`). Without `at` the cold gate would\n // have to fabricate `0` — and a cold attempt after a real-time breaker trip\n // then computes cooldown = `0 - realTripTime < 0` forever (the breaker NEVER\n // recovers), while a `0`-anchored deadline fires immediately. Refuse to build\n // such a machine: errors are data, surfaced at construction, never a silent\n // breaker that can't recover. Retry alone reads time off the result/timer\n // Msgs, not the cold attempt, so `at` stays optional there.\n const timeSensitiveBrick =\n config.circuit !== undefined ||\n config.rateLimit !== undefined ||\n config.cache !== undefined ||\n config.deadline !== undefined;\n if (timeSensitiveBrick && config.at === undefined) {\n throw new Error(\n \"withResilience: a time-sensitive brick (circuit / rateLimit / cache / \" +\n \"deadline) is configured but `config.at` is missing. The cold-attempt \" +\n \"gate needs the REAL wall time the triggering base Msg carries as data \" +\n \"(time-as-data) — without it the gate would fabricate `at = 0`, so a \" +\n \"cold attempt after a real-time breaker trip computes a negative \" +\n \"cooldown and the breaker NEVER recovers (and a deadline brick fires \" +\n \"immediately). Provide `at: (msg) => msg.<wallTimeField>`.\",\n );\n }\n // Read the triggering base Msg's wall time as data for the cold gate. When no\n // time-sensitive brick is configured `at` may be omitted; the cold attempt\n // then gates at `0`, which is harmless because retry backoff reads its time\n // off the result / timer Msgs, never the cold attempt.\n const atOf = config.at ?? (() => 0);\n\n // The REUSED knob: I = the original target base Cmd, R = the opaque base\n // interpret result. Its verbs / subs / gate are used unmodified; the wrapper\n // only adapts the boundary (carrier rename + timer-id re-keying).\n const rc = createResilientCall<C, unknown>(config, rng);\n\n // -------------------------------------------------------------------------\n // The merged update — a flat Reducer over the composed (non-discriminated)\n // Model. Cells: every base Msg.type (delegating to base.update + partition),\n // plus the three `$resilience:*` Msgs (delegating to the reused verbs).\n // -------------------------------------------------------------------------\n\n type Cell = (state: WM, msg: WMsg) => readonly [WM, readonly WCmd[]];\n const update: Record<string, Cell> = {};\n\n // The base's update form, read ONCE from the `__form` tag (see `formOf`) and\n // threaded into the per-form helpers — no structural re-derivation here.\n const baseForm = formOf(base);\n\n // --- Base-Msg cells: delegate, then PARTITION + retag the target Cmd. ----\n for (const key of baseMsgKeys(base.update, baseForm)) {\n update[key] = (state, msg) => {\n // 1) Run the base reducer. Its NON-target Cmds pass through unchanged.\n const [nextBase, baseCmds] = runBaseUpdate<S, M, C>(\n base.update,\n baseForm,\n state.base,\n msg as M,\n );\n\n // 2) Partition base Cmds: non-target pass straight through; each target\n // Cmd is routed through the resilient-call `attempt` gate, which either\n // emits a `resilient_run` carrier (→ renamed `$resilience:run`,\n // retagging the ORIGINAL base Cmd into `input`), or records the gate\n // decision in the slice with NO carrier (cache hit / circuit-open /\n // rate-limited backoff). Either way the target Cmd never escapes raw\n // and never vanishes off-ledger.\n let resilience = state.$resilience;\n const outCmds: WCmd[] = [];\n // The COLD attempt's gate time — the REAL wall time the triggering base\n // Msg carries as data (rule 5: the merged `update` stays pure; the clock\n // does not enter here, the Msg's own `at` data does). With this real\n // instant the breaker compares `at - openedAtMs` against its cooldown\n // (set by a prior real-time `$resilience:err`), so a cold attempt during\n // cooldown fast-fails and one AFTER cooldown is admitted — the breaker\n // RECOVERS. The cache compares `at` against its stored write `at`, the\n // bucket refills from `at`, and the deadline cap anchors at\n // `at + deadline.ms` — all against true wall time, never a fabricated\n // `0`. Every SUBSEQUENT gate run (`fail` → backoff, retry-timer\n // `onTimer` → re-gate) reads time off the result / timer Msgs the same\n // way. `atOf` defaults to `0` ONLY when no time-sensitive brick is\n // configured (construction throws otherwise), where retry backoff reads\n // its time off the result/timer Msgs and the cold `at` is never compared.\n const at = atOf(msg as M);\n for (const cmd of baseCmds) {\n if (cmd.type !== target) {\n outCmds.push(cmd);\n continue;\n }\n const callKey = keyOf(cmd);\n const [nextSlice, runCmds] = rc.attempt(resilience, callKey, cmd, at);\n resilience = nextSlice;\n // rc.attempt emits 0 or 1 `resilient_run` carriers. Rename each to the\n // `$resilience:run` namespace, preserving the retagged `input` (the\n // ORIGINAL base Cmd). Zero carriers = the gate recorded a divergence in\n // `nextSlice` (cache/circuit/backoff) — visible in the slice + log.\n for (const rcRun of runCmds) {\n outCmds.push({\n type: \"$resilience:run\",\n key: rcRun.key,\n input: rcRun.input,\n });\n }\n }\n\n const next: WM = { base: nextBase, $resilience: resilience };\n return [next, outCmds];\n };\n }\n\n // --- `$resilience:ok` → succeed ------------------------------------------\n update[\"$resilience:ok\"] = (state, msg) => {\n const m = msg as ResilienceOkMsg;\n const [slice, runCmds] = rc.succeed(state.$resilience, m.key, {\n type: MsgType.ResilientOk,\n key: m.key,\n result: m.result,\n at: m.at,\n });\n return [{ ...state, $resilience: slice }, renameRunCmds(runCmds)];\n };\n\n // --- `$resilience:err` → fail --------------------------------------------\n update[\"$resilience:err\"] = (state, msg) => {\n const m = msg as ResilienceErrMsg;\n const [slice, runCmds] = rc.fail(state.$resilience, m.key, {\n type: MsgType.ResilientErr,\n key: m.key,\n error: m.error,\n at: m.at,\n });\n return [{ ...state, $resilience: slice }, renameRunCmds(runCmds)];\n };\n\n // --- `$resilience:timer` → onTimer (retry re-runs gate / deadline settles) -\n update[\"$resilience:timer\"] = (state, msg) => {\n const m = msg as ResilienceTimerMsg;\n // Re-key the public `$resilience:`-id back to the resilient-call internal\n // id the `onTimer` verb matches against, then run the unmodified verb.\n const [slice, runCmds] = rc.onTimer(state.$resilience, {\n type: \"deadline_exceeded\",\n id: toRcTimerId(m.id),\n atMs: m.atMs,\n });\n return [{ ...state, $resilience: slice }, renameRunCmds(runCmds)];\n };\n\n // Rename any `resilient_run` carriers a verb produced (the retry re-attempt\n // path) into the `$resilience:run` namespace, preserving the retagged input.\n function renameRunCmds(\n runCmds: readonly { type: string; key: string; input: C }[],\n ): readonly WCmd[] {\n return runCmds.map((r) => ({\n type: \"$resilience:run\" as const,\n key: r.key,\n input: r.input,\n }));\n }\n\n // -------------------------------------------------------------------------\n // Subs — base subs ⧺ resilient-call timers, re-keyed into `$resilience:`.\n // -------------------------------------------------------------------------\n\n const baseSubscriptions = base.subscriptions;\n const baseSubscribe = (base as { subscribe?: unknown }).subscribe;\n\n function subscriptions(state: WM): readonly (U | ResilienceTimerSub)[] {\n const baseSubs = baseSubscriptions\n ? baseSubscriptions(state.base)\n : ([] as readonly U[]);\n // rc.subs returns DeadlineSubs keyed `resilient:retry:{k}` /\n // `resilient:deadline:{k}`. Re-key each into the `$resilience:` namespace\n // and re-type to the wrapper's `$resilience:timer` Sub family (rule 4).\n const rcSubs: readonly DeadlineSub[] = rc.subs(state.$resilience);\n const timerSubs: ResilienceTimerSub[] = rcSubs.map((s) => ({\n id: subId(toWrapperTimerId(s.id)),\n type: \"$resilience:timer\",\n atMs: s.atMs,\n }));\n return [...baseSubs, ...timerSubs];\n }\n\n // -------------------------------------------------------------------------\n // Interpret — base.interpret for non-target + the `$resilience:run` handler\n // that COMPOSES base.interpret for the retagged inner Cmd.\n // -------------------------------------------------------------------------\n\n const baseInterpret =\n (base as { interpret?: Interpret<M, C, Ctx> }).interpret ??\n ({} as Interpret<M, C, Ctx>);\n\n // Reserved-namespace guard (mirrors withTelemetry + the substrate's\n // definePort / SubId collision asserts). The wrapper OWNS four reserved keys:\n // the `$resilience:run` carrier Cmd, the `$resilience:ok` / `$resilience:err`\n // result Msgs, and the `$resilience:timer` Sub Msg. The merges below spread\n // the wrapper's cells over the base's update / interpret / subscribe maps; if\n // the base already declares ANY reserved key on ANY of those three surfaces,\n // the spread would SILENTLY clobber it (or the base's own key would shadow the\n // wrapper's). The `$resilience:` namespace is the wrapper's — refuse to wrap a\n // base that squats on any of the four across any surface.\n //\n // Ordered BEFORE the target-handler guard below: squatting a reserved key is a\n // target-INDEPENDENT structural defect of the base, so it is the more\n // fundamental rejection and must report first. Otherwise a base that BOTH\n // squats `$resilience:*` AND omits the target handler would surface the\n // narrower missing-target error and mask the namespace collision — exactly the\n // regression #111's construction-time hoist introduced (the hoisted target\n // check shadowed this guard for such a base), fixed by #112.\n //\n // `update` is checked PER FORM (the same Reducer-vs-Transitions detection the\n // wrapper already uses in `baseMsgKeys` / `runBaseUpdate`): a Reducer-form\n // base keys its msg-types at the TOP level, but a Transitions-form base keys\n // them in the INNER `{ [stateType]: { [msgType]: cell } }` tables — so a flat\n // top-level `Object.hasOwn` would MISS a reserved msg-type squatting inside an\n // inner table (e.g. an inner `$resilience:ok` cell) and let the merged update\n // silently clobber it. `interpret` and `subscribe` are always flat keyed-by\n // -type maps, so the direct `Object.hasOwn` is correct there.\n const RESERVED = [\n \"$resilience:run\",\n \"$resilience:ok\",\n \"$resilience:err\",\n \"$resilience:timer\",\n ] as const;\n const surfaces: readonly {\n readonly name: string;\n readonly declares: (reserved: string) => boolean;\n }[] = [\n {\n name: \"update\",\n declares: (reserved) =>\n updateDeclaresMsgKey(base.update as object, baseForm, reserved),\n },\n {\n name: \"interpret\",\n declares: (reserved) => Object.hasOwn(baseInterpret as object, reserved),\n },\n {\n name: \"subscribe\",\n declares: (reserved) =>\n Object.hasOwn((baseSubscribe as object | undefined) ?? {}, reserved),\n },\n ];\n for (const reserved of RESERVED) {\n for (const surface of surfaces) {\n if (surface.declares(reserved)) {\n throw new Error(\n `withResilience: the base machine declares a reserved \"${reserved}\" ` +\n `${surface.name} key — the wrapper owns the \"$resilience:\" ` +\n `namespace ($resilience:run / :ok / :err / :timer across update, ` +\n `interpret, and subscribe). Rename the base key.`,\n );\n }\n }\n }\n\n // Construction guard — the target Cmd MUST have a base interpret handler. This\n // is a property of the (base, config) pair, fully known here at construction:\n // the `$resilience:run` carrier delegates to `baseInterpret[target]`, so a\n // missing handler means the resilient effect has nothing to perform. Surface\n // it now — refuse to build a machine whose target can never run — rather than\n // lazily on the first effect (errors are data, surfaced at construction, like\n // the time-sensitive-`at` and reserved-namespace guards above). Ordered AFTER\n // the reserved-namespace guard so a base that squats `$resilience:*` is\n // rejected for the namespace collision first, not masked by this narrower\n // missing-target error (#112).\n if (!Object.hasOwn(baseInterpret as object, target)) {\n throw new Error(\n `withResilience: no base interpret handler for target Cmd \"${target}\" ` +\n `— the resilient effect has nothing to perform. The base machine must ` +\n `declare an interpret handler for its target Cmd type.`,\n );\n }\n\n // The `$resilience:run` handler delegates to the BASE interpret handler for\n // the retagged inner Cmd's type, wrapped via tryInterpret so Ok routes to\n // `$resilience:ok` and Err to `$resilience:err`. `Date.now()` is stamped here\n // — the ONE permitted clock read (interpret is impure; update is pure).\n const runHandler = tryInterpret<\n ResilienceRunCmd<C>,\n // The carried result is the base interpret handler's resolution, whose\n // contract is `Promise<M | void>` (a follow-up base Msg or nothing — see\n // `Interpret<M, C, Ctx>`). Carrying `M | void` here (not bare `unknown`)\n // keeps the base's follow-up Msg type at the seam; `ResilienceOkMsg.result`\n // then narrows from genuine looseness to \"a base Msg or void\".\n // biome-ignore lint/suspicious/noConfusingVoidType: mirrors `Interpret`'s own `Promise<M | void>` — the base handler resolves to a follow-up Msg OR nothing; `M | undefined` would reject no-return bodies\n M | void,\n ResilienceOkMsg | ResilienceErrMsg,\n unknown\n >(\n async (cmd, ctx) => {\n // Compose the base interpret: run the ORIGINAL base Cmd through the base's\n // own handler for its type. The base handler may itself return a follow-up\n // Msg or void; the resilience layer treats its RESOLUTION (resolve vs\n // throw) as the success/failure signal, and carries whatever it returned\n // as `result`. A throw → tryInterpret routes to `$resilience:err`.\n const inner = cmd.input;\n // The base handler's own type is `Interpret<M, C, Ctx>[type]`, i.e.\n // `(cmd, ctx & PortEmitter) => Promise<M | void>`. We read it off the\n // erased `Record` and re-narrow to that contract — the result type is\n // KNOWN (the base Msg union or void), so it is not widened to `unknown`.\n // biome-ignore lint/suspicious/noConfusingVoidType: the base handler contract is `Promise<M | void>` (follow-up Msg or no-return); narrowing to `undefined` would reject void-returning base handlers\n type BaseHandler = (c: C, ctx: Ctx) => Promise<M | void>;\n const handler = (baseInterpret as Record<string, unknown>)[inner.type] as\n | BaseHandler\n | undefined;\n if (handler === undefined) {\n // Unreachable in practice: the construction guard above already refused\n // to build this machine if `baseInterpret[target]` was missing, and the\n // retagged inner Cmd's type is always the target. Kept as defense in\n // depth on the erased-Record read — if it ever fires it routes to\n // `$resilience:err` (errors are data, never swallowed).\n throw new Error(\n `withResilience: no base interpret handler for target Cmd ` +\n `\"${inner.type}\" — the resilient effect has nothing to perform.`,\n );\n }\n return await handler(inner, ctx as unknown as Ctx);\n },\n (result, cmd): ResilienceOkMsg => ({\n type: \"$resilience:ok\",\n key: cmd.key,\n result,\n at: Date.now(),\n }),\n (error, cmd): ResilienceErrMsg => ({\n type: \"$resilience:err\",\n key: cmd.key,\n error,\n at: Date.now(),\n }),\n );\n\n const interpret = {\n ...(baseInterpret as Record<string, unknown>),\n \"$resilience:run\": runHandler,\n } as Interpret<WMsg, WCmd, Ctx>;\n\n // -------------------------------------------------------------------------\n // The `subscribe` map — base cells ⧺ the `$resilience:timer` cell, which\n // delegates the timer lifecycle to the deadline Sub primitive (re-keying the\n // dispatched Msg into the `$resilience:timer` shape). Clock lives here.\n // -------------------------------------------------------------------------\n\n const subscribeMap = {\n ...((baseSubscribe as Record<string, unknown> | undefined) ?? {}),\n \"$resilience:timer\": (\n sub: ResilienceTimerSub,\n ctx: Ctx,\n dispatch: (msg: WMsg) => void,\n ): (() => void) =>\n // Reuse the deadline subscribe cell wholesale: it arms a one-shot timer\n // for `max(0, atMs - Date.now())` and fires when the wall clock crosses\n // `atMs`. We hand it a `DeadlineSub` shape and translate its\n // `deadline_exceeded` Msg into the wrapper's `$resilience:timer` Msg.\n subscribeDeadline(\n { id: sub.id as DeadlineSub[\"id\"], type: \"deadline\", atMs: sub.atMs },\n ctx,\n (dl) =>\n dispatch({ type: \"$resilience:timer\", id: dl.id, atMs: dl.atMs }),\n ),\n };\n\n return {\n init: (loaded, ctx) => {\n // Rehydrate: `loaded !== null` MUST return `[loaded, []]` (no Cmds) — the\n // substrate's replay enforces it. Split the composed loaded Model into its\n // base slice and feed the base its own snapshot so the base rehydrate\n // contract is honored transitively.\n if (loaded !== null) {\n return [loaded, []];\n }\n const [base0, baseCmds] = base.init(null, ctx);\n // The base's OWN init Cmds: NON-target Cmds pass straight through; a\n // TARGET Cmd is RETAGGED (admitted) so it is observed, never raw — the\n // same retag-not-swallow contract the merged update enforces (rule 2). A\n // target Cmd that escaped init raw would bypass the gate AND the carrier,\n // so the resilience layer would never see the effect resolve. At a fresh\n // boot the breaker is closed and the bucket full, so the gate decision is\n // unambiguously ADMIT — but the Cmd must still travel inside a\n // `$resilience:run` carrier (the slice records its `running` phase). Boot\n // is the resilience epoch: the cold gate runs at `at = 0`, harmless here\n // because the breaker is closed (nothing to compare), the cache empty, and\n // the bucket full. Wall time enters once the effect resolves (the\n // `$resilience:ok` / `:err` Msgs carry `at`), exactly as in a transition.\n let resilience = rc.init();\n const initCmds: WCmd[] = [];\n for (const cmd of baseCmds) {\n if (cmd.type !== target) {\n initCmds.push(cmd);\n continue;\n }\n // The boot cold attempt gates at `at = 0` (boot is the resilience epoch:\n // no real Msg drove it, so there is no time-as-data to read). For the\n // circuit / rateLimit / cache bricks that is harmless at a fresh boot —\n // the breaker is closed (nothing to compare), the bucket full, the cache\n // empty, so the gate ADMITS unambiguously and the `0` is never compared\n // against a real instant. The DEADLINE brick is the exception: it anchors\n // the cap at `at + deadline.ms = 0 + ms`, so its `$resilience:deadline`\n // Sub arms at `atMs = ms` and `subscribeDeadline` fires after\n // `max(0, atMs - Date.now()) === 0` ms — i.e. IMMEDIATELY at boot,\n // settling the boot call failed before it can run. A `0`-anchored boot\n // deadline is never the author's intent; it is the same trap the\n // construction guard refuses for transitions (a fabricated `at` the\n // deadline cannot honor). Fail loud: a boot effect that needs a real\n // deadline belongs behind a post-run boot Msg (where a real `at` exists),\n // not an init Cmd. Mirrors the substrate guidance \"boot effects belong in\n // a boot Msg, not init Cmds.\"\n if (config.deadline !== undefined) {\n throw new Error(\n `withResilience: base.init emits the target Cmd \"${target}\" while a ` +\n `deadline brick is configured. The boot cold attempt has no real ` +\n `wall time (boot is gated at at=0), so the deadline would anchor at ` +\n `0 + ${config.deadline.ms}ms and its $resilience:deadline Sub would ` +\n `fire IMMEDIATELY (max(0, atMs - now) === 0), failing the boot call ` +\n `instantly. Move the boot effect out of base.init and into a boot ` +\n `Msg dispatched after run() (where the triggering Msg carries a real ` +\n `at via config.at), so the deadline anchors at a real instant. (Boot ` +\n `effects belong in a boot Msg, not init Cmds.)`,\n );\n }\n const callKey = keyOf(cmd);\n const [nextSlice, runCmds] = rc.attempt(resilience, callKey, cmd, 0);\n resilience = nextSlice;\n for (const rcRun of runCmds) {\n initCmds.push({\n type: \"$resilience:run\",\n key: rcRun.key,\n input: rcRun.input,\n });\n }\n }\n const model: WM = { base: base0, $resilience: resilience };\n return [model, initCmds];\n },\n update: update as unknown as Reducer<WM, WMsg, WCmd>,\n subscriptions,\n subscribe: subscribeMap as unknown as Machine<\n WM,\n WMsg,\n WCmd,\n U | ResilienceTimerSub,\n Ctx\n >[\"subscribe\"],\n interpret,\n } as Machine<WM, WMsg, WCmd, U | ResilienceTimerSub, Ctx>;\n}\n"]}
1
+ {"version":3,"sources":["../../src/with-resilience/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;AAgOA,IAAM,eAAA,GAAkB,kBAAA;AACxB,IAAM,kBAAA,GAAqB,qBAAA;AAC3B,IAAM,eAAA,GAAkB,oBAAA;AACxB,IAAM,kBAAA,GAAqB,uBAAA;AAG3B,SAAS,iBAAiB,IAAA,EAAsB;AAC9C,EAAA,IAAI,IAAA,CAAK,WAAW,eAAe,CAAA;AACjC,IAAA,OAAO,eAAA,GAAkB,IAAA,CAAK,KAAA,CAAM,eAAA,CAAgB,MAAM,CAAA;AAC5D,EAAA,IAAI,IAAA,CAAK,WAAW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O,QAAQ,CAAA;AAAA,IACzB,CAAA;AAAA,IACA,MAAA;AAAA,IACA,aAAA;AAAA,IACA,SAAA,EAAW,YAAA;AAAA,IAOX;AAAA,GACF;AACF","file":"index.js","sourcesContent":["/**\n * @demlik/tea/with-resilience — the INTERCEPTING wrapper of the wrapper tier.\n *\n * `withResilience(base, config)` is a **pure function over machine data**: it\n * takes any `Machine<S, M, C, U, Ctx>`, a chosen TARGET base Cmd type, and a\n * resilience knob, and returns a NEW `Machine` over the composed Model\n * `{ base, $resilience }`. You `run()` / `replay()` the result exactly like any\n * other machine — there is no new runtime, no privileged interception path.\n *\n * This is the HARDEST wrapper. `withTelemetry` only OBSERVES; this one\n * INTERCEPTS. It bolts the resilient-call concern (cache → circuit-breaker →\n * rate-limit → exponential-backoff retry, with a deadline cap) onto a chosen\n * base Cmd WITHOUT the base authoring any of it. The base keeps emitting its\n * plain effect Cmd; the wrapper diverts each one through the resilience gate.\n *\n * ## Retag, never swallow (rule 2 — the whole danger)\n *\n * The merged `update` delegates to `base.update`, then PARTITIONS the base Cmds\n * by type:\n *\n * - A NON-target base Cmd passes through UNCHANGED — byte-identical, in the\n * same slot. The wrapper does not touch effects it was not asked to harden.\n * - A TARGET base Cmd is RETAGGED: it becomes the `input` payload of a\n * `$resilience:run` carrier Cmd (when the gate admits it), OR its gating is\n * RECORDED as a `$resilience:*` decision in the SAME transition (cache hit,\n * circuit-open fast-fail, rate-limited backoff). It is NEVER emitted raw,\n * and it NEVER vanishes without a `$resilience:*` Cmd recording where it\n * went. That recorded divergence is exactly what the conformance gate's\n * `intercepting` option verifies.\n *\n * The resilient-call result Msgs route back through the merged `update`:\n * `$resilience:ok` → `succeed` (close the breaker, fill the cache, reset the\n * retry run), `$resilience:err` → `fail` (trip the breaker, then back off or\n * settle), `$resilience:timer` → `onTimer` (a retry timer re-runs the gate; a\n * deadline timer settles the call failed). Every decision is a Msg/Cmd through\n * the reducer + log — \"why did this fire\" is answerable from the log alone.\n *\n * ## The slice + verbs are REUSED, not reinvented\n *\n * The `$resilience` slice IS resilient-call's `ResilientState<I, R>` (per-key\n * call / retry / circuit / bucket / cache), and the gate / backoff / breaker\n * logic IS its `attempt` / `succeed` / `fail` / `onTimer` verbs + `subs`. The\n * wrapper only ADAPTS the boundary: the verb's `input` is the ORIGINAL base\n * Cmd, the verb's `resilient_run` carrier is renamed to `$resilience:run`, and\n * the sub / timer ids are re-keyed into the `$resilience:` namespace (rule 4).\n *\n * ## The 5 rules it satisfies\n *\n * 1. **Named, serializable slice.** `model.$resilience` is resilient-call's\n * plain-data `ResilientState` — JSON-serializable (the deadline error is a\n * `{_tag,...}` sentinel, never a `new Error`), never a closure.\n * 2. **Retag-and-re-emit, never swallow.** See above — a target base Cmd is\n * always inside a `$resilience:run` inner payload or recorded by a\n * `$resilience:*` divergence Cmd in the same transition.\n * 3. **Every decision is a Msg/Cmd.** Gate / retry-schedule / fast-fail /\n * settle are all `$resilience:*` Cmds and Msgs through the merged `update`.\n * 4. **Subs merge by id.** Base subs ⧺ resilient-call retry/deadline timers,\n * re-keyed `$resilience:retry:{key}` / `$resilience:deadline:{key}`.\n * 5. **Clock out of update.** Backoff jitter RNG is injected at construction;\n * the only clock read is `Date.now()` at the interpret boundary (the\n * `$resilience:run` handler stamps the ok/err Msg `at`) and in the timer\n * Sub. The merged `update` is PURE — `at` arrives as Msg data.\n */\n\nimport { type DeadlineSub, subscribeDeadline } from \"../deadline\";\nimport type {\n Cmd,\n Interpret,\n Machine,\n Reducer,\n Sub,\n UpdateForm,\n} from \"../index\";\nimport { applyCell, formOf, msgKeysOf, subId, tryInterpret } from \"../index\";\nimport { MsgType } from \"../protocol\";\nimport {\n createResilientCall,\n type ResilientConfig,\n type ResilientState,\n} from \"../resilient-call\";\n\n// ===========================================================================\n// Config — the target + the resilience knob + an optional key deriver.\n// ===========================================================================\n\n/**\n * The `withResilience` knob. Extends resilient-call's `ResilientConfig` (every\n * brick optional — omit a brick, omit its gate) with the two fields the wrapper\n * needs that the bare knob does not:\n *\n * - `target` — the `Cmd.type` discriminant of the ONE base Cmd this wrapper\n * hardens. Every other base Cmd passes through untouched.\n * - `keyOf` — OPTIONAL. Derives the per-call resilience `key` from the target\n * base Cmd, so distinct logical calls (distinct urls, distinct ids) get\n * independent retry / cache state. Pure — it runs inside the merged\n * `update`, so it must NOT read the clock / RNG. Defaults to a single\n * shared key (`target`), i.e. one logical call at a time.\n */\nexport interface ResilienceConfig<TC extends Cmd, TM extends { type: string }>\n extends ResilientConfig {\n /** The base `Cmd.type` to make resilient. */\n readonly target: TC[\"type\"];\n /** Optional per-call key deriver. Pure. Defaults to the target type itself. */\n readonly keyOf?: (cmd: TC) => string;\n /**\n * Extracts the real wall-clock time (ms) the TRIGGERING base Msg carries as\n * data — the time-as-data convention `resilient-call` expects on `attempt`.\n *\n * The merged `update` is PURE: it cannot read `Date.now()` (rule 5). The COLD\n * attempt's gate (the very first `attempt` for a target Cmd in a transition)\n * still needs a real instant — the breaker compares `at` against its recorded\n * `openedAtMs`, the cache against its write `at`, the bucket against its last\n * refill `at`, and the deadline cap anchors at `at + deadline.ms`. Fabricating\n * `at = 0` is the betrayal: a cold attempt after a real-time breaker trip then\n * computes cooldown = `0 - realTripTime < 0` forever, so the breaker NEVER\n * recovers, and a `0`-anchored deadline brick fires immediately.\n *\n * So the base Msg that drove this transition MUST carry its own wall time as\n * data, and `at` reads it off that Msg. The merged update passes\n * `at(currentBaseMsg)` into `rc.attempt` for every target Cmd that transition\n * emitted — real time enters the cold gate as Msg data, never `0`.\n *\n * REQUIRED whenever any time-sensitive brick (`circuit`, `rateLimit`, `cache`,\n * `deadline`) is configured — `withResilience` THROWS at construction if such\n * a brick is set and `at` is absent (errors are data: the cold gate needs real\n * time, refuse to build a breaker that can never recover). OPTIONAL when only\n * `retry` is configured: retry backoff reads its time off the result / timer\n * Msgs (`$resilience:err.at`, `$resilience:timer.atMs`), never the cold attempt\n * — so a `0` cold `at` is harmless there. Pure: it runs inside the merged\n * `update`, so it must NOT read the clock / RNG.\n */\n readonly at?: (msg: TM) => number;\n}\n\n// ===========================================================================\n// The slice + the wrapper Cmds/Msgs/Subs/Ports vocabulary.\n// ===========================================================================\n\n/**\n * The composed Model. The base machine's state nests under `base`; the wrapper\n * owns the NAMED `$resilience` slice — resilient-call's `ResilientState` keyed\n * by the per-call `key`, with `I = TC` (the original target base Cmd is the\n * port input) and `R = unknown` (the base interpret handler's result is opaque\n * to the wrapper — it only routes Ok/Err). Plain data → round-trips through\n * `JSON.parse(JSON.stringify(...))` iff the base state does.\n */\nexport interface ResilienceModel<S, TC extends Cmd> {\n readonly base: S;\n readonly $resilience: ResilientState<TC, unknown>;\n}\n\n/**\n * The carrier Cmd the wrapper emits when the gate ADMITS a target base Cmd. It\n * RETAGS the original base Cmd into `input` — the base Cmd is plain data, so no\n * closure (invariant 3). The interpret handler unwraps `input` and runs it\n * through the BASE interpret for that Cmd type. `key` indexes the resilient\n * call this run belongs to.\n */\nexport type ResilienceRunCmd<TC extends Cmd> = Cmd<\"$resilience:run\"> & {\n readonly key: string;\n /** The ORIGINAL base Cmd, retagged — never swallowed. */\n readonly input: TC;\n};\n\n/**\n * The success Msg the `$resilience:run` handler dispatches back when the base\n * interpret resolved OK. Routes to `succeed`. `at` is stamped at the interpret\n * boundary (the one permitted clock read).\n */\nexport type ResilienceOkMsg = {\n readonly type: \"$resilience:ok\";\n readonly key: string;\n readonly result: unknown;\n readonly at: number;\n};\n\n/**\n * The error Msg the `$resilience:run` handler dispatches back when the base\n * interpret threw / rejected. Routes to `fail` (trip the breaker, then back off\n * or settle). `at` is stamped at the interpret boundary.\n */\nexport type ResilienceErrMsg = {\n readonly type: \"$resilience:err\";\n readonly key: string;\n readonly error: unknown;\n readonly at: number;\n};\n\n/**\n * The retry / deadline timer Msg the `$resilience:timer` Sub dispatches when\n * the wall clock crosses the armed instant. Routes to `onTimer`. `id` is the\n * `$resilience:`-namespaced timer id; `atMs` is the fire instant (Msg data, the\n * clock that drove it lives in the Sub).\n */\nexport type ResilienceTimerMsg = {\n readonly type: \"$resilience:timer\";\n readonly id: string;\n readonly atMs: number;\n};\n\n/** Every Msg the wrapper adds to the base's Msg union. */\nexport type ResilienceMsg =\n | ResilienceOkMsg\n | ResilienceErrMsg\n | ResilienceTimerMsg;\n\n/** Every Cmd the wrapper adds to the base's Cmd union. */\nexport type ResilienceCmd<TC extends Cmd> = ResilienceRunCmd<TC>;\n\n/** The Sub the wrapper adds — a deadline-style timer in the `$resilience` family. */\nexport type ResilienceTimerSub = Sub<\"$resilience:timer\"> & {\n readonly atMs: number;\n};\n\n// ===========================================================================\n// Boundary re-keying — the resilient-call namespace ↔ the `$resilience` one.\n// ===========================================================================\n\n// resilient-call emits its carrier as `resilient_run` and keys its timer Subs\n// `resilient:retry:{key}` / `resilient:deadline:{key}`. The wrapper presents the\n// `$resilience:` namespace to the outside world (rule 4) while REUSING the\n// unmodified verbs underneath. These two pure string maps are the only seam:\n// rename the carrier on the way OUT, re-key the timer id on the way IN.\n\nconst RC_RETRY_PREFIX = \"resilient:retry:\";\nconst RC_DEADLINE_PREFIX = \"resilient:deadline:\";\nconst WX_RETRY_PREFIX = \"$resilience:retry:\";\nconst WX_DEADLINE_PREFIX = \"$resilience:deadline:\";\n\n/** resilient-call internal sub id → the `$resilience:`-namespaced public id. */\nfunction toWrapperTimerId(rcId: string): string {\n if (rcId.startsWith(RC_RETRY_PREFIX))\n return WX_RETRY_PREFIX + rcId.slice(RC_RETRY_PREFIX.length);\n if (rcId.startsWith(RC_DEADLINE_PREFIX))\n return WX_DEADLINE_PREFIX + rcId.slice(RC_DEADLINE_PREFIX.length);\n return rcId;\n}\n\n/** The `$resilience:`-namespaced timer id → the resilient-call internal id. */\nfunction toRcTimerId(wxId: string): string {\n if (wxId.startsWith(WX_RETRY_PREFIX))\n return RC_RETRY_PREFIX + wxId.slice(WX_RETRY_PREFIX.length);\n if (wxId.startsWith(WX_DEADLINE_PREFIX))\n return RC_DEADLINE_PREFIX + wxId.slice(WX_DEADLINE_PREFIX.length);\n return wxId;\n}\n\n/**\n * Does the base machine declare `key` as a Msg.type cell, in EITHER update\n * form? The reserved-namespace guard checks the correct level per form (keyed\n * on `formOf`, the same classification `applyCell` / `msgKeysOf` use):\n *\n * - Reducer form (`{ [msgType]: cell }`, values are functions) — the\n * msg-type keys live at the TOP level, so `Object.hasOwn(update, key)`.\n * - Transitions form (`{ [stateType]: { [msgType]: cell } }`, values are\n * records) — the msg-type keys live in the INNER tables, one per state.\n * A reserved msg-type can hide in ANY inner table, so scan EVERY inner\n * table; a collision in even one inner cell would let a transitions-form\n * base squat on e.g. an inner `$resilience:ok` cell that the wrapper's\n * merged update would silently clobber. Top-level `Object.hasOwn` (the\n * old check) only sees state-type keys here and would MISS it entirely.\n */\nfunction updateDeclaresMsgKey(\n machine: { update: object; __form?: UpdateForm },\n key: string,\n): boolean {\n if (formOf(machine) === \"reducer\") {\n // Reducer form — msg-type keys at the top level.\n return Object.hasOwn(machine.update, key);\n }\n // Transitions form — msg-type keys live in each inner state-type table. An\n // inner table can be a callable object (the shape `__form` disambiguates),\n // so accept \"function\" alongside \"object\" here.\n for (const innerTable of Object.values(machine.update)) {\n if (\n innerTable !== null &&\n (typeof innerTable === \"object\" || typeof innerTable === \"function\") &&\n Object.hasOwn(innerTable, key)\n ) {\n return true;\n }\n }\n return false;\n}\n\n// ===========================================================================\n// withResilience — the wrapper.\n// ===========================================================================\n\n/**\n * Wrap `base` so its `config.target` Cmd is run through the resilient-call\n * concern (cache → circuit → rate-limit → retry, deadline-capped). Returns a\n * NEW `Machine` over the composed Model `{ base, $resilience }`, with the\n * base's Msgs/Cmds/Subs/Ctx extended by the wrapper's own.\n *\n * @param base any `Machine<S, M, C, U, Ctx>`.\n * @param config the resilience knob: `target`, the optional bricks, `keyOf`.\n * @param rng injected backoff jitter source. Pass a fixed `() => 0.5` in\n * tests to pin retry delays; defaults to `Math.random` (read only\n * at the verb boundary, never inside the merged `update`).\n */\nexport function withResilience<\n S,\n M extends { type: string },\n C extends Cmd,\n U extends Sub,\n Ctx,\n>(\n base: Machine<S, M, C, U, Ctx>,\n config: ResilienceConfig<C, M>,\n rng: () => number = Math.random,\n): Machine<\n ResilienceModel<S, C>,\n M | ResilienceMsg,\n C | ResilienceCmd<C>,\n U | ResilienceTimerSub,\n Ctx\n> {\n type WM = ResilienceModel<S, C>;\n type WMsg = M | ResilienceMsg;\n type WCmd = C | ResilienceCmd<C>;\n\n const { target } = config;\n const keyOf = config.keyOf ?? (() => target);\n\n // A time-sensitive brick gates the COLD attempt against real wall time read\n // off the triggering base Msg (`config.at`). Without `at` the cold gate would\n // have to fabricate `0` — and a cold attempt after a real-time breaker trip\n // then computes cooldown = `0 - realTripTime < 0` forever (the breaker NEVER\n // recovers), while a `0`-anchored deadline fires immediately. Refuse to build\n // such a machine: errors are data, surfaced at construction, never a silent\n // breaker that can't recover. Retry alone reads time off the result/timer\n // Msgs, not the cold attempt, so `at` stays optional there.\n const timeSensitiveBrick =\n config.circuit !== undefined ||\n config.rateLimit !== undefined ||\n config.cache !== undefined ||\n config.deadline !== undefined;\n if (timeSensitiveBrick && config.at === undefined) {\n throw new Error(\n \"withResilience: a time-sensitive brick (circuit / rateLimit / cache / \" +\n \"deadline) is configured but `config.at` is missing. The cold-attempt \" +\n \"gate needs the REAL wall time the triggering base Msg carries as data \" +\n \"(time-as-data) — without it the gate would fabricate `at = 0`, so a \" +\n \"cold attempt after a real-time breaker trip computes a negative \" +\n \"cooldown and the breaker NEVER recovers (and a deadline brick fires \" +\n \"immediately). Provide `at: (msg) => msg.<wallTimeField>`.\",\n );\n }\n // Read the triggering base Msg's wall time as data for the cold gate. When no\n // time-sensitive brick is configured `at` may be omitted; the cold attempt\n // then gates at `0`, which is harmless because retry backoff reads its time\n // off the result / timer Msgs, never the cold attempt.\n const atOf = config.at ?? (() => 0);\n\n // The REUSED knob: I = the original target base Cmd, R = the opaque base\n // interpret result. Its verbs / subs / gate are used unmodified; the wrapper\n // only adapts the boundary (carrier rename + timer-id re-keying).\n const rc = createResilientCall<C, unknown>(config, rng);\n\n // -------------------------------------------------------------------------\n // The merged update — a flat Reducer over the composed (non-discriminated)\n // Model. Cells: every base Msg.type (delegating to base.update + partition),\n // plus the three `$resilience:*` Msgs (delegating to the reused verbs).\n // -------------------------------------------------------------------------\n\n type Cell = (state: WM, msg: WMsg) => readonly [WM, readonly WCmd[]];\n const update: Record<string, Cell> = {};\n\n // --- Base-Msg cells: delegate, then PARTITION + retag the target Cmd. ----\n // Base Msg keys enumerated via `msgKeysOf(base)` — keyed on the\n // authoritative `__form` tag, no structural re-derivation here (#275).\n for (const key of msgKeysOf(base)) {\n update[key] = (state, msg) => {\n // 1) Run the base reducer. Its NON-target Cmds pass through unchanged.\n const [nextBase, baseCmds] = applyCell<S, M, C>(\n base,\n state.base,\n msg as M,\n );\n\n // 2) Partition base Cmds: non-target pass straight through; each target\n // Cmd is routed through the resilient-call `attempt` gate, which either\n // emits a `resilient_run` carrier (→ renamed `$resilience:run`,\n // retagging the ORIGINAL base Cmd into `input`), or records the gate\n // decision in the slice with NO carrier (cache hit / circuit-open /\n // rate-limited backoff). Either way the target Cmd never escapes raw\n // and never vanishes off-ledger.\n let resilience = state.$resilience;\n const outCmds: WCmd[] = [];\n // The COLD attempt's gate time — the REAL wall time the triggering base\n // Msg carries as data (rule 5: the merged `update` stays pure; the clock\n // does not enter here, the Msg's own `at` data does). With this real\n // instant the breaker compares `at - openedAtMs` against its cooldown\n // (set by a prior real-time `$resilience:err`), so a cold attempt during\n // cooldown fast-fails and one AFTER cooldown is admitted — the breaker\n // RECOVERS. The cache compares `at` against its stored write `at`, the\n // bucket refills from `at`, and the deadline cap anchors at\n // `at + deadline.ms` — all against true wall time, never a fabricated\n // `0`. Every SUBSEQUENT gate run (`fail` → backoff, retry-timer\n // `onTimer` → re-gate) reads time off the result / timer Msgs the same\n // way. `atOf` defaults to `0` ONLY when no time-sensitive brick is\n // configured (construction throws otherwise), where retry backoff reads\n // its time off the result/timer Msgs and the cold `at` is never compared.\n const at = atOf(msg as M);\n for (const cmd of baseCmds) {\n if (cmd.type !== target) {\n outCmds.push(cmd);\n continue;\n }\n const callKey = keyOf(cmd);\n const [nextSlice, runCmds] = rc.attempt(resilience, callKey, cmd, at);\n resilience = nextSlice;\n // rc.attempt emits 0 or 1 `resilient_run` carriers. Rename each to the\n // `$resilience:run` namespace, preserving the retagged `input` (the\n // ORIGINAL base Cmd). Zero carriers = the gate recorded a divergence in\n // `nextSlice` (cache/circuit/backoff) — visible in the slice + log.\n for (const rcRun of runCmds) {\n outCmds.push({\n type: \"$resilience:run\",\n key: rcRun.key,\n input: rcRun.input,\n });\n }\n }\n\n const next: WM = { base: nextBase, $resilience: resilience };\n return [next, outCmds];\n };\n }\n\n // --- `$resilience:ok` → succeed ------------------------------------------\n update[\"$resilience:ok\"] = (state, msg) => {\n const m = msg as ResilienceOkMsg;\n const [slice, runCmds] = rc.succeed(state.$resilience, m.key, {\n type: MsgType.ResilientOk,\n key: m.key,\n result: m.result,\n at: m.at,\n });\n return [{ ...state, $resilience: slice }, renameRunCmds(runCmds)];\n };\n\n // --- `$resilience:err` → fail --------------------------------------------\n update[\"$resilience:err\"] = (state, msg) => {\n const m = msg as ResilienceErrMsg;\n const [slice, runCmds] = rc.fail(state.$resilience, m.key, {\n type: MsgType.ResilientErr,\n key: m.key,\n error: m.error,\n at: m.at,\n });\n return [{ ...state, $resilience: slice }, renameRunCmds(runCmds)];\n };\n\n // --- `$resilience:timer` → onTimer (retry re-runs gate / deadline settles) -\n update[\"$resilience:timer\"] = (state, msg) => {\n const m = msg as ResilienceTimerMsg;\n // Re-key the public `$resilience:`-id back to the resilient-call internal\n // id the `onTimer` verb matches against, then run the unmodified verb.\n const [slice, runCmds] = rc.onTimer(state.$resilience, {\n type: \"deadline_exceeded\",\n id: toRcTimerId(m.id),\n atMs: m.atMs,\n });\n return [{ ...state, $resilience: slice }, renameRunCmds(runCmds)];\n };\n\n // Rename any `resilient_run` carriers a verb produced (the retry re-attempt\n // path) into the `$resilience:run` namespace, preserving the retagged input.\n function renameRunCmds(\n runCmds: readonly { type: string; key: string; input: C }[],\n ): readonly WCmd[] {\n return runCmds.map((r) => ({\n type: \"$resilience:run\" as const,\n key: r.key,\n input: r.input,\n }));\n }\n\n // -------------------------------------------------------------------------\n // Subs — base subs ⧺ resilient-call timers, re-keyed into `$resilience:`.\n // -------------------------------------------------------------------------\n\n const baseSubscriptions = base.subscriptions;\n const baseSubscribe = (base as { subscribe?: unknown }).subscribe;\n\n function subscriptions(state: WM): readonly (U | ResilienceTimerSub)[] {\n const baseSubs = baseSubscriptions\n ? baseSubscriptions(state.base)\n : ([] as readonly U[]);\n // rc.subs returns DeadlineSubs keyed `resilient:retry:{k}` /\n // `resilient:deadline:{k}`. Re-key each into the `$resilience:` namespace\n // and re-type to the wrapper's `$resilience:timer` Sub family (rule 4).\n const rcSubs: readonly DeadlineSub[] = rc.subs(state.$resilience);\n const timerSubs: ResilienceTimerSub[] = rcSubs.map((s) => ({\n id: subId(toWrapperTimerId(s.id)),\n type: \"$resilience:timer\",\n atMs: s.atMs,\n }));\n return [...baseSubs, ...timerSubs];\n }\n\n // -------------------------------------------------------------------------\n // Interpret — base.interpret for non-target + the `$resilience:run` handler\n // that COMPOSES base.interpret for the retagged inner Cmd.\n // -------------------------------------------------------------------------\n\n const baseInterpret =\n (base as { interpret?: Interpret<M, C, Ctx> }).interpret ??\n ({} as Interpret<M, C, Ctx>);\n\n // Reserved-namespace guard (mirrors withTelemetry + the substrate's\n // definePort / SubId collision asserts). The wrapper OWNS four reserved keys:\n // the `$resilience:run` carrier Cmd, the `$resilience:ok` / `$resilience:err`\n // result Msgs, and the `$resilience:timer` Sub Msg. The merges below spread\n // the wrapper's cells over the base's update / interpret / subscribe maps; if\n // the base already declares ANY reserved key on ANY of those three surfaces,\n // the spread would SILENTLY clobber it (or the base's own key would shadow the\n // wrapper's). The `$resilience:` namespace is the wrapper's — refuse to wrap a\n // base that squats on any of the four across any surface.\n //\n // Ordered BEFORE the target-handler guard below: squatting a reserved key is a\n // target-INDEPENDENT structural defect of the base, so it is the more\n // fundamental rejection and must report first. Otherwise a base that BOTH\n // squats `$resilience:*` AND omits the target handler would surface the\n // narrower missing-target error and mask the namespace collision — exactly the\n // regression #111's construction-time hoist introduced (the hoisted target\n // check shadowed this guard for such a base), fixed by #112.\n //\n // `update` is checked PER FORM (the same `formOf` classification the wrapper\n // already uses via `msgKeysOf` / `applyCell`): a Reducer-form\n // base keys its msg-types at the TOP level, but a Transitions-form base keys\n // them in the INNER `{ [stateType]: { [msgType]: cell } }` tables — so a flat\n // top-level `Object.hasOwn` would MISS a reserved msg-type squatting inside an\n // inner table (e.g. an inner `$resilience:ok` cell) and let the merged update\n // silently clobber it. `interpret` and `subscribe` are always flat keyed-by\n // -type maps, so the direct `Object.hasOwn` is correct there.\n const RESERVED = [\n \"$resilience:run\",\n \"$resilience:ok\",\n \"$resilience:err\",\n \"$resilience:timer\",\n ] as const;\n const surfaces: readonly {\n readonly name: string;\n readonly declares: (reserved: string) => boolean;\n }[] = [\n {\n name: \"update\",\n declares: (reserved) => updateDeclaresMsgKey(base, reserved),\n },\n {\n name: \"interpret\",\n declares: (reserved) => Object.hasOwn(baseInterpret as object, reserved),\n },\n {\n name: \"subscribe\",\n declares: (reserved) =>\n Object.hasOwn((baseSubscribe as object | undefined) ?? {}, reserved),\n },\n ];\n for (const reserved of RESERVED) {\n for (const surface of surfaces) {\n if (surface.declares(reserved)) {\n throw new Error(\n `withResilience: the base machine declares a reserved \"${reserved}\" ` +\n `${surface.name} key — the wrapper owns the \"$resilience:\" ` +\n `namespace ($resilience:run / :ok / :err / :timer across update, ` +\n `interpret, and subscribe). Rename the base key.`,\n );\n }\n }\n }\n\n // Construction guard — the target Cmd MUST have a base interpret handler. This\n // is a property of the (base, config) pair, fully known here at construction:\n // the `$resilience:run` carrier delegates to `baseInterpret[target]`, so a\n // missing handler means the resilient effect has nothing to perform. Surface\n // it now — refuse to build a machine whose target can never run — rather than\n // lazily on the first effect (errors are data, surfaced at construction, like\n // the time-sensitive-`at` and reserved-namespace guards above). Ordered AFTER\n // the reserved-namespace guard so a base that squats `$resilience:*` is\n // rejected for the namespace collision first, not masked by this narrower\n // missing-target error (#112).\n if (!Object.hasOwn(baseInterpret as object, target)) {\n throw new Error(\n `withResilience: no base interpret handler for target Cmd \"${target}\" ` +\n `— the resilient effect has nothing to perform. The base machine must ` +\n `declare an interpret handler for its target Cmd type.`,\n );\n }\n\n // The `$resilience:run` handler delegates to the BASE interpret handler for\n // the retagged inner Cmd's type, wrapped via tryInterpret so Ok routes to\n // `$resilience:ok` and Err to `$resilience:err`. `Date.now()` is stamped here\n // — the ONE permitted clock read (interpret is impure; update is pure).\n const runHandler = tryInterpret<\n ResilienceRunCmd<C>,\n // The carried result is the base interpret handler's resolution, whose\n // contract is `Promise<M | void>` (a follow-up base Msg or nothing — see\n // `Interpret<M, C, Ctx>`). Carrying `M | void` here (not bare `unknown`)\n // keeps the base's follow-up Msg type at the seam; `ResilienceOkMsg.result`\n // then narrows from genuine looseness to \"a base Msg or void\".\n // biome-ignore lint/suspicious/noConfusingVoidType: mirrors `Interpret`'s own `Promise<M | void>` — the base handler resolves to a follow-up Msg OR nothing; `M | undefined` would reject no-return bodies\n M | void,\n ResilienceOkMsg | ResilienceErrMsg,\n unknown\n >(\n async (cmd, ctx) => {\n // Compose the base interpret: run the ORIGINAL base Cmd through the base's\n // own handler for its type. The base handler may itself return a follow-up\n // Msg or void; the resilience layer treats its RESOLUTION (resolve vs\n // throw) as the success/failure signal, and carries whatever it returned\n // as `result`. A throw → tryInterpret routes to `$resilience:err`.\n const inner = cmd.input;\n // The base handler's own type is `Interpret<M, C, Ctx>[type]`, i.e.\n // `(cmd, ctx & PortEmitter) => Promise<M | void>`. We read it off the\n // erased `Record` and re-narrow to that contract — the result type is\n // KNOWN (the base Msg union or void), so it is not widened to `unknown`.\n // biome-ignore lint/suspicious/noConfusingVoidType: the base handler contract is `Promise<M | void>` (follow-up Msg or no-return); narrowing to `undefined` would reject void-returning base handlers\n type BaseHandler = (c: C, ctx: Ctx) => Promise<M | void>;\n const handler = (baseInterpret as Record<string, unknown>)[inner.type] as\n | BaseHandler\n | undefined;\n if (handler === undefined) {\n // Unreachable in practice: the construction guard above already refused\n // to build this machine if `baseInterpret[target]` was missing, and the\n // retagged inner Cmd's type is always the target. Kept as defense in\n // depth on the erased-Record read — if it ever fires it routes to\n // `$resilience:err` (errors are data, never swallowed).\n throw new Error(\n `withResilience: no base interpret handler for target Cmd ` +\n `\"${inner.type}\" — the resilient effect has nothing to perform.`,\n );\n }\n return await handler(inner, ctx as unknown as Ctx);\n },\n (result, cmd): ResilienceOkMsg => ({\n type: \"$resilience:ok\",\n key: cmd.key,\n result,\n at: Date.now(),\n }),\n (error, cmd): ResilienceErrMsg => ({\n type: \"$resilience:err\",\n key: cmd.key,\n error,\n at: Date.now(),\n }),\n );\n\n const interpret = {\n ...(baseInterpret as Record<string, unknown>),\n \"$resilience:run\": runHandler,\n } as Interpret<WMsg, WCmd, Ctx>;\n\n // -------------------------------------------------------------------------\n // The `subscribe` map — base cells ⧺ the `$resilience:timer` cell, which\n // delegates the timer lifecycle to the deadline Sub primitive (re-keying the\n // dispatched Msg into the `$resilience:timer` shape). Clock lives here.\n // -------------------------------------------------------------------------\n\n const subscribeMap = {\n ...((baseSubscribe as Record<string, unknown> | undefined) ?? {}),\n \"$resilience:timer\": (\n sub: ResilienceTimerSub,\n ctx: Ctx,\n dispatch: (msg: WMsg) => void,\n ): (() => void) =>\n // Reuse the deadline subscribe cell wholesale: it arms a one-shot timer\n // for `max(0, atMs - Date.now())` and fires when the wall clock crosses\n // `atMs`. We hand it a `DeadlineSub` shape and translate its\n // `deadline_exceeded` Msg into the wrapper's `$resilience:timer` Msg.\n subscribeDeadline(\n { id: sub.id as DeadlineSub[\"id\"], type: \"deadline\", atMs: sub.atMs },\n ctx,\n (dl) =>\n dispatch({ type: \"$resilience:timer\", id: dl.id, atMs: dl.atMs }),\n ),\n };\n\n return {\n init: (loaded, ctx) => {\n // Rehydrate: `loaded !== null` MUST return `[loaded, []]` (no Cmds) — the\n // substrate's replay enforces it. Split the composed loaded Model into its\n // base slice and feed the base its own snapshot so the base rehydrate\n // contract is honored transitively.\n if (loaded !== null) {\n return [loaded, []];\n }\n const [base0, baseCmds] = base.init(null, ctx);\n // The base's OWN init Cmds: NON-target Cmds pass straight through; a\n // TARGET Cmd is RETAGGED (admitted) so it is observed, never raw — the\n // same retag-not-swallow contract the merged update enforces (rule 2). A\n // target Cmd that escaped init raw would bypass the gate AND the carrier,\n // so the resilience layer would never see the effect resolve. At a fresh\n // boot the breaker is closed and the bucket full, so the gate decision is\n // unambiguously ADMIT — but the Cmd must still travel inside a\n // `$resilience:run` carrier (the slice records its `running` phase). Boot\n // is the resilience epoch: the cold gate runs at `at = 0`, harmless here\n // because the breaker is closed (nothing to compare), the cache empty, and\n // the bucket full. Wall time enters once the effect resolves (the\n // `$resilience:ok` / `:err` Msgs carry `at`), exactly as in a transition.\n let resilience = rc.init();\n const initCmds: WCmd[] = [];\n for (const cmd of baseCmds) {\n if (cmd.type !== target) {\n initCmds.push(cmd);\n continue;\n }\n // The boot cold attempt gates at `at = 0` (boot is the resilience epoch:\n // no real Msg drove it, so there is no time-as-data to read). For the\n // circuit / rateLimit / cache bricks that is harmless at a fresh boot —\n // the breaker is closed (nothing to compare), the bucket full, the cache\n // empty, so the gate ADMITS unambiguously and the `0` is never compared\n // against a real instant. The DEADLINE brick is the exception: it anchors\n // the cap at `at + deadline.ms = 0 + ms`, so its `$resilience:deadline`\n // Sub arms at `atMs = ms` and `subscribeDeadline` fires after\n // `max(0, atMs - Date.now()) === 0` ms — i.e. IMMEDIATELY at boot,\n // settling the boot call failed before it can run. A `0`-anchored boot\n // deadline is never the author's intent; it is the same trap the\n // construction guard refuses for transitions (a fabricated `at` the\n // deadline cannot honor). Fail loud: a boot effect that needs a real\n // deadline belongs behind a post-run boot Msg (where a real `at` exists),\n // not an init Cmd. Mirrors the substrate guidance \"boot effects belong in\n // a boot Msg, not init Cmds.\"\n if (config.deadline !== undefined) {\n throw new Error(\n `withResilience: base.init emits the target Cmd \"${target}\" while a ` +\n `deadline brick is configured. The boot cold attempt has no real ` +\n `wall time (boot is gated at at=0), so the deadline would anchor at ` +\n `0 + ${config.deadline.ms}ms and its $resilience:deadline Sub would ` +\n `fire IMMEDIATELY (max(0, atMs - now) === 0), failing the boot call ` +\n `instantly. Move the boot effect out of base.init and into a boot ` +\n `Msg dispatched after run() (where the triggering Msg carries a real ` +\n `at via config.at), so the deadline anchors at a real instant. (Boot ` +\n `effects belong in a boot Msg, not init Cmds.)`,\n );\n }\n const callKey = keyOf(cmd);\n const [nextSlice, runCmds] = rc.attempt(resilience, callKey, cmd, 0);\n resilience = nextSlice;\n for (const rcRun of runCmds) {\n initCmds.push({\n type: \"$resilience:run\",\n key: rcRun.key,\n input: rcRun.input,\n });\n }\n }\n const model: WM = { base: base0, $resilience: resilience };\n return [model, initCmds];\n },\n update: update as unknown as Reducer<WM, WMsg, WCmd>,\n subscriptions,\n subscribe: subscribeMap as unknown as Machine<\n WM,\n WMsg,\n WCmd,\n U | ResilienceTimerSub,\n Ctx\n >[\"subscribe\"],\n interpret,\n } as Machine<WM, WMsg, WCmd, U | ResilienceTimerSub, Ctx>;\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { C as Cmd, S as Sub, M as Machine } from '../core-CymXZCeY.js';
1
+ import { C as Cmd, S as Sub, M as Machine } from '../core-BoB6t7dB.js';
2
2
 
3
3
  /**
4
4
  * @demlik/tea/with-telemetry — the pattern-setting wrapper of the wrapper tier.
@@ -1,29 +1,14 @@
1
- import '../chunk-2WZHS4P2.js';
2
- import { formOf } from '../chunk-BNJYE4AU.js';
1
+ import '../chunk-MMH7CW5K.js';
2
+ import { msgKeysOf, applyCell } from '../chunk-QLA76GIT.js';
3
3
 
4
4
  // src/with-telemetry/index.ts
5
- function runBaseUpdate(update, form, state, msg) {
6
- if (form === "reducer") {
7
- const record = update;
8
- return record[msg.type](state, msg);
9
- }
10
- const table = update;
11
- const stateKey = state.type;
12
- return table[stateKey][msg.type](state, msg);
13
- }
14
5
  function withTelemetry(base, config = {}) {
15
6
  const project = config.event;
16
- const baseForm = formOf(base);
17
- const msgKeys = telemetryMsgKeys(base.update, baseForm);
7
+ const msgKeys = msgKeysOf(base);
18
8
  const update = {};
19
9
  for (const key of msgKeys) {
20
10
  update[key] = (state, msg) => {
21
- const [nextBase, baseCmds] = runBaseUpdate(
22
- base.update,
23
- baseForm,
24
- state.base,
25
- msg
26
- );
11
+ const [nextBase, baseCmds] = applyCell(base, state.base, msg);
27
12
  const $telemetry = { seq: state.$telemetry.seq + 1 };
28
13
  const next = { base: nextBase, $telemetry };
29
14
  const event = project ? project(msg, state, next) : { seq: $telemetry.seq, msgType: msg.type };
@@ -79,16 +64,6 @@ function withTelemetry(base, config = {}) {
79
64
  interpret
80
65
  };
81
66
  }
82
- function telemetryMsgKeys(update, form) {
83
- const keys = Object.keys(update);
84
- const firstKey = keys[0];
85
- if (firstKey === void 0) return [];
86
- if (form === "reducer") {
87
- return keys;
88
- }
89
- const firstValue = update[firstKey];
90
- return Object.keys(firstValue);
91
- }
92
67
 
93
68
  export { withTelemetry };
94
69
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/with-telemetry/index.ts"],"names":[],"mappings":";;;;AAsKA,SAAS,aAAA,CAKP,MAAA,EAEA,IAAA,EACA,KAAA,EACA,GAAA,EAC4B;AAC5B,EAAA,IAAI,SAAS,SAAA,EAAW;AAEtB,IAAA,MAAM,MAAA,GAAS,MAAA;AAEf,IAAA,OAAO,MAAA,CAAO,GAAA,CAAI,IAAI,CAAA,CAAG,OAAO,GAAG,CAAA;AAAA,EACrC;AAEA,EAAA,MAAM,KAAA,GAAQ,MAAA;AAId,EAAA,MAAM,WAAY,KAAA,CAAsC,IAAA;AAExD,EAAA,OAAO,MAAM,QAAQ,CAAA,CAAG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CAAC,KAAA,KACd,iBAAA,CAAkB,MAAM,IAAI;AAAA,QAEhC,EAAC;AAAA,IACL,GAAI,aAAA,GAAgB,EAAE,SAAA,EAAW,aAAA,KAAkB,EAAC;AAAA,IACpD;AAAA,GACF;AAOF;AAQA,SAAS,gBAAA,CAAiB,QAAgB,IAAA,EAAqC;AAC7E,EAAA,MAAM,IAAA,GAAO,MAAA,CAAO,IAAA,CAAK,MAAM,CAAA;AAC/B,EAAA,MAAM,QAAA,GAAW,KAAK,CAAC,CAAA;AACvB,EAAA,IAAI,QAAA,KAAa,MAAA,EAAW,OAAO,EAAC;AACpC,EAAA,IAAI,SAAS,SAAA,EAAW;AAEtB,IAAA,OAAO,IAAA;AAAA,EACT;AAEA,EAAA,MAAM,UAAA,GAAc,OAAmC,QAAQ,CAAA;AAC/D,EAAA,OAAO,MAAA,CAAO,KAAK,UAAoB,CAAA;AACzC","file":"index.js","sourcesContent":["/**\n * @demlik/tea/with-telemetry — the pattern-setting wrapper of the wrapper tier.\n *\n * `withTelemetry(base, config)` is a **pure function over machine data**: it\n * takes any `Machine<S, M, C, U, Ctx>` and returns a NEW `Machine` over the\n * composed Model `{ base, $telemetry }`. You `run()` / `replay()` the result\n * exactly like any other machine — there is no new runtime, no privileged\n * interception path.\n *\n * This is the SAFEST wrapper and the one every future wrapper (`withDeadline`,\n * `withResilience`) copies: it is **OBSERVE-ONLY**. It observes every base Msg\n * + transition, increments a monotonic counter, and emits a fire-and-forget\n * telemetry Cmd whose interpret handler hands the event to a sink Port. It must\n * NOT transform base Cmds or gate base Msgs — base behavior is byte-identical\n * with or without it. The moment a telemetry wrapper alters the Msg/Cmd stream\n * instead of observing it, it has become saga middleware (the betrayal the\n * research warned of).\n *\n * ## The 5 rules it satisfies (from the wrapper-tier contract)\n *\n * 1. **Named, serializable slice.** Wrapper state lives at `model.$telemetry`,\n * a plain `{ seq: number }` — JSON-serializable, never a closure.\n * 2. **Retag-and-re-emit, never swallow.** The merged `update` runs the base\n * reducer, passes its Cmds through UNCHANGED, and APPENDS its own\n * `$telemetry:emit` Cmd. No base Cmd ever vanishes; nothing is gated.\n * 3. **Every decision is a Msg/Cmd.** Each telemetry emission is a\n * `$telemetry:emit` Cmd through the merged `update`, so \"why did this fire\"\n * is answerable from reducer + log alone, and `runtime.observe` sees it.\n * 4. **Subs merge by id.** Telemetry has no timers — merged subs/subscribe are\n * the base's, verbatim.\n * 5. **Clock out of update.** The default event carries no wall-clock read.\n * The optional `at` is stamped at the interpret boundary (the `clock`\n * port), never inside the merged `update`.\n *\n * ## Where the clock lives\n *\n * Inside the merged `update`: nowhere. The reducer is pure — it reads `seq` from\n * the slice and projects the event from `(msg, prev, next)`. The ONLY clock read\n * is at the interpret boundary: the `$telemetry:emit` handler stamps `event.at`\n * from the injected `clock` port (if supplied and the projector left `at`\n * unset), exactly as `resilient-call` reads `Date.now()` only inside `handlers`.\n *\n * ## Typical wiring\n *\n * const observed = withTelemetry(baseMachine, {\n * event: (msg, _prev, next) => ({ seq: next.$telemetry.seq, msgType: msg.type }),\n * });\n * const runtime = run(observed, {\n * ctx: { ...baseCtx, telemetrySink: (e) => posthog.capture(e), clock: Date.now },\n * });\n */\n\nimport type {\n Cmd,\n Interpret,\n Machine,\n Reducer,\n Sub,\n UpdateForm,\n} from \"../index\";\nimport { formOf } from \"../index\";\n\n// ===========================================================================\n// The event + the slice + the ports — the telemetry vocabulary.\n// ===========================================================================\n\n/**\n * The datum handed to the sink. The default projector emits `{ seq, msgType }`;\n * a custom `event` projector may return any extra fields. `at` is OPTIONAL and\n * plain data — it is stamped at the interpret boundary by the `clock` port, not\n * inside the (pure, clock-free) merged `update`. Every field is JSON-round-trip\n * serializable so a recorded telemetry stream stays durable.\n */\nexport interface TelemetryEvent {\n /** Monotonic event counter — equals `$telemetry.seq` after the transition. */\n readonly seq: number;\n /** The `Msg.type` discriminant that drove this transition. */\n readonly msgType: string;\n /**\n * Wall-clock instant the event was emitted, ms since epoch. Absent until the\n * interpret boundary stamps it (the `clock` port). Optional because the\n * merged `update` is clock-free — a verb must never read `Date.now()`.\n */\n readonly at?: number;\n}\n\n/**\n * The wrapper's Model slice. A monotonic event counter — minimal but real, so\n * the named-slice mechanism is exercised for the richer-slice wrappers that\n * follow. `seq` equals the number of base Msgs folded so far: after replaying\n * `N` msgs, `$telemetry.seq === N`. Plain data → serializes into a `Store<S>`.\n */\nexport interface TelemetrySlice {\n readonly seq: number;\n}\n\n/**\n * The composed Model. The base machine's state is nested under `base`; the\n * wrapper's state lives in the NAMED `$telemetry` slice — never hidden in a\n * closure. Both fields are plain data, so the whole composed Model round-trips\n * through `JSON.parse(JSON.stringify(...))` iff the base state does.\n */\nexport interface TelemetryModel<S> {\n readonly base: S;\n readonly $telemetry: TelemetrySlice;\n}\n\n/**\n * The fire-and-forget Cmd the merged `update` appends after every base\n * transition. It carries the projected `event` as plain data (invariant 3 —\n * no closure). The interpret handler hands `event` to the sink and dispatches\n * NOTHING back, so there is no feedback loop.\n */\nexport type TelemetryEmitCmd = Cmd<\"$telemetry:emit\"> & {\n readonly event: TelemetryEvent;\n};\n\n/**\n * The side-effecting ports the wrapper adds to `Ctx`. The sink (PostHog / Sentry\n * bridge) lives at the interpret boundary, never in a verb. `clock` is the\n * optional wall-clock source used to stamp `event.at` at that same boundary —\n * pass `Date.now` in production, a fixed `() => 1000` in tests; omit it to leave\n * `at` unset.\n */\nexport interface TelemetryPorts {\n /** The side-effecting sink. Fire-and-forget — its result is never awaited into a Msg. */\n readonly telemetrySink: (event: TelemetryEvent) => void | Promise<void>;\n /** Optional clock for stamping `event.at` at the interpret boundary. */\n readonly clock?: () => number;\n}\n\n/**\n * The telemetry knob. `event` is an OPTIONAL projector mapping\n * `(msg, prev, next)` to a `TelemetryEvent`; omit it and the default emits\n * `{ seq, msgType }` where `seq` is the post-transition counter. The projector\n * runs INSIDE the pure merged `update`, so it must not read the clock — stamp\n * `at` at the sink boundary via the `clock` port instead.\n */\nexport interface TelemetryConfig<S, M extends { type: string }> {\n readonly event?: (\n msg: M,\n prev: TelemetryModel<S>,\n next: TelemetryModel<S>,\n ) => TelemetryEvent;\n}\n\n// ===========================================================================\n// update-form dispatch — run the base reducer regardless of its shape.\n// ===========================================================================\n\n// The base `update` is either a Reducer (flat record keyed by Msg.type) or a\n// Transitions table (keyed by state.type then Msg.type). The merged machine is\n// always a Reducer over the NON-discriminated `TelemetryModel<S>`, so the merged\n// reducer must invoke the base's update through whichever shape it has. This\n// mirrors the form-branching `run` and `replay` do internally; we keep it inline\n// (not factored into a shared helper) so the wrapper stays standalone.\ntype BaseCellFn<S, M, C extends Cmd> = (\n state: S,\n msg: M,\n) => readonly [S, readonly C[]];\n\n/**\n * Invoke the base machine's `update` for `msg` against base `state`, returning\n * the base's `[nextBase, baseCmds]` UNCHANGED. Pure — it only routes to the\n * base cell; it never reads the clock, allocates an Error, or mutates state.\n */\nfunction runBaseUpdate<S, M extends { type: string }, C extends Cmd>(\n // Typed `object` (not `Machine[...][\"update\"]`) because the field is inspected\n // structurally and re-cast below; the precise union (Reducer | Transitions)\n // collapses under the substrate's conditional `update` type, so the wrapper\n // accepts the erased shape and dispatches on the runtime form.\n update: object,\n // The base's update form, read once via `formOf(base)` — no local heuristic.\n form: UpdateForm,\n state: S,\n msg: M,\n): readonly [S, readonly C[]] {\n if (form === \"reducer\") {\n // Reducer form: `update[msg.type](state, msg)`.\n const record = update as unknown as Record<string, BaseCellFn<S, M, C>>;\n // biome-ignore lint/style/noNonNullAssertion: the base machine's Reducer guarantees a cell for every dispatched Msg.type; `!` required under noUncheckedIndexedAccess and cannot miss for a Msg the base accepts\n return record[msg.type]!(state, msg);\n }\n // Transitions form: `update[state.type][msg.type](state, msg)`.\n const table = update as unknown as Record<\n string,\n Record<string, BaseCellFn<S, M, C>>\n >;\n const stateKey = (state as unknown as { type: string }).type;\n // biome-ignore lint/style/noNonNullAssertion: the base machine's Transitions table guarantees every (state.type × msg.type) cell exists; `!` required under noUncheckedIndexedAccess and cannot miss at runtime\n return table[stateKey]![msg.type]!(state, msg);\n}\n\n// ===========================================================================\n// withTelemetry — the wrapper.\n// ===========================================================================\n\n/**\n * Wrap `base` with observe-only telemetry. Returns a NEW `Machine` over the\n * composed Model `{ base, $telemetry }`, with the base's Msgs/Cmds/Subs/Ctx\n * extended by the wrapper's own.\n *\n * The composed machine:\n * - `init` rehydrates the base (honoring the `[loaded, []]` contract) and\n * seeds `$telemetry: { seq: 0 }`. Base init Cmds pass through unchanged.\n * - `update` (Reducer form, keyed by every base `Msg.type`) runs the base\n * reducer, increments `seq`, and appends a `$telemetry:emit` Cmd carrying\n * the projected event. Base Cmds pass through UNCHANGED — the observe-only\n * property.\n * - `subscriptions` / `subscribe` are the base's, verbatim (no timers).\n * - `interpret` is `{ ...base.interpret, \"$telemetry:emit\": sink-handler }`.\n *\n * @param base any `Machine<S, M, C, U, Ctx>`.\n * @param config the telemetry knob (optional `event` projector).\n */\nexport function withTelemetry<\n S,\n M extends { type: string },\n C extends Cmd,\n U extends Sub,\n Ctx,\n>(\n base: Machine<S, M, C, U, Ctx>,\n config: TelemetryConfig<S, M> = {},\n): Machine<\n TelemetryModel<S>,\n M,\n C | TelemetryEmitCmd,\n U,\n Ctx & TelemetryPorts\n> {\n const project = config.event;\n\n // The merged update is a flat Reducer over the composed Model. The composed\n // Model is NOT discriminated on `.type`, so the Transitions form is never an\n // option here — every base Msg variant gets exactly one cell. We build the\n // record by enumerating the base update's Msg keys: a Reducer's keys ARE the\n // Msg.type set; a Transitions table's inner keys are too (uniform across\n // phases), so we read the first phase's keys to recover them.\n // The base's update form, read ONCE from the `__form` tag (see `formOf`) and\n // threaded into the per-form helpers — no structural re-derivation here.\n const baseForm = formOf(base);\n const msgKeys = telemetryMsgKeys(base.update, baseForm);\n\n const update = {} as Record<\n string,\n (\n state: TelemetryModel<S>,\n msg: M,\n ) => readonly [TelemetryModel<S>, readonly (C | TelemetryEmitCmd)[]]\n >;\n for (const key of msgKeys) {\n update[key] = (state, msg) => {\n // 1) Run the base reducer — its result passes through UNCHANGED.\n const [nextBase, baseCmds] = runBaseUpdate<S, M, C>(\n base.update,\n baseForm,\n state.base,\n msg,\n );\n // 2) Advance the wrapper slice (monotonic counter). New object — no mutation.\n const $telemetry: TelemetrySlice = { seq: state.$telemetry.seq + 1 };\n const next: TelemetryModel<S> = { base: nextBase, $telemetry };\n // 3) Project the event (pure — no clock). Default: { seq, msgType }.\n const event: TelemetryEvent = project\n ? project(msg, state, next)\n : { seq: $telemetry.seq, msgType: msg.type };\n // 4) Append the fire-and-forget emit Cmd. Base Cmds come FIRST, unchanged.\n const emit: TelemetryEmitCmd = { type: \"$telemetry:emit\", event };\n return [next, [...baseCmds, emit]];\n };\n }\n\n // The base's interpret, extended with the one telemetry handler. The sink is\n // the ONLY side effect, and it lives here at the interpret boundary — never in\n // a verb. `clock` (if provided) stamps `event.at` here too, the one permitted\n // clock read. The handler returns void synchronously — it dispatches NOTHING\n // back (no feedback loop) AND it does NOT await the sink (no backpressure /\n // crash from a slow or failing sink). See the fire-and-forget note below.\n const baseInterpret =\n (base as { interpret?: Interpret<M, C, Ctx> }).interpret ??\n ({} as Interpret<M, C, Ctx>);\n // Namespace guard (mirrors the substrate's SubId / definePort collision\n // asserts). The spread below merges `$telemetry:emit` into the base's\n // interpret map; if the base already declares that key, the spread would\n // SILENTLY clobber the base handler. The `$telemetry:` Cmd namespace is the\n // wrapper's — refuse to wrap a base that squats on it instead of stealing it.\n if (Object.hasOwn(baseInterpret as object, \"$telemetry:emit\")) {\n throw new Error(\n 'withTelemetry: the base machine declares a reserved \"$telemetry:emit\" ' +\n 'interpret handler — the wrapper owns the \"$telemetry:\" Cmd namespace. ' +\n \"Rename the base handler.\",\n );\n }\n const interpret = {\n ...(baseInterpret as Record<string, unknown>),\n // OBSERVE-ONLY at the boundary: the sink is fire-and-forget. The runtime\n // `await`s every interpret handler in its dispatch loop, so awaiting the\n // sink here would let a SLOW sink backpressure the wrapped machine (its\n // next dispatch waits) and a FAILING sink crash dispatch (the throw would\n // propagate out of the transition). Both violate the contract: telemetry\n // must never affect base behavior OR latency. So we DO NOT await — we hand\n // the event to the sink, normalize its result to a Promise, swallow any\n // rejection/throw, and return immediately. The handler resolves in the same\n // microtask the dispatch loop reaches it; the machine never waits on the\n // sink, and a rejected sink can never become an unhandled rejection.\n \"$telemetry:emit\": (\n cmd: TelemetryEmitCmd,\n ctx: Ctx & TelemetryPorts,\n ): void => {\n const event =\n cmd.event.at === undefined && ctx.clock !== undefined\n ? { ...cmd.event, at: ctx.clock() }\n : cmd.event;\n // `Promise.resolve(fn())` covers BOTH failure shapes: a sync `throw` is\n // caught by `Promise.resolve` (the call is the argument, so a throw here\n // would escape — guard it), and an async rejection is caught by `.catch`.\n try {\n Promise.resolve(ctx.telemetrySink(event)).catch(() => {});\n } catch {\n // A sink that throws SYNCHRONOUSLY (before returning a Promise) is\n // swallowed here. Either way the slow/failing sink never reaches the\n // dispatch loop's `await`.\n }\n },\n } as Interpret<M, C | TelemetryEmitCmd, Ctx & TelemetryPorts>;\n\n // Capture once so the narrowing survives into the spread (no non-null assert).\n const baseSubscriptions = base.subscriptions;\n const baseSubscribe = (base as { subscribe?: unknown }).subscribe;\n\n return {\n init: (loaded, ctx) => {\n // Rehydrate path: `loaded !== null` MUST return `[loaded, []]` (no Cmds) —\n // the substrate's replay enforces this. We split the composed loaded Model\n // into its base slice and feed the base its own loaded snapshot, so the\n // base's rehydrate contract is honored transitively.\n if (loaded !== null) {\n return [loaded, []];\n }\n const [base0, cmds] = base.init(null, ctx);\n const model: TelemetryModel<S> = { base: base0, $telemetry: { seq: 0 } };\n // Base init Cmds pass through unchanged; no telemetry Cmd on boot (boot is\n // not a base Msg transition, so it does not advance `seq`).\n return [model, cmds];\n },\n update: update as unknown as Reducer<\n TelemetryModel<S>,\n M,\n C | TelemetryEmitCmd\n >,\n // Subs merge to the base's, verbatim — telemetry owns no timers. The base\n // subscribes against its own nested slice.\n ...(baseSubscriptions\n ? {\n subscriptions: (state: TelemetryModel<S>) =>\n baseSubscriptions(state.base),\n }\n : {}),\n ...(baseSubscribe ? { subscribe: baseSubscribe } : {}),\n interpret,\n } as Machine<\n TelemetryModel<S>,\n M,\n C | TelemetryEmitCmd,\n U,\n Ctx & TelemetryPorts\n >;\n}\n\n// Recover the base Msg.type set from either update form. A Reducer's own keys\n// ARE the Msg.type set. A Transitions table's keys are state.type; its INNER\n// keys are the Msg.type set (uniform across phases by the mapped-type\n// contract), so we read the first phase's inner keys. An empty update (`M` is\n// `never`) yields `[]` — the merged reducer then has no cells, which is correct\n// because no Msg can ever be dispatched.\nfunction telemetryMsgKeys(update: object, form: UpdateForm): readonly string[] {\n const keys = Object.keys(update);\n const firstKey = keys[0];\n if (firstKey === undefined) return [];\n if (form === \"reducer\") {\n // Reducer form — keys are Msg.type.\n return keys;\n }\n // Transitions form — keys are state.type; inner keys are Msg.type.\n const firstValue = (update as Record<string, unknown>)[firstKey];\n return Object.keys(firstValue as object);\n}\n"]}
1
+ {"version":3,"sources":["../../src/with-telemetry/index.ts"],"names":[],"mappings":";;;;AAiKO,SAAS,aAAA,CAOd,IAAA,EACA,MAAA,GAAgC,EAAC,EAOjC;AACA,EAAA,MAAM,UAAU,MAAA,CAAO,KAAA;AAMvB,EAAA,MAAM,OAAA,GAAU,UAAU,IAAI,CAAA;AAE9B,EAAA,MAAM,SAAS,EAAC;AAOhB,EAAA,KAAA,MAAW,OAAO,OAAA,EAAS;AACzB,IAAA,MAAA,CAAO,GAAG,CAAA,GAAI,CAAC,KAAA,EAAO,GAAA,KAAQ;AAE5B,MAAA,MAAM,CAAC,UAAU,QAAQ,CAAA,GAAI,UAAmB,IAAA,EAAM,KAAA,CAAM,MAAM,GAAG,CAAA;AAErE,MAAA,MAAM,aAA6B,EAAE,GAAA,EAAK,KAAA,CAAM,UAAA,CAAW,MAAM,CAAA,EAAE;AACnE,MAAA,MAAM,IAAA,GAA0B,EAAE,IAAA,EAAM,QAAA,EAAU,UAAA,EAAW;AAE7D,MAAA,MAAM,KAAA,GAAw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AQ,GAAA,KAAQ;AAKrB,MAAA,IAAI,WAAW,IAAA,EAAM;AACnB,QAAA,OAAO,CAAC,MAAA,EAAQ,EAAE,CAAA;AAAA,MACpB;AACA,MAAA,MAAM,CAAC,KAAA,EAAO,IAAI,IAAI,IAAA,CAAK,IAAA,CAAK,MAAM,GAAG,CAAA;AACzC,MAAA,MAAM,KAAA,GAA2B,EAAE,IAAA,EAAM,KAAA,EAAO,YAAY,EAAE,GAAA,EAAK,GAAE,EAAE;AAGvE,MAAA,OAAO,CAAC,OAAO,IAAI,CAAA;AAAA,IACrB,CAAA;AAAA,IACA,MAAA;AAAA;AAAA;AAAA,IAOA,GAAI,iBAAA,GACA;AAAA,MACE,aAAA,EAAe,CAAC,KAAA,KACd,iBAAA,CAAkB,MAAM,IAAI;AAAA,QAEhC,EAAC;AAAA,IACL,GAAI,aAAA,GAAgB,EAAE,SAAA,EAAW,aAAA,KAAkB,EAAC;AAAA,IACpD;AAAA,GACF;AAOF","file":"index.js","sourcesContent":["/**\n * @demlik/tea/with-telemetry — the pattern-setting wrapper of the wrapper tier.\n *\n * `withTelemetry(base, config)` is a **pure function over machine data**: it\n * takes any `Machine<S, M, C, U, Ctx>` and returns a NEW `Machine` over the\n * composed Model `{ base, $telemetry }`. You `run()` / `replay()` the result\n * exactly like any other machine — there is no new runtime, no privileged\n * interception path.\n *\n * This is the SAFEST wrapper and the one every future wrapper (`withDeadline`,\n * `withResilience`) copies: it is **OBSERVE-ONLY**. It observes every base Msg\n * + transition, increments a monotonic counter, and emits a fire-and-forget\n * telemetry Cmd whose interpret handler hands the event to a sink Port. It must\n * NOT transform base Cmds or gate base Msgs — base behavior is byte-identical\n * with or without it. The moment a telemetry wrapper alters the Msg/Cmd stream\n * instead of observing it, it has become saga middleware (the betrayal the\n * research warned of).\n *\n * ## The 5 rules it satisfies (from the wrapper-tier contract)\n *\n * 1. **Named, serializable slice.** Wrapper state lives at `model.$telemetry`,\n * a plain `{ seq: number }` — JSON-serializable, never a closure.\n * 2. **Retag-and-re-emit, never swallow.** The merged `update` runs the base\n * reducer, passes its Cmds through UNCHANGED, and APPENDS its own\n * `$telemetry:emit` Cmd. No base Cmd ever vanishes; nothing is gated.\n * 3. **Every decision is a Msg/Cmd.** Each telemetry emission is a\n * `$telemetry:emit` Cmd through the merged `update`, so \"why did this fire\"\n * is answerable from reducer + log alone, and `runtime.observe` sees it.\n * 4. **Subs merge by id.** Telemetry has no timers — merged subs/subscribe are\n * the base's, verbatim.\n * 5. **Clock out of update.** The default event carries no wall-clock read.\n * The optional `at` is stamped at the interpret boundary (the `clock`\n * port), never inside the merged `update`.\n *\n * ## Where the clock lives\n *\n * Inside the merged `update`: nowhere. The reducer is pure — it reads `seq` from\n * the slice and projects the event from `(msg, prev, next)`. The ONLY clock read\n * is at the interpret boundary: the `$telemetry:emit` handler stamps `event.at`\n * from the injected `clock` port (if supplied and the projector left `at`\n * unset), exactly as `resilient-call` reads `Date.now()` only inside `handlers`.\n *\n * ## Typical wiring\n *\n * const observed = withTelemetry(baseMachine, {\n * event: (msg, _prev, next) => ({ seq: next.$telemetry.seq, msgType: msg.type }),\n * });\n * const runtime = run(observed, {\n * ctx: { ...baseCtx, telemetrySink: (e) => posthog.capture(e), clock: Date.now },\n * });\n */\n\nimport type { Cmd, Interpret, Machine, Reducer, Sub } from \"../index\";\nimport { applyCell, msgKeysOf } from \"../index\";\n\n// ===========================================================================\n// The event + the slice + the ports — the telemetry vocabulary.\n// ===========================================================================\n\n/**\n * The datum handed to the sink. The default projector emits `{ seq, msgType }`;\n * a custom `event` projector may return any extra fields. `at` is OPTIONAL and\n * plain data — it is stamped at the interpret boundary by the `clock` port, not\n * inside the (pure, clock-free) merged `update`. Every field is JSON-round-trip\n * serializable so a recorded telemetry stream stays durable.\n */\nexport interface TelemetryEvent {\n /** Monotonic event counter — equals `$telemetry.seq` after the transition. */\n readonly seq: number;\n /** The `Msg.type` discriminant that drove this transition. */\n readonly msgType: string;\n /**\n * Wall-clock instant the event was emitted, ms since epoch. Absent until the\n * interpret boundary stamps it (the `clock` port). Optional because the\n * merged `update` is clock-free — a verb must never read `Date.now()`.\n */\n readonly at?: number;\n}\n\n/**\n * The wrapper's Model slice. A monotonic event counter — minimal but real, so\n * the named-slice mechanism is exercised for the richer-slice wrappers that\n * follow. `seq` equals the number of base Msgs folded so far: after replaying\n * `N` msgs, `$telemetry.seq === N`. Plain data → serializes into a `Store<S>`.\n */\nexport interface TelemetrySlice {\n readonly seq: number;\n}\n\n/**\n * The composed Model. The base machine's state is nested under `base`; the\n * wrapper's state lives in the NAMED `$telemetry` slice — never hidden in a\n * closure. Both fields are plain data, so the whole composed Model round-trips\n * through `JSON.parse(JSON.stringify(...))` iff the base state does.\n */\nexport interface TelemetryModel<S> {\n readonly base: S;\n readonly $telemetry: TelemetrySlice;\n}\n\n/**\n * The fire-and-forget Cmd the merged `update` appends after every base\n * transition. It carries the projected `event` as plain data (invariant 3 —\n * no closure). The interpret handler hands `event` to the sink and dispatches\n * NOTHING back, so there is no feedback loop.\n */\nexport type TelemetryEmitCmd = Cmd<\"$telemetry:emit\"> & {\n readonly event: TelemetryEvent;\n};\n\n/**\n * The side-effecting ports the wrapper adds to `Ctx`. The sink (PostHog / Sentry\n * bridge) lives at the interpret boundary, never in a verb. `clock` is the\n * optional wall-clock source used to stamp `event.at` at that same boundary —\n * pass `Date.now` in production, a fixed `() => 1000` in tests; omit it to leave\n * `at` unset.\n */\nexport interface TelemetryPorts {\n /** The side-effecting sink. Fire-and-forget — its result is never awaited into a Msg. */\n readonly telemetrySink: (event: TelemetryEvent) => void | Promise<void>;\n /** Optional clock for stamping `event.at` at the interpret boundary. */\n readonly clock?: () => number;\n}\n\n/**\n * The telemetry knob. `event` is an OPTIONAL projector mapping\n * `(msg, prev, next)` to a `TelemetryEvent`; omit it and the default emits\n * `{ seq, msgType }` where `seq` is the post-transition counter. The projector\n * runs INSIDE the pure merged `update`, so it must not read the clock — stamp\n * `at` at the sink boundary via the `clock` port instead.\n */\nexport interface TelemetryConfig<S, M extends { type: string }> {\n readonly event?: (\n msg: M,\n prev: TelemetryModel<S>,\n next: TelemetryModel<S>,\n ) => TelemetryEvent;\n}\n\n// ===========================================================================\n// withTelemetry — the wrapper.\n// ===========================================================================\n\n/**\n * Wrap `base` with observe-only telemetry. Returns a NEW `Machine` over the\n * composed Model `{ base, $telemetry }`, with the base's Msgs/Cmds/Subs/Ctx\n * extended by the wrapper's own.\n *\n * The composed machine:\n * - `init` rehydrates the base (honoring the `[loaded, []]` contract) and\n * seeds `$telemetry: { seq: 0 }`. Base init Cmds pass through unchanged.\n * - `update` (Reducer form, keyed by every base `Msg.type`) runs the base\n * reducer, increments `seq`, and appends a `$telemetry:emit` Cmd carrying\n * the projected event. Base Cmds pass through UNCHANGED — the observe-only\n * property.\n * - `subscriptions` / `subscribe` are the base's, verbatim (no timers).\n * - `interpret` is `{ ...base.interpret, \"$telemetry:emit\": sink-handler }`.\n *\n * @param base any `Machine<S, M, C, U, Ctx>`.\n * @param config the telemetry knob (optional `event` projector).\n */\nexport function withTelemetry<\n S,\n M extends { type: string },\n C extends Cmd,\n U extends Sub,\n Ctx,\n>(\n base: Machine<S, M, C, U, Ctx>,\n config: TelemetryConfig<S, M> = {},\n): Machine<\n TelemetryModel<S>,\n M,\n C | TelemetryEmitCmd,\n U,\n Ctx & TelemetryPorts\n> {\n const project = config.event;\n\n // The merged update is a flat Reducer over the composed Model. The composed\n // Model is NOT discriminated on `.type`, so the Transitions form is never an\n // option here — every base Msg variant gets exactly one cell, enumerated via\n // `msgKeysOf(base)` (keyed on the authoritative `__form` tag; #275).\n const msgKeys = msgKeysOf(base);\n\n const update = {} as Record<\n string,\n (\n state: TelemetryModel<S>,\n msg: M,\n ) => readonly [TelemetryModel<S>, readonly (C | TelemetryEmitCmd)[]]\n >;\n for (const key of msgKeys) {\n update[key] = (state, msg) => {\n // 1) Run the base reducer — its result passes through UNCHANGED.\n const [nextBase, baseCmds] = applyCell<S, M, C>(base, state.base, msg);\n // 2) Advance the wrapper slice (monotonic counter). New object — no mutation.\n const $telemetry: TelemetrySlice = { seq: state.$telemetry.seq + 1 };\n const next: TelemetryModel<S> = { base: nextBase, $telemetry };\n // 3) Project the event (pure — no clock). Default: { seq, msgType }.\n const event: TelemetryEvent = project\n ? project(msg, state, next)\n : { seq: $telemetry.seq, msgType: msg.type };\n // 4) Append the fire-and-forget emit Cmd. Base Cmds come FIRST, unchanged.\n const emit: TelemetryEmitCmd = { type: \"$telemetry:emit\", event };\n return [next, [...baseCmds, emit]];\n };\n }\n\n // The base's interpret, extended with the one telemetry handler. The sink is\n // the ONLY side effect, and it lives here at the interpret boundary — never in\n // a verb. `clock` (if provided) stamps `event.at` here too, the one permitted\n // clock read. The handler returns void synchronously — it dispatches NOTHING\n // back (no feedback loop) AND it does NOT await the sink (no backpressure /\n // crash from a slow or failing sink). See the fire-and-forget note below.\n const baseInterpret =\n (base as { interpret?: Interpret<M, C, Ctx> }).interpret ??\n ({} as Interpret<M, C, Ctx>);\n // Namespace guard (mirrors the substrate's SubId / definePort collision\n // asserts). The spread below merges `$telemetry:emit` into the base's\n // interpret map; if the base already declares that key, the spread would\n // SILENTLY clobber the base handler. The `$telemetry:` Cmd namespace is the\n // wrapper's — refuse to wrap a base that squats on it instead of stealing it.\n if (Object.hasOwn(baseInterpret as object, \"$telemetry:emit\")) {\n throw new Error(\n 'withTelemetry: the base machine declares a reserved \"$telemetry:emit\" ' +\n 'interpret handler — the wrapper owns the \"$telemetry:\" Cmd namespace. ' +\n \"Rename the base handler.\",\n );\n }\n const interpret = {\n ...(baseInterpret as Record<string, unknown>),\n // OBSERVE-ONLY at the boundary: the sink is fire-and-forget. The runtime\n // `await`s every interpret handler in its dispatch loop, so awaiting the\n // sink here would let a SLOW sink backpressure the wrapped machine (its\n // next dispatch waits) and a FAILING sink crash dispatch (the throw would\n // propagate out of the transition). Both violate the contract: telemetry\n // must never affect base behavior OR latency. So we DO NOT await — we hand\n // the event to the sink, normalize its result to a Promise, swallow any\n // rejection/throw, and return immediately. The handler resolves in the same\n // microtask the dispatch loop reaches it; the machine never waits on the\n // sink, and a rejected sink can never become an unhandled rejection.\n \"$telemetry:emit\": (\n cmd: TelemetryEmitCmd,\n ctx: Ctx & TelemetryPorts,\n ): void => {\n const event =\n cmd.event.at === undefined && ctx.clock !== undefined\n ? { ...cmd.event, at: ctx.clock() }\n : cmd.event;\n // `Promise.resolve(fn())` covers BOTH failure shapes: a sync `throw` is\n // caught by `Promise.resolve` (the call is the argument, so a throw here\n // would escape — guard it), and an async rejection is caught by `.catch`.\n try {\n Promise.resolve(ctx.telemetrySink(event)).catch(() => {});\n } catch {\n // A sink that throws SYNCHRONOUSLY (before returning a Promise) is\n // swallowed here. Either way the slow/failing sink never reaches the\n // dispatch loop's `await`.\n }\n },\n } as Interpret<M, C | TelemetryEmitCmd, Ctx & TelemetryPorts>;\n\n // Capture once so the narrowing survives into the spread (no non-null assert).\n const baseSubscriptions = base.subscriptions;\n const baseSubscribe = (base as { subscribe?: unknown }).subscribe;\n\n return {\n init: (loaded, ctx) => {\n // Rehydrate path: `loaded !== null` MUST return `[loaded, []]` (no Cmds) —\n // the substrate's replay enforces this. We split the composed loaded Model\n // into its base slice and feed the base its own loaded snapshot, so the\n // base's rehydrate contract is honored transitively.\n if (loaded !== null) {\n return [loaded, []];\n }\n const [base0, cmds] = base.init(null, ctx);\n const model: TelemetryModel<S> = { base: base0, $telemetry: { seq: 0 } };\n // Base init Cmds pass through unchanged; no telemetry Cmd on boot (boot is\n // not a base Msg transition, so it does not advance `seq`).\n return [model, cmds];\n },\n update: update as unknown as Reducer<\n TelemetryModel<S>,\n M,\n C | TelemetryEmitCmd\n >,\n // Subs merge to the base's, verbatim — telemetry owns no timers. The base\n // subscribes against its own nested slice.\n ...(baseSubscriptions\n ? {\n subscriptions: (state: TelemetryModel<S>) =>\n baseSubscriptions(state.base),\n }\n : {}),\n ...(baseSubscribe ? { subscribe: baseSubscribe } : {}),\n interpret,\n } as Machine<\n TelemetryModel<S>,\n M,\n C | TelemetryEmitCmd,\n U,\n Ctx & TelemetryPorts\n >;\n}\n"]}