@graphrefly/ts 0.0.0 → 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (307) hide show
  1. package/README.md +135 -0
  2. package/dist/adapters/index.cjs +105 -66
  3. package/dist/adapters/index.cjs.map +1 -1
  4. package/dist/adapters/index.d.cts +11 -136
  5. package/dist/adapters/index.d.ts +11 -136
  6. package/dist/adapters/index.js +27 -225
  7. package/dist/adapters/index.js.map +1 -1
  8. package/dist/adapters/observe-storage.d.cts +4 -4
  9. package/dist/adapters/observe-storage.d.ts +4 -4
  10. package/dist/adapters/observe-storage.js +1 -0
  11. package/dist/adapters/observe-storage.js.map +1 -1
  12. package/dist/adapters/react.cjs +166 -0
  13. package/dist/adapters/react.cjs.map +1 -0
  14. package/dist/adapters/react.d.cts +31 -0
  15. package/dist/adapters/react.d.ts +31 -0
  16. package/dist/adapters/react.js +51 -0
  17. package/dist/adapters/react.js.map +1 -0
  18. package/dist/adapters/solid.cjs +157 -0
  19. package/dist/adapters/solid.cjs.map +1 -0
  20. package/dist/adapters/solid.d.cts +26 -0
  21. package/dist/adapters/solid.d.ts +26 -0
  22. package/dist/adapters/solid.js +48 -0
  23. package/dist/adapters/solid.js.map +1 -0
  24. package/dist/adapters/svelte.cjs +148 -0
  25. package/dist/adapters/svelte.cjs.map +1 -0
  26. package/dist/adapters/svelte.d.cts +31 -0
  27. package/dist/adapters/svelte.d.ts +31 -0
  28. package/dist/adapters/svelte.js +46 -0
  29. package/dist/adapters/svelte.js.map +1 -0
  30. package/dist/adapters/vue.cjs +155 -0
  31. package/dist/adapters/vue.cjs.map +1 -0
  32. package/dist/adapters/vue.d.cts +26 -0
  33. package/dist/adapters/vue.d.ts +26 -0
  34. package/dist/adapters/vue.js +46 -0
  35. package/dist/adapters/vue.js.map +1 -0
  36. package/dist/agent-runtime-BesGDZcB.d.ts +555 -0
  37. package/dist/agent-runtime-DZTJ3C-p.d.cts +555 -0
  38. package/dist/agentic-memory-BmRCvh0d.d.ts +517 -0
  39. package/dist/agentic-memory-DfuVZ-lY.d.cts +517 -0
  40. package/dist/capability-admission-B0BzqAm5.d.cts +102 -0
  41. package/dist/capability-admission-g0mn9hpq.d.ts +102 -0
  42. package/dist/{chunk-JR4IKCR2.js → chunk-2747WN4Y.js} +5 -5
  43. package/dist/{chunk-2ILL7HQI.js → chunk-3JR3EDB2.js} +17 -17
  44. package/dist/{chunk-2ILL7HQI.js.map → chunk-3JR3EDB2.js.map} +1 -1
  45. package/dist/{chunk-GDL26N2T.js → chunk-3KN7NJDR.js} +2 -2
  46. package/dist/{chunk-DJC4CHLQ.js → chunk-43BKLFZU.js} +9 -9
  47. package/dist/chunk-6XAIOL3X.js +2407 -0
  48. package/dist/chunk-6XAIOL3X.js.map +1 -0
  49. package/dist/{chunk-SCRFRCGR.js → chunk-BSQGE5PS.js} +1 -1
  50. package/dist/{chunk-Y3ZLRGHC.js → chunk-CZNV3VXM.js} +16 -16
  51. package/dist/chunk-DGUM43GV.js +11 -0
  52. package/dist/chunk-DGUM43GV.js.map +1 -0
  53. package/dist/{chunk-JIMUDQN3.js → chunk-FBUU43PM.js} +2 -2
  54. package/dist/chunk-H75VXTGT.js +219 -0
  55. package/dist/chunk-H75VXTGT.js.map +1 -0
  56. package/dist/{chunk-RIIOUTGM.js → chunk-HKK2JD7Z.js} +12 -9
  57. package/dist/chunk-HKK2JD7Z.js.map +1 -0
  58. package/dist/{chunk-D6BG7U6A.js → chunk-IXZBUWSP.js} +3 -3
  59. package/dist/chunk-PC3BTTBE.js +3217 -0
  60. package/dist/chunk-PC3BTTBE.js.map +1 -0
  61. package/dist/chunk-QFY4AFY4.js +879 -0
  62. package/dist/chunk-QFY4AFY4.js.map +1 -0
  63. package/dist/{chunk-DK554R7P.js → chunk-S6HXABGL.js} +2 -1
  64. package/dist/chunk-S6HXABGL.js.map +1 -0
  65. package/dist/{chunk-PKVBHGBM.js → chunk-SS2A464I.js} +7 -7
  66. package/dist/chunk-UT3MHJCW.js +49 -0
  67. package/dist/chunk-UT3MHJCW.js.map +1 -0
  68. package/dist/{chunk-G4M3NHRJ.js → chunk-V7CIJE4B.js} +3 -3
  69. package/dist/{chunk-TEW47IVR.js → chunk-VPEFSDME.js} +2 -2
  70. package/dist/chunk-VTHLCFN4.js +368 -0
  71. package/dist/chunk-VTHLCFN4.js.map +1 -0
  72. package/dist/{chunk-SWTLEQL6.js → chunk-WQIA3GFB.js} +2 -2
  73. package/dist/chunk-WQIA3GFB.js.map +1 -0
  74. package/dist/{chunk-I3IHOHCJ.js → chunk-XKXWK2KP.js} +108 -64
  75. package/dist/chunk-XKXWK2KP.js.map +1 -0
  76. package/dist/{chunk-COHO25CZ.js → chunk-YDSIVHRR.js} +553 -7
  77. package/dist/chunk-YDSIVHRR.js.map +1 -0
  78. package/dist/chunk-YXMZ2N6J.js +1884 -0
  79. package/dist/chunk-YXMZ2N6J.js.map +1 -0
  80. package/dist/composition/index.cjs +102 -57
  81. package/dist/composition/index.cjs.map +1 -1
  82. package/dist/composition/index.d.cts +4 -4
  83. package/dist/composition/index.d.ts +4 -4
  84. package/dist/composition/index.js +6 -5
  85. package/dist/core/index.cjs +102 -57
  86. package/dist/core/index.cjs.map +1 -1
  87. package/dist/core/index.d.cts +2 -2
  88. package/dist/core/index.d.ts +2 -2
  89. package/dist/core/index.js +5 -4
  90. package/dist/cqrs/index.cjs.map +1 -1
  91. package/dist/cqrs/index.d.cts +4 -4
  92. package/dist/cqrs/index.d.ts +4 -4
  93. package/dist/cqrs/index.js +3 -2
  94. package/dist/cqrs/index.js.map +1 -1
  95. package/dist/cqrs/messaging.cjs +312 -0
  96. package/dist/cqrs/messaging.cjs.map +1 -0
  97. package/dist/cqrs/messaging.d.cts +57 -0
  98. package/dist/cqrs/messaging.d.ts +57 -0
  99. package/dist/cqrs/messaging.js +274 -0
  100. package/dist/cqrs/messaging.js.map +1 -0
  101. package/dist/cqrs/work-queue.cjs +329 -0
  102. package/dist/cqrs/work-queue.cjs.map +1 -0
  103. package/dist/cqrs/work-queue.d.cts +90 -0
  104. package/dist/cqrs/work-queue.d.ts +90 -0
  105. package/dist/cqrs/work-queue.js +292 -0
  106. package/dist/cqrs/work-queue.js.map +1 -0
  107. package/dist/data/index.cjs +19 -0
  108. package/dist/data/index.cjs.map +1 -0
  109. package/dist/data/index.d.cts +36 -0
  110. package/dist/data/index.d.ts +36 -0
  111. package/dist/data/index.js +1 -0
  112. package/dist/data/index.js.map +1 -0
  113. package/dist/data-structures/index.cjs +105 -57
  114. package/dist/data-structures/index.cjs.map +1 -1
  115. package/dist/data-structures/index.d.cts +8 -8
  116. package/dist/data-structures/index.d.ts +8 -8
  117. package/dist/data-structures/index.js +7 -6
  118. package/dist/{describe-BZb7AS2y.d.ts → describe-BpyJuWkw.d.ts} +1 -1
  119. package/dist/{describe-Ciu8SUnN.d.cts → describe-DYMw_l1C.d.cts} +1 -1
  120. package/dist/executors/work-queue.cjs +342 -0
  121. package/dist/executors/work-queue.cjs.map +1 -0
  122. package/dist/executors/work-queue.d.cts +90 -0
  123. package/dist/executors/work-queue.d.ts +90 -0
  124. package/dist/executors/work-queue.js +306 -0
  125. package/dist/executors/work-queue.js.map +1 -0
  126. package/dist/graph/index.cjs +112 -58
  127. package/dist/graph/index.cjs.map +1 -1
  128. package/dist/graph/index.d.cts +9 -9
  129. package/dist/graph/index.d.ts +9 -9
  130. package/dist/graph/index.js +18 -17
  131. package/dist/{graph-DfdF9zy4.d.ts → graph-D-1-SQeC.d.ts} +3 -3
  132. package/dist/{graph-s23RbbFO.d.cts → graph-DCEWh4T2.d.cts} +3 -3
  133. package/dist/{index-CAEmLCYF.d.cts → index-72VZC0-E.d.cts} +2 -2
  134. package/dist/{index-SnzZu3x7.d.ts → index-Bmxeu0nK.d.ts} +2 -2
  135. package/dist/index.cjs +112 -58
  136. package/dist/index.cjs.map +1 -1
  137. package/dist/index.d.cts +11 -10
  138. package/dist/index.d.ts +11 -10
  139. package/dist/index.js +118 -113
  140. package/dist/inspection/boundary.cjs +98 -0
  141. package/dist/inspection/boundary.cjs.map +1 -0
  142. package/dist/inspection/boundary.d.cts +61 -0
  143. package/dist/inspection/boundary.d.ts +61 -0
  144. package/dist/inspection/boundary.js +75 -0
  145. package/dist/inspection/boundary.js.map +1 -0
  146. package/dist/{messages-BZqrGGm1.d.ts → messages-CAzUPPJM.d.cts} +10 -5
  147. package/dist/{messages-BZqrGGm1.d.cts → messages-CAzUPPJM.d.ts} +10 -5
  148. package/dist/messaging/index.cjs +744 -613
  149. package/dist/messaging/index.cjs.map +1 -1
  150. package/dist/messaging/index.d.cts +216 -160
  151. package/dist/messaging/index.d.ts +216 -160
  152. package/dist/messaging/index.js +19 -749
  153. package/dist/messaging/index.js.map +1 -1
  154. package/dist/operators/index.cjs +102 -57
  155. package/dist/operators/index.cjs.map +1 -1
  156. package/dist/operators/index.d.cts +6 -6
  157. package/dist/operators/index.d.ts +6 -6
  158. package/dist/operators/index.js +8 -7
  159. package/dist/orchestration/index.cjs +3333 -59
  160. package/dist/orchestration/index.cjs.map +1 -1
  161. package/dist/orchestration/index.d.cts +7 -4
  162. package/dist/orchestration/index.d.ts +7 -4
  163. package/dist/orchestration/index.js +49 -8
  164. package/dist/orchestration/index.js.map +1 -1
  165. package/dist/orchestration/messaging.cjs +314 -0
  166. package/dist/orchestration/messaging.cjs.map +1 -0
  167. package/dist/orchestration/messaging.d.cts +59 -0
  168. package/dist/orchestration/messaging.d.ts +59 -0
  169. package/dist/orchestration/messaging.js +276 -0
  170. package/dist/orchestration/messaging.js.map +1 -0
  171. package/dist/orchestration/work-queue.cjs +262 -0
  172. package/dist/orchestration/work-queue.cjs.map +1 -0
  173. package/dist/orchestration/work-queue.d.cts +85 -0
  174. package/dist/orchestration/work-queue.d.ts +85 -0
  175. package/dist/orchestration/work-queue.js +226 -0
  176. package/dist/orchestration/work-queue.js.map +1 -0
  177. package/dist/patterns/event-flow.cjs +447 -0
  178. package/dist/patterns/event-flow.cjs.map +1 -0
  179. package/dist/patterns/event-flow.d.cts +115 -0
  180. package/dist/patterns/event-flow.d.ts +115 -0
  181. package/dist/patterns/event-flow.js +14 -0
  182. package/dist/patterns/event-flow.js.map +1 -0
  183. package/dist/patterns/index.cjs +423 -18
  184. package/dist/patterns/index.cjs.map +1 -1
  185. package/dist/patterns/index.d.cts +8 -5
  186. package/dist/patterns/index.d.ts +8 -5
  187. package/dist/patterns/index.js +13 -4
  188. package/dist/{reactive-collection-Cb1II1Fi.d.ts → reactive-collection-BAmfrGjd.d.ts} +9 -9
  189. package/dist/{reactive-collection-BxBqtIOE.d.cts → reactive-collection-DNV0-gFi.d.cts} +9 -9
  190. package/dist/{reactive-collection-storage-D-KmjE0J.d.cts → reactive-collection-storage-BNEldDyi.d.cts} +5 -5
  191. package/dist/{reactive-collection-storage-BNiEc-Gd.d.ts → reactive-collection-storage-YZsAQsWK.d.ts} +5 -5
  192. package/dist/{reactive-map-D-g3dv8I.d.cts → reactive-map-DRD1LJ2H.d.cts} +6 -6
  193. package/dist/{reactive-map-BcB4KsQR.d.ts → reactive-map-EsDiCmJk.d.ts} +6 -6
  194. package/dist/render/index.d.cts +3 -3
  195. package/dist/render/index.d.ts +3 -3
  196. package/dist/render/index.js +1 -0
  197. package/dist/{semantic-memory-graph-BYoIlP35.d.cts → semantic-memory-graph-DKuNzuWw.d.cts} +2 -2
  198. package/dist/{semantic-memory-graph-CxyXLms3.d.ts → semantic-memory-graph-uwbwJdhe.d.ts} +2 -2
  199. package/dist/solutions/index.cjs +4478 -2
  200. package/dist/solutions/index.cjs.map +1 -1
  201. package/dist/solutions/index.d.cts +13 -519
  202. package/dist/solutions/index.d.ts +13 -519
  203. package/dist/solutions/index.js +90 -6
  204. package/dist/solutions/reactive-layout/browser/index.cjs +449 -0
  205. package/dist/solutions/reactive-layout/browser/index.cjs.map +1 -0
  206. package/dist/solutions/reactive-layout/browser/index.d.cts +44 -0
  207. package/dist/solutions/reactive-layout/browser/index.d.ts +44 -0
  208. package/dist/solutions/reactive-layout/browser/index.js +69 -0
  209. package/dist/solutions/reactive-layout/browser/index.js.map +1 -0
  210. package/dist/solutions/reactive-layout/index.cjs +4266 -0
  211. package/dist/solutions/reactive-layout/index.cjs.map +1 -0
  212. package/dist/solutions/reactive-layout/index.d.cts +581 -0
  213. package/dist/solutions/reactive-layout/index.d.ts +581 -0
  214. package/dist/solutions/reactive-layout/index.js +86 -0
  215. package/dist/solutions/reactive-layout/index.js.map +1 -0
  216. package/dist/solutions/reactive-layout/node-canvas/index.cjs +545 -0
  217. package/dist/solutions/reactive-layout/node-canvas/index.cjs.map +1 -0
  218. package/dist/solutions/reactive-layout/node-canvas/index.d.cts +54 -0
  219. package/dist/solutions/reactive-layout/node-canvas/index.d.ts +54 -0
  220. package/dist/solutions/reactive-layout/node-canvas/index.js +131 -0
  221. package/dist/solutions/reactive-layout/node-canvas/index.js.map +1 -0
  222. package/dist/solutions/reactive-layout/react-native/index.cjs +494 -0
  223. package/dist/solutions/reactive-layout/react-native/index.cjs.map +1 -0
  224. package/dist/solutions/reactive-layout/react-native/index.d.cts +51 -0
  225. package/dist/solutions/reactive-layout/react-native/index.d.ts +51 -0
  226. package/dist/solutions/reactive-layout/react-native/index.js +77 -0
  227. package/dist/solutions/reactive-layout/react-native/index.js.map +1 -0
  228. package/dist/solutions/reactive-layout/skia/index.cjs +547 -0
  229. package/dist/solutions/reactive-layout/skia/index.cjs.map +1 -0
  230. package/dist/solutions/reactive-layout/skia/index.d.cts +64 -0
  231. package/dist/solutions/reactive-layout/skia/index.d.ts +64 -0
  232. package/dist/solutions/reactive-layout/skia/index.js +70 -0
  233. package/dist/solutions/reactive-layout/skia/index.js.map +1 -0
  234. package/dist/solutions/work-item/actions.cjs +2164 -0
  235. package/dist/solutions/work-item/actions.cjs.map +1 -0
  236. package/dist/solutions/work-item/actions.d.cts +201 -0
  237. package/dist/solutions/work-item/actions.d.ts +201 -0
  238. package/dist/solutions/work-item/actions.js +1454 -0
  239. package/dist/solutions/work-item/actions.js.map +1 -0
  240. package/dist/solutions/work-item/scheduling.cjs +2454 -0
  241. package/dist/solutions/work-item/scheduling.cjs.map +1 -0
  242. package/dist/solutions/work-item/scheduling.d.cts +433 -0
  243. package/dist/solutions/work-item/scheduling.d.ts +433 -0
  244. package/dist/solutions/work-item/scheduling.js +32 -0
  245. package/dist/solutions/work-item/scheduling.js.map +1 -0
  246. package/dist/solutions/work-item/work-queue.cjs +306 -0
  247. package/dist/solutions/work-item/work-queue.cjs.map +1 -0
  248. package/dist/solutions/work-item/work-queue.d.cts +71 -0
  249. package/dist/solutions/work-item/work-queue.d.ts +71 -0
  250. package/dist/solutions/work-item/work-queue.js +270 -0
  251. package/dist/solutions/work-item/work-queue.js.map +1 -0
  252. package/dist/sources/browser.cjs +169 -57
  253. package/dist/sources/browser.cjs.map +1 -1
  254. package/dist/sources/browser.d.cts +33 -6
  255. package/dist/sources/browser.d.ts +33 -6
  256. package/dist/sources/browser.js +73 -6
  257. package/dist/sources/browser.js.map +1 -1
  258. package/dist/sources/index.cjs +102 -57
  259. package/dist/sources/index.cjs.map +1 -1
  260. package/dist/sources/index.d.cts +5 -5
  261. package/dist/sources/index.d.ts +5 -5
  262. package/dist/sources/index.js +6 -5
  263. package/dist/sources/node.cjs.map +1 -1
  264. package/dist/sources/node.d.cts +4 -4
  265. package/dist/sources/node.d.ts +4 -4
  266. package/dist/sources/node.js +2 -1
  267. package/dist/sources/node.js.map +1 -1
  268. package/dist/storage/browser.js +1 -0
  269. package/dist/storage/browser.js.map +1 -1
  270. package/dist/storage/index.d.cts +5 -5
  271. package/dist/storage/index.d.ts +5 -5
  272. package/dist/storage/index.js +5 -4
  273. package/dist/storage/node.js +1 -0
  274. package/dist/storage/node.js.map +1 -1
  275. package/dist/store-C-joM4gh.d.ts +123 -0
  276. package/dist/store-CNJwmT-h.d.cts +123 -0
  277. package/dist/testing/index.cjs +1 -0
  278. package/dist/testing/index.cjs.map +1 -1
  279. package/dist/testing/index.d.cts +1 -1
  280. package/dist/testing/index.d.ts +1 -1
  281. package/dist/testing/index.js +3 -2
  282. package/dist/{types-h12mNYbq.d.ts → types-BsJvElYZ.d.ts} +31 -31
  283. package/dist/{types-bNMSWKqF.d.cts → types-CcPIn7sy.d.cts} +31 -31
  284. package/dist/work-item-runtime-C3M79vE9.d.ts +228 -0
  285. package/dist/work-item-runtime-qaVgsL0T.d.cts +228 -0
  286. package/dist/work-queue/index.cjs +1132 -0
  287. package/dist/work-queue/index.cjs.map +1 -0
  288. package/dist/work-queue/index.d.cts +369 -0
  289. package/dist/work-queue/index.d.ts +369 -0
  290. package/dist/work-queue/index.js +1078 -0
  291. package/dist/work-queue/index.js.map +1 -0
  292. package/package.json +266 -2
  293. package/dist/chunk-COHO25CZ.js.map +0 -1
  294. package/dist/chunk-DK554R7P.js.map +0 -1
  295. package/dist/chunk-I3IHOHCJ.js.map +0 -1
  296. package/dist/chunk-RIIOUTGM.js.map +0 -1
  297. package/dist/chunk-SWTLEQL6.js.map +0 -1
  298. /package/dist/{chunk-JR4IKCR2.js.map → chunk-2747WN4Y.js.map} +0 -0
  299. /package/dist/{chunk-GDL26N2T.js.map → chunk-3KN7NJDR.js.map} +0 -0
  300. /package/dist/{chunk-DJC4CHLQ.js.map → chunk-43BKLFZU.js.map} +0 -0
  301. /package/dist/{chunk-SCRFRCGR.js.map → chunk-BSQGE5PS.js.map} +0 -0
  302. /package/dist/{chunk-Y3ZLRGHC.js.map → chunk-CZNV3VXM.js.map} +0 -0
  303. /package/dist/{chunk-JIMUDQN3.js.map → chunk-FBUU43PM.js.map} +0 -0
  304. /package/dist/{chunk-D6BG7U6A.js.map → chunk-IXZBUWSP.js.map} +0 -0
  305. /package/dist/{chunk-PKVBHGBM.js.map → chunk-SS2A464I.js.map} +0 -0
  306. /package/dist/{chunk-G4M3NHRJ.js.map → chunk-V7CIJE4B.js.map} +0 -0
  307. /package/dist/{chunk-TEW47IVR.js.map → chunk-VPEFSDME.js.map} +0 -0
