@graphrefly/graphrefly 0.27.0 → 0.29.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 (428) hide show
  1. package/dist/backoff-HPZMEZNF.js +1 -0
  2. package/dist/cascading-Bp99ckMJ.d.ts +180 -0
  3. package/dist/cascading-CcAgRacD.d.cts +180 -0
  4. package/dist/chunk-22F4K3G7.js +1 -0
  5. package/dist/chunk-22SVXUPB.js +64 -0
  6. package/dist/chunk-2GQREQ6C.js +1 -0
  7. package/dist/chunk-3JXNEPCD.js +2 -0
  8. package/dist/chunk-4JJCCD5S.js +2 -0
  9. package/dist/chunk-4OFIQ66T.js +1 -0
  10. package/dist/chunk-4V4C7K56.js +1 -0
  11. package/dist/chunk-4VVTGLXJ.js +1 -0
  12. package/dist/chunk-567NWZ3T.js +1 -0
  13. package/dist/chunk-5JDE5JHE.js +1 -0
  14. package/dist/chunk-5QDBSZBV.js +1 -0
  15. package/dist/chunk-5Z4HDCO6.js +1 -0
  16. package/dist/chunk-63FFOHLA.js +1 -0
  17. package/dist/chunk-6QZNQS5B.js +1 -0
  18. package/dist/chunk-7JDLFI6N.js +1 -0
  19. package/dist/chunk-7TDOES3L.js +1 -0
  20. package/dist/chunk-A7IAQQ63.js +1 -0
  21. package/dist/chunk-AMG5VBHW.js +1 -0
  22. package/dist/chunk-AUY2YKCO.js +1 -0
  23. package/dist/chunk-AV3PIDFQ.js +1 -0
  24. package/dist/chunk-BA5URFYW.js +1 -0
  25. package/dist/chunk-BKPLTBL5.js +1 -0
  26. package/dist/chunk-BZP5T4X6.js +1 -0
  27. package/dist/chunk-CK2E7BTU.js +1 -0
  28. package/dist/chunk-CSJE2EKV.js +1 -0
  29. package/dist/chunk-E3AXATVZ.js +9 -0
  30. package/dist/chunk-ESMPEKEV.js +1 -0
  31. package/dist/chunk-GJR3P6JG.js +1 -0
  32. package/dist/chunk-GNCBXARM.js +1 -0
  33. package/dist/chunk-GPW2V3RE.js +1 -0
  34. package/dist/chunk-HSIEYSDY.js +1 -0
  35. package/dist/chunk-I6VIH3VA.js +1 -0
  36. package/dist/chunk-ISCENNXS.js +1 -0
  37. package/dist/chunk-JYOUF6UQ.js +1 -0
  38. package/dist/chunk-KASHOCF5.js +1 -0
  39. package/dist/chunk-LGSNR4LU.js +5 -0
  40. package/dist/chunk-LVGBLZM2.js +1 -0
  41. package/dist/chunk-MGKAO4EK.js +7 -0
  42. package/dist/chunk-NSG4C6BF.js +23 -0
  43. package/dist/chunk-OL33ZI6R.js +1 -0
  44. package/dist/chunk-PCZ35NXD.js +78 -0
  45. package/dist/chunk-PGMUCUHG.js +43 -0
  46. package/dist/chunk-QYADASLV.js +1 -0
  47. package/dist/chunk-RD52SNH2.js +1 -0
  48. package/dist/chunk-SLMYTGTU.js +1 -0
  49. package/dist/chunk-TWMEGG45.js +1 -0
  50. package/dist/chunk-UVJQ35G2.js +1 -0
  51. package/dist/chunk-VGTCGNRX.js +18 -0
  52. package/dist/chunk-VIMF6LGM.js +1 -0
  53. package/dist/chunk-VJLMUKOI.js +1 -0
  54. package/dist/chunk-VWPRPPKR.js +1 -0
  55. package/dist/chunk-W4TSQ6RJ.js +1 -0
  56. package/dist/chunk-WM7H7WTY.js +3 -0
  57. package/dist/chunk-Y32RJO24.js +1 -0
  58. package/dist/chunk-Y53B6NS4.js +1 -0
  59. package/dist/compat/index.cjs +15 -7656
  60. package/dist/compat/index.d.cts +15 -14
  61. package/dist/compat/index.d.ts +15 -14
  62. package/dist/compat/index.js +1 -50
  63. package/dist/compat/jotai/index.cjs +1 -2048
  64. package/dist/compat/jotai/index.d.cts +2 -2
  65. package/dist/compat/jotai/index.d.ts +2 -2
  66. package/dist/compat/jotai/index.js +1 -9
  67. package/dist/compat/nanostores/index.cjs +1 -2175
  68. package/dist/compat/nanostores/index.d.cts +2 -2
  69. package/dist/compat/nanostores/index.d.ts +2 -2
  70. package/dist/compat/nanostores/index.js +1 -23
  71. package/dist/compat/nestjs/index.cjs +15 -6782
  72. package/dist/compat/nestjs/index.d.cts +7 -6
  73. package/dist/compat/nestjs/index.d.ts +7 -6
  74. package/dist/compat/nestjs/index.js +1 -83
  75. package/dist/compat/react/index.cjs +1 -141
  76. package/dist/compat/react/index.d.cts +2 -2
  77. package/dist/compat/react/index.d.ts +2 -2
  78. package/dist/compat/react/index.js +1 -12
  79. package/dist/compat/solid/index.cjs +1 -128
  80. package/dist/compat/solid/index.d.cts +2 -2
  81. package/dist/compat/solid/index.d.ts +2 -2
  82. package/dist/compat/solid/index.js +1 -12
  83. package/dist/compat/svelte/index.cjs +1 -131
  84. package/dist/compat/svelte/index.d.cts +2 -2
  85. package/dist/compat/svelte/index.d.ts +2 -2
  86. package/dist/compat/svelte/index.js +1 -12
  87. package/dist/compat/vue/index.cjs +1 -146
  88. package/dist/compat/vue/index.d.cts +2 -2
  89. package/dist/compat/vue/index.d.ts +2 -2
  90. package/dist/compat/vue/index.js +1 -12
  91. package/dist/compat/zustand/index.cjs +7 -4931
  92. package/dist/compat/zustand/index.d.cts +5 -5
  93. package/dist/compat/zustand/index.d.ts +5 -5
  94. package/dist/compat/zustand/index.js +1 -12
  95. package/dist/composite-BL-llbnE.d.ts +69 -0
  96. package/dist/composite-Dze--DaA.d.cts +69 -0
  97. package/dist/core/index.cjs +1 -2271
  98. package/dist/core/index.d.cts +4 -4
  99. package/dist/core/index.d.ts +4 -4
  100. package/dist/core/index.js +1 -110
  101. package/dist/extra/browser.cjs +1 -0
  102. package/dist/extra/browser.d.cts +3 -0
  103. package/dist/extra/browser.d.ts +3 -0
  104. package/dist/extra/browser.js +1 -0
  105. package/dist/extra/index.cjs +24 -9971
  106. package/dist/extra/index.d.cts +13 -6
  107. package/dist/extra/index.d.ts +13 -6
  108. package/dist/extra/index.js +1 -381
  109. package/dist/extra/node.cjs +3 -0
  110. package/dist/extra/node.d.cts +81 -0
  111. package/dist/extra/node.d.ts +81 -0
  112. package/dist/extra/node.js +2 -0
  113. package/dist/extra/operators.cjs +1 -0
  114. package/dist/extra/operators.d.cts +910 -0
  115. package/dist/extra/operators.d.ts +910 -0
  116. package/dist/extra/operators.js +1 -0
  117. package/dist/extra/reactive.cjs +1 -0
  118. package/dist/extra/reactive.d.cts +352 -0
  119. package/dist/extra/reactive.d.ts +352 -0
  120. package/dist/extra/reactive.js +1 -0
  121. package/dist/extra/sources.cjs +1 -2486
  122. package/dist/extra/sources.d.cts +6 -2
  123. package/dist/extra/sources.d.ts +6 -2
  124. package/dist/extra/sources.js +1 -57
  125. package/dist/extra/storage-browser.cjs +1 -0
  126. package/dist/extra/storage-browser.d.cts +71 -0
  127. package/dist/extra/storage-browser.d.ts +71 -0
  128. package/dist/extra/storage-browser.js +1 -0
  129. package/dist/extra/storage-core.cjs +1 -0
  130. package/dist/extra/storage-core.d.cts +98 -0
  131. package/dist/extra/storage-core.d.ts +98 -0
  132. package/dist/extra/storage-core.js +1 -0
  133. package/dist/extra/storage-node.cjs +2 -0
  134. package/dist/extra/storage-node.d.cts +60 -0
  135. package/dist/extra/storage-node.d.ts +60 -0
  136. package/dist/extra/storage-node.js +1 -0
  137. package/dist/fallback-BaTS7vVY.d.cts +258 -0
  138. package/dist/fallback-eOm3LNxP.d.ts +258 -0
  139. package/dist/graph/index.cjs +7 -5030
  140. package/dist/graph/index.d.cts +6 -5
  141. package/dist/graph/index.d.ts +6 -5
  142. package/dist/graph/index.js +1 -50
  143. package/dist/{graph-DNCrvZSn.d.cts → graph-DgohqXK-.d.cts} +151 -32
  144. package/dist/{graph-CCwGKLCm.d.ts → graph-Qjg9gWHI.d.ts} +151 -32
  145. package/dist/{index-BwfLUNw4.d.ts → index-2BVuRCI4.d.ts} +173 -2040
  146. package/dist/{index-BPVt8kqc.d.ts → index-2NvguqQA.d.ts} +10 -195
  147. package/dist/index-A65LZhoM.d.ts +186 -0
  148. package/dist/{index-DlLp-2Xn.d.cts → index-B-8FCEua.d.cts} +10 -195
  149. package/dist/index-B-gqvYel.d.ts +135 -0
  150. package/dist/index-B2PRuolf.d.cts +86 -0
  151. package/dist/index-BJqt9EwW.d.ts +231 -0
  152. package/dist/{index-BHlKbUwO.d.cts → index-BKjT5DiZ.d.cts} +173 -2040
  153. package/dist/{index-C0svESO4.d.ts → index-BM8BU4q6.d.ts} +1 -1
  154. package/dist/{index-VdHQMPy1.d.ts → index-BQaEnxBf.d.ts} +1 -1
  155. package/dist/index-BSfwiy5B.d.ts +192 -0
  156. package/dist/index-BTSkeCZs.d.cts +291 -0
  157. package/dist/index-BUVtw1Ay.d.cts +186 -0
  158. package/dist/index-BUi57v_p.d.ts +163 -0
  159. package/dist/{messaging-Gt4LPbyA.d.cts → index-BanNUILp.d.cts} +31 -93
  160. package/dist/{audit-DRlSzBu9.d.ts → index-BayHDRx6.d.cts} +27 -21
  161. package/dist/{index-B6D3QNSA.d.ts → index-BiyjsZ0m.d.ts} +148 -20
  162. package/dist/index-BqZ6vB2A.d.ts +2057 -0
  163. package/dist/{memory-li6FL5RM.d.ts → index-BuVidq3D.d.cts} +26 -26
  164. package/dist/index-Byh-xTyp.d.ts +105 -0
  165. package/dist/index-C08QPDcV.d.cts +321 -0
  166. package/dist/{demo-shell-BDkOptd6.d.ts → index-C66RJiX8.d.ts} +14 -14
  167. package/dist/index-C8RfjffH.d.ts +291 -0
  168. package/dist/index-CA1Cu7Ud.d.ts +873 -0
  169. package/dist/{index-ByQxazQJ.d.cts → index-CABbltIu.d.cts} +1 -1
  170. package/dist/{index-VHqptjhu.d.cts → index-CHEBsnYv.d.cts} +1 -1
  171. package/dist/{index-BuEoe-Qu.d.ts → index-CI0yDnLp.d.ts} +9 -9
  172. package/dist/{index-B9B7_HEY.d.ts → index-CJ45TW-h.d.ts} +1 -1
  173. package/dist/{index-CO8uBlUh.d.cts → index-CJZKZoo4.d.cts} +148 -20
  174. package/dist/{index-wEn0eFe8.d.ts → index-CX2tFJL1.d.ts} +1 -1
  175. package/dist/{index-BaSM3aYt.d.ts → index-CcWOJ6F0.d.ts} +3 -3
  176. package/dist/{audit-ClmqGOCx.d.cts → index-CiaVoZGo.d.ts} +27 -21
  177. package/dist/{index-Dzk2hrlR.d.ts → index-Ct5CWc4E.d.ts} +1 -1
  178. package/dist/index-D38duMCv.d.cts +357 -0
  179. package/dist/{index-C8oil6M6.d.ts → index-D5XJ2tSx.d.ts} +30 -6
  180. package/dist/{index-DO_6JN9Z.d.cts → index-D80do5jX.d.cts} +1 -1
  181. package/dist/index-D9HKAH_-.d.cts +231 -0
  182. package/dist/index-DBe_8XW5.d.cts +143 -0
  183. package/dist/{memory-C6Z2tGpC.d.cts → index-DCeTyFlB.d.ts} +26 -26
  184. package/dist/index-DDy8eeXS.d.ts +321 -0
  185. package/dist/index-DJ5oNBc8.d.ts +143 -0
  186. package/dist/{index-CI3DprxP.d.cts → index-DP0_O3ls.d.cts} +30 -6
  187. package/dist/{demo-shell-Crid1WdR.d.cts → index-DX8xS-yB.d.cts} +14 -14
  188. package/dist/index-DiZejfCI.d.cts +2057 -0
  189. package/dist/index-DknyJ2Fu.d.cts +163 -0
  190. package/dist/index-DoWMs-Kk.d.cts +135 -0
  191. package/dist/{messaging-XDoYablx.d.ts → index-DuB5aO4-.d.ts} +31 -93
  192. package/dist/index-DwjJGKxV.d.ts +357 -0
  193. package/dist/{index-B6EhDnjH.d.cts → index-H_oxVec5.d.cts} +1 -1
  194. package/dist/{index-3lsddbbS.d.ts → index-IMAHq-ia.d.ts} +1 -1
  195. package/dist/{index-B1tloyhO.d.cts → index-U1nir7MX.d.cts} +1 -1
  196. package/dist/index-Vg7tORgk.d.ts +86 -0
  197. package/dist/index-dig-r2tQ.d.cts +873 -0
  198. package/dist/{index-CxFrXH4m.d.ts → index-gsT79Xu9.d.ts} +1 -1
  199. package/dist/{index-D8wS_PeY.d.cts → index-i99Ka8s7.d.cts} +9 -9
  200. package/dist/index-iKkyJosF.d.cts +105 -0
  201. package/dist/{index-Xi3u0HCQ.d.cts → index-jleeotBT.d.cts} +1 -1
  202. package/dist/{index-DVGiGFGT.d.cts → index-kykKWwV-.d.cts} +3 -3
  203. package/dist/index-vgcLF5TH.d.cts +192 -0
  204. package/dist/{index-DYme44FM.d.cts → index-y1RllPn4.d.cts} +1 -1
  205. package/dist/index.cjs +151 -24142
  206. package/dist/index.d.cts +69 -2099
  207. package/dist/index.d.ts +69 -2099
  208. package/dist/index.js +1 -3868
  209. package/dist/{meta-CbznRPYJ.d.ts → meta-CX7YsOzp.d.cts} +5 -5
  210. package/dist/{meta-BxCA7rcr.d.cts → meta-CckhhFRd.d.ts} +5 -5
  211. package/dist/{node-BmerH3kS.d.cts → node-Dd6wHSib.d.cts} +71 -11
  212. package/dist/{node-BmerH3kS.d.ts → node-Dd6wHSib.d.ts} +71 -11
  213. package/dist/{observable-BgGUwcqp.d.ts → observable-BZJgo616.d.ts} +1 -1
  214. package/dist/{observable-DJt_AxzQ.d.cts → observable-kwzpLvbi.d.cts} +1 -1
  215. package/dist/patterns/ai/browser.cjs +25 -0
  216. package/dist/patterns/ai/browser.d.cts +127 -0
  217. package/dist/patterns/ai/browser.d.ts +127 -0
  218. package/dist/patterns/ai/browser.js +3 -0
  219. package/dist/patterns/ai/index.cjs +92 -0
  220. package/dist/patterns/ai/index.d.cts +17 -0
  221. package/dist/patterns/ai/index.d.ts +17 -0
  222. package/dist/patterns/ai/index.js +1 -0
  223. package/dist/patterns/ai/node.cjs +2 -0
  224. package/dist/patterns/ai/node.d.cts +58 -0
  225. package/dist/patterns/ai/node.d.ts +58 -0
  226. package/dist/patterns/ai/node.js +1 -0
  227. package/dist/patterns/audit/index.cjs +7 -0
  228. package/dist/patterns/audit/index.d.cts +6 -0
  229. package/dist/patterns/audit/index.d.ts +6 -0
  230. package/dist/patterns/audit/index.js +1 -0
  231. package/dist/patterns/cqrs/index.cjs +7 -0
  232. package/dist/patterns/cqrs/index.d.cts +5 -0
  233. package/dist/patterns/cqrs/index.d.ts +5 -0
  234. package/dist/patterns/cqrs/index.js +1 -0
  235. package/dist/patterns/demo-shell/index.cjs +8 -0
  236. package/dist/patterns/demo-shell/index.d.cts +6 -0
  237. package/dist/patterns/demo-shell/index.d.ts +6 -0
  238. package/dist/patterns/demo-shell/index.js +1 -0
  239. package/dist/patterns/domain-templates/index.cjs +7 -0
  240. package/dist/patterns/domain-templates/index.d.cts +5 -0
  241. package/dist/patterns/domain-templates/index.d.ts +5 -0
  242. package/dist/patterns/domain-templates/index.js +1 -0
  243. package/dist/patterns/graphspec/index.cjs +84 -0
  244. package/dist/patterns/graphspec/index.d.cts +7 -0
  245. package/dist/patterns/graphspec/index.d.ts +7 -0
  246. package/dist/patterns/graphspec/index.js +1 -0
  247. package/dist/patterns/guarded-execution/index.cjs +7 -0
  248. package/dist/patterns/guarded-execution/index.d.cts +7 -0
  249. package/dist/patterns/guarded-execution/index.d.ts +7 -0
  250. package/dist/patterns/guarded-execution/index.js +1 -0
  251. package/dist/patterns/harness/index.cjs +49 -0
  252. package/dist/patterns/harness/index.d.cts +11 -0
  253. package/dist/patterns/harness/index.d.ts +11 -0
  254. package/dist/patterns/harness/index.js +1 -0
  255. package/dist/patterns/job-queue/index.cjs +7 -0
  256. package/dist/patterns/job-queue/index.d.cts +5 -0
  257. package/dist/patterns/job-queue/index.d.ts +5 -0
  258. package/dist/patterns/job-queue/index.js +1 -0
  259. package/dist/patterns/lens/index.cjs +7 -0
  260. package/dist/patterns/lens/index.d.cts +7 -0
  261. package/dist/patterns/lens/index.d.ts +7 -0
  262. package/dist/patterns/lens/index.js +1 -0
  263. package/dist/patterns/memory/index.cjs +7 -0
  264. package/dist/patterns/memory/index.d.cts +5 -0
  265. package/dist/patterns/memory/index.d.ts +5 -0
  266. package/dist/patterns/memory/index.js +1 -0
  267. package/dist/patterns/messaging/index.cjs +7 -0
  268. package/dist/patterns/messaging/index.d.cts +5 -0
  269. package/dist/patterns/messaging/index.d.ts +5 -0
  270. package/dist/patterns/messaging/index.js +1 -0
  271. package/dist/patterns/orchestration/index.cjs +7 -0
  272. package/dist/patterns/orchestration/index.d.cts +6 -0
  273. package/dist/patterns/orchestration/index.d.ts +6 -0
  274. package/dist/patterns/orchestration/index.js +1 -0
  275. package/dist/patterns/reactive-layout/index.cjs +8 -6444
  276. package/dist/patterns/reactive-layout/index.d.cts +6 -6
  277. package/dist/patterns/reactive-layout/index.d.ts +6 -6
  278. package/dist/patterns/reactive-layout/index.js +1 -56
  279. package/dist/patterns/reduction/index.cjs +7 -0
  280. package/dist/patterns/reduction/index.d.cts +5 -0
  281. package/dist/patterns/reduction/index.d.ts +5 -0
  282. package/dist/patterns/reduction/index.js +1 -0
  283. package/dist/patterns/refine-loop/index.cjs +9 -0
  284. package/dist/patterns/refine-loop/index.d.cts +7 -0
  285. package/dist/patterns/refine-loop/index.d.ts +7 -0
  286. package/dist/patterns/refine-loop/index.js +1 -0
  287. package/dist/patterns/resilient-pipeline/index.cjs +1 -0
  288. package/dist/patterns/resilient-pipeline/index.d.cts +7 -0
  289. package/dist/patterns/resilient-pipeline/index.d.ts +7 -0
  290. package/dist/patterns/resilient-pipeline/index.js +1 -0
  291. package/dist/patterns/surface/index.cjs +15 -0
  292. package/dist/patterns/surface/index.d.cts +8 -0
  293. package/dist/patterns/surface/index.d.ts +8 -0
  294. package/dist/patterns/surface/index.js +1 -0
  295. package/dist/{reactive-layout-u5Ulnqag.d.ts → reactive-layout-BkBwVvwm.d.ts} +2 -2
  296. package/dist/{reactive-layout-MQP--J3F.d.cts → reactive-layout-PiFwVaWS.d.cts} +2 -2
  297. package/dist/reactive-log-1QTyx10a.d.ts +190 -0
  298. package/dist/reactive-log-BiVoSxke.d.cts +190 -0
  299. package/dist/{composite-aUCvjZVR.d.ts → reactive-map-CwO_COHy.d.cts} +2 -67
  300. package/dist/{composite-C7PcQvcs.d.cts → reactive-map-FeuTVAJb.d.ts} +2 -67
  301. package/dist/resilience-CBfYJW5C.d.ts +493 -0
  302. package/dist/resilience-XRUF267O.js +1 -0
  303. package/dist/resilience-uBz4yvYB.d.cts +493 -0
  304. package/dist/{sugar-CCOxXK1e.d.ts → sugar-CY-MCfZ9.d.ts} +17 -15
  305. package/dist/{sugar-D02n5JjF.d.cts → sugar-DHttV0LX.d.cts} +17 -15
  306. package/dist/topology-tree-CVjt2gp7.d.cts +25 -0
  307. package/dist/topology-tree-one6oSKY.d.ts +25 -0
  308. package/dist/types-O3GzJY2U.d.cts +401 -0
  309. package/dist/types-u64Ose53.d.ts +401 -0
  310. package/package.json +252 -22
  311. package/dist/ai-CaR_912Q.d.cts +0 -1033
  312. package/dist/ai-WlRltJV7.d.ts +0 -1033
  313. package/dist/chunk-3ZWCKRHX.js +0 -117
  314. package/dist/chunk-3ZWCKRHX.js.map +0 -1
  315. package/dist/chunk-7TAQJHQV.js +0 -103
  316. package/dist/chunk-7TAQJHQV.js.map +0 -1
  317. package/dist/chunk-APFNLIRG.js +0 -62
  318. package/dist/chunk-APFNLIRG.js.map +0 -1
  319. package/dist/chunk-AT5LKYNL.js +0 -395
  320. package/dist/chunk-AT5LKYNL.js.map +0 -1
  321. package/dist/chunk-BQ6RQQFF.js +0 -5087
  322. package/dist/chunk-BQ6RQQFF.js.map +0 -1
  323. package/dist/chunk-BVZYTZ5H.js +0 -599
  324. package/dist/chunk-BVZYTZ5H.js.map +0 -1
  325. package/dist/chunk-DST5DKZS.js +0 -1371
  326. package/dist/chunk-DST5DKZS.js.map +0 -1
  327. package/dist/chunk-GTE6PWRZ.js +0 -866
  328. package/dist/chunk-GTE6PWRZ.js.map +0 -1
  329. package/dist/chunk-HXZEYDUR.js +0 -94
  330. package/dist/chunk-HXZEYDUR.js.map +0 -1
  331. package/dist/chunk-J22W6HV3.js +0 -107
  332. package/dist/chunk-J22W6HV3.js.map +0 -1
  333. package/dist/chunk-J2VBW3DZ.js +0 -302
  334. package/dist/chunk-J2VBW3DZ.js.map +0 -1
  335. package/dist/chunk-JSCT3CR4.js +0 -38
  336. package/dist/chunk-JSCT3CR4.js.map +0 -1
  337. package/dist/chunk-JWBCY4NC.js +0 -330
  338. package/dist/chunk-JWBCY4NC.js.map +0 -1
  339. package/dist/chunk-K2AUJHVP.js +0 -2251
  340. package/dist/chunk-K2AUJHVP.js.map +0 -1
  341. package/dist/chunk-MJ2NKQQL.js +0 -119
  342. package/dist/chunk-MJ2NKQQL.js.map +0 -1
  343. package/dist/chunk-N6UR7YVY.js +0 -198
  344. package/dist/chunk-N6UR7YVY.js.map +0 -1
  345. package/dist/chunk-NC6S43JJ.js +0 -456
  346. package/dist/chunk-NC6S43JJ.js.map +0 -1
  347. package/dist/chunk-OFVJBJXR.js +0 -98
  348. package/dist/chunk-OFVJBJXR.js.map +0 -1
  349. package/dist/chunk-OHISZPOJ.js +0 -97
  350. package/dist/chunk-OHISZPOJ.js.map +0 -1
  351. package/dist/chunk-OU5CQKNW.js +0 -102
  352. package/dist/chunk-OU5CQKNW.js.map +0 -1
  353. package/dist/chunk-PF7GRZMW.js +0 -2712
  354. package/dist/chunk-PF7GRZMW.js.map +0 -1
  355. package/dist/chunk-PHOUUNK7.js +0 -2291
  356. package/dist/chunk-PHOUUNK7.js.map +0 -1
  357. package/dist/chunk-RNHBMHKA.js +0 -1665
  358. package/dist/chunk-RNHBMHKA.js.map +0 -1
  359. package/dist/chunk-SX52TAR4.js +0 -110
  360. package/dist/chunk-SX52TAR4.js.map +0 -1
  361. package/dist/chunk-VYPWMZ6H.js +0 -98
  362. package/dist/chunk-VYPWMZ6H.js.map +0 -1
  363. package/dist/chunk-WBZOVTYK.js +0 -171
  364. package/dist/chunk-WBZOVTYK.js.map +0 -1
  365. package/dist/chunk-WKNUIZOY.js +0 -354
  366. package/dist/chunk-WKNUIZOY.js.map +0 -1
  367. package/dist/chunk-X3VMZYBT.js +0 -713
  368. package/dist/chunk-X3VMZYBT.js.map +0 -1
  369. package/dist/chunk-X5R3GL6H.js +0 -525
  370. package/dist/chunk-X5R3GL6H.js.map +0 -1
  371. package/dist/chunk-XGPU467M.js +0 -136
  372. package/dist/chunk-XGPU467M.js.map +0 -1
  373. package/dist/compat/index.cjs.map +0 -1
  374. package/dist/compat/index.js.map +0 -1
  375. package/dist/compat/jotai/index.cjs.map +0 -1
  376. package/dist/compat/jotai/index.js.map +0 -1
  377. package/dist/compat/nanostores/index.cjs.map +0 -1
  378. package/dist/compat/nanostores/index.js.map +0 -1
  379. package/dist/compat/nestjs/index.cjs.map +0 -1
  380. package/dist/compat/nestjs/index.js.map +0 -1
  381. package/dist/compat/react/index.cjs.map +0 -1
  382. package/dist/compat/react/index.js.map +0 -1
  383. package/dist/compat/solid/index.cjs.map +0 -1
  384. package/dist/compat/solid/index.js.map +0 -1
  385. package/dist/compat/svelte/index.cjs.map +0 -1
  386. package/dist/compat/svelte/index.js.map +0 -1
  387. package/dist/compat/vue/index.cjs.map +0 -1
  388. package/dist/compat/vue/index.js.map +0 -1
  389. package/dist/compat/zustand/index.cjs.map +0 -1
  390. package/dist/compat/zustand/index.js.map +0 -1
  391. package/dist/core/index.cjs.map +0 -1
  392. package/dist/core/index.js.map +0 -1
  393. package/dist/extra/index.cjs.map +0 -1
  394. package/dist/extra/index.js.map +0 -1
  395. package/dist/extra/sources.cjs.map +0 -1
  396. package/dist/extra/sources.js.map +0 -1
  397. package/dist/graph/index.cjs.map +0 -1
  398. package/dist/graph/index.js.map +0 -1
  399. package/dist/index.cjs.map +0 -1
  400. package/dist/index.js.map +0 -1
  401. package/dist/patterns/ai.cjs +0 -7930
  402. package/dist/patterns/ai.cjs.map +0 -1
  403. package/dist/patterns/ai.d.cts +0 -10
  404. package/dist/patterns/ai.d.ts +0 -10
  405. package/dist/patterns/ai.js +0 -71
  406. package/dist/patterns/ai.js.map +0 -1
  407. package/dist/patterns/audit.cjs +0 -5805
  408. package/dist/patterns/audit.cjs.map +0 -1
  409. package/dist/patterns/audit.d.cts +0 -6
  410. package/dist/patterns/audit.d.ts +0 -6
  411. package/dist/patterns/audit.js +0 -29
  412. package/dist/patterns/audit.js.map +0 -1
  413. package/dist/patterns/demo-shell.cjs +0 -5604
  414. package/dist/patterns/demo-shell.cjs.map +0 -1
  415. package/dist/patterns/demo-shell.d.cts +0 -6
  416. package/dist/patterns/demo-shell.d.ts +0 -6
  417. package/dist/patterns/demo-shell.js +0 -15
  418. package/dist/patterns/demo-shell.js.map +0 -1
  419. package/dist/patterns/memory.cjs +0 -5283
  420. package/dist/patterns/memory.cjs.map +0 -1
  421. package/dist/patterns/memory.d.cts +0 -5
  422. package/dist/patterns/memory.d.ts +0 -5
  423. package/dist/patterns/memory.js +0 -20
  424. package/dist/patterns/memory.js.map +0 -1
  425. package/dist/patterns/reactive-layout/index.cjs.map +0 -1
  426. package/dist/patterns/reactive-layout/index.js.map +0 -1
  427. package/dist/storage-CMjUUuxn.d.ts +0 -190
  428. package/dist/storage-DdWlZo6U.d.cts +0 -190
