@demlik/tea 0.14.0 → 0.16.0

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 (116) hide show
  1. package/README.md +30 -7
  2. package/dist/agent/index.d.ts +49 -36
  3. package/dist/agent/index.js +12 -8
  4. package/dist/chunk-4LPY67E4.js +18 -0
  5. package/dist/chunk-4LPY67E4.js.map +1 -0
  6. package/dist/chunk-5XU6ZJO2.js +533 -0
  7. package/dist/chunk-5XU6ZJO2.js.map +1 -0
  8. package/dist/{chunk-AQ6ZIMEA.js → chunk-6NG4V5SB.js} +89 -115
  9. package/dist/chunk-6NG4V5SB.js.map +1 -0
  10. package/dist/{chunk-HYDWG35Q.js → chunk-7MGXQZPW.js} +11 -9
  11. package/dist/chunk-7MGXQZPW.js.map +1 -0
  12. package/dist/{chunk-BLJ2JQSH.js → chunk-BCTEOVOU.js} +3 -3
  13. package/dist/{chunk-BLJ2JQSH.js.map → chunk-BCTEOVOU.js.map} +1 -1
  14. package/dist/chunk-CH5KTOEZ.js +710 -0
  15. package/dist/chunk-CH5KTOEZ.js.map +1 -0
  16. package/dist/chunk-CIHSHLQX.js +64 -0
  17. package/dist/chunk-CIHSHLQX.js.map +1 -0
  18. package/dist/{chunk-Z2L3LSNV.js → chunk-EHUDXAKC.js} +246 -210
  19. package/dist/chunk-EHUDXAKC.js.map +1 -0
  20. package/dist/chunk-GOX2CYIM.js +380 -0
  21. package/dist/chunk-GOX2CYIM.js.map +1 -0
  22. package/dist/chunk-IVJP3GKJ.js +104 -0
  23. package/dist/chunk-IVJP3GKJ.js.map +1 -0
  24. package/dist/{chunk-F7FMAWLA.js → chunk-MVZS5FDM.js} +13 -6
  25. package/dist/chunk-MVZS5FDM.js.map +1 -0
  26. package/dist/{chunk-LYLTKJWM.js → chunk-MYNLY3HP.js} +9 -8
  27. package/dist/chunk-MYNLY3HP.js.map +1 -0
  28. package/dist/{chunk-I5MQMJDW.js → chunk-NSIAORRY.js} +20 -30
  29. package/dist/chunk-NSIAORRY.js.map +1 -0
  30. package/dist/{chunk-MYXFNWAJ.js → chunk-QNGYQMZB.js} +4 -4
  31. package/dist/chunk-QNGYQMZB.js.map +1 -0
  32. package/dist/chunk-WT5PBPLB.js +98 -0
  33. package/dist/chunk-WT5PBPLB.js.map +1 -0
  34. package/dist/{core-CTzMJ82M.d.ts → core-BbgtiXdg.d.ts} +231 -139
  35. package/dist/do/index.d.ts +37 -32
  36. package/dist/do/index.js +21 -14
  37. package/dist/do/index.js.map +1 -1
  38. package/dist/{durable-effects-B0-qGQDy.d.ts → durable-effects-7MTK_jnj.d.ts} +1 -1
  39. package/dist/effect/index.d.ts +151 -0
  40. package/dist/effect/index.js +98 -0
  41. package/dist/effect/index.js.map +1 -0
  42. package/dist/extension/index.d.ts +6 -7
  43. package/dist/extension/index.js +3 -2
  44. package/dist/extension/index.js.map +1 -1
  45. package/dist/flow/index.d.ts +68 -70
  46. package/dist/flow/index.js +32 -27
  47. package/dist/flow/index.js.map +1 -1
  48. package/dist/idempotency/index.d.ts +6 -7
  49. package/dist/idempotency/index.js +4 -2
  50. package/dist/{index-DJWIER_3.d.ts → index-7vV8xmsD.d.ts} +1 -1
  51. package/dist/{index-NjrT3fL2.d.ts → index-Bz5Rh9Ga.d.ts} +19 -96
  52. package/dist/index-CjFDUBeq.d.ts +207 -0
  53. package/dist/{index-6A7dB8f6.d.ts → index-CkFYA9Y6.d.ts} +14 -16
  54. package/dist/{index-B5BZ-_cT.d.ts → index-Cou86-GX.d.ts} +189 -108
  55. package/dist/{index-TvRb1KVf.d.ts → index-DU6JpQ8G.d.ts} +1 -1
  56. package/dist/{index-q0hXFeZ0.d.ts → index-Xufl55W8.d.ts} +286 -215
  57. package/dist/{index-4vZzljCD.d.ts → index-_dOR3xqA.d.ts} +57 -45
  58. package/dist/index.d.ts +181 -385
  59. package/dist/index.js +2 -1
  60. package/dist/jev/index.d.ts +147 -99
  61. package/dist/jev/index.js +329 -233
  62. package/dist/jev/index.js.map +1 -1
  63. package/dist/{machine-CdIcN2Xm.d.ts → machine-BQzTV8On.d.ts} +171 -280
  64. package/dist/machine-viz/index.d.ts +5 -5
  65. package/dist/machine-viz/index.js +8 -4
  66. package/dist/machine-viz/index.js.map +1 -1
  67. package/dist/mem/index.d.ts +3 -4
  68. package/dist/mem/index.js +2 -1
  69. package/dist/mem/index.js.map +1 -1
  70. package/dist/node/index.d.ts +119 -78
  71. package/dist/node/index.js +52 -38
  72. package/dist/node/index.js.map +1 -1
  73. package/dist/paginate/index.d.ts +27 -33
  74. package/dist/paginate/index.js +6 -4
  75. package/dist/parity/index.d.ts +4 -5
  76. package/dist/parity/index.js +3 -2
  77. package/dist/parity/index.js.map +1 -1
  78. package/dist/pbt/index.d.ts +2 -2
  79. package/dist/pbt/index.js +2 -1
  80. package/dist/pbt/index.js.map +1 -1
  81. package/dist/persistence/index.d.ts +6 -7
  82. package/dist/persistence/index.js +5 -3
  83. package/dist/promise/index.d.ts +186 -0
  84. package/dist/promise/index.js +5 -0
  85. package/dist/promise/index.js.map +1 -0
  86. package/dist/protocol-ClRZBhHQ.d.ts +53 -0
  87. package/dist/react/index.d.ts +36 -17
  88. package/dist/react/index.js +27 -4
  89. package/dist/react/index.js.map +1 -1
  90. package/dist/resilience/index.d.ts +63 -455
  91. package/dist/resilience/index.js +37 -483
  92. package/dist/resilience/index.js.map +1 -1
  93. package/dist/{runtime-types-LWDoi943.d.ts → runtime-types-CiVpC0HN.d.ts} +131 -388
  94. package/dist/testing/index.d.ts +165 -15
  95. package/dist/testing/index.js +104 -3
  96. package/dist/testing/index.js.map +1 -1
  97. package/dist/timing/index.d.ts +25 -22
  98. package/dist/timing/index.js +4 -3
  99. package/dist/timing/index.js.map +1 -1
  100. package/dist/{types-DP3f5NIl.d.ts → types-LxZxGYda.d.ts} +2 -2
  101. package/dist/work-queue/index.d.ts +5 -6
  102. package/package.json +18 -5
  103. package/dist/chunk-AQ6ZIMEA.js.map +0 -1
  104. package/dist/chunk-F2US5BW6.js +0 -72
  105. package/dist/chunk-F2US5BW6.js.map +0 -1
  106. package/dist/chunk-F7FMAWLA.js.map +0 -1
  107. package/dist/chunk-HUKZQX6U.js +0 -97
  108. package/dist/chunk-HUKZQX6U.js.map +0 -1
  109. package/dist/chunk-HYDWG35Q.js.map +0 -1
  110. package/dist/chunk-I5MQMJDW.js.map +0 -1
  111. package/dist/chunk-LYLTKJWM.js.map +0 -1
  112. package/dist/chunk-MYXFNWAJ.js.map +0 -1
  113. package/dist/chunk-RQULHGYH.js +0 -1804
  114. package/dist/chunk-RQULHGYH.js.map +0 -1
  115. package/dist/chunk-Z2L3LSNV.js.map +0 -1
  116. package/dist/index-DMCeMPMJ.d.ts +0 -272
@@ -1,5 +1,5 @@
1
- import { C as Cmd, S as Sub, M as Machine } from '../core-CTzMJ82M.js';
2
- import 'zod';
1
+ import { C as Cmd, S as Sub, M as Machine } from '../core-BbgtiXdg.js';
2
+ import '@standard-schema/spec';
3
3
 
4
4
  /**
5
5
  * Sanitize a discriminant string into a Mermaid-safe node identifier.
@@ -38,10 +38,10 @@ declare function safeLabel(raw: string): string;
38
38
  *
39
39
  * What we MUST NOT do (these are the effectful paths, off-limits here):
40
40
  * - call `interpret[*]` handlers (perform I/O)
41
- * - call `subscribe[*]` handlers (install listeners)
41
+ * - call `subscribe[*]` runners (install listeners)
42
42
  * - call `run` / the runtime
43
- * We MAY call `init`, `update[*]` cells, and `subscriptions(state)` — all pure
44
- * by the invariants (same set `replay` is allowed to touch).
43
+ * We MAY call `init`, `update[*]` cells, and each `subs` entry's `deps(state)`
44
+ * — all pure by the invariants (same set `replay` is allowed to touch).
45
45
  */
46
46
 