@@ -0,0 +1,447 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/patterns/event-flow.ts
21
+ var event_flow_exports = {};
22
+ __export(event_flow_exports, {
23
+ eventFlow: () => eventFlow,
24
+ eventFlowProjection: () => eventFlowProjection
25
+ });
26
+ module.exports = __toCommonJS(event_flow_exports);
27
+
28
+ // src/protocol/messages.ts
29
+ var SENTINEL = void 0;
30
+
31
+ // src/ctx/types.ts
32
+ function depWaves(ctx, depIndex) {
33
+ return ctx.waveData[depIndex] ?? [];
34
+ }
35
+ function depBatch(ctx, depIndex) {
36
+ const waves = depWaves(ctx, depIndex);
37
+ if (waves.length === 0) return null;
38
+ const flattened = waves.flat().filter((v) => v !== SENTINEL);
39
+ return flattened.length === 0 ? [] : flattened;
40
+ }
41
+
42
+ // src/messaging/index.ts
43
+ function eventMessageIssue(value) {
44
+ if (!isObjectRecord(value)) {
45
+ return eventIssue("event message must be an object");
46
+ }
47
+ if (typeof value.id !== "string" || value.id.length === 0) {
48
+ return eventIssue("event message id must be a non-empty string");
49
+ }
50
+ if (typeof value.type !== "string" || value.type.length === 0) {
51
+ return eventIssue("event message type must be a non-empty string");
52
+ }
53
+ if (!("payload" in value)) {
54
+ return eventIssue("event message payload field is required");
55
+ }
56
+ return void 0;
57
+ }
58
+ function eventIssue(message) {
59
+ return {
60
+ kind: "issue",
61
+ code: "malformed-event-message",
62
+ message,
63
+ severity: "error",
64
+ source: "messageBus.eventMessage"
65
+ };
66
+ }
67
+ var PROMPTS_TOPIC = "prompts";
68
+ var RESPONSES_TOPIC = "responses";
69
+ var INJECTIONS_TOPIC = "injections";
70
+ var DEFERRED_TOPIC = "deferred";
71
+ var SPAWNS_TOPIC = "spawns";
72
+ var CONTEXT_TOPIC = "context";
73
+ var TODOS_TOPIC = "todos";
74
+ var STANDARD_TOPICS = Object.freeze([
75
+ PROMPTS_TOPIC,
76
+ RESPONSES_TOPIC,
77
+ INJECTIONS_TOPIC,
78
+ DEFERRED_TOPIC,
79
+ SPAWNS_TOPIC,
80
+ CONTEXT_TOPIC,
81
+ TODOS_TOPIC
82
+ ]);
83
+ function isObjectRecord(value) {
84
+ return typeof value === "object" && value !== null && !Array.isArray(value);
85
+ }
86
+
87
+ // src/patterns/event-flow.ts
88
+ function eventFlow(graph, opts) {
89
+ const name = opts.name ?? opts.flowId ?? "eventFlow";
90
+ const flowId = opts.flowId ?? name;
91
+ const now = opts.now ?? Date.now;
92
+ const sources = normalizeSources(opts.sources);
93
+ const runtime = graph.node(
94
+ sources.map((source) => source.node),
95
+ (ctx) => {
96
+ const state = ctx.state.get() ?? {
97
+ recordSeq: 0,
98
+ auditSeq: 0,
99
+ highWater: /* @__PURE__ */ new Map()
100
+ };
101
+ ctx.state.persist(true);
102
+ for (let i = 0; i < sources.length; i++) {
103
+ const source = sources[i];
104
+ for (const raw of depBatch(ctx, i) ?? []) {
105
+ reduceEventSource(
106
+ raw,
107
+ source.source,
108
+ flowId,
109
+ now(),
110
+ state,
111
+ (fact) => ctx.down([["DATA", fact]])
112
+ );
113
+ }
114
+ }
115
+ ctx.state.set(state);
116
+ },
117
+ {
118
+ name: `${name}/runtime`,
119
+ factory: "eventFlowRuntime",
120
+ meta: { flowId, sources: sources.map((source) => source.source) },
121
+ partial: true,
122
+ completeWhenDepsComplete: false,
123
+ errorWhenDepsError: false
124
+ }
125
+ );
126
+ return {
127
+ records: runtimeProjection(graph, runtime, "record", `${name}/records`, "eventFlowRecords"),
128
+ status: runtimeProjection(graph, runtime, "status", `${name}/status`, "eventFlowStatus"),
129
+ issues: runtimeProjection(graph, runtime, "issue", `${name}/issues`, "eventFlowIssues"),
130
+ audit: runtimeProjection(graph, runtime, "audit", `${name}/audit`, "eventFlowAudit"),
131
+ highWater: runtimeProjection(
132
+ graph,
133
+ runtime,
134
+ "high-water",
135
+ `${name}/highWater`,
136
+ "eventFlowHighWater"
137
+ )
138
+ };
139
+ }
140
+ function eventFlowProjection(graph, flowOrRecords, opts) {
141
+ const records = isEventFlowBundle(flowOrRecords) ? flowOrRecords.records : flowOrRecords;
142
+ const name = opts.name ?? opts.projectionId ?? "eventFlowProjection";
143
+ const projectionId = opts.projectionId ?? name;
144
+ const now = opts.now ?? Date.now;
145
+ const runtime = graph.node(
146
+ [records],
147
+ (ctx) => {
148
+ const state = ctx.state.get() ?? {
149
+ value: opts.initial,
150
+ highWater: emptyHighWater(projectionId),
151
+ sourceHighWater: /* @__PURE__ */ new Map()
152
+ };
153
+ ctx.state.persist(true);
154
+ for (const raw of depBatch(ctx, 0) ?? []) {
155
+ const record = raw;
156
+ try {
157
+ state.value = opts.reduce(state.value, record);
158
+ state.highWater = projectionHighWater(projectionId, record, state.sourceHighWater);
159
+ ctx.down([
160
+ ["DATA", { kind: "frame", frame: { state: state.value, highWater: state.highWater } }],
161
+ [
162
+ "DATA",
163
+ {
164
+ kind: "status",
165
+ status: {
166
+ kind: "projected",
167
+ projectionId,
168
+ recordSeq: record.recordSeq,
169
+ timestampMs: now()
170
+ }
171
+ }
172
+ ],
173
+ ["DATA", { kind: "high-water", highWater: state.highWater }]
174
+ ]);
175
+ } catch (error) {
176
+ const issue = dataIssue(
177
+ "event-flow-projection-threw",
178
+ error instanceof Error ? error.message : "eventFlowProjection reducer threw",
179
+ { projectionId, record }
180
+ );
181
+ ctx.down([
182
+ ["DATA", { kind: "issue", issue }],
183
+ [
184
+ "DATA",
185
+ {
186
+ kind: "status",
187
+ status: {
188
+ kind: "rejected",
189
+ projectionId,
190
+ recordSeq: record.recordSeq,
191
+ issueCode: issue.code,
192
+ timestampMs: now()
193
+ }
194
+ }
195
+ ]
196
+ ]);
197
+ }
198
+ }
199
+ ctx.state.set(state);
200
+ },
201
+ {
202
+ name: `${name}/runtime`,
203
+ factory: "eventFlowProjectionRuntime",
204
+ meta: { projectionId },
205
+ completeWhenDepsComplete: false,
206
+ errorWhenDepsError: false
207
+ }
208
+ );
209
+ return {
210
+ frames: projectionRuntime(
211
+ graph,
212
+ runtime,
213
+ "frame",
214
+ `${name}/frames`,
215
+ "eventFlowProjectionFrames"
216
+ ),
217
+ snapshot: projectionRuntime(
218
+ graph,
219
+ runtime,
220
+ "frame",
221
+ `${name}/snapshot`,
222
+ "eventFlowProjectionSnapshot",
223
+ (fact) => fact.frame.state
224
+ ),
225
+ status: projectionRuntime(
226
+ graph,
227
+ runtime,
228
+ "status",
229
+ `${name}/status`,
230
+ "eventFlowProjectionStatus"
231
+ ),
232
+ issues: projectionRuntime(
233
+ graph,
234
+ runtime,
235
+ "issue",
236
+ `${name}/issues`,
237
+ "eventFlowProjectionIssues"
238
+ ),
239
+ highWater: projectionRuntime(
240
+ graph,
241
+ runtime,
242
+ "high-water",
243
+ `${name}/highWater`,
244
+ "eventFlowProjectionHighWater"
245
+ )
246
+ };
247
+ }
248
+ function reduceEventSource(raw, source, flowId, timestampMs, state, emit) {
249
+ const normalized = normalizeInput(raw, source);
250
+ if (normalized.issue !== void 0) {
251
+ const status2 = {
252
+ kind: "rejected",
253
+ flowId,
254
+ source: normalized.source,
255
+ issueCode: normalized.issue.code,
256
+ timestampMs
257
+ };
258
+ const audit2 = auditRecord(flowId, state, "rejected", timestampMs, {
259
+ source: normalized.source,
260
+ issueCode: normalized.issue.code
261
+ });
262
+ emit({ kind: "issue", issue: normalized.issue });
263
+ emit({ kind: "status", status: status2 });
264
+ emit({ kind: "audit", audit: audit2 });
265
+ emit({ kind: "high-water", highWater: highWaterSnapshot(flowId, state) });
266
+ return;
267
+ }
268
+ const recordSeq = ++state.recordSeq;
269
+ const record = {
270
+ recordSeq,
271
+ flowId,
272
+ event: normalized.event,
273
+ source: normalized.source,
274
+ observedAtMs: timestampMs,
275
+ ...normalized.event.correlationId === void 0 ? {} : { correlationId: normalized.event.correlationId },
276
+ ...normalized.event.causationId === void 0 ? {} : { causationId: normalized.event.causationId }
277
+ };
278
+ state.highWater.set(sourceKey(normalized.source), {
279
+ source: normalized.source.source,
280
+ ...normalized.source.topic === void 0 ? {} : { topic: normalized.source.topic },
281
+ ...normalized.source.seq === void 0 ? {} : { seq: normalized.source.seq },
282
+ messageId: normalized.event.id,
283
+ recordSeq
284
+ });
285
+ const audit = auditRecord(flowId, state, "recorded", timestampMs, {
286
+ source: normalized.source,
287
+ eventId: normalized.event.id,
288
+ eventType: normalized.event.type
289
+ });
290
+ const highWater = highWaterSnapshot(flowId, state);
291
+ const status = {
292
+ kind: "recorded",
293
+ flowId,
294
+ recordSeq,
295
+ eventId: normalized.event.id,
296
+ eventType: normalized.event.type,
297
+ source: normalized.source,
298
+ timestampMs
299
+ };
300
+ emit({ kind: "record", record });
301
+ emit({ kind: "status", status });
302
+ emit({ kind: "audit", audit });
303
+ emit({ kind: "high-water", highWater });
304
+ }
305
+ function normalizeInput(raw, source) {
306
+ const envelope = messageEnvelopeOf(raw);
307
+ const value = envelope?.payload ?? raw;
308
+ const sourceRef = envelope === void 0 ? { source, ...eventIdOf(value) === void 0 ? {} : { messageId: eventIdOf(value) } } : {
309
+ source,
310
+ topic: envelope.topic,
311
+ seq: envelope.seq,
312
+ messageId: envelope.payload.id,
313
+ ...envelope.idempotencyKey === void 0 ? {} : { idempotencyKey: envelope.idempotencyKey }
314
+ };
315
+ const issue = eventMessageIssue(value);
316
+ if (issue !== void 0) {
317
+ return {
318
+ source: sourceRef,
319
+ issue: dataIssue(issue.code, issue.message, { source: sourceRef, value })
320
+ };
321
+ }
322
+ return { event: value, source: sourceRef };
323
+ }
324
+ function messageEnvelopeOf(value) {
325
+ if (!isRecord(value)) return void 0;
326
+ if (typeof value.topic !== "string" || !Number.isInteger(value.seq) || typeof value.timestampMs !== "number" || !("payload" in value)) {
327
+ return void 0;
328
+ }
329
+ const payloadIssue = eventMessageIssue(value.payload);
330
+ return payloadIssue === void 0 ? value : void 0;
331
+ }
332
+ function normalizeSources(sources) {
333
+ if (sources.length === 0) throw new Error("eventFlow: sources must be non-empty");
334
+ return sources.map((source, index) => {
335
+ if (isRecord(source) && "node" in source) {
336
+ if (typeof source.source !== "string" || source.source.length === 0) {
337
+ throw new Error("eventFlow: source name must be non-empty");
338
+ }
339
+ return source;
340
+ }
341
+ return { source: `source-${index}`, node: source };
342
+ });
343
+ }
344
+ function runtimeProjection(graph, runtime, kind, name, factory) {
345
+ return graph.node(
346
+ [runtime],
347
+ (ctx) => {
348
+ for (const fact of depBatch(ctx, 0) ?? []) {
349
+ const typed = fact;
350
+ if (typed.kind === kind) ctx.down([["DATA", valueOfRuntimeFact(typed)]]);
351
+ }
352
+ },
353
+ { name, factory, completeWhenDepsComplete: false, errorWhenDepsError: false }
354
+ );
355
+ }
356
+ function projectionRuntime(graph, runtime, kind, name, factory, map = valueOfRuntimeFact) {
357
+ return graph.node(
358
+ [runtime],
359
+ (ctx) => {
360
+ for (const fact of depBatch(ctx, 0) ?? []) {
361
+ const typed = fact;
362
+ if (typed.kind === kind) ctx.down([["DATA", map(typed)]]);
363
+ }
364
+ },
365
+ { name, factory, completeWhenDepsComplete: false, errorWhenDepsError: false }
366
+ );
367
+ }
368
+ function valueOfRuntimeFact(fact) {
369
+ if ("record" in fact) return fact.record;
370
+ if ("status" in fact) return fact.status;
371
+ if ("issue" in fact) return fact.issue;
372
+ if ("audit" in fact) return fact.audit;
373
+ if ("highWater" in fact) return fact.highWater;
374
+ if ("frame" in fact) return fact.frame;
375
+ return void 0;
376
+ }
377
+ function auditRecord(flowId, state, outcome, timestampMs, opts) {
378
+ return {
379
+ seq: ++state.auditSeq,
380
+ flowId,
381
+ outcome,
382
+ ...opts.eventId === void 0 ? {} : { eventId: opts.eventId },
383
+ ...opts.eventType === void 0 ? {} : { eventType: opts.eventType },
384
+ ...opts.issueCode === void 0 ? {} : { issueCode: opts.issueCode },
385
+ ...opts.source === void 0 ? {} : { source: opts.source },
386
+ highWater: highWaterSnapshot(flowId, state),
387
+ timestampMs
388
+ };
389
+ }
390
+ function highWaterSnapshot(flowId, state) {
391
+ return {
392
+ flowId,
393
+ recordSeq: state.recordSeq,
394
+ auditSeq: state.auditSeq,
395
+ sources: [...state.highWater.values()].sort(
396
+ (a, b) => a.source.localeCompare(b.source) || (a.topic ?? "").localeCompare(b.topic ?? "")
397
+ )
398
+ };
399
+ }
400
+ function emptyHighWater(flowId) {
401
+ return { flowId, recordSeq: 0, auditSeq: 0, sources: [] };
402
+ }
403
+ function projectionHighWater(flowId, record, sourceHighWater) {
404
+ sourceHighWater.set(sourceKey(record.source), {
405
+ source: record.source.source,
406
+ ...record.source.topic === void 0 ? {} : { topic: record.source.topic },
407
+ ...record.source.seq === void 0 ? {} : { seq: record.source.seq },
408
+ messageId: record.event.id,
409
+ recordSeq: record.recordSeq
410
+ });
411
+ return {
412
+ flowId,
413
+ recordSeq: record.recordSeq,
414
+ auditSeq: 0,
415
+ sources: [...sourceHighWater.values()].sort(
416
+ (a, b) => a.source.localeCompare(b.source) || (a.topic ?? "").localeCompare(b.topic ?? "")
417
+ )
418
+ };
419
+ }
420
+ function sourceKey(source) {
421
+ return `${source.source}\0${source.topic ?? ""}`;
422
+ }
423
+ function eventIdOf(value) {
424
+ return isRecord(value) && typeof value.id === "string" ? value.id : void 0;
425
+ }
426
+ function dataIssue(code, message, details) {
427
+ return {
428
+ kind: "issue",
429
+ code,
430
+ message,
431
+ severity: "error",
432
+ source: "eventFlow",
433
+ ...details === void 0 ? {} : { details }
434
+ };
435
+ }
436
+ function isEventFlowBundle(value) {
437
+ return isRecord(value) && "records" in value && "highWater" in value;
438
+ }
439
+ function isRecord(value) {
440
+ return typeof value === "object" && value !== null && !Array.isArray(value);
441
+ }
442
+ // Annotate the CommonJS export names for ESM import in node:
443
+ 0 && (module.exports = {
444
+ eventFlow,
445
+ eventFlowProjection
446
+ });
447
+ //# sourceMappingURL=event-flow.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/patterns/event-flow.ts","../../src/protocol/messages.ts","../../src/ctx/types.ts","../../src/messaging/index.ts"],"sourcesContent":["/**\n * Event-flow projector helpers (D326/D329/D331).\n *\n * eventFlow consumes declared graph sources that emit EventMessage or\n * MessageEnvelope<EventMessage>. It records projection facts and high-water over\n * source coordinates; it does not own topics, subscriptions, cursors, retention,\n * ack/seek/close, queues, workers, or dead-letter policy.\n */\n\nimport { depBatch } from \"../ctx/types.js\";\nimport type { DataIssue } from \"../data/index.js\";\nimport type { Graph } from \"../graph/graph.js\";\nimport type { EventMessage, MessageEnvelope } from \"../messaging/index.js\";\nimport { eventMessageIssue } from \"../messaging/index.js\";\nimport type { Node } from \"../node/node.js\";\n\nexport interface EventFlowSource<T = unknown> {\n\treadonly source: string;\n\treadonly node: Node<EventMessage<T> | MessageEnvelope<EventMessage<T>> | unknown>;\n}\n\nexport type EventFlowSourceInput<T = unknown> =\n\t| Node<EventMessage<T> | MessageEnvelope<EventMessage<T>> | unknown>\n\t| EventFlowSource<T>;\n\nexport interface EventFlowSourceRef {\n\treadonly source: string;\n\treadonly topic?: string;\n\treadonly seq?: number;\n\treadonly messageId?: string;\n\treadonly idempotencyKey?: string;\n}\n\nexport interface EventFlowRecord<T = unknown> {\n\treadonly recordSeq: number;\n\treadonly flowId: string;\n\treadonly event: EventMessage<T>;\n\treadonly source: EventFlowSourceRef;\n\treadonly observedAtMs: number;\n\treadonly correlationId?: string;\n\treadonly causationId?: string;\n}\n\nexport interface EventFlowStatus {\n\treadonly kind: \"recorded\" | \"rejected\" | \"projection-ready\" | \"projection-stale\";\n\treadonly flowId: string;\n\treadonly recordSeq?: number;\n\treadonly eventId?: string;\n\treadonly eventType?: string;\n\treadonly source?: EventFlowSourceRef;\n\treadonly issueCode?: string;\n\treadonly timestampMs: number;\n}\n\nexport interface EventFlowAuditRecord {\n\treadonly seq: number;\n\treadonly flowId: string;\n\treadonly outcome: \"recorded\" | \"rejected\";\n\treadonly eventId?: string;\n\treadonly eventType?: string;\n\treadonly issueCode?: string;\n\treadonly source?: EventFlowSourceRef;\n\treadonly highWater: EventFlowHighWater;\n\treadonly timestampMs: number;\n}\n\nexport interface EventFlowSourceHighWater {\n\treadonly source: string;\n\treadonly topic?: string;\n\treadonly seq?: number;\n\treadonly messageId?: string;\n\treadonly recordSeq: number;\n}\n\nexport interface EventFlowHighWater {\n\treadonly flowId: string;\n\treadonly recordSeq: number;\n\treadonly auditSeq: number;\n\treadonly sources: readonly EventFlowSourceHighWater[];\n}\n\nexport interface EventFlowOptions<T = unknown> {\n\treadonly flowId?: string;\n\treadonly name?: string;\n\treadonly sources: readonly EventFlowSourceInput<T>[];\n\treadonly now?: () => number;\n}\n\nexport interface EventFlowBundle<T = unknown> {\n\treadonly records: Node<EventFlowRecord<T>>;\n\treadonly status: Node<EventFlowStatus>;\n\treadonly issues: Node<DataIssue>;\n\treadonly audit: Node<EventFlowAuditRecord>;\n\treadonly highWater: Node<EventFlowHighWater>;\n}\n\nexport interface EventFlowProjectionFrame<TState> {\n\treadonly state: TState;\n\treadonly highWater: EventFlowHighWater;\n}\n\nexport interface EventFlowProjectionStatus {\n\treadonly kind: \"projected\" | \"rejected\";\n\treadonly projectionId: string;\n\treadonly recordSeq?: number;\n\treadonly issueCode?: string;\n\treadonly timestampMs: number;\n}\n\nexport interface EventFlowProjectionOptions<TState, TPayload = unknown> {\n\treadonly projectionId?: string;\n\treadonly name?: string;\n\treadonly initial: TState;\n\treadonly reduce: (state: TState, record: EventFlowRecord<TPayload>) => TState;\n\treadonly now?: () => number;\n}\n\nexport interface EventFlowProjectionBundle<TState> {\n\treadonly snapshot: Node<TState>;\n\treadonly frames: Node<EventFlowProjectionFrame<TState>>;\n\treadonly status: Node<EventFlowProjectionStatus>;\n\treadonly issues: Node<DataIssue>;\n\treadonly highWater: Node<EventFlowHighWater>;\n}\n\ntype EventFlowRuntimeFact<T = unknown> =\n\t| { readonly kind: \"record\"; readonly record: EventFlowRecord<T> }\n\t| { readonly kind: \"status\"; readonly status: EventFlowStatus }\n\t| { readonly kind: \"issue\"; readonly issue: DataIssue }\n\t| { readonly kind: \"audit\"; readonly audit: EventFlowAuditRecord }\n\t| { readonly kind: \"high-water\"; readonly highWater: EventFlowHighWater };\n\ninterface EventFlowRuntimeState {\n\trecordSeq: number;\n\tauditSeq: number;\n\thighWater: Map<string, EventFlowSourceHighWater>;\n}\n\nexport function eventFlow<T = unknown>(\n\tgraph: Graph,\n\topts: EventFlowOptions<T>,\n): EventFlowBundle<T> {\n\tconst name = opts.name ?? opts.flowId ?? \"eventFlow\";\n\tconst flowId = opts.flowId ?? name;\n\tconst now = opts.now ?? Date.now;\n\tconst sources = normalizeSources(opts.sources);\n\tconst runtime = graph.node<EventFlowRuntimeFact<T>>(\n\t\tsources.map((source) => source.node),\n\t\t(ctx) => {\n\t\t\tconst state =\n\t\t\t\tctx.state.get<EventFlowRuntimeState>() ??\n\t\t\t\t({\n\t\t\t\t\trecordSeq: 0,\n\t\t\t\t\tauditSeq: 0,\n\t\t\t\t\thighWater: new Map(),\n\t\t\t\t} satisfies EventFlowRuntimeState);\n\t\t\tctx.state.persist(true);\n\t\t\tfor (let i = 0; i < sources.length; i++) {\n\t\t\t\tconst source = sources[i];\n\t\t\t\tfor (const raw of depBatch(ctx, i) ?? []) {\n\t\t\t\t\treduceEventSource(raw, source.source, flowId, now(), state, (fact) =>\n\t\t\t\t\t\tctx.down([[\"DATA\", fact as EventFlowRuntimeFact<T>]]),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t\tctx.state.set(state);\n\t\t},\n\t\t{\n\t\t\tname: `${name}/runtime`,\n\t\t\tfactory: \"eventFlowRuntime\",\n\t\t\tmeta: { flowId, sources: sources.map((source) => source.source) },\n\t\t\tpartial: true,\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n\treturn {\n\t\trecords: runtimeProjection(graph, runtime, \"record\", `${name}/records`, \"eventFlowRecords\"),\n\t\tstatus: runtimeProjection(graph, runtime, \"status\", `${name}/status`, \"eventFlowStatus\"),\n\t\tissues: runtimeProjection(graph, runtime, \"issue\", `${name}/issues`, \"eventFlowIssues\"),\n\t\taudit: runtimeProjection(graph, runtime, \"audit\", `${name}/audit`, \"eventFlowAudit\"),\n\t\thighWater: runtimeProjection(\n\t\t\tgraph,\n\t\t\truntime,\n\t\t\t\"high-water\",\n\t\t\t`${name}/highWater`,\n\t\t\t\"eventFlowHighWater\",\n\t\t),\n\t};\n}\n\nexport function eventFlowProjection<TState, TPayload = unknown>(\n\tgraph: Graph,\n\tflowOrRecords: EventFlowBundle<TPayload> | Node<EventFlowRecord<TPayload>>,\n\topts: EventFlowProjectionOptions<TState, TPayload>,\n): EventFlowProjectionBundle<TState> {\n\tconst records = isEventFlowBundle(flowOrRecords) ? flowOrRecords.records : flowOrRecords;\n\tconst name = opts.name ?? opts.projectionId ?? \"eventFlowProjection\";\n\tconst projectionId = opts.projectionId ?? name;\n\tconst now = opts.now ?? Date.now;\n\tconst runtime = graph.node<\n\t\t| { readonly kind: \"frame\"; readonly frame: EventFlowProjectionFrame<TState> }\n\t\t| { readonly kind: \"status\"; readonly status: EventFlowProjectionStatus }\n\t\t| { readonly kind: \"issue\"; readonly issue: DataIssue }\n\t\t| { readonly kind: \"high-water\"; readonly highWater: EventFlowHighWater }\n\t>(\n\t\t[records],\n\t\t(ctx) => {\n\t\t\tconst state = ctx.state.get<{\n\t\t\t\tvalue: TState;\n\t\t\t\thighWater: EventFlowHighWater;\n\t\t\t\tsourceHighWater: Map<string, EventFlowSourceHighWater>;\n\t\t\t}>() ?? {\n\t\t\t\tvalue: opts.initial,\n\t\t\t\thighWater: emptyHighWater(projectionId),\n\t\t\t\tsourceHighWater: new Map(),\n\t\t\t};\n\t\t\tctx.state.persist(true);\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst record = raw as EventFlowRecord<TPayload>;\n\t\t\t\ttry {\n\t\t\t\t\tstate.value = opts.reduce(state.value, record);\n\t\t\t\t\tstate.highWater = projectionHighWater(projectionId, record, state.sourceHighWater);\n\t\t\t\t\tctx.down([\n\t\t\t\t\t\t[\"DATA\", { kind: \"frame\", frame: { state: state.value, highWater: state.highWater } }],\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tkind: \"status\",\n\t\t\t\t\t\t\t\tstatus: {\n\t\t\t\t\t\t\t\t\tkind: \"projected\",\n\t\t\t\t\t\t\t\t\tprojectionId,\n\t\t\t\t\t\t\t\t\trecordSeq: record.recordSeq,\n\t\t\t\t\t\t\t\t\ttimestampMs: now(),\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t],\n\t\t\t\t\t\t[\"DATA\", { kind: \"high-water\", highWater: state.highWater }],\n\t\t\t\t\t]);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tconst issue = dataIssue(\n\t\t\t\t\t\t\"event-flow-projection-threw\",\n\t\t\t\t\t\terror instanceof Error ? error.message : \"eventFlowProjection reducer threw\",\n\t\t\t\t\t\t{ projectionId, record },\n\t\t\t\t\t);\n\t\t\t\t\tctx.down([\n\t\t\t\t\t\t[\"DATA\", { kind: \"issue\", issue }],\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tkind: \"status\",\n\t\t\t\t\t\t\t\tstatus: {\n\t\t\t\t\t\t\t\t\tkind: \"rejected\",\n\t\t\t\t\t\t\t\t\tprojectionId,\n\t\t\t\t\t\t\t\t\trecordSeq: record.recordSeq,\n\t\t\t\t\t\t\t\t\tissueCode: issue.code,\n\t\t\t\t\t\t\t\t\ttimestampMs: now(),\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t],\n\t\t\t\t\t]);\n\t\t\t\t}\n\t\t\t}\n\t\t\tctx.state.set(state);\n\t\t},\n\t\t{\n\t\t\tname: `${name}/runtime`,\n\t\t\tfactory: \"eventFlowProjectionRuntime\",\n\t\t\tmeta: { projectionId },\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n\treturn {\n\t\tframes: projectionRuntime(\n\t\t\tgraph,\n\t\t\truntime,\n\t\t\t\"frame\",\n\t\t\t`${name}/frames`,\n\t\t\t\"eventFlowProjectionFrames\",\n\t\t),\n\t\tsnapshot: projectionRuntime(\n\t\t\tgraph,\n\t\t\truntime,\n\t\t\t\"frame\",\n\t\t\t`${name}/snapshot`,\n\t\t\t\"eventFlowProjectionSnapshot\",\n\t\t\t(fact) => (fact as { readonly frame: EventFlowProjectionFrame<TState> }).frame.state,\n\t\t),\n\t\tstatus: projectionRuntime(\n\t\t\tgraph,\n\t\t\truntime,\n\t\t\t\"status\",\n\t\t\t`${name}/status`,\n\t\t\t\"eventFlowProjectionStatus\",\n\t\t),\n\t\tissues: projectionRuntime(\n\t\t\tgraph,\n\t\t\truntime,\n\t\t\t\"issue\",\n\t\t\t`${name}/issues`,\n\t\t\t\"eventFlowProjectionIssues\",\n\t\t),\n\t\thighWater: projectionRuntime(\n\t\t\tgraph,\n\t\t\truntime,\n\t\t\t\"high-water\",\n\t\t\t`${name}/highWater`,\n\t\t\t\"eventFlowProjectionHighWater\",\n\t\t),\n\t};\n}\n\nfunction reduceEventSource<T>(\n\traw: unknown,\n\tsource: string,\n\tflowId: string,\n\ttimestampMs: number,\n\tstate: EventFlowRuntimeState,\n\temit: (fact: EventFlowRuntimeFact<T>) => void,\n): void {\n\tconst normalized = normalizeInput(raw, source);\n\tif (normalized.issue !== undefined) {\n\t\tconst status: EventFlowStatus = {\n\t\t\tkind: \"rejected\",\n\t\t\tflowId,\n\t\t\tsource: normalized.source,\n\t\t\tissueCode: normalized.issue.code,\n\t\t\ttimestampMs,\n\t\t};\n\t\tconst audit = auditRecord(flowId, state, \"rejected\", timestampMs, {\n\t\t\tsource: normalized.source,\n\t\t\tissueCode: normalized.issue.code,\n\t\t});\n\t\temit({ kind: \"issue\", issue: normalized.issue });\n\t\temit({ kind: \"status\", status });\n\t\temit({ kind: \"audit\", audit });\n\t\temit({ kind: \"high-water\", highWater: highWaterSnapshot(flowId, state) });\n\t\treturn;\n\t}\n\n\tconst recordSeq = ++state.recordSeq;\n\tconst record: EventFlowRecord<T> = {\n\t\trecordSeq,\n\t\tflowId,\n\t\tevent: normalized.event as EventMessage<T>,\n\t\tsource: normalized.source,\n\t\tobservedAtMs: timestampMs,\n\t\t...(normalized.event.correlationId === undefined\n\t\t\t? {}\n\t\t\t: { correlationId: normalized.event.correlationId }),\n\t\t...(normalized.event.causationId === undefined\n\t\t\t? {}\n\t\t\t: { causationId: normalized.event.causationId }),\n\t};\n\tstate.highWater.set(sourceKey(normalized.source), {\n\t\tsource: normalized.source.source,\n\t\t...(normalized.source.topic === undefined ? {} : { topic: normalized.source.topic }),\n\t\t...(normalized.source.seq === undefined ? {} : { seq: normalized.source.seq }),\n\t\tmessageId: normalized.event.id,\n\t\trecordSeq,\n\t});\n\tconst audit = auditRecord(flowId, state, \"recorded\", timestampMs, {\n\t\tsource: normalized.source,\n\t\teventId: normalized.event.id,\n\t\teventType: normalized.event.type,\n\t});\n\tconst highWater = highWaterSnapshot(flowId, state);\n\tconst status: EventFlowStatus = {\n\t\tkind: \"recorded\",\n\t\tflowId,\n\t\trecordSeq,\n\t\teventId: normalized.event.id,\n\t\teventType: normalized.event.type,\n\t\tsource: normalized.source,\n\t\ttimestampMs,\n\t};\n\temit({ kind: \"record\", record });\n\temit({ kind: \"status\", status });\n\temit({ kind: \"audit\", audit });\n\temit({ kind: \"high-water\", highWater });\n}\n\nfunction normalizeInput(\n\traw: unknown,\n\tsource: string,\n):\n\t| {\n\t\t\treadonly event: EventMessage;\n\t\t\treadonly source: EventFlowSourceRef;\n\t\t\treadonly issue?: undefined;\n\t }\n\t| { readonly source: EventFlowSourceRef; readonly issue: DataIssue } {\n\tconst envelope = messageEnvelopeOf(raw);\n\tconst value = envelope?.payload ?? raw;\n\tconst sourceRef: EventFlowSourceRef =\n\t\tenvelope === undefined\n\t\t\t? { source, ...(eventIdOf(value) === undefined ? {} : { messageId: eventIdOf(value) }) }\n\t\t\t: {\n\t\t\t\t\tsource,\n\t\t\t\t\ttopic: envelope.topic,\n\t\t\t\t\tseq: envelope.seq,\n\t\t\t\t\tmessageId: envelope.payload.id,\n\t\t\t\t\t...(envelope.idempotencyKey === undefined\n\t\t\t\t\t\t? {}\n\t\t\t\t\t\t: { idempotencyKey: envelope.idempotencyKey }),\n\t\t\t\t};\n\tconst issue = eventMessageIssue(value);\n\tif (issue !== undefined) {\n\t\treturn {\n\t\t\tsource: sourceRef,\n\t\t\tissue: dataIssue(issue.code, issue.message, { source: sourceRef, value }),\n\t\t};\n\t}\n\treturn { event: value as EventMessage, source: sourceRef };\n}\n\nfunction messageEnvelopeOf(value: unknown): MessageEnvelope<EventMessage> | undefined {\n\tif (!isRecord(value)) return undefined;\n\tif (\n\t\ttypeof value.topic !== \"string\" ||\n\t\t!Number.isInteger(value.seq) ||\n\t\ttypeof value.timestampMs !== \"number\" ||\n\t\t!(\"payload\" in value)\n\t) {\n\t\treturn undefined;\n\t}\n\tconst payloadIssue = eventMessageIssue(value.payload);\n\treturn payloadIssue === undefined\n\t\t? (value as unknown as MessageEnvelope<EventMessage>)\n\t\t: undefined;\n}\n\nfunction normalizeSources<T>(\n\tsources: readonly EventFlowSourceInput<T>[],\n): readonly EventFlowSource[] {\n\tif (sources.length === 0) throw new Error(\"eventFlow: sources must be non-empty\");\n\treturn sources.map((source, index) => {\n\t\tif (isRecord(source) && \"node\" in source) {\n\t\t\tif (typeof source.source !== \"string\" || source.source.length === 0) {\n\t\t\t\tthrow new Error(\"eventFlow: source name must be non-empty\");\n\t\t\t}\n\t\t\treturn source as EventFlowSource;\n\t\t}\n\t\treturn { source: `source-${index}`, node: source as EventFlowSource[\"node\"] };\n\t});\n}\n\nfunction runtimeProjection<TOut, T>(\n\tgraph: Graph,\n\truntime: Node<EventFlowRuntimeFact<T>>,\n\tkind: EventFlowRuntimeFact<T>[\"kind\"],\n\tname: string,\n\tfactory: string,\n): Node<TOut> {\n\treturn graph.node<TOut>(\n\t\t[runtime],\n\t\t(ctx) => {\n\t\t\tfor (const fact of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst typed = fact as EventFlowRuntimeFact<T>;\n\t\t\t\tif (typed.kind === kind) ctx.down([[\"DATA\", valueOfRuntimeFact(typed) as TOut]]);\n\t\t\t}\n\t\t},\n\t\t{ name, factory, completeWhenDepsComplete: false, errorWhenDepsError: false },\n\t);\n}\n\nfunction projectionRuntime<TOut, TFact extends { readonly kind: string }>(\n\tgraph: Graph,\n\truntime: Node<TFact>,\n\tkind: TFact[\"kind\"],\n\tname: string,\n\tfactory: string,\n\tmap: (fact: Extract<TFact, { readonly kind: typeof kind }>) => TOut = valueOfRuntimeFact as never,\n): Node<TOut> {\n\treturn graph.node<TOut>(\n\t\t[runtime],\n\t\t(ctx) => {\n\t\t\tfor (const fact of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst typed = fact as TFact;\n\t\t\t\tif (typed.kind === kind) ctx.down([[\"DATA\", map(typed as never)]]);\n\t\t\t}\n\t\t},\n\t\t{ name, factory, completeWhenDepsComplete: false, errorWhenDepsError: false },\n\t);\n}\n\nfunction valueOfRuntimeFact(fact: { readonly kind: string }): unknown {\n\tif (\"record\" in fact) return fact.record;\n\tif (\"status\" in fact) return fact.status;\n\tif (\"issue\" in fact) return fact.issue;\n\tif (\"audit\" in fact) return fact.audit;\n\tif (\"highWater\" in fact) return fact.highWater;\n\tif (\"frame\" in fact) return fact.frame;\n\treturn undefined;\n}\n\nfunction auditRecord(\n\tflowId: string,\n\tstate: EventFlowRuntimeState,\n\toutcome: \"recorded\" | \"rejected\",\n\ttimestampMs: number,\n\topts: {\n\t\treadonly source?: EventFlowSourceRef;\n\t\treadonly eventId?: string;\n\t\treadonly eventType?: string;\n\t\treadonly issueCode?: string;\n\t},\n): EventFlowAuditRecord {\n\treturn {\n\t\tseq: ++state.auditSeq,\n\t\tflowId,\n\t\toutcome,\n\t\t...(opts.eventId === undefined ? {} : { eventId: opts.eventId }),\n\t\t...(opts.eventType === undefined ? {} : { eventType: opts.eventType }),\n\t\t...(opts.issueCode === undefined ? {} : { issueCode: opts.issueCode }),\n\t\t...(opts.source === undefined ? {} : { source: opts.source }),\n\t\thighWater: highWaterSnapshot(flowId, state),\n\t\ttimestampMs,\n\t};\n}\n\nfunction highWaterSnapshot(flowId: string, state: EventFlowRuntimeState): EventFlowHighWater {\n\treturn {\n\t\tflowId,\n\t\trecordSeq: state.recordSeq,\n\t\tauditSeq: state.auditSeq,\n\t\tsources: [...state.highWater.values()].sort(\n\t\t\t(a, b) => a.source.localeCompare(b.source) || (a.topic ?? \"\").localeCompare(b.topic ?? \"\"),\n\t\t),\n\t};\n}\n\nfunction emptyHighWater(flowId: string): EventFlowHighWater {\n\treturn { flowId, recordSeq: 0, auditSeq: 0, sources: [] };\n}\n\nfunction projectionHighWater(\n\tflowId: string,\n\trecord: EventFlowRecord,\n\tsourceHighWater: Map<string, EventFlowSourceHighWater>,\n): EventFlowHighWater {\n\tsourceHighWater.set(sourceKey(record.source), {\n\t\tsource: record.source.source,\n\t\t...(record.source.topic === undefined ? {} : { topic: record.source.topic }),\n\t\t...(record.source.seq === undefined ? {} : { seq: record.source.seq }),\n\t\tmessageId: record.event.id,\n\t\trecordSeq: record.recordSeq,\n\t});\n\treturn {\n\t\tflowId,\n\t\trecordSeq: record.recordSeq,\n\t\tauditSeq: 0,\n\t\tsources: [...sourceHighWater.values()].sort(\n\t\t\t(a, b) => a.source.localeCompare(b.source) || (a.topic ?? \"\").localeCompare(b.topic ?? \"\"),\n\t\t),\n\t};\n}\n\nfunction sourceKey(source: EventFlowSourceRef): string {\n\treturn `${source.source}\\u0000${source.topic ?? \"\"}`;\n}\n\nfunction eventIdOf(value: unknown): string | undefined {\n\treturn isRecord(value) && typeof value.id === \"string\" ? value.id : undefined;\n}\n\nfunction dataIssue(code: string, message: string, details?: unknown): DataIssue {\n\treturn {\n\t\tkind: \"issue\",\n\t\tcode,\n\t\tmessage,\n\t\tseverity: \"error\",\n\t\tsource: \"eventFlow\",\n\t\t...(details === undefined ? {} : { details }),\n\t};\n}\n\nfunction isEventFlowBundle<T>(value: unknown): value is EventFlowBundle<T> {\n\treturn isRecord(value) && \"records\" in value && \"highWater\" in value;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n","/**\n * Wave-protocol message types and the tier const table.\n *\n * Canonical authority: ~/src/graphrefly/spec/rules.jsonl\n * R-msg-format, R-msg-closed-set, R-tier (D34), R-data-payload, R-sentinel.\n */\n\n/** Opaque pause-lock / pull identifier (R-pause-lockset, R-pull). */\nexport type LockId = string | symbol;\n\n/** Explicit pull demand payload (D269/D272). Params are holder-visible context, never DATA-up. */\nexport interface PullDemand {\n\treadonly pullId: LockId;\n\treadonly params?: unknown;\n}\n\n/**\n * The CLOSED set of 11 message types (R-msg-closed-set / D9 + D269 + START handshake).\n * No open set, no user-defined custom types. Adding a type is a spec change.\n */\nexport type Message =\n\t| readonly [\"START\"]\n\t| readonly [\"DIRTY\"]\n\t| readonly [\"DATA\", unknown]\n\t| readonly [\"RESOLVED\"]\n\t| readonly [\"INVALIDATE\"]\n\t| readonly [\"COMPLETE\"]\n\t| readonly [\"ERROR\", unknown]\n\t| readonly [\"TEARDOWN\"]\n\t| readonly [\"PAUSE\", LockId]\n\t| readonly [\"RESUME\", LockId]\n\t| readonly [\"PULL\", PullDemand];\n\n/** One array of messages delivered in one call = one Wave (R-wave-boundary). */\nexport type Wave = readonly Message[];\n\n/** The message-type tag (the first tuple element). */\nexport type MessageType = Message[0];\n\n/**\n * SENTINEL = absence-of-DATA (R-sentinel / D16). TS representation is `undefined`.\n * Never a valid DATA payload; `null` IS a valid DATA value (domain-level absence).\n */\nexport const SENTINEL = undefined;\n\n/** R-data-payload: ERROR payloads must not collide with terminal metadata shorthand. */\nexport function isInvalidErrorPayload(v: unknown): boolean {\n\treturn v === SENTINEL || typeof v === \"boolean\";\n}\n\n/** R-data-payload / D78: host-language failures that collide with ctx.terminal shorthand become diagnostics. */\nexport function errorPayload(reason: unknown, fallback = \"error without a valid payload\"): unknown {\n\treturn isInvalidErrorPayload(reason) ? new Error(fallback) : reason;\n}\n\nexport const TIER_START = 0;\nexport const TIER_CONTROL = 1;\nexport const TIER_NOTIFICATION = 2;\nexport const TIER_VALUE = 3;\nexport const TIER_SETTLE = 4;\nexport const TIER_TERMINAL = 5;\nexport const TIER_TEARDOWN = 6;\n\n/**\n * Tier const table (R-tier / D34). Tiers below value dispatch immediately; value\n * and above are batch-deferred. This is a compile-time const table (D18), not runtime config.\n */\nconst TIER: Record<MessageType, number> = {\n\tSTART: TIER_START,\n\tPAUSE: TIER_CONTROL,\n\tRESUME: TIER_CONTROL,\n\tPULL: TIER_CONTROL,\n\tDIRTY: TIER_NOTIFICATION,\n\tDATA: TIER_VALUE,\n\tRESOLVED: TIER_VALUE,\n\tINVALIDATE: TIER_SETTLE,\n\tCOMPLETE: TIER_TERMINAL,\n\tERROR: TIER_TERMINAL,\n\tTEARDOWN: TIER_TEARDOWN,\n};\n\nexport function messageTier(t: MessageType): number {\n\treturn TIER[t];\n}\n\n/** Value and above are deferred inside a batch (DATA/RESOLVED/INVALIDATE/terminal/teardown). */\nexport function isDeferredTier(t: MessageType): boolean {\n\treturn TIER[t] >= TIER_VALUE;\n}\n\n/** Value-tier messages (DATA/RESOLVED) occupy the tier-3 slot. */\nexport function isValueTier(t: MessageType): boolean {\n\treturn TIER[t] === TIER_VALUE;\n}\n\n/** The pause buffer holds the settle slice only: value-tier DATA/RESOLVED plus INVALIDATE. */\nexport function isPauseBufferedTier(t: MessageType): boolean {\n\tconst tier = TIER[t];\n\treturn tier === TIER_VALUE || tier === TIER_SETTLE;\n}\n\n/**\n * A TERMINAL message = tier 5 (COMPLETE | ERROR), R-tier / D34. Detected via the CENTRAL tier\n * table, NOT a per-variant `=== \"COMPLETE\" || === \"ERROR\"` check — so terminal routing stays\n * driven by the one const table (feedback_use_tier_for_signal_routing); discriminate COMPLETE vs\n * ERROR within the tier by the message type only where the handling actually differs.\n */\nexport function isTerminal(t: MessageType): boolean {\n\treturn TIER[t] === TIER_TERMINAL;\n}\n\n/**\n * ctx.up carries control/demand tiers only (R-ctx-up / D269): DIRTY, PAUSE, RESUME, PULL,\n * INVALIDATE, TEARDOWN. DATA/RESOLVED (tier 3) and COMPLETE/ERROR (tier 5) are\n * down-only.\n */\nexport function isUpAllowed(t: MessageType): boolean {\n\tconst tier = TIER[t];\n\treturn tier !== TIER_VALUE && tier !== TIER_TERMINAL;\n}\n","/**\n * The fn-invocation context and per-dep input shapes.\n *\n * Canonical authority: ~/src/graphrefly/spec/rules.jsonl\n * R-fn-contract (D8/D27), R-ctx-state (D23/D29), R-cleanup-hooks (D28), R-ctx-up.\n */\n\nimport type { Dispatcher } from \"../dispatcher/index.js\";\nimport type { EnvironmentDrivers } from \"../graph/environment.js\";\nimport type { Node } from \"../node/node.js\";\nimport { type Message, type PullDemand, SENTINEL, type Wave } from \"../protocol/messages.js\";\n\n/** A downstream sink callback (the only way to connect to a node's output). */\nexport type Sink = (msg: Message, delivery?: DeliveryMeta) => void;\n\n/** Internal delivery metadata used to preserve the upstream `ctx.down(msgs)` wave boundary. */\nexport interface DeliveryMeta {\n\treadonly wave: object;\n\treadonly last: boolean;\n}\n\n/**\n * Internal current-value reader. It is deliberately a symbol-backed implementation detail:\n * raw ctx exposes `waveData` + `terminal`; helpers below derive from that plus this dep cache.\n */\nexport const CTX_DEP_CACHE: unique symbol = Symbol(\"graphrefly.ctx.depCache\");\n\nexport interface CtxDepCache {\n\treadonly latest: readonly unknown[];\n}\n\n/** Internal node-construction binding for graph-local helper-created deps. */\nexport const CTX_NODE_BINDING: unique symbol = Symbol(\"graphrefly.ctx.nodeBinding\");\n\nexport interface CtxNodeBinding {\n\treadonly dispatcher: Dispatcher;\n\tcreate<T>(factory: () => Node<T>): Node<T>;\n}\n\n/** Per-dep wave projections: dep -> waves -> values/SENTINEL markers. */\nexport type WaveData = readonly (readonly (readonly unknown[])[])[];\n\n/** Terminal metadata parallel to `waveData`: false = none, true = COMPLETE, otherwise ERROR payload. */\nexport type TerminalData = readonly unknown[];\n\nexport function isTerminalNone(t: unknown): boolean {\n\treturn t === false || t === undefined;\n}\n\nexport function isTerminalComplete(t: unknown): t is true {\n\treturn t === true;\n}\n\nexport function isTerminalError(t: unknown): boolean {\n\treturn !isTerminalNone(t) && !isTerminalComplete(t);\n}\n\nexport function terminalErrorValue(t: unknown): unknown {\n\treturn isTerminalError(t) ? t : undefined;\n}\n\n/**\n * Per-node private cross-wave state (R-ctx-state / D23,D29). Default fresh-lifecycle\n * wipe; `persist(true)` keeps it across lifecycle transitions.\n */\nexport interface CtxState {\n\tget<S = unknown>(): S | undefined;\n\tset<S = unknown>(v: S): void;\n\tpersist(on?: boolean): void;\n}\n\n/**\n * Deferred SELF-rewire (R-rewire-deferred / D47). A node fn may, DURING its run, request a\n * mutation of its OWN dep set; the request is QUEUED and applied at the committed wave boundary\n * (after the current wave settles / batch commit / final-lock RESUME) as a fresh wave, reusing\n * R-rewire surgical/Option-C semantics (D42). This is the ONLY legal self-triggered rewire — an\n * IMMEDIATE in-fn `node.subscribeDep/unsubscribeDep/replaceDeps` is the D37 mid-fn feedback-cycle ERROR. An\n * added cached dep pushes `[DIRTY,DATA]` on the boundary wave (R-push-subscribe); a removed dep\n * is drained and, if it loses its last subscriber, `_deactivate`s + fires `onDeactivation`\n * (input-side teardown — the basis for higher-order operator cancellation / abortInFlight).\n */\nexport interface RewireNext {\n\t/** Defer subscribing to a dep (paired with the re-supplied fn — positional fn-deps lock, SD-1). */\n\tsubscribeDep(dep: Node<unknown>, fn: NodeFn): void;\n\t/** Defer unsubscribing from a dep (its source is torn down if it loses its last subscriber). */\n\tunsubscribeDep(dep: Node<unknown>, fn: NodeFn): void;\n\t/** Defer replacing the whole dep set (surgical: kept deps untouched, removed drained, added fresh-subscribe). */\n\treplaceDeps(deps: Node<unknown>[], fn: NodeFn): void;\n}\n\n/**\n * The single argument to a node fn: `(ctx) => void` (R-fn-contract / D8). All emission\n * is explicit via `ctx.down`; there is no return-value framing.\n */\nexport interface Ctx {\n\t/**\n\t * Emit upstream toward deps — control tiers only (R-ctx-up). IMMEDIATE. `towardDep` (a dep index)\n\t * routes the wave up ONE declared edge (R-up-routing directed-up); omitted = broadcast up all deps.\n\t * A pull DEMAND is `up([[PULL, { pullId, params }]])` — but for a SELF-demand (demanding a dep\n\t * this fn also reads) use {@link Ctx.upNext} instead, since an immediate demand whose delivery loops back\n\t * re-enters this fn mid-wave (D37 / R-reentrancy).\n\t */\n\tup(msgs: Wave, towardDep?: number): void;\n\t/** Emit downstream toward sinks. */\n\tdown(msgs: Wave): void;\n\t/**\n\t * The single raw dep-value input surface (R-ctx-wave-data / D77): dep -> upstream waves ->\n\t * per-wave DATA payloads and INVALIDATE/SENTINEL markers. `waveData[i] = []` means dep i\n\t * delivered no wave to this invocation; `waveData[i] = [[]]` means RESOLVED-only.\n\t */\n\twaveData: WaveData;\n\t/** Terminal metadata for the same invocation; terminal values never enter `waveData`. */\n\tterminal: TerminalData;\n\tstate: CtxState;\n\t/** Release external resources on deactivation (R-cleanup-hooks). */\n\tonDeactivation(fn: () => void): void;\n\t/** Flush on INVALIDATE (R-cleanup-hooks). */\n\tonInvalidate(fn: () => void): void;\n\t/** Graph-owned environment drivers for source/adapter boundaries (D130/D131). */\n\tenvironment(): EnvironmentDrivers;\n\t/** Holder-visible context for a PULL-caused invocation (D272); absent for ordinary waves. */\n\treadonly pull?: PullDemand;\n\t/**\n\t * Deferred SELF-rewire (R-rewire-deferred / D47) — the substrate affordance higher-order\n\t * operators (switchMap/mergeMap/concatMap/exhaustMap/flatMap) use to grow/shrink their own\n\t * inner-source dep set in response to their own data. Always present; see {@link RewireNext}.\n\t */\n\trewireNext: RewireNext;\n\t/**\n\t * Deferred up — the boundary-deferred form of {@link Ctx.up} (R-up-routing / R-pull / D59). Routes\n\t * `msgs` up from this node at the COMMITTED wave boundary (broadcast, or up the single `towardDep`\n\t * edge), riding the same R-rewire-deferred (D47) drain as {@link RewireNext}. This is the\n\t * SELF-DEMAND path: a consumer issues `ctx.upNext([[PULL, { pullId, params }]])` to demand a pull\n\t * dep it ALSO reads — the cone-routed PULL reaches the pullId-holder, whose delivery loops back as a\n\t * FRESH wave (not a mid-fn re-entry → no D37). The consumer accepts one-wave latency (the\n\t * HTTP-request model). No node reference needed: the author writes the pullId verbatim.\n\t */\n\tupNext(msgs: Wave, towardDep?: number): void;\n\t/**\n\t * Read a dep's latest value by index (dynamicNode only, R-dynamic-node / D35).\n\t * Present only on dynamicNode fns; all declared deps still participate in wave\n\t * tracking. Under D49/R-resolved-undirty an unread dep's change still fires the fn,\n\t * which re-emits its (unchanged) output as a DATA occurrence — there is NO equals-\n\t * absorption; pair with distinctUntilChanged to suppress unchanged re-emits (opt-in).\n\t */\n\ttrack?(depIndex: number): unknown;\n\t[CTX_DEP_CACHE]?: CtxDepCache;\n\t[CTX_NODE_BINDING]?: CtxNodeBinding;\n}\n\n/** A node fn (R-fn-contract). Registered in a dispatcher pool, indexed by Handle. */\nexport type NodeFn = (ctx: Ctx) => void;\n\n/** Number of declared dep slots visible in this invocation. */\nexport function depCount(ctx: Ctx): number {\n\treturn ctx.waveData.length;\n}\n\n/** DATA/SENTINEL projection batches delivered by one dep in this invocation. */\nexport function depWaves(ctx: Ctx, depIndex: number): readonly (readonly unknown[])[] {\n\treturn ctx.waveData[depIndex] ?? [];\n}\n\n/** Flattened DATA projection for old event-counting operator bodies; null = no wave. */\nexport function depBatch(ctx: Ctx, depIndex: number): readonly unknown[] | null {\n\tconst waves = depWaves(ctx, depIndex);\n\tif (waves.length === 0) return null;\n\tconst flattened = waves.flat().filter((v) => v !== SENTINEL);\n\treturn flattened.length === 0 ? [] : flattened;\n}\n\n/** Latest cached DATA for a dep, derived from implementation-owned dep cache. */\nexport function depLatest(ctx: Ctx, depIndex: number): unknown {\n\treturn ctx[CTX_DEP_CACHE]?.latest[depIndex];\n}\n\n/** Terminal metadata for one dep: false = none, true = COMPLETE, otherwise ERROR payload. */\nexport function depTerminal(ctx: Ctx, depIndex: number): unknown {\n\tconst t = ctx.terminal[depIndex];\n\treturn t === undefined ? false : t;\n}\n","/**\n * Reusable application-infrastructure messaging namespace.\n *\n * D279/D282/D284/D285/D276: messageBus is a retained topic-log plus independent\n * subscription-cursor substrate. DynamicHub is intentionally retired; do not add aliases.\n */\n\nimport { depBatch, type NodeFn } from \"../ctx/types.js\";\nimport type { DataIssue } from \"../data/index.js\";\nimport type { Graph } from \"../graph/graph.js\";\nimport type { Node } from \"../node/node.js\";\nimport type { LockId, PullDemand } from \"../protocol/messages.js\";\nimport {\n\tattachMessageBusCommandSource,\n\tgetMessageBusState,\n\tregisterMessageBusState,\n} from \"./internal.js\";\n\nexport interface MessageEnvelope<T = unknown> {\n\treadonly topic: string;\n\treadonly seq: number;\n\treadonly payload: T;\n\treadonly key?: string;\n\treadonly idempotencyKey?: string;\n\treadonly timestampMs: number;\n\treadonly commandId?: string;\n}\n\n/** Minimal JSON Schema vocabulary for passive topic payload descriptions (D125/D132). */\nexport interface JsonSchema {\n\treadonly type?:\n\t\t| \"string\"\n\t\t| \"number\"\n\t\t| \"integer\"\n\t\t| \"boolean\"\n\t\t| \"object\"\n\t\t| \"array\"\n\t\t| \"null\"\n\t\t| readonly (\"string\" | \"number\" | \"integer\" | \"boolean\" | \"object\" | \"array\" | \"null\")[];\n\treadonly properties?: Readonly<Record<string, JsonSchema>>;\n\treadonly required?: readonly string[];\n\treadonly additionalProperties?: boolean | JsonSchema;\n\treadonly items?: JsonSchema | readonly JsonSchema[];\n\treadonly enum?: readonly unknown[];\n\treadonly const?: unknown;\n\treadonly $ref?: string;\n\treadonly definitions?: Readonly<Record<string, JsonSchema>>;\n\treadonly description?: string;\n\treadonly title?: string;\n}\n\n/** Passive envelope for payloads that cross topic, agent, or graph boundaries. */\nexport interface TopicMessage<T = unknown> {\n\treadonly id: string;\n\treadonly schema?: JsonSchema;\n\treadonly expiresAt?: string;\n\treadonly correlationId?: string;\n\treadonly payload: T;\n}\n\n/** Passive domain event vocabulary for messageBus/eventFlow composition (D329). */\nexport interface EventMessage<T = unknown> {\n\treadonly id: string;\n\treadonly type: string;\n\treadonly payload: T;\n\treadonly key?: string;\n\treadonly subjectId?: string;\n\treadonly correlationId?: string;\n\treadonly causationId?: string;\n\treadonly occurredAtMs?: number;\n\treadonly actor?: string;\n\treadonly evidenceRefs?: readonly string[];\n\treadonly schema?: JsonSchema;\n\treadonly metadata?: Readonly<Record<string, unknown>>;\n}\n\nexport interface EventMessageOptions {\n\treadonly id: string;\n\treadonly key?: string;\n\treadonly subjectId?: string;\n\treadonly correlationId?: string;\n\treadonly causationId?: string;\n\treadonly occurredAtMs?: number;\n\treadonly actor?: string;\n\treadonly evidenceRefs?: readonly string[];\n\treadonly schema?: JsonSchema;\n\treadonly metadata?: Readonly<Record<string, unknown>>;\n}\n\nexport function eventMessage<T>(\n\ttype: string,\n\tpayload: T,\n\topts: EventMessageOptions,\n): EventMessage<T> {\n\tassertNonEmpty(type, \"eventMessage.type\");\n\tassertNonEmpty(opts.id, \"eventMessage.id\");\n\treturn {\n\t\tid: opts.id,\n\t\ttype,\n\t\tpayload,\n\t\t...(opts.key === undefined ? {} : { key: opts.key }),\n\t\t...(opts.subjectId === undefined ? {} : { subjectId: opts.subjectId }),\n\t\t...(opts.correlationId === undefined ? {} : { correlationId: opts.correlationId }),\n\t\t...(opts.causationId === undefined ? {} : { causationId: opts.causationId }),\n\t\t...(opts.occurredAtMs === undefined ? {} : { occurredAtMs: opts.occurredAtMs }),\n\t\t...(opts.actor === undefined ? {} : { actor: opts.actor }),\n\t\t...(opts.evidenceRefs === undefined ? {} : { evidenceRefs: opts.evidenceRefs }),\n\t\t...(opts.schema === undefined ? {} : { schema: opts.schema }),\n\t\t...(opts.metadata === undefined ? {} : { metadata: opts.metadata }),\n\t};\n}\n\nexport function isEventMessage(value: unknown): value is EventMessage {\n\treturn eventMessageIssue(value) === undefined;\n}\n\nexport function eventMessageIssue(value: unknown): DataIssue | undefined {\n\tif (!isObjectRecord(value)) {\n\t\treturn eventIssue(\"event message must be an object\");\n\t}\n\tif (typeof value.id !== \"string\" || value.id.length === 0) {\n\t\treturn eventIssue(\"event message id must be a non-empty string\");\n\t}\n\tif (typeof value.type !== \"string\" || value.type.length === 0) {\n\t\treturn eventIssue(\"event message type must be a non-empty string\");\n\t}\n\tif (!(\"payload\" in value)) {\n\t\treturn eventIssue(\"event message payload field is required\");\n\t}\n\treturn undefined;\n}\n\nfunction eventIssue(message: string): DataIssue {\n\treturn {\n\t\tkind: \"issue\",\n\t\tcode: \"malformed-event-message\",\n\t\tmessage,\n\t\tseverity: \"error\",\n\t\tsource: \"messageBus.eventMessage\",\n\t};\n}\n\nexport const PROMPTS_TOPIC = \"prompts\";\nexport const RESPONSES_TOPIC = \"responses\";\nexport const INJECTIONS_TOPIC = \"injections\";\nexport const DEFERRED_TOPIC = \"deferred\";\nexport const SPAWNS_TOPIC = \"spawns\";\nexport const CONTEXT_TOPIC = \"context\";\nexport const TODOS_TOPIC = \"todos\";\n\nexport const STANDARD_TOPICS = Object.freeze([\n\tPROMPTS_TOPIC,\n\tRESPONSES_TOPIC,\n\tINJECTIONS_TOPIC,\n\tDEFERRED_TOPIC,\n\tSPAWNS_TOPIC,\n\tCONTEXT_TOPIC,\n\tTODOS_TOPIC,\n] as const);\n\nexport type StandardTopic = (typeof STANDARD_TOPICS)[number];\n\nexport type MessageBusTopicPolicy = \"strict\" | \"create-as-fact\";\n\nexport interface MessageBusRetentionPolicy {\n\t/** Count retention. Trimming advances headSeq and never rewrites seq (D284). */\n\treadonly maxMessages?: number;\n}\n\nexport interface MessageBusDedupePolicy {\n\t/** Duplicate commandId emits status and never publishes a second retained message (D284). */\n\treadonly commandId?: \"status\" | \"issue\";\n}\n\nexport interface MessageBusOptions<TTopic extends string = string> {\n\treadonly topics?: readonly TTopic[];\n\treadonly name?: string;\n\treadonly now?: () => number;\n\treadonly topicPolicy?: MessageBusTopicPolicy;\n\treadonly retention?: MessageBusRetentionPolicy;\n\treadonly dedupe?: MessageBusDedupePolicy;\n}\n\nexport type MessageBusCommand<T = unknown> =\n\t| {\n\t\t\treadonly kind: \"ensure-topic\";\n\t\t\treadonly topic: string;\n\t\t\treadonly commandId?: string;\n\t }\n\t| {\n\t\t\treadonly kind: \"close-topic\";\n\t\t\treadonly topic: string;\n\t\t\treadonly commandId?: string;\n\t }\n\t| {\n\t\t\treadonly kind: \"publish\";\n\t\t\treadonly topic: string;\n\t\t\treadonly payload: T;\n\t\t\treadonly key?: string;\n\t\t\treadonly commandId?: string;\n\t\t\treadonly idempotencyKey?: string;\n\t }\n\t| {\n\t\t\treadonly kind: \"topic-policy\";\n\t\t\treadonly topicPolicy: MessageBusTopicPolicy;\n\t\t\treadonly commandId?: string;\n\t }\n\t| {\n\t\t\treadonly kind: \"ack\";\n\t\t\treadonly topic: string;\n\t\t\treadonly subscriptionId: string;\n\t\t\treadonly seq: number;\n\t\t\treadonly commandId?: string;\n\t }\n\t| {\n\t\t\treadonly kind: \"seek\";\n\t\t\treadonly topic: string;\n\t\t\treadonly subscriptionId: string;\n\t\t\treadonly nextSeq: number;\n\t\t\treadonly commandId?: string;\n\t }\n\t| {\n\t\t\treadonly kind: \"close-subscription\";\n\t\t\treadonly topic: string;\n\t\t\treadonly subscriptionId: string;\n\t\t\treadonly commandId?: string;\n\t };\n\nexport type MessageBusMessage<T = unknown> = MessageEnvelope<T>;\n\nexport interface MessageBusStatus {\n\treadonly kind:\n\t\t| \"topic-created\"\n\t\t| \"topic-closed\"\n\t\t| \"message-published\"\n\t\t| \"retention-trimmed\"\n\t\t| \"duplicate-command\"\n\t\t| \"subscription-acked\"\n\t\t| \"subscription-sought\"\n\t\t| \"subscription-closed\"\n\t\t| \"command-rejected\"\n\t\t| \"projection-ready\"\n\t\t| \"projection-partial\";\n\treadonly topic?: string;\n\treadonly seq?: number;\n\treadonly headSeq?: number;\n\treadonly subscriptionId?: string;\n\treadonly nextSeq?: number;\n\treadonly commandId?: string;\n\treadonly issueCode?: string;\n\treadonly timestampMs: number;\n\treadonly details?: unknown;\n}\n\nexport interface MessageBusCatalogEntry {\n\treadonly topic: string;\n\treadonly closed: boolean;\n\treadonly headSeq: number;\n\treadonly nextSeq: number;\n\treadonly messageCount: number;\n}\n\nexport interface MessageBusCatalogPage {\n\treadonly topics: readonly MessageBusCatalogEntry[];\n\treadonly nextAfterTopic?: string;\n\treadonly hasMore: boolean;\n}\n\nexport interface MessageBusDeadLetterEntry<T = unknown> {\n\treadonly entrySeq: number;\n\treadonly topic?: string;\n\treadonly command?: MessageBusCommand<T>;\n\treadonly message?: MessageBusMessage<T>;\n\treadonly issue: DataIssue;\n\treadonly timestampMs: number;\n}\n\nexport interface MessageBusDeadLetterPage<T = unknown> {\n\treadonly entries: readonly MessageBusDeadLetterEntry<T>[];\n\treadonly nextAfterEntrySeq?: number;\n\treadonly hasMore: boolean;\n}\n\nexport interface MessageBusTopicPage<T = unknown> {\n\treadonly topic: string;\n\treadonly messages: readonly MessageBusMessage<T>[];\n\treadonly fromSeq: number;\n\treadonly throughSeq?: number;\n\treadonly nextAfterSeq?: number;\n\treadonly hasMore: boolean;\n}\n\nexport interface MessageBusCursor {\n\treadonly topic: string;\n\treadonly subscriptionId: string;\n\treadonly nextSeq: number;\n\treadonly closed: boolean;\n\treadonly retentionGap: boolean;\n\treadonly headSeq: number;\n}\n\nexport interface MessageBusAvailablePage<T = unknown> {\n\treadonly topic: string;\n\treadonly subscriptionId: string;\n\treadonly cursor: MessageBusCursor;\n\treadonly messages: readonly MessageBusMessage<T>[];\n\treadonly fromSeq: number;\n\treadonly throughSeq?: number;\n\treadonly nextAfterSeq?: number;\n\treadonly hasMore: boolean;\n}\n\nexport interface MessageBusPageParams {\n\treadonly limit?: number;\n}\n\nexport interface MessageBusCatalogParams extends MessageBusPageParams {\n\treadonly afterTopic?: string;\n\treadonly includeClosed?: boolean;\n}\n\nexport interface MessageBusDeadLetterParams extends MessageBusPageParams {\n\treadonly afterEntrySeq?: number;\n\treadonly topic?: string;\n\treadonly code?: string;\n}\n\nexport interface MessageBusTopicParams extends MessageBusPageParams {\n\treadonly afterSeq?: number;\n}\n\nexport interface MessageBusAvailableParams extends MessageBusPageParams {\n\treadonly afterSeq?: number;\n}\n\nexport interface MessageBusPullProjection<TPage> {\n\treadonly snapshot: Node<TPage>;\n\treadonly snapshotPullId: LockId;\n\treadonly status: Node<MessageBusStatus>;\n\treadonly issues: Node<DataIssue>;\n}\n\nexport interface MessageBusTopicProjection<T = unknown>\n\textends MessageBusPullProjection<MessageBusTopicPage<T>> {}\n\nexport interface MessageBusSubscription<T = unknown> {\n\treadonly available: Node<MessageBusAvailablePage<T>>;\n\treadonly availablePullId: LockId;\n\treadonly cursor: Node<MessageBusCursor>;\n\treadonly status: Node<MessageBusStatus>;\n\treadonly issues: Node<DataIssue>;\n\tack(seq: number, opts?: { commandId?: string }): MessageBusCommand;\n\tseek(nextSeq: number, opts?: { commandId?: string }): MessageBusCommand;\n\tclose(opts?: { commandId?: string }): MessageBusCommand;\n}\n\nexport interface MessageBus<TTopic extends string = string> {\n\treadonly commands: Node<MessageBusCommand>;\n\treadonly messages: Node<MessageBusMessage>;\n\treadonly status: Node<MessageBusStatus>;\n\treadonly issues: Node<DataIssue>;\n\tensureTopic(topic: TTopic | string, opts?: { commandId?: string }): MessageBusCommand;\n\tcloseTopic(topic: TTopic | string, opts?: { commandId?: string }): MessageBusCommand;\n\tpublish<T = unknown>(\n\t\ttopic: TTopic | string,\n\t\tpayload: T,\n\t\topts?: { key?: string; commandId?: string; idempotencyKey?: string },\n\t): MessageBusCommand<T>;\n\ttopic<T = unknown>(\n\t\ttopic: TTopic | string,\n\t\topts?: { name?: string },\n\t): MessageBusTopicProjection<T>;\n\tcatalog(opts?: { name?: string }): MessageBusPullProjection<MessageBusCatalogPage>;\n\tdeadLetter<T = unknown>(opts?: {\n\t\tname?: string;\n\t}): MessageBusPullProjection<MessageBusDeadLetterPage<T>>;\n\tsubscription<T = unknown>(opts: {\n\t\ttopic: TTopic | string;\n\t\tsubscriptionId: string;\n\t\tfrom?: \"earliest\" | \"latest\" | number;\n\t\tname?: string;\n\t}): MessageBusSubscription<T>;\n}\n\nexport interface ToTopicOptions {\n\treadonly name?: string;\n\treadonly keyOf?: (value: unknown) => string | undefined;\n\treadonly commandIdOf?: (value: unknown) => string | undefined;\n}\n\nexport interface ToTopicBundle<T> {\n\treadonly commands: Node<MessageBusCommand<T>>;\n\trelease(): void;\n}\n\ninterface TopicState {\n\tclosed: boolean;\n\theadSeq: number;\n\tnextSeq: number;\n\tmessages: MessageBusMessage[];\n}\n\ninterface SubscriptionState {\n\ttopic: string;\n\tsubscriptionId: string;\n\tnextSeq: number;\n\tclosed: boolean;\n\tretentionGap: boolean;\n}\n\ntype RuntimeEvent<T = unknown> =\n\t| { readonly kind: \"message\"; readonly message: MessageBusMessage<T> }\n\t| { readonly kind: \"status\"; readonly status: MessageBusStatus }\n\t| { readonly kind: \"issue\"; readonly issue: DataIssue }\n\t| { readonly kind: \"dead-letter\"; readonly entry: MessageBusDeadLetterEntry<T> };\n\ninterface MessageBusState {\n\treadonly graph: Graph;\n\treadonly name: string;\n\treadonly now: () => number;\n\ttopicPolicy: MessageBusTopicPolicy;\n\treadonly retention: MessageBusRetentionPolicy;\n\treadonly dedupe: MessageBusDedupePolicy;\n\treadonly topics: Map<string, TopicState>;\n\treadonly subscriptions: Map<string, SubscriptionState>;\n\treadonly seenCommandIds: Set<string>;\n\treadonly seenIdempotencyKeys: Set<string>;\n\treadonly deadLetters: MessageBusDeadLetterEntry[];\n\tdeadLetterSeq: number;\n\treadonly commandSources: Node<MessageBusCommand>[];\n\treadonly commandBody: NodeFn;\n}\n\nexport function messageBus<TTopic extends string>(\n\tgraph: Graph,\n\topts: MessageBusOptions<TTopic> = {},\n): MessageBus<TTopic> {\n\tconst name = opts.name ?? \"messageBus\";\n\tconst initialTopics = uniqueTopics(opts.topics ?? []);\n\tconst commandSources: Node<MessageBusCommand>[] = [];\n\tconst commandBody: NodeFn = (ctx) => {\n\t\tfor (let i = 0; i < commandSources.length; i++) {\n\t\t\tfor (const command of depBatch(ctx, i) ?? []) ctx.down([[\"DATA\", command]]);\n\t\t}\n\t};\n\tconst commands = graph.node<MessageBusCommand>([], commandBody, {\n\t\tname: `${name}/commands`,\n\t\tfactory: \"messageBusCommands\",\n\t\tcompleteWhenDepsComplete: false,\n\t\terrorWhenDepsError: false,\n\t});\n\tconst state: MessageBusState = {\n\t\tgraph,\n\t\tname,\n\t\tnow: opts.now ?? Date.now,\n\t\ttopicPolicy: opts.topicPolicy ?? \"strict\",\n\t\tretention: opts.retention ?? {},\n\t\tdedupe: opts.dedupe ?? { commandId: \"status\" },\n\t\ttopics: new Map(initialTopics.map((topic) => [topic, makeTopicState()])),\n\t\tsubscriptions: new Map(),\n\t\tseenCommandIds: new Set(),\n\t\tseenIdempotencyKeys: new Set(),\n\t\tdeadLetters: [],\n\t\tdeadLetterSeq: 0,\n\t\tcommandSources,\n\t\tcommandBody,\n\t};\n\tconst runtime = graph.node<RuntimeEvent>(\n\t\t[commands],\n\t\t(ctx) => {\n\t\t\tfor (const command of depBatch(ctx, 0) ?? []) {\n\t\t\t\tfor (const event of reduceMessageBusCommand(state, command as MessageBusCommand)) {\n\t\t\t\t\tctx.down([[\"DATA\", event]]);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tname: `${name}/runtime`,\n\t\t\tfactory: \"messageBusRuntime\",\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n\tgraph.retain(runtime, { reason: `${name}.messageBus.runtime` });\n\tconst messages = graph.node<MessageBusMessage>(\n\t\t[runtime],\n\t\t(ctx) => {\n\t\t\tfor (const event of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst typed = event as RuntimeEvent;\n\t\t\t\tif (typed.kind === \"message\") ctx.down([[\"DATA\", typed.message]]);\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tname: `${name}/messages`,\n\t\t\tfactory: \"messageBusMessages\",\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n\tconst status = graph.node<MessageBusStatus>(\n\t\t[runtime],\n\t\t(ctx) => {\n\t\t\tfor (const event of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst typed = event as RuntimeEvent;\n\t\t\t\tif (typed.kind === \"status\") ctx.down([[\"DATA\", typed.status]]);\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tname: `${name}/status`,\n\t\t\tfactory: \"messageBusStatus\",\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n\tconst issues = graph.node<DataIssue>(\n\t\t[runtime],\n\t\t(ctx) => {\n\t\t\tfor (const event of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst typed = event as RuntimeEvent;\n\t\t\t\tif (typed.kind === \"issue\") ctx.down([[\"DATA\", typed.issue]]);\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tname: `${name}/issues`,\n\t\t\tfactory: \"messageBusIssues\",\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n\n\tconst bus: MessageBus<TTopic> = {\n\t\tcommands,\n\t\tmessages,\n\t\tstatus,\n\t\tissues,\n\t\tensureTopic(topic, commandOpts = {}) {\n\t\t\treturn publishCommand(commands, {\n\t\t\t\tkind: \"ensure-topic\",\n\t\t\t\ttopic,\n\t\t\t\t...(commandOpts.commandId === undefined ? {} : { commandId: commandOpts.commandId }),\n\t\t\t});\n\t\t},\n\t\tcloseTopic(topic, commandOpts = {}) {\n\t\t\treturn publishCommand(commands, {\n\t\t\t\tkind: \"close-topic\",\n\t\t\t\ttopic,\n\t\t\t\t...(commandOpts.commandId === undefined ? {} : { commandId: commandOpts.commandId }),\n\t\t\t});\n\t\t},\n\t\tpublish<T = unknown>(\n\t\t\ttopic: TTopic | string,\n\t\t\tpayload: T,\n\t\t\tpublishOpts: { key?: string; commandId?: string; idempotencyKey?: string } = {},\n\t\t) {\n\t\t\treturn publishCommand(commands, {\n\t\t\t\tkind: \"publish\",\n\t\t\t\ttopic,\n\t\t\t\tpayload,\n\t\t\t\t...(publishOpts.key === undefined ? {} : { key: publishOpts.key }),\n\t\t\t\t...(publishOpts.commandId === undefined ? {} : { commandId: publishOpts.commandId }),\n\t\t\t\t...(publishOpts.idempotencyKey === undefined\n\t\t\t\t\t? {}\n\t\t\t\t\t: { idempotencyKey: publishOpts.idempotencyKey }),\n\t\t\t});\n\t\t},\n\t\ttopic<T = unknown>(topic: TTopic | string, projectionOpts: { name?: string } = {}) {\n\t\t\tassertTopicKey(topic, \"messageBus.topic\");\n\t\t\tconst snapshotPullId = Symbol(`${name}/${topic}/topicSnapshot`);\n\t\t\tconst snapshot = graph.node<MessageBusTopicPage<T>>(\n\t\t\t\t[messages],\n\t\t\t\t(ctx) => {\n\t\t\t\t\tconst params = pullParams<MessageBusTopicParams>(ctx.pull);\n\t\t\t\t\tctx.down([[\"DATA\", topicPage<T>(state, topic, params)]]);\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tname: projectionOpts.name ?? `${name}/${topic}/topic`,\n\t\t\t\t\tfactory: \"messageBusTopicProjection\",\n\t\t\t\t\tmeta: { topic },\n\t\t\t\t\tpullId: snapshotPullId,\n\t\t\t\t\tpartial: true,\n\t\t\t\t\tcompleteWhenDepsComplete: false,\n\t\t\t\t\terrorWhenDepsError: false,\n\t\t\t\t},\n\t\t\t);\n\t\t\treturn { snapshot, snapshotPullId, status, issues };\n\t\t},\n\t\tcatalog(projectionOpts: { name?: string } = {}) {\n\t\t\tconst snapshotPullId = Symbol(`${name}/catalogSnapshot`);\n\t\t\tconst snapshot = graph.node<MessageBusCatalogPage>(\n\t\t\t\t[runtime],\n\t\t\t\t(ctx) => {\n\t\t\t\t\tconst params = pullParams<MessageBusCatalogParams>(ctx.pull);\n\t\t\t\t\tctx.down([[\"DATA\", catalogPage(state, params)]]);\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tname: projectionOpts.name ?? `${name}/catalog`,\n\t\t\t\t\tfactory: \"messageBusCatalog\",\n\t\t\t\t\tpullId: snapshotPullId,\n\t\t\t\t\tpartial: true,\n\t\t\t\t\tcompleteWhenDepsComplete: false,\n\t\t\t\t\terrorWhenDepsError: false,\n\t\t\t\t},\n\t\t\t);\n\t\t\treturn { snapshot, snapshotPullId, status, issues };\n\t\t},\n\t\tdeadLetter<T = unknown>(projectionOpts: { name?: string } = {}) {\n\t\t\tconst snapshotPullId = Symbol(`${name}/deadLetterSnapshot`);\n\t\t\tconst snapshot = graph.node<MessageBusDeadLetterPage<T>>(\n\t\t\t\t[runtime],\n\t\t\t\t(ctx) => {\n\t\t\t\t\tconst params = pullParams<MessageBusDeadLetterParams>(ctx.pull);\n\t\t\t\t\tctx.down([[\"DATA\", deadLetterPage<T>(state, params)]]);\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tname: projectionOpts.name ?? `${name}/deadLetter`,\n\t\t\t\t\tfactory: \"messageBusDeadLetter\",\n\t\t\t\t\tpullId: snapshotPullId,\n\t\t\t\t\tpartial: true,\n\t\t\t\t\tcompleteWhenDepsComplete: false,\n\t\t\t\t\terrorWhenDepsError: false,\n\t\t\t\t},\n\t\t\t);\n\t\t\treturn { snapshot, snapshotPullId, status, issues };\n\t\t},\n\t\tsubscription<T = unknown>(subscriptionOpts: {\n\t\t\ttopic: TTopic | string;\n\t\t\tsubscriptionId: string;\n\t\t\tfrom?: \"earliest\" | \"latest\" | number;\n\t\t\tname?: string;\n\t\t}) {\n\t\t\tassertTopicKey(subscriptionOpts.topic, \"messageBus.subscription\");\n\t\t\tassertNonEmpty(subscriptionOpts.subscriptionId, \"messageBus.subscriptionId\");\n\t\t\tconst sub = ensureSubscription(state, {\n\t\t\t\ttopic: subscriptionOpts.topic,\n\t\t\t\tsubscriptionId: subscriptionOpts.subscriptionId,\n\t\t\t\tfrom: subscriptionOpts.from ?? \"earliest\",\n\t\t\t});\n\t\t\tconst availablePullId = Symbol(\n\t\t\t\t`${name}/${subscriptionOpts.topic}/${subscriptionOpts.subscriptionId}/available`,\n\t\t\t);\n\t\t\tconst projectionName =\n\t\t\t\tsubscriptionOpts.name ??\n\t\t\t\t`${name}/${subscriptionOpts.topic}/${subscriptionOpts.subscriptionId}`;\n\t\t\tconst available = graph.node<MessageBusAvailablePage<T>>(\n\t\t\t\t[messages, status],\n\t\t\t\t(ctx) => {\n\t\t\t\t\tconst params = pullParams<MessageBusAvailableParams>(ctx.pull);\n\t\t\t\t\tctx.down([[\"DATA\", availablePage<T>(state, sub, params)]]);\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tname: `${projectionName}/available`,\n\t\t\t\t\tfactory: \"messageBusSubscriptionAvailable\",\n\t\t\t\t\tmeta: { topic: subscriptionOpts.topic, subscriptionId: subscriptionOpts.subscriptionId },\n\t\t\t\t\tpullId: availablePullId,\n\t\t\t\t\tpartial: true,\n\t\t\t\t\tcompleteWhenDepsComplete: false,\n\t\t\t\t\terrorWhenDepsError: false,\n\t\t\t\t},\n\t\t\t);\n\t\t\tconst cursor = graph.node<MessageBusCursor>(\n\t\t\t\t[status],\n\t\t\t\t(ctx) => {\n\t\t\t\t\tfor (const fact of depBatch(ctx, 0) ?? []) {\n\t\t\t\t\t\tconst typed = fact as MessageBusStatus;\n\t\t\t\t\t\tconst subscriptionMoved =\n\t\t\t\t\t\t\ttyped.topic === sub.topic &&\n\t\t\t\t\t\t\ttyped.subscriptionId === sub.subscriptionId &&\n\t\t\t\t\t\t\t(typed.kind === \"subscription-acked\" ||\n\t\t\t\t\t\t\t\ttyped.kind === \"subscription-sought\" ||\n\t\t\t\t\t\t\t\ttyped.kind === \"subscription-closed\");\n\t\t\t\t\t\tconst retentionMoved = typed.topic === sub.topic && typed.kind === \"retention-trimmed\";\n\t\t\t\t\t\tif (subscriptionMoved || retentionMoved) {\n\t\t\t\t\t\t\tctx.down([[\"DATA\", cursorSnapshot(state, sub)]]);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tname: `${projectionName}/cursor`,\n\t\t\t\t\tfactory: \"messageBusSubscriptionCursor\",\n\t\t\t\t\tcompleteWhenDepsComplete: false,\n\t\t\t\t\terrorWhenDepsError: false,\n\t\t\t\t},\n\t\t\t);\n\t\t\treturn {\n\t\t\t\tavailable,\n\t\t\t\tavailablePullId,\n\t\t\t\tcursor,\n\t\t\t\tstatus,\n\t\t\t\tissues,\n\t\t\t\tack(seq, commandOpts = {}) {\n\t\t\t\t\treturn publishCommand(commands, {\n\t\t\t\t\t\tkind: \"ack\",\n\t\t\t\t\t\ttopic: sub.topic,\n\t\t\t\t\t\tsubscriptionId: sub.subscriptionId,\n\t\t\t\t\t\tseq,\n\t\t\t\t\t\t...(commandOpts.commandId === undefined ? {} : { commandId: commandOpts.commandId }),\n\t\t\t\t\t});\n\t\t\t\t},\n\t\t\t\tseek(nextSeq, commandOpts = {}) {\n\t\t\t\t\treturn publishCommand(commands, {\n\t\t\t\t\t\tkind: \"seek\",\n\t\t\t\t\t\ttopic: sub.topic,\n\t\t\t\t\t\tsubscriptionId: sub.subscriptionId,\n\t\t\t\t\t\tnextSeq,\n\t\t\t\t\t\t...(commandOpts.commandId === undefined ? {} : { commandId: commandOpts.commandId }),\n\t\t\t\t\t});\n\t\t\t\t},\n\t\t\t\tclose(commandOpts = {}) {\n\t\t\t\t\treturn publishCommand(commands, {\n\t\t\t\t\t\tkind: \"close-subscription\",\n\t\t\t\t\t\ttopic: sub.topic,\n\t\t\t\t\t\tsubscriptionId: sub.subscriptionId,\n\t\t\t\t\t\t...(commandOpts.commandId === undefined ? {} : { commandId: commandOpts.commandId }),\n\t\t\t\t\t});\n\t\t\t\t},\n\t\t\t};\n\t\t},\n\t};\n\tregisterMessageBusState(bus, state);\n\treturn bus;\n}\n\nexport function fromTopic<T = unknown, TTopic extends string = string>(\n\tbus: MessageBus<TTopic>,\n\ttopic: TTopic | string,\n): Node<MessageBusTopicPage<T>> {\n\treturn bus.topic<T>(topic).snapshot;\n}\n\nexport function toTopic<T, TTopic extends string>(\n\tgraph: Graph,\n\tsource: Node<T>,\n\tbus: MessageBus<TTopic>,\n\ttopic: TTopic | string,\n\topts: ToTopicOptions = {},\n): ToTopicBundle<T> {\n\tconst state = getMessageBusState(bus);\n\tif (state === undefined) throw new Error(\"toTopic: unknown message bus implementation\");\n\tif (state.graph !== graph) throw new Error(\"toTopic: bus and source graph must match\");\n\tassertTopicKey(topic, \"toTopic\");\n\tconst commands = graph.node<MessageBusCommand<T>>(\n\t\t[source],\n\t\t(ctx) => {\n\t\t\tfor (const value of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst key = opts.keyOf?.(value);\n\t\t\t\tconst commandId = opts.commandIdOf?.(value);\n\t\t\t\tctx.down([\n\t\t\t\t\t[\n\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tkind: \"publish\",\n\t\t\t\t\t\t\ttopic,\n\t\t\t\t\t\t\tpayload: value as T,\n\t\t\t\t\t\t\t...(key === undefined ? {} : { key }),\n\t\t\t\t\t\t\t...(commandId === undefined ? {} : { commandId }),\n\t\t\t\t\t\t} satisfies MessageBusCommand<T>,\n\t\t\t\t\t],\n\t\t\t\t]);\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tname: opts.name ?? `${state.name}/${topic}/toTopic`,\n\t\t\tfactory: \"toTopic\",\n\t\t\tmeta: { topic },\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n\tconst releaseSource = attachMessageBusCommandSource(\n\t\tgraph,\n\t\tbus,\n\t\tcommands as Node<MessageBusCommand>,\n\t);\n\tlet released = false;\n\treturn {\n\t\tcommands,\n\t\trelease() {\n\t\t\tif (released) return;\n\t\t\treleased = true;\n\t\t\treleaseSource();\n\t\t},\n\t};\n}\n\nfunction reduceMessageBusCommand(\n\tstate: MessageBusState,\n\tcommand: MessageBusCommand,\n): RuntimeEvent[] {\n\tconst malformed = validateCommand(command);\n\tif (malformed !== undefined) return rejectCommand(state, command, malformed);\n\tif (command.commandId !== undefined) {\n\t\tif (state.seenCommandIds.has(command.commandId)) {\n\t\t\treturn duplicateCommandEvents(state, command, \"duplicate commandId\");\n\t\t}\n\t\tstate.seenCommandIds.add(command.commandId);\n\t}\n\tif (\n\t\tcommand.kind === \"publish\" &&\n\t\tcommand.idempotencyKey !== undefined &&\n\t\tstate.seenIdempotencyKeys.has(idempotencyKey(command.topic, command.idempotencyKey))\n\t) {\n\t\treturn duplicateCommandEvents(state, command, \"duplicate idempotencyKey\");\n\t}\n\tswitch (command.kind) {\n\t\tcase \"ensure-topic\":\n\t\t\treturn ensureTopic(state, command.topic, command.commandId);\n\t\tcase \"close-topic\": {\n\t\t\tconst topic = state.topics.get(command.topic);\n\t\t\tif (topic === undefined) {\n\t\t\t\treturn issueEvents(state, command, \"unknown-topic\", `unknown topic '${command.topic}'`);\n\t\t\t}\n\t\t\ttopic.closed = true;\n\t\t\treturn [\n\t\t\t\t{\n\t\t\t\t\tkind: \"status\",\n\t\t\t\t\tstatus: statusFact(state, \"topic-closed\", {\n\t\t\t\t\t\ttopic: command.topic,\n\t\t\t\t\t\tcommandId: command.commandId,\n\t\t\t\t\t}),\n\t\t\t\t},\n\t\t\t];\n\t\t}\n\t\tcase \"topic-policy\":\n\t\t\tstate.topicPolicy = command.topicPolicy;\n\t\t\treturn [\n\t\t\t\t{\n\t\t\t\t\tkind: \"status\",\n\t\t\t\t\tstatus: statusFact(state, \"projection-ready\", {\n\t\t\t\t\t\tcommandId: command.commandId,\n\t\t\t\t\t\tdetails: { topicPolicy: command.topicPolicy },\n\t\t\t\t\t}),\n\t\t\t\t},\n\t\t\t];\n\t\tcase \"publish\":\n\t\t\treturn publishMessage(state, command);\n\t\tcase \"ack\":\n\t\t\treturn ackSubscription(state, command);\n\t\tcase \"seek\":\n\t\t\treturn seekSubscription(state, command);\n\t\tcase \"close-subscription\":\n\t\t\treturn closeSubscription(state, command);\n\t}\n}\n\nfunction publishMessage(\n\tstate: MessageBusState,\n\tcommand: Extract<MessageBusCommand, { kind: \"publish\" }>,\n): RuntimeEvent[] {\n\tlet topic = state.topics.get(command.topic);\n\tconst events: RuntimeEvent[] = [];\n\tif (topic === undefined) {\n\t\tif (state.topicPolicy !== \"create-as-fact\") {\n\t\t\treturn issueEvents(state, command, \"unknown-topic\", `unknown topic '${command.topic}'`);\n\t\t}\n\t\tevents.push(...ensureTopic(state, command.topic, command.commandId));\n\t\ttopic = state.topics.get(command.topic);\n\t}\n\tif (topic === undefined)\n\t\treturn issueEvents(state, command, \"unknown-topic\", `unknown topic '${command.topic}'`);\n\tif (topic.closed)\n\t\treturn issueEvents(state, command, \"closed-topic\", `closed topic '${command.topic}'`);\n\tconst message: MessageBusMessage = {\n\t\ttopic: command.topic,\n\t\tseq: topic.nextSeq++,\n\t\tpayload: command.payload,\n\t\ttimestampMs: state.now(),\n\t\t...(command.key === undefined ? {} : { key: command.key }),\n\t\t...(command.idempotencyKey === undefined ? {} : { idempotencyKey: command.idempotencyKey }),\n\t\t...(command.commandId === undefined ? {} : { commandId: command.commandId }),\n\t};\n\tif (command.idempotencyKey !== undefined) {\n\t\tstate.seenIdempotencyKeys.add(idempotencyKey(command.topic, command.idempotencyKey));\n\t}\n\ttopic.messages.push(message);\n\tevents.push({ kind: \"message\", message });\n\tevents.push({\n\t\tkind: \"status\",\n\t\tstatus: statusFact(state, \"message-published\", {\n\t\t\ttopic: command.topic,\n\t\t\tseq: message.seq,\n\t\t\tcommandId: command.commandId,\n\t\t}),\n\t});\n\tevents.push(...trimRetention(state, command.topic, topic));\n\treturn events;\n}\n\nfunction ensureTopic(state: MessageBusState, topic: string, commandId?: string): RuntimeEvent[] {\n\tassertTopicKey(topic, \"messageBus\");\n\tif (!state.topics.has(topic)) state.topics.set(topic, makeTopicState());\n\treturn [\n\t\t{\n\t\t\tkind: \"status\",\n\t\t\tstatus: statusFact(state, \"topic-created\", { topic, commandId }),\n\t\t},\n\t];\n}\n\nfunction trimRetention(\n\tstate: MessageBusState,\n\ttopicName: string,\n\ttopic: TopicState,\n): RuntimeEvent[] {\n\tconst max = state.retention.maxMessages;\n\tif (max === undefined || topic.messages.length <= max) return [];\n\tif (!Number.isInteger(max) || max < 1) {\n\t\treturn issueEvents(\n\t\t\tstate,\n\t\t\t{ kind: \"publish\", topic: topicName, payload: undefined },\n\t\t\t\"policy-rejected\",\n\t\t\t\"retention.maxMessages must be a positive integer\",\n\t\t);\n\t}\n\tconst trimCount = topic.messages.length - max;\n\ttopic.messages.splice(0, trimCount);\n\ttopic.headSeq = topic.messages[0]?.seq ?? topic.nextSeq;\n\tconst events: RuntimeEvent[] = [\n\t\t{\n\t\t\tkind: \"status\",\n\t\t\tstatus: statusFact(state, \"retention-trimmed\", {\n\t\t\t\ttopic: topicName,\n\t\t\t\theadSeq: topic.headSeq,\n\t\t\t\tdetails: { trimCount },\n\t\t\t}),\n\t\t},\n\t];\n\tfor (const sub of state.subscriptions.values()) {\n\t\tif (sub.closed || sub.topic !== topicName || sub.nextSeq >= topic.headSeq) continue;\n\t\tsub.retentionGap = true;\n\t\tevents.push(\n\t\t\t...issueEvents(\n\t\t\t\tstate,\n\t\t\t\t{\n\t\t\t\t\tkind: \"seek\",\n\t\t\t\t\ttopic: topicName,\n\t\t\t\t\tsubscriptionId: sub.subscriptionId,\n\t\t\t\t\tnextSeq: sub.nextSeq,\n\t\t\t\t},\n\t\t\t\t\"retention-gap\",\n\t\t\t\t`subscription '${sub.subscriptionId}' is before retained headSeq`,\n\t\t\t),\n\t\t);\n\t}\n\treturn events;\n}\n\nfunction ackSubscription(\n\tstate: MessageBusState,\n\tcommand: Extract<MessageBusCommand, { kind: \"ack\" }>,\n): RuntimeEvent[] {\n\tconst topic = state.topics.get(command.topic);\n\tif (topic === undefined)\n\t\treturn issueEvents(state, command, \"unknown-topic\", `unknown topic '${command.topic}'`);\n\tconst sub = getSubscription(state, command.topic, command.subscriptionId);\n\tif (sub === undefined)\n\t\treturn issueEvents(\n\t\t\tstate,\n\t\t\tcommand,\n\t\t\t\"unknown-subscription\",\n\t\t\t`unknown subscription '${command.subscriptionId}'`,\n\t\t);\n\tif (sub.closed)\n\t\treturn issueEvents(state, command, \"subscription-closed\", \"subscription is closed\");\n\tif (sub.retentionGap)\n\t\treturn issueEvents(state, command, \"retention-gap\", \"subscription must seek before ack\");\n\tif (command.seq < sub.nextSeq)\n\t\treturn issueEvents(state, command, \"source-cursor-stale\", \"ack is behind subscription cursor\");\n\tif (command.seq >= topic.nextSeq)\n\t\treturn issueEvents(state, command, \"cursor-out-of-range\", \"ack is beyond topic tail\");\n\tsub.nextSeq = Math.max(sub.nextSeq, command.seq + 1);\n\treturn [\n\t\t{\n\t\t\tkind: \"status\",\n\t\t\tstatus: statusFact(state, \"subscription-acked\", {\n\t\t\t\ttopic: command.topic,\n\t\t\t\tsubscriptionId: command.subscriptionId,\n\t\t\t\tnextSeq: sub.nextSeq,\n\t\t\t\tcommandId: command.commandId,\n\t\t\t}),\n\t\t},\n\t];\n}\n\nfunction seekSubscription(\n\tstate: MessageBusState,\n\tcommand: Extract<MessageBusCommand, { kind: \"seek\" }>,\n): RuntimeEvent[] {\n\tconst topic = state.topics.get(command.topic);\n\tif (topic === undefined)\n\t\treturn issueEvents(state, command, \"unknown-topic\", `unknown topic '${command.topic}'`);\n\tconst sub = getSubscription(state, command.topic, command.subscriptionId);\n\tif (sub === undefined)\n\t\treturn issueEvents(\n\t\t\tstate,\n\t\t\tcommand,\n\t\t\t\"unknown-subscription\",\n\t\t\t`unknown subscription '${command.subscriptionId}'`,\n\t\t);\n\tif (sub.closed)\n\t\treturn issueEvents(state, command, \"subscription-closed\", \"subscription is closed\");\n\tif (command.nextSeq < topic.headSeq)\n\t\treturn issueEvents(state, command, \"retention-gap\", \"seek is before retained headSeq\");\n\tif (command.nextSeq > topic.nextSeq)\n\t\treturn issueEvents(state, command, \"cursor-out-of-range\", \"seek is beyond topic tail\");\n\tsub.nextSeq = command.nextSeq;\n\tsub.retentionGap = false;\n\treturn [\n\t\t{\n\t\t\tkind: \"status\",\n\t\t\tstatus: statusFact(state, \"subscription-sought\", {\n\t\t\t\ttopic: command.topic,\n\t\t\t\tsubscriptionId: command.subscriptionId,\n\t\t\t\tnextSeq: sub.nextSeq,\n\t\t\t\tcommandId: command.commandId,\n\t\t\t}),\n\t\t},\n\t];\n}\n\nfunction closeSubscription(\n\tstate: MessageBusState,\n\tcommand: Extract<MessageBusCommand, { kind: \"close-subscription\" }>,\n): RuntimeEvent[] {\n\tif (!state.topics.has(command.topic))\n\t\treturn issueEvents(state, command, \"unknown-topic\", `unknown topic '${command.topic}'`);\n\tconst sub = getSubscription(state, command.topic, command.subscriptionId);\n\tif (sub === undefined)\n\t\treturn issueEvents(\n\t\t\tstate,\n\t\t\tcommand,\n\t\t\t\"unknown-subscription\",\n\t\t\t`unknown subscription '${command.subscriptionId}'`,\n\t\t);\n\tsub.closed = true;\n\treturn [\n\t\t{\n\t\t\tkind: \"status\",\n\t\t\tstatus: statusFact(state, \"subscription-closed\", {\n\t\t\t\ttopic: command.topic,\n\t\t\t\tsubscriptionId: command.subscriptionId,\n\t\t\t\tnextSeq: sub.nextSeq,\n\t\t\t\tcommandId: command.commandId,\n\t\t\t}),\n\t\t},\n\t];\n}\n\nfunction issueEvents(\n\tstate: MessageBusState,\n\tcommand: unknown,\n\tcode: string,\n\tmessage: string,\n): RuntimeEvent[] {\n\tconst topic = commandTopic(command);\n\tconst commandId = commandIdOf(command);\n\tconst issue: DataIssue = {\n\t\tkind: \"issue\",\n\t\tcode,\n\t\tmessage,\n\t\tseverity: \"error\",\n\t\tsource: \"messageBus\",\n\t\tdetails: command,\n\t\tmetadata: topic === undefined ? undefined : { topic },\n\t};\n\tconst entry: MessageBusDeadLetterEntry = {\n\t\tentrySeq: ++state.deadLetterSeq,\n\t\t...(topic === undefined ? {} : { topic }),\n\t\t...(isObjectRecord(command) ? { command: command as MessageBusCommand } : {}),\n\t\tissue,\n\t\ttimestampMs: state.now(),\n\t};\n\tstate.deadLetters.push(entry);\n\treturn [\n\t\t{ kind: \"issue\", issue },\n\t\t{ kind: \"dead-letter\", entry },\n\t\t{\n\t\t\tkind: \"status\",\n\t\t\tstatus: statusFact(state, \"command-rejected\", {\n\t\t\t\ttopic,\n\t\t\t\tcommandId,\n\t\t\t\tissueCode: code,\n\t\t\t}),\n\t\t},\n\t];\n}\n\nfunction rejectCommand(state: MessageBusState, command: unknown, reason: string): RuntimeEvent[] {\n\treturn issueEvents(state, command, \"malformed-command\", reason);\n}\n\nfunction duplicateCommandEvents(\n\tstate: MessageBusState,\n\tcommand: MessageBusCommand,\n\tmessage: string,\n): RuntimeEvent[] {\n\tconst status = statusFact(state, \"duplicate-command\", {\n\t\ttopic: \"topic\" in command ? command.topic : undefined,\n\t\tcommandId: command.commandId,\n\t});\n\tif (state.dedupe.commandId === \"issue\") {\n\t\treturn [\n\t\t\t{ kind: \"status\", status },\n\t\t\t...issueEvents(state, command, \"duplicate-command\", message),\n\t\t];\n\t}\n\treturn [{ kind: \"status\", status }];\n}\n\nfunction statusFact(\n\tstate: MessageBusState,\n\tkind: MessageBusStatus[\"kind\"],\n\tfields: Partial<MessageBusStatus>,\n): MessageBusStatus {\n\treturn {\n\t\tkind,\n\t\ttimestampMs: state.now(),\n\t\t...(fields.topic === undefined ? {} : { topic: fields.topic }),\n\t\t...(fields.seq === undefined ? {} : { seq: fields.seq }),\n\t\t...(fields.headSeq === undefined ? {} : { headSeq: fields.headSeq }),\n\t\t...(fields.subscriptionId === undefined ? {} : { subscriptionId: fields.subscriptionId }),\n\t\t...(fields.nextSeq === undefined ? {} : { nextSeq: fields.nextSeq }),\n\t\t...(fields.commandId === undefined ? {} : { commandId: fields.commandId }),\n\t\t...(fields.issueCode === undefined ? {} : { issueCode: fields.issueCode }),\n\t\t...(fields.details === undefined ? {} : { details: fields.details }),\n\t};\n}\n\nfunction validateCommand(command: unknown): string | undefined {\n\tif (!isObjectRecord(command)) return \"command must be an object\";\n\tif (typeof command.kind !== \"string\") return \"command kind is required\";\n\tif (!isMessageBusCommandKind(command.kind)) return `unknown command kind '${command.kind}'`;\n\tif (\"topic\" in command) {\n\t\tif (typeof command.topic !== \"string\") return \"messageBus: topic must be a non-empty string\";\n\t\tconst topicError = validateTopicKey(command.topic, \"messageBus\");\n\t\tif (topicError !== undefined) return topicError;\n\t}\n\tif (\"subscriptionId\" in command && typeof command.subscriptionId !== \"string\") {\n\t\treturn \"subscriptionId must be a string\";\n\t}\n\tif (command.kind === \"publish\" && command.payload === undefined)\n\t\treturn \"publish payload is required\";\n\tif (command.kind === \"ack\" && !isPositiveSeq(command.seq))\n\t\treturn \"ack seq must be a positive integer\";\n\tif (command.kind === \"seek\" && !isPositiveSeq(command.nextSeq)) {\n\t\treturn \"seek nextSeq must be a positive integer\";\n\t}\n\tif (\n\t\tcommand.kind === \"topic-policy\" &&\n\t\tcommand.topicPolicy !== \"strict\" &&\n\t\tcommand.topicPolicy !== \"create-as-fact\"\n\t) {\n\t\treturn \"topicPolicy is not recognized\";\n\t}\n\treturn undefined;\n}\n\nfunction isMessageBusCommandKind(kind: string): kind is MessageBusCommand[\"kind\"] {\n\treturn (\n\t\tkind === \"ensure-topic\" ||\n\t\tkind === \"close-topic\" ||\n\t\tkind === \"publish\" ||\n\t\tkind === \"topic-policy\" ||\n\t\tkind === \"ack\" ||\n\t\tkind === \"seek\" ||\n\t\tkind === \"close-subscription\"\n\t);\n}\n\nfunction catalogPage(\n\tstate: MessageBusState,\n\tparams: MessageBusCatalogParams,\n): MessageBusCatalogPage {\n\tconst limit = positiveLimit(params.limit);\n\tconst topics = [...state.topics.entries()]\n\t\t.filter(\n\t\t\t([topic, value]) =>\n\t\t\t\t(params.includeClosed ? true : !value.closed) &&\n\t\t\t\t(params.afterTopic === undefined || topic > params.afterTopic),\n\t\t)\n\t\t.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));\n\tconst page = topics.slice(0, limit);\n\tconst hasMore = topics.length > limit;\n\treturn {\n\t\ttopics: page.map(([topic, value]) => ({\n\t\t\ttopic,\n\t\t\tclosed: value.closed,\n\t\t\theadSeq: value.headSeq,\n\t\t\tnextSeq: value.nextSeq,\n\t\t\tmessageCount: value.messages.length,\n\t\t})),\n\t\t...(hasMore && page.length > 0 ? { nextAfterTopic: page[page.length - 1]?.[0] } : {}),\n\t\thasMore,\n\t};\n}\n\nfunction topicPage<T>(\n\tstate: MessageBusState,\n\ttopicName: string,\n\tparams: MessageBusTopicParams,\n): MessageBusTopicPage<T> {\n\tconst topic = state.topics.get(topicName);\n\tconst start = params.afterSeq === undefined ? (topic?.headSeq ?? 1) : params.afterSeq + 1;\n\tconst all = (topic?.messages ?? []).filter((message) => message.seq >= start);\n\tconst limit = positiveLimit(params.limit);\n\tconst messages = all.slice(0, limit) as MessageBusMessage<T>[];\n\tconst hasMore = all.length > limit;\n\treturn {\n\t\ttopic: topicName,\n\t\tmessages,\n\t\tfromSeq: start,\n\t\t...(messages.length > 0 ? { throughSeq: messages[messages.length - 1]?.seq } : {}),\n\t\t...(hasMore && messages.length > 0 ? { nextAfterSeq: messages[messages.length - 1]?.seq } : {}),\n\t\thasMore,\n\t};\n}\n\nfunction availablePage<T>(\n\tstate: MessageBusState,\n\tsub: SubscriptionState,\n\tparams: MessageBusAvailableParams,\n): MessageBusAvailablePage<T> {\n\tconst cursor = cursorSnapshot(state, sub);\n\tconst start = params.afterSeq === undefined ? sub.nextSeq : params.afterSeq + 1;\n\tconst topic = state.topics.get(sub.topic);\n\tconst all = sub.retentionGap\n\t\t? []\n\t\t: (topic?.messages ?? []).filter((message) => message.seq >= start);\n\tconst limit = positiveLimit(params.limit);\n\tconst messages = all.slice(0, limit) as MessageBusMessage<T>[];\n\tconst hasMore = all.length > limit;\n\treturn {\n\t\ttopic: sub.topic,\n\t\tsubscriptionId: sub.subscriptionId,\n\t\tcursor,\n\t\tmessages,\n\t\tfromSeq: start,\n\t\t...(messages.length > 0 ? { throughSeq: messages[messages.length - 1]?.seq } : {}),\n\t\t...(hasMore && messages.length > 0 ? { nextAfterSeq: messages[messages.length - 1]?.seq } : {}),\n\t\thasMore,\n\t};\n}\n\nfunction deadLetterPage<T>(\n\tstate: MessageBusState,\n\tparams: MessageBusDeadLetterParams,\n): MessageBusDeadLetterPage<T> {\n\tconst limit = positiveLimit(params.limit);\n\tconst entries = state.deadLetters.filter((entry) => {\n\t\tif (params.afterEntrySeq !== undefined && entry.entrySeq <= params.afterEntrySeq) return false;\n\t\tif (params.topic !== undefined && entry.topic !== params.topic) return false;\n\t\tif (params.code !== undefined && entry.issue.code !== params.code) return false;\n\t\treturn true;\n\t});\n\tconst page = entries.slice(0, limit) as MessageBusDeadLetterEntry<T>[];\n\tconst hasMore = entries.length > limit;\n\treturn {\n\t\tentries: page,\n\t\t...(hasMore && page.length > 0 ? { nextAfterEntrySeq: page[page.length - 1]?.entrySeq } : {}),\n\t\thasMore,\n\t};\n}\n\nfunction cursorSnapshot(state: MessageBusState, sub: SubscriptionState): MessageBusCursor {\n\tconst topic = state.topics.get(sub.topic);\n\treturn {\n\t\ttopic: sub.topic,\n\t\tsubscriptionId: sub.subscriptionId,\n\t\tnextSeq: sub.nextSeq,\n\t\tclosed: sub.closed,\n\t\tretentionGap: sub.retentionGap,\n\t\theadSeq: topic?.headSeq ?? 1,\n\t};\n}\n\nfunction ensureSubscription(\n\tstate: MessageBusState,\n\topts: { topic: string; subscriptionId: string; from: \"earliest\" | \"latest\" | number },\n): SubscriptionState {\n\tconst key = `${opts.topic}\\u0000${opts.subscriptionId}`;\n\tconst existing = state.subscriptions.get(key);\n\tif (existing !== undefined) return existing;\n\tconst topic = state.topics.get(opts.topic);\n\tconst nextSeq =\n\t\topts.from === \"earliest\"\n\t\t\t? (topic?.headSeq ?? 1)\n\t\t\t: opts.from === \"latest\"\n\t\t\t\t? (topic?.nextSeq ?? 1)\n\t\t\t\t: opts.from;\n\tconst sub: SubscriptionState = {\n\t\ttopic: opts.topic,\n\t\tsubscriptionId: opts.subscriptionId,\n\t\tnextSeq,\n\t\tclosed: false,\n\t\tretentionGap: topic !== undefined && nextSeq < topic.headSeq,\n\t};\n\tstate.subscriptions.set(key, sub);\n\treturn sub;\n}\n\nfunction getSubscription(\n\tstate: MessageBusState,\n\ttopic: string,\n\tsubscriptionId: string,\n): SubscriptionState | undefined {\n\treturn state.subscriptions.get(`${topic}\\u0000${subscriptionId}`);\n}\n\nfunction pullParams<T>(pull: PullDemand | undefined): T {\n\treturn (isObjectRecord(pull?.params) ? pull.params : {}) as T;\n}\n\nfunction publishCommand<T extends MessageBusCommand>(\n\tcommandNode: Node<MessageBusCommand>,\n\tcommand: T,\n): T {\n\tcommandNode.down([[\"DATA\", command]]);\n\treturn command;\n}\n\nfunction makeTopicState(): TopicState {\n\treturn { closed: false, headSeq: 1, nextSeq: 1, messages: [] };\n}\n\nfunction uniqueTopics(topics: readonly string[]): readonly string[] {\n\tconst unique = [...new Set(topics)];\n\tif (unique.length !== topics.length) throw new Error(\"messageBus: duplicate topic\");\n\tfor (const topic of unique) assertTopicKey(topic, \"messageBus\");\n\treturn Object.freeze(unique.sort());\n}\n\nfunction assertTopicKey(topic: string, owner: string): void {\n\tconst error = validateTopicKey(topic, owner);\n\tif (error !== undefined) throw new Error(error);\n}\n\nfunction validateTopicKey(topic: string, owner: string): string | undefined {\n\tif (typeof topic !== \"string\" || topic.length === 0)\n\t\treturn `${owner}: topic must be a non-empty string`;\n\treturn undefined;\n}\n\nfunction assertNonEmpty(value: string, owner: string): void {\n\tif (typeof value !== \"string\" || value.length === 0)\n\t\tthrow new Error(`${owner}: must be a non-empty string`);\n}\n\nfunction positiveLimit(limit: number | undefined): number {\n\tif (limit === undefined) return 100;\n\tif (!Number.isInteger(limit) || limit < 1)\n\t\tthrow new Error(\"messageBus: limit must be a positive integer\");\n\treturn limit;\n}\n\nfunction isPositiveSeq(value: unknown): value is number {\n\treturn Number.isInteger(value) && (value as number) >= 1;\n}\n\nfunction isObjectRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction commandTopic(command: unknown): string | undefined {\n\treturn isObjectRecord(command) && typeof command.topic === \"string\" ? command.topic : undefined;\n}\n\nfunction commandIdOf(command: unknown): string | undefined {\n\treturn isObjectRecord(command) && typeof command.commandId === \"string\"\n\t\t? command.commandId\n\t\t: undefined;\n}\n\nfunction idempotencyKey(topic: string, key: string): string {\n\treturn `${topic}\\u0000${key}`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;AC2CO,IAAM,WAAW;;;ACoHjB,SAAS,SAAS,KAAU,UAAmD;AACrF,SAAO,IAAI,SAAS,QAAQ,KAAK,CAAC;AACnC;AAGO,SAAS,SAAS,KAAU,UAA6C;AAC/E,QAAM,QAAQ,SAAS,KAAK,QAAQ;AACpC,MAAI,MAAM,WAAW,EAAG,QAAO;AAC/B,QAAM,YAAY,MAAM,KAAK,EAAE,OAAO,CAAC,MAAM,MAAM,QAAQ;AAC3D,SA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