@@ -1,2271 +1 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
-
20
- // src/core/index.ts
21
- var core_exports = {};
22
- __export(core_exports, {
23
- COMPLETE: () => COMPLETE,
24
- COMPLETE_MSG: () => COMPLETE_MSG,
25
- COMPLETE_ONLY_BATCH: () => COMPLETE_ONLY_BATCH,
26
- DATA: () => DATA,
27
- DEFAULT_ACTOR: () => DEFAULT_ACTOR,
28
- DIRTY: () => DIRTY,
29
- DIRTY_MSG: () => DIRTY_MSG,
30
- DIRTY_ONLY_BATCH: () => DIRTY_ONLY_BATCH,
31
- ERROR: () => ERROR,
32
- GraphReFlyConfig: () => GraphReFlyConfig,
33
- GuardDenied: () => GuardDenied,
34
- INVALIDATE: () => INVALIDATE,
35
- INVALIDATE_MSG: () => INVALIDATE_MSG,
36
- INVALIDATE_ONLY_BATCH: () => INVALIDATE_ONLY_BATCH,
37
- NodeImpl: () => NodeImpl,
38
- PAUSE: () => PAUSE,
39
- RESOLVED: () => RESOLVED,
40
- RESOLVED_MSG: () => RESOLVED_MSG,
41
- RESOLVED_ONLY_BATCH: () => RESOLVED_ONLY_BATCH,
42
- RESUME: () => RESUME,
43
- START: () => START,
44
- START_MSG: () => START_MSG,
45
- TEARDOWN: () => TEARDOWN,
46
- TEARDOWN_MSG: () => TEARDOWN_MSG,
47
- TEARDOWN_ONLY_BATCH: () => TEARDOWN_ONLY_BATCH,
48
- accessHintForGuard: () => accessHintForGuard,
49
- advanceVersion: () => advanceVersion,
50
- autoTrackNode: () => autoTrackNode,
51
- batch: () => batch,
52
- configure: () => configure,
53
- createVersioning: () => createVersioning,
54
- defaultConfig: () => defaultConfig,
55
- defaultHash: () => defaultHash,
56
- derived: () => derived,
57
- downWithBatch: () => downWithBatch,
58
- dynamicNode: () => dynamicNode,
59
- effect: () => effect,
60
- isBatching: () => isBatching,
61
- isV1: () => isV1,
62
- monotonicNs: () => monotonicNs,
63
- node: () => node,
64
- normalizeActor: () => normalizeActor,
65
- pipe: () => pipe,
66
- policy: () => policy,
67
- policyFromRules: () => policyFromRules,
68
- producer: () => producer,
69
- registerBuiltins: () => registerBuiltins,
70
- resolveDescribeFields: () => resolveDescribeFields,
71
- state: () => state,
72
- wallClockNs: () => wallClockNs
73
- });
74
- module.exports = __toCommonJS(core_exports);
75
-
76
- // src/core/actor.ts
77
- var DEFAULT_ACTOR = { type: "system", id: "" };
78
- function normalizeActor(actor) {
79
- if (actor == null) return DEFAULT_ACTOR;
80
- const { type, id, ...rest } = actor;
81
- return {
82
- type: type ?? "system",
83
- id: id ?? "",
84
- ...rest
85
- };
86
- }
87
-
88
- // src/core/batch.ts
89
- var MAX_DRAIN_ITERATIONS = 1e3;
90
- var batchDepth = 0;
91
- var flushInProgress = false;
92
- var drainPhase2 = [];
93
- var drainPhase3 = [];
94
- var drainPhase4 = [];
95
- var flushHooks = [];
96
- function isBatching() {
97
- return batchDepth > 0 || flushInProgress;
98
- }
99
- function isExplicitlyBatching() {
100
- return batchDepth > 0;
101
- }
102
- function registerBatchFlushHook(hook) {
103
- if (batchDepth > 0) {
104
- flushHooks.push(hook);
105
- } else {
106
- hook();
107
- }
108
- }
109
- function batch(fn) {
110
- batchDepth += 1;
111
- let threw = false;
112
- try {
113
- fn();
114
- } catch (e) {
115
- threw = true;
116
- throw e;
117
- } finally {
118
- batchDepth -= 1;
119
- if (batchDepth === 0) {
120
- if (threw) {
121
- if (!flushInProgress) {
122
- const hooks = flushHooks.splice(0);
123
- for (const h of hooks) {
124
- try {
125
- h();
126
- } catch {
127
- }
128
- }
129
- drainPhase2.length = 0;
130
- drainPhase3.length = 0;
131
- drainPhase4.length = 0;
132
- }
133
- } else {
134
- drainPending();
135
- }
136
- }
137
- }
138
- }
139
- function drainPending() {
140
- const ownsFlush = !flushInProgress;
141
- if (ownsFlush) flushInProgress = true;
142
- const errors = [];
143
- let iterations = 0;
144
- try {
145
- while (drainPhase2.length > 0 || drainPhase3.length > 0 || drainPhase4.length > 0 || ownsFlush && flushHooks.length > 0) {
146
- if (ownsFlush && flushHooks.length > 0) {
147
- const hooks = flushHooks.splice(0);
148
- for (const h of hooks) {
149
- try {
150
- h();
151
- } catch (e) {
152
- errors.push(e);
153
- }
154
- }
155
- continue;
156
- }
157
- iterations += 1;
158
- if (iterations > MAX_DRAIN_ITERATIONS) {
159
- drainPhase2.length = 0;
160
- drainPhase3.length = 0;
161
- drainPhase4.length = 0;
162
- throw new Error(
163
- `batch drain exceeded ${MAX_DRAIN_ITERATIONS} iterations \u2014 likely a reactive cycle`
164
- );
165
- }
166
- const queue = drainPhase2.length > 0 ? drainPhase2 : drainPhase3.length > 0 ? drainPhase3 : drainPhase4;
167
- const ops = queue.splice(0);
168
- for (const run of ops) {
169
- try {
170
- run();
171
- } catch (e) {
172
- errors.push(e);
173
- }
174
- }
175
- }
176
- } finally {
177
- if (ownsFlush) flushInProgress = false;
178
- }
179
- if (errors.length === 1) throw errors[0];
180
- if (errors.length > 1) {
181
- throw new AggregateError(errors, "batch drain: multiple callbacks threw");
182
- }
183
- }
184
- function downWithBatch(sink, messages, tierOf) {
185
- if (messages.length === 0) return;
186
- if (messages.length === 1) {
187
- const tier = tierOf(messages[0][0]);
188
- if (tier < 3 || !isBatching()) {
189
- sink(messages);
190
- return;
191
- }
192
- const queue = tier >= 5 ? drainPhase4 : tier === 4 ? drainPhase3 : drainPhase2;
193
- queue.push(() => sink(messages));
194
- return;
195
- }
196
- const n = messages.length;
197
- let phase2Start = n;
198
- let phase3Start = n;
199
- let phase4Start = n;
200
- let i = 0;
201
- while (i < n && tierOf(messages[i][0]) < 3) i++;
202
- phase2Start = i;
203
- while (i < n && tierOf(messages[i][0]) === 3) i++;
204
- phase3Start = i;
205
- while (i < n && tierOf(messages[i][0]) === 4) i++;
206
- phase4Start = i;
207
- const batching = isBatching();
208
- if (phase2Start > 0) {
209
- const immediate = messages.slice(0, phase2Start);
210
- sink(immediate);
211
- }
212
- if (phase3Start > phase2Start) {
213
- const phase2 = messages.slice(phase2Start, phase3Start);
214
- if (batching) drainPhase2.push(() => sink(phase2));
215
- else sink(phase2);
216
- }
217
- if (phase4Start > phase3Start) {
218
- const phase3 = messages.slice(phase3Start, phase4Start);
219
- if (batching) drainPhase3.push(() => sink(phase3));
220
- else sink(phase3);
221
- }
222
- if (n > phase4Start) {
223
- const phase4 = messages.slice(phase4Start, n);
224
- if (batching) drainPhase4.push(() => sink(phase4));
225
- else sink(phase4);
226
- }
227
- }
228
-
229
- // src/core/clock.ts
230
- function monotonicNs() {
231
- return Math.trunc(performance.now() * 1e6);
232
- }
233
- function wallClockNs() {
234
- return Date.now() * 1e6;
235
- }
236
-
237
- // src/core/messages.ts
238
- var START = /* @__PURE__ */ Symbol.for("graphrefly/START");
239
- var DATA = /* @__PURE__ */ Symbol.for("graphrefly/DATA");
240
- var DIRTY = /* @__PURE__ */ Symbol.for("graphrefly/DIRTY");
241
- var RESOLVED = /* @__PURE__ */ Symbol.for("graphrefly/RESOLVED");
242
- var INVALIDATE = /* @__PURE__ */ Symbol.for("graphrefly/INVALIDATE");
243
- var PAUSE = /* @__PURE__ */ Symbol.for("graphrefly/PAUSE");
244
- var RESUME = /* @__PURE__ */ Symbol.for("graphrefly/RESUME");
245
- var TEARDOWN = /* @__PURE__ */ Symbol.for("graphrefly/TEARDOWN");
246
- var COMPLETE = /* @__PURE__ */ Symbol.for("graphrefly/COMPLETE");
247
- var ERROR = /* @__PURE__ */ Symbol.for("graphrefly/ERROR");
248
- var DIRTY_MSG = Object.freeze([DIRTY]);
249
- var RESOLVED_MSG = Object.freeze([RESOLVED]);
250
- var INVALIDATE_MSG = Object.freeze([INVALIDATE]);
251
- var START_MSG = Object.freeze([START]);
252
- var COMPLETE_MSG = Object.freeze([COMPLETE]);
253
- var TEARDOWN_MSG = Object.freeze([TEARDOWN]);
254
- var DIRTY_ONLY_BATCH = Object.freeze([DIRTY_MSG]);
255
- var RESOLVED_ONLY_BATCH = Object.freeze([RESOLVED_MSG]);
256
- var INVALIDATE_ONLY_BATCH = Object.freeze([INVALIDATE_MSG]);
257
- var COMPLETE_ONLY_BATCH = Object.freeze([COMPLETE_MSG]);
258
- var TEARDOWN_ONLY_BATCH = Object.freeze([TEARDOWN_MSG]);
259
-
260
- // src/core/config.ts
261
- var GraphReFlyConfig = class {
262
- _messageTypes = /* @__PURE__ */ new Map();
263
- _codecs = /* @__PURE__ */ new Map();
264
- _onMessage;
265
- _onSubscribe;
266
- _defaultVersioning;
267
- _defaultHashFn;
268
- _inspectorEnabled = !(typeof process !== "undefined" && process.env?.NODE_ENV === "production");
269
- _globalInspector;
270
- _frozen = false;
271
- /**
272
- * Pre-bound tier lookup — shared by every node bound to this config. Since
273
- * the registry is frozen on first hook access, this closure can be built
274
- * once in the constructor and handed directly to `downWithBatch` /
275
- * `_frameBatch` paths without per-node or per-emission `.bind(config)`
276
- * allocation.
277
- */
278
- tierOf;
279
- constructor(init) {
280
- this._onMessage = init.onMessage;
281
- this._onSubscribe = init.onSubscribe;
282
- this._defaultVersioning = init.defaultVersioning;
283
- this._defaultHashFn = init.defaultHashFn;
284
- this.tierOf = (t) => {
285
- const reg = this._messageTypes.get(t);
286
- return reg != null ? reg.tier : 1;
287
- };
288
- }
289
- // --- Hook getters (freeze on read) ---
290
- get onMessage() {
291
- this._frozen = true;
292
- return this._onMessage;
293
- }
294
- get onSubscribe() {
295
- this._frozen = true;
296
- return this._onSubscribe;
297
- }
298
- // --- Hook setters (throw when frozen) ---
299
- set onMessage(v) {
300
- this._assertUnfrozen();
301
- this._onMessage = v;
302
- }
303
- set onSubscribe(v) {
304
- this._assertUnfrozen();
305
- this._onSubscribe = v;
306
- }
307
- /**
308
- * Default versioning level applied to every node bound to this config,
309
- * unless the node's own `opts.versioning` provides an explicit override.
310
- * Setting this is only allowed before the config freezes (i.e., before
311
- * the first node is created) so every node in the graph sees a
312
- * consistent starting level. Individual nodes can still opt into a
313
- * higher level via `opts.versioning`, or post-hoc via
314
- * `NodeImpl._applyVersioning(level)` when the node is quiescent.
315
- *
316
- * v0 is the minimum opt-in — unversioned nodes (`undefined`) skip
317
- * the version counter entirely. v1 adds content-addressed cid.
318
- * Future levels (v2, v3) are reserved for linked-history and
319
- * cryptographic attestation extensions.
320
- */
321
- get defaultVersioning() {
322
- return this._defaultVersioning;
323
- }
324
- set defaultVersioning(v) {
325
- this._assertUnfrozen();
326
- this._defaultVersioning = v;
327
- }
328
- /**
329
- * Default content-hash function applied to every versioned node bound
330
- * to this config, unless the node's own `opts.versioningHash` provides
331
- * an explicit override. Use this when a graph needs a non-default hash
332
- * — e.g., swap the vendored sync SHA-256 for a faster non-crypto hash
333
- * (xxHash, FNV-1a) in hot-path workloads, or a stronger hash when
334
- * versioning v1 cids are used as audit anchors.
335
- *
336
- * Only settable before the config freezes. Individual nodes can still
337
- * override via `opts.versioningHash`.
338
- */
339
- get defaultHashFn() {
340
- return this._defaultHashFn;
341
- }
342
- set defaultHashFn(v) {
343
- this._assertUnfrozen();
344
- this._defaultHashFn = v;
345
- }
346
- /**
347
- * When `false`, structured observation options (`causal`, `timeline`)
348
- * and `Graph.trace()` writes are no-ops. Raw `Graph.observe()` always
349
- * works. Default: `true` outside production (`NODE_ENV !== "production"`).
350
- *
351
- * Settable at any time — inspector gating is an operational concern, not
352
- * a protocol invariant, so it does NOT require freeze before node creation.
353
- */
354
- get inspectorEnabled() {
355
- return this._inspectorEnabled;
356
- }
357
- set inspectorEnabled(v) {
358
- this._inspectorEnabled = v;
359
- }
360
- /**
361
- * Process-global observability hook (Redux-DevTools-style full-graph
362
- * tracer). Fires once per outgoing batch from every node bound to this
363
- * config, gated by {@link inspectorEnabled}. See {@link GlobalInspectorHook}.
364
- *
365
- * Settable at any time — like {@link inspectorEnabled} this is operational,
366
- * not protocol-shaping, so it does NOT trigger config freeze.
367
- */
368
- get globalInspector() {
369
- return this._globalInspector;
370
- }
371
- set globalInspector(v) {
372
- this._globalInspector = v;
373
- }
374
- // --- Registry (writes require unfrozen; reads are free lookups) ---
375
- /**
376
- * Register a custom message type. Must be called before any node that
377
- * uses this config has been created — otherwise throws. Default
378
- * `wireCrossing` is `tier >= 3`.
379
- */
380
- registerMessageType(t, input) {
381
- this._assertUnfrozen();
382
- this._messageTypes.set(t, {
383
- tier: input.tier,
384
- wireCrossing: input.wireCrossing ?? input.tier >= 3,
385
- metaPassthrough: input.metaPassthrough ?? true
386
- });
387
- return this;
388
- }
389
- /** Tier for `t`. Unknown types default to tier 1 (immediate, after START). */
390
- messageTier(t) {
391
- const reg = this._messageTypes.get(t);
392
- return reg != null ? reg.tier : 1;
393
- }
394
- /**
395
- * Whether `t` is registered as wire-crossing. Unknown types default to
396
- * `true` (spec §1.3.6 forward-compat — unknowns cross the wire).
397
- */
398
- isWireCrossing(t) {
399
- const reg = this._messageTypes.get(t);
400
- return reg != null ? reg.wireCrossing : true;
401
- }
402
- /** Convenience inverse of {@link isWireCrossing}. */
403
- isLocalOnly(t) {
404
- return !this.isWireCrossing(t);
405
- }
406
- /**
407
- * Whether `t` is forwarded to meta companions by `Graph.signal`. Defaults
408
- * to `true` for unknowns (forward-compat — new types pass through meta by
409
- * default; opt-in filter via `registerMessageType({metaPassthrough: false})`).
410
- */
411
- isMetaPassthrough(t) {
412
- const reg = this._messageTypes.get(t);
413
- return reg != null ? reg.metaPassthrough : true;
414
- }
415
- /** Whether `t` is a registered (built-in or custom) type. */
416
- isKnownMessageType(t) {
417
- return this._messageTypes.has(t);
418
- }
419
- // --- Codec registry (writes require unfrozen; reads are free lookups) ---
420
- /**
421
- * Register a graph codec by `codec.name`. Used by the envelope-based
422
- * `graph.snapshot({format: "bytes", codec: name})` path and
423
- * `Graph.decode(bytes)` auto-dispatch. Must be called before any node
424
- * bound to this config is created — otherwise throws.
425
- *
426
- * Re-registering the same name overwrites, so user codecs can shadow
427
- * built-in ones before freeze (e.g., to swap a zstd-wrapped dag-cbor in
428
- * for `"dag-cbor"`).
429
- */
430
- registerCodec(codec) {
431
- this._assertUnfrozen();
432
- this._codecs.set(codec.name, codec);
433
- return this;
434
- }
435
- /**
436
- * Resolve a registered codec by name. Returns `undefined` for unknown
437
- * names. Typed callers cast to their concrete codec interface (e.g.,
438
- * `config.lookupCodec<GraphCodec>("json")`) — this method stays
439
- * layer-pure (no import of graph-layer types into `core/`).
440
- */
441
- lookupCodec(name) {
442
- return this._codecs.get(name);
443
- }
444
- /** @internal Used by tests and dev tooling — check freeze state without triggering it. */
445
- _isFrozen() {
446
- return this._frozen;
447
- }
448
- _assertUnfrozen() {
449
- if (this._frozen) {
450
- throw new Error(
451
- "GraphReFlyConfig is frozen: a node has already captured this config. Register custom types and set hooks before creating any node."
452
- );
453
- }
454
- }
455
- };
456
- function registerBuiltins(cfg) {
457
- cfg.registerMessageType(START, { tier: 0, wireCrossing: false });
458
- cfg.registerMessageType(DIRTY, { tier: 1, wireCrossing: false });
459
- cfg.registerMessageType(INVALIDATE, {
460
- tier: 1,
461
- wireCrossing: false,
462
- metaPassthrough: false
463
- });
464
- cfg.registerMessageType(PAUSE, { tier: 2, wireCrossing: false });
465
- cfg.registerMessageType(RESUME, { tier: 2, wireCrossing: false });
466
- cfg.registerMessageType(DATA, { tier: 3, wireCrossing: true });
467
- cfg.registerMessageType(RESOLVED, { tier: 3, wireCrossing: true });
468
- cfg.registerMessageType(COMPLETE, {
469
- tier: 4,
470
- wireCrossing: true,
471
- metaPassthrough: false
472
- });
473
- cfg.registerMessageType(ERROR, {
474
- tier: 4,
475
- wireCrossing: true,
476
- metaPassthrough: false
477
- });
478
- cfg.registerMessageType(TEARDOWN, {
479
- tier: 5,
480
- wireCrossing: true,
481
- metaPassthrough: false
482
- });
483
- }
484
-
485
- // src/core/guard.ts
486
- var GuardDenied = class extends Error {
487
- actor;
488
- action;
489
- nodeName;
490
- /**
491
- * @param details - Actor, action, and optional node name for the denial.
492
- * @param message - Optional override for the default error message.
493
- */
494
- constructor(details, message) {
495
- super(
496
- message ?? `GuardDenied: action "${String(details.action)}" denied for actor type "${String(details.actor.type)}"`
497
- );
498
- this.name = "GuardDenied";
499
- this.actor = details.actor;
500
- this.action = details.action;
501
- this.nodeName = details.nodeName;
502
- }
503
- /** Qualified registry path when known (roadmap diagnostics: same as {@link nodeName}). */
504
- get node() {
505
- return this.nodeName;
506
- }
507
- };
508
- function normalizeActions(action) {
509
- if (Array.isArray(action)) {
510
- return [...action];
511
- }
512
- return [action];
513
- }
514
- function matchesActions(set, action) {
515
- return set.has(action) || set.has("*");
516
- }
517
- function policy(build) {
518
- const rules = [];
519
- const allow = (action, opts) => {
520
- rules.push({
521
- kind: "allow",
522
- actions: new Set(normalizeActions(action)),
523
- where: opts?.where ?? (() => true)
524
- });
525
- };
526
- const deny = (action, opts) => {
527
- rules.push({
528
- kind: "deny",
529
- actions: new Set(normalizeActions(action)),
530
- where: opts?.where ?? (() => true)
531
- });
532
- };
533
- build(allow, deny);
534
- return (actor, action) => {
535
- let denied = false;
536
- let allowed = false;
537
- for (const r of rules) {
538
- if (!matchesActions(r.actions, action)) continue;
539
- if (!r.where(actor)) continue;
540
- if (r.kind === "deny") {
541
- denied = true;
542
- } else {
543
- allowed = true;
544
- }
545
- }
546
- if (denied) return false;
547
- return allowed;
548
- };
549
- }
550
- function policyFromRules(rules) {
551
- return policy((allow, deny) => {
552
- for (const rule of rules) {
553
- const actorTypes = rule.actorType == null ? null : new Set(Array.isArray(rule.actorType) ? rule.actorType : [rule.actorType]);
554
- const actorIds = rule.actorId == null ? null : new Set(Array.isArray(rule.actorId) ? rule.actorId : [rule.actorId]);
555
- const claimEntries = Object.entries(rule.claims ?? {});
556
- const where = (actor) => {
557
- if (actorTypes !== null && !actorTypes.has(String(actor.type))) return false;
558
- if (actorIds !== null && !actorIds.has(String(actor.id ?? ""))) return false;
559
- for (const [key, value] of claimEntries) {
560
- if (actor[key] !== value) return false;
561
- }
562
- return true;
563
- };
564
- if (rule.effect === "deny") {
565
- deny(rule.action, { where });
566
- } else {
567
- allow(rule.action, { where });
568
- }
569
- }
570
- });
571
- }
572
- var STANDARD_WRITE_TYPES = ["human", "llm", "wallet", "system"];
573
- function accessHintForGuard(guard) {
574
- const allowed = STANDARD_WRITE_TYPES.filter((t) => guard({ type: t, id: "" }, "write"));
575
- if (allowed.length === 0) return "restricted";
576
- if (allowed.includes("human") && allowed.includes("llm") && allowed.every((t) => t === "human" || t === "llm" || t === "system")) {
577
- return "both";
578
- }
579
- if (allowed.length === 1) return allowed[0];
580
- return allowed.join("+");
581
- }
582
-
583
- // src/graph/codec.ts
584
- var JsonCodec = {
585
- name: "json",
586
- version: 1,
587
- contentType: "application/json",
588
- encode(snapshot) {
589
- const json = JSON.stringify(snapshot);
590
- return new TextEncoder().encode(json);
591
- },
592
- decode(buffer, _codecVersion) {
593
- const json = new TextDecoder().decode(buffer);
594
- return JSON.parse(json);
595
- }
596
- };
597
- function registerBuiltinCodecs(config) {
598
- config.registerCodec(JsonCodec);
599
- }
600
-
601
- // src/core/versioning.ts
602
- function canonicalizeForHash(value) {
603
- if (value === void 0) return null;
604
- if (typeof value === "number") {
605
- if (!Number.isFinite(value)) {
606
- throw new TypeError(`Cannot hash non-finite number: ${value}`);
607
- }
608
- if (Number.isInteger(value) && !Number.isSafeInteger(value)) {
609
- throw new TypeError(
610
- `Cannot hash integer outside safe range (|n| > 2^53-1): ${value}. Cross-language cid parity is not guaranteed for unsafe integers.`
611
- );
612
- }
613
- return value;
614
- }
615
- if (typeof value === "string" || typeof value === "boolean" || value === null) {
616
- return value;
617
- }
618
- if (Array.isArray(value)) {
619
- return value.map(canonicalizeForHash);
620
- }
621
- if (typeof value === "object" && value !== null) {
622
- const sorted = {};
623
- for (const k of Object.keys(value).sort()) {
624
- sorted[k] = canonicalizeForHash(value[k]);
625
- }
626
- return sorted;
627
- }
628
- return null;
629
- }
630
- var SHA256_K = /* @__PURE__ */ new Uint32Array([
631
- 1116352408,
632
- 1899447441,
633
- 3049323471,
634
- 3921009573,
635
- 961987163,
636
- 1508970993,
637
- 2453635748,
638
- 2870763221,
639
- 3624381080,
640
- 310598401,
641
- 607225278,
642
- 1426881987,
643
- 1925078388,
644
- 2162078206,
645
- 2614888103,
646
- 3248222580,
647
- 3835390401,
648
- 4022224774,
649
- 264347078,
650
- 604807628,
651
- 770255983,
652
- 1249150122,
653
- 1555081692,
654
- 1996064986,
655
- 2554220882,
656
- 2821834349,
657
- 2952996808,
658
- 3210313671,
659
- 3336571891,
660
- 3584528711,
661
- 113926993,
662
- 338241895,
663
- 666307205,
664
- 773529912,
665
- 1294757372,
666
- 1396182291,
667
- 1695183700,
668
- 1986661051,
669
- 2177026350,
670
- 2456956037,
671
- 2730485921,
672
- 2820302411,
673
- 3259730800,
674
- 3345764771,
675
- 3516065817,
676
- 3600352804,
677
- 4094571909,
678
- 275423344,
679
- 430227734,
680
- 506948616,
681
- 659060556,
682
- 883997877,
683
- 958139571,
684
- 1322822218,
685
- 1537002063,
686
- 1747873779,
687
- 1955562222,
688
- 2024104815,
689
- 2227730452,
690
- 2361852424,
691
- 2428436474,
692
- 2756734187,
693
- 3204031479,
694
- 3329325298
695
- ]);
696
- var UTF8_ENCODER = /* @__PURE__ */ new TextEncoder();
697
- function sha256Hex(msg) {
698
- const bytes = UTF8_ENCODER.encode(msg);
699
- const msgLen = bytes.length;
700
- const bitLen = msgLen * 8;
701
- const totalLen = msgLen + 9 + 63 & ~63;
702
- const padded = new Uint8Array(totalLen);
703
- padded.set(bytes);
704
- padded[msgLen] = 128;
705
- const dv = new DataView(padded.buffer);
706
- dv.setUint32(totalLen - 4, bitLen >>> 0, false);
707
- dv.setUint32(totalLen - 8, Math.floor(bitLen / 4294967296) >>> 0, false);
708
- let h0 = 1779033703;
709
- let h1 = 3144134277;
710
- let h2 = 1013904242;
711
- let h3 = 2773480762;
712
- let h4 = 1359893119;
713
- let h5 = 2600822924;
714
- let h6 = 528734635;
715
- let h7 = 1541459225;
716
- const W = new Uint32Array(64);
717
- const rotr = (x, n) => x >>> n | x << 32 - n;
718
- for (let off = 0; off < totalLen; off += 64) {
719
- for (let i = 0; i < 16; i++) W[i] = dv.getUint32(off + i * 4, false);
720
- for (let i = 16; i < 64; i++) {
721
- const w15 = W[i - 15];
722
- const w2 = W[i - 2];
723
- const s0 = rotr(w15, 7) ^ rotr(w15, 18) ^ w15 >>> 3;
724
- const s1 = rotr(w2, 17) ^ rotr(w2, 19) ^ w2 >>> 10;
725
- W[i] = W[i - 16] + s0 + W[i - 7] + s1 >>> 0;
726
- }
727
- let a = h0;
728
- let b = h1;
729
- let c = h2;
730
- let d = h3;
731
- let e = h4;
732
- let f = h5;
733
- let g = h6;
734
- let h = h7;
735
- for (let i = 0; i < 64; i++) {
736
- const S1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25);
737
- const ch = e & f ^ ~e & g;
738
- const t1 = h + S1 + ch + SHA256_K[i] + W[i] >>> 0;
739
- const S0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22);
740
- const mj = a & b ^ a & c ^ b & c;
741
- const t2 = S0 + mj >>> 0;
742
- h = g;
743
- g = f;
744
- f = e;
745
- e = d + t1 >>> 0;
746
- d = c;
747
- c = b;
748
- b = a;
749
- a = t1 + t2 >>> 0;
750
- }
751
- h0 = h0 + a >>> 0;
752
- h1 = h1 + b >>> 0;
753
- h2 = h2 + c >>> 0;
754
- h3 = h3 + d >>> 0;
755
- h4 = h4 + e >>> 0;
756
- h5 = h5 + f >>> 0;
757
- h6 = h6 + g >>> 0;
758
- h7 = h7 + h >>> 0;
759
- }
760
- const toHex = (x) => x.toString(16).padStart(8, "0");
761
- return toHex(h0) + toHex(h1) + toHex(h2) + toHex(h3) + toHex(h4) + toHex(h5) + toHex(h6) + toHex(h7);
762
- }
763
- function defaultHash(value) {
764
- const canonical = canonicalizeForHash(value ?? null);
765
- const json = JSON.stringify(canonical);
766
- return sha256Hex(json).slice(0, 16);
767
- }
768
- function randomUuid() {
769
- const c = globalThis.crypto;
770
- if (c?.randomUUID) return c.randomUUID();
771
- const r = () => Math.floor(Math.random() * 4294967296).toString(16).padStart(8, "0");
772
- const hex = r() + r() + r() + r();
773
- return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-4${hex.slice(13, 16)}-${(parseInt(hex.slice(16, 17), 16) & 3 | 8).toString(16)}${hex.slice(17, 20)}-${hex.slice(20, 32)}`;
774
- }
775
- function createVersioning(level, initialValue, opts) {
776
- const id = opts?.id ?? randomUuid();
777
- if (level === 0) {
778
- return { id, version: 0 };
779
- }
780
- const hash = opts?.hash ?? defaultHash;
781
- const cid = hash(initialValue);
782
- return { id, version: 0, cid, prev: null };
783
- }
784
- function advanceVersion(info, newValue, hashFn) {
785
- info.version += 1;
786
- if ("cid" in info) {
787
- info.prev = info.cid;
788
- info.cid = hashFn(newValue);
789
- }
790
- }
791
- function isV1(info) {
792
- return "cid" in info;
793
- }
794
-
795
- // src/core/node.ts
796
- var noopUnsub = () => {
797
- };
798
- var MAX_RERUN_DEPTH = 100;
799
- function createDepRecord(n) {
800
- return {
801
- node: n,
802
- unsub: null,
803
- prevData: void 0,
804
- dirty: false,
805
- involvedThisWave: false,
806
- dataBatch: [],
807
- terminal: void 0
808
- };
809
- }
810
- function resetDepRecord(d) {
811
- d.prevData = void 0;
812
- d.dirty = false;
813
- d.involvedThisWave = false;
814
- d.dataBatch.length = 0;
815
- d.terminal = void 0;
816
- }
817
- function normalizeMessages(input) {
818
- if (input.length === 0) return input;
819
- return typeof input[0] === "symbol" ? [input] : input;
820
- }
821
- var defaultOnMessage = (node2, msg, ctx, _actions) => {
822
- if (ctx.direction === "down-in") {
823
- node2._onDepMessage(ctx.depIndex, msg);
824
- }
825
- return void 0;
826
- };
827
- var defaultOnSubscribe = (node2, sink, _ctx, _actions) => {
828
- const impl = node2;
829
- if (impl._status === "completed" || impl._status === "errored") return;
830
- const cached = impl._cached;
831
- const initial = cached === void 0 ? [START_MSG] : [START_MSG, [DATA, cached]];
832
- if (impl._status === "dirty") initial.push(DIRTY_MSG);
833
- downWithBatch(sink, initial, impl._config.tierOf);
834
- };
835
- var defaultConfig = new GraphReFlyConfig({
836
- onMessage: defaultOnMessage,
837
- onSubscribe: defaultOnSubscribe
838
- });
839
- registerBuiltins(defaultConfig);
840
- registerBuiltinCodecs(defaultConfig);
841
- function configure(fn) {
842
- if (defaultConfig._isFrozen()) {
843
- throw new Error(
844
- "configure() called after a node was created \u2014 the default GraphReFlyConfig is frozen. Call configure(...) at application startup, before any node factories run."
845
- );
846
- }
847
- fn(defaultConfig);
848
- }
849
- var NodeImpl = class _NodeImpl {
850
- // --- Identity ---
851
- _optsName;
852
- _describeKind;
853
- meta;
854
- /**
855
- * Cached `Object.keys(meta).length > 0` check. `meta` is frozen at
856
- * construction so this boolean never flips. Used by `_emit` to skip
857
- * the meta TEARDOWN fan-out block allocation on the common "no meta"
858
- * hot path.
859
- */
860
- _hasMeta;
861
- // --- Config ---
862
- _config;
863
- // --- Topology ---
864
- /** Mutable for autoTrackNode / Graph.connect() post-construction dep addition. */
865
- _deps;
866
- _sinks = null;
867
- _sinkCount = 0;
868
- // --- State ---
869
- _cached;
870
- _status;
871
- _cleanup;
872
- _store = {};
873
- _waveHasNewData = false;
874
- _hasNewTerminal = false;
875
- _hasCalledFnOnce = false;
876
- _paused = false;
877
- _pendingWave = false;
878
- _isExecutingFn = false;
879
- _pendingRerun = false;
880
- _rerunDepth = 0;
881
- // --- Settlement counter (A3) ---
882
- /**
883
- * Count of deps currently in `dirty === true`. `_maybeRunFnOnSettlement`
884
- * treats `0` as "wave settled" — O(1) check for full dep settlement.
885
- */
886
- _dirtyDepCount = 0;
887
- // --- Per-batch emit accumulator (Bug 2: K+1 fan-in fix) ---
888
- /**
889
- * Inside an explicit `batch(() => ...)` scope, every `_emit` accumulates
890
- * its already-framed messages here instead of dispatching synchronously.
891
- * At batch end, `_flushBatchPending` runs (registered via
892
- * `registerBatchFlushHook`) and delivers the whole accumulated batch as
893
- * one `downWithBatch` call — collapsing what would otherwise be K
894
- * separate sink invocations into one. This is the fix for the diamond
895
- * fan-in K+1 over-fire.
896
- *
897
- * `null` outside batch (or after flush). Only ever appended to within
898
- * a single explicit batch lifetime; reset to `null` on flush. State
899
- * updates (cache, version, status) still happen per-emit via
900
- * `_updateState` — only the downstream delivery is coalesced.
901
- */
902
- _batchPendingMessages = null;
903
- // --- PAUSE/RESUME lock tracking (C0) ---
904
- /**
905
- * Set of active pause locks held against this node. Every `[PAUSE, lockId]`
906
- * adds its `lockId` to the set; every `[RESUME, lockId]` removes it.
907
- * `_paused` is a derived quantity: `_pauseLocks.size > 0`. Multi-pauser
908
- * correctness — one controller releasing its lock does NOT resume the
909
- * node while another controller still holds its lock.
910
- */
911
- _pauseLocks = null;
912
- /**
913
- * Buffered DATA messages held while paused. Only populated when
914
- * `_pausable === "resumeAll"` (bufferAll mode). On final lock release
915
- * the buffer is replayed through the node's outgoing pipeline in the
916
- * order received. Non-bufferAll pause mode drops DATA on the floor
917
- * (upstream is expected to honor PAUSE by suppressing production).
918
- */
919
- _pauseBuffer = null;
920
- // --- Options (frozen at construction) ---
921
- _fn;
922
- _equals;
923
- _resubscribable;
924
- _resetOnTeardown;
925
- _autoComplete;
926
- _autoError;
927
- _pausable;
928
- _guard;
929
- /**
930
- * @internal Additional guards stacked at runtime via {@link NodeImpl._pushGuard}
931
- * (e.g. by `policyEnforcer({ mode: "enforce" })`, roadmap §9.2). Effective
932
- * write/signal/observe checks AND the original `_guard` with every entry here.
933
- */
934
- _extraGuards;
935
- _hashFn;
936
- _versioning;
937
- /**
938
- * Explicit versioning level, tracked separately from `_versioning` so
939
- * monotonicity checks and future v2/v3 extensions don't rely on the
940
- * fragile `"cid" in _versioning` shape discriminator. `undefined` means
941
- * the node has no versioning attached; `0` / `1` / future levels name
942
- * the tier. Mutated in lockstep with `_versioning` by the constructor
943
- * and by `_applyVersioning`.
944
- */
945
- _versioningLevel;
946
- // --- ABAC ---
947
- _lastMutation;
948
- /**
949
- * @internal Per-node inspector hooks for `Graph.observe(path,
950
- * { causal, derived })`. Fires in `_onDepMessage` and `_execFn`.
951
- * Attached via `_setInspectorHook` (returns a disposer). Multiple
952
- * observers can attach simultaneously — all registered hooks fire for
953
- * every event.
954
- */
955
- _inspectorHooks;
956
- // --- Actions (built once in the constructor) ---
957
- _actions;
958
- constructor(deps, fn, opts) {
959
- this._config = opts.config ?? defaultConfig;
960
- void this._config.onMessage;
961
- this._optsName = opts.name;
962
- this._describeKind = opts.describeKind;
963
- this._equals = opts.equals ?? Object.is;
964
- this._resubscribable = opts.resubscribable ?? false;
965
- this._resetOnTeardown = opts.resetOnTeardown ?? false;
966
- this._autoComplete = opts.completeWhenDepsComplete ?? true;
967
- this._autoError = opts.errorWhenDepsError ?? true;
968
- this._pausable = opts.pausable ?? true;
969
- this._guard = opts.guard;
970
- this._fn = fn;
971
- this._cached = opts.initial !== void 0 ? opts.initial : void 0;
972
- this._status = deps.length === 0 && fn == null && this._cached !== void 0 ? "settled" : "sentinel";
973
- this._hashFn = opts.versioningHash ?? this._config.defaultHashFn ?? defaultHash;
974
- const versioningLevel = opts.versioning ?? this._config.defaultVersioning;
975
- this._versioningLevel = versioningLevel;
976
- this._versioning = versioningLevel != null ? createVersioning(versioningLevel, this._cached === void 0 ? void 0 : this._cached, {
977
- id: opts.versioningId,
978
- hash: this._hashFn
979
- }) : void 0;
980
- this._deps = deps.map(createDepRecord);
981
- const meta = {};
982
- for (const [k, v] of Object.entries(opts.meta ?? {})) {
983
- const metaOpts = {
984
- initial: v,
985
- name: `${opts.name ?? "node"}:meta:${k}`,
986
- describeKind: "state",
987
- config: this._config
988
- };
989
- if (opts.guard != null) metaOpts.guard = opts.guard;
990
- meta[k] = new _NodeImpl([], void 0, metaOpts);
991
- }
992
- Object.freeze(meta);
993
- this.meta = meta;
994
- this._hasMeta = Object.keys(meta).length > 0;
995
- const self = this;
996
- this._actions = {
997
- emit(value) {
998
- self._emit([[DATA, value]]);
999
- },
1000
- down(messageOrMessages) {
1001
- self._emit(normalizeMessages(messageOrMessages));
1002
- },
1003
- up(messageOrMessages) {
1004
- self._emitUp(normalizeMessages(messageOrMessages));
1005
- }
1006
- };
1007
- this.down = this.down.bind(this);
1008
- this.up = this.up.bind(this);
1009
- }
1010
- // --- Derived state ---
1011
- get _isTerminal() {
1012
- return this._status === "completed" || this._status === "errored";
1013
- }
1014
- // --- Public getters ---
1015
- get name() {
1016
- return this._optsName;
1017
- }
1018
- get status() {
1019
- return this._status;
1020
- }
1021
- get cache() {
1022
- return this._cached === void 0 ? void 0 : this._cached;
1023
- }
1024
- get lastMutation() {
1025
- return this._lastMutation;
1026
- }
1027
- get v() {
1028
- return this._versioning;
1029
- }
1030
- hasGuard() {
1031
- return this._guard != null;
1032
- }
1033
- /**
1034
- * @internal Retroactively attach (or upgrade) versioning state on this
1035
- * node. Intended for `Graph.setVersioning(level)` bulk application and
1036
- * for rare cases where a specific node needs to be bumped to a higher
1037
- * level (e.g., `v0 → v1`) after construction.
1038
- *
1039
- * **Safety:** the mutation is rejected mid-wave. Specifically,
1040
- * throws if the node is currently executing its fn (`_isExecutingFn`).
1041
- * Callers at quiescent points — before the first sink subscribes, or
1042
- * after all sinks unsubscribe, or between external `down()` / `emit()`
1043
- * invocations — are safe. The re-entrance window that motivated §10.6.4
1044
- * removal was the "transition `_versioning` from `undefined` to a fresh
1045
- * object mid-`_updateState`" case; that path is now guarded.
1046
- *
1047
- * **Monotonicity:** levels can only go up. Downgrade (e.g., `v1 → v0`)
1048
- * is a no-op — once a node carries higher-level metadata, dropping it
1049
- * mid-graph would tear the linked-history invariant for v1 and above.
1050
- *
1051
- * **Linked-history boundary (D1, 2026-04-13):** upgrading v0 → v1
1052
- * produces a **fresh history root**. The new v1 state has `cid =
1053
- * hash(currentCachedValue)` and `prev = null`, not a synthetic `prev`
1054
- * anchored to any previous v0 value. The v0 monotonic `version` counter
1055
- * is preserved across the upgrade, but the linked-cid chain (spec §7)
1056
- * starts fresh at the upgrade point. Downstream audit tools that walk
1057
- * `v.cid.prev` backwards through time will see a `null` boundary at
1058
- * the upgrade — **this is intentional**: v0 had no cid to link to, and
1059
- * fabricating one would lie about the hash. Callers that require an
1060
- * unbroken cid chain from birth must attach versioning at construction
1061
- * via `opts.versioning` or `config.defaultVersioning`, not retroactively.
1062
- *
1063
- * @param level - New minimum versioning level.
1064
- * @param opts - Optional id / hash overrides; applied only if the
1065
- * node currently has no versioning state.
1066
- */
1067
- _applyVersioning(level, opts) {
1068
- if (this._isExecutingFn) {
1069
- throw new Error(
1070
- `Node "${this.name}": _applyVersioning cannot run mid-fn \u2014 call it outside of \`_execFn\` (typically at graph setup time before the first subscribe).`
1071
- );
1072
- }
1073
- const currentLevel = this._versioningLevel;
1074
- if (currentLevel != null && level <= currentLevel) {
1075
- return;
1076
- }
1077
- const hash = opts?.hash ?? this._hashFn;
1078
- if (hash !== this._hashFn) this._hashFn = hash;
1079
- const initialValue = this._cached === void 0 ? void 0 : this._cached;
1080
- const current = this._versioning;
1081
- const preservedId = current?.id ?? opts?.id;
1082
- const preservedVersion = current?.version ?? 0;
1083
- const fresh = createVersioning(level, initialValue, {
1084
- id: preservedId,
1085
- hash
1086
- });
1087
- fresh.version = preservedVersion;
1088
- this._versioning = fresh;
1089
- this._versioningLevel = level;
1090
- }
1091
- /**
1092
- * @internal Attach an inspector hook. Returns a disposer that removes
1093
- * the hook. Used by `Graph.observe(path, { causal, derived })` to build
1094
- * causal traces. Multiple hooks may be attached concurrently — all fire
1095
- * for every event in registration order. Passing `undefined` is a no-op
1096
- * and returns a no-op disposer.
1097
- */
1098
- _setInspectorHook(hook) {
1099
- if (hook == null) return () => {
1100
- };
1101
- if (this._inspectorHooks == null) this._inspectorHooks = /* @__PURE__ */ new Set();
1102
- this._inspectorHooks.add(hook);
1103
- return () => {
1104
- this._inspectorHooks?.delete(hook);
1105
- if (this._inspectorHooks?.size === 0) this._inspectorHooks = void 0;
1106
- };
1107
- }
1108
- /**
1109
- * @internal Push an additional guard onto this node. Effective enforcement
1110
- * is the AND of `_guard` and every guard pushed via this hook — any one
1111
- * rejecting throws {@link GuardDenied}. Returns a disposer that removes
1112
- * the pushed guard. Multiple guards may be stacked simultaneously.
1113
- *
1114
- * Used by `policyEnforcer({ mode: "enforce" })` (roadmap §9.2) to overlay
1115
- * runtime constraint enforcement onto an existing graph without rebuilding
1116
- * its nodes. Pre-1.0 internal API; not part of the public surface.
1117
- *
1118
- * **Identity semantics:** guards are tracked in a `Set`, so pushing the
1119
- * same `NodeGuard` reference twice is a single registration. Wrap each
1120
- * push in a unique closure if independent stacking is needed.
1121
- *
1122
- * **Iteration order:** insertion-ordered (`Set` semantics). Determinism
1123
- * follows from single-threaded JS execution; nested re-entry from inside
1124
- * a guard body (push/pop while iterating) is undefined-but-survivable.
1125
- */
1126
- _pushGuard(guard) {
1127
- if (this._extraGuards == null) this._extraGuards = /* @__PURE__ */ new Set();
1128
- this._extraGuards.add(guard);
1129
- return () => {
1130
- this._extraGuards?.delete(guard);
1131
- if (this._extraGuards?.size === 0) this._extraGuards = void 0;
1132
- };
1133
- }
1134
- allowsObserve(actor) {
1135
- if (this._guard == null && this._extraGuards == null) return true;
1136
- const a = normalizeActor(actor);
1137
- if (this._guard != null && !this._guard(a, "observe")) return false;
1138
- if (this._extraGuards != null) {
1139
- for (const eg of this._extraGuards) {
1140
- if (!eg(a, "observe")) return false;
1141
- }
1142
- }
1143
- return true;
1144
- }
1145
- // --- Guard helper ---
1146
- _checkGuard(options) {
1147
- if (options?.internal) return;
1148
- const hasGuard = this._guard != null || this._extraGuards != null;
1149
- const hasActor = options?.actor != null;
1150
- if (!hasGuard && !hasActor) return;
1151
- const actor = normalizeActor(options?.actor);
1152
- const action = options?.delivery === "signal" ? "signal" : "write";
1153
- if (this._guard != null && !this._guard(actor, action)) {
1154
- throw new GuardDenied({ actor, action, nodeName: this.name });
1155
- }
1156
- if (this._extraGuards != null) {
1157
- for (const eg of this._extraGuards) {
1158
- if (!eg(actor, action)) {
1159
- throw new GuardDenied({ actor, action, nodeName: this.name });
1160
- }
1161
- }
1162
- }
1163
- this._lastMutation = { actor, timestamp_ns: wallClockNs() };
1164
- }
1165
- // --- Public transport ---
1166
- down(messageOrMessages, options) {
1167
- const messages = normalizeMessages(messageOrMessages);
1168
- if (messages.length === 0) return;
1169
- this._checkGuard(options);
1170
- this._emit(messages);
1171
- }
1172
- emit(value, options) {
1173
- this._checkGuard(options);
1174
- this._emit([[DATA, value]]);
1175
- }
1176
- up(messageOrMessages, options) {
1177
- if (this._deps.length === 0) return;
1178
- const messages = normalizeMessages(messageOrMessages);
1179
- if (messages.length === 0) return;
1180
- this._checkGuard(options);
1181
- const forwardOpts = options ?? { internal: true };
1182
- this._validateUpTiers(messages);
1183
- for (const d of this._deps) {
1184
- d.node.up?.(messages, forwardOpts);
1185
- }
1186
- }
1187
- /**
1188
- * @internal Internal up-path used by `actions.up(...)` from inside fn.
1189
- * Same tier validation as public `up`, but bypasses the guard check
1190
- * since the fn context is already inside an authorized operation.
1191
- */
1192
- _emitUp(messages) {
1193
- if (this._deps.length === 0) return;
1194
- if (messages.length === 0) return;
1195
- this._validateUpTiers(messages);
1196
- for (const d of this._deps) {
1197
- d.node.up?.(messages, { internal: true });
1198
- }
1199
- }
1200
- /**
1201
- * @internal Enforce spec §1.2 — up-direction messages are restricted to
1202
- * tier 0–2 and tier 5 (START, DIRTY, INVALIDATE, PAUSE, RESUME,
1203
- * TEARDOWN). Tier 3 (DATA/RESOLVED) and tier 4 (COMPLETE/ERROR) are
1204
- * downstream-only. Emitting tier-3/4 via `up` would bypass equals
1205
- * substitution and cache advance entirely and is a protocol bug.
1206
- */
1207
- _validateUpTiers(messages) {
1208
- const tierOf = this._config.tierOf;
1209
- for (const m of messages) {
1210
- const tier = tierOf(m[0]);
1211
- if (tier === 3 || tier === 4) {
1212
- throw new Error(
1213
- `Node "${this.name}": tier-${tier} 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).`
1214
- );
1215
- }
1216
- }
1217
- }
1218
- subscribe(sink, actor) {
1219
- if (actor != null && this._guard != null) {
1220
- const a = normalizeActor(actor);
1221
- if (!this._guard(a, "observe")) {
1222
- throw new GuardDenied({ actor: a, action: "observe", nodeName: this.name });
1223
- }
1224
- }
1225
- const wasTerminal = this._isTerminal;
1226
- const afterTerminalReset = wasTerminal && this._resubscribable;
1227
- if (afterTerminalReset) {
1228
- this._cached = void 0;
1229
- this._status = "sentinel";
1230
- this._store = {};
1231
- this._hasCalledFnOnce = false;
1232
- this._waveHasNewData = false;
1233
- this._hasNewTerminal = false;
1234
- this._paused = false;
1235
- this._pendingWave = false;
1236
- this._pendingRerun = false;
1237
- this._isExecutingFn = false;
1238
- this._rerunDepth = 0;
1239
- this._dirtyDepCount = 0;
1240
- this._pauseLocks = null;
1241
- this._pauseBuffer = null;
1242
- for (const d of this._deps) resetDepRecord(d);
1243
- }
1244
- this._sinkCount += 1;
1245
- let subCleanup;
1246
- try {
1247
- subCleanup = this._config.onSubscribe(
1248
- this,
1249
- sink,
1250
- { sinkCount: this._sinkCount, afterTerminalReset },
1251
- this._actions
1252
- );
1253
- } catch (err) {
1254
- this._sinkCount -= 1;
1255
- throw err;
1256
- }
1257
- if (this._sinks == null) {
1258
- this._sinks = sink;
1259
- } else if (typeof this._sinks === "function") {
1260
- this._sinks = /* @__PURE__ */ new Set([this._sinks, sink]);
1261
- } else {
1262
- this._sinks.add(sink);
1263
- }
1264
- const isTerminalNow = this._isTerminal;
1265
- if (this._sinkCount === 1 && !isTerminalNow) {
1266
- try {
1267
- this._activate();
1268
- } catch (err) {
1269
- this._sinkCount -= 1;
1270
- this._removeSink(sink);
1271
- if (this._sinkCount === 0) this._status = "sentinel";
1272
- if (typeof subCleanup === "function") {
1273
- try {
1274
- subCleanup();
1275
- } catch {
1276
- }
1277
- }
1278
- throw err;
1279
- }
1280
- }
1281
- if (this._status === "sentinel" && this._cached === void 0) {
1282
- this._status = "pending";
1283
- }
1284
- let removed = false;
1285
- return () => {
1286
- if (removed) return;
1287
- removed = true;
1288
- this._sinkCount -= 1;
1289
- this._removeSink(sink);
1290
- if (typeof subCleanup === "function") subCleanup();
1291
- if (this._sinks == null) this._deactivate();
1292
- };
1293
- }
1294
- _removeSink(sink) {
1295
- if (this._sinks === sink) {
1296
- this._sinks = null;
1297
- } else if (this._sinks != null && typeof this._sinks !== "function") {
1298
- this._sinks.delete(sink);
1299
- if (this._sinks.size === 1) {
1300
- const [only] = this._sinks;
1301
- this._sinks = only;
1302
- } else if (this._sinks.size === 0) {
1303
- this._sinks = null;
1304
- }
1305
- }
1306
- }
1307
- // --- Lifecycle ---
1308
- /**
1309
- * @internal First-sink activation. For a producer (no deps + fn),
1310
- * invokes fn once. For a compute node (has deps), subscribes to every
1311
- * dep with the pre-set-dirty trick so the first-run gate waits for
1312
- * every dep to settle at least once.
1313
- */
1314
- _activate() {
1315
- if (this._deps.length === 0) {
1316
- if (this._fn) this._execFn();
1317
- return;
1318
- }
1319
- this._dirtyDepCount = 0;
1320
- const initialLen = this._deps.length;
1321
- let subscribedCount = 0;
1322
- try {
1323
- for (let i = 0; i < initialLen; i++) {
1324
- const depIdx = i;
1325
- const dep = this._deps[i];
1326
- dep.unsub = noopUnsub;
1327
- dep.unsub = dep.node.subscribe((msgs) => {
1328
- if (dep.unsub === null) return;
1329
- const tierOf = this._config.tierOf;
1330
- let sawSettlement = false;
1331
- for (const m of msgs) {
1332
- if (tierOf(m[0]) >= 3) sawSettlement = true;
1333
- this._config.onMessage(
1334
- this,
1335
- m,
1336
- { direction: "down-in", depIndex: depIdx },
1337
- this._actions
1338
- );
1339
- }
1340
- if (sawSettlement) this._maybeRunFnOnSettlement();
1341
- });
1342
- subscribedCount++;
1343
- }
1344
- } catch (err) {
1345
- this._deps[subscribedCount].unsub = null;
1346
- for (let j = 0; j < subscribedCount; j++) {
1347
- const d = this._deps[j];
1348
- if (d.unsub != null) {
1349
- const u = d.unsub;
1350
- d.unsub = null;
1351
- try {
1352
- u();
1353
- } catch {
1354
- }
1355
- resetDepRecord(d);
1356
- }
1357
- }
1358
- this._dirtyDepCount = 0;
1359
- throw err;
1360
- }
1361
- }
1362
- /**
1363
- * @internal Append a dep post-construction. Used by `autoTrackNode`
1364
- * (runtime dep discovery) and `Graph.connect()` (post-construction
1365
- * wiring). Subscribes immediately — if DATA arrives synchronously
1366
- * during subscribe and fn is currently executing, the re-run is
1367
- * deferred via `_pendingRerun` flag (see `_execFn` guard).
1368
- *
1369
- * **Dedup:** idempotent on duplicate `depNode` — if `depNode` is
1370
- * already in `_deps`, returns the existing index without mutating
1371
- * state. Callers can safely invoke `_addDep` without their own
1372
- * "already added" check. `autoTrackNode` still keeps a `depIndexMap`
1373
- * as a fast-path lookup for known deps (returning cached `data[idx]`
1374
- * without calling `_addDep` at all); this internal dedup is the
1375
- * backstop for any caller that doesn't track its own dep set.
1376
- *
1377
- * @returns The index of the new dep in `_deps`, or the existing index
1378
- * if the dep was already present.
1379
- */
1380
- _addDep(depNode) {
1381
- for (let i = 0; i < this._deps.length; i++) {
1382
- if (this._deps[i].node === depNode) return i;
1383
- }
1384
- const depIdx = this._deps.length;
1385
- const record = createDepRecord(depNode);
1386
- this._deps.push(record);
1387
- if (this._sinks == null) return depIdx;
1388
- record.dirty = true;
1389
- this._dirtyDepCount++;
1390
- if (this._status !== "dirty") this._emit(DIRTY_ONLY_BATCH);
1391
- record.unsub = noopUnsub;
1392
- try {
1393
- record.unsub = depNode.subscribe((msgs) => {
1394
- if (record.unsub === null) return;
1395
- const tierOf = this._config.tierOf;
1396
- let sawSettlement = false;
1397
- for (const m of msgs) {
1398
- if (tierOf(m[0]) >= 3) sawSettlement = true;
1399
- this._config.onMessage(
1400
- this,
1401
- m,
1402
- { direction: "down-in", depIndex: depIdx },
1403
- this._actions
1404
- );
1405
- }
1406
- if (sawSettlement) this._maybeRunFnOnSettlement();
1407
- });
1408
- } catch (err) {
1409
- record.unsub = null;
1410
- this._deps.pop();
1411
- this._dirtyDepCount--;
1412
- throw err;
1413
- }
1414
- return depIdx;
1415
- }
1416
- /**
1417
- * @internal Unsubscribes from deps, fires fn cleanup (both shapes),
1418
- * clears wave/store state, and (for compute nodes) drops `_cached` per
1419
- * the ROM/RAM rule. Idempotent: second call is a no-op.
1420
- *
1421
- * @param skipStatusUpdate — When `true`, the caller takes responsibility
1422
- * for setting `_status` after deactivation (e.g. TEARDOWN always sets
1423
- * `"sentinel"` unconditionally). When `false` (default), deactivation
1424
- * applies the ROM rule: compute nodes → `"sentinel"`, state nodes
1425
- * preserve their current status.
1426
- */
1427
- _deactivate(skipStatusUpdate = false) {
1428
- const cleanup = this._cleanup;
1429
- this._cleanup = void 0;
1430
- if (typeof cleanup === "function") {
1431
- try {
1432
- cleanup();
1433
- } catch (err) {
1434
- this._emit([[ERROR, this._wrapFnError("cleanup threw", err)]]);
1435
- }
1436
- } else if (cleanup != null && typeof cleanup.deactivation === "function") {
1437
- try {
1438
- cleanup.deactivation();
1439
- } catch (err) {
1440
- this._emit([[ERROR, this._wrapFnError("cleanup.deactivation threw", err)]]);
1441
- }
1442
- }
1443
- for (const d of this._deps) {
1444
- if (d.unsub != null) {
1445
- const u = d.unsub;
1446
- d.unsub = null;
1447
- try {
1448
- u();
1449
- } catch {
1450
- }
1451
- }
1452
- resetDepRecord(d);
1453
- }
1454
- this._waveHasNewData = false;
1455
- this._hasNewTerminal = false;
1456
- this._hasCalledFnOnce = false;
1457
- this._paused = false;
1458
- this._pendingWave = false;
1459
- this._pendingRerun = false;
1460
- this._rerunDepth = 0;
1461
- this._store = {};
1462
- this._dirtyDepCount = 0;
1463
- this._pauseLocks = null;
1464
- this._pauseBuffer = null;
1465
- if (this._fn != null) {
1466
- this._cached = void 0;
1467
- }
1468
- if (!skipStatusUpdate) {
1469
- if (this._fn != null || this._deps.length > 0) {
1470
- if (!this._isTerminal || this._resubscribable) {
1471
- this._status = "sentinel";
1472
- }
1473
- }
1474
- }
1475
- }
1476
- // --- Dep message dispatch (§3.5 singleton default) ---
1477
- /**
1478
- * @internal Default per-tier dispatch for incoming dep messages. Called
1479
- * by `defaultOnMessage`. Updates the DepRecord, triggers wave
1480
- * completion, and forwards passthrough traffic.
1481
- */
1482
- _onDepMessage(depIndex, msg) {
1483
- const dep = this._deps[depIndex];
1484
- const t = msg[0];
1485
- if (this._inspectorHooks != null) {
1486
- const ev = { kind: "dep_message", depIndex, message: msg };
1487
- for (const hook of this._inspectorHooks) hook(ev);
1488
- }
1489
- if (t === START) return;
1490
- if (t === DIRTY) {
1491
- this._depDirtied(dep);
1492
- return;
1493
- }
1494
- if (t === INVALIDATE) {
1495
- this._depInvalidated(dep);
1496
- this._emit(INVALIDATE_ONLY_BATCH);
1497
- return;
1498
- }
1499
- if (t === PAUSE || t === RESUME) {
1500
- this._emit([msg]);
1501
- return;
1502
- }
1503
- if (t === TEARDOWN) {
1504
- this._emit(TEARDOWN_ONLY_BATCH);
1505
- return;
1506
- }
1507
- if (t === DATA) {
1508
- this._depSettledAsData(dep, msg[1]);
1509
- } else if (t === RESOLVED) {
1510
- this._depSettledAsResolved(dep);
1511
- } else if (t === COMPLETE) {
1512
- this._depSettledAsTerminal(dep, true);
1513
- } else if (t === ERROR) {
1514
- this._depSettledAsTerminal(dep, msg[1]);
1515
- } else {
1516
- this._emit([msg]);
1517
- return;
1518
- }
1519
- if (!this._fn) {
1520
- if (t === DATA || t === RESOLVED) {
1521
- this._emit([msg]);
1522
- }
1523
- if (t === COMPLETE || t === ERROR) {
1524
- this._maybeAutoTerminalAfterWave();
1525
- }
1526
- return;
1527
- }
1528
- }
1529
- // --- Centralized dep-state transitions (A3 settlement counters) ---
1530
- //
1531
- // Every mutation to `DepRecord.dirty` / `DepRecord.prevData` /
1532
- // `DepRecord.terminal` must go through one of these helpers so the
1533
- // `_dirtyDepCount` and `_sentinelDepCount` counters stay in sync with
1534
- // the per-record flags. `_maybeRunFnOnSettlement` reads the counters
1535
- // and never re-scans the `_deps` array.
1536
- /**
1537
- * Called when a dep transitions `dirty: false → true` (either from an
1538
- * incoming DIRTY, or pre-set during `_activate` / `_addDep` /
1539
- * `_depInvalidated`). No-op if the dep is already dirty. Fires the
1540
- * downstream DIRTY emit if we're the first to dirty this wave.
1541
- */
1542
- _depDirtied(dep) {
1543
- if (dep.dirty) return;
1544
- dep.dirty = true;
1545
- dep.involvedThisWave = true;
1546
- this._dirtyDepCount++;
1547
- if (this._status !== "dirty") {
1548
- this._emit(DIRTY_ONLY_BATCH);
1549
- }
1550
- }
1551
- /**
1552
- * Called when a dep delivers new DATA: clears dirty, stores the payload,
1553
- * marks wave-has-data, and — if this is the dep's first DATA — clears
1554
- * its sentinel slot so the first-run gate can open.
1555
- */
1556
- _depSettledAsData(dep, value) {
1557
- if (dep.dirty) {
1558
- dep.dirty = false;
1559
- this._dirtyDepCount--;
1560
- }
1561
- dep.involvedThisWave = true;
1562
- dep.dataBatch.push(value);
1563
- this._waveHasNewData = true;
1564
- }
1565
- /**
1566
- * Called when a dep emits RESOLVED (wave settled, value unchanged).
1567
- * Clears dirty; does NOT touch `prevData` / `terminal` / sentinel
1568
- * count — sentinel only exits on first DATA or terminal, not RESOLVED.
1569
- */
1570
- _depSettledAsResolved(dep) {
1571
- if (dep.dirty) {
1572
- dep.dirty = false;
1573
- this._dirtyDepCount--;
1574
- }
1575
- }
1576
- /**
1577
- * Called when a dep delivers COMPLETE (`terminal = true`) or ERROR
1578
- * (`terminal = errorPayload`). Clears dirty, stores the terminal, and
1579
- * — if the dep had never contributed a DATA yet — leaves sentinel
1580
- * since the gate treats "terminated without data" as gate-open too.
1581
- */
1582
- _depSettledAsTerminal(dep, terminal) {
1583
- if (dep.dirty) {
1584
- dep.dirty = false;
1585
- this._dirtyDepCount--;
1586
- }
1587
- dep.terminal = terminal;
1588
- dep.involvedThisWave = true;
1589
- this._hasNewTerminal = true;
1590
- }
1591
- /**
1592
- * Called when a dep emits INVALIDATE: clears prevData, terminal, and
1593
- * dataBatch. The dep is now back in the "never delivered a real value"
1594
- * state — `prevData === undefined` so the sentinel check in fn will fire.
1595
- */
1596
- _depInvalidated(dep) {
1597
- dep.prevData = void 0;
1598
- dep.terminal = void 0;
1599
- dep.dataBatch.length = 0;
1600
- if (!dep.dirty) {
1601
- dep.dirty = true;
1602
- dep.involvedThisWave = true;
1603
- this._dirtyDepCount++;
1604
- } else {
1605
- dep.involvedThisWave = false;
1606
- }
1607
- }
1608
- _maybeRunFnOnSettlement() {
1609
- if (this._isTerminal && !this._resubscribable) return;
1610
- if (this._dirtyDepCount > 0) return;
1611
- if (this._paused) {
1612
- this._pendingWave = true;
1613
- return;
1614
- }
1615
- if (!this._waveHasNewData && !this._hasNewTerminal && this._hasCalledFnOnce) {
1616
- this._clearWaveFlags();
1617
- this._emit(RESOLVED_ONLY_BATCH);
1618
- this._maybeAutoTerminalAfterWave();
1619
- return;
1620
- }
1621
- if (this._fn) this._execFn();
1622
- this._maybeAutoTerminalAfterWave();
1623
- }
1624
- _maybeAutoTerminalAfterWave() {
1625
- if (this._deps.length === 0) return;
1626
- if (this._isTerminal) return;
1627
- const erroredDep = this._deps.find((d) => d.terminal !== void 0 && d.terminal !== true);
1628
- if (erroredDep != null) {
1629
- if (this._autoError) {
1630
- this._emit([[ERROR, erroredDep.terminal]]);
1631
- }
1632
- return;
1633
- }
1634
- if (this._autoComplete && this._deps.every((d) => d.terminal !== void 0)) {
1635
- this._emit(COMPLETE_ONLY_BATCH);
1636
- }
1637
- }
1638
- // --- Fn execution ---
1639
- /**
1640
- * @internal Runs the node fn once. Default cleanup (function form) fires
1641
- * before the new run; `{ deactivation }` cleanup survives.
1642
- */
1643
- _execFn() {
1644
- if (!this._fn) return;
1645
- if (this._isTerminal && !this._resubscribable) return;
1646
- if (this._isExecutingFn) {
1647
- this._pendingRerun = true;
1648
- return;
1649
- }
1650
- const prevCleanup = this._cleanup;
1651
- if (typeof prevCleanup === "function") {
1652
- this._cleanup = void 0;
1653
- try {
1654
- prevCleanup();
1655
- } catch (err) {
1656
- this._emit([[ERROR, this._wrapFnError("cleanup threw", err)]]);
1657
- return;
1658
- }
1659
- }
1660
- const batchData = this._deps.map(
1661
- (d) => !d.involvedThisWave ? void 0 : d.dataBatch.length > 0 ? [...d.dataBatch] : []
1662
- );
1663
- const prevData = this._deps.map((d) => d.prevData);
1664
- for (let i = 0; i < this._deps.length; i++) {
1665
- const batch2 = batchData[i];
1666
- if (batch2 != null && batch2.length > 0) {
1667
- this._deps[i].prevData = batch2[batch2.length - 1];
1668
- }
1669
- }
1670
- const terminalDeps = this._deps.map((d) => d.terminal);
1671
- const ctx = { prevData, terminalDeps, store: this._store };
1672
- this._hasCalledFnOnce = true;
1673
- this._clearWaveFlags();
1674
- if (this._inspectorHooks != null) {
1675
- const ev = { kind: "run", batchData, prevData };
1676
- for (const hook of this._inspectorHooks) hook(ev);
1677
- }
1678
- this._isExecutingFn = true;
1679
- try {
1680
- const result = this._fn(batchData, this._actions, ctx);
1681
- if (typeof result === "function") {
1682
- this._cleanup = result;
1683
- } else if (result != null && typeof result === "object" && typeof result.deactivation === "function") {
1684
- this._cleanup = result;
1685
- }
1686
- } catch (err) {
1687
- this._emit([[ERROR, this._wrapFnError("fn threw", err)]]);
1688
- } finally {
1689
- this._isExecutingFn = false;
1690
- if (this._pendingRerun) {
1691
- this._pendingRerun = false;
1692
- this._rerunDepth += 1;
1693
- if (this._rerunDepth > MAX_RERUN_DEPTH) {
1694
- this._rerunDepth = 0;
1695
- this._emit([
1696
- [
1697
- ERROR,
1698
- new Error(
1699
- `Node "${this.name}": _pendingRerun depth exceeded ${MAX_RERUN_DEPTH} \u2014 likely a reactive cycle`
1700
- )
1701
- ]
1702
- ]);
1703
- } else {
1704
- this._maybeRunFnOnSettlement();
1705
- }
1706
- } else {
1707
- this._rerunDepth = 0;
1708
- }
1709
- this._clearWaveFlags();
1710
- }
1711
- }
1712
- _clearWaveFlags() {
1713
- this._waveHasNewData = false;
1714
- this._hasNewTerminal = false;
1715
- for (const d of this._deps) {
1716
- d.involvedThisWave = false;
1717
- d.dataBatch.length = 0;
1718
- }
1719
- }
1720
- _wrapFnError(label, err) {
1721
- const msg = err instanceof Error ? err.message : String(err);
1722
- return new Error(`Node "${this.name}": ${label}: ${msg}`, { cause: err });
1723
- }
1724
- // --- Framing (tier sort + synthetic DIRTY prefix) ---
1725
- /**
1726
- * @internal Stable tier sort + synthetic DIRTY prefix for an outgoing
1727
- * batch. Fast path: already-monotone single-tier batches (the common
1728
- * case from interned singletons like `DIRTY_ONLY_BATCH`) return the
1729
- * input unchanged. General path: decorate-sort-undecorate into a new
1730
- * array, then prepend `[DIRTY]` after any tier-0 START entries when
1731
- * a tier-3 payload is present and the node isn't already dirty.
1732
- *
1733
- * Single source of truth for the spec §1.3.1 framing invariant. Every
1734
- * outgoing path hits `_frameBatch` exactly once via `_emit`.
1735
- */
1736
- _frameBatch(messages) {
1737
- const tierOf = this._config.tierOf;
1738
- if (messages.length === 1) {
1739
- const t = tierOf(messages[0][0]);
1740
- if (t === 3 && this._status !== "dirty") {
1741
- return [DIRTY_MSG, messages[0]];
1742
- }
1743
- return messages;
1744
- }
1745
- let monotone = true;
1746
- let hasTier3 = false;
1747
- let hasDirty = false;
1748
- let prevTier = -1;
1749
- for (const m of messages) {
1750
- const tier = tierOf(m[0]);
1751
- if (tier < prevTier) monotone = false;
1752
- if (tier === 3) hasTier3 = true;
1753
- if (m[0] === DIRTY) hasDirty = true;
1754
- prevTier = tier;
1755
- }
1756
- let sorted = messages;
1757
- if (!monotone) {
1758
- const indexed = messages.map((m, i) => ({ m, i, tier: tierOf(m[0]) }));
1759
- indexed.sort((a, b) => a.tier - b.tier || a.i - b.i);
1760
- sorted = indexed.map((x) => x.m);
1761
- }
1762
- if (hasTier3 && !hasDirty && this._status !== "dirty") {
1763
- let insertAt = 0;
1764
- while (insertAt < sorted.length && tierOf(sorted[insertAt][0]) === 0) insertAt++;
1765
- if (insertAt === 0) return [DIRTY_MSG, ...sorted];
1766
- return [...sorted.slice(0, insertAt), DIRTY_MSG, ...sorted.slice(insertAt)];
1767
- }
1768
- return sorted;
1769
- }
1770
- // --- Emit pipeline ---
1771
- /**
1772
- * @internal The unified dispatch waist — one call = one wave.
1773
- * See `GRAPHREFLY-SPEC.md` §1.3.1 for protocol context — the stages
1774
- * below are the implementation order.
1775
- *
1776
- * Pipeline stages, in order:
1777
- *
1778
- * 1. Terminal filter — post-COMPLETE/ERROR only TEARDOWN/INVALIDATE
1779
- * still propagate so graph teardown and cache-clear still work.
1780
- * 2. Tier sort (stable) — the batch can be in any order when it
1781
- * arrives; the walker downstream (`downWithBatch`) assumes
1782
- * ascending tier monotone, and so does `_updateState`'s tier-3
1783
- * slice walk. This is the single source of truth for ordering.
1784
- * 3. Synthetic DIRTY prefix — if a tier-3 payload is present, no
1785
- * DIRTY is already in the batch, and the node isn't already in
1786
- * `"dirty"` status, prepend `[DIRTY]` after any tier-0 START
1787
- * entries. Guarantees spec §1.3.1 (DIRTY precedes DATA within
1788
- * the same batch) uniformly across every entry point.
1789
- * 4. PAUSE/RESUME lock bookkeeping (C0) — update `_pauseLocks`,
1790
- * derive `_paused`, filter unknown-lockId RESUME, replay
1791
- * bufferAll buffer on final lock release.
1792
- * 5. Meta TEARDOWN fan-out — notify meta children before
1793
- * `_updateState`'s TEARDOWN branch calls `_deactivate`. Hoisted
1794
- * out of the walk to keep `_updateState` re-entrance-free.
1795
- * 6. `_updateState` — walk the batch in tier order, advancing
1796
- * `_cached` / `_status` / `_versioning` and running equals
1797
- * substitution on tier-3 DATA (§3.5.1). Returns
1798
- * `{finalMessages, equalsError?}`.
1799
- * 7. `downWithBatch` dispatch (or bufferAll capture if paused with
1800
- * `pausable: "resumeAll"`).
1801
- * 8. Recursive ERROR emission if equals threw mid-walk.
1802
- */
1803
- _emit(messages) {
1804
- if (messages.length === 0) return;
1805
- let deliverable = messages;
1806
- const terminal = this._isTerminal;
1807
- if (terminal && !this._resubscribable) {
1808
- const pass = messages.filter((m) => m[0] === TEARDOWN || m[0] === INVALIDATE);
1809
- if (pass.length === 0) return;
1810
- deliverable = pass;
1811
- }
1812
- deliverable = this._frameBatch(deliverable);
1813
- let filtered = null;
1814
- for (let i = 0; i < deliverable.length; i++) {
1815
- const m = deliverable[i];
1816
- const t = m[0];
1817
- if (t !== PAUSE && t !== RESUME) {
1818
- if (filtered != null) filtered.push(m);
1819
- continue;
1820
- }
1821
- if (m.length < 2) {
1822
- throw new Error(
1823
- `Node "${this.name}": [[${t === PAUSE ? "PAUSE" : "RESUME"}]] must carry a lockId payload \u2014 bare PAUSE/RESUME is a protocol violation (C0 rule). Use \`[[PAUSE, lockId]]\` / \`[[RESUME, lockId]]\`.`
1824
- );
1825
- }
1826
- let forward = true;
1827
- if (this._pausable !== false) {
1828
- const lockId = m[1];
1829
- if (t === PAUSE) {
1830
- if (this._pauseLocks == null) this._pauseLocks = /* @__PURE__ */ new Set();
1831
- this._pauseLocks.add(lockId);
1832
- this._paused = true;
1833
- if (this._pausable === "resumeAll" && this._pauseBuffer == null) {
1834
- this._pauseBuffer = [];
1835
- }
1836
- } else {
1837
- if (this._pauseLocks == null || !this._pauseLocks.has(lockId)) {
1838
- forward = false;
1839
- } else {
1840
- this._pauseLocks.delete(lockId);
1841
- if (this._pauseLocks.size === 0) {
1842
- this._paused = false;
1843
- if (this._pauseBuffer != null && this._pauseBuffer.length > 0) {
1844
- const drain = this._pauseBuffer;
1845
- this._pauseBuffer = [];
1846
- this._emit(drain);
1847
- }
1848
- if (this._pendingWave) {
1849
- this._pendingWave = false;
1850
- this._maybeRunFnOnSettlement();
1851
- }
1852
- }
1853
- }
1854
- }
1855
- }
1856
- if (!forward) {
1857
- if (filtered == null) filtered = deliverable.slice(0, i);
1858
- } else if (filtered != null) {
1859
- filtered.push(m);
1860
- }
1861
- }
1862
- if (filtered != null) {
1863
- if (filtered.length === 0) return;
1864
- deliverable = filtered;
1865
- }
1866
- if (this._hasMeta && deliverable.some((m) => m[0] === TEARDOWN)) {
1867
- for (const k of Object.keys(this.meta)) {
1868
- try {
1869
- this.meta[k]._emit(TEARDOWN_ONLY_BATCH);
1870
- } catch {
1871
- }
1872
- }
1873
- }
1874
- const { finalMessages, equalsError } = this._updateState(deliverable);
1875
- if (finalMessages.length > 0 && this._config.inspectorEnabled) {
1876
- const inspector = this._config.globalInspector;
1877
- if (inspector != null) {
1878
- try {
1879
- inspector({ kind: "emit", node: this, messages: finalMessages });
1880
- } catch {
1881
- }
1882
- }
1883
- }
1884
- if (finalMessages.length > 0) {
1885
- if (this._paused && this._pausable === "resumeAll" && this._pauseBuffer != null) {
1886
- const tierOf = this._config.tierOf;
1887
- const immediate = [];
1888
- for (const m of finalMessages) {
1889
- const tier = tierOf(m[0]);
1890
- if (tier < 3 || tier === 5) {
1891
- immediate.push(m);
1892
- } else {
1893
- this._pauseBuffer.push(m);
1894
- }
1895
- }
1896
- if (immediate.length > 0) {
1897
- this._dispatchOrAccumulate(immediate);
1898
- }
1899
- } else {
1900
- this._dispatchOrAccumulate(finalMessages);
1901
- }
1902
- }
1903
- if (equalsError != null) {
1904
- this._emit([[ERROR, equalsError]]);
1905
- }
1906
- }
1907
- /**
1908
- * @internal Walk an outgoing (already-framed) batch, updating own
1909
- * cache / status / versioning and running equals substitution on
1910
- * every tier-3 DATA (§3.5.1). Framing — tier sort and synthetic
1911
- * DIRTY prefix — has already happened upstream in `_frameBatch`.
1912
- * This walk trusts the input is in monotone tier order and that the
1913
- * spec §1.3.1 DIRTY/RESOLVED precedence invariant is already
1914
- * satisfied by the frame.
1915
- *
1916
- * Equals substitution: every DATA payload is compared against the
1917
- * live `_cached`; when equal, the tuple is rewritten to `[RESOLVED]`
1918
- * in a per-call copy and cache is not re-advanced. `.cache` remains
1919
- * coherent with "the last DATA payload this node actually sent
1920
- * downstream".
1921
- *
1922
- * Returns `{ finalMessages, equalsError? }`:
1923
- * - `finalMessages` — the array to deliver to sinks (may be
1924
- * `messages` unchanged, a rewritten copy with DATA→RESOLVED
1925
- * substitutions, or a truncated prefix when equals throws mid-walk).
1926
- * - `equalsError` — present only when the configured `equals` function
1927
- * threw on some DATA message. `_emit` delivers the prefix first,
1928
- * then emits a fresh ERROR batch via a recursive `_emit` call so
1929
- * subscribers observe `[...walked_prefix, ERROR]` in order.
1930
- */
1931
- _updateState(messages) {
1932
- const tierOf = this._config.tierOf;
1933
- let rewritten;
1934
- let equalsError;
1935
- let abortedAt = -1;
1936
- let dataCount = 0;
1937
- for (const m of messages) {
1938
- if (tierOf(m[0]) === 3) dataCount++;
1939
- }
1940
- const checkEquals = dataCount <= 1;
1941
- let lastDataIdx = -1;
1942
- if (this._versioning != null && dataCount > 1) {
1943
- for (let i = messages.length - 1; i >= 0; i--) {
1944
- if (messages[i][0] === DATA) {
1945
- lastDataIdx = i;
1946
- break;
1947
- }
1948
- }
1949
- }
1950
- for (let i = 0; i < messages.length; i++) {
1951
- const m = messages[i];
1952
- const t = m[0];
1953
- if (t === DATA) {
1954
- if (m.length >= 2) {
1955
- let unchanged = false;
1956
- if (checkEquals && this._cached !== void 0) {
1957
- try {
1958
- unchanged = this._equals(this._cached, m[1]);
1959
- } catch (err) {
1960
- equalsError = this._wrapFnError("equals threw", err);
1961
- abortedAt = i;
1962
- break;
1963
- }
1964
- }
1965
- if (unchanged) {
1966
- if (rewritten == null) rewritten = messages.slice(0, i);
1967
- rewritten.push(RESOLVED_MSG);
1968
- this._status = "resolved";
1969
- continue;
1970
- }
1971
- this._cached = m[1];
1972
- if (this._versioning != null) {
1973
- if (lastDataIdx < 0 || i === lastDataIdx) {
1974
- advanceVersion(this._versioning, m[1], this._hashFn);
1975
- }
1976
- }
1977
- }
1978
- this._status = "settled";
1979
- if (rewritten != null) rewritten.push(m);
1980
- } else {
1981
- if (rewritten != null) rewritten.push(m);
1982
- if (t === DIRTY) {
1983
- this._status = "dirty";
1984
- } else if (t === RESOLVED) {
1985
- this._status = "resolved";
1986
- } else if (t === COMPLETE) {
1987
- this._status = "completed";
1988
- } else if (t === ERROR) {
1989
- this._status = "errored";
1990
- } else if (t === INVALIDATE) {
1991
- this._cached = void 0;
1992
- this._status = "dirty";
1993
- const c = this._cleanup;
1994
- if (typeof c === "function") {
1995
- this._cleanup = void 0;
1996
- try {
1997
- c();
1998
- } catch {
1999
- }
2000
- }
2001
- } else if (t === TEARDOWN) {
2002
- if (this._resetOnTeardown) this._cached = void 0;
2003
- this._deactivate(
2004
- /* skipStatusUpdate */
2005
- true
2006
- );
2007
- this._status = "sentinel";
2008
- }
2009
- }
2010
- }
2011
- const base = abortedAt >= 0 ? rewritten ?? messages.slice(0, abortedAt) : rewritten ?? messages;
2012
- return equalsError != null ? { finalMessages: base, equalsError } : { finalMessages: base };
2013
- }
2014
- _deliverToSinks = (messages) => {
2015
- if (this._sinks == null) return;
2016
- if (typeof this._sinks === "function") {
2017
- this._sinks(messages);
2018
- return;
2019
- }
2020
- const snapshot = [...this._sinks];
2021
- for (const sink of snapshot) sink(messages);
2022
- };
2023
- /**
2024
- * @internal Dispatch entry point that respects the per-batch emit
2025
- * accumulator (Bug 2). Inside an explicit `batch()` scope, append to
2026
- * `_batchPendingMessages` and register a flush hook on first append.
2027
- * Outside batch — or during a drain (where `flushInProgress` is true
2028
- * but `batchDepth` is 0) — dispatch synchronously through `downWithBatch`.
2029
- *
2030
- * Per-emit state updates (`_frameBatch`, `_updateState`) have already
2031
- * happened by the time we reach here; only the **downstream delivery**
2032
- * is coalesced. Cache, version, and status are visible mid-batch on
2033
- * the emitting node itself.
2034
- */
2035
- _dispatchOrAccumulate(messages) {
2036
- if (isExplicitlyBatching()) {
2037
- if (this._batchPendingMessages === null) {
2038
- this._batchPendingMessages = [];
2039
- registerBatchFlushHook(() => this._flushBatchPending());
2040
- }
2041
- for (const m of messages) this._batchPendingMessages.push(m);
2042
- return;
2043
- }
2044
- downWithBatch(this._deliverToSinks, messages, this._config.tierOf);
2045
- }
2046
- /**
2047
- * @internal Flushes the accumulated batch through `downWithBatch` and
2048
- * clears the pending state. Idempotent — safe to call when pending is
2049
- * already null or empty (e.g. on a `batch()` throw, where the hook
2050
- * fires for cleanup but the drainPhase queues are wiped after).
2051
- *
2052
- * Critical: the accumulated batch is interleaved per-emit framings like
2053
- * `[DIRTY, DATA(1), DIRTY, DATA(2)]` — non-monotone tier order. We must
2054
- * re-frame to sort by tier before handing to `downWithBatch`, which
2055
- * assumes pre-sorted input. `_frameBatch` also handles the synthetic
2056
- * DIRTY prepend rule (no-op here — `hasDirty` is true since each
2057
- * accumulated emit already carries its own DIRTY prefix).
2058
- */
2059
- _flushBatchPending() {
2060
- const pending = this._batchPendingMessages;
2061
- if (pending === null) return;
2062
- this._batchPendingMessages = null;
2063
- if (pending.length === 0) return;
2064
- const framed = this._frameBatch(pending);
2065
- downWithBatch(this._deliverToSinks, framed, this._config.tierOf);
2066
- }
2067
- };
2068
- var isNodeArray = (value) => Array.isArray(value);
2069
- var isNodeOptionsObject = (value) => typeof value === "object" && value != null && !Array.isArray(value);
2070
- function node(depsOrFn, fnOrOpts, optsArg) {
2071
- const deps = isNodeArray(depsOrFn) ? depsOrFn : [];
2072
- const fn = typeof depsOrFn === "function" ? depsOrFn : typeof fnOrOpts === "function" ? fnOrOpts : void 0;
2073
- let opts = {};
2074
- if (isNodeArray(depsOrFn)) {
2075
- opts = (isNodeOptionsObject(fnOrOpts) ? fnOrOpts : optsArg) ?? {};
2076
- } else if (isNodeOptionsObject(depsOrFn)) {
2077
- opts = depsOrFn;
2078
- } else {
2079
- opts = (isNodeOptionsObject(fnOrOpts) ? fnOrOpts : optsArg) ?? {};
2080
- }
2081
- return new NodeImpl(deps, fn, opts);
2082
- }
2083
-
2084
- // src/core/meta.ts
2085
- function resolveDescribeFields(detail, fields) {
2086
- if (fields != null && fields.length > 0) return new Set(fields);
2087
- switch (detail) {
2088
- case "standard":
2089
- return /* @__PURE__ */ new Set(["type", "status", "value", "deps", "meta", "v"]);
2090
- case "full":
2091
- return null;
2092
- default:
2093
- return /* @__PURE__ */ new Set(["type", "deps"]);
2094
- }
2095
- }
2096
-
2097
- // src/core/sugar.ts
2098
- function sentinelGuard(batchData, ctx, allowPartial) {
2099
- if (allowPartial) return false;
2100
- return batchData.some(
2101
- (batch2, i) => !(batch2 != null && batch2.length > 0) && ctx.prevData[i] === void 0
2102
- );
2103
- }
2104
- function state(initial, opts) {
2105
- return node([], { ...opts, initial });
2106
- }
2107
- function producer(fn, opts) {
2108
- const wrapped = (_data, actions, ctx) => fn(actions, ctx) ?? void 0;
2109
- return node(wrapped, { describeKind: "producer", ...opts });
2110
- }
2111
- function derived(deps, fn, opts) {
2112
- const allowPartial = opts?.partial ?? false;
2113
- const wrapped = (batchData, actions, ctx) => {
2114
- if (sentinelGuard(batchData, ctx, allowPartial)) {
2115
- actions.down([[RESOLVED]]);
2116
- return void 0;
2117
- }
2118
- const data = batchData.map(
2119
- (batch2, i) => batch2 != null && batch2.length > 0 ? batch2.at(-1) : ctx.prevData[i]
2120
- );
2121
- actions.emit(fn(data, ctx));
2122
- return void 0;
2123
- };
2124
- return node(deps, wrapped, { describeKind: "derived", ...opts });
2125
- }
2126
- function effect(deps, fn, opts) {
2127
- const allowPartial = opts?.partial ?? false;
2128
- const wrapped = (batchData, actions, ctx) => {
2129
- if (sentinelGuard(batchData, ctx, allowPartial)) {
2130
- actions.down([[RESOLVED]]);
2131
- return void 0;
2132
- }
2133
- const data = batchData.map(
2134
- (batch2, i) => batch2 != null && batch2.length > 0 ? batch2.at(-1) : ctx.prevData[i]
2135
- );
2136
- return fn(data, actions, ctx) ?? void 0;
2137
- };
2138
- return node(deps, wrapped, { describeKind: "effect", ...opts });
2139
- }
2140
- function dynamicNode(allDeps, fn, opts) {
2141
- const depIndex = /* @__PURE__ */ new Map();
2142
- allDeps.forEach((d, i) => {
2143
- depIndex.set(d, i);
2144
- });
2145
- return derived(
2146
- allDeps,
2147
- // data[i] is already sugar-unwrapped to a scalar by derived()'s wrapper.
2148
- (data, ctx) => {
2149
- const track = (dep) => {
2150
- const i = depIndex.get(dep);
2151
- if (i == null) {
2152
- throw new Error(`dynamicNode: untracked dep "${dep.name ?? "<unnamed>"}"`);
2153
- }
2154
- return data[i];
2155
- };
2156
- return fn(track, ctx);
2157
- },
2158
- opts
2159
- );
2160
- }
2161
- function autoTrackNode(fn, opts) {
2162
- let implRef;
2163
- const depIndexMap = /* @__PURE__ */ new Map();
2164
- const allowPartial = opts?.partial ?? false;
2165
- const wrappedFn = (batchData, actions, ctx) => {
2166
- let foundNew = false;
2167
- const track = (dep) => {
2168
- const idx = depIndexMap.get(dep);
2169
- if (idx !== void 0) {
2170
- if (idx < batchData.length) {
2171
- const batch2 = batchData[idx];
2172
- if (batch2 != null && batch2.length > 0) return batch2.at(-1);
2173
- return ctx.prevData[idx];
2174
- }
2175
- return dep.cache;
2176
- }
2177
- foundNew = true;
2178
- const newIdx = implRef._addDep(dep);
2179
- depIndexMap.set(dep, newIdx);
2180
- return dep.cache;
2181
- };
2182
- if (!allowPartial && depIndexMap.size > 0) {
2183
- for (const [, idx] of depIndexMap) {
2184
- if (idx < batchData.length) {
2185
- const batch2 = batchData[idx];
2186
- if (!(batch2 != null && batch2.length > 0) && ctx.prevData[idx] === void 0) {
2187
- actions.down([[RESOLVED]]);
2188
- return void 0;
2189
- }
2190
- }
2191
- }
2192
- }
2193
- try {
2194
- const result = fn(track, ctx);
2195
- if (!foundNew) {
2196
- actions.emit(result);
2197
- if (ctx.store.__autoTrackLastDiscoveryError != null) {
2198
- delete ctx.store.__autoTrackLastDiscoveryError;
2199
- }
2200
- }
2201
- } catch (err) {
2202
- if (!foundNew) throw err;
2203
- ctx.store.__autoTrackLastDiscoveryError = err;
2204
- }
2205
- return void 0;
2206
- };
2207
- implRef = new NodeImpl([], wrappedFn, {
2208
- describeKind: "derived",
2209
- ...opts
2210
- });
2211
- return implRef;
2212
- }
2213
- function pipe(source, ...ops) {
2214
- let current = source;
2215
- for (const op of ops) current = op(current);
2216
- return current;
2217
- }
2218
- // Annotate the CommonJS export names for ESM import in node:
2219
- 0 && (module.exports = {
2220
- COMPLETE,
2221
- COMPLETE_MSG,
2222
- COMPLETE_ONLY_BATCH,
2223
- DATA,
2224
- DEFAULT_ACTOR,
2225
- DIRTY,
2226
- DIRTY_MSG,
2227
- DIRTY_ONLY_BATCH,
2228
- ERROR,
2229
- GraphReFlyConfig,
2230
- GuardDenied,
2231
- INVALIDATE,
2232
- INVALIDATE_MSG,
2233
- INVALIDATE_ONLY_BATCH,
2234
- NodeImpl,
2235
- PAUSE,
2236
- RESOLVED,
2237
- RESOLVED_MSG,
2238
- RESOLVED_ONLY_BATCH,
2239
- RESUME,
2240
- START,
2241
- START_MSG,
2242
- TEARDOWN,
2243
- TEARDOWN_MSG,
2244
- TEARDOWN_ONLY_BATCH,
2245
- accessHintForGuard,
2246
- advanceVersion,
2247
- autoTrackNode,
2248
- batch,
2249
- configure,
2250
- createVersioning,
2251
- defaultConfig,
2252
- defaultHash,
2253
- derived,
2254
- downWithBatch,
2255
- dynamicNode,
2256
- effect,
2257
- isBatching,
2258
- isV1,
2259
- monotonicNs,
2260
- node,
2261
- normalizeActor,
2262
- pipe,
2263
- policy,
2264
- policyFromRules,
2265
- producer,
2266
- registerBuiltins,
2267
- resolveDescribeFields,
2268
- state,
2269
- wallClockNs
2270
- });
2271
- //# sourceMappingURL=index.cjs.map
1
+ "use strict";var _e=Object.defineProperty;var Ye=Object.getOwnPropertyDescriptor;var qe=Object.getOwnPropertyNames;var Ke=Object.prototype.hasOwnProperty;var Je=(n,e)=>{for(var t in e)_e(n,t,{get:e[t],enumerable:!0})},Xe=(n,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of qe(e))!Ke.call(n,r)&&r!==t&&_e(n,r,{get:()=>e[r],enumerable:!(s=Ye(e,r))||s.enumerable});return n};var Ze=n=>Xe(_e({},"__esModule",{value:!0}),n);var ut={};Je(ut,{COMPLETE:()=>A,COMPLETE_MSG:()=>me,COMPLETE_ONLY_BATCH:()=>le,DATA:()=>_,DEFAULT_ACTOR:()=>Ne,DIRTY:()=>w,DIRTY_MSG:()=>S,DIRTY_ONLY_BATCH:()=>Z,ERROR:()=>p,GraphReFlyConfig:()=>W,GuardDenied:()=>F,INVALIDATE:()=>T,INVALIDATE_MSG:()=>ye,INVALIDATE_ONLY_BATCH:()=>de,NodeImpl:()=>H,PAUSE:()=>N,RESOLVED:()=>x,RESOLVED_MSG:()=>J,RESOLVED_ONLY_BATCH:()=>ae,RESUME:()=>I,START:()=>C,START_MSG:()=>X,TEARDOWN:()=>b,TEARDOWN_MSG:()=>be,TEARDOWN_ONLY_BATCH:()=>Q,accessHintForGuard:()=>st,advanceVersion:()=>ue,autoTrackNode:()=>Be,batch:()=>Me,configure:()=>He,createVersioning:()=>te,defaultConfig:()=>G,defaultHash:()=>ee,derived:()=>Te,downWithBatch:()=>U,dynamicNode:()=>We,effect:()=>Ue,isBatching:()=>ie,isV1:()=>Re,monotonicNs:()=>ke,node:()=>L,normalizeActor:()=>Y,pipe:()=>je,policy:()=>De,policyFromRules:()=>tt,producer:()=>Pe,registerBuiltins:()=>ce,resolveDescribeFields:()=>Le,state:()=>Ve,wallClockNs:()=>oe});module.exports=Ze(ut);var Ne={type:"system",id:""};function Y(n){if(n==null)return Ne;let{type:e,id:t,...s}=n;return{type:e??"system",id:t??"",...s}}var V=0,q=!1,O=[],R=[],P=[],K=[];function ie(){return V>0||q}function Ae(){return V>0}function Ee(n){V>0?K.push(n):n()}function Me(n){V+=1;let e=!1;try{n()}catch(t){throw e=!0,t}finally{if(V-=1,V===0)if(e){if(!q){let t=K.splice(0);for(let s of t)try{s()}catch{}O.length=0,R.length=0,P.length=0}}else Qe()}}function Qe(){let n=!q;n&&(q=!0);let e=[],t=0;try{for(;O.length>0||R.length>0||P.length>0||n&&K.length>0;){if(n&&K.length>0){let o=K.splice(0);for(let a of o)try{a()}catch(i){e.push(i)}continue}if(t+=1,t>1e3)throw O.length=0,R.length=0,P.length=0,new Error("batch drain exceeded 1000 iterations \u2014 likely a reactive cycle");let r=(O.length>0?O:R.length>0?R:P).splice(0);for(let o of r)try{o()}catch(a){e.push(a)}}}finally{n&&(q=!1)}if(e.length===1)throw e[0];if(e.length>1)throw new AggregateError(e,"batch drain: multiple callbacks threw")}function U(n,e,t){if(e.length===0)return;if(e.length===1){let l=t(e[0][0]);if(l<3||!ie()){n(e);return}(l>=5?P:l===4?R:O).push(()=>n(e));return}let s=e.length,r=s,o=s,a=s,i=0;for(;i<s&&t(e[i][0])<3;)i++;for(r=i;i<s&&t(e[i][0])===3;)i++;for(o=i;i<s&&t(e[i][0])===4;)i++;a=i;let d=ie();if(r>0){let l=e.slice(0,r);n(l)}if(o>r){let l=e.slice(r,o);d?O.push(()=>n(l)):n(l)}if(a>o){let l=e.slice(o,a);d?R.push(()=>n(l)):n(l)}if(s>a){let l=e.slice(a,s);d?P.push(()=>n(l)):n(l)}}function ke(){return Math.trunc(performance.now()*1e6)}function oe(){return Date.now()*1e6}var C=Symbol.for("graphrefly/START"),_=Symbol.for("graphrefly/DATA"),w=Symbol.for("graphrefly/DIRTY"),x=Symbol.for("graphrefly/RESOLVED"),T=Symbol.for("graphrefly/INVALIDATE"),N=Symbol.for("graphrefly/PAUSE"),I=Symbol.for("graphrefly/RESUME"),b=Symbol.for("graphrefly/TEARDOWN"),A=Symbol.for("graphrefly/COMPLETE"),p=Symbol.for("graphrefly/ERROR"),S=Object.freeze([w]),J=Object.freeze([x]),ye=Object.freeze([T]),X=Object.freeze([C]),me=Object.freeze([A]),be=Object.freeze([b]),Z=Object.freeze([S]),ae=Object.freeze([J]),de=Object.freeze([ye]),le=Object.freeze([me]),Q=Object.freeze([be]);var W=class{_messageTypes=new Map;_codecs=new Map;_onMessage;_onSubscribe;_defaultVersioning;_defaultHashFn;_inspectorEnabled=!(typeof process<"u"&&process.env?.NODE_ENV==="production");_globalInspector;_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 s=this._messageTypes.get(t);return s!=null?s.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}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 ce(n){n.registerMessageType(C,{tier:0,wireCrossing:!1}),n.registerMessageType(w,{tier:1,wireCrossing:!1}),n.registerMessageType(T,{tier:1,wireCrossing:!1,metaPassthrough:!1}),n.registerMessageType(N,{tier:2,wireCrossing:!1}),n.registerMessageType(I,{tier:2,wireCrossing:!1}),n.registerMessageType(_,{tier:3,wireCrossing:!0}),n.registerMessageType(x,{tier:3,wireCrossing:!0}),n.registerMessageType(A,{tier:4,wireCrossing:!0,metaPassthrough:!1}),n.registerMessageType(p,{tier:4,wireCrossing:!0,metaPassthrough:!1}),n.registerMessageType(b,{tier:5,wireCrossing:!0,metaPassthrough:!1})}var F=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}};function Se(n){return Array.isArray(n)?[...n]:[n]}function et(n,e){return n.has(e)||n.has("*")}function De(n){let e=[];return n((r,o)=>{e.push({kind:"allow",actions:new Set(Se(r)),where:o?.where??(()=>!0)})},(r,o)=>{e.push({kind:"deny",actions:new Set(Se(r)),where:o?.where??(()=>!0)})}),(r,o)=>{let a=!1,i=!1;for(let d of e)et(d.actions,o)&&d.where(r)&&(d.kind==="deny"?a=!0:i=!0);return a?!1:i}}function tt(n){return De((e,t)=>{for(let s of n){let r=s.actorType==null?null:new Set(Array.isArray(s.actorType)?s.actorType:[s.actorType]),o=s.actorId==null?null:new Set(Array.isArray(s.actorId)?s.actorId:[s.actorId]),a=Object.entries(s.claims??{}),i=d=>{if(r!==null&&!r.has(String(d.type))||o!==null&&!o.has(String(d.id??"")))return!1;for(let[l,c]of a)if(d[l]!==c)return!1;return!0};s.effect==="deny"?t(s.action,{where:i}):e(s.action,{where:i})}})}var nt=["human","llm","wallet","system"];function st(n){let e=nt.filter(t=>n({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 rt={name:"json",version:1,contentType:"application/json",encode(n){let e=JSON.stringify(n);return new TextEncoder().encode(e)},decode(n,e){let t=new TextDecoder().decode(n);return JSON.parse(t)}};function Oe(n){n.registerCodec(rt)}function ve(n){if(n===void 0)return null;if(typeof n=="number"){if(!Number.isFinite(n))throw new TypeError(`Cannot hash non-finite number: ${n}`);if(Number.isInteger(n)&&!Number.isSafeInteger(n))throw new TypeError(`Cannot hash integer outside safe range (|n| > 2^53-1): ${n}. Cross-language cid parity is not guaranteed for unsafe integers.`);return n}if(typeof n=="string"||typeof n=="boolean"||n===null)return n;if(Array.isArray(n))return n.map(ve);if(typeof n=="object"&&n!==null){let e={};for(let t of Object.keys(n).sort())e[t]=ve(n[t]);return e}return null}var it=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]),ot=new TextEncoder;function at(n){let e=ot.encode(n),t=e.length,s=t*8,r=t+9+63&-64,o=new Uint8Array(r);o.set(e),o[t]=128;let a=new DataView(o.buffer);a.setUint32(r-4,s>>>0,!1),a.setUint32(r-8,Math.floor(s/4294967296)>>>0,!1);let i=1779033703,d=3144134277,l=1013904242,c=2773480762,u=1359893119,g=2600822924,f=528734635,v=1541459225,D=new Uint32Array(64),m=(M,y)=>M>>>y|M<<32-y;for(let M=0;M<r;M+=64){for(let h=0;h<16;h++)D[h]=a.getUint32(M+h*4,!1);for(let h=16;h<64;h++){let z=D[h-15],$=D[h-2],re=m(z,7)^m(z,18)^z>>>3,ge=m($,17)^m($,19)^$>>>10;D[h]=D[h-16]+re+D[h-7]+ge>>>0}let y=i,B=d,j=l,he=c,k=u,ne=g,se=f,pe=v;for(let h=0;h<64;h++){let z=m(k,6)^m(k,11)^m(k,25),$=k&ne^~k&se,re=pe+z+$+it[h]+D[h]>>>0,ge=m(y,2)^m(y,13)^m(y,22),ze=y&B^y&j^B&j,$e=ge+ze>>>0;pe=se,se=ne,ne=k,k=he+re>>>0,he=j,j=B,B=y,y=re+$e>>>0}i=i+y>>>0,d=d+B>>>0,l=l+j>>>0,c=c+he>>>0,u=u+k>>>0,g=g+ne>>>0,f=f+se>>>0,v=v+pe>>>0}let E=M=>M.toString(16).padStart(8,"0");return E(i)+E(d)+E(l)+E(c)+E(u)+E(g)+E(f)+E(v)}function ee(n){let e=ve(n??null),t=JSON.stringify(e);return at(t).slice(0,16)}function dt(){let n=globalThis.crypto;if(n?.randomUUID)return n.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 te(n,e,t){let s=t?.id??dt();if(n===0)return{id:s,version:0};let o=(t?.hash??ee)(e);return{id:s,version:0,cid:o,prev:null}}function ue(n,e,t){n.version+=1,"cid"in n&&(n.prev=n.cid,n.cid=t(e))}function Re(n){return"cid"in n}var Ce=()=>{},Ie=100;function Fe(n){return{node:n,unsub:null,prevData:void 0,dirty:!1,involvedThisWave:!1,dataBatch:[],terminal:void 0}}function we(n){n.prevData=void 0,n.dirty=!1,n.involvedThisWave=!1,n.dataBatch.length=0,n.terminal=void 0}function fe(n){return n.length===0?n:typeof n[0]=="symbol"?[n]:n}var lt=(n,e,t,s)=>{t.direction==="down-in"&&n._onDepMessage(t.depIndex,e)},ct=(n,e,t,s)=>{let r=n;if(r._status==="completed"||r._status==="errored")return;let o=r._cached,a=o===void 0?[X]:[X,[_,o]];r._status==="dirty"&&a.push(S),U(e,a,r._config.tierOf)},G=new W({onMessage:lt,onSubscribe:ct});ce(G);Oe(G);function He(n){if(G._isFrozen())throw new Error("configure() called after a node was created \u2014 the default GraphReFlyConfig is frozen. Call configure(...) at application startup, before any node factories run.");n(G)}var H=class n{_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,s){this._config=s.config??G,this._config.onMessage,this._optsName=s.name,this._describeKind=s.describeKind,this._equals=s.equals??Object.is,this._resubscribable=s.resubscribable??!1,this._resetOnTeardown=s.resetOnTeardown??!1,this._autoComplete=s.completeWhenDepsComplete??!0,this._autoError=s.errorWhenDepsError??!0,this._pausable=s.pausable??!0,this._guard=s.guard,this._fn=t,this._partial=s.partial??!1,this._cached=s.initial!==void 0?s.initial:void 0,this._status=e.length===0&&t==null&&this._cached!==void 0?"settled":"sentinel",this._hashFn=s.versioningHash??this._config.defaultHashFn??ee;let r=s.versioning??this._config.defaultVersioning;this._versioningLevel=r,this._versioning=r!=null?te(r,this._cached===void 0?void 0:this._cached,{id:s.versioningId,hash:this._hashFn}):void 0,this._deps=e.map(Fe);let o={};for(let[i,d]of Object.entries(s.meta??{})){let l={initial:d,name:`${s.name??"node"}:meta:${i}`,describeKind:"state",config:this._config};s.guard!=null&&(l.guard=s.guard),o[i]=new n([],void 0,l)}Object.freeze(o),this.meta=o,this._hasMeta=Object.keys(o).length>0;let a=this;this._actions={emit(i){a._emit([[_,i]])},down(i){a._emit(fe(i))},up(i){a._emitUp(fe(i))}},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 s=this._versioningLevel;if(s!=null&&e<=s)return;let r=t?.hash??this._hashFn;r!==this._hashFn&&(this._hashFn=r);let o=this._cached===void 0?void 0:this._cached,a=this._versioning,i=a?.id??t?.id,d=a?.version??0,l=te(e,o,{id:i,hash:r});l.version=d,this._versioning=l,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=Y(e);if(this._guard!=null&&!this._guard(t,"observe"))return!1;if(this._extraGuards!=null){for(let s of this._extraGuards)if(!s(t,"observe"))return!1}return!0}_checkGuard(e){if(e?.internal)return;let t=this._guard!=null||this._extraGuards!=null,s=e?.actor!=null;if(!t&&!s)return;let r=Y(e?.actor),o=e?.delivery==="signal"?"signal":"write";if(this._guard!=null&&!this._guard(r,o))throw new F({actor:r,action:o,nodeName:this.name});if(this._extraGuards!=null){for(let a of this._extraGuards)if(!a(r,o))throw new F({actor:r,action:o,nodeName:this.name})}this._lastMutation={actor:r,timestamp_ns:oe()}}down(e,t){let s=fe(e);s.length!==0&&(this._checkGuard(t),this._emit(s))}emit(e,t){this._checkGuard(t),this._emit([[_,e]])}up(e,t){if(this._deps.length===0)return;let s=fe(e);if(s.length===0)return;this._checkGuard(t);let r=t??{internal:!0};this._validateUpTiers(s);for(let o of this._deps)o.node.up?.(s,r)}_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 s of e){let r=t(s[0]);if(r===3||r===4)throw new Error(`Node "${this.name}": tier-${r} 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=Y(t);if(!this._guard(d,"observe"))throw new F({actor:d,action:"observe",nodeName:this.name})}let r=this._isTerminal&&this._resubscribable;if(r){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)we(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:r},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 a=this._isTerminal;if(this._sinkCount===1&&!a)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 i=!1;return()=>{i||(i=!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 s=0;s<e;s++){let r=s,o=this._deps[s];o.unsub=Ce,o.unsub=o.node.subscribe(a=>{if(o.unsub===null)return;let i=this._config.tierOf,d=!1;for(let l of a)i(l[0])>=3&&(d=!0),this._config.onMessage(this,l,{direction:"down-in",depIndex:r},this._actions);d&&this._maybeRunFnOnSettlement()}),t++}}catch(s){this._deps[t].unsub=null;for(let r=0;r<t;r++){let o=this._deps[r];if(o.unsub!=null){let a=o.unsub;o.unsub=null;try{a()}catch{}we(o)}}throw this._dirtyDepCount=0,s}}_addDep(e){for(let r=0;r<this._deps.length;r++)if(this._deps[r].node===e)return r;let t=this._deps.length,s=Fe(e);if(this._deps.push(s),this._sinks==null)return t;s.dirty=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(Z),s.unsub=Ce;try{s.unsub=e.subscribe(r=>{if(s.unsub===null)return;let o=this._config.tierOf,a=!1;for(let i of r)o(i[0])>=3&&(a=!0),this._config.onMessage(this,i,{direction:"down-in",depIndex:t},this._actions);a&&this._maybeRunFnOnSettlement()})}catch(r){throw s.unsub=null,this._deps.pop(),this._dirtyDepCount--,r}return t}_deactivate(e=!1){let t=this._cleanup;if(this._cleanup=void 0,typeof t=="function")try{t()}catch(s){this._emit([[p,this._wrapFnError("cleanup threw",s)]])}else if(t!=null&&typeof t=="object"){let s=t.deactivate;if(typeof s=="function")try{s()}catch(r){this._emit([[p,this._wrapFnError("cleanup.deactivate threw",r)]])}}for(let s of this._deps){if(s.unsub!=null){let r=s.unsub;s.unsub=null;try{r()}catch{}}we(s)}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 s=this._deps[e],r=t[0];if(this._inspectorHooks!=null){let o={kind:"dep_message",depIndex:e,message:t};for(let a of this._inspectorHooks)a(o)}if(r!==C){if(r===w){this._depDirtied(s);return}if(r===T){this._depInvalidated(s),this._emit(de);return}if(r===N||r===I){this._emit([t]);return}if(r===b){this._emit(Q);return}if(r===_)this._depSettledAsData(s,t[1]);else if(r===x)this._depSettledAsResolved(s);else if(r===A)this._depSettledAsTerminal(s,!0);else if(r===p)this._depSettledAsTerminal(s,t[1]);else{this._emit([t]);return}if(!this._fn){(r===_||r===x)&&this._emit([t]),(r===A||r===p)&&this._maybeAutoTerminalAfterWave();return}}}_depDirtied(e){e.dirty||(e.dirty=!0,e.involvedThisWave=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(Z))}_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(ae),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([[p,e.terminal]]);return}this._autoComplete&&this._deps.every(t=>t.terminal!==void 0)&&this._emit(le)}_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(a){this._emit([[p,this._wrapFnError("cleanup threw",a)]]);return}}else if(e!=null&&typeof e=="object"){let a=e.beforeRun;if(typeof a=="function"){e.beforeRun=void 0;try{a()}catch(i){this._emit([[p,this._wrapFnError("cleanup.beforeRun threw",i)]]);return}}}let t=this._deps.map(a=>a.involvedThisWave?a.dataBatch.length>0?[...a.dataBatch]:[]:void 0),s=this._deps.map(a=>a.prevData);for(let a=0;a<this._deps.length;a++){let i=t[a];i!=null&&i.length>0&&(this._deps[a].prevData=i[i.length-1])}let r=this._deps.map(a=>a.terminal),o={prevData:s,terminalDeps:r,store:this._store};if(this._hasCalledFnOnce=!0,this._clearWaveFlags(),this._inspectorHooks!=null){let a={kind:"run",batchData:t,prevData:s};for(let i of this._inspectorHooks)i(a)}this._isExecutingFn=!0;try{let a=this._fn(t,this._actions,o);if(typeof a=="function")this._cleanup=a;else if(a!=null&&typeof a=="object"){let i=a;(typeof i.beforeRun=="function"||typeof i.deactivate=="function"||typeof i.invalidate=="function")&&(this._cleanup=a)}}catch(a){this._emit([[p,this._wrapFnError("fn threw",a)]])}finally{this._isExecutingFn=!1,this._pendingRerun?(this._pendingRerun=!1,this._rerunDepth+=1,this._rerunDepth>Ie?(this._rerunDepth=0,this._emit([[p,new Error(`Node "${this.name}": _pendingRerun depth exceeded ${Ie} \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 s=t instanceof Error?t.message:String(t);return new Error(`Node "${this.name}": ${e}: ${s}`,{cause:t})}_frameBatch(e){let t=this._config.tierOf;if(e.length===1)return t(e[0][0])===3&&this._status!=="dirty"?[S,e[0]]:e;let s=!0,r=!1,o=!1,a=-1;for(let d of e){let l=t(d[0]);l<a&&(s=!1),l===3&&(r=!0),d[0]===w&&(o=!0),a=l}let i=e;if(!s){let d=e.map((l,c)=>({m:l,i:c,tier:t(l[0])}));d.sort((l,c)=>l.tier-c.tier||l.i-c.i),i=d.map(l=>l.m)}if(r&&!o&&this._status!=="dirty"){let d=0;for(;d<i.length&&t(i[d][0])===0;)d++;return d===0?[S,...i]:[...i.slice(0,d),S,...i.slice(d)]}return i}_emit(e){if(e.length===0)return;for(let i=0;i<e.length;i++){let d=e[i];if(d[0]===p&&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 i=e.filter(d=>d[0]===b||d[0]===T);if(i.length===0)return;t=i}t=this._frameBatch(t);let r=null;for(let i=0;i<t.length;i++){let d=t[i],l=d[0];if(l!==N&&l!==I){r?.push(d);continue}if(d.length<2)throw new Error(`Node "${this.name}": [[${l===N?"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 u=d[1];if(l===N)this._pauseLocks==null&&(this._pauseLocks=new Set),this._pauseLocks.add(u),this._paused=!0,this._pausable==="resumeAll"&&this._pauseBuffer==null&&(this._pauseBuffer=[]);else if(this._pauseLocks==null||!this._pauseLocks.has(u))c=!1;else if(this._pauseLocks.delete(u),this._pauseLocks.size===0){if(this._paused=!1,this._pauseBuffer!=null&&this._pauseBuffer.length>0){let g=this._pauseBuffer;this._pauseBuffer=[],this._emit(g)}this._pendingWave&&(this._pendingWave=!1,this._maybeRunFnOnSettlement())}}c?r?.push(d):r==null&&(r=t.slice(0,i))}if(r!=null){if(r.length===0)return;t=r}if(this._hasMeta&&t.some(i=>i[0]===b))for(let i of Object.keys(this.meta))try{this.meta[i]._emit(Q)}catch{}let{finalMessages:o,equalsError:a}=this._updateState(t);if(o.length>0&&this._config.inspectorEnabled){let i=this._config.globalInspector;if(i!=null)try{i({kind:"emit",node:this,messages:o})}catch{}}if(o.length>0)if(this._paused&&this._pausable==="resumeAll"&&this._pauseBuffer!=null){let i=this._config.tierOf,d=[];for(let l of o)i(l[0])===3?this._pauseBuffer.push(l):d.push(l);d.length>0&&this._dispatchOrAccumulate(d)}else this._dispatchOrAccumulate(o);a!=null&&this._emit([[p,a]])}_updateState(e){let t=this._config.tierOf,s,r,o=-1,a=0;for(let c of e)t(c[0])===3&&a++;let i=a<=1,d=-1;if(this._versioning!=null&&a>1){for(let c=e.length-1;c>=0;c--)if(e[c][0]===_){d=c;break}}for(let c=0;c<e.length;c++){let u=e[c],g=u[0];if(g===_){if(u.length>=2){let f=!1;if(i&&this._cached!==void 0)try{f=this._equals(this._cached,u[1])}catch(v){r=this._wrapFnError("equals threw",v),o=c;break}if(f){s==null&&(s=e.slice(0,c)),s.push(J),this._status="resolved";continue}this._cached=u[1],this._versioning!=null&&(d<0||c===d)&&ue(this._versioning,u[1],this._hashFn)}this._status="settled",s?.push(u)}else if(s?.push(u),g===w)this._status="dirty";else if(g===x)this._status="resolved";else if(g===A)this._status="completed";else if(g===p)this._status="errored";else if(g===T){this._cached=void 0,this._status="dirty";let f=this._cleanup;if(typeof f=="function"){this._cleanup=void 0;try{f()}catch{}}else if(f!=null&&typeof f=="object"){let v=f.invalidate;if(typeof v=="function")try{v()}catch{}}}else g===b&&(this._resetOnTeardown&&(this._cached=void 0),this._deactivate(!0),this._status="sentinel")}let l=o>=0?s??e.slice(0,o):s??e;return r!=null?{finalMessages:l,equalsError:r}:{finalMessages:l}}_deliverToSinks=e=>{if(this._sinks==null)return;if(typeof this._sinks=="function"){this._sinks(e);return}let t=[...this._sinks];for(let s of t)s(e)};_dispatchOrAccumulate(e){if(Ae()){this._batchPendingMessages===null&&(this._batchPendingMessages=[],Ee(()=>this._flushBatchPending()));for(let t of e)this._batchPendingMessages.push(t);return}U(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);U(this._deliverToSinks,t,this._config.tierOf)}},Ge=n=>Array.isArray(n),xe=n=>typeof n=="object"&&n!=null&&!Array.isArray(n);function L(n,e,t){let s=Ge(n)?n:[],r=typeof n=="function"?n:typeof e=="function"?e:void 0,o={};return Ge(n)?o=(xe(e)?e:t)??{}:xe(n)?o=n:o=(xe(e)?e:t)??{},new H(s,r,o)}function Le(n,e){if(e!=null&&e.length>0)return new Set(e);switch(n){case"standard":return new Set(["type","status","value","deps","meta","v"]);case"full":return null;default:return new Set(["type","deps"])}}function Ve(n,e){return L([],{...e,initial:n})}function Pe(n,e){return L((s,r,o)=>n(r,o)??void 0,{describeKind:"producer",...e})}function Te(n,e,t){return L(n,(r,o,a)=>{let i=r.map((d,l)=>d!=null&&d.length>0?d.at(-1):a.prevData[l]);o.emit(e(i,a))},{describeKind:"derived",...t})}function Ue(n,e,t){return L(n,(r,o,a)=>{let i=r.map((d,l)=>d!=null&&d.length>0?d.at(-1):a.prevData[l]);return e(i,o,a)??void 0},{describeKind:"effect",...t})}function We(n,e,t){let s=new Map;return n.forEach((r,o)=>{s.set(r,o)}),Te(n,(r,o)=>e(i=>{let d=s.get(i);if(d==null)throw new Error(`dynamicNode: untracked dep "${i.name??"<unnamed>"}"`);return r[d]},o),t)}function Be(n,e){let t,s=new Map,r=(o,a,i)=>{let d=!1,l=c=>{let u=s.get(c);if(u!==void 0){if(u<o.length){let f=o[u];return f!=null&&f.length>0?f.at(-1):i.prevData[u]}return c.cache}d=!0;let g=t._addDep(c);return s.set(c,g),c.cache};try{let c=n(l,i);d||(a.emit(c),i.store.__autoTrackLastDiscoveryError!=null&&delete i.store.__autoTrackLastDiscoveryError)}catch(c){if(!d)throw c;i.store.__autoTrackLastDiscoveryError=c}};return t=new H([],r,{describeKind:"derived",...e}),t}function je(n,...e){let t=n;for(let s of e)t=s(t);return t}0&&(module.exports={COMPLETE,COMPLETE_MSG,COMPLETE_ONLY_BATCH,DATA,DEFAULT_ACTOR,DIRTY,DIRTY_MSG,DIRTY_ONLY_BATCH,ERROR,GraphReFlyConfig,GuardDenied,INVALIDATE,INVALIDATE_MSG,INVALIDATE_ONLY_BATCH,NodeImpl,PAUSE,RESOLVED,RESOLVED_MSG,RESOLVED_ONLY_BATCH,RESUME,START,START_MSG,TEARDOWN,TEARDOWN_MSG,TEARDOWN_ONLY_BATCH,accessHintForGuard,advanceVersion,autoTrackNode,batch,configure,createVersioning,defaultConfig,defaultHash,derived,downWithBatch,dynamicNode,effect,isBatching,isV1,monotonicNs,node,normalizeActor,pipe,policy,policyFromRules,producer,registerBuiltins,resolveDescribeFields,state,wallClockNs});