47
47
  /**
@@ -1,4 +1,5 @@
1
- import { formOf } from '../chunk-RQULHGYH.js';
1
+ import '../chunk-GOX2CYIM.js';
2
+ import { formOf, subEntriesOf, desiredSub } from '../chunk-CH5KTOEZ.js';
2
3
 
3
4
  // src/machine-viz/mermaid-id.ts
4
5
  function safeId(raw) {
@@ -116,14 +117,17 @@ function resolveEdge(row, stateType, msgType, ctx) {
116
117
  }
117
118
  }
118
119
  function emitSubscriptions(machine, lines, stateSamples) {
119
- if (machine.subscriptions === void 0) return;
120
+ const entries = subEntriesOf(machine);
121
+ if (entries.length === 0) return;
120
122
  const stateTypes = Object.keys(stateSamples);
121
123
  if (stateTypes.length === 0) return;
122
124
  for (const st of stateTypes) {
123
125
  const sample = stateSamples[st];
124
126
  if (sample === void 0) continue;
125
- const subs = machine.subscriptions(sample);
126
- const subTypes = subs.map((s) => s.type);
127
+ const subTypes = entries.flatMap((entry) => {
128
+ const sub = desiredSub(entry, sample);
129
+ return sub === null ? [] : [sub.type];
130
+ });
127
131
  const body = subTypes.length === 0 ? "(no active subs)" : `subs: ${subTypes.map(safeLabel).join(", ")}`;
128
132
  lines.push(` note left of ${safeId(st)}`);
129
133
  lines.push(` ${body}`);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/machine-viz/mermaid-id.ts","../../src/machine-viz/index.ts"],"names":[],"mappings":";;;AAqBO,SAAS,OAAO,GAAA,EAAqB;AAC1C,EAAA,MAAM,OAAA,GAAU,GAAA,CAAI,OAAA,CAAQ,gBAAA,EAAkB,GAAG,CAAA;AACjD,EAAA,IAAI,OAAA,KAAY,IAAI,OAAO,QAAA;AAC3B,EAAA,OAAO,SAAS,IAAA,CAAK,OAAO,CAAA,GAAI,CAAA,EAAA,EAAK,OAAO,CAAA,CAAA,GAAK,OAAA;AACnD;AAQO,SAAS,UAAU,GAAA,EAAqB;AAC7C,EAAA,OAAO,GAAA,CAAI,OAAA,CAAQ,YAAA,EAAc,GAAG,EAAE,IAAA,EAAK;AAC7C;;;ACyDO,SAAS,SAAA,CAOd,OAAA,EAKA,IAAA,GAAkD,EAAC,EAC3C;AACR,EAAA,MAAM,SAAA,GAAY,KAAK,SAAA,IAAa,IAAA;AACpC,EAAA,MAAM,YAAA,GAAe,IAAA,CAAK,OAAA,EAAS,MAAA,IAAU,EAAC;AAC9C,EAAA,M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,CAAc,MAAM,CAAA;AACzC,IAAA,MAAM,WAAW,IAAA,CAAK,GAAA,CAAI,CAAC,CAAA,KAAM,EAAE,IAAI,CAAA;AACvC,IAAA,MAAM,IAAA,GACJ,QAAA,CAAS,MAAA,KAAW,CAAA,GAChB,kBAAA,GACA,CAAA,MAAA,EAAS,QAAA,CAAS,GAAA,CAAI,SAAS,CAAA,CAAE,IAAA,CAAK,IAAI,CAAC,CAAA,CAAA;AACjD,IAAA,KAAA,CAAM,IAAA,CAAK,CAAA,eAAA,EAAkB,MAAA,CAAO,EAAE,CAAC,CAAA,CAAE,CAAA;AACzC,IAAA,KAAA,CAAM,IAAA,CAAK,CAAA,IAAA,EAAO,IAAI,CAAA,CAAE,CAAA;AACxB,IAAA,KAAA,CAAM,KAAK,YAAY,CAAA;AAAA,EACzB;AACF","file":"index.js","sourcesContent":["// ═══════════════════════════════════════════════════════════════════════════\n// MERMAID SANITIZING — the two functions every drawing in this package shares.\n//\n// Mermaid state ids must be identifier-safe, and a transition label must not\n// contain the characters that terminate it. A state name like\n// `human:cp-approval` breaks the diagram on both counts.\n//\n// So it lives here, in a module with NO imports, rather than inside\n// `machine-viz/index.ts` — that one pulls in the whole substrate (`formOf`\n// from `../index`), and a future drawing must not acquire that dependency\n// merely to sanitize a string.\n// ═══════════════════════════════════════════════════════════════════════════\n\n/**\n * Sanitize a discriminant string into a Mermaid-safe node identifier.\n *\n * Any run of non-identifier characters becomes `_`; a leading digit is\n * prefixed so the id is always a valid Mermaid token; the empty string gets a\n * stable placeholder. Deterministic and idempotent — `safeId(safeId(x))` is\n * `safeId(x)`, so a diagram may sanitize the same name at several sites.\n */\nexport function safeId(raw: string): string {\n const cleaned = raw.replace(/[^A-Za-z0-9_]/g, \"_\");\n if (cleaned === \"\") return \"_empty\";\n return /^[0-9]/.test(cleaned) ? `s_${cleaned}` : cleaned;\n}\n\n/**\n * Sanitize text used as a Mermaid edge/transition label (the part after `:`).\n *\n * Strips the characters that terminate or confuse a label: newlines, the `:`\n * that separates label from target, and Mermaid's `\"`/`;` delimiters.\n */\nexport function safeLabel(raw: string): string {\n return raw.replace(/[\"\\n\\r;:]/g, \" \").trim();\n}\n","/**\n * @demlik/tea/machine-viz — turn a `Machine` into a Mermaid diagram string.\n *\n * PURE. No deps, no AST parsing, no file I/O. The function reads only the\n * `Machine` value it is handed plus optional sample states/msgs/ctx.\n *\n * The trick: TEA update cells are PURE (invariant 2 — they return\n * `[nextState, cmds]` as data, no effects). So we can SAFELY EXECUTE a cell to\n * discover its target state — exactly what `replay` does. That gives us REAL\n * edges (`red --> green : go`) without parsing source. When no sample is\n * provided for a `(state, msg)` pair we cannot resolve the target, so we fall\n * back to a STRUCTURAL self-edge annotated with `?` — visually distinct from a\n * resolved edge and documented in the diagram's legend.\n *\n * Form detection is `formOf(machine)` — the same reader `run`/`replay` use,\n * honoring the authoritative `__form` tag `defineMachine` stamps (falling back\n * to the structural heuristic for machines built without it; #275).\n *\n * What we MUST NOT do (these are the effectful paths, off-limits here):\n * - call `interpret[*]` handlers (perform I/O)\n * - call `subscribe[*]` handlers (install listeners)\n * - call `run` / the runtime\n * We MAY call `init`, `update[*]` cells, and `subscriptions(state)` — all pure\n * by the invariants (same set `replay` is allowed to touch).\n */\n\nimport type { Cmd, Machine, Sub } from \"../index\";\nimport { formOf } from \"../index\";\nimport { safeId, safeLabel } from \"./mermaid-id\";\n\n// The sanitizers live in a dependency-free module and are re-exported here,\n// because a consumer post-processing this drawing needs the same escaping.\nexport { safeId, safeLabel } from \"./mermaid-id\";\n\n// === Public options ===\n\n/**\n * Options controlling diagram emission.\n *\n * `samples` is the lever that turns STRUCTURAL edges into RESOLVED edges. For a\n * Transitions machine, providing a sample state for `stateType` AND a sample\n * msg for `msgType` lets us execute `update[stateType][msgType](state, msg)` and\n * read the real target `next.type`. Sample maps are keyed by the discriminant\n * string (`state.type` / `msg.type`).\n *\n * `samples.ctx` is the argument to `init(null, ctx)` — provide it to draw the\n * `[*] -->` initial-state edge. Omitted ⇒ no init edge (annotated as such),\n * because `init`'s signature requires a ctx and we will not invent one.\n */\nexport interface MachineVizOptions<S, M> {\n samples?: {\n /** Sample state per `state.type` — unlocks RESOLVED edges + sub annotations. */\n states?: Partial<Record<string, S>>;\n /** Sample msg per `msg.type` — unlocks RESOLVED edges. */\n msgs?: Partial<Record<string, M>>;\n /** Ctx for `init(null, ctx)` — unlocks the `[*] -->` initial-state edge. */\n ctx?: unknown;\n };\n /** Mermaid layout direction. Default `\"TB\"` (top-to-bottom). */\n direction?: \"TB\" | \"LR\";\n /** Optional diagram title, emitted as a Mermaid front-matter `title:` block. */\n title?: string;\n}\n\n// === Edge model ===\n\ntype Edge =\n // Resolved: we executed the cell with samples and read the real target.\n | { kind: \"resolved\"; from: string; to: string; msg: string }\n // Structural: no samples for the pair → target unknown, drawn as a self-loop.\n | { kind: \"structural\"; from: string; msg: string };\n\n// === toMermaid ===\n\n/**\n * Render a `Machine` as a Mermaid `stateDiagram-v2` string.\n *\n * - **Transitions form** (`update` is a record-of-records): nodes are the\n * `state.type` keys; each `(stateType × msgType)` cell becomes an edge. With\n * samples for both, the edge is RESOLVED by executing the (pure) cell. Without\n * samples it is STRUCTURAL — a `from --> from : msg?` self-loop (the `?`\n * suffix marks \"target unresolved\"). A legend note documents the distinction.\n * The `[*] -->` init edge is drawn only when `samples.ctx` is provided.\n *\n * - **Reducer form** (`update` values are functions): there is no static phase\n * graph (state is not a discriminated union over phases). We emit a single\n * node listing the handled `msg.type`s and an honest note saying so. No edges\n * are invented.\n *\n * Output is deterministic for the same input (keys iterated in insertion order,\n * no clocks, no randomness).\n */\nexport function toMermaid<\n S,\n M extends { type: string },\n C extends Cmd,\n U extends Sub,\n Ctx,\n>(\n machine: Machine<S, M, C, U, Ctx>,\n // `NoInfer` pins S/M to the `machine` argument so sample object literals in\n // `opts` are CHECKED against the machine's State/Msg unions rather than\n // driving inference (which would widen `{ type: \"open\" }` to `{ type: string }`\n // and collide with the machine's discriminated union).\n opts: MachineVizOptions<NoInfer<S>, NoInfer<M>> = {},\n): string {\n const direction = opts.direction ?? \"TB\";\n const stateSamples = opts.samples?.states ?? {};\n const msgSamples = opts.samples?.msgs ?? {};\n const hasCtx = opts.samples !== undefined && \"ctx\" in opts.samples;\n\n const mode = formOf(machine);\n const lines: string[] = [];\n\n // Front matter — Mermaid reads a YAML `title:` block before the diagram.\n if (opts.title !== undefined) {\n lines.push(\"---\", `title: ${opts.title}`, \"---\");\n }\n lines.push(\"stateDiagram-v2\");\n lines.push(` direction ${direction}`);\n\n if (mode === \"reducer\") {\n emitReducer(machine, lines);\n } else {\n emitTransitions(machine, lines, {\n stateSamples,\n msgSamples,\n hasCtx,\n ctx: opts.samples?.ctx,\n });\n }\n\n // Subscriptions annotation — pure call to `subscriptions(sampleState)` per\n // sampled state. Skipped entirely when no state samples are provided (we\n // refuse to invent a state to feed it).\n emitSubscriptions(machine, lines, stateSamples);\n\n return lines.join(\"\\n\");\n}\n\n// === Reducer-form emission ===\n\n/**\n * Reducer form has no phase graph. Emit one node listing the handled msg types\n * plus an honest note. The msg set is the `update` record's keys (the Reducer\n * mapped type guarantees one cell per Msg variant).\n */\nfunction emitReducer(machine: { update: unknown }, lines: string[]): void {\n const msgTypes = Object.keys(machine.update as object);\n lines.push(\" state ReducerMachine {\");\n if (msgTypes.length === 0) {\n lines.push(\" [*] --> NoMsgs\");\n lines.push(' NoMsgs : \"(no msg variants — M is never)\"');\n } else {\n for (const m of msgTypes) {\n lines.push(` ${safeId(m)} : ${safeLabel(m)}`);\n }\n }\n lines.push(\" }\");\n // The note IS the design honesty: no edges, because reducer-form state is not\n // a discriminated union over phases — there is no static target to draw.\n lines.push(\" note right of ReducerMachine\");\n lines.push(\" Reducer-form machine: flat dispatch keyed by msg.type.\");\n lines.push(\n \" No phase graph — state is not a discriminated union over phases.\",\n );\n lines.push(` Handled msg types: ${msgTypes.length}`);\n lines.push(\" end note\");\n}\n\n// === Transitions-form emission ===\n\ninterface TransitionsCtx<S, M> {\n stateSamples: Partial<Record<string, S>>;\n msgSamples: Partial<Record<string, M>>;\n hasCtx: boolean;\n ctx: unknown;\n}\n\n/**\n * Transitions form: walk the `update[stateType][msgType]` table. Execute the\n * (pure) cell when both samples exist → RESOLVED edge; otherwise → STRUCTURAL\n * self-loop. Draw the `[*] -->` init edge only when a ctx sample is given.\n */\nfunction emitTransitions<\n S,\n M extends { type: string },\n C extends Cmd,\n U extends Sub,\n Ctx,\n>(\n machine: Machine<S, M, C, U, Ctx>,\n lines: string[],\n ctx: TransitionsCtx<S, M>,\n): void {\n type CellFn = (state: S, msg: M) => readonly [S, readonly C[]];\n type Table = Record<string, Record<string, CellFn>>;\n const table = machine.update as unknown as Table;\n const stateTypes = Object.keys(table);\n\n // Declare every node up front so even unreachable phases render.\n for (const st of stateTypes) {\n lines.push(` ${safeId(st)}`);\n }\n\n // Init edge — only resolvable with a ctx sample. `init(null, ctx)` is pure\n // (invariant 2: fresh-boot branch returns a starting state). Read `next.type`.\n if (ctx.hasCtx) {\n const [initState] = machine.init(null, ctx.ctx as Ctx);\n const initType = (initState as unknown as { type: string }).type;\n lines.push(` [*] --> ${safeId(initType)}`);\n } else {\n lines.push(\n \" %% init edge omitted: no samples.ctx provided to run init(null, ctx)\",\n );\n }\n\n let anyStructural = false;\n for (const st of stateTypes) {\n const row = table[st];\n if (row === undefined) continue;\n const msgTypes = Object.keys(row);\n for (const mt of msgTypes) {\n const edge = resolveEdge(row, st, mt, ctx);\n if (edge.kind === \"resolved\") {\n lines.push(\n ` ${safeId(edge.from)} --> ${safeId(edge.to)} : ${safeLabel(edge.msg)}`,\n );\n } else {\n anyStructural = true;\n // Structural self-loop with a `?` suffix — target unresolved. Visually\n // distinct from a resolved edge (self-loop + trailing `?`).\n lines.push(\n ` ${safeId(edge.from)} --> ${safeId(edge.from)} : ${safeLabel(edge.msg)}?`,\n );\n }\n }\n }\n\n // Legend — document the resolved-vs-structural distinction in the output.\n lines.push(` note right of ${safeId(stateTypes[0] ?? \"_empty\")}`);\n lines.push(\" Transitions-form machine.\");\n lines.push(\" Edge a --> b : msg = RESOLVED (cell executed with samples).\");\n if (anyStructural) {\n lines.push(\n \" Self-loop a --> a : msg? = STRUCTURAL (no sample; target unresolved).\",\n );\n }\n lines.push(\" end note\");\n}\n\n/**\n * Resolve a single `(stateType, msgType)` cell into an Edge. With both a sample\n * state and a sample msg, EXECUTE the pure cell to read the real target. Any\n * missing sample → structural. A thrown cell (e.g. a sample shaped wrong for\n * the cell) degrades to structural rather than crashing the whole diagram —\n * the diagram is a best-effort visualization, not a correctness gate.\n */\nfunction resolveEdge<S, M extends { type: string }, C extends Cmd>(\n row: Record<string, (state: S, msg: M) => readonly [S, readonly C[]]>,\n stateType: string,\n msgType: string,\n ctx: {\n stateSamples: Partial<Record<string, S>>;\n msgSamples: Partial<Record<string, M>>;\n },\n): Edge {\n const sampleState = ctx.stateSamples[stateType];\n const sampleMsg = ctx.msgSamples[msgType];\n const cell = row[msgType];\n if (\n sampleState === undefined ||\n sampleMsg === undefined ||\n cell === undefined\n ) {\n return { kind: \"structural\", from: stateType, msg: msgType };\n }\n try {\n const [next] = cell(sampleState, sampleMsg);\n const to = (next as unknown as { type: string }).type;\n return { kind: \"resolved\", from: stateType, to, msg: msgType };\n } catch {\n // Mismatched sample → cannot resolve. Fall back to structural.\n return { kind: \"structural\", from: stateType, msg: msgType };\n }\n}\n\n// === Subscriptions annotation ===\n\n/**\n * For each sampled state, call the (pure) `subscriptions(state)` description\n * function and annotate which Sub types are active in that state as a Mermaid\n * note. We call `subscriptions` (the description) but NEVER `subscribe[*]` (the\n * effectful installer) — same boundary `replay` honors. Skipped when no state\n * samples are provided or the machine declares no `subscriptions`.\n */\nfunction emitSubscriptions<\n S,\n M extends { type: string },\n C extends Cmd,\n U extends Sub,\n Ctx,\n>(\n machine: Machine<S, M, C, U, Ctx>,\n lines: string[],\n stateSamples: Partial<Record<string, S>>,\n): void {\n if (machine.subscriptions === undefined) return;\n const stateTypes = Object.keys(stateSamples);\n if (stateTypes.length === 0) return;\n\n for (const st of stateTypes) {\n const sample = stateSamples[st];\n if (sample === undefined) continue;\n const subs = machine.subscriptions(sample);\n const subTypes = subs.map((s) => s.type);\n const body =\n subTypes.length === 0\n ? \"(no active subs)\"\n : `subs: ${subTypes.map(safeLabel).join(\", \")}`;\n lines.push(` note left of ${safeId(st)}`);\n lines.push(` ${body}`);\n lines.push(\" end note\");\n }\n}\n"]}
