@demlik/tea 0.6.0 → 0.8.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 (158) hide show
  1. package/dist/agent/index.d.ts +6 -5
  2. package/dist/agent/index.js +10 -10
  3. package/dist/authed-call/index.d.ts +2 -2
  4. package/dist/authed-call/index.js +7 -7
  5. package/dist/await-terminal/index.d.ts +3 -2
  6. package/dist/await-terminal/index.js +2 -2
  7. package/dist/batch-window/index.d.ts +4 -3
  8. package/dist/batch-window/index.js +3 -3
  9. package/dist/cache/index.d.ts +2 -2
  10. package/dist/cache/index.js +4 -4
  11. package/dist/chart/index.d.ts +217 -0
  12. package/dist/chart/index.js +16 -0
  13. package/dist/chart/index.js.map +1 -0
  14. package/dist/chart/inspect/index.d.ts +85 -0
  15. package/dist/chart/inspect/index.js +5 -0
  16. package/dist/chart/inspect/index.js.map +1 -0
  17. package/dist/chart/inspect/react.d.ts +112 -0
  18. package/dist/chart/inspect/react.js +11 -0
  19. package/dist/chart/inspect/react.js.map +1 -0
  20. package/dist/chart/inspect/styles.css +286 -0
  21. package/dist/chart/lane/index.d.ts +361 -0
  22. package/dist/chart/lane/index.js +9 -0
  23. package/dist/chart/lane/index.js.map +1 -0
  24. package/dist/chart/lane/react.d.ts +83 -0
  25. package/dist/chart/lane/react.js +559 -0
  26. package/dist/chart/lane/react.js.map +1 -0
  27. package/dist/chart/lane/styles.css +498 -0
  28. package/dist/chart/report/index.d.ts +116 -0
  29. package/dist/chart/report/index.js +32 -0
  30. package/dist/chart/report/index.js.map +1 -0
  31. package/dist/{chunk-2UGTDYOK.js → chunk-3JU6657S.js} +3 -3
  32. package/dist/{chunk-2UGTDYOK.js.map → chunk-3JU6657S.js.map} +1 -1
  33. package/dist/{chunk-AZ3NHUPD.js → chunk-4KTWLPL5.js} +3 -3
  34. package/dist/{chunk-AZ3NHUPD.js.map → chunk-4KTWLPL5.js.map} +1 -1
  35. package/dist/{chunk-ZH454CR5.js → chunk-5EHLEUTL.js} +24 -4
  36. package/dist/chunk-5EHLEUTL.js.map +1 -0
  37. package/dist/chunk-5KJKJOFC.js +758 -0
  38. package/dist/chunk-5KJKJOFC.js.map +1 -0
  39. package/dist/{chunk-WF46FABO.js → chunk-7SVIRMC6.js} +3 -3
  40. package/dist/{chunk-WF46FABO.js.map → chunk-7SVIRMC6.js.map} +1 -1
  41. package/dist/{chunk-XMHZ44QC.js → chunk-7V4EVLZA.js} +4 -4
  42. package/dist/{chunk-XMHZ44QC.js.map → chunk-7V4EVLZA.js.map} +1 -1
  43. package/dist/{chunk-IVHQCVFX.js → chunk-A56OR5RF.js} +3 -3
  44. package/dist/{chunk-IVHQCVFX.js.map → chunk-A56OR5RF.js.map} +1 -1
  45. package/dist/{chunk-O7ED34JH.js → chunk-B5VXOFMZ.js} +47 -15
  46. package/dist/chunk-B5VXOFMZ.js.map +1 -0
  47. package/dist/chunk-E6GEDSF4.js +307 -0
  48. package/dist/chunk-E6GEDSF4.js.map +1 -0
  49. package/dist/{chunk-EC6FO42Q.js → chunk-EUF7XOEE.js} +6 -6
  50. package/dist/{chunk-EC6FO42Q.js.map → chunk-EUF7XOEE.js.map} +1 -1
  51. package/dist/{chunk-XOAP3LOT.js → chunk-I5OV65MS.js} +3 -3
  52. package/dist/{chunk-XOAP3LOT.js.map → chunk-I5OV65MS.js.map} +1 -1
  53. package/dist/chunk-JER5O7PQ.js +416 -0
  54. package/dist/chunk-JER5O7PQ.js.map +1 -0
  55. package/dist/{chunk-ASX7PL2K.js → chunk-JGVL3WPL.js} +3 -3
  56. package/dist/{chunk-ASX7PL2K.js.map → chunk-JGVL3WPL.js.map} +1 -1
  57. package/dist/{chunk-S6Y3RNX4.js → chunk-JP5D6GSL.js} +4 -4
  58. package/dist/{chunk-S6Y3RNX4.js.map → chunk-JP5D6GSL.js.map} +1 -1
  59. package/dist/{chunk-ERYY5P6W.js → chunk-ND3DH6KM.js} +3 -3
  60. package/dist/{chunk-ERYY5P6W.js.map → chunk-ND3DH6KM.js.map} +1 -1
  61. package/dist/{chunk-A7USKARI.js → chunk-SUST46KO.js} +3 -3
  62. package/dist/{chunk-A7USKARI.js.map → chunk-SUST46KO.js.map} +1 -1
  63. package/dist/{chunk-2KBEIGYP.js → chunk-TP5UPGLY.js} +3 -3
  64. package/dist/{chunk-2KBEIGYP.js.map → chunk-TP5UPGLY.js.map} +1 -1
  65. package/dist/chunk-UOC2PL46.js +13 -0
  66. package/dist/chunk-UOC2PL46.js.map +1 -0
  67. package/dist/{chunk-66S2KEQQ.js → chunk-WLGO64WC.js} +4 -4
  68. package/dist/{chunk-66S2KEQQ.js.map → chunk-WLGO64WC.js.map} +1 -1
  69. package/dist/chunk-WRAA7GVZ.js +209 -0
  70. package/dist/chunk-WRAA7GVZ.js.map +1 -0
  71. package/dist/chunk-ZCL7SCBK.js +685 -0
  72. package/dist/chunk-ZCL7SCBK.js.map +1 -0
  73. package/dist/chunk-ZD6PNZBK.js +457 -0
  74. package/dist/chunk-ZD6PNZBK.js.map +1 -0
  75. package/dist/{chunk-UV7VCTNC.js → chunk-ZF6WDK2D.js} +7 -7
  76. package/dist/{chunk-UV7VCTNC.js.map → chunk-ZF6WDK2D.js.map} +1 -1
  77. package/dist/{core-CUN5HDKL.d.ts → core-Bjc0bS8j.d.ts} +22 -1
  78. package/dist/deadline/index.d.ts +2 -2
  79. package/dist/deadline/index.js +3 -3
  80. package/dist/devtools/index.js +2 -207
  81. package/dist/devtools/index.js.map +1 -1
  82. package/dist/do/index.d.ts +7 -6
  83. package/dist/do/index.js +10 -10
  84. package/dist/{durable-effects-CXMOi-sp.d.ts → durable-effects-D8SqU_if.d.ts} +1 -1
  85. package/dist/extension/index.d.ts +3 -2
  86. package/dist/extension/index.js +3 -3
  87. package/dist/extension/react.js +3 -3
  88. package/dist/extension/subs/index.d.ts +2 -2
  89. package/dist/fan-out/index.d.ts +3 -2
  90. package/dist/fold-Blbhru48.d.ts +435 -0
  91. package/dist/graph-CcjWZVrd.d.ts +923 -0
  92. package/dist/idempotent-intake/index.d.ts +3 -2
  93. package/dist/index.d.ts +5 -4
  94. package/dist/index.js +2 -2
  95. package/dist/llm-call/index.d.ts +2 -2
  96. package/dist/llm-call/index.js +7 -7
  97. package/dist/{machine-CoWpvp8x.d.ts → machine-0OmPvsy_.d.ts} +1 -1
  98. package/dist/machine-viz/index.d.ts +19 -2
  99. package/dist/machine-viz/index.js +4 -10
  100. package/dist/machine-viz/index.js.map +1 -1
  101. package/dist/mem/index.d.ts +3 -2
  102. package/dist/monitored-run/index.d.ts +4 -3
  103. package/dist/monitored-run/index.js +5 -5
  104. package/dist/node/index.d.ts +3 -2
  105. package/dist/paginated-walk/index.d.ts +2 -2
  106. package/dist/paginated-walk/index.js +7 -7
  107. package/dist/parity/index.d.ts +3 -2
  108. package/dist/parity/index.js +3 -3
  109. package/dist/pbt/arbitraries/index.d.ts +1 -1
  110. package/dist/pbt/index.d.ts +1 -1
  111. package/dist/pbt/index.js +3 -3
  112. package/dist/pbt/runners/index.d.ts +1 -1
  113. package/dist/pbt/runners/index.js +3 -3
  114. package/dist/poller/index.d.ts +28 -7
  115. package/dist/poller/index.js +3 -3
  116. package/dist/poller/index.js.map +1 -1
  117. package/dist/prediction/index.d.ts +1 -1
  118. package/dist/prediction/index.js +2 -2
  119. package/dist/pure/index.d.ts +1 -1
  120. package/dist/pure/index.js +2 -2
  121. package/dist/react/index.d.ts +3 -2
  122. package/dist/react/index.js +2 -2
  123. package/dist/reconciler/index.d.ts +2 -2
  124. package/dist/reconciler/index.js +7 -7
  125. package/dist/recorder/index.d.ts +3 -2
  126. package/dist/reducer-BqyoVyBG.d.ts +447 -0
  127. package/dist/resilient-call/index.d.ts +2 -2
  128. package/dist/resilient-call/index.js +6 -6
  129. package/dist/run-BVeqJDBF.d.ts +713 -0
  130. package/dist/{runtime-types-BD3ZFfdw.d.ts → runtime-types-Bxc637bp.d.ts} +53 -2
  131. package/dist/saga/index.d.ts +3 -2
  132. package/dist/samples-DCt6nF8H.d.ts +59 -0
  133. package/dist/snapshot/index.d.ts +1 -1
  134. package/dist/snapshot/index.js +3 -3
  135. package/dist/subs/index.d.ts +4 -3
  136. package/dist/subs/index.js +3 -3
  137. package/dist/testing/index.d.ts +3 -2
  138. package/dist/testing/index.js +2 -2
  139. package/dist/throttled-input/index.d.ts +2 -2
  140. package/dist/throttled-input/index.js +6 -6
  141. package/dist/token-refresh/index.d.ts +1 -1
  142. package/dist/token-refresh/index.js +3 -3
  143. package/dist/trace-replay/index.d.ts +3 -2
  144. package/dist/trace-replay/index.js +3 -3
  145. package/dist/{types-CjAkI83U.d.ts → types-D7u9DkH7.d.ts} +1 -1
  146. package/dist/with-deadline/index.d.ts +1 -1
  147. package/dist/with-deadline/index.js +2 -2
  148. package/dist/with-resilience/index.d.ts +2 -2
  149. package/dist/with-resilience/index.js +6 -6
  150. package/dist/with-telemetry/index.d.ts +1 -1
  151. package/dist/with-telemetry/index.js +2 -2
  152. package/dist/work-queue/adapter.d.ts +3 -2
  153. package/dist/work-queue/index.d.ts +3 -2
  154. package/dist/work-queue/ops.d.ts +3 -2
  155. package/dist/workflow/index.d.ts +3 -3
  156. package/package.json +31 -1
  157. package/dist/chunk-O7ED34JH.js.map +0 -1
  158. package/dist/chunk-ZH454CR5.js.map +0 -1
@@ -1,19 +1,20 @@
1
- import { C as Cmd } from '../core-CUN5HDKL.js';
1
+ import { C as Cmd } from '../core-Bjc0bS8j.js';
2
2
  export { LlmCall, LlmErr, LlmFailMsg, LlmOk, LlmRunCmd, LlmSucceedMsg, MessageLoader, ModelFactory, Schema } from '../llm-call/index.js';
