@graphrefly/graphrefly 0.44.0 → 0.46.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (720) hide show
  1. package/README.md +22 -19
  2. package/dist/_internal-B23BagFd.d.cts +33 -0
  3. package/dist/_internal-B23BagFd.d.ts +33 -0
  4. package/dist/adaptive-rate-limiter-Dch_xYIi.d.cts +111 -0
  5. package/dist/adaptive-rate-limiter-Dch_xYIi.d.ts +111 -0
  6. package/dist/agents-C0Ji9ldU.d.cts +629 -0
  7. package/dist/agents-C9zexT7I.d.ts +629 -0
  8. package/dist/audit-BAXb3VOg.d.ts +246 -0
  9. package/dist/audit-C_bPfkqS.d.cts +246 -0
  10. package/dist/backoff-7KIK3WQW.js +24 -0
  11. package/dist/backoff-7KIK3WQW.js.map +1 -0
  12. package/dist/backoff-Bnb9OoPh.d.cts +6 -0
  13. package/dist/backoff-Bnb9OoPh.d.ts +6 -0
  14. package/dist/base/composition/index.cjs +811 -0
  15. package/dist/base/composition/index.cjs.map +1 -0
  16. package/dist/base/composition/index.d.cts +469 -0
  17. package/dist/base/composition/index.d.ts +469 -0
  18. package/dist/base/composition/index.js +40 -0
  19. package/dist/base/composition/index.js.map +1 -0
  20. package/dist/base/index.cjs +6336 -0
  21. package/dist/base/index.cjs.map +1 -0
  22. package/dist/base/index.d.cts +22 -0
  23. package/dist/base/index.d.ts +22 -0
  24. package/dist/base/index.js +259 -0
  25. package/dist/base/index.js.map +1 -0
  26. package/dist/base/io/index.cjs +3270 -0
  27. package/dist/base/io/index.cjs.map +1 -0
  28. package/dist/base/io/index.d.cts +2245 -0
  29. package/dist/base/io/index.d.ts +2245 -0
  30. package/dist/base/io/index.js +117 -0
  31. package/dist/base/io/index.js.map +1 -0
  32. package/dist/base/meta/index.cjs +43 -0
  33. package/dist/base/meta/index.cjs.map +1 -0
  34. package/dist/base/meta/index.d.cts +45 -0
  35. package/dist/base/meta/index.d.ts +45 -0
  36. package/dist/base/meta/index.js +13 -0
  37. package/dist/base/meta/index.js.map +1 -0
  38. package/dist/base/mutation/index.cjs +200 -0
  39. package/dist/base/mutation/index.cjs.map +1 -0
  40. package/dist/base/mutation/index.d.cts +177 -0
  41. package/dist/base/mutation/index.d.ts +177 -0
  42. package/dist/base/mutation/index.js +22 -0
  43. package/dist/base/mutation/index.js.map +1 -0
  44. package/dist/base/render/index.cjs +1120 -0
  45. package/dist/base/render/index.cjs.map +1 -0
  46. package/dist/{extra/render/index.d.ts → base/render/index.d.cts} +75 -31
  47. package/dist/{extra/render/index.d.cts → base/render/index.d.ts} +75 -31
  48. package/dist/base/render/index.js +24 -0
  49. package/dist/base/render/index.js.map +1 -0
  50. package/dist/base/sources/browser/index.cjs +172 -0
  51. package/dist/base/sources/browser/index.cjs.map +1 -0
  52. package/dist/base/sources/browser/index.d.cts +84 -0
  53. package/dist/base/sources/browser/index.d.ts +84 -0
  54. package/dist/base/sources/browser/index.js +151 -0
  55. package/dist/base/sources/browser/index.js.map +1 -0
  56. package/dist/base/sources/event/index.cjs +98 -0
  57. package/dist/base/sources/event/index.cjs.map +1 -0
  58. package/dist/base/sources/event/index.d.cts +91 -0
  59. package/dist/base/sources/event/index.d.ts +91 -0
  60. package/dist/base/sources/event/index.js +13 -0
  61. package/dist/base/sources/event/index.js.map +1 -0
  62. package/dist/base/sources/index.cjs +755 -0
  63. package/dist/base/sources/index.cjs.map +1 -0
  64. package/dist/{extra/sources.d.ts → base/sources/index.d.cts} +74 -301
  65. package/dist/{extra/sources.d.cts → base/sources/index.d.ts} +74 -301
  66. package/dist/base/sources/index.js +42 -0
  67. package/dist/base/sources/index.js.map +1 -0
  68. package/dist/base/sources/node/index.cjs +320 -0
  69. package/dist/base/sources/node/index.cjs.map +1 -0
  70. package/dist/{extra/node.d.ts → base/sources/node/index.d.cts} +35 -37
  71. package/dist/{extra/node.d.cts → base/sources/node/index.d.ts} +35 -37
  72. package/dist/base/sources/node/index.js +306 -0
  73. package/dist/base/sources/node/index.js.map +1 -0
  74. package/dist/base/utils/index.cjs +37 -0
  75. package/dist/base/utils/index.cjs.map +1 -0
  76. package/dist/base/utils/index.d.cts +37 -0
  77. package/dist/base/utils/index.d.ts +37 -0
  78. package/dist/base/utils/index.js +11 -0
  79. package/dist/base/utils/index.js.map +1 -0
  80. package/dist/base/worker/index.cjs +548 -0
  81. package/dist/base/worker/index.cjs.map +1 -0
  82. package/dist/base/worker/index.d.cts +207 -0
  83. package/dist/base/worker/index.d.ts +207 -0
  84. package/dist/base/worker/index.js +20 -0
  85. package/dist/base/worker/index.js.map +1 -0
  86. package/dist/breaker-C9skL3d8.d.ts +175 -0
  87. package/dist/breaker-ugSdq54q.d.cts +175 -0
  88. package/dist/{cascading-BglDkMdX.d.cts → cascading-CSSbKGrJ.d.ts} +3 -3
  89. package/dist/{cascading-MFgxu7Yo.d.ts → cascading-baGkiihI.d.cts} +3 -3
  90. package/dist/chunk-255UCBG4.js +58 -0
  91. package/dist/chunk-255UCBG4.js.map +1 -0
  92. package/dist/chunk-2LO3EL4W.js +1 -0
  93. package/dist/chunk-2LO3EL4W.js.map +1 -0
  94. package/dist/chunk-2OB3CEJS.js +1065 -0
  95. package/dist/chunk-2OB3CEJS.js.map +1 -0
  96. package/dist/chunk-36NMM65U.js +144 -0
  97. package/dist/chunk-36NMM65U.js.map +1 -0
  98. package/dist/chunk-3CEXCBN6.js +1 -0
  99. package/dist/chunk-3CEXCBN6.js.map +1 -0
  100. package/dist/chunk-3MUSLI6E.js +105 -0
  101. package/dist/chunk-3MUSLI6E.js.map +1 -0
  102. package/dist/chunk-3PSLNJDU.js +884 -0
  103. package/dist/chunk-3PSLNJDU.js.map +1 -0
  104. package/dist/chunk-3QZY5BI7.js +92 -0
  105. package/dist/chunk-3QZY5BI7.js.map +1 -0
  106. package/dist/chunk-42FQ27MQ.js +594 -0
  107. package/dist/chunk-42FQ27MQ.js.map +1 -0
  108. package/dist/chunk-4GYMCUDZ.js +1085 -0
  109. package/dist/chunk-4GYMCUDZ.js.map +1 -0
  110. package/dist/chunk-4S53H2KR.js +382 -0
  111. package/dist/chunk-4S53H2KR.js.map +1 -0
  112. package/dist/chunk-4XCHZRUJ.js +128 -0
  113. package/dist/chunk-4XCHZRUJ.js.map +1 -0
  114. package/dist/chunk-5THCXDWY.js +725 -0
  115. package/dist/chunk-5THCXDWY.js.map +1 -0
  116. package/dist/chunk-6XZYT4SW.js +256 -0
  117. package/dist/chunk-6XZYT4SW.js.map +1 -0
  118. package/dist/chunk-7EGRP2VX.js +76 -0
  119. package/dist/chunk-7EGRP2VX.js.map +1 -0
  120. package/dist/chunk-A7KV5UK4.js +150 -0
  121. package/dist/chunk-A7KV5UK4.js.map +1 -0
  122. package/dist/chunk-APY2SS5X.js +156 -0
  123. package/dist/chunk-APY2SS5X.js.map +1 -0
  124. package/dist/chunk-AZDQPQ3V.js +66 -0
  125. package/dist/chunk-AZDQPQ3V.js.map +1 -0
  126. package/dist/chunk-BU3SEFA5.js +90 -0
  127. package/dist/chunk-BU3SEFA5.js.map +1 -0
  128. package/dist/chunk-BXGZFGZ4.js +189 -0
  129. package/dist/chunk-BXGZFGZ4.js.map +1 -0
  130. package/dist/chunk-CGHORL6G.js +579 -0
  131. package/dist/chunk-CGHORL6G.js.map +1 -0
  132. package/dist/chunk-CXANAIZU.js +530 -0
  133. package/dist/chunk-CXANAIZU.js.map +1 -0
  134. package/dist/chunk-CZQHCKKG.js +1 -0
  135. package/dist/chunk-CZQHCKKG.js.map +1 -0
  136. package/dist/chunk-DKNHAICT.js +133 -0
  137. package/dist/chunk-DKNHAICT.js.map +1 -0
  138. package/dist/chunk-DM4OMPWK.js +584 -0
  139. package/dist/chunk-DM4OMPWK.js.map +1 -0
  140. package/dist/chunk-DMSNO6ZB.js +452 -0
  141. package/dist/chunk-DMSNO6ZB.js.map +1 -0
  142. package/dist/chunk-E5OZPDIW.js +229 -0
  143. package/dist/chunk-E5OZPDIW.js.map +1 -0
  144. package/dist/chunk-EVYY4X5A.js +509 -0
  145. package/dist/chunk-EVYY4X5A.js.map +1 -0
  146. package/dist/chunk-FDFD67UO.js +1 -0
  147. package/dist/chunk-FDFD67UO.js.map +1 -0
  148. package/dist/chunk-FMPF42Q4.js +13 -0
  149. package/dist/chunk-FMPF42Q4.js.map +1 -0
  150. package/dist/chunk-FR6RGA3B.js +1277 -0
  151. package/dist/chunk-FR6RGA3B.js.map +1 -0
  152. package/dist/chunk-FW23JYNQ.js +454 -0
  153. package/dist/chunk-FW23JYNQ.js.map +1 -0
  154. package/dist/chunk-GBCENOLN.js +1575 -0
  155. package/dist/chunk-GBCENOLN.js.map +1 -0
  156. package/dist/chunk-HL7HUJIX.js +1 -0
  157. package/dist/chunk-HL7HUJIX.js.map +1 -0
  158. package/dist/chunk-HULCUY35.js +2508 -0
  159. package/dist/chunk-HULCUY35.js.map +1 -0
  160. package/dist/chunk-IHTWQEDR.js +169 -0
  161. package/dist/chunk-IHTWQEDR.js.map +1 -0
  162. package/dist/chunk-IJRR6YAI.js +128 -0
  163. package/dist/chunk-IJRR6YAI.js.map +1 -0
  164. package/dist/chunk-JGFRAFDL.js +221 -0
  165. package/dist/chunk-JGFRAFDL.js.map +1 -0
  166. package/dist/chunk-KIIXR252.js +211 -0
  167. package/dist/chunk-KIIXR252.js.map +1 -0
  168. package/dist/chunk-KN3H5CNT.js +11 -0
  169. package/dist/chunk-KN3H5CNT.js.map +1 -0
  170. package/dist/chunk-KPG3DGLA.js +1 -0
  171. package/dist/chunk-KPG3DGLA.js.map +1 -0
  172. package/dist/chunk-KRNQ6RGQ.js +1 -0
  173. package/dist/chunk-KRNQ6RGQ.js.map +1 -0
  174. package/dist/chunk-LBAJK24K.js +1071 -0
  175. package/dist/chunk-LBAJK24K.js.map +1 -0
  176. package/dist/chunk-MLTPJMH6.js +417 -0
  177. package/dist/chunk-MLTPJMH6.js.map +1 -0
  178. package/dist/chunk-N3SZ7BMH.js +95 -0
  179. package/dist/chunk-N3SZ7BMH.js.map +1 -0
  180. package/dist/chunk-NDUD3IMO.js +540 -0
  181. package/dist/chunk-NDUD3IMO.js.map +1 -0
  182. package/dist/chunk-NY2PYHNC.js +873 -0
  183. package/dist/chunk-NY2PYHNC.js.map +1 -0
  184. package/dist/chunk-O3MT7DYI.js +225 -0
  185. package/dist/chunk-O3MT7DYI.js.map +1 -0
  186. package/dist/chunk-OCUDSN63.js +2386 -0
  187. package/dist/chunk-OCUDSN63.js.map +1 -0
  188. package/dist/chunk-OIWU3NYV.js +199 -0
  189. package/dist/chunk-OIWU3NYV.js.map +1 -0
  190. package/dist/chunk-OO5BM6CJ.js +1153 -0
  191. package/dist/chunk-OO5BM6CJ.js.map +1 -0
  192. package/dist/chunk-OQUIJT7A.js +1 -0
  193. package/dist/chunk-OQUIJT7A.js.map +1 -0
  194. package/dist/chunk-P5LBT622.js +105 -0
  195. package/dist/chunk-P5LBT622.js.map +1 -0
  196. package/dist/chunk-PKGQG5QQ.js +519 -0
  197. package/dist/chunk-PKGQG5QQ.js.map +1 -0
  198. package/dist/chunk-PKPO3JTZ.js +561 -0
  199. package/dist/chunk-PKPO3JTZ.js.map +1 -0
  200. package/dist/chunk-PL5UDIQ5.js +118 -0
  201. package/dist/chunk-PL5UDIQ5.js.map +1 -0
  202. package/dist/chunk-PZWISPIQ.js +432 -0
  203. package/dist/chunk-PZWISPIQ.js.map +1 -0
  204. package/dist/chunk-Q3EYOCZB.js +510 -0
  205. package/dist/chunk-Q3EYOCZB.js.map +1 -0
  206. package/dist/chunk-QMBYUVRL.js +15 -0
  207. package/dist/chunk-QMBYUVRL.js.map +1 -0
  208. package/dist/chunk-RAGGHLCV.js +200 -0
  209. package/dist/chunk-RAGGHLCV.js.map +1 -0
  210. package/dist/chunk-RGL53X5G.js +574 -0
  211. package/dist/chunk-RGL53X5G.js.map +1 -0
  212. package/dist/chunk-RJOG4IJU.js +1039 -0
  213. package/dist/chunk-RJOG4IJU.js.map +1 -0
  214. package/dist/chunk-SOOKUYVM.js +403 -0
  215. package/dist/chunk-SOOKUYVM.js.map +1 -0
  216. package/dist/chunk-T5BN5KG7.js +1 -0
  217. package/dist/chunk-T5BN5KG7.js.map +1 -0
  218. package/dist/chunk-TP7244Y6.js +207 -0
  219. package/dist/chunk-TP7244Y6.js.map +1 -0
  220. package/dist/chunk-TSBFTJKM.js +57 -0
  221. package/dist/chunk-TSBFTJKM.js.map +1 -0
  222. package/dist/chunk-URQ2CBBF.js +143 -0
  223. package/dist/chunk-URQ2CBBF.js.map +1 -0
  224. package/dist/chunk-W2BOPXTI.js +1 -0
  225. package/dist/chunk-W2BOPXTI.js.map +1 -0
  226. package/dist/chunk-WKSWLSCX.js +207 -0
  227. package/dist/chunk-WKSWLSCX.js.map +1 -0
  228. package/dist/chunk-Y52CS6YA.js +88 -0
  229. package/dist/chunk-Y52CS6YA.js.map +1 -0
  230. package/dist/chunk-YCBUWK77.js +92 -0
  231. package/dist/chunk-YCBUWK77.js.map +1 -0
  232. package/dist/chunk-YJ4U2D2C.js +314 -0
  233. package/dist/chunk-YJ4U2D2C.js.map +1 -0
  234. package/dist/chunk-Z4YXAUDN.js +239 -0
  235. package/dist/chunk-Z4YXAUDN.js.map +1 -0
  236. package/dist/chunk-Z6EGP5D7.js +92 -0
  237. package/dist/chunk-Z6EGP5D7.js.map +1 -0
  238. package/dist/compat/index.cjs +3100 -9
  239. package/dist/compat/index.cjs.map +1 -0
  240. package/dist/compat/index.d.cts +112 -18
  241. package/dist/compat/index.d.ts +112 -18
  242. package/dist/compat/index.js +176 -1
  243. package/dist/compat/index.js.map +1 -0
  244. package/dist/compat/jotai/index.cjs +149 -1
  245. package/dist/compat/jotai/index.cjs.map +1 -0
  246. package/dist/compat/jotai/index.d.cts +2 -2
  247. package/dist/compat/jotai/index.d.ts +2 -2
  248. package/dist/compat/jotai/index.js +8 -1
  249. package/dist/compat/jotai/index.js.map +1 -0
  250. package/dist/compat/nanostores/index.cjs +205 -1
  251. package/dist/compat/nanostores/index.cjs.map +1 -0
  252. package/dist/compat/nanostores/index.d.cts +2 -2
  253. package/dist/compat/nanostores/index.d.ts +2 -2
  254. package/dist/compat/nanostores/index.js +22 -1
  255. package/dist/compat/nanostores/index.js.map +1 -0
  256. package/dist/compat/nestjs/index.cjs +2241 -9
  257. package/dist/compat/nestjs/index.cjs.map +1 -0
  258. package/dist/compat/nestjs/index.d.cts +7 -10
  259. package/dist/compat/nestjs/index.d.ts +7 -10
  260. package/dist/compat/nestjs/index.js +78 -1
  261. package/dist/compat/nestjs/index.js.map +1 -0
  262. package/dist/compat/react/index.cjs +114 -1
  263. package/dist/compat/react/index.cjs.map +1 -0
  264. package/dist/compat/react/index.d.cts +2 -2
  265. package/dist/compat/react/index.d.ts +2 -2
  266. package/dist/compat/react/index.js +12 -1
  267. package/dist/compat/react/index.js.map +1 -0
  268. package/dist/compat/solid/index.cjs +101 -1
  269. package/dist/compat/solid/index.cjs.map +1 -0
  270. package/dist/compat/solid/index.d.cts +2 -2
  271. package/dist/compat/solid/index.d.ts +2 -2
  272. package/dist/compat/solid/index.js +12 -1
  273. package/dist/compat/solid/index.js.map +1 -0
  274. package/dist/compat/svelte/index.cjs +104 -1
  275. package/dist/compat/svelte/index.cjs.map +1 -0
  276. package/dist/compat/svelte/index.d.cts +2 -2
  277. package/dist/compat/svelte/index.d.ts +2 -2
  278. package/dist/compat/svelte/index.js +12 -1
  279. package/dist/compat/svelte/index.js.map +1 -0
  280. package/dist/compat/vue/index.cjs +119 -1
  281. package/dist/compat/vue/index.cjs.map +1 -0
  282. package/dist/compat/vue/index.d.cts +2 -2
  283. package/dist/compat/vue/index.d.ts +2 -2
  284. package/dist/compat/vue/index.js +12 -1
  285. package/dist/compat/vue/index.js.map +1 -0
  286. package/dist/compat/zustand/index.cjs +69 -3
  287. package/dist/compat/zustand/index.cjs.map +1 -0
  288. package/dist/compat/zustand/index.d.cts +2 -6
  289. package/dist/compat/zustand/index.d.ts +2 -6
  290. package/dist/compat/zustand/index.js +8 -1
  291. package/dist/compat/zustand/index.js.map +1 -0
  292. package/dist/distill-De6Rnn15.d.cts +48 -0
  293. package/dist/distill-De6Rnn15.d.ts +48 -0
  294. package/dist/external-register-CWyroXb_.d.cts +138 -0
  295. package/dist/external-register-CWyroXb_.d.ts +138 -0
  296. package/dist/{fallback-74oxi34l.d.cts → fallback-Bx46zqky.d.cts} +3 -10
  297. package/dist/{fallback-DUyyBTBK.d.ts → fallback-pIWW8A2d.d.ts} +3 -10
  298. package/dist/guarded-execution-BcdtxeBk.d.ts +207 -0
  299. package/dist/guarded-execution-C-3hnP6A.d.cts +207 -0
  300. package/dist/{index-CBGUK09R.d.ts → index-5SU_O78r.d.cts} +5 -5
  301. package/dist/{index-BmZXHqkE.d.ts → index-B6pxYJzO.d.cts} +1 -1
  302. package/dist/{index-hcDJ8PSI.d.cts → index-B6pxYJzO.d.ts} +1 -1
  303. package/dist/{index-C5stwKcw.d.cts → index-BFsng6v1.d.cts} +1 -1
  304. package/dist/{index-CdAlHFEt.d.ts → index-BFsng6v1.d.ts} +1 -1
  305. package/dist/{index-_6ODbuOu.d.cts → index-Bg-LwEt-.d.cts} +1 -1
  306. package/dist/{index-CviRnE4K.d.ts → index-Bg-LwEt-.d.ts} +1 -1
  307. package/dist/{index-CBBLl_rc.d.ts → index-Brp888t0.d.cts} +1 -1
  308. package/dist/{index-BQSKmbuG.d.cts → index-Brp888t0.d.ts} +1 -1
  309. package/dist/{index-sqkqlb1p.d.ts → index-CDfk6jHN.d.cts} +1 -1
  310. package/dist/{index-ZVQhLa2i.d.cts → index-CDfk6jHN.d.ts} +1 -1
  311. package/dist/{index-Climxqsu.d.cts → index-CEXCtYYJ.d.ts} +5 -5
  312. package/dist/index-DLAxYaN5.d.cts +169 -0
  313. package/dist/index-DLAxYaN5.d.ts +169 -0
  314. package/dist/{index-CK29LV56.d.cts → index-DeWbQzMe.d.cts} +1 -1
  315. package/dist/{index-CPQlGA29.d.ts → index-DeWbQzMe.d.ts} +1 -1
  316. package/dist/{index-BrPrLl4e.d.cts → index-dX9IzPqj.d.cts} +1 -1
  317. package/dist/{index-Dgl1HpPn.d.ts → index-dX9IzPqj.d.ts} +1 -1
  318. package/dist/index.cjs +25934 -191
  319. package/dist/index.cjs.map +1 -0
  320. package/dist/index.d.cts +58 -94
  321. package/dist/index.d.ts +58 -94
  322. package/dist/index.js +852 -1
  323. package/dist/index.js.map +1 -0
  324. package/dist/layout-types-B5aiHYgk.d.cts +72 -0
  325. package/dist/layout-types-B5aiHYgk.d.ts +72 -0
  326. package/dist/memory-composers-BryDrRBX.d.cts +529 -0
  327. package/dist/memory-composers-CVQqPYEV.d.ts +529 -0
  328. package/dist/{observable-DWjNfLvC.d.ts → observable-BXQoW1P-.d.cts} +1 -1
  329. package/dist/{observable-e3eiPPFy.d.cts → observable-BXQoW1P-.d.ts} +1 -1
  330. package/dist/{pipeline-graph-Sgj0gCwn.d.ts → pipeline-graph-Ce47CB6Y.d.cts} +13 -10
  331. package/dist/{pipeline-graph-CIKhynsF.d.cts → pipeline-graph-DXCwY9vG.d.ts} +13 -10
  332. package/dist/presets/ai/index.cjs +4377 -0
  333. package/dist/presets/ai/index.cjs.map +1 -0
  334. package/dist/presets/ai/index.d.cts +98 -0
  335. package/dist/presets/ai/index.d.ts +98 -0
  336. package/dist/presets/ai/index.js +54 -0
  337. package/dist/presets/ai/index.js.map +1 -0
  338. package/dist/presets/harness/index.cjs +5929 -0
  339. package/dist/presets/harness/index.cjs.map +1 -0
  340. package/dist/presets/harness/index.d.cts +566 -0
  341. package/dist/presets/harness/index.d.ts +566 -0
  342. package/dist/presets/harness/index.js +71 -0
  343. package/dist/presets/harness/index.js.map +1 -0
  344. package/dist/presets/index.cjs +9782 -0
  345. package/dist/presets/index.cjs.map +1 -0
  346. package/dist/presets/index.d.cts +28 -0
  347. package/dist/presets/index.d.ts +28 -0
  348. package/dist/presets/index.js +129 -0
  349. package/dist/presets/index.js.map +1 -0
  350. package/dist/presets/inspect/index.cjs +1087 -0
  351. package/dist/presets/inspect/index.cjs.map +1 -0
  352. package/dist/presets/inspect/index.d.cts +172 -0
  353. package/dist/presets/inspect/index.d.ts +172 -0
  354. package/dist/presets/inspect/index.js +21 -0
  355. package/dist/presets/inspect/index.js.map +1 -0
  356. package/dist/presets/resilience/index.cjs +1593 -0
  357. package/dist/presets/resilience/index.cjs.map +1 -0
  358. package/dist/presets/resilience/index.d.cts +205 -0
  359. package/dist/presets/resilience/index.d.ts +205 -0
  360. package/dist/presets/resilience/index.js +18 -0
  361. package/dist/presets/resilience/index.js.map +1 -0
  362. package/dist/rate-limiter-CEALq4N1.d.ts +559 -0
  363. package/dist/rate-limiter-DpVbSYdH.d.cts +559 -0
  364. package/dist/{reactive-layout-DOTs9P3X.d.ts → reactive-layout-fswlBUvX.d.cts} +19 -7
  365. package/dist/{reactive-layout-DgctbqZo.d.cts → reactive-layout-fswlBUvX.d.ts} +19 -7
  366. package/dist/retry-BDbRZ_gx.d.ts +125 -0
  367. package/dist/retry-DWuhjvsA.d.cts +125 -0
  368. package/dist/solutions/index.cjs +8200 -0
  369. package/dist/solutions/index.cjs.map +1 -0
  370. package/dist/solutions/index.d.cts +23 -0
  371. package/dist/solutions/index.d.ts +23 -0
  372. package/dist/solutions/index.js +55 -0
  373. package/dist/solutions/index.js.map +1 -0
  374. package/dist/spawnable-5mDY501F.d.cts +746 -0
  375. package/dist/spawnable-D3lR0oQu.d.ts +746 -0
  376. package/dist/status-U-rUI79b.d.cts +84 -0
  377. package/dist/status-U-rUI79b.d.ts +84 -0
  378. package/dist/timeout-U5O4ESK3.js +12 -0
  379. package/dist/timeout-U5O4ESK3.js.map +1 -0
  380. package/dist/{types-CWFysE9E.d.ts → types-BB5Lw-pB.d.cts} +3 -3
  381. package/dist/{types-C0_yquda.d.cts → types-BB5Lw-pB.d.ts} +3 -3
  382. package/dist/types-CJWIMJiZ.d.ts +548 -0
  383. package/dist/types-vCq7ShIm.d.cts +548 -0
  384. package/dist/utils/ai/browser.cjs +2169 -0
  385. package/dist/utils/ai/browser.cjs.map +1 -0
  386. package/dist/{patterns → utils}/ai/browser.d.cts +7 -5
  387. package/dist/{patterns → utils}/ai/browser.d.ts +7 -5
  388. package/dist/utils/ai/browser.js +255 -0
  389. package/dist/utils/ai/browser.js.map +1 -0
  390. package/dist/utils/ai/index.cjs +8468 -0
  391. package/dist/utils/ai/index.cjs.map +1 -0
  392. package/dist/{index-CR8QpwX8.d.ts → utils/ai/index.d.cts} +73 -976
  393. package/dist/{index-UPSiS-X7.d.cts → utils/ai/index.d.ts} +73 -976
  394. package/dist/utils/ai/index.js +173 -0
  395. package/dist/utils/ai/index.js.map +1 -0
  396. package/dist/utils/ai/node.cjs +648 -0
  397. package/dist/utils/ai/node.cjs.map +1 -0
  398. package/dist/{patterns → utils}/ai/node.d.cts +5 -7
  399. package/dist/{patterns → utils}/ai/node.d.ts +5 -7
  400. package/dist/utils/ai/node.js +84 -0
  401. package/dist/utils/ai/node.js.map +1 -0
  402. package/dist/utils/cqrs/index.cjs +1036 -0
  403. package/dist/utils/cqrs/index.cjs.map +1 -0
  404. package/dist/{index-CeFiHtAg.d.ts → utils/cqrs/index.d.cts} +7 -37
  405. package/dist/{index-B-_tFaqV.d.cts → utils/cqrs/index.d.ts} +7 -37
  406. package/dist/utils/cqrs/index.js +18 -0
  407. package/dist/utils/cqrs/index.js.map +1 -0
  408. package/dist/utils/demo-shell/index.cjs +865 -0
  409. package/dist/utils/demo-shell/index.cjs.map +1 -0
  410. package/dist/{index-B8YnZpIR.d.ts → utils/demo-shell/index.d.cts} +4 -16
  411. package/dist/{index-Cwv0KWcU.d.cts → utils/demo-shell/index.d.ts} +4 -16
  412. package/dist/utils/demo-shell/index.js +13 -0
  413. package/dist/utils/demo-shell/index.js.map +1 -0
  414. package/dist/utils/domain-templates/index.cjs +732 -0
  415. package/dist/utils/domain-templates/index.cjs.map +1 -0
  416. package/dist/{index-CzLVrjxn.d.ts → utils/domain-templates/index.d.cts} +3 -20
  417. package/dist/{index-BaQaY_IQ.d.cts → utils/domain-templates/index.d.ts} +3 -20
  418. package/dist/utils/domain-templates/index.js +17 -0
  419. package/dist/utils/domain-templates/index.js.map +1 -0
  420. package/dist/utils/graphspec/index.cjs +1174 -0
  421. package/dist/utils/graphspec/index.cjs.map +1 -0
  422. package/dist/{index-CMh5Rz1y.d.ts → utils/graphspec/index.d.cts} +106 -42
  423. package/dist/{index-CS0LTlB8.d.cts → utils/graphspec/index.d.ts} +106 -42
  424. package/dist/utils/graphspec/index.js +35 -0
  425. package/dist/utils/graphspec/index.js.map +1 -0
  426. package/dist/utils/harness/index.cjs +656 -0
  427. package/dist/utils/harness/index.cjs.map +1 -0
  428. package/dist/utils/harness/index.d.cts +542 -0
  429. package/dist/utils/harness/index.d.ts +542 -0
  430. package/dist/utils/harness/index.js +56 -0
  431. package/dist/utils/harness/index.js.map +1 -0
  432. package/dist/utils/index.cjs +17609 -0
  433. package/dist/utils/index.cjs.map +1 -0
  434. package/dist/utils/index.d.cts +96 -0
  435. package/dist/utils/index.d.ts +96 -0
  436. package/dist/utils/index.js +514 -0
  437. package/dist/utils/index.js.map +1 -0
  438. package/dist/utils/inspect/index.cjs +807 -0
  439. package/dist/utils/inspect/index.cjs.map +1 -0
  440. package/dist/utils/inspect/index.d.cts +123 -0
  441. package/dist/utils/inspect/index.d.ts +123 -0
  442. package/dist/utils/inspect/index.js +30 -0
  443. package/dist/utils/inspect/index.js.map +1 -0
  444. package/dist/utils/job-queue/index.cjs +717 -0
  445. package/dist/utils/job-queue/index.cjs.map +1 -0
  446. package/dist/{index-DisjX8a-.d.ts → utils/job-queue/index.d.cts} +5 -26
  447. package/dist/{index-DV_1YuVk.d.cts → utils/job-queue/index.d.ts} +5 -26
  448. package/dist/utils/job-queue/index.js +18 -0
  449. package/dist/utils/job-queue/index.js.map +1 -0
  450. package/dist/utils/memory/index.cjs +1451 -0
  451. package/dist/utils/memory/index.cjs.map +1 -0
  452. package/dist/{index-CZ3r5Rxp.d.ts → utils/memory/index.d.cts} +242 -34
  453. package/dist/{index-B17QddL1.d.cts → utils/memory/index.d.ts} +242 -34
  454. package/dist/utils/memory/index.js +19 -0
  455. package/dist/utils/memory/index.js.map +1 -0
  456. package/dist/utils/messaging/index.cjs +666 -0
  457. package/dist/utils/messaging/index.cjs.map +1 -0
  458. package/dist/utils/messaging/index.d.cts +562 -0
  459. package/dist/utils/messaging/index.d.ts +562 -0
  460. package/dist/utils/messaging/index.js +50 -0
  461. package/dist/utils/messaging/index.js.map +1 -0
  462. package/dist/utils/orchestration/index.cjs +876 -0
  463. package/dist/utils/orchestration/index.cjs.map +1 -0
  464. package/dist/utils/orchestration/index.d.cts +233 -0
  465. package/dist/utils/orchestration/index.d.ts +233 -0
  466. package/dist/utils/orchestration/index.js +19 -0
  467. package/dist/utils/orchestration/index.js.map +1 -0
  468. package/dist/utils/process/index.cjs +743 -0
  469. package/dist/utils/process/index.cjs.map +1 -0
  470. package/dist/{index-p09KSrTN.d.ts → utils/process/index.d.cts} +97 -44
  471. package/dist/{index-CasX6Pfq.d.cts → utils/process/index.d.ts} +97 -44
  472. package/dist/utils/process/index.js +14 -0
  473. package/dist/utils/process/index.js.map +1 -0
  474. package/dist/utils/reactive-layout/index.cjs +1607 -0
  475. package/dist/utils/reactive-layout/index.cjs.map +1 -0
  476. package/dist/{index-B5S8ULbU.d.ts → utils/reactive-layout/index.d.cts} +58 -81
  477. package/dist/{index-Dc4AYqrJ.d.cts → utils/reactive-layout/index.d.ts} +58 -81
  478. package/dist/utils/reactive-layout/index.js +52 -0
  479. package/dist/utils/reactive-layout/index.js.map +1 -0
  480. package/dist/utils/reduction/index.cjs +203 -0
  481. package/dist/utils/reduction/index.cjs.map +1 -0
  482. package/dist/{index-Byu-OpX_.d.ts → utils/reduction/index.d.cts} +6 -17
  483. package/dist/{index-tRCxuAXF.d.cts → utils/reduction/index.d.ts} +6 -17
  484. package/dist/utils/reduction/index.js +14 -0
  485. package/dist/utils/reduction/index.js.map +1 -0
  486. package/dist/utils/resilience/index.cjs +1617 -0
  487. package/dist/utils/resilience/index.cjs.map +1 -0
  488. package/dist/utils/resilience/index.d.cts +9 -0
  489. package/dist/utils/resilience/index.d.ts +9 -0
  490. package/dist/utils/resilience/index.js +44 -0
  491. package/dist/utils/resilience/index.js.map +1 -0
  492. package/dist/utils/surface/index.cjs +1070 -0
  493. package/dist/utils/surface/index.cjs.map +1 -0
  494. package/dist/{index-CYq8vAyV.d.ts → utils/surface/index.d.cts} +7 -58
  495. package/dist/{index-CSOmP7xT.d.cts → utils/surface/index.d.ts} +7 -58
  496. package/dist/utils/surface/index.js +30 -0
  497. package/dist/utils/surface/index.js.map +1 -0
  498. package/dist/utils/topology-view/index.cjs +620 -0
  499. package/dist/utils/topology-view/index.cjs.map +1 -0
  500. package/dist/utils/topology-view/index.d.cts +68 -0
  501. package/dist/utils/topology-view/index.d.ts +68 -0
  502. package/dist/utils/topology-view/index.js +11 -0
  503. package/dist/utils/topology-view/index.js.map +1 -0
  504. package/package.json +664 -584
  505. package/dist/backoff-HPZMEZNF.js +0 -1
  506. package/dist/chunk-2T7U5EU6.js +0 -1
  507. package/dist/chunk-3G5U5QNE.js +0 -5
  508. package/dist/chunk-4VVTGLXJ.js +0 -1
  509. package/dist/chunk-5M4CCMMD.js +0 -45
  510. package/dist/chunk-5QDBSZBV.js +0 -1
  511. package/dist/chunk-5XJ6B66J.js +0 -1
  512. package/dist/chunk-6QZNQS5B.js +0 -1
  513. package/dist/chunk-6X7AFUJV.js +0 -9
  514. package/dist/chunk-7K6PWTDQ.js +0 -1
  515. package/dist/chunk-7LIAPXJB.js +0 -1
  516. package/dist/chunk-7WPU3UHQ.js +0 -1
  517. package/dist/chunk-A5WCQ5NO.js +0 -1
  518. package/dist/chunk-APPIWSGD.js +0 -84
  519. package/dist/chunk-BEZWM2SY.js +0 -1
  520. package/dist/chunk-C72GO4IZ.js +0 -1
  521. package/dist/chunk-CB676TKJ.js +0 -1
  522. package/dist/chunk-CE6TI2TL.js +0 -1
  523. package/dist/chunk-CE72X3WO.js +0 -1
  524. package/dist/chunk-CK2E7BTU.js +0 -1
  525. package/dist/chunk-CLVB32RD.js +0 -1
  526. package/dist/chunk-CRVT7D2P.js +0 -1
  527. package/dist/chunk-D5RFJOZ2.js +0 -1
  528. package/dist/chunk-D7GPHKFH.js +0 -1
  529. package/dist/chunk-DHRX7JX4.js +0 -2
  530. package/dist/chunk-ESMPEKEV.js +0 -1
  531. package/dist/chunk-F672GV32.js +0 -1
  532. package/dist/chunk-FZMYDOWV.js +0 -1
  533. package/dist/chunk-GHBWHMRZ.js +0 -1
  534. package/dist/chunk-GLERH466.js +0 -1
  535. package/dist/chunk-GPW2V3RE.js +0 -1
  536. package/dist/chunk-HIDYF36O.js +0 -1
  537. package/dist/chunk-HITNVN6B.js +0 -3
  538. package/dist/chunk-HY4DJBA7.js +0 -5
  539. package/dist/chunk-KZIEYVXN.js +0 -1
  540. package/dist/chunk-L6NSJVJZ.js +0 -1
  541. package/dist/chunk-N4MQX6JU.js +0 -18
  542. package/dist/chunk-N7FHEL4D.js +0 -1
  543. package/dist/chunk-NTEURFZH.js +0 -1
  544. package/dist/chunk-OIVP6KFV.js +0 -1
  545. package/dist/chunk-OPHBU3LG.js +0 -1
  546. package/dist/chunk-OYQOZP2F.js +0 -5
  547. package/dist/chunk-PTZK576G.js +0 -1
  548. package/dist/chunk-QYADASLV.js +0 -1
  549. package/dist/chunk-ST7UXLWR.js +0 -1
  550. package/dist/chunk-SVY7VUYU.js +0 -1
  551. package/dist/chunk-TK3NWWD4.js +0 -1
  552. package/dist/chunk-TSOYJ743.js +0 -1
  553. package/dist/chunk-UNGSTR4X.js +0 -61
  554. package/dist/chunk-VIMF6LGM.js +0 -1
  555. package/dist/chunk-VJLMUKOI.js +0 -1
  556. package/dist/chunk-VN6RDSK2.js +0 -1
  557. package/dist/chunk-VV4N5P64.js +0 -1
  558. package/dist/chunk-W3I423PS.js +0 -1
  559. package/dist/chunk-WJR24TAG.js +0 -1
  560. package/dist/chunk-XTGKMHSW.js +0 -1
  561. package/dist/chunk-YBB7ZGTY.js +0 -1
  562. package/dist/chunk-Z4NPUARF.js +0 -1
  563. package/dist/chunk-ZGNQRPDT.js +0 -1
  564. package/dist/chunk-ZKPSFFKU.js +0 -1
  565. package/dist/chunk-ZLV5SQSX.js +0 -1
  566. package/dist/content-addressed-storage-4-ST1tYk.d.cts +0 -124
  567. package/dist/content-addressed-storage-DuYMjV7o.d.ts +0 -124
  568. package/dist/core/index.cjs +0 -1
  569. package/dist/core/index.d.cts +0 -3
  570. package/dist/core/index.d.ts +0 -3
  571. package/dist/core/index.js +0 -1
  572. package/dist/decay-BvOWTZ00.d.ts +0 -112
  573. package/dist/decay-CFlLvXUT.d.cts +0 -112
  574. package/dist/extra/browser.cjs +0 -1
  575. package/dist/extra/browser.d.cts +0 -4
  576. package/dist/extra/browser.d.ts +0 -4
  577. package/dist/extra/browser.js +0 -1
  578. package/dist/extra/index.cjs +0 -20
  579. package/dist/extra/index.d.cts +0 -17
  580. package/dist/extra/index.d.ts +0 -17
  581. package/dist/extra/index.js +0 -1
  582. package/dist/extra/node.cjs +0 -2
  583. package/dist/extra/node.js +0 -2
  584. package/dist/extra/operators.cjs +0 -1
  585. package/dist/extra/operators.d.cts +0 -958
  586. package/dist/extra/operators.d.ts +0 -958
  587. package/dist/extra/operators.js +0 -1
  588. package/dist/extra/reactive.cjs +0 -1
  589. package/dist/extra/reactive.d.cts +0 -353
  590. package/dist/extra/reactive.d.ts +0 -353
  591. package/dist/extra/reactive.js +0 -1
  592. package/dist/extra/render/index.cjs +0 -5
  593. package/dist/extra/render/index.js +0 -1
  594. package/dist/extra/sources.cjs +0 -3
  595. package/dist/extra/sources.js +0 -1
  596. package/dist/extra/storage-browser.cjs +0 -1
  597. package/dist/extra/storage-browser.d.cts +0 -37
  598. package/dist/extra/storage-browser.d.ts +0 -37
  599. package/dist/extra/storage-browser.js +0 -1
  600. package/dist/extra/storage-core.cjs +0 -1
  601. package/dist/extra/storage-core.d.cts +0 -28
  602. package/dist/extra/storage-core.d.ts +0 -28
  603. package/dist/extra/storage-core.js +0 -1
  604. package/dist/extra/storage-node.cjs +0 -1
  605. package/dist/extra/storage-node.d.cts +0 -2
  606. package/dist/extra/storage-node.d.ts +0 -2
  607. package/dist/extra/storage-node.js +0 -0
  608. package/dist/extra/storage-tiers-browser.cjs +0 -1
  609. package/dist/extra/storage-tiers-browser.d.cts +0 -120
  610. package/dist/extra/storage-tiers-browser.d.ts +0 -120
  611. package/dist/extra/storage-tiers-browser.js +0 -1
  612. package/dist/extra/storage-tiers-node.cjs +0 -1
  613. package/dist/extra/storage-tiers-node.d.cts +0 -210
  614. package/dist/extra/storage-tiers-node.d.ts +0 -210
  615. package/dist/extra/storage-tiers-node.js +0 -1
  616. package/dist/extra/storage-tiers.cjs +0 -1
  617. package/dist/extra/storage-tiers.d.cts +0 -412
  618. package/dist/extra/storage-tiers.d.ts +0 -412
  619. package/dist/extra/storage-tiers.js +0 -1
  620. package/dist/graph/index.cjs +0 -7
  621. package/dist/graph/index.d.cts +0 -7
  622. package/dist/graph/index.d.ts +0 -7
  623. package/dist/graph/index.js +0 -1
  624. package/dist/graph-CWvEUQAq.d.cts +0 -1861
  625. package/dist/graph-D9LFnda9.d.ts +0 -1861
  626. package/dist/index-5k1T6jl0.d.cts +0 -121
  627. package/dist/index-9770hRuQ.d.cts +0 -779
  628. package/dist/index-B1F8Enjf.d.ts +0 -704
  629. package/dist/index-BHskSB8v.d.ts +0 -3413
  630. package/dist/index-BIYAkbAi.d.cts +0 -26
  631. package/dist/index-BoJ5JHxI.d.ts +0 -557
  632. package/dist/index-BocU7pqs.d.ts +0 -779
  633. package/dist/index-BxNs2HB9.d.cts +0 -1858
  634. package/dist/index-C1T3d7V-.d.cts +0 -704
  635. package/dist/index-C5ri2Axc.d.cts +0 -301
  636. package/dist/index-C9l6OEBL.d.ts +0 -26
  637. package/dist/index-CC-AvFTy.d.cts +0 -557
  638. package/dist/index-CJF1URuX.d.ts +0 -121
  639. package/dist/index-CdTelp1M.d.ts +0 -202
  640. package/dist/index-Cj3WohTd.d.cts +0 -202
  641. package/dist/index-Co7uli2l.d.cts +0 -3413
  642. package/dist/index-D0aciIex.d.cts +0 -209
  643. package/dist/index-DHen9Klo.d.ts +0 -1858
  644. package/dist/index-Yq60JP3s.d.ts +0 -209
  645. package/dist/index-nozs3fFC.d.ts +0 -301
  646. package/dist/node-kK3CvTrR.d.cts +0 -1347
  647. package/dist/node-kK3CvTrR.d.ts +0 -1347
  648. package/dist/patterns/ai/browser.cjs +0 -8
  649. package/dist/patterns/ai/browser.js +0 -3
  650. package/dist/patterns/ai/index.cjs +0 -74
  651. package/dist/patterns/ai/index.d.cts +0 -20
  652. package/dist/patterns/ai/index.d.ts +0 -20
  653. package/dist/patterns/ai/index.js +0 -1
  654. package/dist/patterns/ai/node.cjs +0 -1
  655. package/dist/patterns/ai/node.js +0 -1
  656. package/dist/patterns/cqrs/index.cjs +0 -3
  657. package/dist/patterns/cqrs/index.d.cts +0 -8
  658. package/dist/patterns/cqrs/index.d.ts +0 -8
  659. package/dist/patterns/cqrs/index.js +0 -1
  660. package/dist/patterns/demo-shell/index.cjs +0 -5
  661. package/dist/patterns/demo-shell/index.d.cts +0 -7
  662. package/dist/patterns/demo-shell/index.d.ts +0 -7
  663. package/dist/patterns/demo-shell/index.js +0 -1
  664. package/dist/patterns/domain-templates/index.cjs +0 -3
  665. package/dist/patterns/domain-templates/index.d.cts +0 -6
  666. package/dist/patterns/domain-templates/index.d.ts +0 -6
  667. package/dist/patterns/domain-templates/index.js +0 -1
  668. package/dist/patterns/graphspec/index.cjs +0 -86
  669. package/dist/patterns/graphspec/index.d.cts +0 -8
  670. package/dist/patterns/graphspec/index.d.ts +0 -8
  671. package/dist/patterns/graphspec/index.js +0 -1
  672. package/dist/patterns/harness/index.cjs +0 -48
  673. package/dist/patterns/harness/index.d.cts +0 -13
  674. package/dist/patterns/harness/index.d.ts +0 -13
  675. package/dist/patterns/harness/index.js +0 -1
  676. package/dist/patterns/inspect/index.cjs +0 -3
  677. package/dist/patterns/inspect/index.d.cts +0 -9
  678. package/dist/patterns/inspect/index.d.ts +0 -9
  679. package/dist/patterns/inspect/index.js +0 -1
  680. package/dist/patterns/job-queue/index.cjs +0 -3
  681. package/dist/patterns/job-queue/index.d.cts +0 -9
  682. package/dist/patterns/job-queue/index.d.ts +0 -9
  683. package/dist/patterns/job-queue/index.js +0 -1
  684. package/dist/patterns/memory/index.cjs +0 -3
  685. package/dist/patterns/memory/index.d.cts +0 -8
  686. package/dist/patterns/memory/index.d.ts +0 -8
  687. package/dist/patterns/memory/index.js +0 -1
  688. package/dist/patterns/messaging/index.cjs +0 -3
  689. package/dist/patterns/messaging/index.d.cts +0 -7
  690. package/dist/patterns/messaging/index.d.ts +0 -7
  691. package/dist/patterns/messaging/index.js +0 -1
  692. package/dist/patterns/orchestration/index.cjs +0 -3
  693. package/dist/patterns/orchestration/index.d.cts +0 -8
  694. package/dist/patterns/orchestration/index.d.ts +0 -8
  695. package/dist/patterns/orchestration/index.js +0 -1
  696. package/dist/patterns/process/index.cjs +0 -3
  697. package/dist/patterns/process/index.d.cts +0 -10
  698. package/dist/patterns/process/index.d.ts +0 -10
  699. package/dist/patterns/process/index.js +0 -1
  700. package/dist/patterns/reactive-layout/index.cjs +0 -4
  701. package/dist/patterns/reactive-layout/index.d.cts +0 -7
  702. package/dist/patterns/reactive-layout/index.d.ts +0 -7
  703. package/dist/patterns/reactive-layout/index.js +0 -1
  704. package/dist/patterns/reduction/index.cjs +0 -3
  705. package/dist/patterns/reduction/index.d.cts +0 -6
  706. package/dist/patterns/reduction/index.d.ts +0 -6
  707. package/dist/patterns/reduction/index.js +0 -1
  708. package/dist/patterns/surface/index.cjs +0 -13
  709. package/dist/patterns/surface/index.d.cts +0 -9
  710. package/dist/patterns/surface/index.d.ts +0 -9
  711. package/dist/patterns/surface/index.js +0 -1
  712. package/dist/reactive-log-BKALbfal.d.ts +0 -223
  713. package/dist/reactive-log-DIGdYqQ6.d.cts +0 -223
  714. package/dist/reactive-map-CEFGp8TK.d.cts +0 -296
  715. package/dist/reactive-map-DS_SIAxv.d.ts +0 -296
  716. package/dist/resilience-6LYQJAC5.js +0 -1
  717. package/dist/sugar-DQjFmVqb.d.cts +0 -399
  718. package/dist/sugar-fhLIE7TT.d.ts +0 -399
  719. package/dist/topology-tree-Bcz27hpF.d.cts +0 -25
  720. package/dist/topology-tree-xvaD0fOX.d.ts +0 -25