1
+ {"version":3,"sources":["../../src/machine-viz/mermaid-id.ts","../../src/machine-viz/index.ts"],"names":[],"mappings":";;;;AAqBO,SAAS,OAAO,GAAA,EAAqB;AAC1C,EAAA,MAAM,OAAA,GAAU,GAAA,CAAI,OAAA,CAAQ,gBAAA,EAAkB,GAAG,CAAA;AACjD,EAAA,IAAI,OAAA,KAAY,IAAI,OAAO,QAAA;AAC3B,EAAA,OAAO,SAAS,IAAA,CAAK,OAAO,CAAA,GAAI,CAAA,EAAA,EAAK,OAAO,CAAA,CAAA,GAAK,OAAA;AACnD;AAQO,SAAS,UAAU,GAAA,EAAqB;AAC7C,EAAA,OAAO,GAAA,CAAI,OAAA,CAAQ,YAAA,EAAc,GAAG,EAAE,IAAA,EAAK;AAC7C;;;AC0DO,SAAS,SAAA,CAOd,OAAA,EAKA,IAAA,GAAkD,EAAC,EAC3C;AACR,EAAA,MAAM,SAAA,GAAY,KAAK,SAAA,IAAa,IAAA;AACpC,EAAA,MAAM,YAAA,GAAe,IAAA,CAAK,OAAA,EAAS,MAAA,IAAU,EAAC;AAC9C,EAAA,MAAM,UAAA,GAAa,IAAA,CAAK,OAAA,EAAS,IAAA,IAAQ,EAAC;AAC1C,EAAA,MAAM,MAAA,GAAS,IAAA,CAAK,OAAA,KAAY,MAAA,IAAa,SAAS,IAAA,CAAK,OAAA;AAE3D,EAAA,MAAM,IAAA,GAAO,OAAO,OAAO,CAAA;AAC3B,EAAA,MAAM,QAAkB,EAAC;AAGzB,EAAA,IAAI,IAAA,CAAK,UAAU,MAAA,EAAW;AAC5B,IAAA,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A,GAChB,kBAAA,GACA,CAAA,MAAA,EAAS,QAAA,CAAS,GAAA,CAAI,SAAS,CAAA,CAAE,IAAA,CAAK,IAAI,CAAC,CAAA,CAAA;AACjD,IAAA,KAAA,CAAM,IAAA,CAAK,CAAA,eAAA,EAAkB,MAAA,CAAO,EAAE,CAAC,CAAA,CAAE,CAAA;AACzC,IAAA,KAAA,CAAM,IAAA,CAAK,CAAA,IAAA,EAAO,IAAI,CAAA,CAAE,CAAA;AACxB,IAAA,KAAA,CAAM,KAAK,YAAY,CAAA;AAAA,EACzB;AACF","file":"index.js","sourcesContent":["// ═══════════════════════════════════════════════════════════════════════════\n// MERMAID SANITIZING — the two functions every drawing in this package shares.\n//\n// Mermaid state ids must be identifier-safe, and a transition label must not\n// contain the characters that terminate it. A state name like\n// `human:cp-approval` breaks the diagram on both counts.\n//\n// So it lives here, in a module with NO imports, rather than inside\n// `machine-viz/index.ts` — that one pulls in the whole substrate (`formOf`\n// from `../index`), and a future drawing must not acquire that dependency\n// merely to sanitize a string.\n// ═══════════════════════════════════════════════════════════════════════════\n\n/**\n * Sanitize a discriminant string into a Mermaid-safe node identifier.\n *\n * Any run of non-identifier characters becomes `_`; a leading digit is\n * prefixed so the id is always a valid Mermaid token; the empty string gets a\n * stable placeholder. Deterministic and idempotent — `safeId(safeId(x))` is\n * `safeId(x)`, so a diagram may sanitize the same name at several sites.\n */\nexport function safeId(raw: string): string {\n const cleaned = raw.replace(/[^A-Za-z0-9_]/g, \"_\");\n if (cleaned === \"\") return \"_empty\";\n return /^[0-9]/.test(cleaned) ? `s_${cleaned}` : cleaned;\n}\n\n/**\n * Sanitize text used as a Mermaid edge/transition label (the part after `:`).\n *\n * Strips the characters that terminate or confuse a label: newlines, the `:`\n * that separates label from target, and Mermaid's `\"`/`;` delimiters.\n */\nexport function safeLabel(raw: string): string {\n return raw.replace(/[\"\\n\\r;:]/g, \" \").trim();\n}\n","/**\n * @demlik/tea/machine-viz — turn a `Machine` into a Mermaid diagram string.\n *\n * PURE. No deps, no AST parsing, no file I/O. The function reads only the\n * `Machine` value it is handed plus optional sample states/msgs/ctx.\n *\n * The trick: TEA update cells are PURE (invariant 2 — they return\n * `[nextState, cmds]` as data, no effects). So we can SAFELY EXECUTE a cell to\n * discover its target state — exactly what `replay` does. That gives us REAL\n * edges (`red --> green : go`) without parsing source. When no sample is\n * provided for a `(state, msg)` pair we cannot resolve the target, so we fall\n * back to a STRUCTURAL self-edge annotated with `?` — visually distinct from a\n * resolved edge and documented in the diagram's legend.\n *\n * Form detection is `formOf(machine)` — the same reader `run`/`replay` use,\n * honoring the authoritative `__form` tag `defineMachine` stamps (falling back\n * to the structural heuristic for machines built without it; #275).\n *\n * What we MUST NOT do (these are the effectful paths, off-limits here):\n * - call `interpret[*]` handlers (perform I/O)\n * - call `subscribe[*]` runners (install listeners)\n * - call `run` / the runtime\n * We MAY call `init`, `update[*]` cells, and each `subs` entry's `deps(state)`\n * — all pure by the invariants (same set `replay` is allowed to touch).\n */\n\nimport type { Cmd, Machine, Sub } from \"../index\";\nimport { formOf } from \"../index\";\nimport { desiredSub, subEntriesOf } from \"../pure/core\";\nimport { safeId, safeLabel } from \"./mermaid-id\";\n\n// The sanitizers live in a dependency-free module and are re-exported here,\n// because a consumer post-processing this drawing needs the same escaping.\nexport { safeId, safeLabel } from \"./mermaid-id\";\n\n// === Public options ===\n\n/**\n * Options controlling diagram emission.\n *\n * `samples` is the lever that turns STRUCTURAL edges into RESOLVED edges. For a\n * Transitions machine, providing a sample state for `stateType` AND a sample\n * msg for `msgType` lets us execute `update[stateType][msgType](state, msg)` and\n * read the real target `next.type`. Sample maps are keyed by the discriminant\n * string (`state.type` / `msg.type`).\n *\n * `samples.ctx` is the argument to `init(null, ctx)` — provide it to draw the\n * `[*] -->` initial-state edge. Omitted ⇒ no init edge (annotated as such),\n * because `init`'s signature requires a ctx and we will not invent one.\n */\nexport interface MachineVizOptions<S, M> {\n samples?: {\n /** Sample state per `state.type` — unlocks RESOLVED edges + sub annotations. */\n states?: Partial<Record<string, S>>;\n /** Sample msg per `msg.type` — unlocks RESOLVED edges. */\n msgs?: Partial<Record<string, M>>;\n /** Ctx for `init(null, ctx)` — unlocks the `[*] -->` initial-state edge. */\n ctx?: unknown;\n };\n /** Mermaid layout direction. Default `\"TB\"` (top-to-bottom). */\n direction?: \"TB\" | \"LR\";\n /** Optional diagram title, emitted as a Mermaid front-matter `title:` block. */\n title?: string;\n}\n\n// === Edge model ===\n\ntype Edge =\n // Resolved: we executed the cell with samples and read the real target.\n | { kind: \"resolved\"; from: string; to: string; msg: string }\n // Structural: no samples for the pair → target unknown, drawn as a self-loop.\n | { kind: \"structural\"; from: string; msg: string };\n\n// === toMermaid ===\n\n/**\n * Render a `Machine` as a Mermaid `stateDiagram-v2` string.\n *\n * - **Transitions form** (`update` is a record-of-records): nodes are the\n * `state.type` keys; each `(stateType × msgType)` cell becomes an edge. With\n * samples for both, the edge is RESOLVED by executing the (pure) cell. Without\n * samples it is STRUCTURAL — a `from --> from : msg?` self-loop (the `?`\n * suffix marks \"target unresolved\"). A legend note documents the distinction.\n * The `[*] -->` init edge is drawn only when `samples.ctx` is provided.\n *\n * - **Reducer form** (`update` values are functions): there is no static phase\n * graph (state is not a discriminated union over phases). We emit a single\n * node listing the handled `msg.type`s and an honest note saying so. No edges\n * are invented.\n *\n * Output is deterministic for the same input (keys iterated in insertion order,\n * no clocks, no randomness).\n */\nexport function toMermaid<\n S,\n M extends { type: string },\n C extends Cmd,\n U extends Sub,\n Ctx,\n>(\n machine: Machine<S, M, C, U, Ctx>,\n // `NoInfer` pins S/M to the `machine` argument so sample object literals in\n // `opts` are CHECKED against the machine's State/Msg unions rather than\n // driving inference (which would widen `{ type: \"open\" }` to `{ type: string }`\n // and collide with the machine's discriminated union).\n opts: MachineVizOptions<NoInfer<S>, NoInfer<M>> = {},\n): string {\n const direction = opts.direction ?? \"TB\";\n const stateSamples = opts.samples?.states ?? {};\n const msgSamples = opts.samples?.msgs ?? {};\n const hasCtx = opts.samples !== undefined && \"ctx\" in opts.samples;\n\n const mode = formOf(machine);\n const lines: string[] = [];\n\n // Front matter — Mermaid reads a YAML `title:` block before the diagram.\n if (opts.title !== undefined) {\n lines.push(\"---\", `title: ${opts.title}`, \"---\");\n }\n lines.push(\"stateDiagram-v2\");\n lines.push(` direction ${direction}`);\n\n if (mode === \"reducer\") {\n emitReducer(machine, lines);\n } else {\n emitTransitions(machine, lines, {\n stateSamples,\n msgSamples,\n hasCtx,\n ctx: opts.samples?.ctx,\n });\n }\n\n // Subscriptions annotation — pure call to each `subs` entry's `deps` per\n // sampled state. Skipped entirely when no state samples are provided (we\n // refuse to invent a state to feed it).\n emitSubscriptions(machine, lines, stateSamples);\n\n return lines.join(\"\\n\");\n}\n\n// === Reducer-form emission ===\n\n/**\n * Reducer form has no phase graph. Emit one node listing the handled msg types\n * plus an honest note. The msg set is the `update` record's keys (the Reducer\n * mapped type guarantees one cell per Msg variant).\n */\nfunction emitReducer(machine: { update: unknown }, lines: string[]): void {\n const msgTypes = Object.keys(machine.update as object);\n lines.push(\" state ReducerMachine {\");\n if (msgTypes.length === 0) {\n lines.push(\" [*] --> NoMsgs\");\n lines.push(' NoMsgs : \"(no msg variants — M is never)\"');\n } else {\n for (const m of msgTypes) {\n lines.push(` ${safeId(m)} : ${safeLabel(m)}`);\n }\n }\n lines.push(\" }\");\n // The note IS the design honesty: no edges, because reducer-form state is not\n // a discriminated union over phases — there is no static target to draw.\n lines.push(\" note right of ReducerMachine\");\n lines.push(\" Reducer-form machine: flat dispatch keyed by msg.type.\");\n lines.push(\n \" No phase graph — state is not a discriminated union over phases.\",\n );\n lines.push(` Handled msg types: ${msgTypes.length}`);\n lines.push(\" end note\");\n}\n\n// === Transitions-form emission ===\n\ninterface TransitionsCtx<S, M> {\n stateSamples: Partial<Record<string, S>>;\n msgSamples: Partial<Record<string, M>>;\n hasCtx: boolean;\n ctx: unknown;\n}\n\n/**\n * Transitions form: walk the `update[stateType][msgType]` table. Execute the\n * (pure) cell when both samples exist → RESOLVED edge; otherwise → STRUCTURAL\n * self-loop. Draw the `[*] -->` init edge only when a ctx sample is given.\n */\nfunction emitTransitions<\n S,\n M extends { type: string },\n C extends Cmd,\n U extends Sub,\n Ctx,\n>(\n machine: Machine<S, M, C, U, Ctx>,\n lines: string[],\n ctx: TransitionsCtx<S, M>,\n): void {\n type CellFn = (state: S, msg: M) => readonly [S, readonly C[]];\n type Table = Record<string, Record<string, CellFn>>;\n const table = machine.update as unknown as Table;\n const stateTypes = Object.keys(table);\n\n // Declare every node up front so even unreachable phases render.\n for (const st of stateTypes) {\n lines.push(` ${safeId(st)}`);\n }\n\n // Init edge — only resolvable with a ctx sample. `init(null, ctx)` is pure\n // (invariant 2: fresh-boot branch returns a starting state). Read `next.type`.\n if (ctx.hasCtx) {\n const [initState] = machine.init(null, ctx.ctx as Ctx);\n const initType = (initState as unknown as { type: string }).type;\n lines.push(` [*] --> ${safeId(initType)}`);\n } else {\n lines.push(\n \" %% init edge omitted: no samples.ctx provided to run init(null, ctx)\",\n );\n }\n\n let anyStructural = false;\n for (const st of stateTypes) {\n const row = table[st];\n if (row === undefined) continue;\n const msgTypes = Object.keys(row);\n for (const mt of msgTypes) {\n const edge = resolveEdge(row, st, mt, ctx);\n if (edge.kind === \"resolved\") {\n lines.push(\n ` ${safeId(edge.from)} --> ${safeId(edge.to)} : ${safeLabel(edge.msg)}`,\n );\n } else {\n anyStructural = true;\n // Structural self-loop with a `?` suffix — target unresolved. Visually\n // distinct from a resolved edge (self-loop + trailing `?`).\n lines.push(\n ` ${safeId(edge.from)} --> ${safeId(edge.from)} : ${safeLabel(edge.msg)}?`,\n );\n }\n }\n }\n\n // Legend — document the resolved-vs-structural distinction in the output.\n lines.push(` note right of ${safeId(stateTypes[0] ?? \"_empty\")}`);\n lines.push(\" Transitions-form machine.\");\n lines.push(\" Edge a --> b : msg = RESOLVED (cell executed with samples).\");\n if (anyStructural) {\n lines.push(\n \" Self-loop a --> a : msg? = STRUCTURAL (no sample; target unresolved).\",\n );\n }\n lines.push(\" end note\");\n}\n\n/**\n * Resolve a single `(stateType, msgType)` cell into an Edge. With both a sample\n * state and a sample msg, EXECUTE the pure cell to read the real target. Any\n * missing sample → structural. A thrown cell (e.g. a sample shaped wrong for\n * the cell) degrades to structural rather than crashing the whole diagram —\n * the diagram is a best-effort visualization, not a correctness gate.\n */\nfunction resolveEdge<S, M extends { type: string }, C extends Cmd>(\n row: Record<string, (state: S, msg: M) => readonly [S, readonly C[]]>,\n stateType: string,\n msgType: string,\n ctx: {\n stateSamples: Partial<Record<string, S>>;\n msgSamples: Partial<Record<string, M>>;\n },\n): Edge {\n const sampleState = ctx.stateSamples[stateType];\n const sampleMsg = ctx.msgSamples[msgType];\n const cell = row[msgType];\n if (\n sampleState === undefined ||\n sampleMsg === undefined ||\n cell === undefined\n ) {\n return { kind: \"structural\", from: stateType, msg: msgType };\n }\n try {\n const [next] = cell(sampleState, sampleMsg);\n const to = (next as unknown as { type: string }).type;\n return { kind: \"resolved\", from: stateType, to, msg: msgType };\n } catch {\n // Mismatched sample → cannot resolve. Fall back to structural.\n return { kind: \"structural\", from: stateType, msg: msgType };\n }\n}\n\n// === Subscriptions annotation ===\n\n/**\n * For each sampled state, read which `subs` entries are on there (their pure\n * `deps`) and annotate those Sub types as a Mermaid note. We read `deps` (the\n * description) but NEVER a `subscribe[*]` runner (the effectful installer) —\n * same boundary `replay` honors. Skipped when no state samples are provided or\n * the machine declares no `subs`.\n */\nfunction emitSubscriptions<\n S,\n M extends { type: string },\n C extends Cmd,\n U extends Sub,\n Ctx,\n>(\n machine: Machine<S, M, C, U, Ctx>,\n lines: string[],\n stateSamples: Partial<Record<string, S>>,\n): void {\n const entries = subEntriesOf<S>(machine);\n if (entries.length === 0) return;\n const stateTypes = Object.keys(stateSamples);\n if (stateTypes.length === 0) return;\n\n for (const st of stateTypes) {\n const sample = stateSamples[st];\n if (sample === undefined) continue;\n const subTypes = entries.flatMap((entry) => {\n const sub = desiredSub(entry, sample);\n return sub === null ? [] : [sub.type];\n });\n const body =\n subTypes.length === 0\n ? \"(no active subs)\"\n : `subs: ${subTypes.map(safeLabel).join(\", \")}`;\n lines.push(` note left of ${safeId(st)}`);\n lines.push(` ${body}`);\n lines.push(\" end note\");\n }\n}\n"]}
@@ -1,7 +1,6 @@
1
- import { S as Store, F as FencedStore } from '../runtime-types-LWDoi943.js';
2
- import 'better-result';
3
- import '../core-CTzMJ82M.js';
4
- import 'zod';
1
+ import { S as Store, F as FencedStore } from '../runtime-types-CiVpC0HN.js';
2
+ import '../core-BbgtiXdg.js';
3
+ import '@standard-schema/spec';
5
4
 