3
- import { A as AgentTurn, a as AgentConfigCore, C as CompactionPolicy, b as AgentKnob } from '../machine-CoWpvp8x.js';
4
- export { c as AgentBootMsg, d as AgentCmd, e as AgentCompactErrMsg, f as AgentCompactOkMsg, g as AgentCompactRunCmd, h as AgentCompactionConfig, i as AgentConfig, j as AgentDetachedHandlers, k as AgentEvent, l as AgentFailure, m as AgentLlmErrMsg, n as AgentLlmOkMsg, o as AgentLlmRunCmd, p as AgentMachineMsg, q as AgentPorts, r as AgentSnapshotConfig, s as AgentState, t as AgentStatus, u as AgentTerminalFailure, v as AgentTimerMsg, w as AgentToMachine, x as Awaiting, y as COMPACTION_PURPOSE, z as CompactInterpret, B as CompactionOutputs, D as CompactionPurpose, E as CompactionSummary, F as Conversation, S as SnapshotInterpret, T as ToolCall, G as ToolOutcome, H as ToolRecord, I as agentBootMsg, J as agentEvents, K as agentTurnSchema, L as compactionSummarySchema, M as isAgentTurn, N as isCompactionSummary, O as liftAgent, P as mergeInterpret, Q as status } from '../machine-CoWpvp8x.js';
3
+ import { A as AgentTurn, a as AgentConfigCore, C as CompactionPolicy, b as AgentKnob } from '../machine-0OmPvsy_.js';
4
+ export { c as AgentBootMsg, d as AgentCmd, e as AgentCompactErrMsg, f as AgentCompactOkMsg, g as AgentCompactRunCmd, h as AgentCompactionConfig, i as AgentConfig, j as AgentDetachedHandlers, k as AgentEvent, l as AgentFailure, m as AgentLlmErrMsg, n as AgentLlmOkMsg, o as AgentLlmRunCmd, p as AgentMachineMsg, q as AgentPorts, r as AgentSnapshotConfig, s as AgentState, t as AgentStatus, u as AgentTerminalFailure, v as AgentTimerMsg, w as AgentToMachine, x as Awaiting, y as COMPACTION_PURPOSE, z as CompactInterpret, B as CompactionOutputs, D as CompactionPurpose, E as CompactionSummary, F as Conversation, S as SnapshotInterpret, T as ToolCall, G as ToolOutcome, H as ToolRecord, I as agentBootMsg, J as agentEvents, K as agentTurnSchema, L as compactionSummarySchema, M as isAgentTurn, N as isCompactionSummary, O as liftAgent, P as mergeInterpret, Q as status } from '../machine-0OmPvsy_.js';
5
5
  export { MonitoredRunCmd, RunFailure } from '../monitored-run/index.js';
6
6
  export { DeadlineSub, deadlineSub, subscribeDeadline } from '../deadline/index.js';
7
7
  import '../resilient-call/index.js';
8
8
  import '../cache/index.js';
9
- import '../types-CjAkI83U.js';
9
+ import '../types-D7u9DkH7.js';
10
10
  import '../circuit-breaker/index.js';
11
11
  import '../protocol-B5YmJr0d.js';
12
12
  import '../rate-limit/index.js';
13
13
  import '../retry-backoff/index.js';
14
14
  import '../fan-out/index.js';
15
15
  import '../work-queue/index.js';
16
- import '../runtime-types-BD3ZFfdw.js';
16
+ import '../runtime-types-Bxc637bp.js';
17
+ import 'better-result';
17
18
  import '../snapshot/index.js';
18
19
 