@@ -1,11 +1,2243 @@
1
- "use strict";var es=Object.create;var De=Object.defineProperty;var xn=Object.getOwnPropertyDescriptor;var ts=Object.getOwnPropertyNames;var ns=Object.prototype.hasOwnProperty;var Nn=(r,e)=>(e=Symbol[r])?e:Symbol.for("Symbol."+r),Je=r=>{throw TypeError(r)};var rs=(r,e,t)=>e in r?De(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var Tn=(r,e)=>De(r,"name",{value:e,configurable:!0});var $=(r,e)=>()=>(r&&(e=r(r=0)),e);var ss=(r,e)=>{for(var t in e)De(r,t,{get:e[t],enumerable:!0})},os=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of ts(e))!ns.call(r,s)&&s!==t&&De(r,s,{get:()=>e[s],enumerable:!(n=xn(e,s))||n.enumerable});return r};var is=r=>os(De({},"__esModule",{value:!0}),r);var kn=r=>[,,,es(r?.[Nn("metadata")]??null)],Rn=["class","method","getter","setter","accessor","field","value","get","set"],Ye=r=>r!==void 0&&typeof r!="function"?Je("Function expected"):r,as=(r,e,t,n,s)=>({kind:Rn[r],name:e,metadata:n,addInitializer:o=>t._?Je("Already initialized"):s.push(Ye(o||null))}),ds=(r,e)=>rs(e,Nn("metadata"),r[3]),Sn=(r,e,t,n)=>{for(var s=0,o=r[e>>1],i=o&&o.length;s<i;s++)e&1?o[s].call(t):n=o[s].call(t,n);return n},An=(r,e,t,n,s,o)=>{var i,a,d,u,c,f=e&7,p=!!(e&8),h=!!(e&16),l=f>3?r.length+1:f?p?1:2:0,m=Rn[f+5],g=f>3&&(r[l-1]=[]),E=r[l]||(r[l]=[]),v=f&&(!h&&!p&&(s=s.prototype),f<5&&(f>3||!h)&&xn(f<4?s:{get[t](){return En(this,o)},set[t](b){return On(this,o,b)}},t));f?h&&f<4&&Tn(o,(f>2?"set ":f>1?"get ":"")+t):Tn(s,t);for(var _=n.length-1;_>=0;_--)u=as(f,t,d={},r[3],E),f&&(u.static=p,u.private=h,c=u.access={has:h?b=>us(s,b):b=>t in b},f^3&&(c.get=h?b=>(f^1?En:cs)(b,s,f^4?o:v.get):b=>b[t]),f>2&&(c.set=h?(b,w)=>On(b,s,w,f^4?o:v.set):(b,w)=>b[t]=w)),a=(0,n[_])(f?f<4?h?o:v[m]:f>4?void 0:{get:v.get,set:v.set}:s,u),d._=1,f^4||a===void 0?Ye(a)&&(f>4?g.unshift(a):f?h?o=a:v[m]=a:s=a):typeof a!="object"||a===null?Je("Object expected"):(Ye(i=a.get)&&(v.get=i),Ye(i=a.set)&&(v.set=i),Ye(i=a.init)&&g.unshift(i));return f||ds(r,s),v&&De(s,t,v),h?f^4?o:v:s};var Vt=(r,e,t)=>e.has(r)||Je("Cannot "+t),us=(r,e)=>Object(e)!==e?Je('Cannot use the "in" operator on this value'):r.has(e),En=(r,e,t)=>(Vt(r,e,"read from private field"),t?t.call(r):e.get(r));var On=(r,e,t,n)=>(Vt(r,e,"write to private field"),n?n.call(r,t):e.set(r,t),t),cs=(r,e,t)=>(Vt(r,e,"access private method"),t);var ye,M,j,W,ee,Q,te,F,G,D,be,pt,Cn,ht,Mn,Dn,gt,zt,jt,Bt,mt,ne=$(()=>{"use strict";ye=Symbol.for("graphrefly/START"),M=Symbol.for("graphrefly/DATA"),j=Symbol.for("graphrefly/DIRTY"),W=Symbol.for("graphrefly/RESOLVED"),ee=Symbol.for("graphrefly/INVALIDATE"),Q=Symbol.for("graphrefly/PAUSE"),te=Symbol.for("graphrefly/RESUME"),F=Symbol.for("graphrefly/TEARDOWN"),G=Symbol.for("graphrefly/COMPLETE"),D=Symbol.for("graphrefly/ERROR"),be=Object.freeze([j]),pt=Object.freeze([W]),Cn=Object.freeze([ee]),ht=Object.freeze([ye]),Mn=Object.freeze([G]),Dn=Object.freeze([F]),gt=Object.freeze([be]),zt=Object.freeze([pt]),jt=Object.freeze([Cn]),Bt=Object.freeze([Mn]),mt=Object.freeze([Dn])});function le(){return Math.trunc(performance.now()*1e6)}function se(){return Date.now()*1e6}var _e=$(()=>{"use strict"});function Wn(r,e){let t=new TextEncoder().encode(r.name);if(t.length===0||t.length>255)throw new Error(`encodeEnvelope: codec name "${r.name}" encodes to ${t.length} bytes (must be 1\u2013255)`);let n=r.version;if(!Number.isInteger(n)||n<0||n>65535)throw new Error(`encodeEnvelope: codec.version ${n} out of u16 range (expected integer 0\u201365535)`);let s=2+t.length+2+e.length;if(s>4294967295)throw new Error(`encodeEnvelope: total envelope size ${s} exceeds 2^32-1 bytes (payload ${e.length} bytes)`);let o=new Uint8Array(s),i=0;return o[i++]=Kt,o[i++]=t.length,o.set(t,i),i+=t.length,o[i++]=n>>>8&255,o[i++]=n&255,o.set(e,i),o}function Kn(r,e){if(r.length<Bn)throw new Error(`decodeEnvelope: bytes too short (${r.length} < ${Bn})`);let t=0,n=r[t++];if(n!==Kt)throw new Error(`decodeEnvelope: unsupported envelope version ${n} (expected ${Kt})`);let s=r[t++];if(s===0)throw new Error("decodeEnvelope: name_len must be >= 1");if(t+s+2>r.length)throw new Error(`decodeEnvelope: envelope truncated (need ${t+s+2} bytes, have ${r.length})`);let o=new TextDecoder().decode(r.subarray(t,t+s));t+=s;let i=(r[t]<<8|r[t+1])>>>0;t+=2;let a=r.subarray(t),d=e.lookupCodec(o);if(d==null)throw new Error(`decodeEnvelope: codec "${o}" not registered (envelope codec_v=${i})`);return{codec:d,codecVersion:i,payload:a}}function Un(r){r.registerCodec(ls)}var ls,Kt,Bn,Ut=$(()=>{"use strict";ls={name:"json",version:1,contentType:"application/json",encode(r){let e=JSON.stringify(r);return new TextEncoder().encode(e)},decode(r,e){let t=new TextDecoder().decode(r);return JSON.parse(t)}},Kt=1,Bn=4});function we(r){if(r==null)return pe;let{type:e,id:t,...n}=r;return{type:e??"system",id:t??"",...n}}var pe,Ze=$(()=>{"use strict";pe={type:"system",id:""}});function yt(){return qe>0||Xe}function Yn(){return qe>0}function ze(r){qe>0?et.push(r):r()}function Oe(r){qe+=1;let e=!1;try{r()}catch(t){throw e=!0,t}finally{if(qe-=1,qe===0)if(e){if(!Xe){let t=et.splice(0);for(let n of t)try{n()}catch{}Te.length=0,Ee.length=0,Ve.length=0}}else fs()}}function fs(){let r=!Xe;r&&(Xe=!0);let e=[],t=0;try{for(;Te.length>0||Ee.length>0||Ve.length>0||r&&et.length>0;){if(r&&et.length>0){let o=et.splice(0);for(let i of o)try{i()}catch(a){e.push(a)}continue}if(t+=1,t>1e3)throw Te.length=0,Ee.length=0,Ve.length=0,new Error("batch drain exceeded 1000 iterations \u2014 likely a reactive cycle");let s=(Te.length>0?Te:Ee.length>0?Ee:Ve).splice(0);for(let o of s)try{o()}catch(i){e.push(i)}}}finally{r&&(Xe=!1)}if(e.length===1)throw e[0];if(e.length>1)throw new AggregateError(e,"batch drain: multiple callbacks threw")}function bt(r,e,t){if(e.length===0)return;if(e.length===1){let u=t(e[0][0]);if(u<3||!yt()){r(e);return}(u>=5?Ve:u===4?Ee:Te).push(()=>r(e));return}let n=e.length,s=n,o=n,i=n,a=0;for(;a<n&&t(e[a][0])<3;)a++;for(s=a;a<n&&t(e[a][0])===3;)a++;for(o=a;a<n&&t(e[a][0])===4;)a++;i=a;let d=yt();if(s>0){let u=e.slice(0,s);r(u)}if(o>s){let u=e.slice(s,o);d?Te.push(()=>r(u)):r(u)}if(i>o){let u=e.slice(o,i);d?Ee.push(()=>r(u)):r(u)}if(n>i){let u=e.slice(i,n);d?Ve.push(()=>r(u)):r(u)}}var qe,Xe,Te,Ee,Ve,et,tt=$(()=>{"use strict";qe=0,Xe=!1,Te=[],Ee=[],Ve=[],et=[]});function Jn(r){r.registerMessageType(ye,{tier:0,wireCrossing:!1}),r.registerMessageType(j,{tier:1,wireCrossing:!1}),r.registerMessageType(ee,{tier:1,wireCrossing:!1,metaPassthrough:!1}),r.registerMessageType(Q,{tier:2,wireCrossing:!1}),r.registerMessageType(te,{tier:2,wireCrossing:!1}),r.registerMessageType(M,{tier:3,wireCrossing:!0}),r.registerMessageType(W,{tier:3,wireCrossing:!0}),r.registerMessageType(G,{tier:4,wireCrossing:!0,metaPassthrough:!1}),r.registerMessageType(D,{tier:4,wireCrossing:!0,metaPassthrough:!1}),r.registerMessageType(F,{tier:5,wireCrossing:!0,metaPassthrough:!1})}var vt,Qn=$(()=>{"use strict";ne();vt=class{_messageTypes=new Map;_codecs=new Map;_onMessage;_onSubscribe;_defaultVersioning;_defaultHashFn;_inspectorEnabled=!(typeof process<"u"&&process.env?.NODE_ENV==="production");_globalInspector;_rigorRecorder;_frozen=!1;tierOf;constructor(e){this._onMessage=e.onMessage,this._onSubscribe=e.onSubscribe,this._defaultVersioning=e.defaultVersioning,this._defaultHashFn=e.defaultHashFn,this.tierOf=t=>{let n=this._messageTypes.get(t);return n!=null?n.tier:1}}get onMessage(){return this._frozen=!0,this._onMessage}get onSubscribe(){return this._frozen=!0,this._onSubscribe}set onMessage(e){this._assertUnfrozen(),this._onMessage=e}set onSubscribe(e){this._assertUnfrozen(),this._onSubscribe=e}get defaultVersioning(){return this._defaultVersioning}set defaultVersioning(e){this._assertUnfrozen(),this._defaultVersioning=e}get defaultHashFn(){return this._defaultHashFn}set defaultHashFn(e){this._assertUnfrozen(),this._defaultHashFn=e}get inspectorEnabled(){return this._inspectorEnabled}set inspectorEnabled(e){this._inspectorEnabled=e}get globalInspector(){return this._globalInspector}set globalInspector(e){this._globalInspector=e}get rigorRecorder(){return this._rigorRecorder}set rigorRecorder(e){this._rigorRecorder=e}registerMessageType(e,t){return this._assertUnfrozen(),this._messageTypes.set(e,{tier:t.tier,wireCrossing:t.wireCrossing??t.tier>=3,metaPassthrough:t.metaPassthrough??!0}),this}messageTier(e){let t=this._messageTypes.get(e);return t!=null?t.tier:1}isWireCrossing(e){let t=this._messageTypes.get(e);return t!=null?t.wireCrossing:!0}isLocalOnly(e){return!this.isWireCrossing(e)}isMetaPassthrough(e){let t=this._messageTypes.get(e);return t!=null?t.metaPassthrough:!0}isKnownMessageType(e){return this._messageTypes.has(e)}registerCodec(e){return this._assertUnfrozen(),this._codecs.set(e.name,e),this}lookupCodec(e){return this._codecs.get(e)}_isFrozen(){return this._frozen}_assertUnfrozen(){if(this._frozen)throw new Error("GraphReFlyConfig is frozen: a node has already captured this config. Register custom types and set hooks before creating any node.")}}});function Zn(r){return Array.isArray(r)?[...r]:[r]}function ps(r,e){return r.has(e)||r.has("*")}function je(r){let e=[];return r((s,o)=>{e.push({kind:"allow",actions:new Set(Zn(s)),where:o?.where??(()=>!0)})},(s,o)=>{e.push({kind:"deny",actions:new Set(Zn(s)),where:o?.where??(()=>!0)})}),(s,o)=>{let i=!1,a=!1;for(let d of e)ps(d.actions,o)&&d.where(s)&&(d.kind==="deny"?i=!0:a=!0);return i?!1:a}}function Yt(r){let e=hs.filter(t=>r({type:t,id:""},"write"));return e.length===0?"restricted":e.includes("human")&&e.includes("llm")&&e.every(t=>t==="human"||t==="llm"||t==="system")?"both":e.length===1?e[0]:e.join("+")}var oe,hs,xe=$(()=>{"use strict";oe=class extends Error{actor;action;nodeName;constructor(e,t){super(t??`GuardDenied: action "${String(e.action)}" denied for actor type "${String(e.actor.type)}"`),this.name="GuardDenied",this.actor=e.actor,this.action=e.action,this.nodeName=e.nodeName}get node(){return this.nodeName}};hs=["human","llm","wallet","system"]});function Jt(r){if(r===void 0)return null;if(typeof r=="number"){if(!Number.isFinite(r))throw new TypeError(`Cannot hash non-finite number: ${r}`);if(Number.isInteger(r)&&!Number.isSafeInteger(r))throw new TypeError(`Cannot hash integer outside safe range (|n| > 2^53-1): ${r}. Cross-language cid parity is not guaranteed for unsafe integers.`);return r}if(typeof r=="string"||typeof r=="boolean"||r===null)return r;if(Array.isArray(r))return r.map(Jt);if(typeof r=="object"&&r!==null){let e={};for(let t of Object.keys(r).sort())e[t]=Jt(r[t]);return e}return null}function ys(r){let e=ms.encode(r),t=e.length,n=t*8,s=t+9+63&-64,o=new Uint8Array(s);o.set(e),o[t]=128;let i=new DataView(o.buffer);i.setUint32(s-4,n>>>0,!1),i.setUint32(s-8,Math.floor(n/4294967296)>>>0,!1);let a=1779033703,d=3144134277,u=1013904242,c=2773480762,f=1359893119,p=2600822924,h=528734635,l=1541459225,m=new Uint32Array(64),g=(v,_)=>v>>>_|v<<32-_;for(let v=0;v<s;v+=64){for(let T=0;T<16;T++)m[T]=i.getUint32(v+T*4,!1);for(let T=16;T<64;T++){let R=m[T-15],C=m[T-2],S=g(R,7)^g(R,18)^R>>>3,H=g(C,17)^g(C,19)^C>>>10;m[T]=m[T-16]+S+m[T-7]+H>>>0}let _=a,b=d,w=u,N=c,y=f,O=p,k=h,x=l;for(let T=0;T<64;T++){let R=g(y,6)^g(y,11)^g(y,25),C=y&O^~y&k,S=x+R+C+gs[T]+m[T]>>>0,H=g(_,2)^g(_,13)^g(_,22),z=_&b^_&w^b&w,J=H+z>>>0;x=k,k=O,O=y,y=N+S>>>0,N=w,w=b,b=_,_=S+J>>>0}a=a+_>>>0,d=d+b>>>0,u=u+w>>>0,c=c+N>>>0,f=f+y>>>0,p=p+O>>>0,h=h+k>>>0,l=l+x>>>0}let E=v=>v.toString(16).padStart(8,"0");return E(a)+E(d)+E(u)+E(c)+E(f)+E(p)+E(h)+E(l)}function Qt(r){let e=Jt(r??null),t=JSON.stringify(e);return ys(t).slice(0,16)}function bs(){let r=globalThis.crypto;if(r?.randomUUID)return r.randomUUID();let e=()=>Math.floor(Math.random()*4294967296).toString(16).padStart(8,"0"),t=e()+e()+e()+e();return`${t.slice(0,8)}-${t.slice(8,12)}-4${t.slice(13,16)}-${(parseInt(t.slice(16,17),16)&3|8).toString(16)}${t.slice(17,20)}-${t.slice(20,32)}`}function Zt(r,e,t){let n=t?.id??bs();if(r===0)return{id:n,version:0};let o=(t?.hash??Qt)(e);return{id:n,version:0,cid:o,prev:null}}function Xn(r,e,t){r.version+=1,"cid"in r&&(r.prev=r.cid,r.cid=t(e))}var gs,ms,er=$(()=>{"use strict";gs=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),ms=new TextEncoder});function rr(r){return{node:r,unsub:null,prevData:void 0,dirty:!1,involvedThisWave:!1,dataBatch:[],terminal:void 0}}function Xt(r){r.prevData=void 0,r.dirty=!1,r.involvedThisWave=!1,r.dataBatch.length=0,r.terminal=void 0}function _t(r){return r.length===0?r:typeof r[0]=="symbol"?[r]:r}function ue(r,e,t){let n=sr(r)?r:[],s=typeof r=="function"?r:typeof e=="function"?e:void 0,o={};return sr(r)?o=(en(e)?e:t)??{}:en(r)?o=r:o=(en(e)?e:t)??{},new q(n,s,o)}var tr,nr,vs,_s,Ne,q,sr,en,ke=$(()=>{"use strict";Ut();Ze();tt();_e();Qn();xe();ne();er();tr=()=>{},nr=100;vs=(r,e,t,n)=>{t.direction==="down-in"&&r._onDepMessage(t.depIndex,e)},_s=(r,e,t,n)=>{let s=r;if(s._status==="completed"||s._status==="errored")return;let o=s._cached,i=o===void 0?[ht]:[ht,[M,o]];s._status==="dirty"&&i.push(be),bt(e,i,s._config.tierOf)},Ne=new vt({onMessage:vs,onSubscribe:_s});Jn(Ne);Un(Ne);q=class r{_optsName;_describeKind;meta;_hasMeta;_config;_deps;_sinks=null;_sinkCount=0;_cached;_status;_cleanup;_store={};_waveHasNewData=!1;_hasNewTerminal=!1;_hasCalledFnOnce=!1;_paused=!1;_pendingWave=!1;_isExecutingFn=!1;_pendingRerun=!1;_rerunDepth=0;_dirtyDepCount=0;_batchPendingMessages=null;_pauseLocks=null;_pauseBuffer=null;_fn;_equals;_resubscribable;_resetOnTeardown;_autoComplete;_autoError;_pausable;_partial;_guard;_extraGuards;_hashFn;_versioning;_versioningLevel;_lastMutation;_inspectorHooks;_actions;constructor(e,t,n){this._config=n.config??Ne,this._config.onMessage,this._optsName=n.name,this._describeKind=n.describeKind,this._equals=n.equals??Object.is,this._resubscribable=n.resubscribable??!1,this._resetOnTeardown=n.resetOnTeardown??!1,this._autoComplete=n.completeWhenDepsComplete??!0,this._autoError=n.errorWhenDepsError??!0,this._pausable=n.pausable??!0,this._guard=n.guard,this._fn=t,this._partial=n.partial??!1,this._cached=n.initial!==void 0?n.initial:void 0,this._status=e.length===0&&t==null&&this._cached!==void 0?"settled":"sentinel",this._hashFn=n.versioningHash??this._config.defaultHashFn??Qt;let s=n.versioning??this._config.defaultVersioning;this._versioningLevel=s,this._versioning=s!=null?Zt(s,this._cached===void 0?void 0:this._cached,{id:n.versioningId,hash:this._hashFn}):void 0,this._deps=e.map(rr);let o={};for(let[a,d]of Object.entries(n.meta??{})){let u={initial:d,name:`${n.name??"node"}:meta:${a}`,describeKind:"state",config:this._config};n.guard!=null&&(u.guard=n.guard),n.resubscribable===!0&&(u.resubscribable=!0),o[a]=new r([],void 0,u)}Object.freeze(o),this.meta=o,this._hasMeta=Object.keys(o).length>0;let i=this;this._actions={emit(a){i._emit([[M,a]])},down(a){i._emit(_t(a))},up(a){i._emitUp(_t(a))}},this.down=this.down.bind(this),this.up=this.up.bind(this)}get _isTerminal(){return this._status==="completed"||this._status==="errored"}get name(){return this._optsName}get status(){return this._status}get cache(){return this._cached===void 0?void 0:this._cached}get lastMutation(){return this._lastMutation}get v(){return this._versioning}hasGuard(){return this._guard!=null}_applyVersioning(e,t){if(this._isExecutingFn)throw new Error(`Node "${this.name}": _applyVersioning cannot run mid-fn \u2014 call it outside of \`_execFn\` (typically at graph setup time before the first subscribe).`);let n=this._versioningLevel;if(n!=null&&e<=n)return;let s=t?.hash??this._hashFn;s!==this._hashFn&&(this._hashFn=s);let o=this._cached===void 0?void 0:this._cached,i=this._versioning,a=i?.id??t?.id,d=i?.version??0,u=Zt(e,o,{id:a,hash:s});u.version=d,this._versioning=u,this._versioningLevel=e}_setInspectorHook(e){return e==null?()=>{}:(this._inspectorHooks==null&&(this._inspectorHooks=new Set),this._inspectorHooks.add(e),()=>{this._inspectorHooks?.delete(e),this._inspectorHooks?.size===0&&(this._inspectorHooks=void 0)})}_pushGuard(e){return this._extraGuards==null&&(this._extraGuards=new Set),this._extraGuards.add(e),()=>{this._extraGuards?.delete(e),this._extraGuards?.size===0&&(this._extraGuards=void 0)}}allowsObserve(e){if(this._guard==null&&this._extraGuards==null)return!0;let t=we(e);if(this._guard!=null&&!this._guard(t,"observe"))return!1;if(this._extraGuards!=null){for(let n of this._extraGuards)if(!n(t,"observe"))return!1}return!0}_checkGuard(e){if(e?.internal)return;let t=this._guard!=null||this._extraGuards!=null,n=e?.actor!=null;if(!t&&!n)return;let s=we(e?.actor),o=e?.delivery==="signal"?"signal":"write";if(this._guard!=null&&!this._guard(s,o))throw new oe({actor:s,action:o,nodeName:this.name});if(this._extraGuards!=null){for(let i of this._extraGuards)if(!i(s,o))throw new oe({actor:s,action:o,nodeName:this.name})}this._lastMutation={actor:s,timestamp_ns:se()}}down(e,t){let n=_t(e);n.length!==0&&(this._checkGuard(t),this._emit(n))}emit(e,t){this._checkGuard(t),this._emit([[M,e]])}up(e,t){if(this._deps.length===0)return;let n=_t(e);if(n.length===0)return;this._checkGuard(t);let s=t??{internal:!0};this._validateUpTiers(n);for(let o of this._deps)o.node.up?.(n,s)}_emitUp(e){if(this._deps.length!==0&&e.length!==0){this._validateUpTiers(e);for(let t of this._deps)t.node.up?.(e,{internal:!0})}}_validateUpTiers(e){let t=this._config.tierOf;for(let n of e){let s=t(n[0]);if(s===3||s===4)throw new Error(`Node "${this.name}": tier-${s} messages cannot flow up \u2014 DATA/RESOLVED/COMPLETE/ERROR are downstream-only. Use \`down(...)\` for value delivery; \`up(...)\` is for control signals (DIRTY, INVALIDATE, PAUSE, RESUME, TEARDOWN).`)}}subscribe(e,t){if(t!=null&&this._guard!=null){let d=we(t);if(!this._guard(d,"observe"))throw new oe({actor:d,action:"observe",nodeName:this.name})}let s=this._isTerminal&&this._resubscribable;if(s){this._cached=void 0,this._status="sentinel",this._store={},this._hasCalledFnOnce=!1,this._waveHasNewData=!1,this._hasNewTerminal=!1,this._paused=!1,this._pendingWave=!1,this._pendingRerun=!1,this._isExecutingFn=!1,this._rerunDepth=0,this._dirtyDepCount=0,this._pauseLocks=null,this._pauseBuffer=null;for(let d of this._deps)Xt(d);if(this._partial===!1){for(let d of this._deps)if(d.prevData!==void 0||d.dataBatch.length!==0||d.terminal!==void 0||d.dirty)throw new Error(`resubscribable-reset invariant: DepRecord not fully reset for node ${this._optsName??"(anonymous)"}`)}}this._sinkCount+=1;let o;try{o=this._config.onSubscribe(this,e,{sinkCount:this._sinkCount,afterTerminalReset:s},this._actions)}catch(d){throw this._sinkCount-=1,d}this._sinks==null?this._sinks=e:typeof this._sinks=="function"?this._sinks=new Set([this._sinks,e]):this._sinks.add(e);let i=this._isTerminal;if(this._sinkCount===1&&!i)try{this._activate()}catch(d){if(this._sinkCount-=1,this._removeSink(e),this._sinkCount===0&&(this._status="sentinel"),typeof o=="function")try{o()}catch{}throw d}this._status==="sentinel"&&this._cached===void 0&&(this._status="pending");let a=!1;return()=>{a||(a=!0,this._sinkCount-=1,this._removeSink(e),typeof o=="function"&&o(),this._sinks==null&&this._deactivate())}}_removeSink(e){if(this._sinks===e)this._sinks=null;else if(this._sinks!=null&&typeof this._sinks!="function")if(this._sinks.delete(e),this._sinks.size===1){let[t]=this._sinks;this._sinks=t}else this._sinks.size===0&&(this._sinks=null)}_activate(){if(this._deps.length===0){this._fn&&this._execFn();return}this._dirtyDepCount=0;let e=this._deps.length,t=0;try{for(let n=0;n<e;n++){let s=n,o=this._deps[n];o.unsub=tr,o.unsub=o.node.subscribe(i=>{if(o.unsub===null)return;let a=this._config.tierOf,d=!1;for(let u of i)a(u[0])>=3&&(d=!0),this._config.onMessage(this,u,{direction:"down-in",depIndex:s},this._actions);d&&this._maybeRunFnOnSettlement()}),t++}}catch(n){this._deps[t].unsub=null;for(let s=0;s<t;s++){let o=this._deps[s];if(o.unsub!=null){let i=o.unsub;o.unsub=null;try{i()}catch{}Xt(o)}}throw this._dirtyDepCount=0,n}}_addDep(e){for(let s=0;s<this._deps.length;s++)if(this._deps[s].node===e)return s;let t=this._deps.length,n=rr(e);if(this._deps.push(n),this._sinks==null)return t;n.dirty=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(gt),n.unsub=tr;try{n.unsub=e.subscribe(s=>{if(n.unsub===null)return;let o=this._config.tierOf,i=!1;for(let a of s)o(a[0])>=3&&(i=!0),this._config.onMessage(this,a,{direction:"down-in",depIndex:t},this._actions);i&&this._maybeRunFnOnSettlement()})}catch(s){throw n.unsub=null,this._deps.pop(),this._dirtyDepCount--,s}return t}_deactivate(e=!1){let t=this._cleanup;if(this._cleanup=void 0,typeof t=="function")try{t()}catch(n){this._emit([[D,this._wrapFnError("cleanup threw",n)]])}else if(t!=null&&typeof t=="object"){let n=t.deactivate;if(typeof n=="function")try{n()}catch(s){this._emit([[D,this._wrapFnError("cleanup.deactivate threw",s)]])}}for(let n of this._deps){if(n.unsub!=null){let s=n.unsub;n.unsub=null;try{s()}catch{}}Xt(n)}this._waveHasNewData=!1,this._hasNewTerminal=!1,this._hasCalledFnOnce=!1,this._paused=!1,this._pendingWave=!1,this._pendingRerun=!1,this._rerunDepth=0,this._store={},this._dirtyDepCount=0,this._pauseLocks=null,this._pauseBuffer=null,this._fn!=null&&(this._cached=void 0),e||(this._fn!=null||this._deps.length>0)&&(!this._isTerminal||this._resubscribable)&&(this._status="sentinel")}_onDepMessage(e,t){let n=this._deps[e],s=t[0];if(this._inspectorHooks!=null){let o={kind:"dep_message",depIndex:e,message:t};for(let i of this._inspectorHooks)i(o)}if(s!==ye){if(s===j){this._depDirtied(n);return}if(s===ee){if(this._depInvalidated(n),this._cached===void 0)return;this._emit(jt);return}if(s===Q||s===te){this._emit([t]);return}if(s===F){this._emit(mt);return}if(s===M)this._depSettledAsData(n,t[1]);else if(s===W)this._depSettledAsResolved(n);else if(s===G)this._depSettledAsTerminal(n,!0);else if(s===D)this._depSettledAsTerminal(n,t[1]);else{this._emit([t]);return}if(!this._fn){(s===M||s===W)&&this._emit([t]),(s===G||s===D)&&this._maybeAutoTerminalAfterWave();return}}}_depDirtied(e){e.dirty||(e.dirty=!0,e.involvedThisWave=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(gt))}_depSettledAsData(e,t){e.dirty&&(e.dirty=!1,this._dirtyDepCount--),e.involvedThisWave=!0,e.dataBatch.push(t),this._waveHasNewData=!0}_depSettledAsResolved(e){e.dirty&&(e.dirty=!1,this._dirtyDepCount--)}_depSettledAsTerminal(e,t){e.dirty&&(e.dirty=!1,this._dirtyDepCount--),e.terminal=t,e.involvedThisWave=!0,this._hasNewTerminal=!0}_depInvalidated(e){e.prevData=void 0,e.terminal=void 0,e.dataBatch.length=0,e.dirty?e.involvedThisWave=!1:(e.dirty=!0,e.involvedThisWave=!0,this._dirtyDepCount++)}_maybeRunFnOnSettlement(){if(!(this._isTerminal&&!this._resubscribable)&&!(this._dirtyDepCount>0)){if(!this._partial&&!this._hasCalledFnOnce)for(let e=0;e<this._deps.length;e++){let t=this._deps[e];if(t.dataBatch.length===0&&t.prevData===void 0&&t.terminal===void 0){this._maybeAutoTerminalAfterWave();return}}if(this._paused){this._pendingWave=!0;return}if(!this._waveHasNewData&&!this._hasNewTerminal&&this._hasCalledFnOnce){this._clearWaveFlags(),this._emit(zt),this._maybeAutoTerminalAfterWave();return}this._fn&&this._execFn(),this._maybeAutoTerminalAfterWave()}}_maybeAutoTerminalAfterWave(){if(this._deps.length===0||this._isTerminal)return;let e=this._deps.find(t=>t.terminal!==void 0&&t.terminal!==!0);if(e!=null){this._autoError&&this._emit([[D,e.terminal]]);return}this._autoComplete&&this._deps.every(t=>t.terminal!==void 0)&&this._emit(Bt)}_execFn(){if(!this._fn||this._isTerminal&&!this._resubscribable)return;if(this._isExecutingFn){this._pendingRerun=!0;return}let e=this._cleanup;if(typeof e=="function"){this._cleanup=void 0;try{e()}catch(i){this._emit([[D,this._wrapFnError("cleanup threw",i)]]);return}}else if(e!=null&&typeof e=="object"){let i=e.beforeRun;if(typeof i=="function"){e.beforeRun=void 0;try{i()}catch(a){this._emit([[D,this._wrapFnError("cleanup.beforeRun threw",a)]]);return}}}let t=this._deps.map(i=>i.involvedThisWave?i.dataBatch.length>0?[...i.dataBatch]:[]:void 0),n=this._deps.map(i=>i.prevData);for(let i=0;i<this._deps.length;i++){let a=t[i];a!=null&&a.length>0&&(this._deps[i].prevData=a[a.length-1])}let s=this._deps.map(i=>i.terminal),o={prevData:n,terminalDeps:s,store:this._store};if(this._hasCalledFnOnce=!0,this._clearWaveFlags(),this._inspectorHooks!=null){let i={kind:"run",batchData:t,prevData:n};for(let a of this._inspectorHooks)a(i)}this._isExecutingFn=!0;try{let i=this._fn(t,this._actions,o);if(typeof i=="function")this._cleanup=i;else if(i!=null&&typeof i=="object"){let a=i;(typeof a.beforeRun=="function"||typeof a.deactivate=="function"||typeof a.invalidate=="function")&&(this._cleanup=i)}}catch(i){this._emit([[D,this._wrapFnError("fn threw",i)]])}finally{this._isExecutingFn=!1,this._pendingRerun?(this._pendingRerun=!1,this._rerunDepth+=1,this._rerunDepth>nr?(this._rerunDepth=0,this._emit([[D,new Error(`Node "${this.name}": _pendingRerun depth exceeded ${nr} \u2014 likely a reactive cycle`)]])):this._maybeRunFnOnSettlement()):this._rerunDepth=0,this._clearWaveFlags()}}_clearWaveFlags(){this._waveHasNewData=!1,this._hasNewTerminal=!1;for(let e of this._deps)e.involvedThisWave=!1,e.dataBatch.length=0}_wrapFnError(e,t){let n=t instanceof Error?t.message:String(t);return new Error(`Node "${this.name}": ${e}: ${n}`,{cause:t})}_frameBatch(e){let t=this._config.tierOf;if(e.length===1)return t(e[0][0])===3&&this._status!=="dirty"?[be,e[0]]:e;let n=!0,s=!1,o=!1,i=-1;for(let d of e){let u=t(d[0]);u<i&&(n=!1),u===3&&(s=!0),d[0]===j&&(o=!0),i=u}let a=e;if(!n){let d=e.map((u,c)=>({m:u,i:c,tier:t(u[0])}));d.sort((u,c)=>u.tier-c.tier||u.i-c.i),a=d.map(u=>u.m)}if(s&&!o&&this._status!=="dirty"){let d=0;for(;d<a.length&&t(a[d][0])===0;)d++;return d===0?[be,...a]:[...a.slice(0,d),be,...a.slice(d)]}return a}_emit(e){if(e.length===0)return;for(let a=0;a<e.length;a++){let d=e[a];if(d[0]===D&&d[1]===void 0)throw new TypeError('[ERROR, payload] requires a non-undefined payload (spec \xA71.2). Pass an Error object or domain tag instead \u2014 e.g. node.down([[ERROR, new Error("reason")]])')}let t=e;if(this._isTerminal&&!this._resubscribable){let a=e.filter(d=>d[0]===F||d[0]===ee);if(a.length===0)return;t=a}t=this._frameBatch(t);let s=null;for(let a=0;a<t.length;a++){let d=t[a],u=d[0];if(u!==Q&&u!==te){s?.push(d);continue}if(d.length<2)throw new Error(`Node "${this.name}": [[${u===Q?"PAUSE":"RESUME"}]] must carry a lockId payload \u2014 bare PAUSE/RESUME is a protocol violation (C0 rule). Use \`[[PAUSE, lockId]]\` / \`[[RESUME, lockId]]\`.`);let c=!0;if(this._pausable!==!1){let f=d[1];if(u===Q)this._pauseLocks==null&&(this._pauseLocks=new Set),this._pauseLocks.add(f),this._paused=!0,this._pausable==="resumeAll"&&this._pauseBuffer==null&&(this._pauseBuffer=[]);else if(this._pauseLocks==null||!this._pauseLocks.has(f))c=!1;else if(this._pauseLocks.delete(f),this._pauseLocks.size===0){if(this._paused=!1,this._pauseBuffer!=null&&this._pauseBuffer.length>0){let p=this._pauseBuffer;this._pauseBuffer=[],this._emit(p)}this._pendingWave&&(this._pendingWave=!1,this._maybeRunFnOnSettlement())}}c?s?.push(d):s==null&&(s=t.slice(0,a))}if(s!=null){if(s.length===0)return;t=s}if(this._hasMeta&&t.some(a=>a[0]===F))for(let a of Object.keys(this.meta))try{this.meta[a]._emit(mt)}catch{}let{finalMessages:o,equalsError:i}=this._updateState(t);if(o.length>0&&this._config.inspectorEnabled){let a=this._config.globalInspector;if(a!=null)try{a({kind:"emit",node:this,messages:o})}catch{}}if(o.length>0)if(this._paused&&this._pausable==="resumeAll"&&this._pauseBuffer!=null){let a=this._config.tierOf,d=[];for(let u of o)a(u[0])===3?this._pauseBuffer.push(u):d.push(u);d.length>0&&this._dispatchOrAccumulate(d)}else this._dispatchOrAccumulate(o);i!=null&&this._emit([[D,i]])}_updateState(e){let t=this._config.tierOf,n,s,o=-1,i=0;for(let c of e)t(c[0])===3&&i++;let a=i<=1,d=-1;if(this._versioning!=null&&i>1){for(let c=e.length-1;c>=0;c--)if(e[c][0]===M){d=c;break}}for(let c=0;c<e.length;c++){let f=e[c],p=f[0];if(p===M){if(f.length>=2){let h=!1;if(a&&this._cached!==void 0)try{h=this._equals(this._cached,f[1])}catch(l){s=this._wrapFnError("equals threw",l),o=c;break}if(h){n==null&&(n=e.slice(0,c)),n.push(pt),this._status="resolved";continue}this._cached=f[1],this._versioning!=null&&(d<0||c===d)&&Xn(this._versioning,f[1],this._hashFn)}this._status="settled",n?.push(f)}else if(n?.push(f),p===j)this._status="dirty";else if(p===W)this._status="resolved";else if(p===G){this._status="completed";{let h=this._config.rigorRecorder;if(h!=null)try{h.onTerminalTransition(this,"completed",this._autoComplete,this._autoError,this._deps.length>0)}catch{}}}else if(p===D){this._status="errored";{let h=this._config.rigorRecorder;if(h!=null)try{h.onTerminalTransition(this,"errored",this._autoComplete,this._autoError,this._deps.length>0)}catch{}}}else if(p===ee){if(this._cached!==void 0){let l=this._config.rigorRecorder;if(l!=null)try{l.onNonVacuousInvalidate(this,this._cached)}catch{}}this._cached=void 0,this._status="dirty";let h=this._cleanup;if(typeof h=="function"){this._cleanup=void 0;try{h()}catch{}}else if(h!=null&&typeof h=="object"){let l=h.invalidate;if(typeof l=="function")try{l()}catch{}}}else p===F&&(this._resetOnTeardown&&(this._cached=void 0),this._deactivate(!0),this._status="sentinel")}let u=o>=0?n??e.slice(0,o):n??e;return s!=null?{finalMessages:u,equalsError:s}:{finalMessages:u}}_deliverToSinks=e=>{if(this._sinks==null)return;if(typeof this._sinks=="function"){this._sinks(e);return}let t=[...this._sinks];for(let n of t)n(e)};_dispatchOrAccumulate(e){if(Yn()){this._batchPendingMessages===null&&(this._batchPendingMessages=[],ze(()=>this._flushBatchPending()));for(let t of e)this._batchPendingMessages.push(t);return}bt(this._deliverToSinks,e,this._config.tierOf)}_flushBatchPending(){let e=this._batchPendingMessages;if(e===null||(this._batchPendingMessages=null,e.length===0))return;let t=this._frameBatch(e);bt(this._deliverToSinks,t,this._config.tierOf)}},sr=r=>Array.isArray(r),en=r=>typeof r=="object"&&r!=null&&!Array.isArray(r)});function U(r,e){return ue([],{...e,initial:r})}function ce(r,e){return ue((n,s,o)=>r(s,o)??void 0,{describeKind:"producer",...e})}function Y(r,e,t){return ue(r,(s,o,i)=>{let a=s.map((d,u)=>d!=null&&d.length>0?d.at(-1):i.prevData[u]);o.emit(e(a,i))},{describeKind:"derived",...t})}function tn(r,e,t){return ue(r,(s,o,i)=>{let a=s.map((d,u)=>d!=null&&d.length>0?d.at(-1):i.prevData[u]);return e(a,o,i)??void 0},{describeKind:"effect",...t})}var Be=$(()=>{"use strict";ke()});function nt(r,e,t){let n=new Set;for(let s of r.split(",")){let[o,i]=s.split("/"),a=i?Number.parseInt(i,10):1;if(Number.isNaN(a)||a<1)throw new Error(`Invalid cron step: ${s}`);let d,u;if(o==="*")d=e,u=t;else if(o.includes("-")){let[c,f]=o.split("-");d=Number.parseInt(c,10),u=Number.parseInt(f,10)}else d=Number.parseInt(o,10),u=d;if(Number.isNaN(d)||Number.isNaN(u))throw new Error(`Invalid cron field: ${r}`);if(d<e||u>t)throw new Error(`Cron field out of range: ${r} (${e}-${t})`);if(d>u)throw new Error(`Invalid cron range: ${d}-${u} in ${r}`);for(let c=d;c<=u;c+=a)n.add(c)}return n}function or(r){let e=r.trim().split(/\s+/);if(e.length!==5)throw new Error(`Invalid cron: expected 5 fields, got ${e.length}`);return{minutes:nt(e[0],0,59),hours:nt(e[1],0,23),daysOfMonth:nt(e[2],1,31),months:nt(e[3],1,12),daysOfWeek:nt(e[4],0,6)}}function ir(r,e){return r.minutes.has(e.getMinutes())&&r.hours.has(e.getHours())&&r.daysOfMonth.has(e.getDate())&&r.months.has(e.getMonth()+1)&&r.daysOfWeek.has(e.getDay())}var ar=$(()=>{"use strict"});function rt(r){return{describeKind:"producer",...r}}function dr(r,e){let{signal:t,period:n,...s}=e??{};return ce(o=>{let i=!1,a=0,d,u,c=()=>{i=!0,d!==void 0&&clearTimeout(d),u!==void 0&&clearInterval(u),t?.removeEventListener("abort",p)},f=()=>{i||(n!=null?(o.emit(a++),u=setInterval(()=>{i||o.emit(a++)},n)):(i=!0,t?.removeEventListener("abort",p),o.emit(a++),o.down([[G]])))},p=()=>{i||(c(),o.down([[D,t.reason]]))};if(t?.aborted){p();return}return d=setTimeout(f,r),t?.addEventListener("abort",p,{once:!0}),c},rt(s))}function ur(r,e){let t=or(r),{tickMs:n,output:s,...o}=e??{},i=n??6e4,a=s==="date";return ce(d=>{let u=-1,c=()=>{let p=new Date,h=p.getFullYear()*1e8+(p.getMonth()+1)*1e6+p.getDate()*1e4+p.getHours()*100+p.getMinutes();h!==u&&ir(t,p)&&(u=h,d.emit(a?p:se()))};c();let f=setInterval(c,i);return()=>clearInterval(f)},{...rt(o),name:o.name??`cron:${r}`})}function cr(r,e){return ce(t=>{let n=!1;try{for(let s of r){if(n)return;t.emit(s)}n||t.down([[G]])}catch(s){n||t.down([[D,s]])}return()=>{n=!0}},rt(e))}function ws(r){return r!=null&&typeof r.then=="function"}function Ts(r,e){let{signal:t,...n}=e??{};return ce(s=>{let o=!1,i=()=>{o||(o=!0,s.down([[D,t.reason]]))};if(t?.aborted){i();return}return t?.addEventListener("abort",i,{once:!0}),Promise.resolve(r).then(a=>{o||(o=!0,t?.removeEventListener("abort",i),s.emit(a),s.down([[G]]))},a=>{o||(o=!0,t?.removeEventListener("abort",i),s.down([[D,a]]))}),()=>{o=!0,t?.removeEventListener("abort",i)}},rt(n))}function Es(r,e){let{signal:t,...n}=e??{};return ce(s=>{let o=new AbortController,i=()=>o.abort(t?.reason);t?.aborted?o.abort(t.reason):t?.addEventListener("abort",i,{once:!0});let a=t??o.signal,d=!1,u=r[Symbol.asyncIterator](),c=()=>{d||a.aborted||Promise.resolve(u.next()).then(f=>{if(!(d||a.aborted)){if(f.done){s.down([[G]]);return}s.emit(f.value),c()}},f=>{!d&&!a.aborted&&s.down([[D,f]])})};return c(),()=>{d=!0,t?.removeEventListener("abort",i),o.abort(),Promise.resolve(u.return?.()).catch(()=>{})}},rt(n))}function Os(r){return r!=null&&typeof r=="object"&&"cache"in r&&typeof r.subscribe=="function"}function lr(r,e){if(Os(r))return r;if(ws(r))return Ts(r,e);if(r!=null){let t=r;if(typeof t[Symbol.asyncIterator]=="function")return Es(r,e);if(typeof t[Symbol.iterator]=="function")return cr(r,e)}return xs(r)}function xs(...r){return cr(r,void 0)}function fe(r){return r.subscribe(()=>{})}var fr=$(()=>{"use strict";_e();ne();Be();ar()});var wt=$(()=>{"use strict";fr()});function xt(r,e){if(e!=null&&e.length>0)return new Set(e);switch(r){case"standard":return new Set(["type","status","value","deps","meta","v"]);case"full":return null;case"spec":return new Set(["type","deps","meta","value"]);default:return new Set(["type","deps"])}}function As(r){return r._describeKind!=null?r._describeKind:r._deps.length>0?"derived":r._fn!=null?"producer":"state"}function an(r){let e=new WeakSet,t={};for(let[n,s]of vr(r))t[n]=on(s,e);return t}function on(r,e){if(r==null)return r;let t=typeof r;if(t==="boolean"||t==="number"||t==="string")return r;if(t==="function")return"<function>";if(Array.isArray(r))return e.has(r)?"<cycle>":(e.add(r),r.map(n=>on(n,e)));if(t==="object"){let n=r;if(e.has(n))return"<cycle>";e.add(n);try{if(typeof n.subscribe=="function"&&"cache"in n)return"<Node>"}catch{return"<unserializable>"}let s={};for(let[o,i]of vr(n))s[o]=on(i,e);return s}return"<unserializable>"}function vr(r){let e=[],t;try{t=Object.keys(r)}catch{return e}for(let n of t)try{e.push([n,r[n]])}catch{e.push([n,"<unserializable>"])}return e}function Cs(r){let e={};for(let[t,n]of Object.entries(r.meta))try{e[t]=n.cache}catch{}return e}function dn(r,e,t){let n=e==null,s=!n&&e!=null?[...e].filter(c=>c.startsWith("meta.")).map(c=>c.slice(5)):null,o=n||e.has("meta")||s!=null&&s.length>0,i="state",a=[];r instanceof q&&(i=As(r),a=r._deps.map(c=>c.node.name??""));let d={type:i,deps:a};(n||e.has("status"))&&(d.status=r.status);let u=r instanceof q?r._guard:void 0;if(o){let c={...Cs(r)};if(u!=null&&c.access===void 0&&(c.access=Yt(u)),s!=null&&s.length>0&&!e.has("meta")){let f={};for(let p of s)p in c&&(f[p]=c[p]);d.meta=f}else d.meta=c}if(r.name!=null&&(d.name=r.name),(n||e.has("value"))&&(!t||i==="state")){r.status==="sentinel"&&(d.sentinel=!0);try{d.value=r.cache}catch{}}if((n||e.has("v"))&&r.v!=null){let c={id:r.v.id,version:r.v.version};"cid"in r.v&&(c.cid=r.v.cid,c.prev=r.v.prev),d.v=c}return(n||e.has("guard"))&&u!=null&&(d.guard=Yt(u)),(n||e.has("lastMutation"))&&r.lastMutation!=null&&(d.lastMutation=r.lastMutation),d}var un=$(()=>{"use strict";xe();ke()});function cn(r,e){if(Object.is(r,e))return!0;if(r==null||e==null||typeof r!="object"||typeof e!="object")return!1;if(Array.isArray(r)){if(!Array.isArray(e)||r.length!==e.length)return!1;for(let o=0;o<r.length;o++)if(!cn(r[o],e[o]))return!1;return!0}if(Array.isArray(e))return!1;let t=Object.keys(r),n=Object.keys(e);if(t.length!==n.length)return!1;let s=new Set(n);for(let o of t)if(!s.has(o)||!cn(r[o],e[o]))return!1;return!0}function _r(r,e){return`${r}\0${e}`}function ln(r,e){let t=[],n=new Set(r.subgraphs),s=new Set(e.subgraphs),o=[];for(let g of s)n.has(g)||o.push(g);o.sort();for(let g of o)t.push({type:"subgraph-mounted",path:g});let i=new Set(Object.keys(r.nodes)),a=new Set(Object.keys(e.nodes)),d=[];for(let g of a)i.has(g)||d.push(g);d.sort();for(let g of d)t.push({type:"node-added",path:g,node:{...e.nodes[g]}});let u=[];for(let g of a){if(!i.has(g))continue;let E=r.nodes[g]?.meta,v=e.nodes[g]?.meta;E==null&&v==null||cn(E??{},v??{})||u.push(g)}u.sort();for(let g of u)t.push({type:"node-meta-changed",path:g,prevMeta:r.nodes[g]?.meta??{},nextMeta:e.nodes[g]?.meta??{}});let c=new Map;for(let g of r.edges)c.set(_r(g.from,g.to),g);let f=new Map;for(let g of e.edges)f.set(_r(g.from,g.to),g);let p=[];for(let[g,E]of f)c.has(g)||p.push(E);p.sort((g,E)=>g.from<E.from?-1:g.from>E.from?1:g.to<E.to?-1:g.to>E.to?1:0);for(let g of p)t.push({type:"edge-added",from:g.from,to:g.to});let h=[];for(let[g,E]of c)f.has(g)||h.push(E);h.sort((g,E)=>g.from<E.from?-1:g.from>E.from?1:g.to<E.to?-1:g.to>E.to?1:0);for(let g of h)t.push({type:"edge-removed",from:g.from,to:g.to});let l=[];for(let g of i)a.has(g)||l.push(g);l.sort();for(let g of l)t.push({type:"node-removed",path:g});let m=[];for(let g of n)s.has(g)||m.push(g);m.sort();for(let g of m)t.push({type:"subgraph-unmounted",path:g});return{events:t,flushedAt_ns:le()}}var wr=$(()=>{"use strict";_e()});var Nt,Tr=$(()=>{"use strict";Nt=class{_timer;_gen=0;start(e,t){this.cancel(),this._gen+=1;let n=this._gen;this._timer=setTimeout(()=>{this._timer=void 0,n===this._gen&&t()},e)}cancel(){this._timer!==void 0&&(clearTimeout(this._timer),this._timer=void 0)}get pending(){return this._timer!==void 0}}});var ot,Er=$(()=>{"use strict";ot=class{constructor(e){this.capacity=e;if(!Number.isInteger(e)||e<=0)throw new Error(`RingBuffer capacity must be a positive integer (got ${e})`);this.buf=new Array(e)}buf;head=0;_size=0;get size(){return this._size}get maxSize(){return this.capacity}push(e){let t=(this.head+this._size)%this.capacity;this.buf[t]=e,this._size<this.capacity?this._size++:this.head=(this.head+1)%this.capacity}shift(){if(this._size===0)return;let e=this.buf[this.head];return this.buf[this.head]=void 0,this.head=(this.head+1)%this.capacity,this._size--,e}at(e){if(this._size===0)return;let t=e<0?this._size+e:e;if(!(t<0||t>=this._size))return this.buf[(this.head+t)%this.capacity]}toArray(){let e=new Array(this._size);for(let t=0;t<this._size;t++)e[t]=this.buf[(this.head+t)%this.capacity];return e}clear(){for(let e=0;e<this._size;e++)this.buf[(this.head+e)%this.capacity]=void 0;this.head=0,this._size=0}}});function Or(r,e,t,n={}){let s=e in r.nodes,o=t in r.nodes;if(!s)return kt(e,t,"no-such-from");if(!o)return kt(e,t,"no-such-to");let i=n.maxDepth;if(i!=null&&(!Number.isInteger(i)||i<0))throw new Error("explainPath: maxDepth must be an integer >= 0");if(e===t){if(n.findCycle===!0){let u=Ms(r,e,n);if(u!=null)return u}let d=Rt(e,r.nodes[e],0,n);return St(e,t,[d])}if(i===0)return kt(e,t,"no-path");let a=xr(r,e,t,i);return a.found?St(e,t,Nr(r,a.pathOrder,n)):kt(e,t,a.truncated?"max-depth-exceeded":"no-path")}function xr(r,e,t,n){let s=new Map,o=[{path:t,depth:0}],i=new Set([t]),a=0,d=!1;for(;a<o.length;){let f=o[a++];if(f.path===e)break;if(n!=null&&f.depth>=n){let m=r.nodes[f.path];m?.deps&&m.deps.length>0&&(d=!0);continue}let p=r.nodes[f.path];if(p==null)continue;let h=p.deps??[],l=new Map;for(let m=0;m<h.length;m++){let g=h[m];if(!g)continue;let E=l.get(g);E==null&&(E=[],l.set(g,E)),E.push(m)}for(let[m,g]of l)i.has(m)||(i.add(m),s.set(m,{from:f.path,depIndices:g}),o.push({path:m,depth:f.depth+1}))}if(!s.has(e))return{found:!1,pathOrder:[],truncated:d};let u=[{path:e}],c=e;for(;c!==t;){let f=s.get(c);if(f==null)return{found:!1,pathOrder:[],truncated:!1};u[u.length-1].depIndices=f.depIndices,u.push({path:f.from}),c=f.from}return{found:!0,pathOrder:u,truncated:!1}}function Ms(r,e,t){let n=r.nodes[e];if(n==null)return null;let s=n.deps??[],o=[];for(let a=0;a<s.length;a++)s[a]===e&&o.push(a);if(o.length>0){let a=Rt(e,n,0,t);a.dep_index=o[0];let d=Rt(e,n,1,t);return St(e,e,[a,d])}let i=null;for(let a=0;a<s.length;a++){let d=s[a];if(!d||d===e)continue;let u=xr(r,d,e,t.maxDepth);u.found&&(i==null||u.pathOrder.length<i.pathOrder.length)&&(i=u,i={found:!0,pathOrder:[{path:e,depIndices:[a]},...u.pathOrder],truncated:!1})}return i==null?null:St(e,e,Nr(r,i.pathOrder,t))}function Nr(r,e,t){return e.map((n,s)=>{let o=r.nodes[n.path],i=Rt(n.path,o,s,t);return n.depIndices!=null&&n.depIndices.length>0&&(i.dep_index=n.depIndices[0],n.depIndices.length>1&&(i.dep_indices=[...n.depIndices])),i})}function Rt(r,e,t,n){let s={path:r,type:e.type,hop:t};e.status!==void 0&&(s.status=e.status),"value"in e&&(s.value=e.value),e.v!=null&&(s.v=e.v);let o=n.annotations?.get(r)??e.annotation;o!=null&&(s.annotation=o);let i=n.lastMutations?.get(r)??e.lastMutation;return i!=null&&(s.lastMutation=i),s}function St(r,e,t){return kr(r,e,!0,"ok",t)}function kt(r,e,t){return kr(r,e,!1,t,[])}function kr(r,e,t,n,s){let o=Ds(r,e,t,n,s);return{from:r,to:e,found:t,reason:n,steps:s,text:o,toJSON(){return{from:r,to:e,found:t,reason:n,steps:s}}}}function Ds(r,e,t,n,s){if(!t)switch(n){case"no-such-from":return`explainPath: no node named "${r}"`;case"no-such-to":return`explainPath: no node named "${e}"`;case"max-depth-exceeded":return`explainPath: no path from "${r}" to "${e}" within maxDepth`;default:return`explainPath: no path from "${r}" to "${e}"`}let o=[`Causal path: ${r} \u2192 ${e} (${s.length} step(s))`];for(let i of s){let d=` ${i.hop===0?"\xB7":"\u2193"} ${i.path} (${i.type}${i.status?`/${i.status}`:""})`;if(o.push(d),"value"in i&&o.push(` value: ${Gs(i.value)}`),i.annotation!=null&&o.push(` annotation: ${i.annotation}`),i.lastMutation!=null){let u=i.lastMutation.actor;o.push(` actor: ${u.type}${u.id?`:${u.id}`:""}`)}}return o.join(`
2
- `)}function Gs(r){if(r===void 0)return"<sentinel>";if(r===null)return"null";if(typeof r=="string")return JSON.stringify(r);if(typeof r=="number"||typeof r=="boolean"||typeof r=="bigint")return String(r);try{let e=JSON.stringify(r);return e.length>80?`${e.slice(0,77)}...`:e}catch{return String(r)}}var Rr=$(()=>{"use strict"});function Sr(r){let e=new WeakSet,t=new WeakSet,n=[r],s=0;for(;n.length>0;){let o=n.pop();s+=Ps(o,e,t,n)}return s}function Ps(r,e,t,n){if(r==null)return 0;switch(typeof r){case"number":return V.number;case"boolean":return V.boolean;case"string":return V.string+r.length*2;case"bigint":return V.bigint+Ls(r);case"symbol":return V.symbol;case"function":return e.has(r)?0:(e.add(r),V.function);case"undefined":return 0}let o=r;if(e.has(o))return 0;e.add(o);let i=o[Is];if(typeof i=="function")try{let u=i.call(o);if(typeof u=="number"&&Number.isFinite(u))return u}catch{}if(o instanceof Date)return V.date;if(o instanceof RegExp)return V.regexp+o.source.length*2;if(o instanceof Error){let u=o.message?o.message.length*2:0,c=o.stack?o.stack.length*2:0;return V.error+u+c}if(typeof URL<"u"&&o instanceof URL)return V.url+o.href.length*2;if(typeof Promise<"u"&&o instanceof Promise)return V.promise;if(o instanceof WeakMap)return V.weakmap;if(o instanceof WeakSet)return V.weakset;if(o instanceof Map){let u=V.map;for(let[c,f]of o)u+=V.mapEntry,n.push(c),n.push(f);return u}if(o instanceof Set){let u=V.set;for(let c of o)u+=V.setEntry,n.push(c);return u}if(Array.isArray(o)){let u=V.array+o.length*8;for(let c of o)n.push(c);return u}if(o instanceof ArrayBuffer)return t.has(o)?0:(t.add(o),o.byteLength);if(ArrayBuffer.isView(o)){let u=o;return t.has(u.buffer)?48:(t.add(u.buffer),u.buffer.byteLength+48)}let a=V.object,d=Object.keys(o);for(let u of d){a+=V.string+u.length*2;try{n.push(o[u])}catch{}}return a}function Ls(r){let e=r<0n?-r:r;if(e===0n)return 0;let t=e.toString(2).length;return Math.ceil(t/32)*8}var V,Is,Ar=$(()=>{"use strict";V={object:56,array:64,string:40,number:8,boolean:4,null:0,undefined:0,symbol:40,bigint:16,function:120,map:72,set:72,mapEntry:40,setEntry:24,date:24,regexp:48,error:64,url:80,promise:48,weakmap:40,weakset:40},Is=Symbol.for("sizeof")});function Cr(r,e){let t=e?.topN??10,n=r.describe({detail:"standard"}),s=[],o=r._collectObserveTargets;typeof o=="function"&&o.call(r,"",s);let i=new Map;for(let[p,h]of s)i.set(p,h);let a=[];for(let[p,h]of Object.entries(n.nodes)){let l=i.get(p),m=l instanceof q?l:null,g=m?Sr(m.cache):0,E=m?m._sinkCount:0,v=h.deps?.length??0,_=h.type==="effect"&&E===0,b=E===0?h.type==="effect"?"orphan-effect":h.type==="derived"?"idle-derived":h.type==="producer"?"idle-producer":null:null;a.push({path:p,type:h.type,status:h.status??"unknown",valueSizeBytes:g,subscriberCount:E,depCount:v,isOrphanEffect:_,orphanKind:b})}let d=a.reduce((p,h)=>p+h.valueSizeBytes,0),u=(p,h)=>[...a].sort(h??((l,m)=>m[p]-l[p])).slice(0,t),c=a.filter(p=>p.orphanKind!=null),f=a.filter(p=>p.isOrphanEffect);return{nodeCount:a.length,edgeCount:n.edges.length,subgraphCount:n.subgraphs.length,nodes:a,totalValueSizeBytes:d,hotspots:{byValueSize:u("valueSizeBytes"),bySubscriberCount:u("subscriberCount"),byDepCount:u("depCount")},orphans:c,orphanEffects:f}}var Mr=$(()=>{"use strict";ke();Ar()});function At(r,e){let t=Math.max(16,r.size*4),n=0;for(;r.size>0;){if(n++>=t){console.error(`[Graph "${e}".destroy] disposer drain exceeded cap (${t}); ${r.size} disposer(s) discarded`),r.clear();return}let s=r.values().next();if(s.done)return;let o=s.value;r.delete(o);try{o()}catch(i){console.error(`[Graph "${e}".destroy] disposer threw:`,i)}}}function Lr(r){return r!=null&&typeof r=="object"&&"cache"in r&&typeof r.subscribe=="function"&&typeof r.down=="function"}function $s(r){if(r!=null)return Lr(r)?r.cache:r}function Ae(r){return r!=null&&typeof r=="object"&&"cache"in r&&typeof r.subscribe=="function"&&typeof r.down=="function"}function he(r){return Ae(r)?r.cache??"":r}function Dr(r){return Ae(r)?r.cache??0:r}function Gr(r){return Ae(r)?r.cache??!1:r}function Fs(r){let e=[];for(let t of Object.keys(r).sort()){let n=r[t].v;n!=null&&e.push(`${t} ${n.id} ${n.version}`)}return e.join(`
3
- `)}function Ir(r){if(r.version!==Se)throw new Error(`unsupported snapshot version ${String(r.version)} (expected ${Se})`);for(let e of["name","nodes","edges","subgraphs"])if(!(e in r))throw new Error(`snapshot missing required key "${e}"`);if(typeof r.name!="string")throw new TypeError("snapshot 'name' must be a string");if(typeof r.nodes!="object"||r.nodes===null||Array.isArray(r.nodes))throw new TypeError("snapshot 'nodes' must be an object");if(!Array.isArray(r.edges))throw new TypeError("snapshot 'edges' must be an array");if(!Array.isArray(r.subgraphs))throw new TypeError("snapshot 'subgraphs' must be an array")}function Hs(r,e){let t=new WeakMap,n=(s,o)=>{if(Object.is(s,o))return!0;if(s==null||o==null||typeof s!="object"||typeof o!="object")return!1;let i=t.get(s);if(i==null&&(i=new WeakSet,t.set(s,i)),i.has(o))return!0;i.add(o);let a=s.constructor,d=o.constructor;if(a!==d)return!1;if(s instanceof Date)return s.getTime()===o.getTime();if(s instanceof RegExp)return s.source===o.source&&s.flags===o.flags;if(Array.isArray(s)){let p=o;if(s.length!==p.length)return!1;for(let h=0;h<s.length;h++)if(!n(s[h],p[h]))return!1;return!0}if(s instanceof Map){let p=o;if(s.size!==p.size)return!1;for(let[h,l]of s)if(!p.has(h)||!n(l,p.get(h)))return!1;return!0}if(s instanceof Set){let p=o;if(s.size!==p.size)return!1;for(let h of s){let l=!1;for(let m of p)if(n(h,m)){l=!0;break}if(!l)return!1}return!0}if(ArrayBuffer.isView(s)){let p=s,h=o;if(p.length!==h.length)return!1;for(let l=0;l<p.length;l++)if(p[l]!==h[l])return!1;return!0}let u=Object.keys(s),c=Object.keys(o);if(u.length!==c.length)return!1;let f=new Set(c);for(let p of u)if(!f.has(p)||!n(s[p],o[p]))return!1;return!0};return n(r,e)}function qs(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ct(r){let e="^";for(let t=0;t<r.length;t+=1){let n=r[t];if(n==="*"){e+=".*";continue}if(n==="?"){e+=".";continue}if(n==="["){let s=r.indexOf("]",t+1);if(s<=t+1){e+="\\[";continue}let o=r.slice(t+1,s);o.startsWith("!")&&(o=`^${o.slice(1)}`),o=o.replace(/\\/g,"\\\\"),e+=`[${o}]`,t=s;continue}e+=qs(n)}return e+="$",new RegExp(e)}function fn(r){if(typeof r=="string")return JSON.stringify(r);if(typeof r=="number"||typeof r=="boolean"||r==null)return String(r);try{return JSON.stringify(r)}catch{return"[unserializable]"}}function js(r){return r==="none"?zs:r==="ansi"||r==null?Vs:{data:r.data??"",dirty:r.dirty??"",resolved:r.resolved??"",invalidate:r.invalidate??"",pause:r.pause??"",resume:r.resume??"",complete:r.complete??"",error:r.error??"",teardown:r.teardown??"",derived:r.derived??"",path:r.path??"",reset:r.reset??""}}function Pr(r){if(r==null)return{};let e=r.detail;return e==="full"?{...r,structured:r.structured??!0,timeline:r.timeline??!0,causal:r.causal??!0,derived:r.derived??!0}:e==="minimal"?{...r,structured:r.structured??!0}:r.format==="stage-log"?{...r,structured:r.structured??!0,timeline:r.timeline??!0}:r}function Bs(r,e,t){for(let n=0;n<r.length;n++){let s=r.charCodeAt(n);if(s<32||s===127)throw new Error(`Graph "${e}": ${t} "${r}" must not contain control character (U+${s.toString(16).padStart(4,"0").toUpperCase()} at index ${n})`)}}function pn(r,e,t){if(r==="")throw new Error(`Graph "${e}": ${t} name must be non-empty`);if(r.includes(L))throw new Error(`Graph "${e}": ${t} "${r}" must not contain '${L}' (path separator)`);if(r===ie)throw new Error(`Graph "${e}": ${t} name "${ie}" is reserved for meta companion paths`);Bs(r,e,t)}function Ws(r,e){if(r==="")throw new Error(`Graph "${e}": resolve path must be non-empty`);let t=r.split(L);for(let n of t)if(n==="")throw new Error(`Graph "${e}": resolve path has empty segment`);return t}function Ks(r,e){let t=!1;for(let s of r)if(!e.isMetaPassthrough(s[0])){t=!0;break}return t?r.filter(s=>e.isMetaPassthrough(s[0])):r}function $r(r){for(let e of r._mounts.values())$r(e);for(let e of r._nodes.values())try{e.down([[F]],{internal:!0})}catch{}}function Fr(r,e){let t=ae.diff(r,e),n={};for(let s of t.nodesAdded){let o=e.nodes[s];o!=null&&(n[s]=o)}return{...t,nodesAddedFull:n}}function hn(r,e,t,n={}){let s={paths:[],depths:new Map,truncated:!1};if(!e)return n.withDetail?s:[];if(!n.both&&t!=="upstream"&&t!=="downstream")throw new Error('reachable: direction must be "upstream" or "downstream"');let o=n.maxDepth;if(o!=null&&(!Number.isInteger(o)||o<0))throw new Error("reachable: maxDepth must be an integer >= 0");if(o===0)return n.withDetail?s:[];let i=new Map,a=new Map,d=new Map,u=new Map,c=new Set;for(let[_,b]of Object.entries(r.nodes)){if(!_)continue;c.add(_);let w=b.deps??[];i.set(_,w);for(let N of w)N&&(c.add(N),a.has(N)||a.set(N,new Set),a.get(N).add(_))}for(let _ of r.edges){if(_==null||typeof _!="object")continue;let b=typeof _.from=="string"?_.from:"",w=typeof _.to=="string"?_.to:"";!b||!w||(c.add(b),c.add(w),u.has(b)||u.set(b,new Set),u.get(b).add(w),d.has(w)||d.set(w,new Set),d.get(w).add(b))}if(!c.has(e))return n.withDetail?s:[];let f=n.both===!0,p=_=>{if(f){let y=i.get(_)??[],O=d.get(_),k=a.get(_),x=u.get(_),T=[...y];return O&&T.push(...O),k&&T.push(...k),x&&T.push(...x),T}if(t==="upstream"){let y=i.get(_)??[],O=d.get(_);return O?[...y,...O]:y}let b=a.get(_),w=u.get(_),N=b?[...b]:[];return w&&N.push(...w),N},h=new Set([e]),l=new Map,m=[{path:e,depth:0}],g=0,E=!1;for(;g<m.length;){let _=m[g++];if(o!=null&&_.depth>=o){p(_.path).length>0&&(E=!0);continue}for(let b of p(_.path))!b||h.has(b)||(h.add(b),l.set(b,_.depth+1),m.push({path:b,depth:_.depth+1}))}let v=[...l.keys()].sort((_,b)=>_<b?-1:_>b?1:0);return n.withDetail?{paths:v,depths:l,truncated:E}:v}function Us(r,e){if(r.length!==e.length)return!1;for(let t=0;t<r.length;t++){let n=r[t],s=e[t];if(n.path!==s.path||n.type!==s.type||n.status!==s.status||n.hop!==s.hop||n.dep_index!==s.dep_index||n.annotation!==s.annotation||n.value!==s.value||n.lastMutation!==s.lastMutation)return!1;let o=n.v,i=s.v;if(o!==i&&(o==null||i==null||o.id!==i.id||o.version!==i.version))return!1}return!0}var L,ie,Se,Vs,zs,ae,Mt=$(()=>{"use strict";Ze();tt();_e();xe();ne();un();ke();Be();wr();wt();Tr();Er();Ut();Rr();Mr();L="::",ie="__meta__",Se=1;Vs={data:"\x1B[32m",dirty:"\x1B[33m",resolved:"\x1B[36m",invalidate:"\x1B[93m",pause:"\x1B[90m",resume:"\x1B[96m",complete:"\x1B[34m",error:"\x1B[31m",teardown:"\x1B[91m",derived:"\x1B[35m",path:"\x1B[90m",reset:"\x1B[0m"},zs={data:"",dirty:"",resolved:"",invalidate:"",pause:"",resume:"",complete:"",error:"",teardown:"",derived:"",path:"",reset:""};ae=class r{name;opts;config;_nodes=new Map;_nodeToName=new WeakMap;_mounts=new Map;_parent=void 0;_storageDisposers=new Set;_disposers=new Set;_destroyed=!1;_topology;_topologyEmitters=new Set;_factory;_factoryArgs;constructor(e,t){if(e==="")throw new Error("Graph name must be non-empty");if(e.includes(L))throw new Error(`Graph name must not contain '${L}' (got "${e}")`);if(e===ie)throw new Error(`Graph name "${ie}" is reserved for meta companion paths`);this.name=e,this.opts=Object.freeze({...t??{}}),this.config=t?.config??Ne,this._traceRing=new ot(t?.traceCapacity??1e3),t?.versioning!=null&&this.setVersioning(t.versioning),typeof t?.factory=="string"&&(this._factory=t.factory,t.factoryArgs!==void 0&&(this._factoryArgs=t.factoryArgs))}tagFactory(e,t){return this._factory=e,this._factoryArgs=t,this}ancestors(e=!0){let t=[],n=e?this:this._parent;for(;n!=null;)t.push(n),n=n._parent;return t}get topology(){return this._topology==null&&(this._topology=ce(e=>{let t=n=>{e.emit(n)};return this._topologyEmitters.add(t),()=>{this._topologyEmitters.delete(t)}},{name:`${this.name}_topology`})),this._topology}_emitTopology(e){if(!(this._topology==null||this._topologyEmitters.size===0))for(let t of this._topologyEmitters)t(e)}nameOf(e){return this._nodeToName.get(e)}add(e,t){let n=e.name,s=t?.name??n;if(s==null||s==="")throw new Error(`Graph "${this.name}": graph.add requires a non-empty name \u2014 pass via opts.name or set it on the node (e.g. state(0, { name: "x" }))`);let o=s,i=t?.annotation;if(pn(o,this.name,"add"),this._mounts.has(o))throw new Error(`Graph "${this.name}": name "${o}" is already a mount point`);if(this._nodes.has(o))throw new Error(`Graph "${this.name}": node "${o}" already exists`);let a=this._nodeToName.get(e);if(a!==void 0)throw new Error(`Graph "${this.name}": node instance already registered as "${a}"`);return this._nodes.set(o,e),this._nodeToName.set(e,o),this._emitTopology({kind:"added",name:o,nodeKind:"node"}),i!=null&&(this._annotations.set(o,i),this.config.inspectorEnabled&&this._traceRing.push({path:o,annotation:i,timestamp_ns:le()})),e}setVersioning(e){if(e!=null)for(let t of this._nodes.values())t instanceof q&&t._applyVersioning(e)}remove(e){pn(e,this.name,"remove");let t=this._mounts.get(e);if(t){let o={kind:"mount",nodes:[],mounts:[]},i=[];t._collectObserveTargets("",i);for(let[a,d]of i)a.includes(`${L}${ie}${L}`)||o.nodes.push(a);return o.nodes.sort(),o.mounts.push(e),o.mounts.push(...t._collectSubgraphs(`${e}${L}`)),this._mounts.delete(e),t._parent=void 0,$r(t),this._emitTopology({kind:"removed",name:e,nodeKind:"mount",audit:o}),o}let n=this._nodes.get(e);if(!n)throw new Error(`Graph "${this.name}": unknown node or mount "${e}"`);this._nodes.delete(e),this._nodeToName.delete(n),n.down([[F]],{internal:!0});let s={kind:"node",nodes:[e],mounts:[]};return this._emitTopology({kind:"removed",name:e,nodeKind:"node",audit:s}),s}removeAll(e){let t=typeof e=="function"?e:(()=>{let o=Ct(e);return i=>o.test(i)})(),n={kind:"mount",nodes:[],mounts:[]},s=[...this._nodes.keys(),...this._mounts.keys()].filter(o=>t(o));for(let o of s){let i=this.remove(o);n.nodes.push(...i.nodes),n.mounts.push(...i.mounts)}return n.nodes.sort(),n.mounts.sort(),n}[Symbol.iterator](){let e=[...this._nodes.keys()].sort(),t=this._nodes,n=0;return{[Symbol.iterator](){return this},next(){if(n>=e.length)return{value:void 0,done:!0};let s=e[n++];return{value:[s,t.get(s)],done:!1}}}}node(e){if(e==="")throw new Error(`Graph "${this.name}": node name must be non-empty`);if(e.includes(L))return this.resolve(e);let t=this._nodes.get(e);if(!t)throw new Error(`Graph "${this.name}": unknown node "${e}"`);return t}get(e){return this.node(e).cache}set(e,t,n){let s=n?.internal===!0;this.node(e).down([[M,t]],{actor:n?.actor,internal:s,delivery:"write"})}setAll(e,t){let n=Symbol.iterator in e?e:Object.entries(e);Oe(()=>{for(let[s,o]of n)this.set(s,o,t)})}invalidate(e,t){let n=t?.internal===!0;this.node(e).down([[ee]],{actor:t?.actor,internal:n,delivery:"write"})}error(e,t,n){let s=n?.internal===!0;this.node(e).down([[D,t]],{actor:n?.actor,internal:s,delivery:"write"})}complete(e,t){let n=t?.internal===!0;this.node(e).down([[G]],{actor:t?.actor,internal:n,delivery:"write"})}_registerSelfPruningKeepalive(e){let t,n,s=()=>{t?.(),t=void 0,n?.(),n=void 0};t=e.subscribe(o=>{for(let i of o){let a=i[0];if(a===F||a===G||a===D){s();return}}}),n=this.addDisposer(s)}_wireSignalToRemove(e,t){if(t==null)return;let n=()=>{try{this.remove(e)}catch{}};if(t.aborted){n();return}t.addEventListener("abort",n,{once:!0}),this.addDisposer(()=>t.removeEventListener("abort",n))}derived(e,t,n,s){let o=t.map(h=>this.resolve(h)),{keepAlive:i,annotation:a,equals:d,initial:u,meta:c,signal:f}=s??{},p=Y(o,n,{name:e,...d!=null?{equals:d}:{},...u!==void 0?{initial:u}:{},...c!=null?{meta:c}:{}});return this.add(p,{name:e,...a!=null?{annotation:a}:{}}),i===!0&&this._registerSelfPruningKeepalive(p),this._wireSignalToRemove(e,f),p}effect(e,t,n,s){let o=t.map(c=>this.resolve(c)),{annotation:i,meta:a,signal:d}=s??{},u=tn(o,n,{name:e,...a!=null?{meta:a}:{}});return this.add(u,{name:e,...i!=null?{annotation:i}:{}}),this._wireSignalToRemove(e,d),u}produce(e,t,n){if(t===void 0)throw new Error(`Graph "${this.name}".produce("${e}", \u2026): source must not be \`undefined\` \u2014 undefined is the global SENTINEL (spec \xA71.1). Pass \`null\` for nullary DATA, or a Promise/AsyncIterable/Iterable for async sources.`);if(t!==null&&typeof t=="object"&&"cache"in t&&typeof t.subscribe=="function")throw new Error(`Graph "${this.name}".produce("${e}", \u2026): Node sources are rejected. For Node\u2192Node, use graph.derived(name, [path], ([v]) => v, { keepAlive: true }) \u2014 fromAny passes Nodes through verbatim and silently drops opts.`);let{annotation:s,meta:o,equals:i,signal:a}=n??{},d=lr(t,{name:e,...o!=null?{meta:o}:{},...i!=null?{equals:i}:{},...a!=null?{signal:a}:{}});return this.add(d,{name:e,...s!=null?{annotation:s}:{}}),this._wireSignalToRemove(e,a),d}batch(e){Oe(e)}edges(e){let t=e?.recursive===!0,n=new Map;if(!t){for(let[d,u]of this._nodes)n.set(u,d);let a=[];for(let[d,u]of this._nodes)if(u instanceof q)for(let c of u._deps){let f=n.get(c.node);f!=null&&a.push([f,d])}return a.sort((d,u)=>d[0]<u[0]?-1:d[0]>u[0]?1:d[1]<u[1]?-1:d[1]>u[1]?1:0),a}let s=[];this._collectObserveTargets("",s);let o=new Map;for(let[a,d]of s)o.set(d,a);let i=[];for(let[a,d]of s)if(d instanceof q)for(let u of d._deps){let c=o.get(u.node);c!=null&&i.push([c,a])}return i.sort((a,d)=>a[0]<d[0]?-1:a[0]>d[0]?1:a[1]<d[1]?-1:a[1]>d[1]?1:0),i}mount(e,t){if(t===void 0){let s=new r(e);return this.mount(e,s)}if(typeof t=="function"){let s=new r(e);return t(s),this.mount(e,s)}let n=t;if(pn(e,this.name,"mount"),this._nodes.has(e))throw new Error(`Graph "${this.name}": cannot mount at "${e}" \u2014 node with that name exists`);if(this._mounts.has(e))throw new Error(`Graph "${this.name}": mount "${e}" already exists`);if(n===this)throw new Error(`Graph "${this.name}": cannot mount a graph into itself`);if(n._parent!=null)throw new Error(`Graph "${this.name}": this child graph is already mounted on "${n._parent.name}"`);for(let s=this;s!=null;s=s._parent)if(s===n)throw new Error(`Graph "${this.name}": mount("${e}", \u2026) would create a mount cycle`);return this._mounts.set(e,n),n._parent=this,this._emitTopology({kind:"added",name:e,nodeKind:"mount"}),n}resolve(e){let t=Ws(e,this.name);return this._resolveFromSegments(t)}tryResolve(e){try{return this.resolve(e)}catch{return}}_resolveFromSegments(e){let t=e;if(t[0]===this.name&&(t=t.slice(1),t.length===0))throw new Error(`Graph "${this.name}": resolve path ends at graph name only`);let n=t[0],s=t.slice(1);if(s.length===0){let a=this._nodes.get(n);if(a)return a;throw this._mounts.has(n)?new Error(`Graph "${this.name}": path ends at subgraph "${n}" \u2014 not a node (GRAPHREFLY-SPEC \xA73.5)`):new Error(`Graph "${this.name}": unknown name "${n}"`)}let o=this._nodes.get(n);if(o&&s.length>0&&s[0]===ie)return this._resolveMetaChainFromNode(o,s,t.join(L));let i=this._mounts.get(n);if(!i)throw this._nodes.has(n)?new Error(`Graph "${this.name}": "${n}" is a node; trailing path "${s.join(L)}" is invalid`):new Error(`Graph "${this.name}": unknown mount or node "${n}"`);return i.resolve(s.join(L))}_resolveMetaChainFromNode(e,t,n){let s=e,o=0,i=[...t];for(;o<i.length;){if(i[o]!==ie)throw new Error(`Graph "${this.name}": expected ${ie} segment in meta path "${n}"`);if(o+1>=i.length)throw new Error(`Graph "${this.name}": meta path requires a key after ${ie} in "${n}"`);let a=i[o+1],d=s.meta[a];if(!d)throw new Error(`Graph "${this.name}": unknown meta "${a}" in path "${n}"`);s=d,o+=2}return s}signal(e,t){if(t?.internal!==!0){for(let s of e)if(this.config.messageTier(s[0])===3)throw new Error(`Graph "${this.name}": Graph.signal() rejects tier-3 messages (DATA / RESOLVED). Broadcast is for control-plane tiers (START / DIRTY / INVALIDATE / PAUSE / RESUME / COMPLETE / ERROR / TEARDOWN). For per-node value writes, use Graph.set or graph.node(name).down(...).`)}let n=[];if(this._signalDeliver(e,t??{},new Set,n),n.length>0)throw n[0]}_signalDeliver(e,t,n,s){for(let d of this._mounts.values())d._signalDeliver(e,t,n,s);let i=t.internal===!0?{internal:!0}:{actor:t.actor,delivery:"signal"},a=Ks(e,this.config);for(let d of[...this._nodes.keys()].sort()){let u=this._nodes.get(d);if(!n.has(u)){n.add(u);try{u.down(e,i)}catch(c){if(c instanceof oe)throw c;s.push(c)}a.length!==0&&this._signalMetaSubtree(u,a,n,i,s)}}}_signalMetaSubtree(e,t,n,s,o){for(let i of Object.keys(e.meta).sort()){let a=e.meta[i];if(!n.has(a)){n.add(a);try{a.down(t,s)}catch(d){if(d instanceof oe)throw d;o.push(d)}this._signalMetaSubtree(a,t,n,s,o)}}}describe(e){if(e?.reactive==="diff")return this._describeReactiveDiff(e);if(e?.reactive===!0)return this._describeReactive(e);let t=$s(e?.actor),n=e?.filter;if(e?.detail!=null&&e?.fields!=null)throw new TypeError("Graph.describe(): pass either `detail` or `fields`, not both. `detail: 'spec'` is the canonical spec projection; use `fields` only when you need a custom subset.");let s=xt(e?.detail,e?.fields),o=e?.detail==="spec",i=s,a=[];this._collectObserveTargets("",a);let d=new Map;for(let[b,w]of a)d.set(w,b);let u=[];{let b=a.map(([,y])=>y),w=new Set(d.values()),N=0;for(;b.length>0;){let y=b.shift();if(y instanceof q)for(let O of y._deps){let k=O.node;if(d.has(k))continue;let x=k.name??"",T=x;if(!T||w.has(T))if(x){let R=2;for(;w.has(`${x}#${R}`);)R++;T=`${x}#${R}`}else for(T=`__internal__/${N++}`;w.has(T);)T=`__internal__/${N++}`;d.set(k,T),w.add(T),u.push([T,k]),b.push(k)}}}let c=[...a,...u],f={};for(let[b,w]of c){if(t!=null&&!w.allowsObserve(t))continue;let N=dn(w,i,o),y=w instanceof q?w._deps.map(T=>d.get(T.node)??T.node.name??""):[],{name:O,...k}=N,x={...k,deps:y};if(!o){let T=this._annotations.get(b);T!=null&&(x.annotation=T)}if(n!=null)if(typeof n=="function"){let T=n;if(!(T.length>=2?T(b,x):T(x)))continue}else{let T=!0;for(let[R,C]of Object.entries(n)){let S=R==="deps_includes"?"depsIncludes":R==="meta_has"?"metaHas":R;if(S==="depsIncludes"){if(!x.deps.includes(String(C))){T=!1;break}continue}if(S==="metaHas"){if(!Object.hasOwn(x.meta??{},String(C))){T=!1;break}continue}if(x[S]!==C){T=!1;break}}if(!T)continue}f[b]=x}let p=new Set(Object.keys(f)),h=[];for(let[b,w]of c)if(w instanceof q)for(let N of w._deps){let y=d.get(N.node);y!=null&&h.push([y,b])}h.sort((b,w)=>b[0]<w[0]?-1:b[0]>w[0]?1:b[1]<w[1]?-1:b[1]>w[1]?1:0);let l=h.map(([b,w])=>({from:b,to:w}));(t!=null||n!=null)&&(l=l.filter(b=>p.has(b.from)&&p.has(b.to)));let m=this._collectSubgraphs(""),g=t!=null||n!=null?m.filter(b=>{let w=`${b}${L}`;return[...p].some(N=>N===b||N.startsWith(w))}):m,E=this,v=e;return{name:this.name,nodes:f,edges:l,subgraphs:g,...this._factory!==void 0?{factory:this._factory}:{},...this._factoryArgs!==void 0?{factoryArgs:this._factoryArgs}:{},expand(b){let w={...v};return Array.isArray(b)?(w.fields=b,w.detail=void 0):(w.detail=b,w.fields=void 0),E.describe(w)}}}_collectSubgraphs(e){let t=[];for(let n of[...this._mounts.keys()].sort()){let s=e===""?n:`${e}${n}`;t.push(s),t.push(...this._mounts.get(n)._collectSubgraphs(`${s}${L}`))}return t}resourceProfile(e){return Cr(this,e)}reachable(e,t,n={}){return n.withDetail===!0?hn(this.describe(),e,t,{...n,withDetail:!0}):hn(this.describe(),e,t,n)}explain(e,t,n){return n?.reactive===!0?this._explainReactive(e,t,n):this._explainStatic(he(e),he(t),{...n?.maxDepth!==void 0?{maxDepth:Dr(n.maxDepth)}:{},...n?.findCycle!==void 0?{findCycle:Gr(n.findCycle)}:{}})}_explainStatic(e,t,n){let s=this.describe({detail:"full"}),o=new Map(this._annotations),i=new Map;for(let[a,d]of Object.entries(s.nodes))d.lastMutation!=null&&i.set(a,d.lastMutation);return Or(s,e,t,{...n?.maxDepth!=null?{maxDepth:n.maxDepth}:{},...n?.findCycle===!0?{findCycle:!0}:{},annotations:o,lastMutations:i})}_describeReactive(e){let t={...e,reactive:!1},n=e.reactiveName??"describe",s=0,o=U(s,{name:`${n}_version`}),i=this.observe({timeline:!0,structured:!0}),a=!1,d=!1,u=()=>{a||d||(a=!0,ze(()=>{a=!1,!d&&(s+=1,o.emit(s))}))},c=i.onEvent(v=>{let _=v.type;_!=="data"&&_!=="error"&&_!=="complete"&&_!=="teardown"||u()}),f=[],p=new WeakSet,h=v=>{if(p.has(v)||d)return;p.add(v);let _=v.topology.subscribe(b=>{for(let w of b){if(w[0]!==M)continue;let N=w[1];if(u(),N.kind==="added"&&N.nodeKind==="mount"){let y=v._mounts.get(N.name);y!=null&&h(y)}}});f.push(_);for(let b of v._mounts.keys()){let w=v._mounts.get(b);w!=null&&h(w)}};h(this);let l,m=e.actor;Lr(m)&&(l=m.subscribe(v=>{let _=!1,b=!1;for(let w of v){let N=w[0];N===M?_=!0:(N===G||N===D||N===F)&&(b=!0)}_&&u(),b&&(l?.(),l=void 0,u())}));let g;try{g=Y([o],()=>this.describe(t),{name:n,describeKind:"derived",meta:{domain:"audit",kind:"describe"},equals:(v,_)=>v===_})}catch(v){c(),l?.();for(let _ of f)_();throw i.dispose(),v}let E=fe(g);return{node:g,dispose(){d=!0,c(),l?.();for(let v of f)v();f.length=0,i.dispose(),E()}}}_describeReactiveDiff(e){let t={...e,reactive:!1},n=e.reactiveName??"describe-diff",s={name:this.name,nodes:{},edges:[],subgraphs:[]},o=this.describe(t),i=ln(s,o),a=U(i,{name:n,meta:{domain:"audit",kind:"describe-diff"},equals:(p,h)=>p===h}),d=this._describeReactive({...e,reactiveName:void 0}),u=!1,c=d.node.subscribe(p=>{if(!u)for(let h of p){if(h[0]!==M)continue;let l=h[1],m=ln(o,l);o=l,m.events.length!==0&&a.emit(m)}}),f=fe(a);return{node:a,dispose(){u=!0,c(),d.dispose(),a.down([[F,"describe-diff disposed"]]),f()}}}_explainReactive(e,t,n){let s=0,o=U(s,{name:"explain_version"}),i=this.observe({timeline:!0,structured:!0}),a=!1,d=!1,u=()=>{a||d||(a=!0,ze(()=>{a=!1,!d&&(s+=1,o.emit(s))}))},c=i.onEvent(v=>{let _=v.type;_!=="data"&&_!=="error"&&_!=="complete"&&_!=="teardown"||u()}),f=[];e!=null&&Ae(e)&&f.push(e),t!=null&&Ae(t)&&f.push(t),n?.maxDepth!=null&&Ae(n.maxDepth)&&f.push(n.maxDepth),n?.findCycle!=null&&Ae(n.findCycle)&&f.push(n.findCycle);let p=()=>{for(let v of f)if(v.cache===void 0)return!1;return!0},h=()=>{let v=he(e),_=he(t);return{from:v,to:_,found:!1,reason:"pending",steps:[],text:"(awaiting reactive args)",toJSON:()=>({from:v,to:_,found:!1,reason:"pending",steps:[]})}},l;try{l=Y([o],()=>{if(!p())return h();let v=he(e),_=he(t),b={...n?.maxDepth!==void 0?{maxDepth:Dr(n.maxDepth)}:{},...n?.findCycle!==void 0?{findCycle:Gr(n.findCycle)}:{}};return this._explainStatic(v,_,b)},{name:n?.name??"explain",describeKind:"derived",meta:{domain:"audit",kind:"explain_path",from:he(e),to:he(t)},equals:(v,_)=>v.found===_.found&&v.reason===_.reason&&v.steps.length===_.steps.length&&Us(v.steps,_.steps)})}catch(v){throw c(),i.dispose(),v}let m=fe(l),g=[],E=v=>{let _;return _=v.subscribe(b=>{let w=!1,N=!1;for(let y of b){let O=y[0];O===M?w=!0:(O===G||O===D||O===F)&&(N=!0)}(w||N)&&u(),N&&_&&(_(),_=void 0)}),()=>{_&&(_(),_=void 0)}};for(let v of f)g.push(E(v));return{node:l,dispose(){d=!0,c();for(let v of g)v?.();g.length=0,i.dispose(),m()}}}_pathsMatching(e){let t=Ct(e),n=[];return this._collectObserveTargets("",n),n.map(([s])=>s).filter(s=>t.test(s))}_collectObserveTargets(e,t){for(let n of[...this._mounts.keys()].sort()){let s=e===""?n:`${e}${L}${n}`;this._mounts.get(n)._collectObserveTargets(s,t)}for(let n of[...this._nodes.keys()].sort()){let s=this._nodes.get(n),o=e===""?n:`${e}${L}${n}`;t.push([o,s]),this._appendMetaObserveTargets(o,s,t)}}_appendMetaObserveTargets(e,t,n){for(let s of Object.keys(t.meta).sort()){let o=t.meta[s],i=`${e}${L}${ie}${L}${s}`;n.push([i,o]),this._appendMetaObserveTargets(i,o,n)}}observe(e,t){let n=typeof e=="string",o=Pr(n?t:e);if(o.reactive===!0)return this._observeReactive(n?e:void 0,o);let i=o.structured===!0||o.timeline===!0||o.causal===!0||o.derived===!0||o.detail==="minimal"||o.detail==="full"||o.format!=null,a=o.actor;if(n){let c=e,f=this.resolve(c);if(a!=null&&!f.allowsObserve(a))throw new oe({actor:a,action:"observe",nodeName:c});return i?this._buildStructuredObserver([[c,f]],o,"one"):{subscribe(p){return f.subscribe(p)},up(p){try{f.up?.(p)}catch(h){if(h instanceof oe)return;throw h}}}}let d=[];this._collectObserveTargets("",d),d.sort((c,f)=>c[0]<f[0]?-1:c[0]>f[0]?1:0);let u=a==null?d:d.filter(([,c])=>c.allowsObserve(a));return i?this._buildStructuredObserver(u,o,"all"):{subscribe:c=>{let f=u.map(([p,h])=>h.subscribe(l=>{c(p,l)}));return()=>{for(let p of f)p()}},up:(c,f)=>{try{this.resolve(c).up?.(f)}catch(p){if(p instanceof oe)return;throw p}}}}_observeReactive(e,t){let n=t.tiers,s=n!=null?new Set(n):null,o=t.reactiveName??"observe";return ce(i=>{let a=[],d=!1,u=!1,c=()=>{if(a.length===0||u)return;let m={events:a.slice(),flushedAt_ns:le()};a.length=0,i.emit(m)},f={...t,reactive:!1,structured:!0,timeline:!0},p=e!=null?this.observe(e,f):this.observe(f),h=m=>{u||(a.push(m),!d&&(d=!0,ze(()=>{d=!1,c()})))};for(let m of p.events)h(m);let l=p.onEvent(h);return()=>{u=!0,l(),p.dispose()}},{name:o,meta:{domain:"audit",kind:"observe-reactive"}})}_buildStructuredObserver(e,t,n){let s=n==="one"?e[0]?.[0]:void 0,o=i=>{if(n==="one"&&s!=null){let c=this.resolve(s);return this._buildStructuredObserver([[s,c]],i,"one")}let a=[];this._collectObserveTargets("",a),a.sort((c,f)=>c[0]<f[0]?-1:c[0]>f[0]?1:0);let d=i.actor,u=d==null?a:a.filter(([,c])=>c.allowsObserve(d));return this._buildStructuredObserver(u,i,"all")};return this._createObserveResult(e,t,o)}_createObserveResult(e,t,n){let s=t.timeline===!0,o=t.causal===!0,i=t.derived===!0,a=t.detail==="minimal",d=this.config.inspectorEnabled,u=(o||i)&&d,c=t.maxEvents,f=c!=null&&c>0?new ot(c):null,p=[],h=new Set,l=t.tiers!=null?new Set(t.tiers):null,m={},g=new Set,E=0,v=0,_=0,b=0,w=0,N=0,y=!1,O=!1,k=0,x=new Map,T=new Map,R=new Map,C=A=>{if(!(l!=null&&!l.has(A.type))){f?f.push(A):p.push(A);for(let P of h)P(A)}},S=A=>l==null||l.has(A),H=()=>s?{timestamp_ns:le(),in_batch:yt(),batch_id:k}:{},z=(A,P)=>{if(!(!u||!(A instanceof q)))return A._setInspectorHook(Z=>{if(Z.kind==="dep_message")x.set(A,Z.depIndex);else if(Z.kind==="run"){let Ue=Z.batchData.map((I,B)=>I!=null&&I.length>0?I.at(-1):Z.prevData[B]);T.set(A,Ue);let X=Z.batchData.map(I=>I!=null?[...I]:void 0);R.set(A,X),i&&C({type:"derived",path:P,dep_values:Ue,dep_batches:X,...H()})}})},J=A=>{let P=x.get(A),Z=T.get(A);if(!o||Z==null)return{};let X=(P!=null&&P>=0&&A instanceof q?A._deps[P]:void 0)?.node,I=X?.v,B=R.get(A);return{trigger_dep_index:P,trigger_dep_name:X?.name,...I!=null?{trigger_version:{id:I.id,version:I.version}}:{},dep_values:[...Z],...B!=null?{dep_batches:B}:{}}},Ce=[],Me=[];for(let[A,P]of e){let Z=z(P,A);Z&&Ce.push(Z),Me.push(P.subscribe(Ue=>{k++;for(let X of Ue){let I=X[0],B=H();if(I===M){m[A]=X[1];let qt=P instanceof q?P.lastMutation?.actor??pe:pe;C({type:"data",path:A,data:X[1],actor:qt,...B,...J(P)})}else if(a)I===j?S("dirty")&&E++:I===W?S("resolved")&&v++:I===ee?S("invalidate")&&_++:I===Q?S("pause")&&b++:I===te?S("resume")&&w++:I===F?S("teardown")&&N++:I===G&&!g.has(A)?S("complete")&&(y=!0):I===D&&S("error")&&(O=!0,g.add(A));else if(I===j)S("dirty")&&E++,C({type:"dirty",path:A,...B});else if(I===W)S("resolved")&&v++,C({type:"resolved",path:A,...B,...J(P)});else if(I===ee)S("invalidate")&&_++,C({type:"invalidate",path:A,...B});else if(I===Q)S("pause")&&b++,C({type:"pause",path:A,lockId:X[1],...B});else if(I===te)S("resume")&&w++,C({type:"resume",path:A,lockId:X[1],...B});else if(I===G)S("complete")&&!g.has(A)&&(y=!0),C({type:"complete",path:A,...B});else if(I===D){S("error")&&(O=!0,g.add(A));let qt=P instanceof q?P.lastMutation?.actor??pe:pe;C({type:"error",path:A,data:X[1],actor:qt,...B})}else I===F&&(S("teardown")&&N++,C({type:"teardown",path:A,...B}))}}))}let We=!1,Ke=()=>{if(!We){We=!0;for(let A of Me)A();for(let A of Ce)A();for(let A of ft)A({value:void 0,done:!0});ft.length=0}},Ht=[],ft=[];h.add(A=>{let P=ft.shift();P?P({value:A,done:!1}):Ht.push(A)});let wn={get values(){return m},get dirtyCount(){return E},get resolvedCount(){return v},get invalidateCount(){return _},get pauseCount(){return b},get resumeCount(){return w},get teardownCount(){return N},get events(){return f?f.toArray():[...p]},get anyCompletedCleanly(){return y},get anyErrored(){return O},get completedWithoutErrors(){return y&&!O},onEvent(A){return h.add(A),()=>h.delete(A)},dispose:Ke,expand(A){Ke();let P={...t};return typeof A=="string"?P.detail=A:Object.assign(P,A),n(Pr(P))},[Symbol.asyncIterator](){return{next(){return Ht.length>0?Promise.resolve({value:Ht.shift(),done:!1}):We?Promise.resolve({value:void 0,done:!0}):new Promise(A=>ft.push(A))},return(){return Ke(),Promise.resolve({value:void 0,done:!0})}}}};return t.format!=null&&this._attachFormatLogger(wn,t),wn}_attachFormatLogger(e,t){let n=t.format;if(n==null)return;let s=t.logger??(l=>console.log(l)),o=t.includeTypes?new Set(t.includeTypes):null,i=t.excludeTypes?new Set(t.excludeTypes):null,a=o==null&&i==null?()=>!0:l=>(o==null||o.has(l))&&(i==null||!i.has(l)),d=js(t.theme),u=n==="stage-log"?le():0,c=l=>l==null?"":t.stageLabels?.[l]??l,f=(l,m)=>l.length>m?`${l.slice(0,m-1)}\u2026`:l,p=l=>l.type==="data"||l.type==="error"?f(fn(l.data),120):"",h=l=>{if(n==="stage-log"){let y=(le()-u)/1e9,O=c(l.path).padEnd(9);if(l.type==="data"){let k=p(l);return`[${y.toFixed(3)}s] ${O} \u2190${k?` ${k}`:""}`}if(l.type==="error"){let k=p(l);return`[${y.toFixed(3)}s] ${O} \u2717${k?` ${k}`:""}`}return l.type==="complete"?`[${y.toFixed(3)}s] ${O} \u25A0 complete`:`[${y.toFixed(3)}s] ${O} ${l.type}`}if(n==="json")try{return JSON.stringify(l)}catch{return JSON.stringify({type:l.type,path:l.path,data:"[unserializable]"})}let m=d[l.type]??"",g=l.path?`${d.path}${l.path}${d.reset} `:"",E=l.type==="data"||l.type==="error",v=l.type==="pause"||l.type==="resume",_=E?` ${fn(l.data)}`:v?` ${fn(l.lockId)}`:"",b=l.type==="data"||l.type==="resolved"||l.type==="derived"?l:void 0,w=b?.trigger_dep_name!=null?` <- ${b.trigger_dep_name}`:b?.trigger_dep_index!=null?` <- #${b.trigger_dep_index}`:"",N=l.in_batch?" [batch]":"";return`${g}${m}${l.type.toUpperCase()}${d.reset}${_}${w}${N}`};e.onEvent(l=>{a(l.type)&&s(h(l),l)})}addDisposer(e){return this._disposers.add(e),()=>{this._disposers.delete(e)}}destroy(){At(this._disposers,this.name),this.signal([[F]],{internal:!0}),At(this._storageDisposers,this.name);for(let e of[...this._mounts.values()])e._parent=void 0,e._destroyClearOnly();this._mounts.clear(),this._nodes.clear(),this._parent=void 0,this._destroyed=!0}get destroyed(){return this._destroyed}_destroyClearOnly(){At(this._disposers,this.name),At(this._storageDisposers,this.name);for(let e of[...this._mounts.values()])e._parent=void 0,e._destroyClearOnly();this._mounts.clear(),this._nodes.clear(),this._parent=void 0,this._destroyed=!0}snapshot(e){let{expand:t,...n}=this.describe({detail:"full"}),s={};for(let a of Object.keys(n.nodes).sort()){let{lastMutation:d,guard:u,...c}=n.nodes[a];s[a]=c}let o=[...n.subgraphs].sort(),i={...n,version:1,nodes:s,subgraphs:o};if(e?.format==null)return i;if(e.format==="json-string")return JSON.stringify(i);if(e.format==="bytes"){if(e.codec==null)throw new Error("snapshot({format: 'bytes'}) requires a `codec` name");let a=this.config.lookupCodec(e.codec);if(a==null)throw new Error(`snapshot: codec "${e.codec}" is not registered on this graph's config. Call config.registerCodec(...) before creating nodes.`);return Wn(a,a.encode(i))}throw new Error(`snapshot: unknown format "${String(e.format)}"`)}static decode(e,t){let n=t?.config??Ne,{codec:s,codecVersion:o,payload:i}=Kn(e,n);return s.decode(i,o)}restore(e,t){if(Ir(e),e.name!==this.name)throw new Error(`Graph "${this.name}": restore snapshot name "${e.name}" does not match this graph`);let n=t?.only==null?null:(Array.isArray(t.only)?t.only:[t.only]).map(o=>Ct(o)),s=t?.includeProducers===!0;for(let o of Object.keys(e.nodes).sort()){if(n!==null&&!n.some(a=>a.test(o)))continue;let i=e.nodes[o];if(i!==void 0){if(!("value"in i)||i.value===void 0){"value"in i&&i.value===void 0&&t?.onError?.(o,new Error(`restore: slice.value is undefined for "${o}" (undefined is the global SENTINEL; not valid DATA)`));continue}if(!(i.type==="derived"||i.type==="effect")&&!(i.type==="producer"&&!s)){if(i.v!=null){let d=this.tryResolve(o)?.v;if(d!=null&&d.id===i.v.id&&d.version===i.v.version)continue}try{this.set(o,i.value)}catch(a){t?.onError?.(o,a)}}}}}static fromSnapshot(e,t){Ir(e);let n=typeof t=="function"?t:t?.build,s=typeof t=="function"?void 0:t?.factories,o=new r(e.name);if(n)return n(o),o.restore(e),o;for(let h of[...e.subgraphs].sort((l,m)=>{let g=l.split(L).length,E=m.split(L).length;return g!==E?g-E:l<m?-1:l>m?1:0})){let l=h.split(L),m=o;for(let g of l)m._mounts.has(g)||m.mount(g,new r(g)),m=m._mounts.get(g)}let i=s?Object.entries(s).map(([h,l])=>({re:Ct(h),factory:l})):[],a=h=>{for(let l of i)if(l.re.test(h))return l.factory},d=h=>{let l=h.split(L),m=l.pop();if(m==null||m.length===0)throw new Error(`invalid snapshot path "${h}"`);let g=o;for(let E of l){let v=g._mounts.get(E);if(!v)throw new Error(`unknown mount "${E}" in path "${h}"`);g=v}return[g,m]},u=Object.entries(e.nodes).filter(([h])=>!h.includes(`${L}${ie}${L}`)).sort((h,l)=>h[0]<l[0]?-1:h[0]>l[0]?1:0),c=new Map(u),f=new Map,p=!0;for(;c.size>0&&p;){p=!1;for(let[h,l]of[...c.entries()]){let m=l?.deps??[];if(!m.every(w=>f.has(w)))continue;let[g,E]=d(h),v={...l?.meta??{}},_=a(h),b;if(l?.type==="state")b=U(l.value,{meta:v});else{if(_==null)continue;b=_(E,{path:h,type:l.type,value:l.value,meta:v,deps:m,resolvedDeps:m.map(w=>f.get(w))})}g.add(b,{name:E}),f.set(h,b),c.delete(h),p=!0}}if(c.size>0){let h=[...c.keys()].sort().join(", ");throw new Error(`Graph.fromSnapshot could not reconstruct nodes without build callback: ${h}. Pass matching factories via fromSnapshot(data, { factories: { pattern: factoryFn } }).`)}return o.restore(e),o}toJSON(){return this.snapshot()}attachSnapshotStorage(e,t={}){let n=e.map(u=>({tier:u,debounceMs:Math.max(0,u.debounceMs??0),compactEvery:Math.max(1,u.compactEvery??10),timer:void 0,seq:0,lastSnapshot:void 0,lastFingerprint:"",disposed:!1,savePending:void 0}));t.autoRestore===!0&&this._cascadeRestore(e,t.onError);let s=(u,c)=>{if(u.disposed)return;let f=Fs(c.nodes);if(u.lastSnapshot!=null&&f!==""&&f===u.lastFingerprint)return;let p=u.seq+1,h=se(),g=u.lastSnapshot==null||p%u.compactEvery===0?{name:this.name,mode:"full",snapshot:c,seq:p,timestamp_ns:h,format_version:Se}:{name:this.name,mode:"diff",diff:Fr(u.lastSnapshot,c),seq:p,timestamp_ns:h,format_version:Se};if(u.tier.filter&&!u.tier.filter(g))return;let E;try{E=u.tier.save(g)}catch(v){t.onError?.(v,u.tier);return}if(E&&typeof E.then=="function"){let b=(u.savePending??Promise.resolve()).then(()=>E,()=>E).then(()=>{u.disposed||(u.seq=p,u.lastSnapshot=c,u.lastFingerprint=f)},w=>{t.onError?.(w,u.tier)});u.savePending=b.finally(()=>{u.savePending===b&&(u.savePending=void 0)})}else u.seq=p,u.lastSnapshot=c,u.lastFingerprint=f},o=(u,c)=>{try{s(u,c)}catch(f){t.onError?.(f,u.tier)}},i=(u,c)=>{if(!c.some(l=>{let m=this.config.messageTier(l[0]);return m>=3&&m<5}))return;if(t.filter){let l=this.tryResolve(u);if(l==null)return;let m=dn(l,xt("standard"));if(!t.filter(u,m))return}let p,h=()=>(p==null&&(p=this.snapshot()),p);for(let l of n)l.disposed||(l.debounceMs===0?o(l,h()):(l.timer==null&&(l.timer=new Nt),l.timer.start(l.debounceMs,()=>{l.disposed||o(l,this.snapshot())})))},a;if(t.paths!=null){let c=(typeof t.paths=="string"?this._pathsMatching(t.paths):t.paths).map(f=>{let p=this.tryResolve(f);return p==null?()=>{}:p.subscribe(h=>i(f,h))});a=()=>{for(let f of c)f()}}else a=this.observe().subscribe((u,c)=>i(u,c));let d=()=>{a();for(let u of n)u.disposed=!0,u.timer?.cancel();this._storageDisposers.delete(d)};return this._storageDisposers.add(d),{dispose:d}}async _cascadeRestore(e,t){for(let n of e){let s;try{s=await n.load?.()}catch(i){t?.(i,n);continue}if(s==null||typeof s!="object"||Array.isArray(s))continue;let o=s;try{if(o.mode==="full"&&o.snapshot!=null)return this.restore(o.snapshot),!0;if(o.version===Se&&o.nodes!=null)return this.restore(o),!0}catch(i){t?.(i,n)}}return!1}static async fromStorage(e,t,n){for(let s of t){let o;try{o=await s.load?.()}catch(d){n?.onError?.(d,s);continue}if(o==null||typeof o!="object"||Array.isArray(o))continue;let i=o,a=i.mode==="full"&&i.snapshot!=null?i.snapshot:i.version===Se&&i.nodes!=null?i:void 0;if(a!=null)try{return r.fromSnapshot(a,n)}catch(d){n?.onError?.(d,s)}}throw new Error(`Graph.fromStorage: no tier held a restorable record for "${e}" across ${t.length} tier(s)`)}_annotations=new Map;_traceRing;trace(e,t,n){if(e!=null&&t!=null){if(this.tryResolve(e)==null)return;if(this._annotations.set(e,t),this.config.inspectorEnabled){let s={path:e,annotation:t,timestamp_ns:le(),...n?.actor!=null?{actor:n.actor}:{}};this._traceRing.push(s)}return}return e!=null?this.config.inspectorEnabled?this._annotations.get(e):void 0:this.config.inspectorEnabled?this._traceRing.toArray():[]}annotation(e){return this._annotations.get(e)}clearTrace(){this._annotations.clear(),this._traceRing.clear()}pruneTrace(e){let t=this._traceRing.toArray().filter(s=>!e(s)),n=this._traceRing.size-t.length;this._traceRing.clear();for(let s of t)this._traceRing.push(s);return n}static diff(e,t){let n=new Set(Object.keys(e.nodes)),s=new Set(Object.keys(t.nodes)),o=[...s].filter(v=>!n.has(v)).sort(),i=[...n].filter(v=>!s.has(v)).sort(),a=[],d=[];for(let v of n){if(!s.has(v))continue;let _=e.nodes[v],b=t.nodes[v],w=_.v,N=b.v;w!=null&&N!=null&&w.id===N.id&&w.version!==N.version&&d.push({path:v,id:w.id,from:w.version,to:N.version});let y=w!=null&&N!=null&&w.id===N.id&&w.version===N.version;for(let O of["type","status","sentinel"]){let k=_[O],x=b[O];k!==x&&a.push({path:v,field:O,from:k,to:x})}if(!y)for(let O of["value","meta"]){let k=_[O],x=b[O];Hs(k,x)||a.push({path:v,field:O,from:k,to:x})}}let u=v=>`${v.from} ${v.to}`,c=new Set(e.edges.map(u)),f=new Set(t.edges.map(u)),p=t.edges.filter(v=>!c.has(u(v))),h=e.edges.filter(v=>!f.has(u(v))),l=new Set(e.subgraphs),m=new Set(t.subgraphs),g=[...m].filter(v=>!l.has(v)).sort(),E=[...l].filter(v=>!m.has(v)).sort();return{nodesAdded:o,nodesRemoved:i,nodesChanged:a,versionChanges:d,edgesAdded:p,edgesRemoved:h,subgraphsAdded:g,subgraphsRemoved:E}}}});var Wr=$(()=>{"use strict";Mt()});function Kr(r,e,t){return{[r]:!0,[`${r}_type`]:e,...t??{}}}var Ur=$(()=>{"use strict"});var Xs={};ss(Xs,{ACTOR_KEY:()=>Ot,COMMAND_HANDLERS:()=>Le,CQRS_EVENT_HANDLERS:()=>$e,CRON_HANDLERS:()=>Pe,CommandHandler:()=>qn,EVENT_HANDLERS:()=>Ge,EventHandler:()=>Vn,GRAPHREFLY_REQUEST_GRAPH:()=>ve,GRAPHREFLY_ROOT_GRAPH:()=>re,GraphCron:()=>Hn,GraphInterval:()=>Fn,GraphReflyEventExplorer:()=>Re,GraphReflyGuard:()=>br,GraphReflyGuardImpl:()=>st,GraphReflyModule:()=>Ft,INTERVAL_HANDLERS:()=>Ie,InjectCqrsGraph:()=>Pn,InjectGraph:()=>In,InjectNode:()=>Ln,ObserveGateway:()=>Et,OnGraphEvent:()=>$n,QUERY_HANDLERS:()=>Fe,QueryHandler:()=>zn,SAGA_HANDLERS:()=>He,SagaHandler:()=>jn,fromHeader:()=>mr,fromJwtPayload:()=>sn,getActor:()=>yr,getGraphToken:()=>K,getNodeToken:()=>de,observeSSE:()=>hr,observeSubscription:()=>gr,toObservable:()=>Gn});module.exports=is(Xs);var Wt=require("rxjs");ne();function Gn(r,e){return e?.raw?new Wt.Observable(t=>r.subscribe(s=>{if(!t.closed){t.next(s);for(let o of s){if(o[0]===D){t.error(o[1]);return}if(o[0]===G){t.complete();return}}}})):new Wt.Observable(t=>r.subscribe(s=>{for(let o of s){if(t.closed)return;if(o[0]===M)t.next(o[1]);else if(o[0]===D){t.error(o[1]);return}else if(o[0]===G){t.complete();return}}}))}var Qe=require("@nestjs/common");var re=Symbol.for("graphrefly:root-graph");var ve=Symbol.for("graphrefly:request-graph");function K(r){return Symbol.for(`graphrefly:graph:${r}`)}function de(r){return Symbol.for(`graphrefly:node:${r}`)}var Ge=new Map,Ie=new Map,Pe=new Map,Le=new Map,$e=new Map,Fe=new Map,He=new Map;function In(r){return r==="request"?(0,Qe.Inject)(ve):(0,Qe.Inject)(r?K(r):re)}function Pn(r){return(0,Qe.Inject)(K(r))}function Ln(r){return(0,Qe.Inject)(de(r))}function $n(r){return(e,t)=>{let n=t.name;t.addInitializer(function(){let s=this.constructor,o=Ge.get(s)??[];o.push({nodeName:r,methodKey:n}),Ge.set(s,o)})}}function Fn(r){return(e,t)=>{let n=t.name;t.addInitializer(function(){let s=this.constructor,o=Ie.get(s)??[];o.push({ms:r,methodKey:n}),Ie.set(s,o)})}}function Hn(r){return(e,t)=>{let n=t.name;t.addInitializer(function(){let s=this.constructor,o=Pe.get(s)??[];o.push({expr:r,methodKey:n}),Pe.set(s,o)})}}function qn(r,e){return(t,n)=>{let s=n.name;n.addInitializer(function(){let o=this.constructor,i=Le.get(o)??[];i.push({cqrsName:r,commandName:e,methodKey:s}),Le.set(o,i)})}}function Vn(r,e){return(t,n)=>{let s=n.name;n.addInitializer(function(){let o=this.constructor,i=$e.get(o)??[];i.push({cqrsName:r,eventName:e,methodKey:s}),$e.set(o,i)})}}function zn(r,e){return(t,n)=>{let s=n.name;n.addInitializer(function(){let o=this.constructor,i=Fe.get(o)??[];i.push({cqrsName:r,projectionName:e,methodKey:s}),Fe.set(o,i)})}}function jn(r,e,t){return(n,s)=>{let o=s.name;s.addInitializer(function(){let i=this.constructor,a=He.get(i)??[];a.push({cqrsName:r,eventNames:t,sagaName:e,methodKey:o}),He.set(i,a)})}}ne();wt();var pr=0,Re=class{constructor(e,t){this.graph=e;this.moduleRef=t}disposers=[];scheduleNodeNames=[];onModuleInit(){this.wireEvents(),this.wireIntervals(),this.wireCrons(),this.wireCqrsCommands(),this.wireCqrsEvents(),this.wireCqrsQueries(),this.wireCqrsSagas()}onModuleDestroy(){for(let e of this.disposers)e();this.disposers.length=0;for(let e of this.scheduleNodeNames)try{this.graph.remove(e)}catch{}this.scheduleNodeNames.length=0}wireEvents(){for(let[e,t]of Ge){let n=this.resolveInstance(e);if(n)for(let s of t)this.wireEventHandler(n,s)}}wireEventHandler(e,t){let n=e[t.methodKey];if(typeof n!="function")return;let s=n.bind(e),i=this.observeNode(t.nodeName).subscribe(a=>{for(let d of a)d[0]===M&&s(d[1])});this.disposers.push(i)}wireIntervals(){for(let[e,t]of Ie){let n=this.resolveInstance(e);if(n)for(let s of t)this.wireIntervalHandler(n,e,s)}}wireIntervalHandler(e,t,n){let s=e[n.methodKey];if(typeof s!="function")return;let o=s.bind(e),a=`__schedule__.${t.name??"anonymous"}.${String(n.methodKey)}.${pr++}`,d=dr(n.ms,{period:n.ms,name:a});this.graph.add(d),this.scheduleNodeNames.push(a);let c=this.observeNode(a).subscribe(f=>{for(let p of f)p[0]===M&&o(p[1])});this.disposers.push(c)}wireCrons(){for(let[e,t]of Pe){let n=this.resolveInstance(e);if(n)for(let s of t)this.wireCronHandler(n,e,s)}}wireCronHandler(e,t,n){let s=e[n.methodKey];if(typeof s!="function")return;let o=s.bind(e),a=`__schedule__.${t.name??"anonymous"}.${String(n.methodKey)}.${pr++}`,d=ur(n.expr,{name:a});this.graph.add(d),this.scheduleNodeNames.push(a);let c=this.observeNode(a).subscribe(f=>{for(let p of f)p[0]===M&&o(p[1])});this.disposers.push(c)}wireCqrsCommands(){for(let[e,t]of Le){let n=this.resolveInstance(e);if(n)for(let s of t)this.wireCqrsCommand(n,s)}}wireCqrsCommand(e,t){let n=e[t.methodKey];if(typeof n!="function")return;let s=n.bind(e),o=this.resolveCqrsGraph(t.cqrsName);o&&o.command(t.commandName,s)}wireCqrsEvents(){for(let[e,t]of $e){let n=this.resolveInstance(e);if(n)for(let s of t)this.wireCqrsEventHandler(n,s)}}wireCqrsEventHandler(e,t){let n=e[t.methodKey];if(typeof n!="function")return;let s=n.bind(e),o=this.resolveCqrsGraph(t.cqrsName);if(!o)return;o.event(t.eventName);let a=o.resolve(t.eventName).cache,d=a&&a.length>0?a[a.length-1].seq:0,c=this.observeNodeOn(o,t.eventName).subscribe(f=>{for(let p of f)if(p[0]===M){let h=p[1];for(let l of h)l.seq>d&&(s(l),d=l.seq)}});this.disposers.push(c)}wireCqrsQueries(){for(let[e,t]of Fe){let n=this.resolveInstance(e);if(n)for(let s of t)this.wireCqrsQuery(n,s)}}wireCqrsQuery(e,t){let n=e[t.methodKey];if(typeof n!="function")return;let s=n.bind(e),o=this.resolveCqrsGraph(t.cqrsName);if(!o)return;let a=this.observeNodeOn(o,t.projectionName).subscribe(d=>{for(let u of d)u[0]===M&&s(u[1])});this.disposers.push(a)}wireCqrsSagas(){for(let[e,t]of He){let n=this.resolveInstance(e);if(n)for(let s of t)this.wireCqrsSaga(n,s)}}wireCqrsSaga(e,t){let n=e[t.methodKey];if(typeof n!="function")return;let s=n.bind(e),o=this.resolveCqrsGraph(t.cqrsName);o&&o.saga(t.sagaName,t.eventNames,s)}observeNode(e){return this.graph.observe(e)}observeNodeOn(e,t){return e.observe(t)}resolveCqrsGraph(e){try{return this.moduleRef.get(K(e),{strict:!1})}catch{return console.warn(`[GraphReFly] CqrsGraph "${e}" not found in DI \u2014 did you import GraphReflyModule.forCqrs({ name: "${e}" })?`),null}}resolveInstance(e){try{return this.moduleRef.get(e,{strict:!1})}catch{return null}}};ne();ne();var Ns=0;function Tt(r,e){if(e.highWaterMark<1)throw new RangeError("highWaterMark must be >= 1");if(e.lowWaterMark<0)throw new RangeError("lowWaterMark must be >= 0");if(e.lowWaterMark>=e.highWaterMark)throw new RangeError("lowWaterMark must be < highWaterMark");let t=Symbol(`bp-${++Ns}`),n=0,s=!1;return{onEnqueue(){return n+=1,!s&&n>=e.highWaterMark?(s=!0,r([[Q,t]]),!0):!1},onDequeue(){return n>0&&(n-=1),s&&n<=e.lowWaterMark?(s=!1,r([[te,t]]),!0):!1},get pending(){return n},get paused(){return s},dispose(){s&&(s=!1,r([[te,t]]))}}}function hr(r,e,t){let{actor:n,serialize:s=ks,keepAliveMs:o,signal:i}=t??{},a=new TextEncoder,d,u=t?.highWaterMark!=null,c,f,p=[],h=!1;return new ReadableStream({start(l){let m,g=()=>{},E=()=>{if(!h){h=!0,m!==void 0&&clearInterval(m),i?.removeEventListener("abort",v),g(),c?.dispose(),f?.(),f=void 0;for(let b of p)l.enqueue(b.frame);p.length=0,l.close()}};d=E;let v=()=>E(),_=r.observe(e,{actor:n});u&&(c=Tt(b=>_.up(b),{highWaterMark:t.highWaterMark,lowWaterMark:t.lowWaterMark??Math.floor(t.highWaterMark/2)})),g=_.subscribe(b=>{for(let w of b){if(h)return;let N=w[0];if(N===M){let y=a.encode(nn("data",s(w[1])));u?(p.push({frame:y,counted:!0}),c.onEnqueue(),f?.(),f=void 0):l.enqueue(y)}else if(N===D){let y=a.encode(nn("error",s(w[1])));u?(p.push({frame:y,counted:!1}),f?.(),f=void 0):l.enqueue(y),E();return}else if(N===G||N===F){if(N===G){let y=a.encode(nn("complete"));u?(p.push({frame:y,counted:!1}),f?.(),f=void 0):l.enqueue(y)}E();return}}}),o!==void 0&&o>0&&(m=setInterval(()=>{h||(u?(p.push({frame:a.encode(`: keepalive
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __knownSymbol = (name, symbol) => (symbol = Symbol[name]) ? symbol : /* @__PURE__ */ Symbol.for("Symbol." + name);
8
+ var __typeError = (msg) => {
9
+ throw TypeError(msg);
10
+ };
11
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
12
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
13
+ var __export = (target, all) => {
14
+ for (var name in all)
15
+ __defProp(target, name, { get: all[name], enumerable: true });
16
+ };
17
+ var __copyProps = (to, from, except, desc) => {
18
+ if (from && typeof from === "object" || typeof from === "function") {
19
+ for (let key of __getOwnPropNames(from))
20
+ if (!__hasOwnProp.call(to, key) && key !== except)
21
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
22
+ }
23
+ return to;
24
+ };
25
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
26
+ var __decoratorStart = (base) => [, , , __create(base?.[__knownSymbol("metadata")] ?? null)];
27
+ var __decoratorStrings = ["class", "method", "getter", "setter", "accessor", "field", "value", "get", "set"];
28
+ var __expectFn = (fn) => fn !== void 0 && typeof fn !== "function" ? __typeError("Function expected") : fn;
29
+ var __decoratorContext = (kind, name, done, metadata, fns) => ({ kind: __decoratorStrings[kind], name, metadata, addInitializer: (fn) => done._ ? __typeError("Already initialized") : fns.push(__expectFn(fn || null)) });
30
+ var __decoratorMetadata = (array, target) => __defNormalProp(target, __knownSymbol("metadata"), array[3]);
31
+ var __runInitializers = (array, flags, self, value) => {
32
+ for (var i = 0, fns = array[flags >> 1], n = fns && fns.length; i < n; i++) flags & 1 ? fns[i].call(self) : value = fns[i].call(self, value);
33
+ return value;
34
+ };
35
+ var __decorateElement = (array, flags, name, decorators, target, extra) => {
36
+ var fn, it, done, ctx, access, k = flags & 7, s = !!(flags & 8), p = !!(flags & 16);
37
+ var j = k > 3 ? array.length + 1 : k ? s ? 1 : 2 : 0, key = __decoratorStrings[k + 5];
38
+ var initializers = k > 3 && (array[j - 1] = []), extraInitializers = array[j] || (array[j] = []);
39
+ var desc = k && (!p && !s && (target = target.prototype), k < 5 && (k > 3 || !p) && __getOwnPropDesc(k < 4 ? target : { get [name]() {
40
+ return __privateGet(this, extra);
41
+ }, set [name](x) {
42
+ return __privateSet(this, extra, x);
43
+ } }, name));
44
+ k ? p && k < 4 && __name(extra, (k > 2 ? "set " : k > 1 ? "get " : "") + name) : __name(target, name);
45
+ for (var i = decorators.length - 1; i >= 0; i--) {
46
+ ctx = __decoratorContext(k, name, done = {}, array[3], extraInitializers);
47
+ if (k) {
48
+ ctx.static = s, ctx.private = p, access = ctx.access = { has: p ? (x) => __privateIn(target, x) : (x) => name in x };
49
+ if (k ^ 3) access.get = p ? (x) => (k ^ 1 ? __privateGet : __privateMethod)(x, target, k ^ 4 ? extra : desc.get) : (x) => x[name];
50
+ if (k > 2) access.set = p ? (x, y) => __privateSet(x, target, y, k ^ 4 ? extra : desc.set) : (x, y) => x[name] = y;
51
+ }
52
+ it = (0, decorators[i])(k ? k < 4 ? p ? extra : desc[key] : k > 4 ? void 0 : { get: desc.get, set: desc.set } : target, ctx), done._ = 1;
53
+ if (k ^ 4 || it === void 0) __expectFn(it) && (k > 4 ? initializers.unshift(it) : k ? p ? extra = it : desc[key] = it : target = it);
54
+ else if (typeof it !== "object" || it === null) __typeError("Object expected");
55
+ else __expectFn(fn = it.get) && (desc.get = fn), __expectFn(fn = it.set) && (desc.set = fn), __expectFn(fn = it.init) && initializers.unshift(fn);
56
+ }
57
+ return k || __decoratorMetadata(array, target), desc && __defProp(target, name, desc), p ? k ^ 4 ? extra : desc : target;
58
+ };
59
+ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
60
+ var __privateIn = (member, obj) => Object(obj) !== obj ? __typeError('Cannot use the "in" operator on this value') : member.has(obj);
61
+ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
62
+ var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
63
+ var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
4
64
 
5
- `),counted:!1}),f?.(),f=void 0):l.enqueue(a.encode(`: keepalive
65
+ // src/compat/nestjs/index.ts
66
+ var nestjs_exports = {};
67
+ __export(nestjs_exports, {
68
+ ACTOR_KEY: () => ACTOR_KEY,
69
+ COMMAND_HANDLERS: () => COMMAND_HANDLERS,
70
+ CQRS_EVENT_HANDLERS: () => CQRS_EVENT_HANDLERS,
71
+ CRON_HANDLERS: () => CRON_HANDLERS,
72
+ CommandHandler: () => CommandHandler,
73
+ EVENT_HANDLERS: () => EVENT_HANDLERS,
74
+ EventHandler: () => EventHandler,
75
+ GRAPHREFLY_REQUEST_GRAPH: () => GRAPHREFLY_REQUEST_GRAPH,
76
+ GRAPHREFLY_ROOT_GRAPH: () => GRAPHREFLY_ROOT_GRAPH,
77
+ GraphCron: () => GraphCron,
78
+ GraphInterval: () => GraphInterval,
79
+ GraphReflyEventExplorer: () => GraphReflyEventExplorer,
80
+ GraphReflyGuard: () => GraphReflyGuard,
81
+ GraphReflyGuardImpl: () => GraphReflyGuardImpl,
82
+ GraphReflyModule: () => GraphReflyModule,
83
+ INTERVAL_HANDLERS: () => INTERVAL_HANDLERS,
84
+ InjectCqrsGraph: () => InjectCqrsGraph,
85
+ InjectGraph: () => InjectGraph,
86
+ InjectNode: () => InjectNode,
87
+ ObserveGateway: () => ObserveGateway,
88
+ OnGraphEvent: () => OnGraphEvent,
89
+ QUERY_HANDLERS: () => QUERY_HANDLERS,
90
+ QueryHandler: () => QueryHandler,
91
+ SAGA_HANDLERS: () => SAGA_HANDLERS,
92
+ SagaHandler: () => SagaHandler,
93
+ fromHeader: () => fromHeader,
94
+ fromJwtPayload: () => fromJwtPayload,
95
+ getActor: () => getActor,
96
+ getGraphToken: () => getGraphToken,
97
+ getNodeToken: () => getNodeToken,
98
+ observeSSE: () => observeSSE,
99
+ observeSubscription: () => observeSubscription,
100
+ toObservable: () => toObservable
101
+ });
102
+ module.exports = __toCommonJS(nestjs_exports);
6
103
 
7
- `)))},o)),i?.aborted?v():i?.addEventListener("abort",v,{once:!0})},pull(l){if(u&&!h){if(p.length>0){let m=p.shift();l.enqueue(m.frame),m.counted&&c.onDequeue();return}return new Promise(m=>{f=m})}},cancel(){try{d?.()}catch{}}})}function gr(r,e,t){let{actor:n,filter:s}=t??{},o=[],i=[],a=!1,d=r.observe(e,{actor:n}),u=t?.highWaterMark!=null?Tt(l=>d.up(l),{highWaterMark:t.highWaterMark,lowWaterMark:t.lowWaterMark??Math.floor(t.highWaterMark/2)}):void 0,c=()=>{a||(a=!0,u?.dispose(),p())},f=l=>{if(!a)if(i.length>0){let m=i.shift();l.done&&l.error?m.reject(l.error):l.done?m.resolve({done:!0,value:void 0}):m.resolve({done:!1,value:l.value})}else o.push(l),l.done||u?.onEnqueue()},p=d.subscribe(l=>{for(let m of l){let g=m[0];if(g===M){let E=m[1];if(s&&!s(E))continue;f({done:!1,value:E})}else if(g===D){let E=m[1]instanceof Error?m[1]:new Error(String(m[1]));f({done:!0,error:E}),c();return}else if(g===G||g===F){f({done:!0}),c();return}}});return{next(){if(o.length>0){let l=o.shift();return l.done||u?.onDequeue(),l.done&&l.error?Promise.reject(l.error):Promise.resolve(l.done?{done:!0,value:void 0}:{done:!1,value:l.value})}return a?Promise.resolve({done:!0,value:void 0}):new Promise((l,m)=>{i.push({resolve:l,reject:m})})},return(){c();for(let l of i)l.resolve({done:!0,value:void 0});return i.length=0,Promise.resolve({done:!0,value:void 0})},throw(l){return c(),Promise.reject(l)},[Symbol.asyncIterator](){return this}}}var Et=class{constructor(e,t){this.graph=e;this.extractActor=t?.extractActor??(()=>{}),this.parse=t?.parse??Rs,this.highWaterMark=t?.highWaterMark,this.lowWaterMark=t?.lowWaterMark}clients=new Map;extractActor;parse;highWaterMark;lowWaterMark;handleConnection(e){this.clients.has(e)||this.clients.set(e,new Map)}handleDisconnect(e){let t=this.clients.get(e);if(t){for(let n of t.values())n.wm?.dispose(),n.unsub();this.clients.delete(e)}}handleMessage(e,t,n){let s=n??Ss.bind(null,e),o;try{o=typeof t=="string"?this.parse(t):t}catch{s({type:"err",message:"invalid command"});return}o.type==="subscribe"?this.subscribe(e,o.path,s):o.type==="unsubscribe"?this.unsubscribe(e,o.path,s):o.type==="ack"?this.ack(e,o.path,o.count??1):s({type:"err",message:`unknown command type: ${o.type}`})}subscriptionCount(e){return this.clients.get(e)?.size??0}destroy(){for(let[e]of this.clients)this.handleDisconnect(e)}subscribe(e,t,n){let s=this.clients.get(e);if(s||(s=new Map,this.clients.set(e,s)),s.has(t)){n({type:"subscribed",path:t});return}let o=this.extractActor(e),i;try{i=this.graph.observe(t,{actor:o})}catch(c){let f=c instanceof Error?c.message:String(c);n({type:"err",message:f});return}let a=this.highWaterMark!=null?Tt(c=>i.up(c),{highWaterMark:this.highWaterMark,lowWaterMark:this.lowWaterMark??Math.floor(this.highWaterMark/2)}):void 0,d=()=>{a?.dispose(),u(),s.delete(t)},u=i.subscribe(c=>{for(let f of c){let p=f[0];if(p===M)a?.onEnqueue(),rn(n,{type:"data",path:t,value:f[1]});else if(p===D){let h=f[1]instanceof Error?f[1].message:String(f[1]);rn(n,{type:"error",path:t,error:h}),d();return}else if(p===G||p===F){rn(n,{type:"complete",path:t}),d();return}}});s.set(t,{unsub:u,wm:a}),n({type:"subscribed",path:t})}unsubscribe(e,t,n){let s=this.clients.get(e),o=s?.get(t);o&&(o.wm?.dispose(),o.unsub(),s.delete(t)),n({type:"unsubscribed",path:t})}ack(e,t,n){let s=this.clients.get(e)?.get(t);if(!s?.wm)return;let o=Math.min(Math.max(0,Math.floor(n)),1024);for(let i=0;i<o;i++)s.wm.onDequeue()}};function ks(r){if(r instanceof Error)return r.message;try{return JSON.stringify(r)}catch{return String(r)}}function nn(r,e){let t=`event: ${r}
8
- `;if(e!==void 0)for(let n of e.split(`
9
- `))t+=`data: ${n}
10
- `;return t+=`
11
- `,t}function Rs(r){return JSON.parse(r)}function Ss(r,e){try{r.send(JSON.stringify(e))}catch{}}function rn(r,e){try{r(e)}catch{}}Ze();var Ot="graphReflyActor";function sn(r){return e=>{let n=e.switchToHttp().getRequest()?.user;if(n!=null)return r?r(n):n}}function mr(r="x-graphrefly-actor"){return e=>{let n=e.switchToHttp().getRequest()?.headers?.[r.toLowerCase()];if(!(typeof n!="string"||n.length===0))try{return JSON.parse(n)}catch{return}}}function yr(r){let e=r?.[Ot];return e!=null?we(e):pe}var st=class{constructor(e){this.extractor=e}canActivate(e){let t=we(this.extractor(e)),n=e.switchToHttp().getRequest();return n!=null&&(n[Ot]=t),!0}};function br(r){return new st(r??sn())}var lt=require("@nestjs/common"),Xr=require("@nestjs/core");Mt();_e();xe();Ze();xe();ne();un();ke();Be();tt();_e();xe();ne();Be();Mt();tt();ne();ke();Be();var gn=class{_version=0;_maxSize;_buf;_head=0;_size=0;constructor(e,t){if(t!==void 0&&t<1)throw new RangeError("maxSize must be >= 1");if(this._maxSize=t,t!==void 0){if(this._buf=new Array(t),e&&e.length>0){let n=Math.min(e.length,t),s=e.length-n;for(let o=0;o<n;o++)this._buf[o]=e[s+o];this._size=n}}else this._buf=e?[...e]:[],this._size=this._buf.length}get version(){return this._version}get size(){return this._size}at(e){if(!Number.isInteger(e))return;let t=e>=0?e:this._size+e;if(!(t<0||t>=this._size))return this._maxSize!==void 0?this._buf[(this._head+t)%this._maxSize]:this._buf[t]}append(e){this._rawAppend(e),this._version+=1}appendMany(e){if(e.length===0)return;let t=this._maxSize!==void 0&&e.length>this._maxSize?e.length-this._maxSize:0;for(let n=t;n<e.length;n++)this._rawAppend(e[n]);this._version+=1}clear(){if(this._size===0)return 0;let e=this._size;if(this._maxSize===void 0)this._buf.length=0;else for(let t=0;t<e;t++)this._buf[(this._head+t)%this._maxSize]=void 0;return this._head=0,this._size=0,this._version+=1,e}trimHead(e){if(!Number.isInteger(e)||e<0)throw new RangeError(`trimHead: n must be a non-negative integer (got ${e})`);if(e===0||this._size===0)return 0;let t=Math.min(e,this._size);if(this._maxSize===void 0)this._buf.splice(0,t);else{for(let n=0;n<t;n++)this._buf[(this._head+n)%this._maxSize]=void 0;this._head=(this._head+t)%this._maxSize}return this._size-=t,this._version+=1,t}slice(e,t){if(!Number.isInteger(e)||e<0)throw new RangeError(`slice: start must be a non-negative integer (got ${e})`);if(t!==void 0&&(!Number.isInteger(t)||t<0))throw new RangeError(`slice: stop must be a non-negative integer or undefined (got ${t})`);let n=t===void 0?this._size:Math.min(Math.max(t,0),this._size),s=Math.min(e,this._size);if(s>=n)return[];let o=n-s;if(this._maxSize===void 0)return this._buf.slice(s,n);let i=new Array(o);for(let a=0;a<o;a++)i[a]=this._buf[(this._head+s+a)%this._maxSize];return i}tail(e){if(!Number.isInteger(e)||e<0)throw new RangeError(`tail: n must be a non-negative integer (got ${e})`);if(e===0||this._size===0)return[];let t=Math.min(e,this._size);return this.slice(this._size-t,this._size)}toArray(){if(this._maxSize===void 0)return[...this._buf];let e=new Array(this._size);for(let t=0;t<this._size;t++)e[t]=this._buf[(this._head+t)%this._maxSize];return e}snapshot(){return this.toArray()}restore(e){if(this._maxSize===void 0){this._buf.length=0;for(let t=0;t<e.length;t++)this._buf.push(e[t]);this._size=this._buf.length}else{let t=this._maxSize;for(let o=0;o<t;o++)this._buf[o]=void 0;this._head=0;let n=Math.min(e.length,t),s=e.length-n;for(let o=0;o<n;o++)this._buf[o]=e[s+o];this._size=n}this._version+=1}_rawAppend(e){if(this._maxSize===void 0){this._buf.push(e),this._size=this._buf.length;return}this._size<this._maxSize?(this._buf[(this._head+this._size)%this._maxSize]=e,this._size+=1):(this._buf[this._head]=e,this._head=(this._head+1)%this._maxSize)}};function it(r){return r.subscribe(()=>{})}var Ys=64;function at(r,e={}){let{name:t,maxSize:n,versioning:s,guard:o,backend:i}=e,a=i??new gn(r,n),d=U(a.toArray(),{name:t,describeKind:"state",equals:(y,O)=>y===O,...s!=null?{versioning:s}:{},...o!=null?{guard:o}:{}});function u(){let y=a.toArray();Oe(()=>{d.down([[j]],{internal:!0}),d.down([[M,y]],{internal:!0})})}let c=new Map,f=new Map,p=new Map;function h(y,O){return`${y}:${O===void 0?"END":O}`}function l(y){if(y.size<Ys)return;let O=y.keys().next();if(O.done)return;let k=y.get(O.value);k!==void 0&&k.dispose(),y.delete(O.value)}function m(y){let O=a.version;try{return y()}finally{a.version!==O&&u()}}function g(y){if(!Number.isInteger(y)||y<0)throw new RangeError(`tail: n must be a non-negative integer (got ${y})`);let O=c.get(y);if(O!==void 0)return c.delete(y),c.set(y,O),O.node;l(c);let k=Y([d],([T])=>{let R=T;return y===0||R.length===0?[]:R.slice(Math.max(0,R.length-y))},{initial:a.tail(y),describeKind:"derived"}),x=it(k);return c.set(y,{node:k,dispose:x}),k}function E(y,O){if(!Number.isInteger(y)||y<0)throw new RangeError(`slice: start must be a non-negative integer (got ${y})`);if(O!==void 0&&(!Number.isInteger(O)||O<0))throw new RangeError(`slice: stop must be a non-negative integer or undefined (got ${O})`);let k=h(y,O),x=f.get(k);if(x!==void 0)return f.delete(k),f.set(k,x),x.node;l(f);let T=Y([d],([C])=>{let S=C;return O===void 0?S.slice(y):S.slice(y,O)},{initial:a.slice(y,O),describeKind:"derived"}),R=it(T);return f.set(k,{node:T,dispose:R}),T}function v(y){let O=p.get(y);if(O!==void 0)return O.node;let k=Y([d,y],([T,R])=>{let C=T,S=Math.max(0,Math.trunc(R??0));return C.slice(S)},{initial:[],describeKind:"derived"}),x=it(k);return p.set(y,{node:k,dispose:x}),k}let _,b;function w(){_===void 0&&(_=ue([d],(y,O,k)=>{let x=y[0],R=x!=null&&x.length>0?x.at(-1):k.prevData[0];if(R==null||R.length===0){O.down([[W]]);return}O.emit(R[R.length-1])},{name:t!=null?`${t}::lastValue`:"lastValue",describeKind:"derived",initial:a.size===0?void 0:a.at(a.size-1)}),b=Y([d],([y])=>y.length>0,{name:t!=null?`${t}::hasLatest`:"hasLatest",describeKind:"derived",initial:a.size>0}),it(_),it(b))}let N={entries:d,get size(){return a.size},at(y){return a.at(y)},append(y){m(()=>a.append(y))},appendMany(y){y.length!==0&&m(()=>a.appendMany(y))},clear(){m(()=>a.clear())},trimHead(y){m(()=>a.trimHead(y))},withLatest(){return w(),d},get lastValue(){return w(),_},get hasLatest(){return w(),b},view(y){switch(y.kind){case"tail":return g(y.n);case"slice":return E(y.start,y.stop);case"fromCursor":return v(y.cursor)}},attach(y){let O=y.subscribe(k=>{for(let x of k)x[0]===M&&N.append(x[1])});return()=>O()},attachStorage(y){if(y.length===0)return()=>{};let O=new Map;for(let x of y)O.set(x,a.size);(async()=>{for(let x of y)if(typeof x.loadEntries=="function")try{let T=await Promise.resolve(x.loadEntries());T.entries.length>0&&a.size===0&&(a.restore(T.entries),O.set(x,T.entries.length),u());break}catch{}})();let k=d.subscribe(x=>{for(let T of x){if(T[0]!==M)continue;let R=T[1];for(let C of y){let S=O.get(C)??0;if(R.length<S){try{let z=C.appendEntries(R);z instanceof Promise&&z.catch(()=>{})}catch{}O.set(C,R.length);continue}if(R.length===S)continue;let H=R.slice(S);O.set(C,R.length);try{let z=C.appendEntries(H);z instanceof Promise&&z.catch(()=>{})}catch{}}}});return()=>k()},disposeAllViews(){for(let y of c.values())y.dispose();c.clear();for(let y of f.values())y.dispose();f.clear();for(let y of p.values())y.dispose();p.clear()},dispose(){for(let y of c.values())y.dispose();c.clear();for(let y of f.values())y.dispose();f.clear();for(let y of p.values())y.dispose();p.clear()}};return N}var Js=je((r,e)=>{r("observe"),r("signal"),e("write")});function Gt(r){let e=at([],{name:r.name,maxSize:r.retainedLimit??1024,guard:r.guard??Js,...r.versioning!=null?{versioning:r.versioning}:{}});return e.withLatest(),r.graph&&r.graph.add(e.entries,{name:r.name}),e}function mn(r){if(r===null||typeof r!="object"||Object.isFrozen(r))return r;for(let e of Object.keys(r))mn(r[e]);return Object.freeze(r)}var Hr=new WeakSet;function qr(r){let e=r.cache,t=typeof e=="number"&&Number.isFinite(e);!t&&e!==void 0&&!Hr.has(r)&&(Hr.add(r),console.warn(`bumpCursor: cursor cache held a non-numeric value (${String(e)}); resetting to 0. Causes include: a snapshot codec round-tripping the cursor as a string / null / NaN, OR a malformed initial seed (e.g. state<number>(NaN)). Audit consumers may see colliding seq values after this point.`));let s=(t?e:0)+1;return r.down([[j],[M,s]]),s}function Dt(r,e,t,n,s,o){let i=e(t,n,s);if(i===void 0)return;let a=o!=null?{...i,handlerVersion:o}:i;r.append(a)}function Vr(r,e){let t=e.freeze??!0;return function(...s){let o=t?s.map(mn):s,i=se(),a=e.seq?qr(e.seq):void 0;try{let d=r(...o);return e.audit&&e.onSuccess&&Dt(e.audit,e.onSuccess,o,d,{t_ns:i,seq:a},e.handlerVersion),d}catch(d){if(e.audit&&e.onFailure){let u=d instanceof Error?d.name:typeof d;Dt(e.audit,e.onFailure,o,d,{t_ns:i,seq:a,errorType:u},e.handlerVersion)}throw d}}}function zr(r,e){let t=e.freeze??!0;return function(...s){let o=t?s.map(mn):s,i=se(),a,d,u=!1,c;try{Oe(()=>{e.seq&&(c=qr(e.seq));try{a=r(...o),e.audit&&e.onSuccess&&Dt(e.audit,e.onSuccess,o,a,{t_ns:i,seq:c},e.handlerVersion)}catch(f){throw d=f,u=!0,f}})}catch(f){if(u&&e.audit&&e.onFailure){let p=d instanceof Error?d.name:typeof d;Dt(e.audit,e.onFailure,o,d,{t_ns:i,seq:c,errorType:p},e.handlerVersion)}throw u?d:f}return a}}function jr(r,e,t=0){let n=U(t,{name:e,describeKind:"state"});return r.add(n,{name:e}),n}function Br(r,e,t,n=0){let s={},o=new ae(e);for(let i of t){let a=U(n,{name:i,describeKind:"state"});o.add(a,{name:i}),s[i]=a}return r.mount(e,o),s}Wr();var ge=class extends Error{constructor(e,t){super(e,t),this.name=this.constructor.name}},It=class extends ge{constructor(t,n){super(`Duplicate ${t} registration: "${n}"`);this.kind=t;this.registrationName=n}},Pt=class extends ge{constructor(t,n,s){super(`Command "${t}" emitted undeclared event "${n}". Declared emits: [${s.join(", ")}]`);this.commandName=t;this.eventName=n;this.declaredEmits=s}},Lt=class extends ge{constructor(t,n,s){super(`Optimistic concurrency conflict on aggregate "${t}": expected version ${n}, got ${s}`);this.aggregateId=t;this.expected=n;this.actual=s}},$t=class extends ge{constructor(t){super(`Unknown command: "${t}". Register with command() first.`);this.commandName=t}},dt=class extends ge{constructor(t,n){super(`Command handler "${t}" threw: ${n instanceof Error?n.message:String(n)}`,{cause:n});this.commandName=t}};var ut=class extends ge{constructor(t,n){super(`Projection "${t}" rebuild failed: ${n instanceof Error?n.message:String(n)}`,{cause:n});this.projectionName=t}};Ur();wt();var Qs=je((r,e)=>{r("write"),r("signal"),e("observe")}),Zs=je((r,e)=>{r("observe"),r("signal"),e("write")}),Yr=je((r,e)=>{r("observe"),r("signal"),e("write")});function ct(r,e){return Kr("cqrs",r,e)}function Jr(r){if(r===null||typeof r!="object"||Object.isFrozen(r))return r;for(let e of Object.keys(r))Jr(r[e]);return Object.freeze(r)}var yn=class extends ae{_eventLogs=new Map;_eventLogsByAggregate=new Map;_aggregateVersions=new Map;_aggregateLru=new Map;_commandRegs=new Map;_projections=new Set;_sagas=new Set;_keepaliveDisposers=[];_seq=0;_retainedLimit;_freezeCommandPayload;_freezeEventPayload;_maxAggregates;_dispatchSeqCursor;dispatches;audit;aggregateEvictions;constructor(e,t={}){super(e,t.graph),this._retainedLimit=t.retainedLimit??1024,this._freezeCommandPayload=t.freezeCommandPayload??!0,this._freezeEventPayload=t.freezeEventPayload??!0,this._maxAggregates=t.maxAggregates??1e4,this.dispatches=Gt({name:"dispatches",retainedLimit:this._retainedLimit,graph:this}),this.audit=this.dispatches,this.aggregateEvictions=Gt({name:"aggregateEvictions",retainedLimit:this._retainedLimit,graph:this}),this._dispatchSeqCursor=jr(this,"dispatch_seq",0)}aggregateVersion(e,t){return this._aggregateVersions.get(`${e}::${t}`)??0}_touchAggregate(e){this._aggregateLru.delete(e),this._aggregateLru.set(e,!0)}_enforceAggregateLru(){for(;this._aggregateLru.size>this._maxAggregates;){let e=this._aggregateLru.keys().next();if(e.done)break;let t=e.value;this._aggregateLru.delete(t);let n=t.indexOf("::");if(n<0)continue;let s=t.slice(0,n),o=t.slice(n+2),i=this._aggregateVersions.get(t)??0;this._aggregateVersions.delete(t);let a=this._eventLogsByAggregate.get(s);a&&(a.delete(o),a.size===0&&this._eventLogsByAggregate.delete(s)),this.aggregateEvictions.append({aggregateId:o,type:s,lastVersion:i,t_ns:se()})}}destroy(){for(let e of this._keepaliveDisposers)e();this._keepaliveDisposers.length=0,super.destroy()}_attachedEventTiers=[];_attachedTierDisposers=new Map;attachEventStorage(e){this._attachedEventTiers.push(e);for(let[t,n]of this._eventLogs){let s=n.log.attachStorage(e),o=this._attachedTierDisposers.get(t);o||(o=[],this._attachedTierDisposers.set(t,o)),o.push(s)}for(let[t,n]of this._eventLogsByAggregate)for(let[s,o]of n){let i=`${t}::${s}`,a=o.log.attachStorage(e),d=this._attachedTierDisposers.get(i);d||(d=[],this._attachedTierDisposers.set(i,d)),d.push(a)}return()=>{let t=this._attachedEventTiers.indexOf(e);t>=0&&this._attachedEventTiers.splice(t,1)}}_autoWireStreamStorage(e,t){if(this._attachedEventTiers.length===0)return;let n=this._attachedTierDisposers.get(e);n||(n=[],this._attachedTierDisposers.set(e,n));for(let s of this._attachedEventTiers)n.push(t.attachStorage(s))}event(e,t){if(t!==void 0)return this._ensureAggregateStream(e,t).node;let n=this._eventLogs.get(e);if(n)return n.node;let s=at([],{name:e,versioning:0,maxSize:this._retainedLimit});s.withLatest();let o=s.entries,i=Y([o],([a])=>a,{name:e,describeKind:"state",meta:ct("event",{event_name:e}),guard:Yr,initial:o.cache});return this.add(i,{name:e}),this._keepaliveDisposers.push(fe(i)),this._eventLogs.set(e,{log:s,node:i}),this._autoWireStreamStorage(e,s),i}_ensureAggregateStream(e,t){this._eventLogs.has(e)||this.event(e);let n=this._eventLogsByAggregate.get(e);n||(n=new Map,this._eventLogsByAggregate.set(e,n));let s=`${e}::${t}`;this._touchAggregate(s);let o=n.get(t);if(o)return o;let i=`${e}_${t.replace(/[^a-zA-Z0-9_-]/g,"_")}`,a=at([],{name:i,versioning:0,maxSize:this._retainedLimit});a.withLatest();let d=a.entries,u=Y([d],([h])=>h,{name:i,describeKind:"state",meta:ct("event_aggregate",{event_name:e,aggregate_id:t}),guard:Yr,initial:d.cache}),c=i,f=0;for(;this.nameOf(this.resolveOptional(c)??u)===c&&(f+=1,c=`${i}_${f}`,this.resolveOptional(c)!==void 0););try{this.add(u,{name:c})}catch{}this._keepaliveDisposers.push(fe(u));let p={log:a,node:u};return n.set(t,p),this._autoWireStreamStorage(`${e}::${t}`,a),this._enforceAggregateLru(),p}resolveOptional(e){try{return this.resolve(e)}catch{return}}_appendEvent(e,t,n){let s=this._eventLogs.get(e);if(s||(this.event(e),s=this._eventLogs.get(e)),s.node.status==="completed"||s.node.status==="errored")throw new Error(`Cannot dispatch to terminated event stream "${e}" (status: ${s.node.status}).`);let o,i;if(n?.aggregateId!==void 0){let c=`${e}::${n.aggregateId}`;o=(this._aggregateVersions.get(c)??0)+1,this._aggregateVersions.set(c,o),i=this._ensureAggregateStream(e,n.aggregateId)}let a=s.log.entries.v,d=this._freezeEventPayload?Jr(t):t,u={type:e,payload:d,timestampNs:se(),seq:++this._seq,...n?.aggregateId!==void 0?{aggregateId:n.aggregateId}:{},...o!==void 0?{aggregateVersion:o}:{},...n?.correlationId!==void 0?{correlationId:n.correlationId}:{},...n?.causationId!==void 0?{causationId:n.causationId}:{},...n?.metadata!==void 0?{metadata:Object.freeze({...n.metadata})}:{},...n?.handlerVersion!==void 0?{handlerVersion:n.handlerVersion}:{},...a!=null?{v0:{id:a.id,version:a.version}}:{}};return s.log.append(u),i&&i.log.append(u),u}command(e,t){if(this._commandRegs.has(e))throw new It("command",e);let n=typeof t=="function"?{handler:t}:t,s=U(void 0,{name:e,describeKind:"state",meta:{...ct("command",{command_name:e}),error:null},guard:Qs});if(this.add(s,{name:e}),this._commandRegs.set(e,{handler:n.handler,...n.emits!==void 0?{emits:n.emits}:{},...n.handlerVersion!==void 0?{handlerVersion:n.handlerVersion}:{}}),n.emits)for(let o of n.emits)this._eventLogs.has(o)||this.event(o);return s}dispatch(e,t,n){let s=this._commandRegs.get(e);if(!s)throw new $t(e);if(n?.aggregateId!==void 0&&n.expectedAggregateVersion!==void 0&&s.emits!==void 0){let u=0;for(let c of s.emits){let f=this._aggregateVersions.get(`${c}::${n.aggregateId}`);f!==void 0&&f>u&&(u=f)}if(u!==n.expectedAggregateVersion)throw new Lt(n.aggregateId,n.expectedAggregateVersion,u)}let o=this.resolve(e),i=[],a=!1,d=u=>{o.emit(u,{internal:!0});try{s.handler(u,{emit:(c,f)=>{if(s.emits!==void 0&&!s.emits.includes(c))throw new Pt(e,c,s.emits);i.push(c),this._appendEvent(c,f,{...n?.aggregateId!==void 0?{aggregateId:n.aggregateId}:{},...n?.correlationId!==void 0?{correlationId:n.correlationId}:{},...n?.causationId!==void 0?{causationId:n.causationId}:{},...n?.metadata!==void 0?{metadata:Object.freeze({...n.metadata})}:{},...s.handlerVersion!==void 0?{handlerVersion:s.handlerVersion}:{}})}}),o.meta.error.emit(null,{internal:!0})}catch(c){throw a=!0,c}};try{zr(d,{audit:this.dispatches,seq:this._dispatchSeqCursor,freeze:this._freezeCommandPayload,onSuccess:([u],c,{t_ns:f,seq:p})=>({commandName:e,payload:u,outcome:"success",emittedEvents:[...i],t_ns:f,seq:p??0,...s.handlerVersion!==void 0?{handlerVersion:s.handlerVersion}:{}}),onFailure:([u],c,{t_ns:f,seq:p,errorType:h})=>{let l=c instanceof dt?c:new dt(e,c);return{commandName:e,payload:u,outcome:"failure",error:l,errorType:h,emittedEvents:[...i],t_ns:f,seq:p??0,...s.handlerVersion!==void 0?{handlerVersion:s.handlerVersion}:{}}}})(t)}catch(u){throw a&&o.meta.error.emit(u,{internal:!0}),u}}projection(e){let{name:t,events:n,reducer:s,initial:o}=e,i=e.mode??"scan",a=e.freezeInputs??!0,d=e.snapshot,u=n.map(x=>(this._eventLogs.has(x)||this.event(x),this._eventLogs.get(x).node));function c(x){x.sort((T,R)=>T.timestampNs-R.timestampNs||T.seq-R.seq||(T.aggregateId??"").localeCompare(R.aggregateId??""))}function f(x){let T=[];for(let R of x)T.push(...R);return c(T),T}let p=u.map(x=>x.cache??[]),h=f(p),l=a?Object.freeze(h):h,m=0,g=o;i==="scan"&&h.length>0&&(g=s(o,l),m=h.length);let E=i==="replay"?s(o,l):g,v=d?.saveDebounceMs??1e3,_=d?.saveEvery??1e3,b,w=0;function N(x){if(d?.save){if(w+=1,w>=_){w=0,b!==void 0&&(clearTimeout(b),b=void 0);let T=d.save(x);T instanceof Promise&&T.catch(()=>{});return}b!==void 0&&clearTimeout(b),b=setTimeout(()=>{b=void 0,w=0;let T=d.save(x);T instanceof Promise&&T.catch(()=>{})},v)}}let y=Y(u,x=>{let T=f(x),R;if(i==="replay"){let C=a?Object.freeze(T):T;R=s(o,C)}else{let C=T.slice(m);m=T.length;let S=a?Object.freeze(C):C;R=s(g,S),g=R}return N(R),R},{name:t,describeKind:"derived",meta:ct("projection",{projection_name:t,source_events:n}),guard:Zs,initial:E});return this.add(y,{name:t}),this._keepaliveDisposers.push(fe(y)),this._keepaliveDisposers.push(()=>{b!==void 0&&(clearTimeout(b),b=void 0)}),this._projections.add(t),{node:y,rebuild:async x=>{try{let T=x?.pageSize??1e3,R=x?.fromTier??this._attachedEventTiers[0]?.[0],C=f(u.map(H=>H.cache??[])).length,S=o;if(d?.load){let H=await d.load();H!==void 0&&(S=H)}if(!R||!R.loadEntries){let H=f(u.map(J=>J.cache??[])),z=a?Object.freeze(H):H;S=s(S,z)}else{let H=new Set(n),z,J=!1;for(;!J;){let Ce=await R.loadEntries({cursor:z,pageSize:T}),Me=[...Ce.entries].filter(Ke=>H.has(Ke.type));c(Me);let We=a?Object.freeze(Me):Me;S=s(S,We),z=Ce.cursor,J=!z||Ce.entries.length===0}}if(i==="scan"){let H=f(u.map(J=>J.cache??[])),z=H.slice(C);if(z.length>0){let J=a?Object.freeze(z):z;S=s(S,J)}g=S,m=H.length}return y.emit(S,{internal:!0}),S}catch(T){throw new ut(t,T)}},reset:async()=>{try{let x=o;if(d?.load){let S=await d.load();S!==void 0&&(x=S)}let T=f(u.map(S=>S.cache??[])),R=a?Object.freeze(T):T,C=s(x,R);return i==="scan"&&(g=C,m=T.length),y.emit(C,{internal:!0}),C}catch(x){throw new ut(t,x)}}}}saga(e,t,n,s={}){let o=t.map(l=>(this._eventLogs.has(l)||this.event(l),this._eventLogs.get(l).node)),i=Br(this,`${e}_cursor`,t,0),a=Gt({name:`${e}_invocations`,retainedLimit:this._retainedLimit,graph:this}),d=s.aggregateId,u=s.errorPolicy??"advance",c=new Map;for(let l of t){let m=i[l];c.set(l,m.cache??0);let g=m.subscribe(E=>{for(let v of E)v[0]===M&&c.set(l,v[1])});this._keepaliveDisposers.push(g)}let f=Vr((l,m)=>{n(l)},{audit:a,freeze:!1,...s.handlerVersion!==void 0?{handlerVersion:s.handlerVersion}:{},onSuccess:([l,m],g,{t_ns:E})=>({eventType:m,outcome:"success",aggregateId:l.aggregateId,event:l,t_ns:E}),onFailure:([l,m],g,{t_ns:E,errorType:v})=>({eventType:m,outcome:"failure",error:g,errorType:v,aggregateId:l.aggregateId,event:l,t_ns:E})}),p={},h=ue(o,(l,m)=>{let g=p.n.meta.error;for(let E=0;E<l.length;E++){let v=l[E];if(v==null||v.length===0)continue;let _=v.at(-1);if(!_)continue;let b=t[E],w=i[b],N=c.get(b)??0;if(_.length>N){let y=_.slice(N),O=N;for(let k of y){let x=k;if(d!==void 0&&x.aggregateId!==d){O+=1;continue}try{f(x,b),g.emit(null,{internal:!0}),O+=1}catch(T){if(g.emit(T,{internal:!0}),u==="hold")break;O+=1}}w.emit(O)}}},{name:e,describeKind:"effect",meta:{...ct("saga",{saga_name:e,source_events:t}),error:null}});return p.n=h,this.add(h,{name:e}),this._keepaliveDisposers.push(fe(h)),this._sagas.add(e),{node:h,invocations:a,audit:a,cursors:i}}};function Qr(r,e){let t=new yn(r,e),{factory:n,factoryArgs:s,...o}=e??{};return t.tagFactory("cqrs",an(o)),t}var vn=class{constructor(e){this.graph=e}onModuleDestroy(){this.graph.destroy()}},_n=class{graph=new ae("request");onModuleDestroy(){this.graph.destroy()}},Zr,bn;Zr=[(0,lt.Module)({})];var me=class me{static forRoot(e){let t=e??{},n=t.name??"root",s=[{provide:re,useFactory:()=>{let o=new ae(n);return t.build&&t.build(o),t.snapshot&&o.restore(t.snapshot),o}},{provide:Symbol.for("graphrefly:root-lifecycle"),useFactory:o=>new vn(o),inject:[re]},{provide:Re,useFactory:(o,i)=>new Re(o,i),inject:[re,Xr.ModuleRef]}];if(t.nodes)for(let o of t.nodes)s.push({provide:de(o),useFactory:i=>i.resolve(o),inject:[re]});return t.requestScope&&s.push({provide:Symbol.for("graphrefly:request-lifecycle"),useFactory:()=>new _n,scope:lt.Scope.REQUEST},{provide:ve,useFactory:o=>o.graph,inject:[Symbol.for("graphrefly:request-lifecycle")],scope:lt.Scope.REQUEST}),{module:me,global:!0,providers:s,exports:[re,...(t.nodes??[]).map(de),...t.requestScope?[ve]:[]]}}static forFeature(e){let t=[{provide:K(e.name),useFactory:n=>{let s=new ae(e.name);return e.build&&e.build(s),e.snapshot&&s.restore(e.snapshot),n.mount(e.name,s),s},inject:[re]}];if(e.nodes)for(let n of e.nodes)t.push({provide:de(`${e.name}::${n}`),useFactory:s=>s.resolve(n),inject:[K(e.name)]});return{module:me,providers:t,exports:[K(e.name),...(e.nodes??[]).map(n=>de(`${e.name}::${n}`))]}}static forCqrs(e){let t=[{provide:K(e.name),useFactory:n=>{let s=Qr(e.name,e.cqrs);return e.eventStorage&&s.attachEventStorage(e.eventStorage),e.build&&e.build(s),n.mount(e.name,s),s},inject:[re]}];if(e.nodes)for(let n of e.nodes)t.push({provide:de(`${e.name}::${n}`),useFactory:s=>s.resolve(n),inject:[K(e.name)]});return{module:me,providers:t,exports:[K(e.name),...(e.nodes??[]).map(n=>de(`${e.name}::${n}`))]}}};bn=kn(null),me=An(bn,0,"GraphReflyModule",Zr,me),Sn(bn,1,me);var Ft=me;0&&(module.exports={ACTOR_KEY,COMMAND_HANDLERS,CQRS_EVENT_HANDLERS,CRON_HANDLERS,CommandHandler,EVENT_HANDLERS,EventHandler,GRAPHREFLY_REQUEST_GRAPH,GRAPHREFLY_ROOT_GRAPH,GraphCron,GraphInterval,GraphReflyEventExplorer,GraphReflyGuard,GraphReflyGuardImpl,GraphReflyModule,INTERVAL_HANDLERS,InjectCqrsGraph,InjectGraph,InjectNode,ObserveGateway,OnGraphEvent,QUERY_HANDLERS,QueryHandler,SAGA_HANDLERS,SagaHandler,fromHeader,fromJwtPayload,getActor,getGraphToken,getNodeToken,observeSSE,observeSubscription,toObservable});
104
+ // src/base/composition/observable.ts
105
+ var import_core = require("@graphrefly/pure-ts/core");
106
+ var import_rxjs = require("rxjs");
107
+ function toObservable(node4, options) {
108
+ if (options?.raw) {
109
+ return new import_rxjs.Observable((subscriber) => {
110
+ const unsub = node4.subscribe((msgs) => {
111
+ if (subscriber.closed) return;
112
+ subscriber.next(msgs);
113
+ for (const m of msgs) {
114
+ if (m[0] === import_core.ERROR) {
115
+ subscriber.error(m[1]);
116
+ return;
117
+ }
118
+ if (m[0] === import_core.COMPLETE) {
119
+ subscriber.complete();
120
+ return;
121
+ }
122
+ }
123
+ });
124
+ return unsub;
125
+ });
126
+ }
127
+ return new import_rxjs.Observable((subscriber) => {
128
+ const unsub = node4.subscribe((msgs) => {
129
+ for (const m of msgs) {
130
+ if (subscriber.closed) return;
131
+ if (m[0] === import_core.DATA) {
132
+ subscriber.next(m[1]);
133
+ } else if (m[0] === import_core.ERROR) {
134
+ subscriber.error(m[1]);
135
+ return;
136
+ } else if (m[0] === import_core.COMPLETE) {
137
+ subscriber.complete();
138
+ return;
139
+ }
140
+ }
141
+ });
142
+ return unsub;
143
+ });
144
+ }
145
+
146
+ // src/compat/nestjs/decorators.ts
147
+ var import_common = require("@nestjs/common");
148
+
149
+ // src/compat/nestjs/tokens.ts
150
+ var GRAPHREFLY_ROOT_GRAPH = /* @__PURE__ */ Symbol.for("graphrefly:root-graph");
151
+ var GRAPHREFLY_REQUEST_GRAPH = /* @__PURE__ */ Symbol.for("graphrefly:request-graph");
152
+ function getGraphToken(name) {
153
+ return /* @__PURE__ */ Symbol.for(`graphrefly:graph:${name}`);
154
+ }
155
+ function getNodeToken(path) {
156
+ return /* @__PURE__ */ Symbol.for(`graphrefly:node:${path}`);
157
+ }
158
+
159
+ // src/compat/nestjs/decorators.ts
160
+ var EVENT_HANDLERS = /* @__PURE__ */ new Map();
161
+ var INTERVAL_HANDLERS = /* @__PURE__ */ new Map();
162
+ var CRON_HANDLERS = /* @__PURE__ */ new Map();
163
+ var COMMAND_HANDLERS = /* @__PURE__ */ new Map();
164
+ var CQRS_EVENT_HANDLERS = /* @__PURE__ */ new Map();
165
+ var QUERY_HANDLERS = /* @__PURE__ */ new Map();
166
+ var SAGA_HANDLERS = /* @__PURE__ */ new Map();
167
+ function InjectGraph(name) {
168
+ if (name === "request") return (0, import_common.Inject)(GRAPHREFLY_REQUEST_GRAPH);
169
+ return (0, import_common.Inject)(name ? getGraphToken(name) : GRAPHREFLY_ROOT_GRAPH);
170
+ }
171
+ function InjectCqrsGraph(name) {
172
+ return (0, import_common.Inject)(getGraphToken(name));
173
+ }
174
+ function InjectNode(path) {
175
+ return (0, import_common.Inject)(getNodeToken(path));
176
+ }
177
+ function OnGraphEvent(nodeName) {
178
+ return (_value, context) => {
179
+ const methodKey = context.name;
180
+ context.addInitializer(function() {
181
+ const ctor = this.constructor;
182
+ const existing = EVENT_HANDLERS.get(ctor) ?? [];
183
+ existing.push({ nodeName, methodKey });
184
+ EVENT_HANDLERS.set(ctor, existing);
185
+ });
186
+ };
187
+ }
188
+ function GraphInterval(ms) {
189
+ return (_value, context) => {
190
+ const methodKey = context.name;
191
+ context.addInitializer(function() {
192
+ const ctor = this.constructor;
193
+ const existing = INTERVAL_HANDLERS.get(ctor) ?? [];
194
+ existing.push({ ms, methodKey });
195
+ INTERVAL_HANDLERS.set(ctor, existing);
196
+ });
197
+ };
198
+ }
199
+ function GraphCron(expr) {
200
+ return (_value, context) => {
201
+ const methodKey = context.name;
202
+ context.addInitializer(function() {
203
+ const ctor = this.constructor;
204
+ const existing = CRON_HANDLERS.get(ctor) ?? [];
205
+ existing.push({ expr, methodKey });
206
+ CRON_HANDLERS.set(ctor, existing);
207
+ });
208
+ };
209
+ }
210
+ function CommandHandler(cqrsName, commandName) {
211
+ return (_value, context) => {
212
+ const methodKey = context.name;
213
+ context.addInitializer(function() {
214
+ const ctor = this.constructor;
215
+ const existing = COMMAND_HANDLERS.get(ctor) ?? [];
216
+ existing.push({ cqrsName, commandName, methodKey });
217
+ COMMAND_HANDLERS.set(ctor, existing);
218
+ });
219
+ };
220
+ }
221
+ function EventHandler(cqrsName, eventName) {
222
+ return (_value, context) => {
223
+ const methodKey = context.name;
224
+ context.addInitializer(function() {
225
+ const ctor = this.constructor;
226
+ const existing = CQRS_EVENT_HANDLERS.get(ctor) ?? [];
227
+ existing.push({ cqrsName, eventName, methodKey });
228
+ CQRS_EVENT_HANDLERS.set(ctor, existing);
229
+ });
230
+ };
231
+ }
232
+ function QueryHandler(cqrsName, projectionName) {
233
+ return (_value, context) => {
234
+ const methodKey = context.name;
235
+ context.addInitializer(function() {
236
+ const ctor = this.constructor;
237
+ const existing = QUERY_HANDLERS.get(ctor) ?? [];
238
+ existing.push({ cqrsName, projectionName, methodKey });
239
+ QUERY_HANDLERS.set(ctor, existing);
240
+ });
241
+ };
242
+ }
243
+ function SagaHandler(cqrsName, sagaName, eventNames) {
244
+ return (_value, context) => {
245
+ const methodKey = context.name;
246
+ context.addInitializer(function() {
247
+ const ctor = this.constructor;
248
+ const existing = SAGA_HANDLERS.get(ctor) ?? [];
249
+ existing.push({ cqrsName, eventNames, sagaName, methodKey });
250
+ SAGA_HANDLERS.set(ctor, existing);
251
+ });
252
+ };
253
+ }
254
+
255
+ // src/compat/nestjs/explorer.ts
256
+ var import_core3 = require("@graphrefly/pure-ts/core");
257
+ var import_extra = require("@graphrefly/pure-ts/extra");
258
+
259
+ // src/base/sources/event/cron.ts
260
+ var import_core2 = require("@graphrefly/pure-ts/core");
261
+ function sourceOpts(opts) {
262
+ return { describeKind: "producer", ...opts };
263
+ }
264
+ function parseField(field, min, max) {
265
+ const result = /* @__PURE__ */ new Set();
266
+ for (const part of field.split(",")) {
267
+ const [range, stepStr] = part.split("/");
268
+ const step = stepStr ? Number.parseInt(stepStr, 10) : 1;
269
+ if (Number.isNaN(step) || step < 1) throw new Error(`Invalid cron step: ${part}`);
270
+ let start;
271
+ let end;
272
+ if (range === "*") {
273
+ start = min;
274
+ end = max;
275
+ } else if (range.includes("-")) {
276
+ const [a, b] = range.split("-");
277
+ start = Number.parseInt(a, 10);
278
+ end = Number.parseInt(b, 10);
279
+ } else {
280
+ start = Number.parseInt(range, 10);
281
+ end = start;
282
+ }
283
+ if (Number.isNaN(start) || Number.isNaN(end)) throw new Error(`Invalid cron field: ${field}`);
284
+ if (start < min || end > max)
285
+ throw new Error(`Cron field out of range: ${field} (${min}-${max})`);
286
+ if (start > end) throw new Error(`Invalid cron range: ${start}-${end} in ${field}`);
287
+ for (let i = start; i <= end; i += step) result.add(i);
288
+ }
289
+ return result;
290
+ }
291
+ function parseCron(expr) {
292
+ const parts = expr.trim().split(/\s+/);
293
+ if (parts.length !== 5) throw new Error(`Invalid cron: expected 5 fields, got ${parts.length}`);
294
+ return {
295
+ minutes: parseField(parts[0], 0, 59),
296
+ hours: parseField(parts[1], 0, 23),
297
+ daysOfMonth: parseField(parts[2], 1, 31),
298
+ months: parseField(parts[3], 1, 12),
299
+ daysOfWeek: parseField(parts[4], 0, 6)
300
+ };
301
+ }
302
+ function matchesCron(schedule, date) {
303
+ return schedule.minutes.has(date.getMinutes()) && schedule.hours.has(date.getHours()) && schedule.daysOfMonth.has(date.getDate()) && schedule.months.has(date.getMonth() + 1) && schedule.daysOfWeek.has(date.getDay());
304
+ }
305
+ function fromCron(expr, opts) {
306
+ const schedule = parseCron(expr);
307
+ const { tickMs: tickOpt, output, ...rest } = opts ?? {};
308
+ const tickMs = tickOpt ?? 6e4;
309
+ const emitDate = output === "date";
310
+ return (0, import_core2.node)(
311
+ (_data, a) => {
312
+ let lastFiredKey = -1;
313
+ const check = () => {
314
+ const now = /* @__PURE__ */ new Date();
315
+ const key = now.getFullYear() * 1e8 + (now.getMonth() + 1) * 1e6 + now.getDate() * 1e4 + now.getHours() * 100 + now.getMinutes();
316
+ if (key !== lastFiredKey && matchesCron(schedule, now)) {
317
+ lastFiredKey = key;
318
+ a.emit(emitDate ? now : (0, import_core2.wallClockNs)());
319
+ }
320
+ };
321
+ check();
322
+ const id = setInterval(check, tickMs);
323
+ return () => clearInterval(id);
324
+ },
325
+ { ...sourceOpts(rest), name: rest.name ?? `cron:${expr}` }
326
+ );
327
+ }
328
+
329
+ // src/compat/nestjs/explorer.ts
330
+ var scheduleSeq = 0;
331
+ var GraphReflyEventExplorer = class {
332
+ constructor(graph, moduleRef) {
333
+ this.graph = graph;
334
+ this.moduleRef = moduleRef;
335
+ }
336
+ disposers = [];
337
+ scheduleNodeNames = [];
338
+ onModuleInit() {
339
+ this.wireEvents();
340
+ this.wireIntervals();
341
+ this.wireCrons();
342
+ this.wireCqrsCommands();
343
+ this.wireCqrsEvents();
344
+ this.wireCqrsQueries();
345
+ this.wireCqrsSagas();
346
+ }
347
+ onModuleDestroy() {
348
+ for (const dispose of this.disposers) dispose();
349
+ this.disposers.length = 0;
350
+ for (const name of this.scheduleNodeNames) {
351
+ try {
352
+ this.graph.remove(name);
353
+ } catch {
354
+ }
355
+ }
356
+ this.scheduleNodeNames.length = 0;
357
+ }
358
+ // -----------------------------------------------------------------------
359
+ // @OnGraphEvent — reactive subscription via graph.observe()
360
+ // -----------------------------------------------------------------------
361
+ wireEvents() {
362
+ for (const [ctor, metas] of EVENT_HANDLERS) {
363
+ const instance = this.resolveInstance(ctor);
364
+ if (!instance) continue;
365
+ for (const meta of metas) {
366
+ this.wireEventHandler(instance, meta);
367
+ }
368
+ }
369
+ }
370
+ wireEventHandler(instance, meta) {
371
+ const method = instance[meta.methodKey];
372
+ if (typeof method !== "function") return;
373
+ const bound = method.bind(instance);
374
+ const handle = this.observeNode(meta.nodeName);
375
+ const unsub = handle.subscribe((msgs) => {
376
+ for (const m of msgs) {
377
+ if (m[0] === import_core3.DATA) {
378
+ bound(m[1]);
379
+ }
380
+ }
381
+ });
382
+ this.disposers.push(unsub);
383
+ }
384
+ // -----------------------------------------------------------------------
385
+ // @GraphInterval — reactive via fromTimer central timer primitive
386
+ // -----------------------------------------------------------------------
387
+ wireIntervals() {
388
+ for (const [ctor, metas] of INTERVAL_HANDLERS) {
389
+ const instance = this.resolveInstance(ctor);
390
+ if (!instance) continue;
391
+ for (const meta of metas) {
392
+ this.wireIntervalHandler(instance, ctor, meta);
393
+ }
394
+ }
395
+ }
396
+ wireIntervalHandler(instance, ctor, meta) {
397
+ const method = instance[meta.methodKey];
398
+ if (typeof method !== "function") return;
399
+ const bound = method.bind(instance);
400
+ const className = ctor.name ?? "anonymous";
401
+ const nodeName = `__schedule__.${className}.${String(meta.methodKey)}.${scheduleSeq++}`;
402
+ const timerNode = (0, import_extra.fromTimer)(meta.ms, { period: meta.ms, name: nodeName });
403
+ this.graph.add(timerNode);
404
+ this.scheduleNodeNames.push(nodeName);
405
+ const handle = this.observeNode(nodeName);
406
+ const unsub = handle.subscribe((msgs) => {
407
+ for (const m of msgs) {
408
+ if (m[0] === import_core3.DATA) bound(m[1]);
409
+ }
410
+ });
411
+ this.disposers.push(unsub);
412
+ }
413
+ // -----------------------------------------------------------------------
414
+ // @GraphCron — reactive via fromCron central timer primitive
415
+ // -----------------------------------------------------------------------
416
+ wireCrons() {
417
+ for (const [ctor, metas] of CRON_HANDLERS) {
418
+ const instance = this.resolveInstance(ctor);
419
+ if (!instance) continue;
420
+ for (const meta of metas) {
421
+ this.wireCronHandler(instance, ctor, meta);
422
+ }
423
+ }
424
+ }
425
+ wireCronHandler(instance, ctor, meta) {
426
+ const method = instance[meta.methodKey];
427
+ if (typeof method !== "function") return;
428
+ const bound = method.bind(instance);
429
+ const className = ctor.name ?? "anonymous";
430
+ const nodeName = `__schedule__.${className}.${String(meta.methodKey)}.${scheduleSeq++}`;
431
+ const cronNode = fromCron(meta.expr, { name: nodeName });
432
+ this.graph.add(cronNode);
433
+ this.scheduleNodeNames.push(nodeName);
434
+ const handle = this.observeNode(nodeName);
435
+ const unsub = handle.subscribe((msgs) => {
436
+ for (const m of msgs) {
437
+ if (m[0] === import_core3.DATA) bound(m[1]);
438
+ }
439
+ });
440
+ this.disposers.push(unsub);
441
+ }
442
+ // -----------------------------------------------------------------------
443
+ // @CommandHandler — register method as CqrsGraph command handler
444
+ // -----------------------------------------------------------------------
445
+ wireCqrsCommands() {
446
+ for (const [ctor, metas] of COMMAND_HANDLERS) {
447
+ const instance = this.resolveInstance(ctor);
448
+ if (!instance) continue;
449
+ for (const meta of metas) {
450
+ this.wireCqrsCommand(instance, meta);
451
+ }
452
+ }
453
+ }
454
+ wireCqrsCommand(instance, meta) {
455
+ const method = instance[meta.methodKey];
456
+ if (typeof method !== "function") return;
457
+ const bound = method.bind(instance);
458
+ const cqrsGraph = this.resolveCqrsGraph(meta.cqrsName);
459
+ if (!cqrsGraph) return;
460
+ cqrsGraph.command(meta.commandName, bound);
461
+ }
462
+ // -----------------------------------------------------------------------
463
+ // @EventHandler — subscribe method to CQRS event stream
464
+ // -----------------------------------------------------------------------
465
+ wireCqrsEvents() {
466
+ for (const [ctor, metas] of CQRS_EVENT_HANDLERS) {
467
+ const instance = this.resolveInstance(ctor);
468
+ if (!instance) continue;
469
+ for (const meta of metas) {
470
+ this.wireCqrsEventHandler(instance, meta);
471
+ }
472
+ }
473
+ }
474
+ wireCqrsEventHandler(instance, meta) {
475
+ const method = instance[meta.methodKey];
476
+ if (typeof method !== "function") return;
477
+ const bound = method.bind(instance);
478
+ const cqrsGraph = this.resolveCqrsGraph(meta.cqrsName);
479
+ if (!cqrsGraph) return;
480
+ cqrsGraph.event(meta.eventName);
481
+ const eventNode = cqrsGraph.resolve(meta.eventName);
482
+ const existingEntries = eventNode.cache;
483
+ let lastSeq = existingEntries && existingEntries.length > 0 ? existingEntries[existingEntries.length - 1].seq : 0;
484
+ const handle = this.observeNodeOn(cqrsGraph, meta.eventName);
485
+ const unsub = handle.subscribe((msgs) => {
486
+ for (const m of msgs) {
487
+ if (m[0] === import_core3.DATA) {
488
+ const entries = m[1];
489
+ for (const entry of entries) {
490
+ if (entry.seq > lastSeq) {
491
+ bound(entry);
492
+ lastSeq = entry.seq;
493
+ }
494
+ }
495
+ }
496
+ }
497
+ });
498
+ this.disposers.push(unsub);
499
+ }
500
+ // -----------------------------------------------------------------------
501
+ // @QueryHandler — subscribe method to CQRS projection changes
502
+ // -----------------------------------------------------------------------
503
+ wireCqrsQueries() {
504
+ for (const [ctor, metas] of QUERY_HANDLERS) {
505
+ const instance = this.resolveInstance(ctor);
506
+ if (!instance) continue;
507
+ for (const meta of metas) {
508
+ this.wireCqrsQuery(instance, meta);
509
+ }
510
+ }
511
+ }
512
+ wireCqrsQuery(instance, meta) {
513
+ const method = instance[meta.methodKey];
514
+ if (typeof method !== "function") return;
515
+ const bound = method.bind(instance);
516
+ const cqrsGraph = this.resolveCqrsGraph(meta.cqrsName);
517
+ if (!cqrsGraph) return;
518
+ const handle = this.observeNodeOn(cqrsGraph, meta.projectionName);
519
+ const unsub = handle.subscribe((msgs) => {
520
+ for (const m of msgs) {
521
+ if (m[0] === import_core3.DATA) {
522
+ bound(m[1]);
523
+ }
524
+ }
525
+ });
526
+ this.disposers.push(unsub);
527
+ }
528
+ // -----------------------------------------------------------------------
529
+ // @SagaHandler — register method as CqrsGraph saga (subgraph side effect)
530
+ // -----------------------------------------------------------------------
531
+ wireCqrsSagas() {
532
+ for (const [ctor, metas] of SAGA_HANDLERS) {
533
+ const instance = this.resolveInstance(ctor);
534
+ if (!instance) continue;
535
+ for (const meta of metas) {
536
+ this.wireCqrsSaga(instance, meta);
537
+ }
538
+ }
539
+ }
540
+ wireCqrsSaga(instance, meta) {
541
+ const method = instance[meta.methodKey];
542
+ if (typeof method !== "function") return;
543
+ const bound = method.bind(instance);
544
+ const cqrsGraph = this.resolveCqrsGraph(meta.cqrsName);
545
+ if (!cqrsGraph) return;
546
+ cqrsGraph.saga(meta.sagaName, meta.eventNames, bound);
547
+ }
548
+ // -----------------------------------------------------------------------
549
+ // Helpers
550
+ // -----------------------------------------------------------------------
551
+ observeNode(name) {
552
+ return this.graph.observe(name);
553
+ }
554
+ observeNodeOn(graph, name) {
555
+ return graph.observe(name);
556
+ }
557
+ resolveCqrsGraph(name) {
558
+ try {
559
+ return this.moduleRef.get(getGraphToken(name), { strict: false });
560
+ } catch {
561
+ console.warn(
562
+ `[GraphReFly] CqrsGraph "${name}" not found in DI \u2014 did you import GraphReflyModule.forCqrs({ name: "${name}" })?`
563
+ );
564
+ return null;
565
+ }
566
+ }
567
+ resolveInstance(ctor) {
568
+ try {
569
+ return this.moduleRef.get(ctor, { strict: false });
570
+ } catch {
571
+ return null;
572
+ }
573
+ }
574
+ };
575
+
576
+ // src/compat/nestjs/gateway.ts
577
+ var import_core5 = require("@graphrefly/pure-ts/core");
578
+
579
+ // src/base/composition/backpressure.ts
580
+ var import_core4 = require("@graphrefly/pure-ts/core");
581
+ var nextLockId = 0;
582
+ function createWatermarkController(sendUp, opts) {
583
+ if (opts.highWaterMark < 1) throw new RangeError("highWaterMark must be >= 1");
584
+ if (opts.lowWaterMark < 0) throw new RangeError("lowWaterMark must be >= 0");
585
+ if (opts.lowWaterMark >= opts.highWaterMark)
586
+ throw new RangeError("lowWaterMark must be < highWaterMark");
587
+ const lockId = /* @__PURE__ */ Symbol(`bp-${++nextLockId}`);
588
+ let pending = 0;
589
+ let paused = false;
590
+ return {
591
+ onEnqueue() {
592
+ pending += 1;
593
+ if (!paused && pending >= opts.highWaterMark) {
594
+ paused = true;
595
+ sendUp([[import_core4.PAUSE, lockId]]);
596
+ return true;
597
+ }
598
+ return false;
599
+ },
600
+ onDequeue() {
601
+ if (pending > 0) pending -= 1;
602
+ if (paused && pending <= opts.lowWaterMark) {
603
+ paused = false;
604
+ sendUp([[import_core4.RESUME, lockId]]);
605
+ return true;
606
+ }
607
+ return false;
608
+ },
609
+ get pending() {
610
+ return pending;
611
+ },
612
+ get paused() {
613
+ return paused;
614
+ },
615
+ dispose() {
616
+ if (paused) {
617
+ paused = false;
618
+ sendUp([[import_core4.RESUME, lockId]]);
619
+ }
620
+ }
621
+ };
622
+ }
623
+
624
+ // src/compat/nestjs/gateway.ts
625
+ function observeSSE(graph, path, opts) {
626
+ const { actor, serialize = defaultSerialize, keepAliveMs, signal } = opts ?? {};
627
+ const encoder = new TextEncoder();
628
+ let stop;
629
+ const useBackpressure = opts?.highWaterMark != null;
630
+ let wm;
631
+ let pullResolve;
632
+ const taggedBuf = [];
633
+ let closed = false;
634
+ return new ReadableStream({
635
+ start(controller) {
636
+ let keepAlive;
637
+ let unsub = () => {
638
+ };
639
+ const close = () => {
640
+ if (closed) return;
641
+ closed = true;
642
+ if (keepAlive !== void 0) clearInterval(keepAlive);
643
+ signal?.removeEventListener("abort", onAbort);
644
+ unsub();
645
+ wm?.dispose();
646
+ pullResolve?.();
647
+ pullResolve = void 0;
648
+ for (const entry of taggedBuf) controller.enqueue(entry.frame);
649
+ taggedBuf.length = 0;
650
+ controller.close();
651
+ };
652
+ stop = close;
653
+ const onAbort = () => close();
654
+ const handle = graph.observe(path, { actor });
655
+ if (useBackpressure) {
656
+ wm = createWatermarkController((msgs) => handle.up(msgs), {
657
+ highWaterMark: opts.highWaterMark,
658
+ lowWaterMark: opts.lowWaterMark ?? Math.floor(opts.highWaterMark / 2)
659
+ });
660
+ }
661
+ unsub = handle.subscribe((msgs) => {
662
+ for (const msg of msgs) {
663
+ if (closed) return;
664
+ const t = msg[0];
665
+ if (t === import_core5.DATA) {
666
+ const frame = encoder.encode(sseFrame("data", serialize(msg[1])));
667
+ if (useBackpressure) {
668
+ taggedBuf.push({ frame, counted: true });
669
+ wm.onEnqueue();
670
+ pullResolve?.();
671
+ pullResolve = void 0;
672
+ } else {
673
+ controller.enqueue(frame);
674
+ }
675
+ } else if (t === import_core5.ERROR) {
676
+ const frame = encoder.encode(sseFrame("error", serialize(msg[1])));
677
+ if (useBackpressure) {
678
+ taggedBuf.push({ frame, counted: false });
679
+ pullResolve?.();
680
+ pullResolve = void 0;
681
+ } else {
682
+ controller.enqueue(frame);
683
+ }
684
+ close();
685
+ return;
686
+ } else if (t === import_core5.COMPLETE || t === import_core5.TEARDOWN) {
687
+ if (t === import_core5.COMPLETE) {
688
+ const frame = encoder.encode(sseFrame("complete"));
689
+ if (useBackpressure) {
690
+ taggedBuf.push({ frame, counted: false });
691
+ pullResolve?.();
692
+ pullResolve = void 0;
693
+ } else {
694
+ controller.enqueue(frame);
695
+ }
696
+ }
697
+ close();
698
+ return;
699
+ }
700
+ }
701
+ });
702
+ if (keepAliveMs !== void 0 && keepAliveMs > 0) {
703
+ keepAlive = setInterval(() => {
704
+ if (closed) return;
705
+ if (useBackpressure) {
706
+ taggedBuf.push({ frame: encoder.encode(": keepalive\n\n"), counted: false });
707
+ pullResolve?.();
708
+ pullResolve = void 0;
709
+ } else {
710
+ controller.enqueue(encoder.encode(": keepalive\n\n"));
711
+ }
712
+ }, keepAliveMs);
713
+ }
714
+ if (signal?.aborted) onAbort();
715
+ else signal?.addEventListener("abort", onAbort, { once: true });
716
+ },
717
+ pull(controller) {
718
+ if (!useBackpressure) return;
719
+ if (closed) return;
720
+ if (taggedBuf.length > 0) {
721
+ const entry = taggedBuf.shift();
722
+ controller.enqueue(entry.frame);
723
+ if (entry.counted) wm.onDequeue();
724
+ return;
725
+ }
726
+ return new Promise((resolve) => {
727
+ pullResolve = resolve;
728
+ });
729
+ },
730
+ cancel() {
731
+ try {
732
+ stop?.();
733
+ } catch {
734
+ }
735
+ }
736
+ });
737
+ }
738
+ function observeSubscription(graph, path, opts) {
739
+ const { actor, filter } = opts ?? {};
740
+ const queue = [];
741
+ const waiters = [];
742
+ let disposed = false;
743
+ const handle = graph.observe(path, { actor });
744
+ const wm = opts?.highWaterMark != null ? createWatermarkController((msgs) => handle.up(msgs), {
745
+ highWaterMark: opts.highWaterMark,
746
+ lowWaterMark: opts.lowWaterMark ?? Math.floor(opts.highWaterMark / 2)
747
+ }) : void 0;
748
+ const dispose = () => {
749
+ if (disposed) return;
750
+ disposed = true;
751
+ wm?.dispose();
752
+ unsub();
753
+ };
754
+ const push = (item) => {
755
+ if (disposed) return;
756
+ if (waiters.length > 0) {
757
+ const w = waiters.shift();
758
+ if (item.done && item.error) w.reject(item.error);
759
+ else if (item.done) w.resolve({ done: true, value: void 0 });
760
+ else w.resolve({ done: false, value: item.value });
761
+ } else {
762
+ queue.push(item);
763
+ if (!item.done) wm?.onEnqueue();
764
+ }
765
+ };
766
+ const unsub = handle.subscribe((msgs) => {
767
+ for (const msg of msgs) {
768
+ const t = msg[0];
769
+ if (t === import_core5.DATA) {
770
+ const value = msg[1];
771
+ if (filter && !filter(value)) continue;
772
+ push({ done: false, value });
773
+ } else if (t === import_core5.ERROR) {
774
+ const err = msg[1] instanceof Error ? msg[1] : new Error(String(msg[1]));
775
+ push({ done: true, error: err });
776
+ dispose();
777
+ return;
778
+ } else if (t === import_core5.COMPLETE || t === import_core5.TEARDOWN) {
779
+ push({ done: true });
780
+ dispose();
781
+ return;
782
+ }
783
+ }
784
+ });
785
+ const iterator = {
786
+ next() {
787
+ if (queue.length > 0) {
788
+ const item = queue.shift();
789
+ if (!item.done) wm?.onDequeue();
790
+ if (item.done && item.error) return Promise.reject(item.error);
791
+ return Promise.resolve(
792
+ item.done ? { done: true, value: void 0 } : { done: false, value: item.value }
793
+ );
794
+ }
795
+ if (disposed) return Promise.resolve({ done: true, value: void 0 });
796
+ return new Promise((resolve, reject) => {
797
+ waiters.push({ resolve, reject });
798
+ });
799
+ },
800
+ return() {
801
+ dispose();
802
+ for (const w of waiters) w.resolve({ done: true, value: void 0 });
803
+ waiters.length = 0;
804
+ return Promise.resolve({ done: true, value: void 0 });
805
+ },
806
+ throw(err) {
807
+ dispose();
808
+ return Promise.reject(err);
809
+ },
810
+ [Symbol.asyncIterator]() {
811
+ return this;
812
+ }
813
+ };
814
+ return iterator;
815
+ }
816
+ var ObserveGateway = class {
817
+ constructor(graph, opts) {
818
+ this.graph = graph;
819
+ this.extractActor = opts?.extractActor ?? (() => void 0);
820
+ this.parse = opts?.parse ?? defaultParseCommand;
821
+ this.highWaterMark = opts?.highWaterMark;
822
+ this.lowWaterMark = opts?.lowWaterMark;
823
+ }
824
+ clients = /* @__PURE__ */ new Map();
825
+ extractActor;
826
+ parse;
827
+ highWaterMark;
828
+ lowWaterMark;
829
+ /**
830
+ * Register a new client. Call from `handleConnection`.
831
+ */
832
+ handleConnection(client) {
833
+ if (!this.clients.has(client)) {
834
+ this.clients.set(client, /* @__PURE__ */ new Map());
835
+ }
836
+ }
837
+ /**
838
+ * Unregister a client and dispose all its subscriptions. Call from `handleDisconnect`.
839
+ */
840
+ handleDisconnect(client) {
841
+ const subs = this.clients.get(client);
842
+ if (!subs) return;
843
+ for (const entry of subs.values()) {
844
+ entry.wm?.dispose();
845
+ entry.unsub();
846
+ }
847
+ this.clients.delete(client);
848
+ }
849
+ /**
850
+ * Handle an incoming client message (subscribe/unsubscribe/ack command).
851
+ *
852
+ * @param client - The WebSocket client reference.
853
+ * @param raw - Raw message data (string or parsed object).
854
+ * @param send - Function to send a message back to the client.
855
+ * Defaults to `client.send(JSON.stringify(msg))`.
856
+ */
857
+ handleMessage(client, raw, send) {
858
+ const sender = send ?? defaultSend.bind(null, client);
859
+ let cmd;
860
+ try {
861
+ cmd = typeof raw === "string" ? this.parse(raw) : raw;
862
+ } catch {
863
+ sender({ type: "err", message: "invalid command" });
864
+ return;
865
+ }
866
+ if (cmd.type === "subscribe") {
867
+ this.subscribe(client, cmd.path, sender);
868
+ } else if (cmd.type === "unsubscribe") {
869
+ this.unsubscribe(client, cmd.path, sender);
870
+ } else if (cmd.type === "ack") {
871
+ this.ack(client, cmd.path, cmd.count ?? 1);
872
+ } else {
873
+ sender({ type: "err", message: `unknown command type: ${cmd.type}` });
874
+ }
875
+ }
876
+ /**
877
+ * Number of active subscriptions for a client. Useful for tests.
878
+ */
879
+ subscriptionCount(client) {
880
+ return this.clients.get(client)?.size ?? 0;
881
+ }
882
+ /**
883
+ * Dispose all clients and subscriptions.
884
+ */
885
+ destroy() {
886
+ for (const [client] of this.clients) {
887
+ this.handleDisconnect(client);
888
+ }
889
+ }
890
+ // -----------------------------------------------------------------------
891
+ // Internal
892
+ // -----------------------------------------------------------------------
893
+ subscribe(client, path, send) {
894
+ let subs = this.clients.get(client);
895
+ if (!subs) {
896
+ subs = /* @__PURE__ */ new Map();
897
+ this.clients.set(client, subs);
898
+ }
899
+ if (subs.has(path)) {
900
+ send({ type: "subscribed", path });
901
+ return;
902
+ }
903
+ const actor = this.extractActor(client);
904
+ let handle;
905
+ try {
906
+ handle = this.graph.observe(path, { actor });
907
+ } catch (err) {
908
+ const message = err instanceof Error ? err.message : String(err);
909
+ send({ type: "err", message });
910
+ return;
911
+ }
912
+ const wm = this.highWaterMark != null ? createWatermarkController((msgs) => handle.up(msgs), {
913
+ highWaterMark: this.highWaterMark,
914
+ lowWaterMark: this.lowWaterMark ?? Math.floor(this.highWaterMark / 2)
915
+ }) : void 0;
916
+ const cleanup = () => {
917
+ wm?.dispose();
918
+ unsub();
919
+ subs.delete(path);
920
+ };
921
+ const unsub = handle.subscribe((msgs) => {
922
+ for (const msg of msgs) {
923
+ const t = msg[0];
924
+ if (t === import_core5.DATA) {
925
+ wm?.onEnqueue();
926
+ trySend(send, { type: "data", path, value: msg[1] });
927
+ } else if (t === import_core5.ERROR) {
928
+ const errMsg = msg[1] instanceof Error ? msg[1].message : String(msg[1]);
929
+ trySend(send, { type: "error", path, error: errMsg });
930
+ cleanup();
931
+ return;
932
+ } else if (t === import_core5.COMPLETE || t === import_core5.TEARDOWN) {
933
+ trySend(send, { type: "complete", path });
934
+ cleanup();
935
+ return;
936
+ }
937
+ }
938
+ });
939
+ subs.set(path, { unsub, wm });
940
+ send({ type: "subscribed", path });
941
+ }
942
+ unsubscribe(client, path, send) {
943
+ const subs = this.clients.get(client);
944
+ const entry = subs?.get(path);
945
+ if (entry) {
946
+ entry.wm?.dispose();
947
+ entry.unsub();
948
+ subs.delete(path);
949
+ }
950
+ send({ type: "unsubscribed", path });
951
+ }
952
+ ack(client, path, count) {
953
+ const entry = this.clients.get(client)?.get(path);
954
+ if (!entry?.wm) return;
955
+ const n = Math.min(Math.max(0, Math.floor(count)), 1024);
956
+ for (let i = 0; i < n; i++) entry.wm.onDequeue();
957
+ }
958
+ };
959
+ function defaultSerialize(value) {
960
+ if (value instanceof Error) return value.message;
961
+ try {
962
+ return JSON.stringify(value);
963
+ } catch {
964
+ return String(value);
965
+ }
966
+ }
967
+ function sseFrame(event, data) {
968
+ let frame = `event: ${event}
969
+ `;
970
+ if (data !== void 0) {
971
+ for (const line of data.split("\n")) {
972
+ frame += `data: ${line}
973
+ `;
974
+ }
975
+ }
976
+ frame += "\n";
977
+ return frame;
978
+ }
979
+ function defaultParseCommand(data) {
980
+ return JSON.parse(data);
981
+ }
982
+ function defaultSend(client, msg) {
983
+ try {
984
+ client.send(JSON.stringify(msg));
985
+ } catch {
986
+ }
987
+ }
988
+ function trySend(send, msg) {
989
+ try {
990
+ send(msg);
991
+ } catch {
992
+ }
993
+ }
994
+
995
+ // src/compat/nestjs/guard.ts
996
+ var import_core6 = require("@graphrefly/pure-ts/core");
997
+ var ACTOR_KEY = "graphReflyActor";
998
+ function fromJwtPayload(mapping) {
999
+ return (context) => {
1000
+ const req = context.switchToHttp().getRequest();
1001
+ const user = req?.user;
1002
+ if (user == null) return void 0;
1003
+ if (mapping) return mapping(user);
1004
+ return user;
1005
+ };
1006
+ }
1007
+ function fromHeader(headerName = "x-graphrefly-actor") {
1008
+ return (context) => {
1009
+ const req = context.switchToHttp().getRequest();
1010
+ const raw = req?.headers?.[headerName.toLowerCase()];
1011
+ if (typeof raw !== "string" || raw.length === 0) return void 0;
1012
+ try {
1013
+ return JSON.parse(raw);
1014
+ } catch {
1015
+ return void 0;
1016
+ }
1017
+ };
1018
+ }
1019
+ function getActor(req) {
1020
+ const actor = req?.[ACTOR_KEY];
1021
+ return actor != null ? (0, import_core6.normalizeActor)(actor) : import_core6.DEFAULT_ACTOR;
1022
+ }
1023
+ var GraphReflyGuardImpl = class {
1024
+ constructor(extractor) {
1025
+ this.extractor = extractor;
1026
+ }
1027
+ canActivate(context) {
1028
+ const actor = (0, import_core6.normalizeActor)(this.extractor(context));
1029
+ const req = context.switchToHttp().getRequest();
1030
+ if (req != null) {
1031
+ req[ACTOR_KEY] = actor;
1032
+ }
1033
+ return true;
1034
+ }
1035
+ };
1036
+ function GraphReflyGuard(extractor) {
1037
+ return new GraphReflyGuardImpl(extractor ?? fromJwtPayload());
1038
+ }
1039
+
1040
+ // src/compat/nestjs/module.ts
1041
+ var import_graph3 = require("@graphrefly/pure-ts/graph");
1042
+ var import_common2 = require("@nestjs/common");
1043
+ var import_core9 = require("@nestjs/core");
1044
+
1045
+ // src/utils/cqrs/index.ts
1046
+ var import_core8 = require("@graphrefly/pure-ts/core");
1047
+ var import_extra3 = require("@graphrefly/pure-ts/extra");
1048
+ var import_graph2 = require("@graphrefly/pure-ts/graph");
1049
+
1050
+ // src/base/mutation/index.ts
1051
+ var import_core7 = require("@graphrefly/pure-ts/core");
1052
+ var import_extra2 = require("@graphrefly/pure-ts/extra");
1053
+ var import_graph = require("@graphrefly/pure-ts/graph");
1054
+ var DEFAULT_AUDIT_GUARD = (0, import_core7.policy)((allow, deny) => {
1055
+ allow("observe");
1056
+ allow("signal");
1057
+ deny("write");
1058
+ });
1059
+ function createAuditLog(opts) {
1060
+ const log = (0, import_extra2.reactiveLog)([], {
1061
+ name: opts.name,
1062
+ maxSize: opts.retainedLimit ?? 1024,
1063
+ guard: opts.guard ?? DEFAULT_AUDIT_GUARD,
1064
+ ...opts.versioning != null ? { versioning: opts.versioning } : {}
1065
+ });
1066
+ log.withLatest();
1067
+ if (opts.graph) {
1068
+ opts.graph.add(log.entries, { name: opts.name });
1069
+ }
1070
+ return log;
1071
+ }
1072
+ function deepFreeze(value) {
1073
+ if (value === null || typeof value !== "object" || Object.isFrozen(value)) return value;
1074
+ for (const k of Object.keys(value)) {
1075
+ deepFreeze(value[k]);
1076
+ }
1077
+ return Object.freeze(value);
1078
+ }
1079
+ function mutate(act, opts) {
1080
+ const { up, down } = typeof act === "function" ? { up: act, down: void 0 } : act;
1081
+ const freeze = opts.freeze ?? true;
1082
+ if (opts.frame === "inline") {
1083
+ return function wrapped(...args) {
1084
+ const sealed = freeze ? args.map(deepFreeze) : args;
1085
+ const t_ns = (0, import_core7.wallClockNs)();
1086
+ const seq = opts.seq ? bumpCursor(opts.seq) : void 0;
1087
+ try {
1088
+ const result = up(...sealed);
1089
+ if (opts.log && opts.onSuccessRecord) {
1090
+ appendAudit(
1091
+ opts.log,
1092
+ opts.onSuccessRecord,
1093
+ sealed,
1094
+ result,
1095
+ { t_ns, seq },
1096
+ opts.handlerVersion
1097
+ );
1098
+ }
1099
+ return result;
1100
+ } catch (err) {
1101
+ if (opts.log && opts.onFailureRecord) {
1102
+ const errorType = err instanceof Error ? err.name : typeof err;
1103
+ appendAudit(
1104
+ opts.log,
1105
+ opts.onFailureRecord,
1106
+ sealed,
1107
+ err,
1108
+ { t_ns, seq, errorType },
1109
+ opts.handlerVersion
1110
+ );
1111
+ }
1112
+ throw err;
1113
+ }
1114
+ };
1115
+ }
1116
+ return function wrapped(...args) {
1117
+ const sealed = freeze ? args.map(deepFreeze) : args;
1118
+ const t_ns = (0, import_core7.wallClockNs)();
1119
+ let result;
1120
+ let captured;
1121
+ let captureSet = false;
1122
+ let seq;
1123
+ try {
1124
+ (0, import_core7.batch)(() => {
1125
+ if (opts.seq) seq = bumpCursor(opts.seq);
1126
+ try {
1127
+ result = up(...sealed);
1128
+ if (opts.log && opts.onSuccessRecord) {
1129
+ appendAudit(
1130
+ opts.log,
1131
+ opts.onSuccessRecord,
1132
+ sealed,
1133
+ result,
1134
+ { t_ns, seq },
1135
+ opts.handlerVersion
1136
+ );
1137
+ }
1138
+ } catch (err) {
1139
+ captured = err;
1140
+ captureSet = true;
1141
+ throw err;
1142
+ }
1143
+ });
1144
+ } catch (outerErr) {
1145
+ if (captureSet && down) {
1146
+ try {
1147
+ down(...sealed);
1148
+ } catch (downErr) {
1149
+ console.error(
1150
+ `mutate: down hook threw \u2014 original action error preserved (${captured instanceof Error ? captured.name : typeof captured}). Down error:`,
1151
+ downErr
1152
+ );
1153
+ }
1154
+ }
1155
+ if (captureSet && opts.log && opts.onFailureRecord) {
1156
+ const errorType = captured instanceof Error ? captured.name : typeof captured;
1157
+ appendAudit(
1158
+ opts.log,
1159
+ opts.onFailureRecord,
1160
+ sealed,
1161
+ captured,
1162
+ { t_ns, seq, errorType },
1163
+ opts.handlerVersion
1164
+ );
1165
+ }
1166
+ throw captureSet ? captured : outerErr;
1167
+ }
1168
+ return result;
1169
+ };
1170
+ }
1171
+ var _bumpCursorWarned = /* @__PURE__ */ new WeakSet();
1172
+ function bumpCursor(seq) {
1173
+ const raw = seq.cache;
1174
+ const valid = typeof raw === "number" && Number.isFinite(raw);
1175
+ if (!valid && raw !== void 0 && !_bumpCursorWarned.has(seq)) {
1176
+ _bumpCursorWarned.add(seq);
1177
+ console.warn(
1178
+ `bumpCursor: cursor cache held a non-numeric value (${String(raw)}); resetting to 0. Causes include: a snapshot codec round-tripping the cursor as a string / null / NaN, OR a malformed initial seed (e.g. state<number>(NaN)). Audit consumers may see colliding seq values after this point.`
1179
+ );
1180
+ }
1181
+ const cur = valid ? raw : 0;
1182
+ const next = cur + 1;
1183
+ seq.down([[import_core7.DIRTY], [import_core7.DATA, next]]);
1184
+ return next;
1185
+ }
1186
+ function appendAudit(audit, builder, args, value, meta, handlerVersion) {
1187
+ const record = builder(args, value, meta);
1188
+ if (record === void 0) return;
1189
+ const stamped = handlerVersion != null ? { ...record, handlerVersion } : record;
1190
+ audit.append(stamped);
1191
+ }
1192
+ function registerCursor(graph, name, initial = 0) {
1193
+ const cursor = (0, import_core7.node)([], { initial, name, describeKind: "state" });
1194
+ graph.add(cursor, { name });
1195
+ return cursor;
1196
+ }
1197
+ function registerCursorMap(graph, name, keys, initial = 0) {
1198
+ const out = {};
1199
+ const sub = new import_graph.Graph(name);
1200
+ for (const k of keys) {
1201
+ const cursor = (0, import_core7.node)([], {
1202
+ initial,
1203
+ name: k,
1204
+ describeKind: "state"
1205
+ });
1206
+ sub.add(cursor, { name: k });
1207
+ out[k] = cursor;
1208
+ }
1209
+ graph.mount(name, sub);
1210
+ return out;
1211
+ }
1212
+
1213
+ // src/utils/_errors/index.ts
1214
+ var GraphReFlyError = class extends Error {
1215
+ constructor(message, options) {
1216
+ super(message, options);
1217
+ this.name = this.constructor.name;
1218
+ }
1219
+ };
1220
+ var DuplicateRegistrationError = class extends GraphReFlyError {
1221
+ constructor(kind, registrationName) {
1222
+ super(`Duplicate ${kind} registration: "${registrationName}"`);
1223
+ this.kind = kind;
1224
+ this.registrationName = registrationName;
1225
+ }
1226
+ };
1227
+ var UndeclaredEmitError = class extends GraphReFlyError {
1228
+ constructor(commandName, eventName, declaredEmits) {
1229
+ super(
1230
+ `Command "${commandName}" emitted undeclared event "${eventName}". Declared emits: [${declaredEmits.join(", ")}]`
1231
+ );
1232
+ this.commandName = commandName;
1233
+ this.eventName = eventName;
1234
+ this.declaredEmits = declaredEmits;
1235
+ }
1236
+ };
1237
+ var OptimisticConcurrencyError = class extends GraphReFlyError {
1238
+ constructor(aggregateId, expected, actual) {
1239
+ super(
1240
+ `Optimistic concurrency conflict on aggregate "${aggregateId}": expected version ${expected}, got ${actual}`
1241
+ );
1242
+ this.aggregateId = aggregateId;
1243
+ this.expected = expected;
1244
+ this.actual = actual;
1245
+ }
1246
+ };
1247
+ var UnknownCommandError = class extends GraphReFlyError {
1248
+ constructor(commandName) {
1249
+ super(`Unknown command: "${commandName}". Register with command() first.`);
1250
+ this.commandName = commandName;
1251
+ }
1252
+ };
1253
+ var CommandHandlerError = class extends GraphReFlyError {
1254
+ constructor(commandName, cause) {
1255
+ super(
1256
+ `Command handler "${commandName}" threw: ${cause instanceof Error ? cause.message : String(cause)}`,
1257
+ { cause }
1258
+ );
1259
+ this.commandName = commandName;
1260
+ }
1261
+ };
1262
+ var RebuildError = class extends GraphReFlyError {
1263
+ constructor(projectionName, cause) {
1264
+ super(
1265
+ `Projection "${projectionName}" rebuild failed: ${cause instanceof Error ? cause.message : String(cause)}`,
1266
+ { cause }
1267
+ );
1268
+ this.projectionName = projectionName;
1269
+ }
1270
+ };
1271
+
1272
+ // src/utils/cqrs/index.ts
1273
+ var import_extra4 = require("@graphrefly/pure-ts/extra");
1274
+
1275
+ // src/base/meta/domain-meta.ts
1276
+ function domainMeta(domain, kind, extra) {
1277
+ return {
1278
+ [domain]: true,
1279
+ [`${domain}_type`]: kind,
1280
+ ...extra ?? {}
1281
+ };
1282
+ }
1283
+
1284
+ // src/utils/cqrs/index.ts
1285
+ var COMMAND_GUARD = (0, import_core8.policy)((allow, deny) => {
1286
+ allow("write");
1287
+ allow("signal");
1288
+ deny("observe");
1289
+ });
1290
+ var PROJECTION_GUARD = (0, import_core8.policy)((allow, deny) => {
1291
+ allow("observe");
1292
+ allow("signal");
1293
+ deny("write");
1294
+ });
1295
+ var EVENT_GUARD = (0, import_core8.policy)((allow, deny) => {
1296
+ allow("observe");
1297
+ allow("signal");
1298
+ deny("write");
1299
+ });
1300
+ function cqrsMeta(kind, extra) {
1301
+ return domainMeta("cqrs", kind, extra);
1302
+ }
1303
+ function deepFreeze2(value) {
1304
+ if (value === null || typeof value !== "object" || Object.isFrozen(value)) return value;
1305
+ for (const k of Object.keys(value)) {
1306
+ deepFreeze2(value[k]);
1307
+ }
1308
+ return Object.freeze(value);
1309
+ }
1310
+ var CqrsGraph = class extends import_graph2.Graph {
1311
+ /** Fan-in event streams (one per type, all aggregates merged). */
1312
+ _eventLogs = /* @__PURE__ */ new Map();
1313
+ /**
1314
+ * Per-aggregate event streams: type → aggregateId → entry. Used for
1315
+ * `event(type, aggregateId)` dual-form access and per-aggregate version
1316
+ * tracking. Only populated when an event with `aggregateId` is emitted.
1317
+ */
1318
+ _eventLogsByAggregate = /* @__PURE__ */ new Map();
1319
+ /** Per-aggregate version counters: `${type}::${aggregateId}` → current version. */
1320
+ _aggregateVersions = /* @__PURE__ */ new Map();
1321
+ /**
1322
+ * LRU access order for `${type}::${aggregateId}`. Map insertion order
1323
+ * tracks recency — `delete` + `set` on access moves to the end.
1324
+ */
1325
+ _aggregateLru = /* @__PURE__ */ new Map();
1326
+ _commandRegs = /* @__PURE__ */ new Map();
1327
+ _projections = /* @__PURE__ */ new Set();
1328
+ _sagas = /* @__PURE__ */ new Set();
1329
+ _seq = 0;
1330
+ _retainedLimit;
1331
+ _freezeCommandPayload;
1332
+ _freezeEventPayload;
1333
+ _maxAggregates;
1334
+ _dispatchSeqCursor;
1335
+ /** Audit log of every command dispatch (Audit 2). */
1336
+ dispatches;
1337
+ /** Alias for {@link CqrsGraph.dispatches} (Audit 2 `.audit` duplication). */
1338
+ audit;
1339
+ /** Per-aggregate LRU eviction observability; secondary log to `dispatches`. */
1340
+ aggregateEvictions;
1341
+ constructor(name, opts = {}) {
1342
+ super(name, opts.graph);
1343
+ this._retainedLimit = opts.retainedLimit ?? 1024;
1344
+ this._freezeCommandPayload = opts.freezeCommandPayload ?? true;
1345
+ this._freezeEventPayload = opts.freezeEventPayload ?? true;
1346
+ this._maxAggregates = opts.maxAggregates ?? 1e4;
1347
+ this.dispatches = createAuditLog({
1348
+ name: "dispatches",
1349
+ retainedLimit: this._retainedLimit,
1350
+ graph: this
1351
+ });
1352
+ this.audit = this.dispatches;
1353
+ this.aggregateEvictions = createAuditLog({
1354
+ name: "aggregateEvictions",
1355
+ retainedLimit: this._retainedLimit,
1356
+ graph: this
1357
+ });
1358
+ this._dispatchSeqCursor = registerCursor(this, "dispatch_seq", 0);
1359
+ }
1360
+ /**
1361
+ * Read the current per-aggregate version (last emitted `aggregateVersion`
1362
+ * for that `(type, aggregateId)` pair). Returns `0` if no events have been
1363
+ * emitted yet for this aggregate. Useful for callers preparing
1364
+ * {@link DispatchOptions.expectedAggregateVersion}.
1365
+ */
1366
+ aggregateVersion(type, aggregateId) {
1367
+ return this._aggregateVersions.get(`${type}::${aggregateId}`) ?? 0;
1368
+ }
1369
+ /** LRU touch — moves the key to the end of the access order. */
1370
+ _touchAggregate(key) {
1371
+ this._aggregateLru.delete(key);
1372
+ this._aggregateLru.set(key, true);
1373
+ }
1374
+ /**
1375
+ * Evict the oldest aggregate streams (least-recently-touched) until the
1376
+ * aggregate count is back within `_maxAggregates`. Emits one
1377
+ * `AggregateEvictionRecord` per eviction. The fan-in stream is NOT touched
1378
+ * — events stay in the type-level log; only the per-aggregate stream and
1379
+ * version counter are removed.
1380
+ */
1381
+ _enforceAggregateLru() {
1382
+ while (this._aggregateLru.size > this._maxAggregates) {
1383
+ const oldest = this._aggregateLru.keys().next();
1384
+ if (oldest.done) break;
1385
+ const key = oldest.value;
1386
+ this._aggregateLru.delete(key);
1387
+ const sep = key.indexOf("::");
1388
+ if (sep < 0) continue;
1389
+ const type = key.slice(0, sep);
1390
+ const aggregateId = key.slice(sep + 2);
1391
+ const lastVersion = this._aggregateVersions.get(key) ?? 0;
1392
+ this._aggregateVersions.delete(key);
1393
+ const byType = this._eventLogsByAggregate.get(type);
1394
+ if (byType) {
1395
+ byType.delete(aggregateId);
1396
+ if (byType.size === 0) this._eventLogsByAggregate.delete(type);
1397
+ }
1398
+ this.aggregateEvictions.append({
1399
+ aggregateId,
1400
+ type,
1401
+ lastVersion,
1402
+ t_ns: (0, import_core8.wallClockNs)()
1403
+ });
1404
+ }
1405
+ }
1406
+ /** Tiers attached via {@link attachEventStorage}; auto-wired into future event streams. */
1407
+ _attachedEventTiers = [];
1408
+ _attachedTierDisposers = /* @__PURE__ */ new Map();
1409
+ /**
1410
+ * Wire append-log storage tiers for ALL CQRS event streams — both currently
1411
+ * registered AND any future streams created via `event(name)` /
1412
+ * `event(name, aggregateId)` / handler emit. (M4 fix.)
1413
+ *
1414
+ * Returns a disposer that releases all storage subscriptions wired by this
1415
+ * call (including those for streams that were created after the call).
1416
+ */
1417
+ attachEventStorage(tiers) {
1418
+ this._attachedEventTiers.push(tiers);
1419
+ for (const [name, entry] of this._eventLogs) {
1420
+ const dispose = entry.log.attachStorage(tiers);
1421
+ let arr = this._attachedTierDisposers.get(name);
1422
+ if (!arr) {
1423
+ arr = [];
1424
+ this._attachedTierDisposers.set(name, arr);
1425
+ }
1426
+ arr.push(dispose);
1427
+ }
1428
+ for (const [type, byAgg] of this._eventLogsByAggregate) {
1429
+ for (const [aggId, entry] of byAgg) {
1430
+ const key = `${type}::${aggId}`;
1431
+ const dispose = entry.log.attachStorage(tiers);
1432
+ let arr = this._attachedTierDisposers.get(key);
1433
+ if (!arr) {
1434
+ arr = [];
1435
+ this._attachedTierDisposers.set(key, arr);
1436
+ }
1437
+ arr.push(dispose);
1438
+ }
1439
+ }
1440
+ return () => {
1441
+ const idx = this._attachedEventTiers.indexOf(tiers);
1442
+ if (idx >= 0) this._attachedEventTiers.splice(idx, 1);
1443
+ };
1444
+ }
1445
+ /** Wire newly-created event stream into all currently-attached tier sets. */
1446
+ _autoWireStreamStorage(key, log) {
1447
+ if (this._attachedEventTiers.length === 0) return;
1448
+ let arr = this._attachedTierDisposers.get(key);
1449
+ if (!arr) {
1450
+ arr = [];
1451
+ this._attachedTierDisposers.set(key, arr);
1452
+ }
1453
+ for (const tiers of this._attachedEventTiers) {
1454
+ arr.push(log.attachStorage(tiers));
1455
+ }
1456
+ }
1457
+ event(name, aggregateId) {
1458
+ if (aggregateId !== void 0) {
1459
+ return this._ensureAggregateStream(name, aggregateId).node;
1460
+ }
1461
+ const existing = this._eventLogs.get(name);
1462
+ if (existing) return existing.node;
1463
+ const log = (0, import_extra3.reactiveLog)([], {
1464
+ name,
1465
+ versioning: 0,
1466
+ maxSize: this._retainedLimit
1467
+ });
1468
+ log.withLatest();
1469
+ const entries = log.entries;
1470
+ const guarded = this.derived(
1471
+ name,
1472
+ [entries],
1473
+ (batchData, ctx) => {
1474
+ const latest = batchData[0] != null && batchData[0].length > 0 ? batchData[0].at(-1) : ctx.prevData[0];
1475
+ return [latest];
1476
+ },
1477
+ {
1478
+ meta: cqrsMeta("event", { event_name: name }),
1479
+ guard: EVENT_GUARD,
1480
+ initial: entries.cache
1481
+ }
1482
+ );
1483
+ this.addDisposer((0, import_extra4.keepalive)(guarded));
1484
+ this._eventLogs.set(name, { log, node: guarded });
1485
+ this._autoWireStreamStorage(name, log);
1486
+ return guarded;
1487
+ }
1488
+ /**
1489
+ * Get-or-create the per-aggregate event stream for `(type, aggregateId)`.
1490
+ * Mounts the stream as a sibling node named `<type>_<aggregateId>` so it
1491
+ * appears in `describe()`. LRU access is touched on every call.
1492
+ */
1493
+ _ensureAggregateStream(type, aggregateId) {
1494
+ if (!this._eventLogs.has(type)) this.event(type);
1495
+ let byType = this._eventLogsByAggregate.get(type);
1496
+ if (!byType) {
1497
+ byType = /* @__PURE__ */ new Map();
1498
+ this._eventLogsByAggregate.set(type, byType);
1499
+ }
1500
+ const lruKey = `${type}::${aggregateId}`;
1501
+ this._touchAggregate(lruKey);
1502
+ const existing = byType.get(aggregateId);
1503
+ if (existing) return existing;
1504
+ const nodeName = `${type}_${aggregateId.replace(/[^a-zA-Z0-9_-]/g, "_")}`;
1505
+ const log = (0, import_extra3.reactiveLog)([], {
1506
+ name: nodeName,
1507
+ versioning: 0,
1508
+ maxSize: this._retainedLimit
1509
+ });
1510
+ log.withLatest();
1511
+ const entries = log.entries;
1512
+ let mountName = nodeName;
1513
+ let collisionIdx = 0;
1514
+ while (this.resolveOptional(mountName) !== void 0) {
1515
+ collisionIdx += 1;
1516
+ mountName = `${nodeName}_${collisionIdx}`;
1517
+ }
1518
+ let guarded;
1519
+ try {
1520
+ guarded = this.derived(
1521
+ mountName,
1522
+ [entries],
1523
+ (batchData, ctx) => {
1524
+ const latest = batchData[0] != null && batchData[0].length > 0 ? batchData[0].at(-1) : ctx.prevData[0];
1525
+ return [latest];
1526
+ },
1527
+ {
1528
+ meta: cqrsMeta("event_aggregate", {
1529
+ event_name: type,
1530
+ aggregate_id: aggregateId
1531
+ }),
1532
+ guard: EVENT_GUARD,
1533
+ initial: entries.cache
1534
+ }
1535
+ );
1536
+ } catch {
1537
+ guarded = (0, import_core8.node)(
1538
+ [entries],
1539
+ (batchData, actions, ctx) => {
1540
+ const latest = batchData[0] != null && batchData[0].length > 0 ? batchData[0].at(-1) : ctx.prevData[0];
1541
+ actions.emit(latest);
1542
+ },
1543
+ {
1544
+ name: nodeName,
1545
+ describeKind: "derived",
1546
+ meta: cqrsMeta("event_aggregate", {
1547
+ event_name: type,
1548
+ aggregate_id: aggregateId
1549
+ }),
1550
+ guard: EVENT_GUARD,
1551
+ initial: entries.cache
1552
+ }
1553
+ );
1554
+ }
1555
+ this.addDisposer((0, import_extra4.keepalive)(guarded));
1556
+ const entry = { log, node: guarded };
1557
+ byType.set(aggregateId, entry);
1558
+ this._autoWireStreamStorage(`${type}::${aggregateId}`, log);
1559
+ this._enforceAggregateLru();
1560
+ return entry;
1561
+ }
1562
+ /** Try `resolve(path)`; return `undefined` instead of throwing on missing. */
1563
+ resolveOptional(path) {
1564
+ try {
1565
+ return this.resolve(path);
1566
+ } catch {
1567
+ return void 0;
1568
+ }
1569
+ }
1570
+ /** Internal: append to an event log, auto-registering if needed. */
1571
+ _appendEvent(eventName, payload, extra) {
1572
+ let entry = this._eventLogs.get(eventName);
1573
+ if (!entry) {
1574
+ this.event(eventName);
1575
+ entry = this._eventLogs.get(eventName);
1576
+ }
1577
+ if (entry.node.status === "completed" || entry.node.status === "errored") {
1578
+ throw new Error(
1579
+ `Cannot dispatch to terminated event stream "${eventName}" (status: ${entry.node.status}).`
1580
+ );
1581
+ }
1582
+ let aggregateVersion;
1583
+ let aggregateEntry;
1584
+ if (extra?.aggregateId !== void 0) {
1585
+ const lruKey = `${eventName}::${extra.aggregateId}`;
1586
+ aggregateVersion = (this._aggregateVersions.get(lruKey) ?? 0) + 1;
1587
+ this._aggregateVersions.set(lruKey, aggregateVersion);
1588
+ aggregateEntry = this._ensureAggregateStream(eventName, extra.aggregateId);
1589
+ }
1590
+ const nv = entry.log.entries.v;
1591
+ const frozenPayload = this._freezeEventPayload ? deepFreeze2(payload) : payload;
1592
+ const evt = {
1593
+ type: eventName,
1594
+ payload: frozenPayload,
1595
+ timestampNs: (0, import_core8.wallClockNs)(),
1596
+ seq: ++this._seq,
1597
+ ...extra?.aggregateId !== void 0 ? { aggregateId: extra.aggregateId } : {},
1598
+ ...aggregateVersion !== void 0 ? { aggregateVersion } : {},
1599
+ ...extra?.correlationId !== void 0 ? { correlationId: extra.correlationId } : {},
1600
+ ...extra?.causationId !== void 0 ? { causationId: extra.causationId } : {},
1601
+ ...extra?.metadata !== void 0 ? { metadata: Object.freeze({ ...extra.metadata }) } : {},
1602
+ ...extra?.handlerVersion !== void 0 ? { handlerVersion: extra.handlerVersion } : {},
1603
+ ...nv != null ? { v0: { id: nv.id, version: nv.version } } : {}
1604
+ };
1605
+ entry.log.append(evt);
1606
+ if (aggregateEntry) {
1607
+ aggregateEntry.log.append(evt);
1608
+ }
1609
+ return evt;
1610
+ }
1611
+ // -- Commands -------------------------------------------------------------
1612
+ /**
1613
+ * Register a command with its handler. Guard denies `observe` (write-only).
1614
+ * Use `dispatch(name, payload)` to execute.
1615
+ *
1616
+ * The command node carries dynamic `meta.error` — a reactive companion
1617
+ * that holds the last handler error (or `null` on success).
1618
+ */
1619
+ command(name, handlerOrReg) {
1620
+ if (this._commandRegs.has(name)) {
1621
+ throw new DuplicateRegistrationError("command", name);
1622
+ }
1623
+ const reg = typeof handlerOrReg === "function" ? { handler: handlerOrReg } : handlerOrReg;
1624
+ const cmdNode = this.state(name, void 0, {
1625
+ meta: {
1626
+ ...cqrsMeta("command", { command_name: name }),
1627
+ error: null
1628
+ },
1629
+ guard: COMMAND_GUARD
1630
+ });
1631
+ this._commandRegs.set(name, {
1632
+ handler: reg.handler,
1633
+ ...reg.emits !== void 0 ? { emits: reg.emits } : {},
1634
+ ...reg.handlerVersion !== void 0 ? { handlerVersion: reg.handlerVersion } : {}
1635
+ });
1636
+ if (reg.emits) {
1637
+ for (const e of reg.emits) {
1638
+ if (!this._eventLogs.has(e)) this.event(e);
1639
+ }
1640
+ }
1641
+ return cmdNode;
1642
+ }
1643
+ /**
1644
+ * Execute a registered command. Wraps the entire dispatch in `batch()` so
1645
+ * the command node DATA and all emitted events settle atomically.
1646
+ *
1647
+ * If the handler throws, `meta.error` on the command node is set to the
1648
+ * error and the exception is re-thrown.
1649
+ *
1650
+ * **Tier 8 / COMPOSITION-GUIDE §35:** dispatch routes through the shared
1651
+ * {@link mutate} framework so freeze / rollback-on-throw / seq-cursor
1652
+ * advance / audit-record stamping flow through one centralized helper.
1653
+ * Failure records emit OUTSIDE the rolled-back batch (M5 / C4 invariants
1654
+ * preserved by the framework).
1655
+ */
1656
+ dispatch(commandName, payload, opts) {
1657
+ const reg = this._commandRegs.get(commandName);
1658
+ if (!reg) throw new UnknownCommandError(commandName);
1659
+ if (opts?.aggregateId !== void 0 && opts.expectedAggregateVersion !== void 0 && reg.emits !== void 0) {
1660
+ let observedVersion = 0;
1661
+ for (const t of reg.emits) {
1662
+ const v = this._aggregateVersions.get(`${t}::${opts.aggregateId}`);
1663
+ if (v !== void 0 && v > observedVersion) observedVersion = v;
1664
+ }
1665
+ if (observedVersion !== opts.expectedAggregateVersion) {
1666
+ throw new OptimisticConcurrencyError(
1667
+ opts.aggregateId,
1668
+ opts.expectedAggregateVersion,
1669
+ observedVersion
1670
+ );
1671
+ }
1672
+ }
1673
+ const cmdNode = this.resolve(commandName);
1674
+ const emittedEvents = [];
1675
+ let actionThrew = false;
1676
+ const action = (sealed) => {
1677
+ cmdNode.emit(sealed, { internal: true });
1678
+ try {
1679
+ reg.handler(sealed, {
1680
+ emit: (eName, data) => {
1681
+ if (reg.emits !== void 0 && !reg.emits.includes(eName)) {
1682
+ throw new UndeclaredEmitError(commandName, eName, reg.emits);
1683
+ }
1684
+ emittedEvents.push(eName);
1685
+ this._appendEvent(eName, data, {
1686
+ // D1: thread the dispatch's aggregateId through so events
1687
+ // participate in per-aggregate versioning. Handlers can
1688
+ // override per-emit by passing their own through a richer
1689
+ // emit signature (future extension).
1690
+ ...opts?.aggregateId !== void 0 ? { aggregateId: opts.aggregateId } : {},
1691
+ ...opts?.correlationId !== void 0 ? { correlationId: opts.correlationId } : {},
1692
+ ...opts?.causationId !== void 0 ? { causationId: opts.causationId } : {},
1693
+ ...opts?.metadata !== void 0 ? { metadata: Object.freeze({ ...opts.metadata }) } : {},
1694
+ ...reg.handlerVersion !== void 0 ? { handlerVersion: reg.handlerVersion } : {}
1695
+ });
1696
+ }
1697
+ });
1698
+ cmdNode.meta.error.emit(null, { internal: true });
1699
+ } catch (err) {
1700
+ actionThrew = true;
1701
+ throw err;
1702
+ }
1703
+ };
1704
+ try {
1705
+ mutate(action, {
1706
+ frame: "transactional",
1707
+ log: this.dispatches,
1708
+ seq: this._dispatchSeqCursor,
1709
+ freeze: this._freezeCommandPayload,
1710
+ onSuccessRecord: ([sealed], _result, { t_ns, seq }) => ({
1711
+ commandName,
1712
+ payload: sealed,
1713
+ outcome: "success",
1714
+ emittedEvents: [...emittedEvents],
1715
+ t_ns,
1716
+ seq: seq ?? 0,
1717
+ ...reg.handlerVersion !== void 0 ? { handlerVersion: reg.handlerVersion } : {}
1718
+ }),
1719
+ onFailureRecord: ([sealed], err, { t_ns, seq, errorType }) => {
1720
+ const wrapped = err instanceof CommandHandlerError ? err : new CommandHandlerError(commandName, err);
1721
+ return {
1722
+ commandName,
1723
+ payload: sealed,
1724
+ outcome: "failure",
1725
+ error: wrapped,
1726
+ errorType,
1727
+ emittedEvents: [...emittedEvents],
1728
+ t_ns,
1729
+ seq: seq ?? 0,
1730
+ ...reg.handlerVersion !== void 0 ? { handlerVersion: reg.handlerVersion } : {}
1731
+ };
1732
+ }
1733
+ })(payload);
1734
+ } catch (outerErr) {
1735
+ if (actionThrew) {
1736
+ cmdNode.meta.error.emit(outerErr, { internal: true });
1737
+ }
1738
+ throw outerErr;
1739
+ }
1740
+ }
1741
+ // -- Projections ----------------------------------------------------------
1742
+ /**
1743
+ * Register a read-only projection derived from event streams.
1744
+ * Guard denies `write` — value is computed from events only.
1745
+ *
1746
+ * **Wave C.3 Unit 21 (locked 2026-04-24):**
1747
+ * - Object-bag signature replaces the positional `(name, events, reducer, initial)` form.
1748
+ * - `mode: "scan"` (default) — incremental fold; `"replay"` — full replay each wave.
1749
+ * - `snapshot` integration for cold-start load + auto-checkpoint save.
1750
+ * - `freezeInputs` (default `true`) — freeze the event array before passing to reducer.
1751
+ * - Returns `ProjectionController<TState>` with `.node`, `.rebuild()`, `.reset()`.
1752
+ *
1753
+ * Fan-in across `events` is implemented by depending on all event-type fan-in
1754
+ * nodes directly, which preserves `describe()` edges (e.g. `orderPlaced →
1755
+ * orderCount`). Events are sorted by `(timestampNs, seq, aggregateId)` before
1756
+ * passing to the reducer (Option-3 cross-aggregate ordering, C.3).
1757
+ */
1758
+ projection(opts) {
1759
+ const { name, events: eventNames, reducer, initial } = opts;
1760
+ const mode = opts.mode ?? "scan";
1761
+ const freezeInputs = opts.freezeInputs ?? true;
1762
+ const snapshotOpts = opts.snapshot;
1763
+ const eventNodes = eventNames.map((eName) => {
1764
+ if (!this._eventLogs.has(eName)) this.event(eName);
1765
+ return this._eventLogs.get(eName).node;
1766
+ });
1767
+ function sortEvents(evts) {
1768
+ evts.sort(
1769
+ (a, b) => a.timestampNs - b.timestampNs || a.seq - b.seq || (a.aggregateId ?? "").localeCompare(b.aggregateId ?? "")
1770
+ );
1771
+ }
1772
+ function collectAllEvents(snapshots) {
1773
+ const evts = [];
1774
+ for (const snap of snapshots) evts.push(...snap);
1775
+ sortEvents(evts);
1776
+ return evts;
1777
+ }
1778
+ const seedSnapshots = eventNodes.map(
1779
+ (n) => n.cache ?? []
1780
+ );
1781
+ const sortedSeed = collectAllEvents(seedSnapshots);
1782
+ const frozenSeed = freezeInputs ? Object.freeze(sortedSeed) : sortedSeed;
1783
+ let lastProcessedCount = 0;
1784
+ let scanState = initial;
1785
+ if (mode === "scan" && sortedSeed.length > 0) {
1786
+ scanState = reducer(initial, frozenSeed);
1787
+ lastProcessedCount = sortedSeed.length;
1788
+ }
1789
+ const seedState = mode === "replay" ? reducer(initial, frozenSeed) : scanState;
1790
+ const saveDebounceMs = snapshotOpts?.saveDebounceMs ?? 1e3;
1791
+ const saveEvery = snapshotOpts?.saveEvery ?? 1e3;
1792
+ let saveTimer;
1793
+ let savesSinceLastFlush = 0;
1794
+ function scheduleSave(currentState) {
1795
+ if (!snapshotOpts?.save) return;
1796
+ savesSinceLastFlush += 1;
1797
+ if (savesSinceLastFlush >= saveEvery) {
1798
+ savesSinceLastFlush = 0;
1799
+ if (saveTimer !== void 0) {
1800
+ clearTimeout(saveTimer);
1801
+ saveTimer = void 0;
1802
+ }
1803
+ const result = snapshotOpts.save(currentState);
1804
+ if (result instanceof Promise) result.catch(() => void 0);
1805
+ return;
1806
+ }
1807
+ if (saveTimer !== void 0) clearTimeout(saveTimer);
1808
+ saveTimer = setTimeout(() => {
1809
+ saveTimer = void 0;
1810
+ savesSinceLastFlush = 0;
1811
+ const result = snapshotOpts.save(currentState);
1812
+ if (result instanceof Promise) result.catch(() => void 0);
1813
+ }, saveDebounceMs);
1814
+ }
1815
+ const projNode = this.derived(
1816
+ name,
1817
+ eventNames,
1818
+ (batchData, ctx) => {
1819
+ const snapshots = batchData.map(
1820
+ (batch2, i) => batch2 != null && batch2.length > 0 ? batch2.at(-1) : ctx.prevData[i]
1821
+ );
1822
+ const allEvents = collectAllEvents(snapshots);
1823
+ let newState;
1824
+ if (mode === "replay") {
1825
+ const frozen = freezeInputs ? Object.freeze(allEvents) : allEvents;
1826
+ newState = reducer(initial, frozen);
1827
+ } else {
1828
+ const newOnly = allEvents.slice(lastProcessedCount);
1829
+ lastProcessedCount = allEvents.length;
1830
+ const frozenNew = freezeInputs ? Object.freeze(newOnly) : newOnly;
1831
+ newState = reducer(scanState, frozenNew);
1832
+ scanState = newState;
1833
+ }
1834
+ scheduleSave(newState);
1835
+ return [newState];
1836
+ },
1837
+ {
1838
+ meta: cqrsMeta("projection", { projection_name: name, source_events: eventNames }),
1839
+ guard: PROJECTION_GUARD,
1840
+ initial: seedState
1841
+ }
1842
+ );
1843
+ this.addDisposer((0, import_extra4.keepalive)(projNode));
1844
+ this.addDisposer(() => {
1845
+ if (saveTimer !== void 0) {
1846
+ clearTimeout(saveTimer);
1847
+ saveTimer = void 0;
1848
+ }
1849
+ });
1850
+ this._projections.add(name);
1851
+ const rebuild = async (rebuildOpts) => {
1852
+ try {
1853
+ const pageSize = rebuildOpts?.pageSize ?? 1e3;
1854
+ const tier = rebuildOpts?.fromTier ?? this._attachedEventTiers[0]?.[0];
1855
+ const preBuildCount = collectAllEvents(
1856
+ eventNodes.map((n) => n.cache ?? [])
1857
+ ).length;
1858
+ let rebuildState = initial;
1859
+ if (snapshotOpts?.load) {
1860
+ const loaded = await snapshotOpts.load();
1861
+ if (loaded !== void 0) rebuildState = loaded;
1862
+ }
1863
+ if (!tier || !tier.loadEntries) {
1864
+ const inMemory = collectAllEvents(
1865
+ eventNodes.map((n) => n.cache ?? [])
1866
+ );
1867
+ const frozen = freezeInputs ? Object.freeze(inMemory) : inMemory;
1868
+ rebuildState = reducer(rebuildState, frozen);
1869
+ } else {
1870
+ const watchedEvents = new Set(eventNames);
1871
+ let cursor;
1872
+ let done = false;
1873
+ while (!done) {
1874
+ const result = await tier.loadEntries({ cursor, pageSize });
1875
+ const page = [...result.entries].filter((e) => watchedEvents.has(e.type));
1876
+ sortEvents(page);
1877
+ const frozenPage = freezeInputs ? Object.freeze(page) : page;
1878
+ rebuildState = reducer(rebuildState, frozenPage);
1879
+ cursor = result.cursor;
1880
+ done = !cursor || result.entries.length === 0;
1881
+ }
1882
+ }
1883
+ if (mode === "scan") {
1884
+ const allInMemory = collectAllEvents(
1885
+ eventNodes.map((n) => n.cache ?? [])
1886
+ );
1887
+ const pendingEvents = allInMemory.slice(preBuildCount);
1888
+ if (pendingEvents.length > 0) {
1889
+ const frozenPending = freezeInputs ? Object.freeze(pendingEvents) : pendingEvents;
1890
+ rebuildState = reducer(rebuildState, frozenPending);
1891
+ }
1892
+ scanState = rebuildState;
1893
+ lastProcessedCount = allInMemory.length;
1894
+ }
1895
+ projNode.emit(rebuildState, { internal: true });
1896
+ return rebuildState;
1897
+ } catch (err) {
1898
+ throw new RebuildError(name, err);
1899
+ }
1900
+ };
1901
+ const reset = async () => {
1902
+ try {
1903
+ let baseState = initial;
1904
+ if (snapshotOpts?.load) {
1905
+ const loaded = await snapshotOpts.load();
1906
+ if (loaded !== void 0) baseState = loaded;
1907
+ }
1908
+ const inMemory = collectAllEvents(
1909
+ eventNodes.map((n) => n.cache ?? [])
1910
+ );
1911
+ const frozen = freezeInputs ? Object.freeze(inMemory) : inMemory;
1912
+ const newState = reducer(baseState, frozen);
1913
+ if (mode === "scan") {
1914
+ scanState = newState;
1915
+ lastProcessedCount = inMemory.length;
1916
+ }
1917
+ projNode.emit(newState, { internal: true });
1918
+ return newState;
1919
+ } catch (err) {
1920
+ throw new RebuildError(name, err);
1921
+ }
1922
+ };
1923
+ return { node: projNode, rebuild, reset };
1924
+ }
1925
+ // -- Sagas ----------------------------------------------------------------
1926
+ /**
1927
+ * Register an event-driven side effect. Runs handler for each **new** event
1928
+ * from the specified streams (tracks last-processed entry count per stream).
1929
+ *
1930
+ * The saga node carries dynamic `meta.error` — a reactive companion that
1931
+ * holds the last handler error (or `null` on success). Handler errors do
1932
+ * not propagate out of the saga run (the event cursor still advances so
1933
+ * the same entry is not delivered twice).
1934
+ */
1935
+ saga(name, eventNames, handler, opts = {}) {
1936
+ const _eventNodes = eventNames.map((eName) => {
1937
+ if (!this._eventLogs.has(eName)) this.event(eName);
1938
+ return this._eventLogs.get(eName).node;
1939
+ });
1940
+ const cursors = registerCursorMap(this, `${name}_cursor`, eventNames, 0);
1941
+ const invocations = createAuditLog({
1942
+ name: `${name}_invocations`,
1943
+ retainedLimit: this._retainedLimit,
1944
+ graph: this
1945
+ });
1946
+ const aggregateFilter = opts.aggregateId;
1947
+ const errorPolicy = opts.errorPolicy ?? "advance";
1948
+ const latestCursors = /* @__PURE__ */ new Map();
1949
+ for (const eName of eventNames) {
1950
+ const cursor = cursors[eName];
1951
+ latestCursors.set(eName, cursor.cache ?? 0);
1952
+ const sub = cursor.subscribe((msgs) => {
1953
+ for (const m of msgs) if (m[0] === import_core8.DATA) latestCursors.set(eName, m[1]);
1954
+ });
1955
+ this.addDisposer(sub);
1956
+ }
1957
+ const auditedHandler = mutate(
1958
+ (ev, _eName) => {
1959
+ handler(ev);
1960
+ },
1961
+ {
1962
+ frame: "inline",
1963
+ log: invocations,
1964
+ freeze: false,
1965
+ ...opts.handlerVersion !== void 0 ? { handlerVersion: opts.handlerVersion } : {},
1966
+ // D5 (qa lock): always include the `aggregateId` key (even when
1967
+ // undefined) for parity with the pre-Tier-8 saga record shape.
1968
+ // Consumers using `Object.hasOwn(record, "aggregateId")` or JSON
1969
+ // serialization shape would observe a pre-1.0 break otherwise.
1970
+ onSuccessRecord: ([ev, eName], _r, { t_ns }) => ({
1971
+ eventType: eName,
1972
+ outcome: "success",
1973
+ aggregateId: ev.aggregateId,
1974
+ event: ev,
1975
+ t_ns
1976
+ }),
1977
+ onFailureRecord: ([ev, eName], err, { t_ns, errorType }) => ({
1978
+ eventType: eName,
1979
+ outcome: "failure",
1980
+ error: err,
1981
+ errorType,
1982
+ aggregateId: ev.aggregateId,
1983
+ event: ev,
1984
+ t_ns
1985
+ })
1986
+ }
1987
+ );
1988
+ const sagaRef = {};
1989
+ const sagaNode = this.effect(
1990
+ name,
1991
+ eventNames,
1992
+ (snapshots, _up) => {
1993
+ const errNode = sagaRef.n.meta.error;
1994
+ for (let i = 0; i < snapshots.length; i++) {
1995
+ const batch2 = snapshots[i];
1996
+ if (batch2 == null || batch2.length === 0) continue;
1997
+ const entries = batch2.at(-1);
1998
+ if (!entries) continue;
1999
+ const eName = eventNames[i];
2000
+ const cursor = cursors[eName];
2001
+ const lastCount = latestCursors.get(eName) ?? 0;
2002
+ if (entries.length > lastCount) {
2003
+ const newEntries = entries.slice(lastCount);
2004
+ let advancedTo = lastCount;
2005
+ for (const entry of newEntries) {
2006
+ const ev = entry;
2007
+ if (aggregateFilter !== void 0 && ev.aggregateId !== aggregateFilter) {
2008
+ advancedTo += 1;
2009
+ continue;
2010
+ }
2011
+ try {
2012
+ auditedHandler(ev, eName);
2013
+ errNode.emit(null, { internal: true });
2014
+ advancedTo += 1;
2015
+ } catch (err) {
2016
+ errNode.emit(err, { internal: true });
2017
+ if (errorPolicy === "hold") break;
2018
+ advancedTo += 1;
2019
+ }
2020
+ }
2021
+ cursor.emit(advancedTo);
2022
+ }
2023
+ }
2024
+ },
2025
+ {
2026
+ meta: {
2027
+ ...cqrsMeta("saga", { saga_name: name, source_events: eventNames }),
2028
+ error: null
2029
+ }
2030
+ }
2031
+ );
2032
+ sagaRef.n = sagaNode;
2033
+ this.addDisposer((0, import_extra4.keepalive)(sagaNode));
2034
+ this._sagas.add(name);
2035
+ return {
2036
+ node: sagaNode,
2037
+ invocations,
2038
+ audit: invocations,
2039
+ cursors
2040
+ };
2041
+ }
2042
+ };
2043
+ function cqrs(name, opts) {
2044
+ const g = new CqrsGraph(name, opts);
2045
+ const { factory: _f, factoryArgs: _fa, ...tagArgs } = opts ?? {};
2046
+ g.tagFactory("cqrs", (0, import_core8.placeholderArgs)(tagArgs));
2047
+ return g;
2048
+ }
2049
+
2050
+ // src/compat/nestjs/module.ts
2051
+ var GraphReflyRootLifecycle = class {
2052
+ constructor(graph) {
2053
+ this.graph = graph;
2054
+ }
2055
+ onModuleDestroy() {
2056
+ this.graph.destroy();
2057
+ }
2058
+ };
2059
+ var GraphReflyRequestLifecycle = class {
2060
+ graph = new import_graph3.Graph("request");
2061
+ onModuleDestroy() {
2062
+ this.graph.destroy();
2063
+ }
2064
+ };
2065
+ var _GraphReflyModule_decorators, _init;
2066
+ _GraphReflyModule_decorators = [(0, import_common2.Module)({})];
2067
+ var _GraphReflyModule = class _GraphReflyModule {
2068
+ /**
2069
+ * Register the root `Graph` singleton in the NestJS DI container.
2070
+ *
2071
+ * The root graph is `@Global()` — injectable everywhere without importing
2072
+ * the module again. Use `@InjectGraph()` to inject it.
2073
+ *
2074
+ * Lifecycle:
2075
+ * - **init:** Graph created in factory. If `build` is provided, it runs
2076
+ * first (registers nodes/mounts). If `snapshot` is provided, values
2077
+ * are restored via `graph.restore()`.
2078
+ * - **destroy:** Calls `graph.destroy()` — sends `[[TEARDOWN]]` to all
2079
+ * nodes, including mounted feature subgraphs (cascading teardown).
2080
+ */
2081
+ static forRoot(opts) {
2082
+ const options = opts ?? {};
2083
+ const graphName = options.name ?? "root";
2084
+ const providers = [
2085
+ {
2086
+ provide: GRAPHREFLY_ROOT_GRAPH,
2087
+ useFactory: () => {
2088
+ const g = new import_graph3.Graph(graphName);
2089
+ if (options.build) options.build(g);
2090
+ if (options.snapshot) g.restore(options.snapshot);
2091
+ return g;
2092
+ }
2093
+ },
2094
+ {
2095
+ provide: /* @__PURE__ */ Symbol.for("graphrefly:root-lifecycle"),
2096
+ useFactory: (graph) => new GraphReflyRootLifecycle(graph),
2097
+ inject: [GRAPHREFLY_ROOT_GRAPH]
2098
+ },
2099
+ {
2100
+ provide: GraphReflyEventExplorer,
2101
+ useFactory: (graph, moduleRef) => new GraphReflyEventExplorer(graph, moduleRef),
2102
+ inject: [GRAPHREFLY_ROOT_GRAPH, import_core9.ModuleRef]
2103
+ }
2104
+ ];
2105
+ if (options.nodes) {
2106
+ for (const path of options.nodes) {
2107
+ providers.push({
2108
+ provide: getNodeToken(path),
2109
+ useFactory: (graph) => graph.resolve(path),
2110
+ inject: [GRAPHREFLY_ROOT_GRAPH]
2111
+ });
2112
+ }
2113
+ }
2114
+ if (options.requestScope) {
2115
+ providers.push(
2116
+ {
2117
+ provide: /* @__PURE__ */ Symbol.for("graphrefly:request-lifecycle"),
2118
+ useFactory: () => new GraphReflyRequestLifecycle(),
2119
+ scope: import_common2.Scope.REQUEST
2120
+ },
2121
+ {
2122
+ provide: GRAPHREFLY_REQUEST_GRAPH,
2123
+ useFactory: (lifecycle) => lifecycle.graph,
2124
+ inject: [/* @__PURE__ */ Symbol.for("graphrefly:request-lifecycle")],
2125
+ scope: import_common2.Scope.REQUEST
2126
+ }
2127
+ );
2128
+ }
2129
+ return {
2130
+ module: _GraphReflyModule,
2131
+ global: true,
2132
+ providers,
2133
+ exports: [
2134
+ GRAPHREFLY_ROOT_GRAPH,
2135
+ ...(options.nodes ?? []).map(getNodeToken),
2136
+ ...options.requestScope ? [GRAPHREFLY_REQUEST_GRAPH] : []
2137
+ ]
2138
+ };
2139
+ }
2140
+ /**
2141
+ * Register a feature subgraph that auto-mounts into the root graph.
2142
+ *
2143
+ * The feature graph is created in the factory, built/restored, then
2144
+ * mounted into root via `root.mount(name, featureGraph)`. On app
2145
+ * shutdown, root's `graph.destroy()` cascades TEARDOWN through all
2146
+ * mounted subgraphs (no explicit remove needed).
2147
+ *
2148
+ * Node tokens are auto-qualified as `featureName::path` to prevent
2149
+ * collisions between features declaring nodes with the same local name.
2150
+ *
2151
+ * Injectable via `@InjectGraph(name)`.
2152
+ */
2153
+ static forFeature(opts) {
2154
+ const providers = [
2155
+ {
2156
+ provide: getGraphToken(opts.name),
2157
+ useFactory: (rootGraph) => {
2158
+ const g = new import_graph3.Graph(opts.name);
2159
+ if (opts.build) opts.build(g);
2160
+ if (opts.snapshot) g.restore(opts.snapshot);
2161
+ rootGraph.mount(opts.name, g);
2162
+ return g;
2163
+ },
2164
+ inject: [GRAPHREFLY_ROOT_GRAPH]
2165
+ }
2166
+ ];
2167
+ if (opts.nodes) {
2168
+ for (const path of opts.nodes) {
2169
+ providers.push({
2170
+ provide: getNodeToken(`${opts.name}::${path}`),
2171
+ useFactory: (graph) => graph.resolve(path),
2172
+ inject: [getGraphToken(opts.name)]
2173
+ });
2174
+ }
2175
+ }
2176
+ return {
2177
+ module: _GraphReflyModule,
2178
+ providers,
2179
+ exports: [
2180
+ getGraphToken(opts.name),
2181
+ ...(opts.nodes ?? []).map((p) => getNodeToken(`${opts.name}::${p}`))
2182
+ ]
2183
+ };
2184
+ }
2185
+ /**
2186
+ * Register a CQRS subgraph that auto-mounts into the root graph.
2187
+ *
2188
+ * Creates a `CqrsGraph` via the `cqrs()` factory (roadmap §4.5), mounts it
2189
+ * into the root graph, and exposes it for DI via `@InjectGraph(name)`.
2190
+ *
2191
+ * CQRS decorators (`@CommandHandler`, `@EventHandler`, `@QueryHandler`,
2192
+ * `@SagaHandler`) are discovered by the explorer and wired to this graph
2193
+ * on module init.
2194
+ *
2195
+ * @example
2196
+ * ```ts
2197
+ * GraphReflyModule.forCqrs({
2198
+ * name: "orders",
2199
+ * build: (g) => {
2200
+ * g.event("orderPlaced");
2201
+ * g.projection({ name: "orderCount", events: ["orderPlaced"], reducer: (_s, evts) => evts.length, initial: 0 });
2202
+ * },
2203
+ * })
2204
+ * ```
2205
+ */
2206
+ static forCqrs(opts) {
2207
+ const providers = [
2208
+ {
2209
+ provide: getGraphToken(opts.name),
2210
+ useFactory: (rootGraph) => {
2211
+ const g = cqrs(opts.name, opts.cqrs);
2212
+ if (opts.eventStorage) g.attachEventStorage(opts.eventStorage);
2213
+ if (opts.build) opts.build(g);
2214
+ rootGraph.mount(opts.name, g);
2215
+ return g;
2216
+ },
2217
+ inject: [GRAPHREFLY_ROOT_GRAPH]
2218
+ }
2219
+ ];
2220
+ if (opts.nodes) {
2221
+ for (const path of opts.nodes) {
2222
+ providers.push({
2223
+ provide: getNodeToken(`${opts.name}::${path}`),
2224
+ useFactory: (graph) => graph.resolve(path),
2225
+ inject: [getGraphToken(opts.name)]
2226
+ });
2227
+ }
2228
+ }
2229
+ return {
2230
+ module: _GraphReflyModule,
2231
+ providers,
2232
+ exports: [
2233
+ getGraphToken(opts.name),
2234
+ ...(opts.nodes ?? []).map((p) => getNodeToken(`${opts.name}::${p}`))
2235
+ ]
2236
+ };
2237
+ }
2238
+ };
2239
+ _init = __decoratorStart(null);
2240
+ _GraphReflyModule = __decorateElement(_init, 0, "GraphReflyModule", _GraphReflyModule_decorators, _GraphReflyModule);
2241
+ __runInitializers(_init, 1, _GraphReflyModule);
2242
+ var GraphReflyModule = _GraphReflyModule;
2243
+ //# sourceMappingURL=index.cjs.map