6
5
  /**
7
6
  * @packageDocumentation
package/dist/mem/index.js CHANGED
@@ -1,4 +1,5 @@
1
- import { StoreConflictError } from '../chunk-RQULHGYH.js';
1
+ import '../chunk-GOX2CYIM.js';
2
+ import { StoreConflictError } from '../chunk-CH5KTOEZ.js';
2
3
 
3
4
  // src/mem/index.ts
4
5
  function memoryStore(initial, parse = (raw) => raw, options = {}) {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/mem/index.ts"],"names":[],"mappings":";;;AAsEO,SAAS,WAAA,CACd,SACA,KAAA,GAAoC,CAAC,QAAQ,GAAA,EAC7C,OAAA,GAA8B,EAAC,EACJ;AAG3B,EAAA,IAAI,OAAiB,OAAA,IAAW,IAAA;AAGhC,EAAA,IAAI,OAAA,GAAU,CAAA;AAEd,EAAA,MAAM,IAAA,GAAiB;AAAA,IACrB,MAAM,IAAA,GAAyB;AAC7B,MAAA,OAAO,IAAA;AAAA,IACT,CAAA;AAAA,IACA,MAAM,KAAK,KAAA,EAAyB;AAClC,MAAA,IAAA,GAAO,KAAA;AACP,MAAA,OAAA,IAAW,CAAA;AAAA,IACb,CAAA;AAAA,IACA,QAAQ,GAAA,EAAwB;AAC9B,MAAA,OAAO,MAAM,GAAG,CAAA;AAAA,IAClB;AAAA,GACF;AACA,EAAA,IAAI,OAAA,CAAQ,MAAA,KAAW,IAAA,EAAM,OAAO,IAAA;AAEpC,EAAA,OAAO;AAAA,IACL,GAAG,IAAA;AAAA,IACH,MAAA,EAAQ,IAAA;AAAA,IACR,MAAM,UAAA,GAAyD;AAC7D,MAAA,OAAO,EAAE,GAAA,EAAK,IAAA,EAAM,OAAA,EAAQ;AAAA,IAC9B,CAAA;AAAA,IACA,MAAM,UAAA,CAAW,KAAA,EAAU,eAAA,EAA0C;AAInE,MAAA,IAAI,YAAY,eAAA,EAAiB;AAC/B,QAAA,MAAM,IAAI,kBAAA,CAAmB,eAAA,EAAiB,OAAO,CAAA;AAAA,MACvD;AACA,MAAA,IAAA,GAAO,KAAA;AACP,MAAA,OAAA,IAAW,CAAA;AACX,MAAA,OAAO,OAAA;AAAA,IACT;AAAA,GACF;AACF","file":"index.js","sourcesContent":["/**\n * @packageDocumentation\n * @demlik/tea/mem — in-memory `Store<S>` adapter for `@demlik/tea`.\n *\n * The standard test adapter — used everywhere a Worker or DO would be\n * overkill. Mirrors the source-only convention from `packages/widget-engine`\n * and `packages/tea` (no build step).\n *\n * Reference semantics, NOT deep-clone semantics:\n * - `save(state)` stores the reference; subsequent mutations to that\n * reference by the caller are observable through later `load()` calls.\n * - `load()` returns the stored reference; mutations made through it are\n * observable on the next `load()`.\n *\n * This matches what a real KV/DO `get()` would NOT do (those serialize +\n * deserialize), but it also matches what an in-memory cache obviously does.\n * Adding a deep clone here would lie about the boundary and impose a JSON\n * round-trip on every test. Tests that need fresh copies should clone at the\n * call site.\n *\n * Boundary parse (invariant 8): `Store<S>` requires `migrate(raw)`. For\n * `memoryStore` we ship a permissive identity-default — `(raw) => raw as\n * S | null` — because this adapter is a degenerate same-process boundary:\n * there is no serialization, the reference we read is structurally the\n * reference we wrote. The `as` cast here is the documented exception to the\n * invariant-8 no-`as` rule, scoped to the parameter default. Callers that\n * want strict parsing (e.g. a test that hand-seeds the cell from outside)\n * may pass an explicit `parse` to override.\n */\n\nimport type { FencedStore, Store } from \"../index\";\nimport { StoreConflictError } from \"../index\";\n\n/** Options for {@link memoryStore}. */\nexport interface MemoryStoreOptions {\n /**\n * Refuse a second live writer (#143). With `{ fenced: true }` the returned\n * store is a `FencedStore<S>` whose version is an in-process counter — honest\n * for this adapter, since the cell it guards is in this process too. Two\n * `run`s handed the SAME `memoryStore` are the case it catches, and it is the\n * cheapest way to exercise the fenced path in a test.\n */\n readonly fenced?: true;\n}\n\n/**\n * Build an in-memory `Store<S>`.\n *\n * @param initial - optional seed value. `undefined` and explicit `null` both\n * mean \"no seed\"; `load()` resolves with `null` until the first `save()`.\n * A concrete `S` seed is returned by `load()` until overwritten.\n * @param parse - optional boundary parse for the `Store<S>.migrate` contract.\n * Defaults to identity (`(raw) => raw as S | null`) — honest for this\n * adapter's degenerate same-process boundary. Pass an explicit parser when\n * the test wants to reject seeded shapes that don't match `S`.\n */\nexport function memoryStore<S>(\n initial?: S | null,\n parse?: (raw: unknown) => S | null,\n): Store<S>;\nexport function memoryStore<S>(\n initial: S | null | undefined,\n parse: ((raw: unknown) => S | null) | undefined,\n options: MemoryStoreOptions & { readonly fenced: true },\n): FencedStore<S>;\nexport function memoryStore<S>(\n initial?: S | null,\n parse?: (raw: unknown) => S | null,\n options?: MemoryStoreOptions,\n): Store<S> | FencedStore<S>;\nexport function memoryStore<S>(\n initial?: S | null,\n parse: (raw: unknown) => S | null = (raw) => raw as S | null,\n options: MemoryStoreOptions = {},\n): Store<S> | FencedStore<S> {\n // Single internal cell — `undefined` and `null` collapse to one\n // representation so the load site is branchless.\n let cell: S | null = initial ?? null;\n // The version the cell was last written at. A never-written cell reads `0`,\n // matching `fileStore`'s absent stamp.\n let version = 0;\n\n const base: Store<S> = {\n async load(): Promise<unknown> {\n return cell;\n },\n async save(state: S): Promise<void> {\n cell = state;\n version += 1;\n },\n migrate(raw: unknown): S | null {\n return parse(raw);\n },\n };\n if (options.fenced !== true) return base;\n\n return {\n ...base,\n fenced: true,\n async loadFenced(): Promise<{ raw: unknown; version: number }> {\n return { raw: cell, version };\n },\n async saveFenced(state: S, expectedVersion: number): Promise<number> {\n // No lock: the whole store is one process's memory, and this body has no\n // await before the compare, so nothing can interleave between the check\n // and the write.\n if (version !== expectedVersion) {\n throw new StoreConflictError(expectedVersion, version);\n }\n cell = state;\n version += 1;\n return version;\n },\n };\n}\n"]}