19
20
  /**
@@ -1,22 +1,22 @@
1
- export { COMPACTION_PURPOSE, agentBootMsg, agentEvents, agentTurnSchema, compactionSummarySchema, createAgent, isAgentTurn, isCompactionSummary, liftAgent, mergeInterpret, status } from '../chunk-UV7VCTNC.js';
2
- import '../chunk-66S2KEQQ.js';
3
- import '../chunk-ERYY5P6W.js';
4
- import '../chunk-XMHZ44QC.js';
5
- import '../chunk-EC6FO42Q.js';
1
+ export { COMPACTION_PURPOSE, agentBootMsg, agentEvents, agentTurnSchema, compactionSummarySchema, createAgent, isAgentTurn, isCompactionSummary, liftAgent, mergeInterpret, status } from '../chunk-ZF6WDK2D.js';
2
+ import '../chunk-WLGO64WC.js';
3
+ import '../chunk-ND3DH6KM.js';
4
+ import '../chunk-7V4EVLZA.js';
5
+ import '../chunk-EUF7XOEE.js';
6
6
  import '../chunk-JELSZN25.js';
7
7
  import '../chunk-D736QUGF.js';
8
- export { deadlineSub, subscribeDeadline } from '../chunk-ASX7PL2K.js';
8
+ export { deadlineSub, subscribeDeadline } from '../chunk-JGVL3WPL.js';
9
9
  import '../chunk-Q2UM7BXU.js';
10
10
  import '../chunk-S2EGRPCM.js';
11
11
  import '../chunk-UF4MZSLT.js';
12
- import '../chunk-WF46FABO.js';
12
+ import '../chunk-7SVIRMC6.js';
13
13
  import '../chunk-MU6MCIAC.js';
14
14
  import '../chunk-FV3Z5MBE.js';
15
- import '../chunk-2UGTDYOK.js';
15
+ import '../chunk-3JU6657S.js';
16
16
  import '../chunk-2YFLOCWX.js';
17
17
  import '../chunk-ZJ5AOYBH.js';
18
18
  import '../chunk-G5E74IJB.js';
19
- import '../chunk-ZH454CR5.js';
20
- import '../chunk-O7ED34JH.js';
19
+ import '../chunk-5EHLEUTL.js';
20
+ import '../chunk-B5VXOFMZ.js';
21
21
  //# sourceMappingURL=index.js.map
22
22
  //# sourceMappingURL=index.js.map
@@ -1,11 +1,11 @@
1
- import { P as PortEmitter, C as Cmd } from '../core-CUN5HDKL.js';
1
+ import { P as PortEmitter, C as Cmd } from '../core-Bjc0bS8j.js';
2
2
  import { M as MsgType } from '../protocol-B5YmJr0d.js';
3
3
  import { ResilientConfig, ResilientState, RunCmd, SucceedMsg, FailMsg, ResilientTimerMsg, ResilientPorts } from '../resilient-call/index.js';
4
4
  import { TokenRefreshConfig, Token, TokenState, RefreshTokenCmd, TokenRefreshMsg } from '../token-refresh/index.js';
5
5
  import { DeadlineSub } from '../deadline/index.js';
6
6
  export { DeadlineExceeded, deadlineSub, subscribeDeadline } from '../deadline/index.js';
7
7
  import '../cache/index.js';
8
- import '../types-CjAkI83U.js';
8
+ import '../types-D7u9DkH7.js';
9
9
  import '../circuit-breaker/index.js';
10
10
  import '../rate-limit/index.js';
11
11
  import '../retry-backoff/index.js';
@@ -1,16 +1,16 @@
1
- import { createTokenRefresh, refreshTokenCmd } from '../chunk-2KBEIGYP.js';
2
- import { createResilientCall } from '../chunk-EC6FO42Q.js';
1
+ import { createTokenRefresh, refreshTokenCmd } from '../chunk-TP5UPGLY.js';
2
+ import { createResilientCall } from '../chunk-EUF7XOEE.js';
3
3
  import '../chunk-JELSZN25.js';
4
- export { deadlineSub, subscribeDeadline } from '../chunk-ASX7PL2K.js';
4
+ export { deadlineSub, subscribeDeadline } from '../chunk-JGVL3WPL.js';
5
5
  import '../chunk-Q2UM7BXU.js';
6
6
  import '../chunk-S2EGRPCM.js';
7
7
  import '../chunk-UF4MZSLT.js';
8
- import '../chunk-WF46FABO.js';
9
- import '../chunk-2UGTDYOK.js';
8
+ import '../chunk-7SVIRMC6.js';
9
+ import '../chunk-3JU6657S.js';
10
10
  import '../chunk-2YFLOCWX.js';
11
11
  import '../chunk-ZJ5AOYBH.js';
12
- import '../chunk-ZH454CR5.js';
13
- import { without } from '../chunk-O7ED34JH.js';
12
+ import '../chunk-5EHLEUTL.js';
13
+ import { without } from '../chunk-B5VXOFMZ.js';
14
14
 
15
15
  // src/authed-call/index.ts
16
16
  function createAuthedCall(config, rng = Math.random) {
@@ -1,5 +1,6 @@
1
- import { R as Runtime, C as CtxArg } from '../runtime-types-BD3ZFfdw.js';
2
- import { C as Cmd, S as Sub, M as Machine } from '../core-CUN5HDKL.js';
1
+ import { R as Runtime, C as CtxArg } from '../runtime-types-Bxc637bp.js';
2
+ import { C as Cmd, S as Sub, M as Machine } from '../core-Bjc0bS8j.js';
3
+ import 'better-result';
3
4
 
4
5
  /**
5
6
  * @demlik/tea/await-terminal — run a ONE-SHOT / decision-procedure machine to a
@@ -1,5 +1,5 @@
1
- import { run } from '../chunk-ZH454CR5.js';
2
- import '../chunk-O7ED34JH.js';
1
+ import { run } from '../chunk-5EHLEUTL.js';
2
+ import '../chunk-B5VXOFMZ.js';
3
3
 
4
4
  // src/await-terminal/index.ts
5
5
  var TerminalTimeoutError = class extends Error {
@@ -1,9 +1,10 @@
1
- import { C as Cmd } from '../core-CUN5HDKL.js';
1
+ import { C as Cmd } from '../core-Bjc0bS8j.js';
2
2
  export { Debounced, debounce } from '../debounce/index.js';
3
3
  import { DeadlineExceeded, DeadlineSub } from '../deadline/index.js';
4
- import { S as SubscribeHandler } from '../types-CjAkI83U.js';
4
+ import { S as SubscribeHandler } from '../types-D7u9DkH7.js';
5
5
  export { EnqueueInput } from '../work-queue/index.js';
6
- import '../runtime-types-BD3ZFfdw.js';
6
+ import '../runtime-types-Bxc637bp.js';
7
+ import 'better-result';
7
8
 
8
9
  /**
9
10
  * @demlik/tea/batch-window — coalesce a stream of items into size- or
@@ -1,8 +1,8 @@
1
1
  export { debounce } from '../chunk-J6527VRQ.js';
2
- import { subscribeDeadline, deadlineExceeded, deadlineSub } from '../chunk-ASX7PL2K.js';
2
+ import { subscribeDeadline, deadlineExceeded, deadlineSub } from '../chunk-JGVL3WPL.js';
3
3
  import '../chunk-2YFLOCWX.js';
4
- import '../chunk-ZH454CR5.js';
5
- import '../chunk-O7ED34JH.js';
4
+ import '../chunk-5EHLEUTL.js';
5
+ import '../chunk-B5VXOFMZ.js';
6
6
 
7
7
  // src/batch-window/index.ts
8
8
  function initBatchWindow() {
@@ -1,5 +1,5 @@
1
- import { S as Sub } from '../core-CUN5HDKL.js';
2
- import { S as SubscribeHandler } from '../types-CjAkI83U.js';
1
+ import { S as Sub } from '../core-Bjc0bS8j.js';
2
+ import { S as SubscribeHandler } from '../types-D7u9DkH7.js';
3
3
 
4
4
  /**
5
5
  * @demlik/tea/cache — a TTL cache as pure state, PLUS a periodic eviction Sub.
@@ -1,8 +1,8 @@
1
- export { cacheEvictMsg, cacheEvictionSub, cacheEvictionSubscribe, evictExpired, get, has, initCache, remove, set } from '../chunk-WF46FABO.js';
2
- import '../chunk-2UGTDYOK.js';
1
+ export { cacheEvictMsg, cacheEvictionSub, cacheEvictionSubscribe, evictExpired, get, has, initCache, remove, set } from '../chunk-7SVIRMC6.js';
2
+ import '../chunk-3JU6657S.js';
3
3
  import '../chunk-2YFLOCWX.js';
4
4
  import '../chunk-ZJ5AOYBH.js';
5
- import '../chunk-ZH454CR5.js';
6
- import '../chunk-O7ED34JH.js';
5
+ import '../chunk-5EHLEUTL.js';
6
+ import '../chunk-B5VXOFMZ.js';
7
7
  //# sourceMappingURL=index.js.map
8
8
  //# sourceMappingURL=index.js.map
@@ -0,0 +1,217 @@
1
+ import { C as Cmd, T as Transitions, R as Reducer } from '../core-Bjc0bS8j.js';
2
+ import { A as Assigns, G as GuardName, l as Guards, U as UsedCmdName, m as Cmds, n as CellName, o as Cells, p as RAssigns, q as RGuardName, r as RGuards, s as RUsedCmdName, t as RCmds, u as RCellName, v as RCells, C as Chart, S as StateOf, M as MsgOf, a as CmdOf, j as MsgIn, R as ReducerChart, b as RStateOf, I as InitialData, f as InitialState } from '../graph-CcjWZVrd.js';
3
+ export { w as CmdEvent, x as CmdName, y as EdgeKey, z as EdgeSpec, B as EndPolarity, i as ErrorFinal, E as EventName, k as EventOrigin, F as ForeignEvent, D as GroupName, H as GroupOf, J as MissingPairs, O as OriginAt, P as ParkingState, K as RStateName, c as StateName, L as SubEvent, h as SuccessFinal, g as Ty, W as WorldEvent, N as WorldRole, Q as defineChart, V as defineReducerChart, X as ty } from '../graph-CcjWZVrd.js';
4
+
5
+ /**
6
+ * A cell returned a state OUTSIDE its edge's declared `to`.
7
+ *
8
+ * The escape hatch's bargain is that code may pick the target but only from the
9
+ * set the chart admits — otherwise the drawing stops being a truthful picture
10
+ * of the machine. For a SINGLE-site cell, and for the per-site form of a
11
+ * multi-site one, the clamp is a compile error and this never fires. For the
12
+ * function form of a MULTI-SITE cell it is the only enforcement there is: the
13
+ * return of one rest signature over a union of tuples cannot be made to depend
14
+ * on `at`, so the union of every site's `to` is the tightest static clamp
15
+ * available and this closes the difference at the moment it is violated.
16
+ *
17
+ * It sits inside `buildCell`, so BOTH chart forms — the grid and the reducer —
18
+ * get the same net from the same three lines.
19
+ */
20
+ declare class CellTargetError extends Error {
21
+ readonly at: string;
22
+ readonly cell: string;
23
+ readonly returned: string;
24
+ readonly declared: readonly string[];
25
+ readonly name = "CellTargetError";
26
+ readonly _tag: "CellTargetError";
27
+ constructor(at: string, cell: string, returned: string, declared: readonly string[]);
28
+ }
29
+ type Parts<C, S extends {
30
+ type: string;
31
+ }, M extends {
32
+ type: string;
33
+ }> = {
34
+ readonly assign: Assigns<C, S, M>;
35
+ } & ([GuardName<C>] extends [never] ? {
36
+ readonly guards?: undefined;
37
+ } : {
38
+ readonly guards: Guards<C, S, M>;
39
+ }) & ([UsedCmdName<C>] extends [never] ? {
40
+ readonly cmds?: undefined;
41
+ } : {
42
+ readonly cmds: Cmds<C, S, M>;
43
+ }) & ([CellName<C>] extends [never] ? {
44
+ readonly cells?: undefined;
45
+ } : {
46
+ readonly cells: Cells<C, S, M>;
47
+ });
48
+ /**
49
+ * Compile a chart + the code parts into a genuine `Transitions<S, M, C>`.
50
+ *
51
+ * `ns` is OPTIONAL and PER-EVENT. Omitted, nothing is decorated and the table
52
+ * is keyed by the bare event names — a single-instance machine carries no
53
+ * namespace and passes no dummy string. Given, the author's own events are
54
+ * keyed `${ns}.${event}` (so N instances share one dispatch surface with
55
+ * genuinely disjoint literal unions), while every event the chart marks
56
+ * `foreign: true` keeps its BARE name: a library-minted Msg like
57
+ * `deadline_exceeded` is the same event for every instance, and its name was
58
+ * never the author's to rename.
59
+ *
60
+ * The returned type is `Transitions<S, MsgIn<C, NS>, K>` — literal keys, never
61
+ * `string`. The parts are authored against the BARE msg union; the compiled
62
+ * cell restores the bare event name before calling them.
63
+ *
64
+ * `S`/`M`/`K` DEFAULT to the chart's own derivations, so the common call is
65
+ * `compile(chart, parts)` with no type arguments at all.
66
+ */
67
+ declare function compile<const C extends Chart<C>, S extends {
68
+ type: string;
69
+ } = StateOf<C>, M extends {
70
+ type: string;
71
+ } = MsgOf<C>, K extends Cmd = CmdOf<C>, const NS extends string | undefined = undefined>(chart: C, parts: Parts<C, S, M>, ns?: NS): Transitions<S, MsgIn<C, NS>, K>;
72
+ /**
73
+ * The reducer form's parts bag. Structurally identical to `Parts`, over the
74
+ * reducer chart's derivations — `assign` is total over the DECLARATIVE events
75
+ * (a cell event owes none), and each of `guards`/`cmds`/`cells` is demanded
76
+ * exactly when the chart names one.
77
+ */
78
+ type RParts<C, S extends {
79
+ type: string;
80
+ }, M extends {
81
+ type: string;
82
+ }> = {
83
+ readonly assign: RAssigns<C, S, M>;
84
+ } & ([RGuardName<C>] extends [never] ? {
85
+ readonly guards?: undefined;
86
+ } : {
87
+ readonly guards: RGuards<C, S, M>;
88
+ }) & ([RUsedCmdName<C>] extends [never] ? {
89
+ readonly cmds?: undefined;
90
+ } : {
91
+ readonly cmds: RCmds<C, S, M>;
92
+ }) & ([RCellName<C>] extends [never] ? {
93
+ readonly cells?: undefined;
94
+ } : {
95
+ readonly cells: RCells<C, S, M>;
96
+ });
97
+ /**
98
+ * Compile a reducer-form chart into a genuine `Reducer<S, M, K>` — the flat,
99
+ * msg-keyed `update` shape `defineMachine` already accepts (`src/pure/core.ts`).
100
+ *
101
+ * There is no `NoCellError` branch and no refusal branch here, and that is not
102
+ * an omission: `on` is a TOTAL mapped type over the event alphabet, so an
103
+ * undeclared event cannot exist to be missing. The safety the grid form buys
104
+ * with `scope` + `ignore` + `Total<C>`, this form gets from the mapped type.
105
+ *
106
+ * `ns` behaves exactly as in `compile`: per-event, optional, and never applied
107
+ * to an event the chart marks `foreign`.
108
+ */
109
+ declare function compileReducer<const C extends ReducerChart<C>, S extends {
110
+ type: string;
111
+ } = RStateOf<C>, M extends {
112
+ type: string;
113
+ } = MsgOf<C>, K extends Cmd = CmdOf<C>, const NS extends string | undefined = undefined>(chart: C, parts: RParts<C, S, M>, ns?: NS): Reducer<S, MsgIn<C, NS>, K>;
114
+ /**
115
+ * `init` for a reducer chart. The entry state is the chart's `initial` field —
116
+ * one word, still never repeated by the author — and `boot()` supplies `ctx`,
117
+ * which for this form IS the whole state minus its tag.
118
+ */
119
+ declare function reducerInitFrom<const C extends ReducerChart<C>, S extends {
120
+ type: string;
121
+ } = RStateOf<C>, K extends Cmd = CmdOf<C>>(chart: C, boot: () => Omit<RStateOf<C>, "type">): (loaded: S | null) => readonly [S, readonly K[]];
122
+ /**
123
+ * The reducer chart, drawn. There is no per-state routing to show, so the
124
+ * honest picture is one `any` node — every edge is reachable from every state,
125
+ * which is what having no phase dimension MEANS — plus each event's full
126
+ * fan-out, cell edges included.
127
+ */
128
+ declare function reducerMermaid<const C extends ReducerChart<C>>(chart: C): string;
129
+ /**
130
+ * The name of the state marked `initial: true`. Throws unless EXACTLY one is
131
+ * marked — the runtime half of what `InitialData`'s marker types say at the
132
+ * type level.
133
+ */
134
+ declare function initialStateOf<const C extends Chart<C>>(chart: C): InitialState<C>;
135
+ /**
136
+ * Build a `Machine["init"]` from the chart's declared entry state plus a
137
+ * `boot()` that supplies ONLY that state's data. The state NAME is never
138
+ * repeated by the author — it comes from the same `initial: true` that
139
+ * `machine-viz` reads to draw the `[*] -->` edge.
140
+ *
141
+ * Rehydrate is honoured verbatim: a non-null `loaded` is returned untouched
142
+ * with NO cmds, which is exactly Invariant 2's contract.
143
+ */
144
+ declare function initFrom<const C extends Chart<C>, S extends {
145
+ type: string;
146
+ }, K extends Cmd>(chart: C, boot: () => InitialData<C, S>): (loaded: S | null) => readonly [S, readonly K[]];
147
+ /** How many times each {@link edgeKey} was walked. */
148
+ type WalkCounts = ReadonlyMap<string, number>;
149
+ /**
150
+ * The key a {@link ChartMermaidOptions.walked} map is read by.
151
+ *
152
+ * One spelling, shared by whoever counts the walk and the drawing that marks
153
+ * it — the names are the chart's OWN, unsanitized, because the counter reads
154
+ * them off a log and has no business knowing what mermaid can spell.
155
+ *
156
+ * NOT `EdgeKey<C>` (`graph.ts`), despite the casing. That one is the SITE tag
157
+ * — `"state.event"` — which is what a guard or a cmd builder is keyed by,
158
+ * because a site is where code hangs. This one names a drawn ARROW, and a
159
+ * guarded site draws two of them, so it needs the target as well.
160
+ */
161
+ declare const edgeKey: (from: string, event: string, to: string) => string;
162
+ /**
163
+ * Options for {@link chartMermaid}. Every field is optional and every default
164
+ * reproduces the drawing this function emitted before options existed — a flat
165
+ * node set, `direction TB`, no title, no highlight, no polarity and no walk —
166
+ * so an existing caller is untouched.
167
+ *
168
+ * Shaped after `MachineVizOptions` (`../machine-viz`) where the two overlap
169
+ * (`direction`, `title`), because the two drawings are read side by side and a
170
+ * second spelling of the same knob is a fact said twice. What is NOT shared is
171
+ * `samples`: `toMermaid` needs them because it must EXECUTE a compiled cell to
172
+ * learn a target; the chart declares its targets, so there is nothing to
173
+ * resolve and nothing to sample.
174
+ */
175
+ interface ChartMermaidOptions {
176
+ /**
177
+ * Draw this state as the ACTIVE node — a `classDef`/`class` pair Mermaid
178
+ * renders with the highlight fill. Pass the live `state.type`. A name that is
179
+ * not in the chart is ignored rather than drawn as a phantom node.
180
+ */
181
+ readonly highlight?: string;
182
+ /**
183
+ * Draw each phase as a Mermaid COMPOSITE state (`state working { … }`).
184
+ *
185
+ * The chart groups its states into named phases and the flat drawing throws
186
+ * that away — which is the one structural fact `chartMermaid` knew and did
187
+ * not show. Off by default: turning it on changes the emitted text, and the
188
+ * drawing is something a reviewer approves rather than something that moves
189
+ * under them.
190
+ */
191
+ readonly phases?: boolean;
192
+ /**
193
+ * Draw the two ENDINGS differently — a dashed outline on every `end:
194
+ * "error"` final, a heavier one on every `end: true`.
195
+ *
196
+ * A success final and an error final both terminate, so both draw the `[*]`
197
+ * edge, and a picture that stopped there paints `shipped` and `frozen` alike
198
+ * in the one place a reader looks first. Off by default for the same reason
199
+ * `phases` is: it changes the emitted text.
200
+ */
201
+ readonly polarity?: boolean;
202
+ /**
203
+ * Edges the caller actually WALKED, keyed by {@link edgeKey} — each drawn
204
+ * edge that has a count picks up a `»` (or `»×N`) on its label.
205
+ *
206
+ * A missing or zero count marks nothing, so a chart nobody has run through
207
+ * draws exactly as it does without this option.
208
+ */
209
+ readonly walked?: WalkCounts;
210
+ /** Mermaid layout direction. Default `"TB"`. */
211
+ readonly direction?: "TB" | "LR";
212
+ /** Optional title, emitted as a Mermaid front-matter `title:` block. */
213
+ readonly title?: string;
214
+ }
215
+ declare function chartMermaid<const C extends Chart<C>>(chart: C, opts?: ChartMermaidOptions): string;
216
+
217
+ export { Assigns, CellName, CellTargetError, Cells, Chart, type ChartMermaidOptions, CmdOf, Cmds, GuardName, Guards, InitialState, MsgIn, MsgOf, type Parts, RAssigns, RCellName, RCells, RCmds, RGuardName, RGuards, type RParts, RStateOf, RUsedCmdName, ReducerChart, StateOf, UsedCmdName, type WalkCounts, chartMermaid, compile, compileReducer, edgeKey, initFrom, initialStateOf, reducerInitFrom, reducerMermaid };
@@ -0,0 +1,16 @@
1
+ export { CellTargetError, chartMermaid, compile, compileReducer, edgeKey, initFrom, initialStateOf, reducerInitFrom, reducerMermaid } from '../chunk-E6GEDSF4.js';
2
+ import '../chunk-UOC2PL46.js';
3
+ import '../chunk-B5VXOFMZ.js';
4
+
5
+ // src/chart/graph.ts
6
+ var ty = () => ({});
7
+ function defineChart(c) {
8
+ return c;
9
+ }
10
+ function defineReducerChart(c) {
11
+ return c;
12
+ }
13
+
14
+ export { defineChart, defineReducerChart, ty };
15
+ //# sourceMappingURL=index.js.map
16
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/chart/graph.ts"],"names":[],"mappings":";;;;;AAgCO,IAAM,EAAA,GAAK,OAAiB,EAAC;AAmpB7B,SAAS,YACd,CAAA,EACG;AACH,EAAA,OAAO,CAAA;AACT;AA+lBO,SAAS,mBACd,CAAA,EACG;AACH,EAAA,OAAO,CAAA;AACT","file":"index.js","sourcesContent":["// ═══════════════════════════════════════════════════════════════════════════\n// TYPE MACHINERY — everything in this file is erased at runtime.\n//\n// ONE CHART, ONE SITE PER FACT.\n//\n// The chart is a single value with four sections. Each fact is DECLARED in\n// exactly one of them and everything else is derived:\n//\n// ctx — the data every state carries. (1 site)\n// events — the alphabet: name, payload, SCOPE and ORIGIN. (1 site)\n// cmds — the effect alphabet: name and payload. (1 site)\n// states — states grouped into named PHASES, each with its edges. (1 site)\n//\n// The Msg union, the State union, the Cmd union, the guard signatures, the cmd\n// builder signatures, the `was` field on parking states, the entry state and\n// the totality obligation are all DERIVED from that one value. Nothing in the\n// author's file names a state, an event or a cmd twice as a *declaration*; the\n// only repeats are *references* (an edge naming its target, an `assign` key\n// naming the edge it implements), which are the facts themselves.\n// ═══════════════════════════════════════════════════════════════════════════\nimport type { Cmd } from \"../pure/core\";\n\n// ── 0. the phantom-type carrier ────────────────────────────────────────────\n/**\n * A type smuggled through a value position. `ty<{ at: number }>()` is an empty\n * object at runtime whose TYPE remembers `{ at: number }` — which is what lets\n * an event declare its payload IN the chart instead of in a parallel type map\n * the author has to keep in step.\n */\nexport interface Ty<T> {\n readonly __ty: T;\n}\nexport const ty = <T>(): Ty<T> => ({}) as unknown as Ty<T>;\n\n/** `Ty<T>` → `T`; anything else (an absent `data`) → the neutral `unknown`. */\ntype Payload<X> = X extends Ty<infer T> ? T : unknown;\n\n// ── 1. section accessors ───────────────────────────────────────────────────\ntype EvMap<C> = C extends { readonly events: infer E } ? E : never;\ntype CmdMap<C> = C extends { readonly cmds: infer M }\n ? M\n : Record<never, never>;\ntype Groups<C> = C extends { readonly states: infer G } ? G : never;\ntype CtxOf<C> = C extends { readonly ctx: infer T } ? Payload<T> : unknown;\n\nexport type EventName<C> = Extract<keyof EvMap<C>, string>;\nexport type CmdName<C> = Extract<keyof CmdMap<C>, string>;\n/** The named phases — `keyof states`. A group name is declared by BEING a key. */\nexport type GroupName<C> = Extract<keyof Groups<C>, string>;\n\nexport type StateName<C> = Extract<\n { [G in keyof Groups<C>]: keyof Groups<C>[G] }[keyof Groups<C>],\n string\n>;\n\n/** The node for state `S`, found by scanning the groups. Groups partition. */\ntype NodeAt<C, S> = {\n [G in keyof Groups<C>]: S extends keyof Groups<C>[G]\n ? Groups<C>[G][S]\n : never;\n}[keyof Groups<C>];\n\n/** The phase `S` lives in. A union here means `S` was declared twice. */\nexport type GroupOf<C, S> = Extract<\n {\n [G in keyof Groups<C>]: S extends keyof Groups<C>[G] ? G : never;\n }[keyof Groups<C>],\n string\n>;\n\n// naked-parameter helpers: a conditional distributes only over a bare `X`.\ntype OnOf<X> = X extends { readonly on: infer O } ? O : Record<never, never>;\ntype IgnoreOf<X> = X extends { readonly ignore: readonly (infer I)[] }\n ? Extract<I, string>\n : never;\ntype DataOf<X> = X extends { readonly data: infer D } ? Payload<D> : unknown;\n// A final is a final whatever its POLARITY: `end: true` (success) and\n// `end: \"error\"` (the failure terminal) are both \"accepts nothing, owes\n// nothing\". Every rule that keys off finality — `MissingAt`'s exemption,\n// `Total`'s `__endStateCannotDeclareEdges` — must therefore read BOTH, or an\n// error final silently regains the totality obligation a success final is\n// excused from and regains the right to declare edges.\ntype IsEndOf<X> = X extends { readonly end: true | \"error\" } ? true : false;\ntype IsInitialOf<X> = X extends { readonly initial: true } ? true : false;\ntype IsForeignOf<X> = X extends { readonly foreign: true } ? true : false;\ntype ScopeOf<X> = X extends { readonly scope: infer S }\n ? S extends readonly string[]\n ? S[number]\n : S\n : never;\n\ntype On<C, S> = OnOf<NodeAt<C, S>>;\ntype IgnoredAt<C, S> = IgnoreOf<NodeAt<C, S>>;\n\n// ── 2. the edge shape ──────────────────────────────────────────────────────\n/** A cmd reference on an edge: one declared name, or an ORDERED list of them. */\nexport type CmdRef<N extends string> = N | readonly N[];\n\nexport type EdgeSpec<SN extends string, CN extends string> =\n | SN\n // ── THE ESCAPE HATCH ────────────────────────────────────────────────────\n // The author declares the SET of reachable targets; a hand-written cell\n // picks one at runtime and returns `[state, cmds]` itself. Everything the\n // chart is for is still declared here — `to` is the fan-out `machine-viz`\n // draws and the union the cell's return type is clamped to — and the one\n // thing the chart genuinely cannot know (WHICH of them, this time) is the\n // only thing left in code.\n | { readonly to: readonly SN[]; readonly cell: string }\n | { readonly target: SN; readonly cmd?: CmdRef<CN> }\n | {\n readonly target: SN;\n readonly when: string;\n readonly otherwise: SN;\n /** Fires only when the guard HOLDS. */\n readonly cmd?: CmdRef<CN>;\n /** Fires only when the guard FAILS — `Cmd.when` lifted onto the edge. */\n readonly otherwiseCmd?: CmdRef<CN>;\n }\n | { readonly resume: { readonly fallback: SN }; readonly cmd?: CmdRef<CN> };\n\n// ── 3. SCOPE — the answer to the |S| × |M| enumeration problem ─────────────\n//\n// The old design made every state list the events it deliberately drops. That\n// is correct and it scales as |S| × |M|: 30 states × 12 events is ~300 hand-\n// typed strings, which the author produces by pasting the tsc error back.\n//\n// The fact being written 300 times is really |M| facts, one per event: WHERE\n// DOES THIS EVENT MEAN ANYTHING? So it is declared once, on the event, as its\n// `scope` — a dial with three settings:\n//\n// \"edges\" — targeted. Live exactly where it is routed; everywhere else it\n// is not \"ignored\", it is simply not addressed to that state.\n// Obligation: none. Cost: one word.\n// <phase> — broadcast within a phase (or a list of phases). Every state in\n// that phase must handle it or `ignore` it BY NAME. Adding a\n// state to the phase turns that state red, naming the pair.\n// \"all\" — broadcast machine-wide. Every state must decide. This is the\n// old behaviour, still available, now opt-in per event.\n//\n// Totality is unchanged in form: a pair that is neither handled nor covered by\n// a decision fails to compile, naming the pair. What changed is that the\n// decision may be QUANTIFIED (one word, on the event) instead of ENUMERATED\n// (one string per cell). See `.decisions` note in the report: forcing a\n// per-pair reconsideration on every new event *requires* |S| × |M| author-owned\n// sites — that is the one thing the two goals genuinely trade against.\n\n// ── 3a. FROM — where the Msg comes from ────────────────────────────────────\n//\n// A chart says `WIP: \"build\"` — an edge from an event to a target. It never\n// said where the event COMES FROM, and that absence is not a small one: in TEA\n// a Msg has exactly three origins and no fourth,\n//\n// a Cmd's result — the machine asked, and this is the answer coming back\n// a Sub firing — a source the machine subscribed to, speaking unprompted\n// the outside world — someone who is not this machine, acting\n//\n// so \"what is this state waiting on\" is answerable from the chart alone, once\n// the chart carries the fact. Before it did, every reader that wanted the\n// answer reconstructed it by matching STATE NAMES against a list of its\n// consumer's own — which is a second declaration site for a fact the event\n// owns, and it went stale the moment the consumer renamed a state.\n//\n// THE THIRD ORIGIN IS PARAMETERISED, and that is the whole reason this\n// generalises past any one consumer. \"The outside world\" alone cannot tell an\n// operator from a human from a webhook, and those roles are the CONSUMER's —\n// fabrika's operator, a checkout's shopper, an ops tool's on-call. So the world\n// origin carries a role NAME the consumer chooses, and this file enumerates\n// none of them. What is closed is the taxonomy (three origins, from TEA); what\n// is open is the cast (any role, from whoever is writing the chart).\n//\n// The role is a free noun phrase rather than a bare noun deliberately: a reader\n// renders it in a sentence, and only the consumer knows whether its role is\n// definite (\"the operator\" — there is one) or indefinite (\"a human\" — any of\n// them). An enum of nouns would put that article in OUR source, which is the\n// same mistake one level down.\n\n/**\n * Where an event's Msg comes from. TEA's own taxonomy, and no wider:\n *\n * `\"cmd\"` — a Cmd's result.\n * `\"sub\"` — a Sub firing.\n * `{ world: <role> }` — the outside world, through the role the CONSUMER\n * names. `{ world: \"the operator\" }`, `{ world: \"a\n * human\" }` — this file knows no role names.\n *\n * Written as one exported alias and used at the declaration site too, unlike\n * `scope` (which is spelled out inline so tsc prints the chart's own phase\n * names and offers \"Did you mean …?\" against them). There is nothing chart-\n * specific to print here — the alphabet is closed, universal and three members\n * long — so the alias name in the diagnostic costs nothing and the one-site\n * rule wins.\n */\nexport type EventOrigin = \"cmd\" | \"sub\" | { readonly world: string };\n\n/** The `from` field AS DECLARED — before the authored/fallback test. */\ntype FromOf<X> = X extends { readonly from: infer F } ? F : never;\ntype WorldRoleOf<F> = F extends { readonly world: infer R } ? R : never;\n\n/**\n * Is this event's `from` something the AUTHOR wrote, or is it tsc's fallback?\n *\n * `IsAuthoredScope`'s test, applied to this field's shape. When some OTHER\n * error in the literal defeats inference of `C`, tsc falls back to the\n * `Chart<C>` constraint, where `from` is the whole `EventOrigin` union — a\n * union MIXING a word with an object, which no literal can produce. An author's\n * `from` is either a word (`\"cmd\"`) or a `{ world }` with a LITERAL role; a\n * bare `string` role is not authorable as a declaration either, so it keeps the\n * same reading of \"no declaration\".\n */\ntype IsAuthoredFrom<X, F = FromOf<X>> = [F] extends [string]\n ? [string] extends [F]\n ? false\n : true\n : [F] extends [{ readonly world: string }]\n ? [string] extends [WorldRoleOf<F>]\n ? false\n : true\n : false;\n\n/** Event `E`'s declared origin, once it is established that it IS a declaration. */\nexport type OriginAt<C, E extends keyof EvMap<C>> = [\n IsAuthoredFrom<EvMap<C>[E]>,\n] extends [true]\n ? FromOf<EvMap<C>[E]>\n : never;\n\n/**\n * The events whose declared origin is exactly `O`.\n *\n * The `[never] extends [O]` arm comes FIRST and is not optional: an event with\n * no `from` has `OriginAt` `never`, and `[never] extends [\"cmd\"]` is TRUE — so\n * without it an undeclared event would be classified as every origin at once,\n * which is the loudest possible way to turn \"the chart does not say\" into a\n * confident wrong answer.\n */\ntype EventsFrom<C, O> = Extract<\n {\n [E in EventName<C>]: [OriginAt<C, E>] extends [never]\n ? never\n : [OriginAt<C, E>] extends [O]\n ? E\n : never;\n }[EventName<C>],\n string\n>;\n\n/** The events the chart says are a Cmd's result. */\nexport type CmdEvent<C> = EventsFrom<C, \"cmd\">;\n\n/** The events the chart says a Sub fires. */\nexport type SubEvent<C> = EventsFrom<C, \"sub\">;\n\n/** The events the chart attributes to a named outside-world role. */\nexport type WorldEvent<C> = Extract<\n {\n [E in EventName<C>]: [WorldRoleOf<OriginAt<C, E>>] extends [never]\n ? never\n : E;\n }[EventName<C>],\n string\n>;\n\n/** The role `E` is attributed to — `never` for a `cmd`/`sub`/undeclared event. */\nexport type WorldRole<C, E extends keyof EvMap<C>> = Extract<\n WorldRoleOf<OriginAt<C, E>>,\n string\n>;\n\n/** The `scope` field AS DECLARED — before the list is flattened to its members. */\ntype ScopeDeclOf<X> = X extends { readonly scope: infer S } ? S : never;\ntype ScopeElems<S> = S extends readonly (infer T)[] ? T : S;\n\n/**\n * Is this event's `scope` something the AUTHOR wrote, or is it tsc's fallback?\n *\n * When some OTHER error in the chart literal (a typo'd target, say) defeats\n * inference of `C`, tsc falls back to the `Chart<C>` constraint, where `scope`\n * is the whole `\"edges\" | \"all\" | GroupName<C> | readonly (…)[]` universe. Left\n * alone that makes every event look live in every phase and buries the one real\n * diagnostic under a wall of spurious unhandled-pair demands.\n *\n * The fallback is recognised BY ITS SHAPE, not by what it happens to cover: it\n * is the one form that is a union MIXING a string with a list, which no literal\n * can produce. An author's scope is either a word (`\"all\"`) or a list\n * (`[\"edges\", \"p\"]`) — never both at once.\n *\n * The older test — \"a scope that spans the entire universe is no scope\" — was a\n * proxy for this, and it misfired on the genuinely authored `[\"edges\",\"all\",\"p\"]`:\n * the type layer read it as NO scope (so `MissingPairs<C>` was `never` and the\n * chart looked total) while `compile`'s `scopeList(…).includes(\"all\")` read it as\n * live everywhere and threw `NoCellError` on the first msg. Testing the shape\n * instead makes the two layers agree by construction.\n *\n * A `string`-typed (non-literal) scope is also not authorable as a decision, so\n * it keeps the old reading of \"no scope\".\n */\ntype IsAuthoredScope<X, S = ScopeDeclOf<X>> = [S] extends [string]\n ? [string] extends [S]\n ? false\n : true\n : [S] extends [readonly string[]]\n ? [string] extends [ScopeElems<S>]\n ? false\n : true\n : false;\n\n/** The event's declared scope, once it is established that it IS a declaration. */\ntype ScopeAt<C, E extends keyof EvMap<C>> = [\n IsAuthoredScope<EvMap<C>[E]>,\n] extends [true]\n ? ScopeOf<EvMap<C>[E]>\n : never;\n\n/** The events that are LIVE at `S` — i.e. that `S` owes a decision about. */\ntype LiveAt<C, S> = {\n [E in EventName<C>]: \"all\" extends ScopeAt<C, E>\n ? E\n : [GroupOf<C, S>] extends [ScopeAt<C, E>]\n ? E\n : never;\n}[EventName<C>];\n\n/** Pairs at `S` that are live, unhandled and unrefused. Empty = total. */\nexport type MissingAt<C, S> = [IsEndOf<NodeAt<C, S>>] extends [true]\n ? never\n : Exclude<LiveAt<C, S>, Extract<keyof On<C, S>, string> | IgnoredAt<C, S>>;\n\n/** Every unhandled pair in the whole chart — `never` when the chart is total. */\nexport type MissingPairs<C> = {\n [S in StateName<C>]: `${S}.${Extract<MissingAt<C, S>, string>}`;\n}[StateName<C>];\n\n// ── 4. the chart shape (F-bounded: every reference checked against itself) ──\nexport type Chart<C> = {\n /** Data EVERY state carries. Declared once; intersected into all of them. */\n readonly ctx?: Ty<object>;\n readonly events: {\n readonly [E in keyof EvMap<C>]: {\n readonly data?: Ty<object>;\n /**\n * \"This name is not mine.\" The Msg is minted by SOMEONE ELSE — a library\n * Sub (`@demlik/tea/deadline` dispatching `deadline_exceeded`), a host\n * bridge, another machine — so the author cannot rename it and the\n * compiler must not decorate it. A foreign event keeps its BARE name in\n * the emitted table under every namespace, which is what makes it the\n * same event across all N instances. Everything else — payload, `scope`,\n * totality, edges — is unchanged: it is a normal event that happens to\n * belong to someone else.\n */\n readonly foreign?: true;\n /**\n * WHERE THIS MSG COMES FROM — see {@link EventOrigin} and §3a.\n *\n * Optional, and its absence means exactly \"the chart does not say\",\n * never a default: a chart that declares no `from` behaves as it always\n * did, and a reader that wants the answer must degrade honestly rather\n * than guess. It composes with everything else on the event — `scope`\n * answers WHERE the event is live, `data` WHAT it carries, `foreign`\n * WHOSE NAME it is, and this WHO SENT IT — and none of the four is\n * derivable from another.\n */\n readonly from?: EventOrigin;\n // written out rather than aliased: tsc prints the alias NAME in the\n // diagnostic, and the author needs to see the phase names themselves\n // (and get tsc's \"Did you mean …?\" against them).\n readonly scope:\n | \"edges\"\n | \"all\"\n | GroupName<C>\n | readonly (\"edges\" | \"all\" | GroupName<C>)[];\n };\n };\n readonly cmds?: { readonly [N in keyof CmdMap<C>]: Ty<object> };\n readonly states: {\n readonly [G in keyof Groups<C>]: {\n readonly [S in keyof Groups<C>[G]]: {\n /** Exactly one state in a machine-bearing chart marks itself the entry. */\n readonly initial?: true;\n /** Extra data only THIS state carries, on top of `ctx`. */\n readonly data?: Ty<object>;\n readonly on?: {\n readonly [E in EventName<C>]?: EdgeSpec<StateName<C>, CmdName<C>>;\n };\n /** Per-state exception: refuse a live event by name. */\n readonly ignore?: readonly EventName<C>[];\n /**\n * Terminal, and WITH WHICH POLARITY.\n *\n * `true` is the success final — the meaning it has always had, so every\n * chart written before this field widened is unchanged. `\"error\"` is\n * the failure final: the state a guarded edge falls through to when its\n * guard is spent (`frozen`, `tripped`), which a driver reads to trip the\n * whole run rather than to call it done.\n *\n * Both are finals in every structural sense — no obligations, no edges.\n * The difference is not \"is this the end\" but \"which end\", and it is\n * declared here because it is a fact ABOUT THE STATE, not a fact about\n * the one edge that happens to reach it.\n */\n readonly end?: true | \"error\";\n };\n };\n };\n};\n\n// ── 5. the strictness layers that assignability alone does not buy ─────────\n//\n// Constraint checking is plain assignability — it does NOT run excess-property\n// checks — so `{ target, whn, otherwise }` structurally satisfies\n// `{ target: SN; cmd?: … }` and a typo'd `when` would silently drop the guard,\n// and a typo'd EVENT key in `on` would silently invent an edge for an event\n// that does not exist. These map the offending shape to a marker object naming\n// the offender, which the object-literal check then rejects.\ntype KnownEdgeField =\n | \"target\"\n | \"cmd\"\n | \"otherwiseCmd\"\n | \"when\"\n | \"otherwise\"\n | \"resume\"\n | \"to\"\n | \"cell\";\n\n/**\n * A cell edge OWNS its transition end to end — it picks the target and returns\n * its own cmds. So every declarative field that would also decide one of those\n * is illegal ALONGSIDE it, rather than silently ignored by the walk:\n *\n * `cmd`/`otherwiseCmd` — the cell already returns the cmd list (req. 4)\n * `when`/`otherwise` — the cell already chose (a guard would choose twice)\n * `target`/`resume` — same fact as `to`, said a second way\n *\n * The `assign` bypass (req. 6) is caught one level up: `Assigns` is keyed by\n * `EdgeKey` MINUS the cell edges, so writing `\"polling.poll_failed\"` in the\n * assign bag of a cell edge is an excess property, named by tsc.\n */\ntype CellFieldConflict =\n | \"target\"\n | \"cmd\"\n | \"otherwiseCmd\"\n | \"when\"\n | \"otherwise\"\n | \"resume\";\n\n/**\n * A resume edge OWNS its transition the same way a cell edge does: the target\n * is `st.was ?? fallback`, which is neither declared nor chosen by a guard. So\n * every field that would ALSO decide the target is illegal alongside it, rather\n * than accepted and then skipped by the walk — `buildCell` tests `edge.resume`\n * first, so a `when` beside it is a guard the author writes, maintains and\n * reads as load-bearing, and which is never once called.\n *\n * `cmd` is absent from this list deliberately: `EdgeSpec` admits `{ resume, cmd }`\n * and the walk fires it, so it is a real, working field on a resume edge.\n * `to`/`cell` are absent because `CellCheck` already names that conflict.\n */\ntype ResumeFieldConflict = \"target\" | \"when\" | \"otherwise\" | \"otherwiseCmd\";\n\ntype ResumeCheck<X> = X extends { readonly resume: unknown }\n ? [Extract<keyof X, ResumeFieldConflict>] extends [never]\n ? unknown\n : {\n readonly __resumeEdgeCannotAlsoDeclare: Extract<\n keyof X,\n ResumeFieldConflict\n >;\n }\n : unknown;\n\n/**\n * `when` and `otherwise` are ONE fact — \"this edge branches\" — written in two\n * halves, and half of it is not a decision, it is a hole.\n *\n * The two layers used to key the `{ then, else }` assign shape off different\n * halves: `Cell<C, X, …>` off `X extends { target; otherwise }`, `buildCell`\n * off `edge.when !== undefined`. Omit either field and they picked opposite\n * shapes — the chart compiled and then died with `payloadFn is not a function`\n * on the first message. Both layers now read `when`, and this makes the two\n * halves inseparable, so there is no shape left on which they could disagree.\n */\ntype GuardPairCheck<X> = X extends { readonly when: string }\n ? X extends { readonly otherwise: unknown }\n ? unknown\n : { readonly __whenNeedsAnOtherwiseTarget: true }\n : X extends { readonly otherwise: unknown }\n ? { readonly __otherwiseNeedsAWhenGuard: true }\n : unknown;\n\ntype CellCheck<X> = X extends { readonly cell: string }\n ? X extends { readonly to: readonly unknown[] }\n ? [Extract<keyof X, CellFieldConflict>] extends [never]\n ? unknown\n : {\n readonly __cellEdgeCannotAlsoDeclare: Extract<\n keyof X,\n CellFieldConflict\n >;\n }\n : { readonly __cellEdgeMustDeclareItsTargetsInTo: true }\n : X extends { readonly to: readonly unknown[] }\n ? { readonly __toWithoutACellToPickFromIt: true }\n : unknown;\n\ntype EdgeCheck<X> = X extends string\n ? unknown\n : [Exclude<keyof X, KnownEdgeField>] extends [never]\n ? CellCheck<X> &\n ResumeCheck<X> &\n GuardPairCheck<X> &\n // `otherwiseCmd` is meaningless without a guard to have an \"otherwise\":\n // it would sit on an unguarded edge and silently never fire.\n (X extends { readonly otherwiseCmd: unknown }\n ? X extends { readonly when: string }\n ? unknown\n : { readonly __otherwiseCmdWithoutAGuard: true }\n : unknown)\n : { readonly __edgeHasUnknownField: Exclude<keyof X, KnownEdgeField> };\n\n// ── unknown KEYS, at every level of the literal ────────────────────────────\n//\n// The same hole `KnownEdgeField` closes on an edge exists at the three levels\n// above it, and for the same reason: constraint checking is plain assignability\n// and `C` is inferred FROM the literal, so the literal's own typo is part of the\n// type it is checked against and excess-property checking has nothing to fire\n// on. `cxt: ty<…>()` was therefore a chart with no `ctx` — `CtxOf<C>` fell back\n// to `unknown`, `StateOf<C>` collapsed to bare `{ type }`, and every `assign`\n// builder was left owing nothing. The chart enforced LESS than a hand-written\n// table. Same shape for `foriegn` (the library event gets namespaced — exactly\n// what `foreign: true` exists to prevent), `dta`, `intial`, `evnets`.\n//\n// So: one rule per level, naming the offending key, the way the edge level does.\ntype KnownChartField = \"ctx\" | \"events\" | \"cmds\" | \"states\";\ntype KnownEventField = \"data\" | \"foreign\" | \"scope\" | \"from\";\ntype KnownNodeField = \"initial\" | \"data\" | \"on\" | \"ignore\" | \"end\";\n\ntype UnknownKeys<X, Known extends string> = Exclude<keyof X, Known>;\n\n/**\n * The `{ world }` form's own unknown-key rule — the same hole one level down.\n *\n * `EventCheck` names a typo'd key ON the event (`frm`), but the world origin is\n * an object of its own and constraint checking runs no excess-property check\n * inside it either: `{ world: \"a human\", role: \"reviewer\" }` structurally\n * satisfies `{ world: string }`, so a second field would be accepted and then\n * silently dropped by every reader. A role is ONE fact and it is `world`.\n */\ntype FromCheck<X> = X extends { readonly from: infer F }\n ? [F] extends [string]\n ? unknown\n : [Exclude<keyof F, \"world\">] extends [never]\n ? unknown\n : { readonly __fromWorldCannotAlsoDeclare: Exclude<keyof F, \"world\"> }\n : unknown;\n\ntype EventCheck<X> = ([UnknownKeys<X, KnownEventField>] extends [never]\n ? unknown\n : { readonly __eventHasUnknownField: UnknownKeys<X, KnownEventField> }) &\n FromCheck<X>;\n\ntype NodeCheck<N> = [UnknownKeys<N, KnownNodeField>] extends [never]\n ? unknown\n : { readonly __stateNodeHasUnknownField: UnknownKeys<N, KnownNodeField> };\n\ntype StrictNode<C, N> = NodeCheck<N> & {\n readonly on?: {\n readonly [E in keyof OnOf<N>]: E extends EventName<C>\n ? EdgeCheck<OnOf<N>[E]>\n : { readonly __onDeclaresAnUndeclaredEvent: E };\n };\n};\n\n// ── the DEGENERACY guard ───────────────────────────────────────────────────\n//\n// Every derivation in this file is a union of LITERALS. One computed key whose\n// type is the bare `string` —\n//\n// const prefix = \"a\" as string;\n// states: { only: { [prefix]: { … } } }\n//\n// — gives `states.only` an index signature, `StateName<C>` becomes `string`, and\n// every check downstream of it silently stops checking: a bogus `target` is\n// accepted, `EdgeKey<C>` degenerates, and `compile(g, { assign: {} })` demands\n// no builders at all. The chart is not weakened, it is switched OFF, and nothing\n// says so. A LITERAL computed key (`const NAME = \"a\"`) and a spread of another\n// object both keep their literal types and are unaffected.\ntype IsDegenerate<N> = [string] extends [N] ? true : false;\n\ntype LiteralAlphabets<C> = ([IsDegenerate<StateName<C>>] extends [true]\n ? { readonly __stateNamesMustBeLiteralsNotAComputedStringKey: true }\n : unknown) &\n ([IsDegenerate<EventName<C>>] extends [true]\n ? { readonly __eventNamesMustBeLiteralsNotAComputedStringKey: true }\n : unknown) &\n ([IsDegenerate<CmdName<C>>] extends [true]\n ? { readonly __cmdNamesMustBeLiteralsNotAComputedStringKey: true }\n : unknown) &\n ([IsDegenerate<GroupName<C>>] extends [true]\n ? { readonly __phaseNamesMustBeLiteralsNotAComputedStringKey: true }\n : unknown);\n\nexport type Strict<C> = LiteralAlphabets<C> &\n ([UnknownKeys<C, KnownChartField>] extends [never]\n ? unknown\n : { readonly __chartHasUnknownField: UnknownKeys<C, KnownChartField> }) & {\n readonly events: {\n readonly [E in keyof EvMap<C>]: EventCheck<EvMap<C>[E]>;\n };\n readonly states: {\n readonly [G in keyof Groups<C>]: {\n readonly [S in keyof Groups<C>[G]]: StrictNode<C, Groups<C>[G][S]>;\n };\n };\n };\n\n// The diagnostic IS the property name: tsc reports the missing property\n// verbatim, so the author reads which pair and what the fixes are without\n// decoding a type. Value `never` so it cannot be silenced by writing the key.\ntype Demand<S extends string, E extends string> = E extends string\n ? `unhandled pair \"${S}.${E}\" — declare it in \\`on\\`, or list \"${E}\" in this state's \\`ignore\\`, or narrow the \\`scope\\` of event \"${E}\"`\n : never;\n\ntype IsUnion<T, U = T> = T extends unknown\n ? [U] extends [T]\n ? false\n : true\n : never;\n\nexport type Total<C> = {\n // A namespaced key IS `${ns}.${event}`, so a foreign name that already\n // contains a dot is indistinguishable from one. Banning the dot on foreign\n // names makes the collision unrepresentable for EVERY namespace at once,\n // rather than deferring it to a per-`compile` check that only fires for the\n // one namespace that happens to collide.\n readonly events: {\n readonly [E in keyof EvMap<C>]: [IsForeignOf<EvMap<C>[E]>] extends [true]\n ? E extends `${string}.${string}`\n ? { readonly __foreignEventNameCannotContainADot: E }\n : unknown\n : unknown;\n };\n readonly states: {\n readonly [G in keyof Groups<C>]: {\n readonly [S in keyof Groups<C>[G]]: ([MissingAt<C, S>] extends [never]\n ? unknown\n : {\n readonly [K in Demand<\n Extract<S, string>,\n Extract<MissingAt<C, S>, string>\n >]: never;\n }) &\n // An edge key IS `${state}.${event}` and `Assigns` splits it at the\n // FIRST dot, so a dotted state name re-partitions every key it appears\n // in: `\"a.b.X\"` reads as state `\"a\"`, event `\"b.X\"`. It already failed\n // closed, but with a diagnostic that named nothing (`Type '(s: any) =>\n // …' is not assignable to type 'never'`). Same ban, same reason and now\n // the same shape as `__foreignEventNameCannotContainADot`.\n (Extract<S, string> extends `${string}.${string}`\n ? { readonly __stateNameCannotContainADot: S }\n : unknown) &\n // `end: true` means \"accepts nothing\" — it cannot also accept something.\n ([Extract<keyof On<C, S>, string>] extends [never]\n ? unknown\n : [IsEndOf<Groups<C>[G][S]>] extends [true]\n ? { readonly __endStateCannotDeclareEdges: keyof On<C, S> }\n : unknown) &\n // a state may live in exactly one phase.\n ([IsUnion<GroupOf<C, S>>] extends [true]\n ? { readonly __stateDeclaredInTwoPhases: GroupOf<C, S> }\n : unknown) &\n // an `ignore` entry that refuses an event which is not live here\n // refuses nothing — the paste-the-error-back loop, caught.\n ([Exclude<IgnoredAt<C, S>, LiveAt<C, S>>] extends [never]\n ? unknown\n : {\n readonly __refusalRefusesNothing: Exclude<\n IgnoredAt<C, S>,\n LiveAt<C, S>\n >;\n });\n };\n };\n};\n\n/**\n * `const C` preserves the nested literals with no `as const` at the call site\n * (without it every edge value widens to `string` and every derivation below\n * collapses). `Strict` and `Total` sit on the PARAMETER, not on the constraint:\n * intersecting them into the constraint makes the typo'd-target diagnostic\n * collapse to an index-signature complaint about `string` and lose tsc's\n * \"Did you mean '\"review\"'?\" suggestion.\n */\nexport function defineChart<const C extends Chart<C>>(\n c: C & Strict<C> & Total<C>,\n): C {\n return c;\n}\n\n// ── 6. derivations off the chart ───────────────────────────────────────────\ntype EdgeAt<C, S, E> = E extends keyof On<C, S> ? On<C, S>[E] : never;\n\n/** The `State.Event` pairs that are ACTUALLY declared — not the cross product. */\nexport type EdgeKey<C> = {\n [S in StateName<C>]: `${S}.${Extract<keyof On<C, S>, string>}`;\n}[StateName<C>];\n\n/** The subset of `EdgeKey` whose transition is delegated to a cell. */\nexport type CellEdgeKey<C> = Extract<\n {\n [S in StateName<C>]: {\n [E in keyof On<C, S>]: On<C, S>[E] extends { readonly cell: string }\n ? `${S}.${Extract<E, string>}`\n : never;\n }[keyof On<C, S>];\n }[StateName<C>],\n string\n>;\n\n/** The state marked `initial: true` — the chart's entry, as data. */\nexport type InitialState<C> = Extract<\n {\n [S in StateName<C>]: [IsInitialOf<NodeAt<C, S>>] extends [true] ? S : never;\n }[StateName<C>],\n string\n>;\n\n/**\n * `S`'s terminal polarity, as data: `true` (success final), `\"error\"` (failure\n * final) or `false` (not a final at all).\n *\n * Read off the ONE site the polarity is declared at, so a drawing, a driver and\n * a status derivation cannot disagree about which finals mean \"done\" and which\n * mean \"tripped\".\n */\nexport type EndPolarity<C, S> = [IsEndOf<NodeAt<C, S>>] extends [true]\n ? NodeAt<C, S> extends { readonly end: \"error\" }\n ? \"error\"\n : true\n : false;\n\n/** Every state the chart declares a SUCCESS final. */\nexport type SuccessFinal<C> = Extract<\n {\n [S in StateName<C>]: [EndPolarity<C, S>] extends [true] ? S : never;\n }[StateName<C>],\n string\n>;\n\n/** Every state the chart declares an ERROR final — the tripped terminals. */\nexport type ErrorFinal<C> = Extract<\n {\n [S in StateName<C>]: [EndPolarity<C, S>] extends [\"error\"] ? S : never;\n }[StateName<C>],\n string\n>;\n\n// ── 7. the resume (\"hist\") derivation ──────────────────────────────────────\n/** States that carry a `resume` edge out of them — the parking states. */\nexport type ParkingState<C> = Extract<\n {\n [S in StateName<C>]: {\n [E in keyof On<C, S>]: On<C, S>[E] extends { readonly resume: unknown }\n ? S\n : never;\n }[keyof On<C, S>];\n }[StateName<C>],\n string\n>;\n\n/** The targets a CELL edge declares — the union its cell is clamped to. */\ntype ToOf<X> = X extends { readonly to: readonly (infer T)[] } ? T : never;\n\n/**\n * Every state an edge can land on. A guarded edge contributes both arms; a\n * cell edge contributes its whole declared `to` fan-out — which is precisely\n * why the escape hatch does not blind the derivations (`ResumeTargets`,\n * `chartMermaid`) that read the graph's shape.\n */\ntype TargetOf<X> = X extends string\n ? X\n : X extends { readonly to: readonly unknown[] }\n ? ToOf<X>\n : X extends { readonly target: infer T }\n ? T | (X extends { readonly otherwise: infer O } ? O : never)\n : never;\n\n/** States with an edge INTO `P` — i.e. the states you could be parked from. */\ntype ResumeSource<C, P> = {\n [S in StateName<C>]: {\n [E in keyof On<C, S>]: P extends TargetOf<On<C, S>[E]> ? S : never;\n }[keyof On<C, S>];\n}[StateName<C>];\n\n/** The `fallback` declared on `P`'s resume edge — Umut's `?? initial`. */\ntype FallbackOf<C, P> = {\n [E in keyof On<C, P>]: On<C, P>[E] extends {\n readonly resume: { readonly fallback: infer F };\n }\n ? F\n : never;\n}[keyof On<C, P>];\n\n/**\n * Where a resume edge out of parking state `P` can land: any state with an edge\n * into `P`, plus the declared fallback. `was ?? initial` lifted to a type — and\n * DERIVED, so adding a `BLOCKED` edge from a new state widens the legal `was`.\n */\nexport type ResumeTargets<C, P> = Extract<\n ResumeSource<C, P> | FallbackOf<C, P>,\n string\n>;\n\n// ── 8. the three unions, all derived from the one chart ────────────────────\n/**\n * `was` is INJECTED here, not authored: a parking state is one with a `resume`\n * edge, which the chart already says. Writing `blocked: Ctx & { was: … }` by\n * hand would be that same fact a second time.\n */\nexport type StateOf<C> = {\n [S in StateName<C>]: { readonly type: S } & CtxOf<C> &\n DataOf<NodeAt<C, S>> &\n (S extends ParkingState<C>\n ? { readonly was: ResumeTargets<C, S> }\n : unknown);\n}[StateName<C>];\n\nexport type MsgOf<C> = {\n [E in EventName<C>]: { readonly type: E } & DataOf<EvMap<C>[E]>;\n}[EventName<C>];\n\nexport type CmdOf<C> = [CmdName<C>] extends [never]\n ? Cmd<never>\n : {\n [N in CmdName<C>]: { readonly type: N } & Payload<CmdMap<C>[N]>;\n }[CmdName<C>];\n\n/** The events the chart declares FOREIGN — the names that are not ours to decorate. */\nexport type ForeignEvent<C> = Extract<\n {\n [E in EventName<C>]: [IsForeignOf<EvMap<C>[E]>] extends [true] ? E : never;\n }[EventName<C>],\n string\n>;\n\n/**\n * How the compiled table keys event `E`. Namespacing is PER-EVENT, not\n * per-machine: `NS` omitted (`undefined`) namespaces nothing, and a foreign\n * event keeps its bare name even under a namespace. Everything stays a literal.\n */\n// The foreign test comes FIRST, deliberately. `NS` is often an unresolved type\n// parameter (inside a `function make<const NS extends string>(ns: NS)` factory),\n// and a conditional on it stays deferred — which would leave even the foreign\n// key unresolved, so the library's own Msg would not be assignable to the\n// instance's Msg union inside the factory. Testing `E` first resolves the\n// foreign branch eagerly, whatever `NS` turns out to be.\ntype KeyOf<C, NS extends string | undefined, E extends string> =\n E extends ForeignEvent<C> ? E : NS extends string ? `${NS}.${E}` : E;\n\n/**\n * The Msg union AS THE COMPILED TABLE CONSUMES IT — the same derivation as\n * `MsgOf`, with the keys the namespace produces. Two namespaces give genuinely\n * disjoint literal unions for the author's OWN events, while the foreign events\n * are literally shared, because they are the same event.\n */\nexport type MsgIn<C, NS extends string | undefined = undefined> = {\n [E in EventName<C>]: { readonly type: KeyOf<C, NS, E> } & DataOf<EvMap<C>[E]>;\n}[EventName<C>];\n\n// ── 9. the parts the chart cannot own ──────────────────────────────────────\ntype Narrow<U, K> = Extract<U, { type: K }>;\ntype Data<S, K> = K extends string ? Omit<Narrow<S, K>, \"type\"> : never;\n\ntype UnionToIntersection<U> = (\n U extends unknown\n ? (x: U) => void\n : never\n) extends (x: infer I) => void\n ? I\n : never;\n\n/**\n * What an `assign` must return for a given target. `was` is stripped when the\n * target is a parking state: the compiler injects it from `state.type`, so the\n * author can neither forget it nor type it wrong.\n */\ntype Assigned<C, S, T> = T extends string\n ? T extends ParkingState<C>\n ? Omit<Data<S, T>, \"was\">\n : Data<S, T>\n : never;\n\n/**\n * What `boot()` must return: the initial state's payload, minus the `type` the\n * compiler stamps on. The two degenerate charts get a NAMED marker type rather\n * than a silent `never`, so the diagnostic says which rule was broken.\n */\nexport type InitialData<C, S extends { type: string }> = [\n InitialState<C>,\n] extends [never]\n ? { readonly __chartDeclaresNoInitialState: true }\n : [IsUnion<InitialState<C>>] extends [true]\n ? { readonly __chartDeclaresManyInitialStates: InitialState<C> }\n : Data<S, InitialState<C>>;\n\ntype Fn<S, M, From, Ev, R> = (state: Narrow<S, From>, msg: Narrow<M, Ev>) => R;\n\ntype Cell<C, X, S, M, From, Ev> = X extends { readonly resume: unknown }\n ? // a resume edge may land on ANY resume target → the payload must satisfy\n // all of them, hence the intersection (not the union).\n Fn<\n S,\n M,\n From,\n Ev,\n UnionToIntersection<Assigned<C, S, ResumeTargets<C, From>>>\n >\n : // THE SAME PREDICATE THE WALK USES. `buildCell` branches on\n // `edge.when !== undefined`; so does this. `GuardPairCheck` makes `when`\n // and `otherwise` inseparable, so on any chart that compiles the two arms\n // below are both present — but the SHAPE is decided by one field read by\n // both layers, not by two conditions that have to be kept in agreement.\n X extends { readonly when: string }\n ? {\n readonly then: Fn<\n S,\n M,\n From,\n Ev,\n Assigned<C, S, X extends { readonly target: infer T } ? T : never>\n >;\n readonly else: Fn<\n S,\n M,\n From,\n Ev,\n Assigned<C, S, X extends { readonly otherwise: infer O } ? O : never>\n >;\n }\n : X extends { readonly target: infer T }\n ? Fn<S, M, From, Ev, Assigned<C, S, T>>\n : X extends string\n ? Fn<S, M, From, Ev, Assigned<C, S, X>>\n : never;\n\n/**\n * The payload builders — one per DECLARATIVE edge. Cell edges are excluded:\n * a cell returns the whole next state itself, so an `assign` entry for one\n * would be dead code the walk never calls. Because this is a mapped type over\n * a closed key union, writing that entry anyway is an excess property and tsc\n * names it (req. 6 — the bypass is a compile error, not a surprise).\n */\nexport type Assigns<\n C,\n S extends { type: string },\n M extends { type: string },\n> = {\n [K in Exclude<\n EdgeKey<C>,\n CellEdgeKey<C>\n >]: K extends `${infer From}.${infer Ev}`\n ? Cell<C, EdgeAt<C, From, Ev>, S, M, From, Ev>\n : never;\n};\n\n// ── 10. guards / cmds, typed FROM THEIR USE SITES ──────────────────────────\nexport type GuardName<C> = Extract<\n {\n [S in StateName<C>]: {\n [E in keyof On<C, S>]: On<C, S>[E] extends { readonly when: infer W }\n ? W\n : never;\n }[keyof On<C, S>];\n }[StateName<C>],\n string\n>;\n\n/** Every cell named by a `{ to, cell }` edge — the escape hatch's alphabet. */\nexport type CellName<C> = Extract<\n {\n [S in StateName<C>]: {\n [E in keyof On<C, S>]: On<C, S>[E] extends { readonly cell: infer W }\n ? W\n : never;\n }[keyof On<C, S>];\n }[StateName<C>],\n string\n>;\n\n/** Flatten a `CmdRef` — one name, or every name in an ordered list. */\ntype Flatten<X> = X extends readonly string[] ? X[number] : X;\n\n/** Every cmd an edge can fire, across BOTH guard arms. */\ntype EdgeCmds<X> =\n | (X extends { readonly cmd: infer Q } ? Flatten<Q> : never)\n | (X extends { readonly otherwiseCmd: infer Q } ? Flatten<Q> : never);\n\n/** Every cmd name any edge in the chart actually FIRES declaratively. */\nexport type UsedCmdName<C> = Extract<\n {\n [S in StateName<C>]: {\n [E in keyof On<C, S>]: EdgeCmds<On<C, S>[E]>;\n }[keyof On<C, S>];\n }[StateName<C>],\n string\n>;\n\n/** What field `F` on an edge REFERENCES — a guard/cell name, or its cmd names. */\ntype Referenced<X, F extends \"when\" | \"cmd\" | \"cell\"> = F extends \"when\"\n ? X extends { readonly when: infer W }\n ? W\n : never\n : F extends \"cell\"\n ? X extends { readonly cell: infer W }\n ? W\n : never\n : EdgeCmds<X>;\n\n/**\n * Scan the chart for every edge that references `Name` through field `F`.\n * `[Name] extends [Referenced<…>]` rather than an equality check, because an\n * edge's cmd list references SEVERAL names at once.\n */\ntype SitesWhere<C, F extends \"when\" | \"cmd\" | \"cell\", Name> = {\n [S in StateName<C>]: {\n [E in keyof On<C, S>]: [Name] extends [Referenced<On<C, S>[E], F>]\n ? `${S}.${Extract<E, string>}`\n : never;\n }[keyof On<C, S>];\n}[StateName<C>];\n\n/**\n * `\"review.FAIL\"` → `[state: ReviewState, msg: FailMsg, at: \"review.FAIL\"]`.\n * Distributes over N sites, so a multi-site name yields a UNION OF TUPLES.\n *\n * The third element is the correlator. A union of tuples does not, on its own,\n * keep `state` and `msg` in step: narrowing `state.type` is a NESTED\n * discriminant, and TypeScript's dependent-parameter control-flow analysis\n * (TS 4.6, microsoft/TypeScript#47109) only re-narrows sibling parameters from\n * a discriminant that is a DIRECT, literal-typed element of the union. `at` is\n * exactly that: one `switch (at)` collapses the tuple union to a single member,\n * and `state` AND `msg` both narrow with it.\n *\n * For a single-site name `K` is not a union, so this is a lone tuple and the\n * author may keep writing `(s, m) => …`.\n */\ntype SiteArgs<K, S, M> = K extends `${infer From}.${infer Ev}`\n ? [state: Narrow<S, From>, msg: Narrow<M, Ev>, at: K]\n : never;\n\n/**\n * THE POINT. A guard's parameters come from the edges that REFERENCE it, not\n * from a standalone registry declaration — so `retriesRemaining`, used only at\n * `review.FAIL`, receives exactly `review`'s state and `FAIL`'s msg.\n */\nexport type Guards<\n C,\n S extends { type: string },\n M extends { type: string },\n> = {\n [N in GuardName<C>]: (\n ...args: SiteArgs<SitesWhere<C, \"when\", N>, S, M>\n ) => boolean;\n};\n\n/**\n * Same technique: a cmd's parameters come from the edges that REFERENCE it, and\n * the payload it owes is the one DECLARED in the chart's `cmds` section — the\n * single site where the effect alphabet lives. A cmd fired from two edges gets\n * the union of both sites' `[state, msg]` tuples.\n */\nexport type Cmds<C, S extends { type: string }, M extends { type: string }> = {\n // keyed by the cmds edges FIRE, not by every cmd declared. A cmd only ever\n // emitted from inside a cell needs no builder — the cell built the payload\n // when it built the cmd — but its name still belongs in the `cmds` section,\n // because that section is where the Cmd union comes from.\n [N in UsedCmdName<C>]: (\n ...args: SiteArgs<SitesWhere<C, \"cmd\", N>, S, M>\n ) => Payload<CmdMap<C>[N]>;\n};\n\n/**\n * THE ESCAPE HATCH's parts bag. Same shape and the same `SitesWhere`/`SiteArgs`\n * narrowing as `guards` and `cmds` — a cell used at one site gets exactly that\n * site's state and msg, a cell used at N sites gets the union of N tuples plus\n * the `at` correlator to discriminate on.\n *\n * What is different is the RETURN: a cell returns the transition itself,\n * `[nextState, cmds]`, clamped to the states the edge DECLARED in `to`. That\n * clamp is the whole bargain — code may decide, but only among the targets the\n * chart admits, so the chart stays a truthful drawing of the machine.\n */\nexport type Cells<C, S extends { type: string }, M extends { type: string }> = {\n [N in CellName<C>]: CellForm<C, SitesWhere<C, \"cell\", N>, S, M>;\n};\n\n/** The `to` union of every site `N` is used at, resolved to real State members. */\ntype CellTarget<C, Sites, S> = Sites extends `${infer From}.${infer Ev}`\n ? Narrow<S, ToOf<EdgeAt<C, From, Ev>>>\n : never;\n\ntype CellReturn<C, Sites, S> = readonly [\n CellTarget<C, Sites, S>,\n readonly CmdOf<C>[],\n];\n\n/**\n * THE MULTI-SITE RETURN, EXACTLY. One entry per use site, each a lone tuple of\n * parameters and each clamped to THAT site's `to` — so `a.X` returning a `c` is\n * rejected at `a.X` rather than waved through because some OTHER site admits a\n * `c`. The `at` element is still passed (the walk hands it over uniformly), and\n * is simply redundant here: the key already says which site this is.\n */\ntype CellBySite<C, Sites, S, M> = {\n readonly [K in Extract<Sites, string>]: (\n ...args: SiteArgs<K, S, M>\n ) => CellReturn<C, K, S>;\n};\n\n/**\n * A cell is written in ONE of two forms, and the choice is the precision dial.\n *\n * the FUNCTION form — one body, `switch (at)` inside. Parameters narrow per\n * site (the `SiteArgs` correlator); the RETURN does not, because the whole\n * thing is one rest signature over a union of tuples and TypeScript has no\n * dependent return type over that (5.7: a union of function types is\n * reduced back to exactly this shape, an intersection loses the parameter\n * correlation, and a generic on the site key correlates nothing and merely\n * rejects every body — all three measured, none of them work). The clamp is\n * therefore the union of every site's `to`.\n *\n * the PER-SITE form — one entry per site, each exact in both directions.\n *\n * The second is offered ONLY when the cell is genuinely multi-site: with one\n * site the function form is already exact in both directions, so its type stays\n * byte-for-byte what it was and the common case cannot regress.\n *\n * The looseness the function form keeps is closed at RUNTIME instead: the walk\n * checks the returned `type` against the edge's declared `to` and throws\n * `CellTargetError`. Worth less than a compile error, worth more than nothing —\n * and `to` is right there, so it costs one `includes`.\n */\ntype CellForm<C, Sites, S, M> =\n | ((...args: SiteArgs<Sites, S, M>) => CellReturn<C, Sites, S>)\n | ([IsUnion<Sites>] extends [true] ? CellBySite<C, Sites, S, M> : never);\n\n// ═══════════════════════════════════════════════════════════════════════════\n// 12. REDUCER FORM — the same chart, minus the state grouping.\n//\n// A `Transitions` chart answers |S| × |M| questions. A great many real machines\n// answer only |M| of them: the logic is keyed by the MESSAGE, and `state.type`\n// is a label the message handler writes rather than a dimension it dispatches\n// on. `examples/resilient-fetch.ts` is exactly that — four cells, six phases,\n// and not one of the four asks which phase it is in (except `deadline_exceeded`,\n// which asks INSIDE its body). Forcing it into a grid multiplies each of those\n// four facts by six.\n//\n// So: drop the dimension the machine does not have. Everything else — `ctx`,\n// `events` (with `foreign`), `cmds`, `EdgeSpec` (including `{ to, cell }`),\n// `Referenced`/`EdgeCmds`, `Cell`, `MsgIn`/`KeyOf` — is reused verbatim. What\n// this section adds is the three-line site notion (a site is an EVENT, not a\n// `state.event` pair) and the shapes that hang off it.\n//\n// ── `states`: KEPT, as a flat list ────────────────────────────────────────\n// It is still the chart's job to own every name. `states` stays because two\n// things need it and neither can be recovered from anywhere else:\n//\n// 1. `StateOf<C>` — the State type is DERIVED, as in the grid form, so\n// `type` is spelled once. Declaring the union separately in TypeScript\n// would be the one-site rule broken for no gain.\n// 2. the `to` clamp — `to: [\"succeded\"]` has to be a typo the compiler\n// catches, and it can only do that against a declared universe.\n//\n// What it is NOT is a record of nodes: a reducer cell receives the WHOLE `S`\n// un-narrowed (that is what `Reducer<S, M, C>` says), so per-state `data`,\n// per-state `on`, `end` and `ignore` are all unrepresentable here — which is\n// correct, not a limitation. `StateOf` therefore collapses from a union of\n// members to ONE object whose `type` is a union of literals. That is precisely\n// the original's `interface State { phase: Phase; … }`.\n//\n// ── `scope`/totality: `scope` GOES, totality STAYS (one dimension smaller) ─\n// `scope` answers \"at which states does this event mean anything?\". With no\n// state dimension the question has no content, so the field is gone rather\n// than accepted and ignored.\n//\n// Totality is NOT dropped. It changes quantifier: ∀(s,e) becomes ∀e, and it\n// needs no `Total<C>` analogue to enforce, because `on` is a REQUIRED mapped\n// type over `EventName<C>`. Declare an event and omit its edge and tsc says\n// \"Property 'fetch_err' is missing\". That is the same property `Reducer<S,M,C>`\n// itself enforces on a hand-written record, lifted into the chart — and it is\n// STRONGER per-event than the grid form, where `scope: \"edges\"` lets an event\n// be routed from nowhere at all.\n//\n// What is genuinely LOST, stated plainly: the per-state REFUSAL. A grid chart\n// can say \"in `done`, `poll_failed` is dropped\" and draw it. A reducer chart\n// cannot; that decision lives inside the cell body, exactly where the original\n// hand-written machine had it (`s.phase === \"waiting_retry\" ? … : [s, []]`).\n// This is a real reduction in what the drawing knows. It is the honest trade:\n// the grid form did not RECOVER that information from the original machine, it\n// MANUFACTURED it, at 18 edge declarations for 3 facts. A chart should not\n// charge for knowledge the machine does not have.\n// ═══════════════════════════════════════════════════════════════════════════\n\n/** The declared state names — a flat tuple, not a grouped record of nodes. */\nexport type RStateName<C> = C extends { readonly states: readonly (infer S)[] }\n ? Extract<S, string>\n : never;\n\n/** The top-level edge bag. One edge per event; that IS the totality obligation. */\ntype ROn<C> = C extends { readonly on: infer O } ? O : never;\ntype REdgeAt<C, E> = E extends keyof ROn<C> ? ROn<C>[E] : never;\n\nexport type ReducerChart<C> = {\n /** Data EVERY state carries — and, here, the ONLY data any state carries. */\n readonly ctx?: Ty<object>;\n readonly states: readonly RStateName<C>[];\n /** The entry state, by name. One word where the grid form marks a node. */\n readonly initial: RStateName<C>;\n readonly events: {\n readonly [E in keyof EvMap<C>]: {\n readonly data?: Ty<object>;\n /** Same meaning as the grid form's: this name is not ours to decorate. */\n readonly foreign?: true;\n /**\n * KEPT, where `scope` is dropped. `scope` answers \"at which STATES does\n * this event mean anything\", and with no state dimension the question\n * has no content. \"Who sent this\" has exactly as much content here as it\n * does in the grid form — it is a fact about the event, and this form\n * still has events.\n */\n readonly from?: EventOrigin;\n };\n };\n readonly cmds?: { readonly [N in keyof CmdMap<C>]: Ty<object> };\n /**\n * TOTAL, not partial. Every declared event owes an edge — the `?` the grid\n * form's per-state `on` carries is exactly what `Total<C>` had to police\n * there, and here the mapped type does it for free.\n */\n readonly on: {\n readonly [E in EventName<C>]: EdgeSpec<RStateName<C>, CmdName<C>>;\n };\n};\n\n/**\n * `resume` needs a phase dimension: `was` is derived from \"the states with an\n * edge INTO the parking state\", and here every edge is reachable from every\n * state, so the derivation degenerates to \"all of them\" and says nothing. It\n * is rejected by name rather than silently accepted and ignored by the walk.\n */\ntype RStrictEdge<X> = X extends { readonly resume: unknown }\n ? { readonly __resumeNeedsAPhaseDimension: true }\n : EdgeCheck<X>;\n\n/** The reducer form's key alphabet — `scope` has no meaning without phases. */\ntype KnownReducerChartField =\n | \"ctx\"\n | \"states\"\n | \"initial\"\n | \"events\"\n | \"cmds\"\n | \"on\";\ntype KnownReducerEventField = \"data\" | \"foreign\" | \"from\";\n\ntype REventCheck<X> = ([UnknownKeys<X, KnownReducerEventField>] extends [never]\n ? unknown\n : {\n readonly __eventHasUnknownField: UnknownKeys<X, KnownReducerEventField>;\n }) &\n FromCheck<X>;\n\nexport type StrictR<C> = ([IsDegenerate<RStateName<C>>] extends [true]\n ? { readonly __stateNamesMustBeLiteralsNotAComputedStringKey: true }\n : unknown) &\n ([IsDegenerate<EventName<C>>] extends [true]\n ? { readonly __eventNamesMustBeLiteralsNotAComputedStringKey: true }\n : unknown) &\n ([IsDegenerate<CmdName<C>>] extends [true]\n ? { readonly __cmdNamesMustBeLiteralsNotAComputedStringKey: true }\n : unknown) &\n // the same unknown-key rule as the grid form, over this form's alphabet — a\n // `cxt` typo here empties `RStateOf<C>` down to its bare tag exactly as it\n // emptied `StateOf<C>` there.\n ([UnknownKeys<C, KnownReducerChartField>] extends [never]\n ? unknown\n : {\n readonly __chartHasUnknownField: UnknownKeys<C, KnownReducerChartField>;\n }) & {\n readonly on: {\n readonly [E in keyof ROn<C>]: E extends EventName<C>\n ? RStrictEdge<ROn<C>[E]>\n : { readonly __onDeclaresAnUndeclaredEvent: E };\n };\n readonly events: {\n readonly [E in keyof EvMap<C>]: REventCheck<EvMap<C>[E]> &\n ([IsForeignOf<EvMap<C>[E]>] extends [true]\n ? E extends `${string}.${string}`\n ? { readonly __foreignEventNameCannotContainADot: E }\n : unknown\n : unknown);\n };\n };\n\n/** Same contract as `defineChart`, one dimension smaller. */\nexport function defineReducerChart<const C extends ReducerChart<C>>(\n c: C & StrictR<C>,\n): C {\n return c;\n}\n\n// ── 12b. derivations ───────────────────────────────────────────────────────\n/**\n * ONE object, not a union: every state carries `ctx` and nothing else, so the\n * only thing that varies is the tag. This is the original's\n * `interface State { phase: Phase; … }` with `phase` named `type`.\n */\nexport type RStateOf<C> = { readonly type: RStateName<C> } & CtxOf<C>;\n\n/** The events whose transition is delegated to a cell. */\nexport type RCellEvent<C> = Extract<\n {\n [E in EventName<C>]: ROn<C>[E & keyof ROn<C>] extends {\n readonly cell: string;\n }\n ? E\n : never;\n }[EventName<C>],\n string\n>;\n\ntype RNames<C, F extends \"when\" | \"cmd\" | \"cell\"> = Extract<\n { [E in keyof ROn<C>]: Referenced<ROn<C>[E], F> }[keyof ROn<C>],\n string\n>;\n\nexport type RGuardName<C> = RNames<C, \"when\">;\nexport type RCellName<C> = RNames<C, \"cell\">;\nexport type RUsedCmdName<C> = RNames<C, \"cmd\">;\n\n/**\n * A site is an EVENT. The grid form's `SitesWhere` scans `state × event`; with\n * one dimension the scan is the same shape with the outer loop removed.\n */\ntype RSitesWhere<C, F extends \"when\" | \"cmd\" | \"cell\", Name> = Extract<\n {\n [E in keyof ROn<C>]: [Name] extends [Referenced<ROn<C>[E], F>] ? E : never;\n }[keyof ROn<C>],\n string\n>;\n\n/**\n * The state is NOT narrowed — there is nothing to narrow it to. Everything\n * else is `SiteArgs` verbatim, including the `at` correlator that lets a\n * multi-site helper discriminate its msg with one `switch`.\n */\ntype RSiteArgs<K, S, M> = K extends string\n ? [state: S, msg: Narrow<M, K>, at: K]\n : never;\n\nexport type RGuards<C, S, M extends { type: string }> = {\n [N in RGuardName<C>]: (\n ...args: RSiteArgs<RSitesWhere<C, \"when\", N>, S, M>\n ) => boolean;\n};\n\nexport type RCmds<C, S, M extends { type: string }> = {\n [N in RUsedCmdName<C>]: (\n ...args: RSiteArgs<RSitesWhere<C, \"cmd\", N>, S, M>\n ) => Payload<CmdMap<C>[N & keyof CmdMap<C>]>;\n};\n\nexport type RCells<\n C,\n S extends { type: string },\n M extends { type: string },\n> = {\n [N in RCellName<C>]: RCellForm<C, RSitesWhere<C, \"cell\", N>, S, M>;\n};\n\n/** The `to` clamp, unchanged in spirit: the tag is restricted, `ctx` is not. */\ntype RCellTarget<C, Sites> = Sites extends string\n ? { readonly type: Extract<ToOf<REdgeAt<C, Sites>>, string> } & CtxOf<C>\n : never;\n\ntype RCellReturn<C, Sites> = readonly [\n RCellTarget<C, Sites>,\n readonly CmdOf<C>[],\n];\n\n/**\n * `CellForm`, with the phase dimension removed — the same two forms, offered on\n * the same condition, for the same reason. A site here is an EVENT, so the\n * per-site bag is keyed `\"X\" | \"Y\"` rather than `\"a.X\" | \"b.Y\"`; everything\n * else, including the runtime `CellTargetError` under the function form, is the\n * grid form's machinery reused verbatim (`buildCell` serves both).\n */\ntype RCellForm<C, Sites, S, M extends { type: string }> =\n | ((...args: RSiteArgs<Sites, S, M>) => RCellReturn<C, Sites>)\n | ([IsUnion<Sites>] extends [true]\n ? {\n readonly [K in Extract<Sites, string>]: (\n ...args: RSiteArgs<K, S, M>\n ) => RCellReturn<C, K>;\n }\n : never);\n\n/**\n * What an `assign` returns: `ctx`, for every target. The compiler stamps\n * `type` from the edge, so — as in the grid form — the author cannot forget it\n * and cannot get it wrong.\n */\ntype RAssigned<C> = CtxOf<C>;\ntype RFn<S, M extends { type: string }, E, R> = (\n state: S,\n msg: Narrow<M, E>,\n) => R;\n\n// `when`, for the same reason as the grid form's `Cell`: it is the field\n// `buildCell` — which serves BOTH forms — actually branches on.\ntype RCell<C, X, S, M extends { type: string }, E> = X extends {\n readonly when: string;\n}\n ? {\n readonly then: RFn<S, M, E, RAssigned<C>>;\n readonly else: RFn<S, M, E, RAssigned<C>>;\n }\n : RFn<S, M, E, RAssigned<C>>;\n\n/** One builder per DECLARATIVE event. Cell events own their whole transition. */\nexport type RAssigns<C, S, M extends { type: string }> = {\n [E in Exclude<EventName<C>, RCellEvent<C>>]: RCell<C, REdgeAt<C, E>, S, M, E>;\n};\n\n// ── 11. identity assertion helpers ─────────────────────────────────────────\nexport type Eq<A, B> =\n (<T>() => T extends A ? 1 : 2) extends <T>() => T extends B ? 1 : 2\n ? true\n : false;\nexport type Assert<T extends true> = T;\n"]}