1
+ {"version":3,"sources":["../../src/mem/index.ts"],"names":[],"mappings":";;;;AAsEO,SAAS,WAAA,CACd,SACA,KAAA,GAAoC,CAAC,QAAQ,GAAA,EAC7C,OAAA,GAA8B,EAAC,EACJ;AAG3B,EAAA,IAAI,OAAiB,OAAA,IAAW,IAAA;AAGhC,EAAA,IAAI,OAAA,GAAU,CAAA;AAEd,EAAA,MAAM,IAAA,GAAiB;AAAA,IACrB,MAAM,IAAA,GAAyB;AAC7B,MAAA,OAAO,IAAA;AAAA,IACT,CAAA;AAAA,IACA,MAAM,KAAK,KAAA,EAAyB;AAClC,MAAA,IAAA,GAAO,KAAA;AACP,MAAA,OAAA,IAAW,CAAA;AAAA,IACb,CAAA;AAAA,IACA,QAAQ,GAAA,EAAwB;AAC9B,MAAA,OAAO,MAAM,GAAG,CAAA;AAAA,IAClB;AAAA,GACF;AACA,EAAA,IAAI,OAAA,CAAQ,MAAA,KAAW,IAAA,EAAM,OAAO,IAAA;AAEpC,EAAA,OAAO;AAAA,IACL,GAAG,IAAA;AAAA,IACH,MAAA,EAAQ,IAAA;AAAA,IACR,MAAM,UAAA,GAAyD;AAC7D,MAAA,OAAO,EAAE,GAAA,EAAK,IAAA,EAAM,OAAA,EAAQ;AAAA,IAC9B,CAAA;AAAA,IACA,MAAM,UAAA,CAAW,KAAA,EAAU,eAAA,EAA0C;AAInE,MAAA,IAAI,YAAY,eAAA,EAAiB;AAC/B,QAAA,MAAM,IAAI,kBAAA,CAAmB,eAAA,EAAiB,OAAO,CAAA;AAAA,MACvD;AACA,MAAA,IAAA,GAAO,KAAA;AACP,MAAA,OAAA,IAAW,CAAA;AACX,MAAA,OAAO,OAAA;AAAA,IACT;AAAA,GACF;AACF","file":"index.js","sourcesContent":["/**\n * @packageDocumentation\n * @demlik/tea/mem — in-memory `Store<S>` adapter for `@demlik/tea`.\n *\n * The standard test adapter — used everywhere a Worker or DO would be\n * overkill. Mirrors the source-only convention from `packages/widget-engine`\n * and `packages/tea` (no build step).\n *\n * Reference semantics, NOT deep-clone semantics:\n * - `save(state)` stores the reference; subsequent mutations to that\n * reference by the caller are observable through later `load()` calls.\n * - `load()` returns the stored reference; mutations made through it are\n * observable on the next `load()`.\n *\n * This matches what a real KV/DO `get()` would NOT do (those serialize +\n * deserialize), but it also matches what an in-memory cache obviously does.\n * Adding a deep clone here would lie about the boundary and impose a JSON\n * round-trip on every test. Tests that need fresh copies should clone at the\n * call site.\n *\n * Boundary parse (invariant 8): `Store<S>` requires `migrate(raw)`. For\n * `memoryStore` we ship a permissive identity-default — `(raw) => raw as\n * S | null` — because this adapter is a degenerate same-process boundary:\n * there is no serialization, the reference we read is structurally the\n * reference we wrote. The `as` cast here is the documented exception to the\n * invariant-8 no-`as` rule, scoped to the parameter default. Callers that\n * want strict parsing (e.g. a test that hand-seeds the cell from outside)\n * may pass an explicit `parse` to override.\n */\n\nimport type { FencedStore, Store } from \"../index\";\nimport { StoreConflictError } from \"../index\";\n\n/** Options for {@link memoryStore}. */\nexport interface MemoryStoreOptions {\n /**\n * Refuse a second live writer (#143). With `{ fenced: true }` the returned\n * store is a `FencedStore<S>` whose version is an in-process counter — honest\n * for this adapter, since the cell it guards is in this process too. Two\n * `run`s handed the SAME `memoryStore` are the case it catches, and it is the\n * cheapest way to exercise the fenced path in a test.\n */\n readonly fenced?: true;\n}\n\n/**\n * Build an in-memory `Store<S>`.\n *\n * @param initial - optional seed value. `undefined` and explicit `null` both\n * mean \"no seed\"; `load()` resolves with `null` until the first `save()`.\n * A concrete `S` seed is returned by `load()` until overwritten.\n * @param parse - optional boundary parse for the `Store<S>.migrate` contract.\n * Defaults to identity (`(raw) => raw as S | null`) — honest for this\n * adapter's degenerate same-process boundary. Pass an explicit parser when\n * the test wants to reject seeded shapes that don't match `S`.\n */\nexport function memoryStore<S>(\n initial?: S | null,\n parse?: (raw: unknown) => S | null,\n): Store<S>;\nexport function memoryStore<S>(\n initial: S | null | undefined,\n parse: ((raw: unknown) => S | null) | undefined,\n options: MemoryStoreOptions & { readonly fenced: true },\n): FencedStore<S>;\nexport function memoryStore<S>(\n initial?: S | null,\n parse?: (raw: unknown) => S | null,\n options?: MemoryStoreOptions,\n): Store<S> | FencedStore<S>;\nexport function memoryStore<S>(\n initial?: S | null,\n parse: (raw: unknown) => S | null = (raw) => raw as S | null,\n options: MemoryStoreOptions = {},\n): Store<S> | FencedStore<S> {\n // Single internal cell — `undefined` and `null` collapse to one\n // representation so the load site is branchless.\n let cell: S | null = initial ?? null;\n // The version the cell was last written at. A never-written cell reads `0`,\n // matching `fileStore`'s absent stamp.\n let version = 0;\n\n const base: Store<S> = {\n async load(): Promise<unknown> {\n return cell;\n },\n async save(state: S): Promise<void> {\n cell = state;\n version += 1;\n },\n migrate(raw: unknown): S | null {\n return parse(raw);\n },\n };\n if (options.fenced !== true) return base;\n\n return {\n ...base,\n fenced: true,\n async loadFenced(): Promise<{ raw: unknown; version: number }> {\n return { raw: cell, version };\n },\n async saveFenced(state: S, expectedVersion: number): Promise<number> {\n // No lock: the whole store is one process's memory, and this body has no\n // await before the compare, so nothing can interleave between the check\n // and the write.\n if (version !== expectedVersion) {\n throw new StoreConflictError(expectedVersion, version);\n }\n cell = state;\n version += 1;\n return version;\n },\n };\n}\n"]}
@@ -1,8 +1,7 @@
1
1
  import WebSocket from 'ws';
2
- import { S as Store, F as FencedStore } from '../runtime-types-LWDoi943.js';
3
- import { S as Sub, c as SubId } from '../core-CTzMJ82M.js';
4
- import 'better-result';
5
- import 'zod';
2
+ import { S as Store, F as FencedStore } from '../runtime-types-CiVpC0HN.js';
3
+ import { S as Sub, h as Dispose } from '../core-BbgtiXdg.js';
4
+ import '@standard-schema/spec';
6
5
 
7
6
  /**
8
7
  * @packageDocumentation
@@ -94,29 +93,33 @@ interface Journal<R> {
94
93
  * Use for resumable scripts / local repro of prod machines. Ephemeral
95
94
  * CLIs can skip persistence with `memoryStore` from `@demlik/tea/mem`.
96
95
  *
97
- * 2. `nodeSubscribe<M, Ctx>()` — handler registry for the three node-native
98
- * Sub types this package owns:
99
- * - `node_ws` — opens a `ws` WebSocket; routes open/message/close/
100
- * error into Msgs. Registers the live socket in
101
- * `ctx.wsRegistry` so a Cmd handler can write to it
102
- * (see `sendToWebSocket`). Cleanup closes the socket
103
- * for ANY non-CLOSED state.
104
- * - `node_timer` — setTimeout / setInterval; cleanup clears it.
105
- * - `node_signal` — a process signal (SIGINT/SIGTERM/…) → Msg; cleanup
106
- * detaches the listener.
96
+ * 2. `nodeSubscribe<M, Ctx>({ ws })` — the runners for the three node-native
97
+ * Sub types this package owns, handed to `run` as its `subscribe`:
98
+ * - `node_ws` — deps `{ key, url }`. Opens a `ws` WebSocket; routes
99
+ * open/message/close/error into Msgs through the `ws`
100
+ * handlers. Registers the live socket in
101
+ * `ctx.wsRegistry` under `key` so a Cmd handler can
102
+ * write to it (see `sendToWebSocket`). Cleanup closes
103
+ * the socket for ANY non-CLOSED state.
104
+ * - `node_timer` — deps `{ delayMs, msg, repeat? }`. setTimeout /
105
+ * setInterval; cleanup clears it.
106
+ * - `node_signal` — deps `{ signal, msg }`. A process signal
107
+ * (SIGINT/SIGTERM/…) → Msg; cleanup detaches the
108
+ * listener.
107
109
  *
108
110
  * Unlike tea-do — whose `alarm()` / `webSocketMessage()` are DO lifecycle
109
111
  * methods the handler can't observe from the outside, hence its registries —
110
- * a node process is continuously alive: each handler holds its resource in
111
- * closure and the returned cleanup closes it. The substrate's subscription
112
- * reconciler runs that cleanup the instant `subscriptions(state)` stops listing
113
- * the Sub — end-then-start choreography for free (Rule 9, [invariant 4]).
114
- * A lifecycle-bound resource (a socket, a timer) becomes impossible to leak
115
- * from a reducer cell, because no reducer cell owns its teardown.
112
+ * a node process is continuously alive: each runner holds its resource in
113
+ * closure and the returned cleanup closes it. The engine runs that cleanup the
114
+ * instant the Sub's `deps` go null, and a changed `deps` value stops the old
115
+ * runner before starting the new one — end-then-start choreography for free
116
+ * (Rule 9, [invariant 4]). A lifecycle-bound resource (a socket, a timer)
117
+ * becomes impossible to leak from a reducer cell, because no reducer cell owns
118
+ * its teardown.
116
119
  *
117
- * `ctx.wsRegistry` is the one shared surface: `node_ws` populates it; a Cmd
118
- * interpreter reads it to write to the open socket. Same shape as tea-do's
119
- * `wsRegistry`.
120
+ * `ctx.wsRegistry` is the one shared surface: `node_ws` populates it, keyed by
121
+ * the Sub's `deps.key`; a Cmd interpreter reads it to write to the open
122
+ * socket. Same shape as tea-do's `wsRegistry`.
120
123
  */
121
124
 
122
125
  /**
@@ -180,83 +183,121 @@ interface FileStoreOptions {
180
183
  */
181
184
  declare function fileJournal<R>(dir: string, parse: (raw: unknown) => R): Journal<R>;
182
185
  /**
183
- * A node WebSocket sub. The substrate diffs subs by `id`; the same `id` across
184
- * transitions = the same socket (kept open). Emit a DIFFERENT `id` to force a
185
- * reconnect.
186
+ * The `deps` of a `node_ws` Sub: which socket (`key`) and where it connects
187
+ * (`url`). Both are plain data, so the engine derives the Sub's id from them —
188
+ * the same `{ key, url }` across transitions is the same socket (kept open),
189
+ * and a changed one closes it and opens a fresh one.
186
190
  *
187
- * Only `onMessage` returns `M | null` (null drops the frame) because inbound
188
- * frames are the boundary that needs a parse-and-maybe-discard seam. `onOpen`/
189
- * `onClose`/`onError` always dispatch — a spurious one is dropped in the reducer
190
- * (the cell ignores it), not here.
191
+ * `key` is the author's name for the socket: the Cmd side addresses it through
192
+ * {@link sendToWebSocket} by that key, since the derived Sub id is not
193
+ * something a Cmd handler can know. It must be unique among the machine's live
194
+ * `node_ws` Subs.
191
195
  */
192
- type NodeWsSub<M> = {
193
- id: SubId;
194
- type: "node_ws";
195
- url: string;
196
- onMessage: (data: string) => M | null;
197
- onOpen?: () => M;
198
- onClose?: (code: number, reason: string) => M;
199
- onError?: (message: string) => M;
196
+ type NodeWsDeps = {
197
+ readonly key: string;
198
+ readonly url: string;
200
199
  };
201
200
  /**
202
- * A node timer sub. One-shot `setTimeout` by default; `repeat: true` →
203
- * `setInterval`. Cleanup clears the timer — a timer keyed to a phase is
204
- * cancelled the moment the machine leaves that phase.
201
+ * A node WebSocket sub. Its callbacks are not data, so they live on the runner
202
+ * side — {@link NodeWsHandlers}, handed to {@link nodeSubscribe}.
203
+ */
204
+ type NodeWsSub = Sub<"node_ws", NodeWsDeps>;
205
+ /**
206
+ * The `deps` of a `node_timer` Sub. One-shot `setTimeout` by default;
207
+ * `repeat: true` → `setInterval`.
205
208
  */
206
- type NodeTimerSub<M> = {
207
- id: SubId;
208
- type: "node_timer";
209
- delayMs: number;
210
- msg: M;
211
- repeat?: boolean;
209
+ type NodeTimerDeps<M> = {
210
+ readonly delayMs: number;
211
+ readonly msg: M;
212
+ readonly repeat?: boolean;
212
213
  };
213
214
  /**
214
- * A process-signal sub: `signal` (SIGINT/SIGTERM/…) → `msg`. Cleanup detaches
215
- * the listener. Lets graceful shutdown be a real machine transition rather than
216
- * an out-of-band `process.on` that the reducer can't see.
215
+ * A node timer sub. Cleanup clears the timer — a timer keyed to a phase is
216
+ * cancelled the moment the machine leaves that phase, and a changed
217
+ * `delayMs` / `msg` / `repeat` is a new id, so the timer restarts. For a plain
218
+ * one-shot, the engine's built-in `timer` Sub needs no runner at all.
217
219
  */
218
- type NodeSignalSub<M> = {
219
- id: SubId;
220
- type: "node_signal";
221
- signal: NodeJS.Signals;
222
- msg: M;
220
+ type NodeTimerSub<M> = Sub<"node_timer", NodeTimerDeps<M>>;
221
+ /** The `deps` of a `node_signal` Sub: `signal` (SIGINT/SIGTERM/…) → `msg`. */
222
+ type NodeSignalDeps<M> = {
223
+ readonly signal: NodeJS.Signals;
224
+ readonly msg: M;
223
225
  };
224
- type NodeSub<M> = NodeWsSub<M> | NodeTimerSub<M> | NodeSignalSub<M>;
225
- type AssertNodeSubIsSub<T extends Sub = NodeSub<unknown>> = T;
226
- type NodeWsRegistry = Map<SubId, WebSocket>;
227
226
  /**
228
- * The Ctx fields the node Subs depend on. A consumer's Ctx must extend this so
229
- * `node_ws` can register the live socket and Cmd handlers can reach it.
227
+ * A process-signal sub. Cleanup detaches the listener. Lets graceful shutdown
228
+ * be a real machine transition rather than an out-of-band `process.on` that the
229
+ * reducer can't see.
230
+ */
231
+ type NodeSignalSub<M> = Sub<"node_signal", NodeSignalDeps<M>>;
232
+ type NodeSub<M> = NodeWsSub | NodeTimerSub<M> | NodeSignalSub<M>;
233
+ /** The live `node_ws` sockets, keyed by each Sub's `deps.key`. */
234
+ type NodeWsRegistry = Map<string, WebSocket>;
235
+ /**
236
+ * The Ctx fields the `node_ws` runner depends on. A consumer's Ctx must extend
237
+ * this so the runner can register the live socket and Cmd handlers can reach
238
+ * it.
230
239
  *
231
240
  * Deliberately NOT parameterized by Msg: the registry holds raw `WebSocket`s,
232
- * and each Sub variant carries its own Msg-typed callbacks. Trip-wire: if a
233
- * future node Sub holds a Msg-typed callback on ctx, this becomes
234
- * `NodeSubscribeCtx<M>`.
241
+ * and the Msg-typed callbacks live in the {@link NodeWsHandlers} handed to
242
+ * `nodeSubscribe`. Trip-wire: if a future node Sub holds a Msg-typed callback
243
+ * on ctx, this becomes `NodeSubscribeCtx<M>`.
235
244
  */
236
245
  interface NodeSubscribeCtx {
237
246
  wsRegistry: NodeWsRegistry;
238
247
  }
239
248
  /**
240
- * Write a frame to a registered `node_ws` socket. No-op (returns `false`) when
241
- * the socket is absent, not OPEN, or `send()` throws. The Cmd-side companion to
242
- * the `node_ws` Sub: the Sub owns the socket's lifetime; this writes to it.
249
+ * Write a frame to the `node_ws` socket whose `deps.key` is `key`. No-op
250
+ * (returns `false`) when the socket is absent, not OPEN, or `send()` throws.
251
+ * The Cmd-side companion to the `node_ws` Sub: the Sub owns the socket's
252
+ * lifetime; this writes to it.
243
253
  *
244
254
  * The contract is a boolean no-op, never a throw: the socket can transition out
245
255
  * of OPEN between the `readyState` check and `send()` (or `ws` can throw on an
246
256
  * errored underlying connection), and a Cmd interpreter must not crash on that.
247
257
  */
248
- declare function sendToWebSocket(ctx: NodeSubscribeCtx, id: SubId, data: string): boolean;
258
+ declare function sendToWebSocket(ctx: NodeSubscribeCtx, key: string, data: string): boolean;
249
259
  /**
250
- * Build the `subscribe` handlers for `node_ws`, `node_timer`, and
251
- * `node_signal`. Matches `Machine#subscribe`'s
252
- * `[K in U["type"]]: (sub, ctx, dispatch) => () => void` contract for the
253
- * `NodeSub<M>` variants. Generic `Ctx` must extend `NodeSubscribeCtx` so the
254
- * `node_ws` handler can register its socket.
260
+ * What a `node_ws` socket's events become. Functions cannot be `deps`, so they
261
+ * live here, on the runner side; each receives the running Sub so one handler
262
+ * table can branch on `sub.deps` (its `key` or `url`) when a machine runs more
263
+ * than one socket.
264
+ *
265
+ * Only `onMessage` returns `M | null` (null drops the frame) because inbound
266
+ * frames are the boundary that needs a parse-and-maybe-discard seam. `onOpen`/
267
+ * `onClose`/`onError` always dispatch — a spurious one is dropped in the reducer
268
+ * (the cell ignores it), not here. An omitted one dispatches nothing.
255
269
  */
256
- declare function nodeSubscribe<M, Ctx extends NodeSubscribeCtx>(): {
257
- node_ws: (sub: NodeWsSub<M>, ctx: Ctx, dispatch: (msg: M) => void) => () => void;
258
- node_timer: (sub: NodeTimerSub<M>, ctx: Ctx, dispatch: (msg: M) => void) => () => void;
259
- node_signal: (sub: NodeSignalSub<M>, ctx: Ctx, dispatch: (msg: M) => void) => () => void;
260
- };
270
+ interface NodeWsHandlers<M> {
271
+ onMessage(data: string, sub: NodeWsSub): M | null;
272
+ onOpen?(sub: NodeWsSub): M;
273
+ onClose?(code: number, reason: string, sub: NodeWsSub): M;
274
+ onError?(message: string, sub: NodeWsSub): M;
275
+ }
276
+ /** The options of {@link nodeSubscribe}: the `node_ws` handlers, when used. */
277
+ interface NodeSubscribeOpts<M> {
278
+ readonly ws: NodeWsHandlers<M>;
279
+ }
280
+ /** The `node_timer` + `node_signal` runners — what every `nodeSubscribe` returns. */
281
+ interface NodeSubscribeBase<M> {
282
+ node_timer: (sub: NodeTimerSub<M>, ctx: unknown, dispatch: (msg: M) => void) => Dispose;
283
+ node_signal: (sub: NodeSignalSub<M>, ctx: unknown, dispatch: (msg: M) => void) => Dispose;
284
+ }
285
+ /** The full runner table, with `node_ws` — `nodeSubscribe({ ws })`. */
286
+ interface NodeSubscribeWithWs<M, Ctx extends NodeSubscribeCtx> extends NodeSubscribeBase<M> {
287
+ node_ws: (sub: NodeWsSub, ctx: Ctx, dispatch: (msg: M) => void) => Dispose;
288
+ }
289
+ /**
290
+ * Build the `subscribe` runners for the node Sub types, to hand to `run`:
291
+ * `run(machine, { subscribe: nodeSubscribe<M, Ctx>({ ws: { onMessage } }), ctx })`.
292
+ *
293
+ * `node_timer` and `node_signal` read everything off `sub.deps`, so they need
294
+ * no options. `node_ws` needs its {@link NodeWsHandlers}; called without them,
295
+ * the table has no `node_ws` runner, so a machine that declares `NodeWsSub`
296
+ * fails to typecheck at `run` rather than opening a socket nobody listens to.
297
+ * `Ctx` must extend {@link NodeSubscribeCtx} so the `node_ws` runner can
298
+ * register its socket.
299
+ */
300
+ declare function nodeSubscribe<M>(): NodeSubscribeBase<M>;
301
+ declare function nodeSubscribe<M, Ctx extends NodeSubscribeCtx>(opts: NodeSubscribeOpts<M>): NodeSubscribeWithWs<M, Ctx>;
261
302
 
262
- export { type AssertNodeSubIsSub, type FileStoreOptions, type NodeSignalSub, type NodeSub, type NodeSubscribeCtx, type NodeTimerSub, type NodeWsRegistry, type NodeWsSub, fileJournal, fileStore, nodeSubscribe, sendToWebSocket };
303
+ export { type FileStoreOptions, type NodeSignalDeps, type NodeSignalSub, type NodeSub, type NodeSubscribeBase, type NodeSubscribeCtx, type NodeSubscribeOpts, type NodeSubscribeWithWs, type NodeTimerDeps, type NodeTimerSub, type NodeWsDeps, type NodeWsHandlers, type NodeWsRegistry, type NodeWsSub, fileJournal, fileStore, nodeSubscribe, sendToWebSocket };
@@ -1,4 +1,5 @@
1
- import { StoreConflictError, dispatchIfPresent } from '../chunk-RQULHGYH.js';
1
+ import { dispatchIfPresent } from '../chunk-GOX2CYIM.js';
2
+ import { StoreConflictError } from '../chunk-CH5KTOEZ.js';
2
3
  import { mkdir, writeFile, rename, unlink, open, readFile } from 'fs/promises';
3
4
  import { createRequire } from 'module';
4
5
  import { dirname, join } from 'path';
@@ -238,8 +239,8 @@ function loadWebSocket() {
238
239
  }
239
240
  var WS_OPEN = 1;
240
241
  var WS_CLOSED = 3;
241
- function sendToWebSocket(ctx, id, data) {
242
- const socket = ctx.wsRegistry.get(id);
242
+ function sendToWebSocket(ctx, key, data) {
243
+ const socket = ctx.wsRegistry.get(key);
243
244
  if (!socket || socket.readyState !== WS_OPEN) return false;
244
245
  try {
245
246
  socket.send(data);
@@ -248,51 +249,64 @@ function sendToWebSocket(ctx, id, data) {
248
249
  return false;
249
250
  }
250
251
  }
251
- function nodeSubscribe() {
252
- return {
253
- node_ws: (sub, ctx, dispatch) => {
254
- const socket = new (loadWebSocket())(sub.url);
255
- ctx.wsRegistry.set(sub.id, socket);
256
- socket.on("open", () => {
257
- if (sub.onOpen) dispatch(sub.onOpen());
258
- });
259
- socket.on("message", (data) => {
260
- dispatchIfPresent(dispatch, sub.onMessage(data.toString()));
261
- });
262
- socket.on("close", (code, reason) => {
263
- if (sub.onClose) dispatch(sub.onClose(code, reason.toString()));
264
- });
265
- socket.on("error", (err) => {
266
- if (sub.onError) dispatch(sub.onError(err.message));
267
- });
268
- return () => {
269
- ctx.wsRegistry.delete(sub.id);
270
- socket.removeAllListeners();
271
- socket.on("error", () => {
272
- });
273
- if (socket.readyState === WS_OPEN) {
274
- socket.close(1e3, "tea-node sub cleanup");
275
- } else if (socket.readyState !== WS_CLOSED) {
276
- socket.terminate();
277
- }
278
- };
279
- },
252
+ function nodeSubscribe(opts) {
253
+ const base = {
280
254
  node_timer: (sub, _ctx, dispatch) => {
281
- if (sub.repeat) {
282
- const handle2 = setInterval(() => dispatch(sub.msg), sub.delayMs);
255
+ const { delayMs, msg, repeat } = sub.deps;
256
+ if (repeat) {
257
+ const handle2 = setInterval(() => dispatch(msg), delayMs);
283
258
  return () => clearInterval(handle2);
284
259
  }
285
- const handle = setTimeout(() => dispatch(sub.msg), sub.delayMs);
260
+ const handle = setTimeout(() => dispatch(msg), delayMs);
286
261
  return () => clearTimeout(handle);
287
262
  },
288
263
  node_signal: (sub, _ctx, dispatch) => {
289
- const handler = () => dispatch(sub.msg);
290
- process.on(sub.signal, handler);
264
+ const { signal, msg } = sub.deps;
265
+ const handler = () => dispatch(msg);
266
+ process.on(signal, handler);
291
267
  return () => {
292
- process.off(sub.signal, handler);
268
+ process.off(signal, handler);
293
269
  };
294
270
  }
295
271
  };
272
+ if (opts === void 0) return base;
273
+ return { ...base, node_ws: nodeWsRunner(opts.ws) };
274
+ }
275
+ function nodeWsRunner(handlers) {
276
+ return (sub, ctx, dispatch) => {
277
+ const { key, url } = sub.deps;
278
+ if (ctx.wsRegistry.has(key)) {
279
+ throw new Error(
280
+ `node_ws: a live socket is already registered under key "${key}" \u2014 each running node_ws Sub needs its own \`deps.key\`.`
281
+ );
282
+ }
283
+ const socket = new (loadWebSocket())(url);
284
+ ctx.wsRegistry.set(key, socket);
285
+ socket.on("open", () => {
286
+ if (handlers.onOpen) dispatch(handlers.onOpen(sub));
287
+ });
288
+ socket.on("message", (data) => {
289
+ dispatchIfPresent(dispatch, handlers.onMessage(data.toString(), sub));
290
+ });
291
+ socket.on("close", (code, reason) => {
292
+ if (handlers.onClose)
293
+ dispatch(handlers.onClose(code, reason.toString(), sub));
294
+ });
295
+ socket.on("error", (err) => {
296
+ if (handlers.onError) dispatch(handlers.onError(err.message, sub));
297
+ });
298
+ return () => {
299
+ ctx.wsRegistry.delete(key);
300
+ socket.removeAllListeners();
301
+ socket.on("error", () => {
302
+ });
303
+ if (socket.readyState === WS_OPEN) {
304
+ socket.close(1e3, "tea-node sub cleanup");
305
+ } else if (socket.readyState !== WS_CLOSED) {
306
+ socket.terminate();
307
+ }
308
+ };
309
+ };
296
310
  }
297
311
 
298
312
  export { fileJournal, fileStore, nodeSubscribe, sendToWebSocket };