@graphrefly/ts 0.0.0 → 0.0.2

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 (405) hide show
  1. package/README.md +135 -0
  2. package/dist/actions-types-CSC3NMDl.d.ts +657 -0
  3. package/dist/actions-types-wl9Mgkmr.d.cts +657 -0
  4. package/dist/adapters/index.cjs +5219 -2974
  5. package/dist/adapters/index.cjs.map +1 -1
  6. package/dist/adapters/index.d.cts +204 -192
  7. package/dist/adapters/index.d.ts +204 -192
  8. package/dist/adapters/index.js +3685 -1833
  9. package/dist/adapters/index.js.map +1 -1
  10. package/dist/adapters/nestjs/microservices.cjs +841 -0
  11. package/dist/adapters/nestjs/microservices.cjs.map +1 -0
  12. package/dist/adapters/nestjs/microservices.d.cts +45 -0
  13. package/dist/adapters/nestjs/microservices.d.ts +45 -0
  14. package/dist/adapters/nestjs/microservices.js +206 -0
  15. package/dist/adapters/nestjs/microservices.js.map +1 -0
  16. package/dist/adapters/nestjs/native.cjs +1391 -0
  17. package/dist/adapters/nestjs/native.cjs.map +1 -0
  18. package/dist/adapters/nestjs/native.d.cts +111 -0
  19. package/dist/adapters/nestjs/native.d.ts +111 -0
  20. package/dist/adapters/nestjs/native.js +577 -0
  21. package/dist/adapters/nestjs/native.js.map +1 -0
  22. package/dist/adapters/nestjs/websockets.cjs +924 -0
  23. package/dist/adapters/nestjs/websockets.cjs.map +1 -0
  24. package/dist/adapters/nestjs/websockets.d.cts +47 -0
  25. package/dist/adapters/nestjs/websockets.d.ts +47 -0
  26. package/dist/adapters/nestjs/websockets.js +286 -0
  27. package/dist/adapters/nestjs/websockets.js.map +1 -0
  28. package/dist/adapters/nestjs.cjs +1085 -0
  29. package/dist/adapters/nestjs.cjs.map +1 -0
  30. package/dist/adapters/nestjs.d.cts +385 -0
  31. package/dist/adapters/nestjs.d.ts +385 -0
  32. package/dist/adapters/nestjs.js +112 -0
  33. package/dist/adapters/nestjs.js.map +1 -0
  34. package/dist/adapters/observe-storage.d.cts +4 -4
  35. package/dist/adapters/observe-storage.d.ts +4 -4
  36. package/dist/adapters/observe-storage.js +5 -4
  37. package/dist/adapters/observe-storage.js.map +1 -1
  38. package/dist/adapters/react.cjs +166 -0
  39. package/dist/adapters/react.cjs.map +1 -0
  40. package/dist/adapters/react.d.cts +31 -0
  41. package/dist/adapters/react.d.ts +31 -0
  42. package/dist/adapters/react.js +51 -0
  43. package/dist/adapters/react.js.map +1 -0
  44. package/dist/adapters/solid.cjs +157 -0
  45. package/dist/adapters/solid.cjs.map +1 -0
  46. package/dist/adapters/solid.d.cts +26 -0
  47. package/dist/adapters/solid.d.ts +26 -0
  48. package/dist/adapters/solid.js +48 -0
  49. package/dist/adapters/solid.js.map +1 -0
  50. package/dist/adapters/svelte.cjs +148 -0
  51. package/dist/adapters/svelte.cjs.map +1 -0
  52. package/dist/adapters/svelte.d.cts +31 -0
  53. package/dist/adapters/svelte.d.ts +31 -0
  54. package/dist/adapters/svelte.js +46 -0
  55. package/dist/adapters/svelte.js.map +1 -0
  56. package/dist/adapters/vue.cjs +155 -0
  57. package/dist/adapters/vue.cjs.map +1 -0
  58. package/dist/adapters/vue.d.cts +26 -0
  59. package/dist/adapters/vue.d.ts +26 -0
  60. package/dist/adapters/vue.js +46 -0
  61. package/dist/adapters/vue.js.map +1 -0
  62. package/dist/agent-runtime-types-core-CaXfKNtY.d.cts +406 -0
  63. package/dist/agent-runtime-types-core-hU299uIC.d.ts +406 -0
  64. package/dist/agent-runtime-types-tool-BEpSINol.d.ts +695 -0
  65. package/dist/agent-runtime-types-tool-DninPEzk.d.cts +695 -0
  66. package/dist/agentic-memory-retention-BmGX368S.d.ts +14 -0
  67. package/dist/agentic-memory-retention-Ih1qhX9Z.d.cts +14 -0
  68. package/dist/agentic-memory-types-CVSUS6XR.d.ts +473 -0
  69. package/dist/agentic-memory-types-FnnYlVUs.d.cts +473 -0
  70. package/dist/capability-admission-BW2CziT6.d.ts +102 -0
  71. package/dist/capability-admission-lwSecxXs.d.cts +102 -0
  72. package/dist/chunk-2KUAG2GZ.js +9693 -0
  73. package/dist/chunk-2KUAG2GZ.js.map +1 -0
  74. package/dist/chunk-2NJP6GO4.js +1320 -0
  75. package/dist/chunk-2NJP6GO4.js.map +1 -0
  76. package/dist/{chunk-GDL26N2T.js → chunk-3KN7NJDR.js} +2 -2
  77. package/dist/{chunk-COHO25CZ.js → chunk-4NWSNI4K.js} +2232 -1672
  78. package/dist/chunk-4NWSNI4K.js.map +1 -0
  79. package/dist/{chunk-Z2ANQ6JW.js → chunk-4Q77MMJY.js} +2 -2
  80. package/dist/chunk-6E76H4OU.js +132 -0
  81. package/dist/chunk-6E76H4OU.js.map +1 -0
  82. package/dist/chunk-7GOTIIQ7.js +819 -0
  83. package/dist/chunk-7GOTIIQ7.js.map +1 -0
  84. package/dist/{chunk-D6BG7U6A.js → chunk-7HZRJMN6.js} +3 -3
  85. package/dist/{chunk-SCRFRCGR.js → chunk-BSQGE5PS.js} +1 -1
  86. package/dist/{chunk-PKVBHGBM.js → chunk-CJIFGJQG.js} +7 -7
  87. package/dist/{chunk-G4M3NHRJ.js → chunk-CX6B6PO2.js} +93 -10
  88. package/dist/chunk-CX6B6PO2.js.map +1 -0
  89. package/dist/chunk-DGUM43GV.js +11 -0
  90. package/dist/chunk-DGUM43GV.js.map +1 -0
  91. package/dist/{chunk-JIMUDQN3.js → chunk-E4QCH32M.js} +449 -447
  92. package/dist/chunk-E4QCH32M.js.map +1 -0
  93. package/dist/{chunk-RIIOUTGM.js → chunk-ECURQ3HD.js} +19 -129
  94. package/dist/chunk-ECURQ3HD.js.map +1 -0
  95. package/dist/{chunk-2ILL7HQI.js → chunk-EOKT4QFF.js} +134 -128
  96. package/dist/chunk-EOKT4QFF.js.map +1 -0
  97. package/dist/{chunk-K3FXTC3I.js → chunk-HJACH5PU.js} +3 -3
  98. package/dist/{chunk-GTPCOEOZ.js → chunk-IDMLXLLG.js} +3 -3
  99. package/dist/{chunk-DKP56CSW.js → chunk-JKAYLDQV.js} +2 -2
  100. package/dist/{chunk-4VLAQHZI.js → chunk-K7FB3JTD.js} +17 -1
  101. package/dist/chunk-K7FB3JTD.js.map +1 -0
  102. package/dist/chunk-L6LDXRWE.js +219 -0
  103. package/dist/chunk-L6LDXRWE.js.map +1 -0
  104. package/dist/chunk-M7J6Z4IJ.js +1930 -0
  105. package/dist/chunk-M7J6Z4IJ.js.map +1 -0
  106. package/dist/chunk-MQEQMS7B.js +1009 -0
  107. package/dist/chunk-MQEQMS7B.js.map +1 -0
  108. package/dist/chunk-MTELVIYR.js +1421 -0
  109. package/dist/chunk-MTELVIYR.js.map +1 -0
  110. package/dist/chunk-PVC7WDKI.js +885 -0
  111. package/dist/chunk-PVC7WDKI.js.map +1 -0
  112. package/dist/chunk-RAHNUYA5.js +368 -0
  113. package/dist/chunk-RAHNUYA5.js.map +1 -0
  114. package/dist/{chunk-DK554R7P.js → chunk-S6HXABGL.js} +2 -1
  115. package/dist/chunk-S6HXABGL.js.map +1 -0
  116. package/dist/{chunk-I3IHOHCJ.js → chunk-SHZDP2MQ.js} +1181 -1001
  117. package/dist/chunk-SHZDP2MQ.js.map +1 -0
  118. package/dist/{chunk-Y3ZLRGHC.js → chunk-SIDJO2T4.js} +16 -16
  119. package/dist/chunk-STXRMPW4.js +4131 -0
  120. package/dist/chunk-STXRMPW4.js.map +1 -0
  121. package/dist/{chunk-JR4IKCR2.js → chunk-TPND5MJS.js} +5 -5
  122. package/dist/chunk-TQPCAIQI.js +612 -0
  123. package/dist/chunk-TQPCAIQI.js.map +1 -0
  124. package/dist/chunk-UT3MHJCW.js +49 -0
  125. package/dist/chunk-UT3MHJCW.js.map +1 -0
  126. package/dist/{chunk-TEW47IVR.js → chunk-VPEFSDME.js} +2 -2
  127. package/dist/{chunk-SWTLEQL6.js → chunk-WQIA3GFB.js} +2 -2
  128. package/dist/chunk-WQIA3GFB.js.map +1 -0
  129. package/dist/{chunk-DJC4CHLQ.js → chunk-YDWBXXQZ.js} +5 -5
  130. package/dist/{chunk-6PHB5CJS.js → chunk-ZLFRB6FI.js} +2 -2
  131. package/dist/composition/index.cjs +1256 -1059
  132. package/dist/composition/index.cjs.map +1 -1
  133. package/dist/composition/index.d.cts +4 -4
  134. package/dist/composition/index.d.ts +4 -4
  135. package/dist/composition/index.js +7 -6
  136. package/dist/core/index.cjs +1218 -1021
  137. package/dist/core/index.cjs.map +1 -1
  138. package/dist/core/index.d.cts +2 -2
  139. package/dist/core/index.d.ts +2 -2
  140. package/dist/core/index.js +5 -4
  141. package/dist/cqrs/index.cjs.map +1 -1
  142. package/dist/cqrs/index.d.cts +4 -4
  143. package/dist/cqrs/index.d.ts +4 -4
  144. package/dist/cqrs/index.js +3 -2
  145. package/dist/cqrs/index.js.map +1 -1
  146. package/dist/cqrs/messaging.cjs +312 -0
  147. package/dist/cqrs/messaging.cjs.map +1 -0
  148. package/dist/cqrs/messaging.d.cts +57 -0
  149. package/dist/cqrs/messaging.d.ts +57 -0
  150. package/dist/cqrs/messaging.js +274 -0
  151. package/dist/cqrs/messaging.js.map +1 -0
  152. package/dist/cqrs/work-queue.cjs +329 -0
  153. package/dist/cqrs/work-queue.cjs.map +1 -0
  154. package/dist/cqrs/work-queue.d.cts +90 -0
  155. package/dist/cqrs/work-queue.d.ts +90 -0
  156. package/dist/cqrs/work-queue.js +292 -0
  157. package/dist/cqrs/work-queue.js.map +1 -0
  158. package/dist/data/index.cjs +19 -0
  159. package/dist/data/index.cjs.map +1 -0
  160. package/dist/data/index.d.cts +36 -0
  161. package/dist/data/index.d.ts +36 -0
  162. package/dist/data/index.js +1 -0
  163. package/dist/data/index.js.map +1 -0
  164. package/dist/data-structures/index.cjs +1252 -1052
  165. package/dist/data-structures/index.cjs.map +1 -1
  166. package/dist/data-structures/index.d.cts +9 -8
  167. package/dist/data-structures/index.d.ts +9 -8
  168. package/dist/data-structures/index.js +9 -7
  169. package/dist/{describe-BZb7AS2y.d.ts → describe-B_A5fbXH.d.ts} +1 -1
  170. package/dist/{describe-Ciu8SUnN.d.cts → describe-CQRrkv-Q.d.cts} +1 -1
  171. package/dist/executors/tool-provider-adapters.cjs +3091 -0
  172. package/dist/executors/tool-provider-adapters.cjs.map +1 -0
  173. package/dist/executors/tool-provider-adapters.d.cts +174 -0
  174. package/dist/executors/tool-provider-adapters.d.ts +174 -0
  175. package/dist/executors/tool-provider-adapters.js +1336 -0
  176. package/dist/executors/tool-provider-adapters.js.map +1 -0
  177. package/dist/executors/tool-provider-runtime.cjs +5178 -0
  178. package/dist/executors/tool-provider-runtime.cjs.map +1 -0
  179. package/dist/executors/tool-provider-runtime.d.cts +17 -0
  180. package/dist/executors/tool-provider-runtime.d.ts +17 -0
  181. package/dist/executors/tool-provider-runtime.js +15 -0
  182. package/dist/executors/tool-provider-runtime.js.map +1 -0
  183. package/dist/executors/tool-provider.cjs +6392 -0
  184. package/dist/executors/tool-provider.cjs.map +1 -0
  185. package/dist/executors/tool-provider.d.cts +60 -0
  186. package/dist/executors/tool-provider.d.ts +60 -0
  187. package/dist/executors/tool-provider.js +89 -0
  188. package/dist/executors/tool-provider.js.map +1 -0
  189. package/dist/executors/work-queue.cjs +342 -0
  190. package/dist/executors/work-queue.cjs.map +1 -0
  191. package/dist/executors/work-queue.d.cts +90 -0
  192. package/dist/executors/work-queue.d.ts +90 -0
  193. package/dist/executors/work-queue.js +306 -0
  194. package/dist/executors/work-queue.js.map +1 -0
  195. package/dist/graph/index.cjs +1536 -1324
  196. package/dist/graph/index.cjs.map +1 -1
  197. package/dist/graph/index.d.cts +10 -9
  198. package/dist/graph/index.d.ts +10 -9
  199. package/dist/graph/index.js +22 -20
  200. package/dist/{graph-s23RbbFO.d.cts → graph-CWK3HLPB.d.cts} +134 -132
  201. package/dist/{graph-DfdF9zy4.d.ts → graph-ho5sotHP.d.ts} +134 -132
  202. package/dist/{index-SnzZu3x7.d.ts → index-CQWcE0Dw.d.ts} +18 -4
  203. package/dist/{index-CAEmLCYF.d.cts → index-DHA1i67c.d.cts} +18 -4
  204. package/dist/index.cjs +3331 -3020
  205. package/dist/index.cjs.map +1 -1
  206. package/dist/index.d.cts +14 -10
  207. package/dist/index.d.ts +14 -10
  208. package/dist/index.js +114 -108
  209. package/dist/inspection/boundary.cjs +98 -0
  210. package/dist/inspection/boundary.cjs.map +1 -0
  211. package/dist/inspection/boundary.d.cts +61 -0
  212. package/dist/inspection/boundary.d.ts +61 -0
  213. package/dist/inspection/boundary.js +75 -0
  214. package/dist/inspection/boundary.js.map +1 -0
  215. package/dist/measurements-C0mAvWU1.d.cts +164 -0
  216. package/dist/measurements-OMpCeBwh.d.ts +164 -0
  217. package/dist/{messages-BZqrGGm1.d.ts → messages-CAzUPPJM.d.cts} +10 -5
  218. package/dist/{messages-BZqrGGm1.d.cts → messages-CAzUPPJM.d.ts} +10 -5
  219. package/dist/messaging/index.cjs +756 -619
  220. package/dist/messaging/index.cjs.map +1 -1
  221. package/dist/messaging/index.d.cts +17 -226
  222. package/dist/messaging/index.d.ts +17 -226
  223. package/dist/messaging/index.js +19 -749
  224. package/dist/messaging/index.js.map +1 -1
  225. package/dist/operators/index.cjs +1256 -1059
  226. package/dist/operators/index.cjs.map +1 -1
  227. package/dist/operators/index.d.cts +6 -6
  228. package/dist/operators/index.d.ts +6 -6
  229. package/dist/operators/index.js +9 -8
  230. package/dist/orchestration/index.cjs +8664 -2617
  231. package/dist/orchestration/index.cjs.map +1 -1
  232. package/dist/orchestration/index.d.cts +171 -221
  233. package/dist/orchestration/index.d.ts +171 -221
  234. package/dist/orchestration/index.js +74 -982
  235. package/dist/orchestration/index.js.map +1 -1
  236. package/dist/orchestration/messaging.cjs +314 -0
  237. package/dist/orchestration/messaging.cjs.map +1 -0
  238. package/dist/orchestration/messaging.d.cts +56 -0
  239. package/dist/orchestration/messaging.d.ts +56 -0
  240. package/dist/orchestration/messaging.js +276 -0
  241. package/dist/orchestration/messaging.js.map +1 -0
  242. package/dist/orchestration/work-queue.cjs +1500 -0
  243. package/dist/orchestration/work-queue.cjs.map +1 -0
  244. package/dist/orchestration/work-queue.d.cts +196 -0
  245. package/dist/orchestration/work-queue.d.ts +196 -0
  246. package/dist/orchestration/work-queue.js +1289 -0
  247. package/dist/orchestration/work-queue.js.map +1 -0
  248. package/dist/patterns/event-flow.cjs +433 -0
  249. package/dist/patterns/event-flow.cjs.map +1 -0
  250. package/dist/patterns/event-flow.d.cts +115 -0
  251. package/dist/patterns/event-flow.d.ts +115 -0
  252. package/dist/patterns/event-flow.js +14 -0
  253. package/dist/patterns/event-flow.js.map +1 -0
  254. package/dist/patterns/index.cjs +748 -355
  255. package/dist/patterns/index.cjs.map +1 -1
  256. package/dist/patterns/index.d.cts +9 -5
  257. package/dist/patterns/index.d.ts +9 -5
  258. package/dist/patterns/index.js +13 -4
  259. package/dist/process-types-C9uMYz3i.d.ts +200 -0
  260. package/dist/process-types-h3uRlzDc.d.cts +200 -0
  261. package/dist/{reactive-collection-BxBqtIOE.d.cts → reactive-collection-B9R0Bl1P.d.cts} +11 -41
  262. package/dist/{reactive-collection-Cb1II1Fi.d.ts → reactive-collection-BXFrH0U2.d.ts} +11 -41
  263. package/dist/{reactive-collection-storage-D-KmjE0J.d.cts → reactive-collection-storage-BLGv8Xp8.d.cts} +5 -5
  264. package/dist/{reactive-collection-storage-BNiEc-Gd.d.ts → reactive-collection-storage-a4zD3665.d.ts} +5 -5
  265. package/dist/{reactive-map-BcB4KsQR.d.ts → reactive-map-C_8sOfdS.d.cts} +7 -6
  266. package/dist/{reactive-map-D-g3dv8I.d.cts → reactive-map-jle5dnok.d.ts} +7 -6
  267. package/dist/render/index.d.cts +3 -3
  268. package/dist/render/index.d.ts +3 -3
  269. package/dist/render/index.js +1 -0
  270. package/dist/scheduled-readiness-5rwQlyjV.d.ts +91 -0
  271. package/dist/scheduled-readiness-DpRY8jI0.d.cts +91 -0
  272. package/dist/semantic-memory-graph-C2ZUwIlq.d.ts +30 -0
  273. package/dist/semantic-memory-graph-DlZBD_Eu.d.cts +30 -0
  274. package/dist/{semantic-memory-graph-BYoIlP35.d.cts → semantic-memory-graph-types-BvzdqmkY.d.cts} +2 -28
  275. package/dist/{semantic-memory-graph-CxyXLms3.d.ts → semantic-memory-graph-types-Ci-OtahO.d.ts} +2 -28
  276. package/dist/solutions/index.cjs +6788 -2128
  277. package/dist/solutions/index.cjs.map +1 -1
  278. package/dist/solutions/index.d.cts +15 -519
  279. package/dist/solutions/index.d.ts +15 -519
  280. package/dist/solutions/index.js +91 -7
  281. package/dist/solutions/reactive-layout/browser/index.cjs +457 -0
  282. package/dist/solutions/reactive-layout/browser/index.cjs.map +1 -0
  283. package/dist/solutions/reactive-layout/browser/index.d.cts +44 -0
  284. package/dist/solutions/reactive-layout/browser/index.d.ts +44 -0
  285. package/dist/solutions/reactive-layout/browser/index.js +69 -0
  286. package/dist/solutions/reactive-layout/browser/index.js.map +1 -0
  287. package/dist/solutions/reactive-layout/index.cjs +4494 -0
  288. package/dist/solutions/reactive-layout/index.cjs.map +1 -0
  289. package/dist/solutions/reactive-layout/index.d.cts +37 -0
  290. package/dist/solutions/reactive-layout/index.d.ts +37 -0
  291. package/dist/solutions/reactive-layout/index.js +146 -0
  292. package/dist/solutions/reactive-layout/index.js.map +1 -0
  293. package/dist/solutions/reactive-layout/node-canvas/index.cjs +555 -0
  294. package/dist/solutions/reactive-layout/node-canvas/index.cjs.map +1 -0
  295. package/dist/solutions/reactive-layout/node-canvas/index.d.cts +54 -0
  296. package/dist/solutions/reactive-layout/node-canvas/index.d.ts +54 -0
  297. package/dist/solutions/reactive-layout/node-canvas/index.js +131 -0
  298. package/dist/solutions/reactive-layout/node-canvas/index.js.map +1 -0
  299. package/dist/solutions/reactive-layout/react-native/index.cjs +504 -0
  300. package/dist/solutions/reactive-layout/react-native/index.cjs.map +1 -0
  301. package/dist/solutions/reactive-layout/react-native/index.d.cts +51 -0
  302. package/dist/solutions/reactive-layout/react-native/index.d.ts +51 -0
  303. package/dist/solutions/reactive-layout/react-native/index.js +77 -0
  304. package/dist/solutions/reactive-layout/react-native/index.js.map +1 -0
  305. package/dist/solutions/reactive-layout/skia/index.cjs +557 -0
  306. package/dist/solutions/reactive-layout/skia/index.cjs.map +1 -0
  307. package/dist/solutions/reactive-layout/skia/index.d.cts +64 -0
  308. package/dist/solutions/reactive-layout/skia/index.d.ts +64 -0
  309. package/dist/solutions/reactive-layout/skia/index.js +70 -0
  310. package/dist/solutions/reactive-layout/skia/index.js.map +1 -0
  311. package/dist/solutions/work-item/actions.cjs +2345 -0
  312. package/dist/solutions/work-item/actions.cjs.map +1 -0
  313. package/dist/solutions/work-item/actions.d.cts +40 -0
  314. package/dist/solutions/work-item/actions.d.ts +40 -0
  315. package/dist/solutions/work-item/actions.js +2078 -0
  316. package/dist/solutions/work-item/actions.js.map +1 -0
  317. package/dist/solutions/work-item/scheduling.cjs +9797 -0
  318. package/dist/solutions/work-item/scheduling.cjs.map +1 -0
  319. package/dist/solutions/work-item/scheduling.d.cts +1868 -0
  320. package/dist/solutions/work-item/scheduling.d.ts +1868 -0
  321. package/dist/solutions/work-item/scheduling.js +146 -0
  322. package/dist/solutions/work-item/scheduling.js.map +1 -0
  323. package/dist/solutions/work-item/work-queue.cjs +306 -0
  324. package/dist/solutions/work-item/work-queue.cjs.map +1 -0
  325. package/dist/solutions/work-item/work-queue.d.cts +71 -0
  326. package/dist/solutions/work-item/work-queue.d.ts +71 -0
  327. package/dist/solutions/work-item/work-queue.js +270 -0
  328. package/dist/solutions/work-item/work-queue.js.map +1 -0
  329. package/dist/sources/browser.cjs +1399 -1052
  330. package/dist/sources/browser.cjs.map +1 -1
  331. package/dist/sources/browser.d.cts +33 -6
  332. package/dist/sources/browser.d.ts +33 -6
  333. package/dist/sources/browser.js +73 -6
  334. package/dist/sources/browser.js.map +1 -1
  335. package/dist/sources/index.cjs +1345 -1065
  336. package/dist/sources/index.cjs.map +1 -1
  337. package/dist/sources/index.d.cts +5 -5
  338. package/dist/sources/index.d.ts +5 -5
  339. package/dist/sources/index.js +7 -6
  340. package/dist/sources/node.cjs.map +1 -1
  341. package/dist/sources/node.d.cts +4 -4
  342. package/dist/sources/node.d.ts +4 -4
  343. package/dist/sources/node.js +2 -1
  344. package/dist/sources/node.js.map +1 -1
  345. package/dist/storage/browser.cjs +16 -0
  346. package/dist/storage/browser.cjs.map +1 -1
  347. package/dist/storage/browser.js +4 -3
  348. package/dist/storage/browser.js.map +1 -1
  349. package/dist/storage/index.cjs +16 -0
  350. package/dist/storage/index.cjs.map +1 -1
  351. package/dist/storage/index.d.cts +6 -5
  352. package/dist/storage/index.d.ts +6 -5
  353. package/dist/storage/index.js +10 -9
  354. package/dist/storage/node.cjs +16 -0
  355. package/dist/storage/node.cjs.map +1 -1
  356. package/dist/storage/node.js +4 -3
  357. package/dist/storage/node.js.map +1 -1
  358. package/dist/store-BmtEs9mG.d.ts +123 -0
  359. package/dist/store-PAAsYvML.d.cts +123 -0
  360. package/dist/testing/index.cjs +1 -0
  361. package/dist/testing/index.cjs.map +1 -1
  362. package/dist/testing/index.d.cts +1 -1
  363. package/dist/testing/index.d.ts +1 -1
  364. package/dist/testing/index.js +3 -2
  365. package/dist/types-BRNKoFHj.d.ts +357 -0
  366. package/dist/{types-h12mNYbq.d.ts → types-BS6CyR-x.d.cts} +49 -130
  367. package/dist/types-BWK2ay3e.d.cts +457 -0
  368. package/dist/types-BXKSAoE1.d.cts +357 -0
  369. package/dist/types-BaPpZItj.d.ts +457 -0
  370. package/dist/types-BhveCMg5.d.cts +274 -0
  371. package/dist/{types-bNMSWKqF.d.cts → types-C9NOgNJw.d.ts} +49 -130
  372. package/dist/types-CTsQ8Ww4.d.ts +274 -0
  373. package/dist/types-DL_05n2M.d.ts +34 -0
  374. package/dist/types-XDoqxYO9.d.cts +34 -0
  375. package/dist/work-item-runtime-types-BqtWnSCS.d.ts +138 -0
  376. package/dist/work-item-runtime-types-CHO03AKh.d.cts +138 -0
  377. package/dist/work-queue/index.cjs +1136 -0
  378. package/dist/work-queue/index.cjs.map +1 -0
  379. package/dist/work-queue/index.d.cts +21 -0
  380. package/dist/work-queue/index.d.ts +21 -0
  381. package/dist/work-queue/index.js +1082 -0
  382. package/dist/work-queue/index.js.map +1 -0
  383. package/package.json +603 -249
  384. package/dist/chunk-2ILL7HQI.js.map +0 -1
  385. package/dist/chunk-4VLAQHZI.js.map +0 -1
  386. package/dist/chunk-COHO25CZ.js.map +0 -1
  387. package/dist/chunk-DK554R7P.js.map +0 -1
  388. package/dist/chunk-G4M3NHRJ.js.map +0 -1
  389. package/dist/chunk-I3IHOHCJ.js.map +0 -1
  390. package/dist/chunk-JIMUDQN3.js.map +0 -1
  391. package/dist/chunk-RIIOUTGM.js.map +0 -1
  392. package/dist/chunk-SWTLEQL6.js.map +0 -1
  393. /package/dist/{chunk-GDL26N2T.js.map → chunk-3KN7NJDR.js.map} +0 -0
  394. /package/dist/{chunk-Z2ANQ6JW.js.map → chunk-4Q77MMJY.js.map} +0 -0
  395. /package/dist/{chunk-D6BG7U6A.js.map → chunk-7HZRJMN6.js.map} +0 -0
  396. /package/dist/{chunk-SCRFRCGR.js.map → chunk-BSQGE5PS.js.map} +0 -0
  397. /package/dist/{chunk-PKVBHGBM.js.map → chunk-CJIFGJQG.js.map} +0 -0
  398. /package/dist/{chunk-K3FXTC3I.js.map → chunk-HJACH5PU.js.map} +0 -0
  399. /package/dist/{chunk-GTPCOEOZ.js.map → chunk-IDMLXLLG.js.map} +0 -0
  400. /package/dist/{chunk-DKP56CSW.js.map → chunk-JKAYLDQV.js.map} +0 -0
  401. /package/dist/{chunk-Y3ZLRGHC.js.map → chunk-SIDJO2T4.js.map} +0 -0
  402. /package/dist/{chunk-JR4IKCR2.js.map → chunk-TPND5MJS.js.map} +0 -0
  403. /package/dist/{chunk-TEW47IVR.js.map → chunk-VPEFSDME.js.map} +0 -0
  404. /package/dist/{chunk-DJC4CHLQ.js.map → chunk-YDWBXXQZ.js.map} +0 -0
  405. /package/dist/{chunk-6PHB5CJS.js.map → chunk-ZLFRB6FI.js.map} +0 -0
@@ -0,0 +1,4494 @@
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/solutions/reactive-layout/index.ts
21
+ var reactive_layout_exports = {};
22
+ __export(reactive_layout_exports, {
23
+ BLOCKS_MEASUREMENT_KIND: () => BLOCKS_MEASUREMENT_KIND,
24
+ CapabilityMeasureAdapter: () => CapabilityMeasureAdapter,
25
+ CellMeasureAdapter: () => CellMeasureAdapter,
26
+ IMAGE_SIZE_MEASUREMENT_KIND: () => IMAGE_SIZE_MEASUREMENT_KIND,
27
+ ImageSizeAdapter: () => ImageSizeAdapter,
28
+ InjectedMeasureAdapter: () => InjectedMeasureAdapter,
29
+ PrecomputedMeasureAdapter: () => PrecomputedMeasureAdapter,
30
+ READINESS_MEASUREMENT_KIND: () => READINESS_MEASUREMENT_KIND,
31
+ SVG_BOUNDS_MEASUREMENT_KIND: () => SVG_BOUNDS_MEASUREMENT_KIND,
32
+ SvgBoundsAdapter: () => SvgBoundsAdapter,
33
+ TEXT_SEGMENTS_MEASUREMENT_KIND: () => TEXT_SEGMENTS_MEASUREMENT_KIND,
34
+ analyzeAndMeasure: () => analyzeAndMeasure,
35
+ blockAdaptersProvider: () => blockAdaptersProvider,
36
+ blockMaxWidth: () => blockMaxWidth,
37
+ blockMeasurementProvider: () => blockMeasurementProvider,
38
+ blockedIntervalsForBand: () => blockedIntervalsForBand,
39
+ capabilityTextMeasurements: () => capabilityTextMeasurements,
40
+ carveTextLineSlots: () => carveTextLineSlots,
41
+ cellTextMeasurements: () => cellTextMeasurements,
42
+ circleIntervalForBand: () => circleIntervalForBand,
43
+ clampDimension: () => clampDimension,
44
+ columnGeometry: () => columnGeometry,
45
+ computeBlockFlow: () => computeBlockFlow,
46
+ computeCharPositions: () => computeCharPositions,
47
+ computeFlowLines: () => computeFlowLines,
48
+ computeLineBreaks: () => computeLineBreaks,
49
+ computeTotalHeight: () => computeTotalHeight,
50
+ createDefaultSegmentAdapter: () => createDefaultSegmentAdapter,
51
+ emitLayoutError: () => emitLayoutError,
52
+ finiteNumber: () => finiteNumber,
53
+ fitSize: () => fitSize,
54
+ getDefaultSegmentAdapter: () => getDefaultSegmentAdapter,
55
+ imageSizeMeasurements: () => imageSizeMeasurements,
56
+ injectedTextMeasurements: () => injectedTextMeasurements,
57
+ inputNode: () => inputNode,
58
+ isCJK: () => isCJK,
59
+ kinsokuStart: () => kinsokuStart,
60
+ latestMeasurementValue: () => latestMeasurementValue,
61
+ layoutNextLine: () => layoutNextLine,
62
+ leftStickyPunctuation: () => leftStickyPunctuation,
63
+ measureBlock: () => measureBlock,
64
+ measureBlocks: () => measureBlocks,
65
+ measuredWidth: () => measuredWidth,
66
+ measurementIssue: () => measurementIssue,
67
+ measurementOk: () => measurementOk,
68
+ mergeMeasurements: () => mergeMeasurements,
69
+ metricKey: () => metricKey,
70
+ nonNegativeFinite: () => nonNegativeFinite,
71
+ normalizeWhitespace: () => normalizeWhitespace,
72
+ positiveFinite: () => positiveFinite,
73
+ precomputedTextMeasurements: () => precomputedTextMeasurements,
74
+ reactiveBlockLayout: () => reactiveBlockLayout,
75
+ reactiveFlowLayout: () => reactiveFlowLayout,
76
+ reactiveLayout: () => reactiveLayout,
77
+ readinessMeasurements: () => readinessMeasurements,
78
+ readinessTextMeasurements: () => readinessTextMeasurements,
79
+ rectIntervalForBand: () => rectIntervalForBand,
80
+ resolveTextAdapter: () => resolveTextAdapter,
81
+ sanitizeFlowColumns: () => sanitizeFlowColumns,
82
+ sanitizeFlowContainer: () => sanitizeFlowContainer,
83
+ sanitizeObstacles: () => sanitizeObstacles,
84
+ scopedName: () => scopedName,
85
+ segmentText: () => segmentText,
86
+ svgBoundsMeasurements: () => svgBoundsMeasurements,
87
+ textMeasurementFacts: () => textMeasurementFacts,
88
+ textMeasurementProvider: () => textMeasurementProvider,
89
+ tryMeasureHyphenWidth: () => tryMeasureHyphenWidth,
90
+ validMeasurementSize: () => validMeasurementSize
91
+ });
92
+ module.exports = __toCommonJS(reactive_layout_exports);
93
+
94
+ // src/solutions/reactive-layout/segment.ts
95
+ var kinsokuStart = /* @__PURE__ */ new Set([
96
+ "\u3001",
97
+ "\u3002",
98
+ "\u30FB",
99
+ "\uFF09",
100
+ "\u3015",
101
+ "\u3009",
102
+ "\u300B",
103
+ "\u300D",
104
+ "\u300F",
105
+ "\u3011"
106
+ ]);
107
+ var leftStickyPunctuation = /* @__PURE__ */ new Set([
108
+ ".",
109
+ ",",
110
+ "!",
111
+ "?",
112
+ ":",
113
+ ";",
114
+ ")",
115
+ "]",
116
+ "}",
117
+ "%",
118
+ '"',
119
+ "\u201D",
120
+ "\u2019",
121
+ "\xBB",
122
+ "\u203A",
123
+ "\u2026"
124
+ ]);
125
+ function isCJK(text) {
126
+ for (const ch of text) {
127
+ const c = ch.codePointAt(0);
128
+ if (c !== void 0 && c >= 19968 && c <= 40959 || c !== void 0 && c >= 13312 && c <= 19903 || c !== void 0 && c >= 12288 && c <= 12351 || c !== void 0 && c >= 12352 && c <= 12447 || c !== void 0 && c >= 44032 && c <= 55215 || c !== void 0 && c >= 65280 && c <= 65519) {
129
+ return true;
130
+ }
131
+ }
132
+ return false;
133
+ }
134
+ function normalizeWhitespace(text) {
135
+ return text.replace(/[\t\f ]+/g, " ").replace(/^ | $/g, "");
136
+ }
137
+ function segmentText(text, segmentAdapter) {
138
+ const pieces = [];
139
+ for (const s of segmentAdapter.segmentWords(text)) {
140
+ const wordSegment = s.segment;
141
+ const rawWordLike = s.isWordLike ?? false;
142
+ const pieceTexts = [];
143
+ const pieceWordLikes = [];
144
+ const pieceKinds = [];
145
+ let currentText = "";
146
+ let currentKind = null;
147
+ for (const ch of wordSegment) {
148
+ let kind;
149
+ if (ch === " ") {
150
+ kind = "space";
151
+ } else if (ch === "\u200B") {
152
+ kind = "zero-width-break";
153
+ } else if (ch === "\xAD") {
154
+ kind = "soft-hyphen";
155
+ } else if (ch === "\n") {
156
+ kind = "hard-break";
157
+ } else {
158
+ kind = "text";
159
+ }
160
+ if (currentKind !== null && kind === currentKind) {
161
+ currentText += ch;
162
+ } else {
163
+ if (currentKind !== null) {
164
+ pieceTexts.push(currentText);
165
+ pieceWordLikes.push(currentKind === "text" && rawWordLike);
166
+ pieceKinds.push(currentKind);
167
+ }
168
+ currentText = ch;
169
+ currentKind = kind;
170
+ }
171
+ }
172
+ if (currentKind !== null) {
173
+ pieceTexts.push(currentText);
174
+ pieceWordLikes.push(currentKind === "text" && rawWordLike);
175
+ pieceKinds.push(currentKind);
176
+ }
177
+ pieces.push({ texts: pieceTexts, isWordLike: pieceWordLikes, kinds: pieceKinds });
178
+ }
179
+ return pieces;
180
+ }
181
+ function* fallbackSegmentWords(text) {
182
+ let index = 0;
183
+ let current = "";
184
+ let currentIndex = 0;
185
+ let currentWordLike = null;
186
+ const flush = () => {
187
+ if (current.length === 0 || currentWordLike === null) return void 0;
188
+ const out2 = { segment: current, index: currentIndex, isWordLike: currentWordLike };
189
+ current = "";
190
+ currentWordLike = null;
191
+ return out2;
192
+ };
193
+ for (const ch of text) {
194
+ const isWordLike = !/[\s\u200B\u00AD]/u.test(ch);
195
+ if (currentWordLike !== null && currentWordLike !== isWordLike) {
196
+ const out2 = flush();
197
+ if (out2) yield out2;
198
+ }
199
+ if (currentWordLike === null) {
200
+ currentWordLike = isWordLike;
201
+ currentIndex = index;
202
+ }
203
+ current += ch;
204
+ index += ch.length;
205
+ }
206
+ const out = flush();
207
+ if (out) yield out;
208
+ }
209
+ function* fallbackSegmentGraphemes(text) {
210
+ let index = 0;
211
+ for (const ch of text) {
212
+ yield { segment: ch, index };
213
+ index += ch.length;
214
+ }
215
+ }
216
+ function createDefaultSegmentAdapter() {
217
+ return {
218
+ segmentWords(text) {
219
+ return fallbackSegmentWords(text);
220
+ },
221
+ segmentGraphemes(text) {
222
+ return fallbackSegmentGraphemes(text);
223
+ }
224
+ };
225
+ }
226
+ var defaultSegmentAdapter = null;
227
+ function getDefaultSegmentAdapter() {
228
+ if (defaultSegmentAdapter === null) {
229
+ defaultSegmentAdapter = createDefaultSegmentAdapter();
230
+ }
231
+ return defaultSegmentAdapter;
232
+ }
233
+ function measuredWidth(value) {
234
+ const width = typeof value === "number" ? value : value.width;
235
+ return Number.isFinite(width) && width >= 0 ? width : 0;
236
+ }
237
+ function metricKey(text, font) {
238
+ return `${font}\0${text}`;
239
+ }
240
+
241
+ // src/protocol/messages.ts
242
+ var SENTINEL = void 0;
243
+ function isInvalidErrorPayload(v) {
244
+ return v === SENTINEL || typeof v === "boolean";
245
+ }
246
+ function errorPayload(reason, fallback = "error without a valid payload") {
247
+ return isInvalidErrorPayload(reason) ? new Error(fallback) : reason;
248
+ }
249
+ var TIER_START = 0;
250
+ var TIER_CONTROL = 1;
251
+ var TIER_NOTIFICATION = 2;
252
+ var TIER_VALUE = 3;
253
+ var TIER_SETTLE = 4;
254
+ var TIER_TERMINAL = 5;
255
+ var TIER_TEARDOWN = 6;
256
+ var TIER = {
257
+ START: TIER_START,
258
+ PAUSE: TIER_CONTROL,
259
+ RESUME: TIER_CONTROL,
260
+ PULL: TIER_CONTROL,
261
+ DIRTY: TIER_NOTIFICATION,
262
+ DATA: TIER_VALUE,
263
+ RESOLVED: TIER_VALUE,
264
+ INVALIDATE: TIER_SETTLE,
265
+ COMPLETE: TIER_TERMINAL,
266
+ ERROR: TIER_TERMINAL,
267
+ TEARDOWN: TIER_TEARDOWN
268
+ };
269
+ function messageTier(t) {
270
+ return TIER[t];
271
+ }
272
+ function isDeferredTier(t) {
273
+ return TIER[t] >= TIER_VALUE;
274
+ }
275
+ function isValueTier(t) {
276
+ return TIER[t] === TIER_VALUE;
277
+ }
278
+ function isPauseBufferedTier(t) {
279
+ const tier = TIER[t];
280
+ return tier === TIER_VALUE || tier === TIER_SETTLE;
281
+ }
282
+ function isTerminal(t) {
283
+ return TIER[t] === TIER_TERMINAL;
284
+ }
285
+ function isUpAllowed(t) {
286
+ const tier = TIER[t];
287
+ return tier !== TIER_VALUE && tier !== TIER_TERMINAL;
288
+ }
289
+
290
+ // src/solutions/reactive-layout/utils.ts
291
+ function nonNegativeFinite(value, fallback) {
292
+ return Number.isFinite(value) ? Math.max(0, value) : fallback;
293
+ }
294
+ function finiteNumber(value, fallback) {
295
+ return Number.isFinite(value) ? value : fallback;
296
+ }
297
+ function emitLayoutError(ctx, error, fallback) {
298
+ ctx.down([["ERROR", errorPayload(error, fallback)]]);
299
+ }
300
+ function positiveFinite(value, fallback) {
301
+ return Number.isFinite(value) && value > 0 ? value : fallback;
302
+ }
303
+ function clampDimension(value) {
304
+ return nonNegativeFinite(value ?? 0, 0);
305
+ }
306
+ function fitSize(size, maxWidth) {
307
+ const width = nonNegativeFinite(size.width, 0);
308
+ const height = nonNegativeFinite(size.height, 0);
309
+ if (width === 0 || maxWidth <= 0 || width <= maxWidth) return { width, height };
310
+ const scale = maxWidth / width;
311
+ return { width: maxWidth, height: height * scale };
312
+ }
313
+ function blockMaxWidth(blockMaxWidth2, maxWidth) {
314
+ const own = blockMaxWidth2 === void 0 ? maxWidth : nonNegativeFinite(blockMaxWidth2, maxWidth);
315
+ if (maxWidth <= 0) return own;
316
+ if (own <= 0) return maxWidth;
317
+ return Math.min(own, maxWidth);
318
+ }
319
+ function resolveTextAdapter(opts) {
320
+ const adapter = opts.adapters?.text ?? opts.adapter;
321
+ if (!adapter) throw new Error("Text blocks require a MeasurementAdapter");
322
+ return adapter;
323
+ }
324
+
325
+ // src/solutions/reactive-layout/adapters.ts
326
+ var InjectedMeasureAdapter = class {
327
+ measure;
328
+ shouldCache;
329
+ cache = /* @__PURE__ */ new Map();
330
+ constructor(measure, opts = {}) {
331
+ this.measure = measure;
332
+ this.shouldCache = opts.cache ?? true;
333
+ }
334
+ measureSegment(text, font) {
335
+ const key = metricKey(text, font);
336
+ if (this.shouldCache) {
337
+ const cached = this.cache.get(key);
338
+ if (cached !== void 0) return { width: cached };
339
+ }
340
+ const width = measuredWidth(this.measure(text, font));
341
+ if (this.shouldCache) this.cache.set(key, width);
342
+ return { width };
343
+ }
344
+ clearCache() {
345
+ this.cache.clear();
346
+ }
347
+ };
348
+ var PrecomputedMeasureAdapter = class {
349
+ metrics;
350
+ fallback;
351
+ cellWidth;
352
+ constructor(opts) {
353
+ this.metrics = opts.metrics instanceof Map ? opts.metrics : new Map(Object.entries(opts.metrics));
354
+ this.fallback = opts.fallback ?? "error";
355
+ this.cellWidth = nonNegativeFinite(opts.cellWidth ?? 8, 8);
356
+ }
357
+ measureSegment(text, font) {
358
+ const fontScoped = this.metrics.get(metricKey(text, font));
359
+ if (fontScoped !== void 0) return { width: nonNegativeFinite(fontScoped, 0) };
360
+ const unscoped = this.metrics.get(text);
361
+ if (unscoped !== void 0) return { width: nonNegativeFinite(unscoped, 0) };
362
+ if (this.fallback === "per-char") {
363
+ return { width: Array.from(text).length * this.cellWidth };
364
+ }
365
+ throw new Error(`No precomputed metric for segment ${JSON.stringify(text)}`);
366
+ }
367
+ };
368
+ var CellMeasureAdapter = class {
369
+ cellWidth;
370
+ wideCellWidth;
371
+ tabCells;
372
+ constructor(opts = {}) {
373
+ this.cellWidth = nonNegativeFinite(opts.cellWidth ?? 8, 8);
374
+ this.wideCellWidth = nonNegativeFinite(
375
+ opts.wideCellWidth ?? this.cellWidth * 2,
376
+ this.cellWidth * 2
377
+ );
378
+ this.tabCells = Math.max(1, Math.floor(nonNegativeFinite(opts.tabCells ?? 4, 4)));
379
+ }
380
+ measureSegment(text) {
381
+ let width = 0;
382
+ for (const char of text) {
383
+ if (char === " ") width += this.cellWidth * this.tabCells;
384
+ else width += isCJK(char) ? this.wideCellWidth : this.cellWidth;
385
+ }
386
+ return { width };
387
+ }
388
+ };
389
+ var CapabilityMeasureAdapter = class {
390
+ capability;
391
+ constructor(capability) {
392
+ this.capability = capability;
393
+ }
394
+ measureSegment(text, font) {
395
+ return { width: measuredWidth(this.capability.measureText(text, font)) };
396
+ }
397
+ clearCache() {
398
+ this.capability.clearCache?.();
399
+ }
400
+ };
401
+ function stripSvgIgnoredContent(svg) {
402
+ return svg.replace(/<!--[\s\S]*?-->/g, "").replace(/<!\[CDATA\[[\s\S]*?\]\]>/g, "");
403
+ }
404
+ function readSvgRootTag(svg) {
405
+ return /<svg\b[^>]*>/i.exec(svg)?.[0] ?? null;
406
+ }
407
+ function readNumericAttr(tag, attr) {
408
+ const pattern = new RegExp(`(?:^|\\s)${attr}\\s*=\\s*["']?(-?\\d+(?:\\.\\d+)?)`, "i");
409
+ const match = pattern.exec(tag);
410
+ if (!match) return null;
411
+ const value = Number(match[1]);
412
+ return Number.isFinite(value) && value >= 0 ? value : null;
413
+ }
414
+ function readViewBox(tag) {
415
+ const match = /\bviewBox\s*=\s*["']\s*(-?\d+(?:\.\d+)?)\s+(-?\d+(?:\.\d+)?)\s+(-?\d+(?:\.\d+)?)\s+(-?\d+(?:\.\d+)?)\s*["']/i.exec(
416
+ tag
417
+ );
418
+ if (!match) return null;
419
+ const width = Number(match[3]);
420
+ const height = Number(match[4]);
421
+ if (!Number.isFinite(width) || !Number.isFinite(height) || width < 0 || height < 0) {
422
+ return null;
423
+ }
424
+ return { width, height };
425
+ }
426
+ var SvgBoundsAdapter = class {
427
+ measureSvg(svg) {
428
+ const cleaned = stripSvgIgnoredContent(svg);
429
+ const rootTag = readSvgRootTag(cleaned);
430
+ if (rootTag === null) throw new Error("Cannot measure SVG without a root <svg> element");
431
+ const width = readNumericAttr(rootTag, "width");
432
+ const height = readNumericAttr(rootTag, "height");
433
+ if (width !== null && height !== null) return { width, height };
434
+ const viewBox = readViewBox(rootTag);
435
+ if (viewBox) return viewBox;
436
+ throw new Error("Cannot measure SVG without width/height or viewBox");
437
+ }
438
+ };
439
+ var ImageSizeAdapter = class {
440
+ sizes;
441
+ constructor(sizes) {
442
+ this.sizes = isImageSizeLookup(sizes) ? sizes : new Map(Object.entries(sizes));
443
+ }
444
+ measureImage(src) {
445
+ const size = this.sizes.get(src);
446
+ if (!size) throw new Error(`No image size registered for ${JSON.stringify(src)}`);
447
+ return size;
448
+ }
449
+ };
450
+ function isImageSizeLookup(value) {
451
+ if (value === null) return false;
452
+ const valueType = typeof value;
453
+ if (valueType !== "object" && valueType !== "function") return false;
454
+ return typeof value.get === "function";
455
+ }
456
+
457
+ // src/solutions/reactive-layout/line.ts
458
+ function analyzeAndMeasure(text, font, adapter, cache, stats, segmentAdapter) {
459
+ const normalized = normalizeWhitespace(text);
460
+ if (normalized.length === 0) {
461
+ return [];
462
+ }
463
+ const segAdapter = segmentAdapter ?? getDefaultSegmentAdapter();
464
+ const pieces = segmentText(normalized, segAdapter);
465
+ const rawTexts = [];
466
+ const rawKinds = [];
467
+ const rawWordLike = [];
468
+ for (const piece of pieces) {
469
+ for (let i = 0; i < piece.texts.length; i += 1) {
470
+ rawTexts.push(piece.texts[i]);
471
+ rawKinds.push(piece.kinds[i]);
472
+ rawWordLike.push(piece.isWordLike[i]);
473
+ }
474
+ }
475
+ const mergedTexts = [];
476
+ const mergedKinds = [];
477
+ const mergedWordLike = [];
478
+ for (let i = 0; i < rawTexts.length; i += 1) {
479
+ const t = rawTexts[i];
480
+ const k = rawKinds[i];
481
+ const wl = rawWordLike[i];
482
+ if (k === "text" && !wl && mergedTexts.length > 0 && mergedKinds[mergedTexts.length - 1] === "text") {
483
+ const isSticky = t.length === 1 && (leftStickyPunctuation.has(t) || kinsokuStart.has(t));
484
+ if (isSticky) {
485
+ mergedTexts[mergedTexts.length - 1] += t;
486
+ continue;
487
+ }
488
+ }
489
+ if (t === "-" && mergedTexts.length > 0 && mergedKinds[mergedKinds.length - 1] === "text" && mergedWordLike[mergedWordLike.length - 1]) {
490
+ mergedTexts[mergedTexts.length - 1] += t;
491
+ continue;
492
+ }
493
+ mergedTexts.push(t);
494
+ mergedKinds.push(k);
495
+ mergedWordLike.push(wl);
496
+ }
497
+ const fontCache = cache.get(font) ?? /* @__PURE__ */ new Map();
498
+ if (!cache.has(font)) cache.set(font, fontCache);
499
+ function measureCached(segment) {
500
+ const cached = fontCache.get(segment);
501
+ if (cached === void 0) {
502
+ if (stats) stats.misses += 1;
503
+ const measured = adapter.measureSegment(segment, font).width;
504
+ const width = Number.isFinite(measured) && measured >= 0 ? measured : 0;
505
+ fontCache.set(segment, width);
506
+ return width;
507
+ }
508
+ if (stats) stats.hits += 1;
509
+ return cached;
510
+ }
511
+ const out = [];
512
+ for (let i = 0; i < mergedTexts.length; i += 1) {
513
+ const t = mergedTexts[i];
514
+ const kind = mergedKinds[i];
515
+ if (kind !== "text") {
516
+ out.push({
517
+ text: t,
518
+ width: kind === "space" ? measureCached(" ") * t.length : 0,
519
+ kind,
520
+ graphemeWidths: null
521
+ });
522
+ continue;
523
+ }
524
+ if (isCJK(t)) {
525
+ let unitText = "";
526
+ for (const graphemeSegment of segAdapter.segmentGraphemes(t)) {
527
+ const grapheme = graphemeSegment.segment;
528
+ if (unitText.length > 0 && kinsokuStart.has(grapheme)) {
529
+ unitText += grapheme;
530
+ continue;
531
+ }
532
+ if (unitText.length > 0) {
533
+ out.push({
534
+ text: unitText,
535
+ width: measureCached(unitText),
536
+ kind: "text",
537
+ graphemeWidths: null
538
+ });
539
+ }
540
+ unitText = grapheme;
541
+ }
542
+ if (unitText.length > 0) {
543
+ out.push({
544
+ text: unitText,
545
+ width: measureCached(unitText),
546
+ kind: "text",
547
+ graphemeWidths: null
548
+ });
549
+ }
550
+ continue;
551
+ }
552
+ const textWidth = measureCached(t);
553
+ let graphemeWidths = null;
554
+ if (mergedWordLike[i] && t.length > 1) {
555
+ const widths = [];
556
+ for (const grapheme of segAdapter.segmentGraphemes(t)) {
557
+ widths.push(measureCached(grapheme.segment));
558
+ }
559
+ if (widths.length > 1) graphemeWidths = widths;
560
+ }
561
+ out.push({
562
+ text: t,
563
+ width: textWidth,
564
+ kind: "text",
565
+ graphemeWidths
566
+ });
567
+ }
568
+ return out;
569
+ }
570
+ function computeLineBreaks(segments, maxWidth, opts = {}) {
571
+ if (segments.length === 0) return { lines: [], lineCount: 0 };
572
+ const segAdapter = opts.segmentAdapter ?? getDefaultSegmentAdapter();
573
+ const lines = [];
574
+ let cursor = { segmentIndex: 0, graphemeIndex: 0 };
575
+ while (cursor.segmentIndex < segments.length) {
576
+ const next = layoutNextLine(segments, cursor, maxWidth, {
577
+ hyphenWidth: opts.hyphenWidth,
578
+ segmentAdapter: segAdapter
579
+ });
580
+ if (next === null) break;
581
+ lines.push({
582
+ text: next.text,
583
+ width: next.width,
584
+ startSegment: next.start.segmentIndex,
585
+ startGrapheme: next.start.graphemeIndex,
586
+ endSegment: next.end.segmentIndex,
587
+ endGrapheme: next.end.graphemeIndex
588
+ });
589
+ if (next.end.segmentIndex === cursor.segmentIndex && next.end.graphemeIndex === cursor.graphemeIndex) {
590
+ break;
591
+ }
592
+ cursor = next.end;
593
+ }
594
+ return { lines, lineCount: lines.length };
595
+ }
596
+ function canBreakAfter(kind) {
597
+ return kind === "space" || kind === "zero-width-break" || kind === "soft-hyphen";
598
+ }
599
+ function sliceSegmentText(seg, startGrapheme, endGrapheme, segmentAdapter) {
600
+ if (startGrapheme === 0 && endGrapheme < 0) return seg.text;
601
+ const graphemes = [...segmentAdapter.segmentGraphemes(seg.text)].map((g) => g.segment);
602
+ const stop = endGrapheme < 0 ? graphemes.length : endGrapheme;
603
+ return graphemes.slice(startGrapheme, stop).join("");
604
+ }
605
+ function buildLineText(segments, startSegment, startGrapheme, endSegment, endGrapheme, appendHyphen, segmentAdapter) {
606
+ let text = "";
607
+ for (let i = startSegment; i < endSegment; i += 1) {
608
+ const seg = segments[i];
609
+ if (seg.kind === "soft-hyphen" || seg.kind === "hard-break") continue;
610
+ if (i === startSegment && startGrapheme > 0) {
611
+ text += sliceSegmentText(seg, startGrapheme, -1, segmentAdapter);
612
+ } else {
613
+ text += seg.text;
614
+ }
615
+ }
616
+ if (endGrapheme > 0 && endSegment < segments.length) {
617
+ const seg = segments[endSegment];
618
+ const from = startSegment === endSegment ? startGrapheme : 0;
619
+ text += sliceSegmentText(seg, from, endGrapheme, segmentAdapter);
620
+ }
621
+ if (appendHyphen) text += "-";
622
+ return text;
623
+ }
624
+ function resolveHyphenWidth(ctx) {
625
+ if (ctx?.hyphenWidth !== void 0) return nonNegativeFinite(ctx.hyphenWidth, 0);
626
+ if (ctx?.adapter === void 0 || ctx.font === void 0) return 0;
627
+ const cache = ctx.cache;
628
+ if (cache) {
629
+ let fontCache = cache.get(ctx.font);
630
+ if (fontCache === void 0) {
631
+ fontCache = /* @__PURE__ */ new Map();
632
+ cache.set(ctx.font, fontCache);
633
+ }
634
+ let width = fontCache.get("-");
635
+ if (width === void 0) {
636
+ width = ctx.adapter.measureSegment("-", ctx.font).width;
637
+ fontCache.set("-", width);
638
+ }
639
+ return width;
640
+ }
641
+ return ctx.adapter.measureSegment("-", ctx.font).width;
642
+ }
643
+ function layoutNextLine(segments, cursor, slotWidth, ctx) {
644
+ let i = cursor.segmentIndex;
645
+ const initialGrapheme = cursor.graphemeIndex;
646
+ const segmentAdapter = ctx?.segmentAdapter ?? getDefaultSegmentAdapter();
647
+ if (i >= segments.length) return null;
648
+ if (initialGrapheme === 0) {
649
+ while (i < segments.length) {
650
+ const seg = segments[i];
651
+ if (seg.kind === "hard-break") {
652
+ return {
653
+ text: "",
654
+ width: 0,
655
+ start: { segmentIndex: cursor.segmentIndex, graphemeIndex: 0 },
656
+ end: { segmentIndex: i + 1, graphemeIndex: 0 }
657
+ };
658
+ }
659
+ if (seg.kind === "space" || seg.kind === "zero-width-break" || seg.kind === "soft-hyphen") {
660
+ i += 1;
661
+ continue;
662
+ }
663
+ break;
664
+ }
665
+ if (i >= segments.length) return null;
666
+ }
667
+ const hyphenWidth = resolveHyphenWidth(ctx);
668
+ const startSegment = i;
669
+ const startGrapheme = i === cursor.segmentIndex ? initialGrapheme : 0;
670
+ let lineW = 0;
671
+ let lineEndSegment = startSegment;
672
+ let lineEndGrapheme = 0;
673
+ let hasContent = false;
674
+ let pendingBreakSegment = -1;
675
+ let pendingBreakGrapheme = 0;
676
+ let pendingBreakWidth = 0;
677
+ let pendingBreakSoftHyphen = false;
678
+ const recordPending = (sIdx, gIdx, width, kind) => {
679
+ pendingBreakSegment = sIdx;
680
+ pendingBreakGrapheme = gIdx;
681
+ pendingBreakWidth = width;
682
+ pendingBreakSoftHyphen = kind === "soft-hyphen";
683
+ };
684
+ const consumeBreakable = (segIdx, startG, widths) => {
685
+ for (let g = startG; g < widths.length; g += 1) {
686
+ const gw = widths[g];
687
+ if (!hasContent) {
688
+ lineW = gw;
689
+ lineEndSegment = segIdx;
690
+ lineEndGrapheme = g + 1;
691
+ hasContent = true;
692
+ continue;
693
+ }
694
+ if (lineW + gw > slotWidth + 1e-3) {
695
+ return true;
696
+ }
697
+ lineW += gw;
698
+ lineEndSegment = segIdx;
699
+ lineEndGrapheme = g + 1;
700
+ }
701
+ if (lineEndSegment === segIdx && lineEndGrapheme === widths.length) {
702
+ lineEndSegment = segIdx + 1;
703
+ lineEndGrapheme = 0;
704
+ }
705
+ return false;
706
+ };
707
+ if (startGrapheme > 0 && startSegment < segments.length) {
708
+ const seg = segments[startSegment];
709
+ if (seg.graphemeWidths) {
710
+ const overflow = consumeBreakable(startSegment, startGrapheme, seg.graphemeWidths);
711
+ if (overflow) {
712
+ const text2 = buildLineText(
713
+ segments,
714
+ startSegment,
715
+ startGrapheme,
716
+ lineEndSegment,
717
+ lineEndGrapheme,
718
+ false,
719
+ segmentAdapter
720
+ );
721
+ return {
722
+ text: text2,
723
+ width: lineW,
724
+ start: { segmentIndex: startSegment, graphemeIndex: startGrapheme },
725
+ end: { segmentIndex: lineEndSegment, graphemeIndex: lineEndGrapheme }
726
+ };
727
+ }
728
+ i = lineEndSegment;
729
+ }
730
+ }
731
+ for (; i < segments.length; i += 1) {
732
+ const seg = segments[i];
733
+ if (seg.kind === "hard-break") {
734
+ if (hasContent) {
735
+ const endsAtSoftHyphen2 = lineEndSegment > 0 && segments[lineEndSegment - 1]?.kind === "soft-hyphen";
736
+ const text2 = buildLineText(
737
+ segments,
738
+ startSegment,
739
+ startGrapheme,
740
+ lineEndSegment,
741
+ lineEndGrapheme,
742
+ endsAtSoftHyphen2,
743
+ segmentAdapter
744
+ );
745
+ return {
746
+ text: text2,
747
+ width: lineW + (endsAtSoftHyphen2 ? hyphenWidth : 0),
748
+ start: { segmentIndex: startSegment, graphemeIndex: startGrapheme },
749
+ end: { segmentIndex: i + 1, graphemeIndex: 0 }
750
+ };
751
+ }
752
+ return {
753
+ text: "",
754
+ width: 0,
755
+ start: { segmentIndex: startSegment, graphemeIndex: startGrapheme },
756
+ end: { segmentIndex: i + 1, graphemeIndex: 0 }
757
+ };
758
+ }
759
+ const w = seg.width;
760
+ if (!hasContent) {
761
+ if (w > slotWidth && seg.graphemeWidths) {
762
+ const overflow = consumeBreakable(i, 0, seg.graphemeWidths);
763
+ if (overflow) {
764
+ const text2 = buildLineText(
765
+ segments,
766
+ startSegment,
767
+ startGrapheme,
768
+ lineEndSegment,
769
+ lineEndGrapheme,
770
+ false,
771
+ segmentAdapter
772
+ );
773
+ return {
774
+ text: text2,
775
+ width: lineW,
776
+ start: { segmentIndex: startSegment, graphemeIndex: startGrapheme },
777
+ end: { segmentIndex: lineEndSegment, graphemeIndex: lineEndGrapheme }
778
+ };
779
+ }
780
+ i = lineEndSegment - 1;
781
+ continue;
782
+ }
783
+ lineW = w;
784
+ lineEndSegment = i + 1;
785
+ lineEndGrapheme = 0;
786
+ hasContent = true;
787
+ if (canBreakAfter(seg.kind)) {
788
+ recordPending(i + 1, 0, seg.kind === "space" ? lineW - w : lineW, seg.kind);
789
+ }
790
+ continue;
791
+ }
792
+ const projectedWidth = lineW + w;
793
+ if (projectedWidth > slotWidth + 1e-3) {
794
+ if (canBreakAfter(seg.kind)) {
795
+ lineEndSegment = i + 1;
796
+ lineEndGrapheme = 0;
797
+ const endsAtSoftHyphen2 = seg.kind === "soft-hyphen";
798
+ const text3 = buildLineText(
799
+ segments,
800
+ startSegment,
801
+ startGrapheme,
802
+ lineEndSegment,
803
+ lineEndGrapheme,
804
+ endsAtSoftHyphen2,
805
+ segmentAdapter
806
+ );
807
+ return {
808
+ text: text3,
809
+ width: seg.kind === "space" ? lineW : lineW + (endsAtSoftHyphen2 ? hyphenWidth : 0),
810
+ start: { segmentIndex: startSegment, graphemeIndex: startGrapheme },
811
+ end: { segmentIndex: lineEndSegment, graphemeIndex: lineEndGrapheme }
812
+ };
813
+ }
814
+ if (pendingBreakSegment >= 0) {
815
+ const text3 = buildLineText(
816
+ segments,
817
+ startSegment,
818
+ startGrapheme,
819
+ pendingBreakSegment,
820
+ pendingBreakGrapheme,
821
+ pendingBreakSoftHyphen,
822
+ segmentAdapter
823
+ );
824
+ return {
825
+ text: text3,
826
+ width: pendingBreakWidth + (pendingBreakSoftHyphen ? hyphenWidth : 0),
827
+ start: { segmentIndex: startSegment, graphemeIndex: startGrapheme },
828
+ end: { segmentIndex: pendingBreakSegment, graphemeIndex: pendingBreakGrapheme }
829
+ };
830
+ }
831
+ if (w > slotWidth && seg.graphemeWidths) {
832
+ const text3 = buildLineText(
833
+ segments,
834
+ startSegment,
835
+ startGrapheme,
836
+ lineEndSegment,
837
+ lineEndGrapheme,
838
+ false,
839
+ segmentAdapter
840
+ );
841
+ return {
842
+ text: text3,
843
+ width: lineW,
844
+ start: { segmentIndex: startSegment, graphemeIndex: startGrapheme },
845
+ end: { segmentIndex: lineEndSegment, graphemeIndex: lineEndGrapheme }
846
+ };
847
+ }
848
+ const text2 = buildLineText(
849
+ segments,
850
+ startSegment,
851
+ startGrapheme,
852
+ lineEndSegment,
853
+ lineEndGrapheme,
854
+ false,
855
+ segmentAdapter
856
+ );
857
+ return {
858
+ text: text2,
859
+ width: lineW,
860
+ start: { segmentIndex: startSegment, graphemeIndex: startGrapheme },
861
+ end: { segmentIndex: lineEndSegment, graphemeIndex: lineEndGrapheme }
862
+ };
863
+ }
864
+ lineW = projectedWidth;
865
+ lineEndSegment = i + 1;
866
+ lineEndGrapheme = 0;
867
+ if (canBreakAfter(seg.kind)) {
868
+ recordPending(i + 1, 0, seg.kind === "space" ? lineW - w : lineW, seg.kind);
869
+ }
870
+ }
871
+ if (!hasContent) return null;
872
+ const endsAtSoftHyphen = lineEndSegment > 0 && segments[lineEndSegment - 1]?.kind === "soft-hyphen";
873
+ const text = buildLineText(
874
+ segments,
875
+ startSegment,
876
+ startGrapheme,
877
+ lineEndSegment,
878
+ lineEndGrapheme,
879
+ endsAtSoftHyphen,
880
+ segmentAdapter
881
+ );
882
+ return {
883
+ text,
884
+ width: lineW + (endsAtSoftHyphen ? hyphenWidth : 0),
885
+ start: { segmentIndex: startSegment, graphemeIndex: startGrapheme },
886
+ end: { segmentIndex: lineEndSegment, graphemeIndex: lineEndGrapheme }
887
+ };
888
+ }
889
+ function carveTextLineSlots(base, blocked, minSlotWidth = 0) {
890
+ let slots = [base];
891
+ for (const block of blocked) {
892
+ const next = [];
893
+ for (const slot of slots) {
894
+ if (block.right <= slot.left || block.left >= slot.right) {
895
+ next.push(slot);
896
+ continue;
897
+ }
898
+ if (block.left > slot.left) next.push({ left: slot.left, right: block.left });
899
+ if (block.right < slot.right) next.push({ left: block.right, right: slot.right });
900
+ }
901
+ slots = next;
902
+ }
903
+ if (minSlotWidth > 0) return slots.filter((slot) => slot.right - slot.left >= minSlotWidth);
904
+ return slots;
905
+ }
906
+ function computeCharPositions(lineBreaks, segments, lineHeight, segmentAdapter) {
907
+ const positions = [];
908
+ const segAdapter = segmentAdapter ?? getDefaultSegmentAdapter();
909
+ for (let lineIdx = 0; lineIdx < lineBreaks.lines.length; lineIdx += 1) {
910
+ const line = lineBreaks.lines[lineIdx];
911
+ const y = lineIdx * lineHeight;
912
+ let x = 0;
913
+ for (let si = line.startSegment; si < segments.length; si += 1) {
914
+ const seg = segments[si];
915
+ if (seg.kind === "soft-hyphen" || seg.kind === "hard-break") {
916
+ if (si >= line.endSegment && line.endGrapheme === 0) break;
917
+ continue;
918
+ }
919
+ const graphemes = [...segAdapter.segmentGraphemes(seg.text)].map((g) => g.segment);
920
+ if (graphemes.length === 0) continue;
921
+ const startGrapheme = si === line.startSegment ? line.startGrapheme : 0;
922
+ let endGrapheme;
923
+ if (si < line.endSegment) {
924
+ endGrapheme = graphemes.length;
925
+ } else if (si === line.endSegment && line.endGrapheme > 0) {
926
+ endGrapheme = line.endGrapheme;
927
+ } else {
928
+ break;
929
+ }
930
+ for (let g = startGrapheme; g < endGrapheme; g += 1) {
931
+ const width = seg.graphemeWidths ? seg.graphemeWidths[g] : seg.width / graphemes.length;
932
+ positions.push({ x, y, width, height: lineHeight, line: lineIdx });
933
+ x += width;
934
+ }
935
+ }
936
+ }
937
+ return positions;
938
+ }
939
+
940
+ // src/ctx/types.ts
941
+ var CTX_DEP_CACHE = /* @__PURE__ */ Symbol("graphrefly.ctx.depCache");
942
+ var CTX_NODE_BINDING = /* @__PURE__ */ Symbol("graphrefly.ctx.nodeBinding");
943
+ function depLatest(ctx, depIndex) {
944
+ return ctx[CTX_DEP_CACHE]?.latest[depIndex];
945
+ }
946
+
947
+ // src/batch/boundary.ts
948
+ var depth = 0;
949
+ var pendingCores = [];
950
+ var pendingHead = 0;
951
+ function enterWave() {
952
+ depth++;
953
+ }
954
+ function exitWave() {
955
+ depth--;
956
+ if (depth === 0 && pendingHead < pendingCores.length) drain();
957
+ }
958
+ function deferRewire(core, apply, options = {}) {
959
+ core.enqueueBoundaryTask({ apply, batchToken: options.batchToken, isReady: options.isReady });
960
+ pendingCores.push(core);
961
+ }
962
+ function scheduleBoundaryDrain(core) {
963
+ for (let i = 0; i < core.boundaryTaskCount(); i++) pendingCores.push(core);
964
+ if (depth === 0 && pendingHead < pendingCores.length) drain();
965
+ }
966
+ function drain() {
967
+ let escaped = null;
968
+ while (pendingHead < pendingCores.length) {
969
+ const core = pendingCores[pendingHead++];
970
+ const task = core.shiftBoundaryTask();
971
+ if (task === void 0) continue;
972
+ if (task.batchToken !== void 0) {
973
+ const committed = task.batchToken.committed === true;
974
+ if (!committed) continue;
975
+ }
976
+ if (task.isReady !== void 0 && !task.isReady()) {
977
+ core.unshiftBoundaryTask(task);
978
+ continue;
979
+ }
980
+ depth++;
981
+ try {
982
+ task.apply();
983
+ } catch (e) {
984
+ if (escaped === null) escaped = { e };
985
+ } finally {
986
+ depth--;
987
+ }
988
+ }
989
+ pendingCores.length = 0;
990
+ pendingHead = 0;
991
+ if (escaped !== null) throw escaped.e;
992
+ }
993
+
994
+ // src/dispatcher/index.ts
995
+ var PoolTable = class {
996
+ constructor(kind) {
997
+ this.kind = kind;
998
+ }
999
+ fns = [];
1000
+ free = [];
1001
+ register(fn) {
1002
+ const reused = this.free.pop();
1003
+ if (reused !== void 0) {
1004
+ this.fns[reused] = fn;
1005
+ return reused;
1006
+ }
1007
+ const id = this.fns.length;
1008
+ this.fns.push(fn);
1009
+ return id;
1010
+ }
1011
+ unregister(handleId) {
1012
+ if (this.fns[handleId] === void 0) return;
1013
+ this.fns[handleId] = void 0;
1014
+ this.free.push(handleId);
1015
+ }
1016
+ invoke(handleId, ctx) {
1017
+ this.fns[handleId](ctx);
1018
+ }
1019
+ };
1020
+ var statKey = (h) => `${h.poolId}:${h.handleId}`;
1021
+ var Dispatcher = class {
1022
+ pools = [];
1023
+ syncPoolId;
1024
+ asyncPoolId;
1025
+ // opt-in profile recorder (default OFF → zero overhead, F-PERF).
1026
+ _recording = false;
1027
+ _stats = /* @__PURE__ */ new Map();
1028
+ _totalInvokes = 0;
1029
+ constructor() {
1030
+ this.syncPoolId = this.addPool(new PoolTable("sync"));
1031
+ this.asyncPoolId = this.addPool(new PoolTable("async"));
1032
+ }
1033
+ /** Turn the profile recorder on/off (D39). Off = zero overhead on invoke. */
1034
+ setRecording(on) {
1035
+ this._recording = on;
1036
+ }
1037
+ /** Reset accumulated profiling counters. */
1038
+ clearStats() {
1039
+ this._stats.clear();
1040
+ this._totalInvokes = 0;
1041
+ }
1042
+ /** Read a handle's accumulated counters (undefined if it never ran while recording). */
1043
+ statFor(handle) {
1044
+ return this._stats.get(statKey(handle));
1045
+ }
1046
+ /** Total fn invocations recorded across the dispatcher. */
1047
+ get totalInvokes() {
1048
+ return this._totalInvokes;
1049
+ }
1050
+ addPool(pool) {
1051
+ const id = this.pools.length;
1052
+ this.pools.push(pool);
1053
+ return id;
1054
+ }
1055
+ /** Register a fn in a pool, returning its Handle. Default pool = sync (R-sync-core). */
1056
+ register(fn, pool = "sync") {
1057
+ const poolId = pool === "sync" ? this.syncPoolId : pool === "async" ? this.asyncPoolId : pool;
1058
+ const handleId = this.pools[poolId].register(fn);
1059
+ return { poolId, handleId };
1060
+ }
1061
+ /**
1062
+ * Release a handle (B15): frees the pool slot (closure GC'd, id reusable) and drops any
1063
+ * accumulated profile stat so a reused id never inherits the previous tenant's counters.
1064
+ * Called on rewire fn-swap (node._rewire) — the old handle is dropped before the node
1065
+ * adopts the new one. Idempotent. NOT called on deactivate (a node's handle survives
1066
+ * activate↔deactivate and is reused on reactivation; only a rewire swaps it).
1067
+ */
1068
+ unregister(handle) {
1069
+ this.pools[handle.poolId].unregister(handle.handleId);
1070
+ this._stats.delete(statKey(handle));
1071
+ }
1072
+ /** Uniform sync-void invoke (R-sync-core / R-dispatch-all). */
1073
+ invoke(handle, ctx) {
1074
+ if (!this._recording) {
1075
+ this.pools[handle.poolId].invoke(handle.handleId, ctx);
1076
+ return;
1077
+ }
1078
+ this._totalInvokes++;
1079
+ const t0 = performance.now();
1080
+ try {
1081
+ this.pools[handle.poolId].invoke(handle.handleId, ctx);
1082
+ } finally {
1083
+ const dur = (performance.now() - t0) * 1e6;
1084
+ const key = statKey(handle);
1085
+ const s = this._stats.get(key) ?? {
1086
+ invokes: 0,
1087
+ totalDurationNs: 0,
1088
+ lastDurationNs: 0
1089
+ };
1090
+ s.invokes++;
1091
+ s.lastDurationNs = dur;
1092
+ s.totalDurationNs += dur;
1093
+ this._stats.set(key, s);
1094
+ }
1095
+ }
1096
+ poolKind(poolId) {
1097
+ return this.pools[poolId].kind;
1098
+ }
1099
+ };
1100
+ var defaultDispatcher = new Dispatcher();
1101
+
1102
+ // src/graph/environment.ts
1103
+ var EnvironmentDrivers = class _EnvironmentDrivers {
1104
+ process;
1105
+ http;
1106
+ sse;
1107
+ websocket;
1108
+ webhook;
1109
+ constructor(init = {}) {
1110
+ this.process = init.process;
1111
+ this.http = init.http;
1112
+ this.sse = init.sse;
1113
+ this.websocket = init.websocket;
1114
+ this.webhook = init.webhook;
1115
+ Object.freeze(this);
1116
+ }
1117
+ static empty() {
1118
+ return EMPTY_ENVIRONMENT;
1119
+ }
1120
+ withProcess(driver) {
1121
+ return new _EnvironmentDrivers({ ...this, process: driver });
1122
+ }
1123
+ withHttp(driver) {
1124
+ return new _EnvironmentDrivers({ ...this, http: driver });
1125
+ }
1126
+ withSse(driver) {
1127
+ return new _EnvironmentDrivers({ ...this, sse: driver });
1128
+ }
1129
+ withWebSocket(driver) {
1130
+ return new _EnvironmentDrivers({ ...this, websocket: driver });
1131
+ }
1132
+ withWebhook(driver) {
1133
+ return new _EnvironmentDrivers({ ...this, webhook: driver });
1134
+ }
1135
+ processDriver() {
1136
+ return this.process;
1137
+ }
1138
+ httpDriver() {
1139
+ return this.http;
1140
+ }
1141
+ sseDriver() {
1142
+ return this.sse;
1143
+ }
1144
+ webSocketDriver() {
1145
+ return this.websocket;
1146
+ }
1147
+ webhookDriver() {
1148
+ return this.webhook;
1149
+ }
1150
+ };
1151
+ var EMPTY_ENVIRONMENT = new EnvironmentDrivers();
1152
+
1153
+ // src/node/core.ts
1154
+ var NodeCore = class {
1155
+ nextId = 0;
1156
+ slots = [];
1157
+ values = [];
1158
+ waves = [];
1159
+ controls = [];
1160
+ lifecycles = [];
1161
+ depStates = [];
1162
+ privateStates = [];
1163
+ hooks = [];
1164
+ syncCtxs = [];
1165
+ versionStates = [];
1166
+ boundary = { queue: [], head: 0 };
1167
+ createSlot(slot, state) {
1168
+ const id = this.nextId++;
1169
+ const full = { ...slot, id };
1170
+ this.slots[id] = full;
1171
+ this.depStates[id] = state.dep;
1172
+ this.lifecycles[id] = state.lifecycle;
1173
+ this.values[id] = state.value;
1174
+ this.waves[id] = state.wave;
1175
+ this.controls[id] = state.control;
1176
+ this.privateStates[id] = state.privateState;
1177
+ this.hooks[id] = state.hooks;
1178
+ this.syncCtxs[id] = state.syncCtx;
1179
+ this.versionStates[id] = state.version;
1180
+ return { id, slot: full };
1181
+ }
1182
+ get(id) {
1183
+ const slot = this.slots[id];
1184
+ if (slot === void 0) throw new Error("NodeCore: unknown node slot");
1185
+ return slot;
1186
+ }
1187
+ getValue(id) {
1188
+ const value = this.values[id];
1189
+ if (value === void 0) throw new Error("NodeCore: unknown node value state");
1190
+ return value;
1191
+ }
1192
+ getWave(id) {
1193
+ const wave = this.waves[id];
1194
+ if (wave === void 0) throw new Error("NodeCore: unknown node wave state");
1195
+ return wave;
1196
+ }
1197
+ getControl(id) {
1198
+ const control = this.controls[id];
1199
+ if (control === void 0) throw new Error("NodeCore: unknown node control state");
1200
+ return control;
1201
+ }
1202
+ getLifecycle(id) {
1203
+ const lifecycle = this.lifecycles[id];
1204
+ if (lifecycle === void 0) throw new Error("NodeCore: unknown node lifecycle state");
1205
+ return lifecycle;
1206
+ }
1207
+ getDep(id) {
1208
+ const dep = this.depStates[id];
1209
+ if (dep === void 0) throw new Error("NodeCore: unknown node dep state");
1210
+ return dep;
1211
+ }
1212
+ getPrivateState(id) {
1213
+ const state = this.privateStates[id];
1214
+ if (state === void 0) throw new Error("NodeCore: unknown node private state");
1215
+ return state;
1216
+ }
1217
+ getHooks(id) {
1218
+ const hooks = this.hooks[id];
1219
+ if (hooks === void 0) throw new Error("NodeCore: unknown node cleanup hooks");
1220
+ return hooks;
1221
+ }
1222
+ getSyncCtx(id) {
1223
+ const state = this.syncCtxs[id];
1224
+ if (state === void 0) throw new Error("NodeCore: unknown node ctx state");
1225
+ return state;
1226
+ }
1227
+ getVersion(id) {
1228
+ const state = this.versionStates[id];
1229
+ if (state === void 0) throw new Error("NodeCore: unknown node version state");
1230
+ return state;
1231
+ }
1232
+ /** @internal D122: release graph-owned ephemeral node runtime state from core retention. */
1233
+ releaseSlot(id) {
1234
+ this.slots[id] = void 0;
1235
+ this.depStates[id] = void 0;
1236
+ this.lifecycles[id] = void 0;
1237
+ this.values[id] = void 0;
1238
+ this.waves[id] = void 0;
1239
+ this.controls[id] = void 0;
1240
+ this.privateStates[id] = void 0;
1241
+ this.hooks[id] = void 0;
1242
+ this.syncCtxs[id] = void 0;
1243
+ this.versionStates[id] = void 0;
1244
+ }
1245
+ /** @internal B49: graph-local deferred-boundary queue (rewireNext/upNext/batch-after-commit). */
1246
+ enqueueBoundaryTask(task) {
1247
+ this.boundary.queue.push(task);
1248
+ }
1249
+ /** @internal */
1250
+ hasBoundaryTasks() {
1251
+ return this.boundary.head < this.boundary.queue.length;
1252
+ }
1253
+ /** @internal */
1254
+ boundaryTaskCount() {
1255
+ return this.boundary.queue.length - this.boundary.head;
1256
+ }
1257
+ /** @internal */
1258
+ shiftBoundaryTask() {
1259
+ if (!this.hasBoundaryTasks()) {
1260
+ this.boundary.queue = [];
1261
+ this.boundary.head = 0;
1262
+ return void 0;
1263
+ }
1264
+ const task = this.boundary.queue[this.boundary.head++];
1265
+ if (!this.hasBoundaryTasks()) {
1266
+ this.boundary.queue = [];
1267
+ this.boundary.head = 0;
1268
+ }
1269
+ return task;
1270
+ }
1271
+ /** @internal Put a not-yet-ready task back at this core's FIFO head. */
1272
+ unshiftBoundaryTask(task) {
1273
+ const remaining = this.boundary.queue.slice(this.boundary.head);
1274
+ this.boundary.queue = [task, ...remaining];
1275
+ this.boundary.head = 0;
1276
+ }
1277
+ /** @internal D110: discard all pending tasks caused by an uncommitted batch. */
1278
+ dropBoundaryTasksForBatch(batchToken) {
1279
+ const remaining = this.boundary.queue.slice(this.boundary.head).filter((task) => task.batchToken !== batchToken);
1280
+ this.boundary.queue = remaining;
1281
+ this.boundary.head = 0;
1282
+ }
1283
+ };
1284
+ function makeDepBookkeeping(depCount) {
1285
+ return {
1286
+ batch: new Array(depCount).fill(null),
1287
+ waveData: Array.from({ length: depCount }, () => []),
1288
+ waveTokens: new Array(depCount).fill(void 0),
1289
+ prev: new Array(depCount).fill(SENTINEL),
1290
+ hasData: new Array(depCount).fill(false),
1291
+ dirty: new Array(depCount).fill(false),
1292
+ tier: new Array(depCount).fill(0),
1293
+ terminal: new Array(depCount).fill(void 0),
1294
+ terminalInput: new Array(depCount).fill(void 0),
1295
+ unsubs: [],
1296
+ idxBoxes: []
1297
+ };
1298
+ }
1299
+
1300
+ // src/node/protocol-guards.ts
1301
+ function terminalView(t) {
1302
+ return t === void 0 ? false : t;
1303
+ }
1304
+ function normalizePullDemand(demand) {
1305
+ if (typeof demand !== "object" || demand === null || Array.isArray(demand)) {
1306
+ throw new Error("ctx.up: PULL requires { pullId, params? } demand payload (D269)");
1307
+ }
1308
+ const pullId = demand.pullId;
1309
+ if (typeof pullId !== "string" && typeof pullId !== "symbol") {
1310
+ throw new Error("ctx.up: PULL demand requires a string or symbol pullId (D269)");
1311
+ }
1312
+ const params = demand.params;
1313
+ return params === void 0 ? { pullId } : { pullId, params };
1314
+ }
1315
+ function validateDownPayloads(msgs) {
1316
+ for (const m of msgs) {
1317
+ if (m[0] === "DATA" && m[1] === void 0) {
1318
+ throw new Error("down: DATA requires a non-SENTINEL payload (R-data-payload)");
1319
+ }
1320
+ if (m[0] === "ERROR" && isInvalidErrorPayload(m[1])) {
1321
+ throw new Error("down: ERROR requires a non-SENTINEL, non-boolean payload (R-data-payload)");
1322
+ }
1323
+ }
1324
+ }
1325
+
1326
+ // src/node/runtime-accessors.ts
1327
+ var constructingCore;
1328
+ var constructingEnvironment;
1329
+ var ownerTokens = /* @__PURE__ */ new WeakMap();
1330
+ var topologyDepsChangedObservers = /* @__PURE__ */ new WeakMap();
1331
+ var checkpointReaders = /* @__PURE__ */ new WeakMap();
1332
+ var restoreWriters = /* @__PURE__ */ new WeakMap();
1333
+ var runtimeReleasers = /* @__PURE__ */ new WeakMap();
1334
+ var runtimeQuiescenceReaders = /* @__PURE__ */ new WeakMap();
1335
+ var subscriberCountReaders = /* @__PURE__ */ new WeakMap();
1336
+ var activationReaders = /* @__PURE__ */ new WeakMap();
1337
+ var releasedNodes = /* @__PURE__ */ new WeakSet();
1338
+ function withNodeCore(core, create) {
1339
+ const prev = constructingCore;
1340
+ constructingCore = core;
1341
+ try {
1342
+ return create();
1343
+ } finally {
1344
+ constructingCore = prev;
1345
+ }
1346
+ }
1347
+ function takeConstructingNodeCore() {
1348
+ const core = constructingCore;
1349
+ constructingCore = void 0;
1350
+ return core;
1351
+ }
1352
+ function withEnvironmentDrivers(environment, create) {
1353
+ const prev = constructingEnvironment;
1354
+ constructingEnvironment = environment;
1355
+ try {
1356
+ return create();
1357
+ } finally {
1358
+ constructingEnvironment = prev;
1359
+ }
1360
+ }
1361
+ function takeConstructingEnvironmentDrivers() {
1362
+ const environment = constructingEnvironment;
1363
+ constructingEnvironment = void 0;
1364
+ return environment;
1365
+ }
1366
+ function getNodeOwner(n) {
1367
+ return ownerTokens.get(n);
1368
+ }
1369
+ function notifyTopologyDepsChanged(node, prevDeps, deps) {
1370
+ topologyDepsChangedObservers.get(node)?.(node, prevDeps, deps);
1371
+ }
1372
+
1373
+ // src/node/node-context-runtime.ts
1374
+ function nodeBuildCtx(self) {
1375
+ const kind = self._slot.handle ? self._slot.dispatcher.poolKind(self._slot.handle.poolId) : "sync";
1376
+ if (kind === "sync") {
1377
+ if (self._syncCtx === null) self._syncCtx = self._makeCtx();
1378
+ self._refreshCtx(self._syncCtx);
1379
+ return self._syncCtx;
1380
+ }
1381
+ return self._makeCtx({
1382
+ waveData: self._dep.waveData.map((waves) => waves.map((w) => [...w])),
1383
+ terminal: self._dep.terminalInput.map(terminalView),
1384
+ latest: [...self._dep.prev]
1385
+ });
1386
+ }
1387
+ function nodeMakeCtx(self, snapshot) {
1388
+ const ctx = {
1389
+ // Wave-owner boundary (D47): a SYNC fn's emit nests under the public entry that drove
1390
+ // it (cheap inc/dec, no early drain); an ASYNC-pool fn re-enters here from its stashed
1391
+ // ctx at depth 0, so this is the boundary that drains any rewireNext it issued.
1392
+ up: (msgs, towardDep) => {
1393
+ if (self._released) return;
1394
+ enterWave();
1395
+ try {
1396
+ self._up(msgs, towardDep);
1397
+ } finally {
1398
+ exitWave();
1399
+ }
1400
+ },
1401
+ down: (msgs) => {
1402
+ if (self._released) return;
1403
+ enterWave();
1404
+ try {
1405
+ self._down(msgs);
1406
+ } finally {
1407
+ exitWave();
1408
+ }
1409
+ },
1410
+ waveData: snapshot?.waveData ?? self._dep.waveData,
1411
+ terminal: snapshot?.terminal ?? self._dep.terminalInput.map(terminalView),
1412
+ state: self._makeState(),
1413
+ onDeactivation: (fn) => {
1414
+ if (self._released) return;
1415
+ self._hooks.onDeactivation.push(fn);
1416
+ },
1417
+ onInvalidate: (fn) => {
1418
+ if (self._released) return;
1419
+ self._hooks.onInvalidate.push(fn);
1420
+ },
1421
+ environment: () => self._slot.environment,
1422
+ // R-rewire-deferred (D47): defer a self-dep-set mutation to the committed boundary.
1423
+ rewireNext: {
1424
+ subscribeDep: (dep, fn) => self._requestRewireNext({ kind: "add", dep, fn }),
1425
+ unsubscribeDep: (dep, fn) => self._requestRewireNext({ kind: "remove", dep, fn }),
1426
+ replaceDeps: (deps, fn) => self._requestRewireNext({ kind: "set", deps, fn })
1427
+ },
1428
+ // R-up-routing / R-pull (D269): deferred up — route a control/demand wave (e.g. PULL)
1429
+ // up the declared cone at the committed boundary. The SELF-demand path: an
1430
+ // immediate ctx.up whose delivery loops back re-enters this fn (D37 / R-reentrancy).
1431
+ upNext: (msgs, towardDep) => self._requestUpNext(msgs, towardDep),
1432
+ ...self._control.activePull === void 0 ? {} : { pull: self._control.activePull },
1433
+ [CTX_DEP_CACHE]: { latest: snapshot?.latest ?? self._dep.prev },
1434
+ [CTX_NODE_BINDING]: {
1435
+ dispatcher: self._slot.dispatcher,
1436
+ create: (factory) => withEnvironmentDrivers(self._slot.environment, () => withNodeCore(self._core, factory))
1437
+ }
1438
+ };
1439
+ if (self._slot.dynamic) {
1440
+ ctx.track = (i) => ctx[CTX_DEP_CACHE]?.latest[i];
1441
+ }
1442
+ return ctx;
1443
+ }
1444
+ function nodeRefreshCtx(self, ctx) {
1445
+ ctx.waveData = self._dep.waveData;
1446
+ ctx.terminal = self._dep.terminalInput.map(terminalView);
1447
+ if (self._control.activePull === void 0) {
1448
+ delete ctx.pull;
1449
+ } else {
1450
+ ctx.pull = self._control.activePull;
1451
+ }
1452
+ ctx[CTX_DEP_CACHE] = { latest: self._dep.prev };
1453
+ }
1454
+ function nodeMakeState(self) {
1455
+ return {
1456
+ get: () => self._privateState.value,
1457
+ set: (v) => {
1458
+ self._privateState.value = v;
1459
+ },
1460
+ persist: (on = true) => {
1461
+ self._privateState.persist = on;
1462
+ }
1463
+ };
1464
+ }
1465
+
1466
+ // src/node/node-input-runtime.ts
1467
+ function nodeRecordDepProjection(self, idx, delivery) {
1468
+ const token = delivery?.wave ?? {};
1469
+ if (self._dep.waveTokens[idx] !== token) {
1470
+ self._dep.waveData[idx].push([]);
1471
+ self._dep.waveTokens[idx] = token;
1472
+ }
1473
+ return self._dep.waveData[idx][self._dep.waveData[idx].length - 1];
1474
+ }
1475
+ function nodeDepProjectionHasData(self, idx) {
1476
+ const projection = self._dep.waveData[idx][self._dep.waveData[idx].length - 1];
1477
+ return projection?.some((v) => v !== SENTINEL) ?? false;
1478
+ }
1479
+ function nodeReceiveFromDep(self, idx, msg, delivery) {
1480
+ if (self._released) return;
1481
+ const t = msg[0];
1482
+ if (t === "START") return;
1483
+ const isLastInDeliveredWave = delivery?.last ?? true;
1484
+ if (self._value.terminal !== void 0) {
1485
+ if (t === "TEARDOWN") self._down([["TEARDOWN"]]);
1486
+ return;
1487
+ }
1488
+ if (t === "INVALIDATE") {
1489
+ const projection = self._recordDepProjection(idx, delivery);
1490
+ projection.push(SENTINEL);
1491
+ if (projection.some((v) => v !== SENTINEL) && isLastInDeliveredWave) self._maybeRun();
1492
+ self._dep.prev[idx] = SENTINEL;
1493
+ self._dep.hasData[idx] = false;
1494
+ self._dep.batch[idx] = null;
1495
+ if (self._dep.dirty[idx]) {
1496
+ self._dep.dirty[idx] = false;
1497
+ self._wave.pending--;
1498
+ }
1499
+ if (self._control.pausedDepWaveOccurred && self._dep.batch.every((b) => b === null)) {
1500
+ self._control.pausedDepWaveOccurred = false;
1501
+ }
1502
+ const hadData = self._value.hasData;
1503
+ self._invalidate();
1504
+ if (self._wave.pending === 0 && self._wave.emittedDirtyThisWave) {
1505
+ if (!hadData) self._down([["RESOLVED"]]);
1506
+ else self._wave.emittedDirtyThisWave = false;
1507
+ }
1508
+ self._fireOwedDemandIfReady();
1509
+ return;
1510
+ }
1511
+ if (isTerminal(t)) {
1512
+ const isError = t === "ERROR";
1513
+ const errPayload = isError ? msg[1] : void 0;
1514
+ self._dep.terminal[idx] = isError ? errPayload : true;
1515
+ self._dep.terminalInput[idx] = isError ? errPayload : true;
1516
+ self._releaseDepDirty(idx);
1517
+ const ranValueBeforeTerminal = self._depProjectionHasData(idx) && isLastInDeliveredWave;
1518
+ if (ranValueBeforeTerminal) self._maybeRun();
1519
+ if (isError && self._slot.errorWhenDepsError) {
1520
+ self._down([["ERROR", errPayload]]);
1521
+ } else if (self._slot.terminalAsRealInput) {
1522
+ if (ranValueBeforeTerminal) {
1523
+ self._fireOwedDemandIfReady();
1524
+ return;
1525
+ }
1526
+ self._maybeRun();
1527
+ } else if (self._slot.completeWhenDepsComplete && self._allDepsTerminal()) {
1528
+ self._down([["COMPLETE"]]);
1529
+ } else {
1530
+ self._settleAfterAbsorbedTerminal();
1531
+ }
1532
+ self._fireOwedDemandIfReady();
1533
+ return;
1534
+ }
1535
+ if (t === "TEARDOWN") {
1536
+ self._down([["TEARDOWN"]]);
1537
+ return;
1538
+ }
1539
+ if (t === "DIRTY") {
1540
+ if (!self._dep.dirty[idx]) {
1541
+ self._dep.dirty[idx] = true;
1542
+ self._wave.pending++;
1543
+ self._dep.tier[idx] = 2;
1544
+ self._markDirty();
1545
+ }
1546
+ return;
1547
+ }
1548
+ if (t === "DATA") {
1549
+ const v = msg[1];
1550
+ self._recordDepProjection(idx, delivery).push(v);
1551
+ const b = self._dep.batch[idx];
1552
+ if (b === null) self._dep.batch[idx] = [v];
1553
+ else b.push(v);
1554
+ self._dep.prev[idx] = v;
1555
+ self._dep.hasData[idx] = true;
1556
+ self._dep.tier[idx] = 3;
1557
+ if (self._dep.dirty[idx]) {
1558
+ self._dep.dirty[idx] = false;
1559
+ self._wave.pending--;
1560
+ }
1561
+ if (isLastInDeliveredWave) self._maybeRun();
1562
+ self._fireOwedDemandIfReady();
1563
+ return;
1564
+ }
1565
+ if (t === "RESOLVED") {
1566
+ self._recordDepProjection(idx, delivery);
1567
+ self._dep.tier[idx] = 3;
1568
+ if (self._dep.dirty[idx]) {
1569
+ self._dep.dirty[idx] = false;
1570
+ self._wave.pending--;
1571
+ }
1572
+ if (isLastInDeliveredWave) self._maybeRun();
1573
+ self._fireOwedDemandIfReady();
1574
+ return;
1575
+ }
1576
+ }
1577
+ function nodeReleaseDepDirty(self, idx) {
1578
+ if (self._dep.dirty[idx]) {
1579
+ self._dep.dirty[idx] = false;
1580
+ self._wave.pending--;
1581
+ }
1582
+ }
1583
+ function nodeSettleAfterAbsorbedTerminal(self) {
1584
+ if (self._wave.pending !== 0 || !self._wave.emittedDirtyThisWave) return;
1585
+ const sawData = self._dep.batch.some((b) => b !== null && b.length > 0);
1586
+ if (sawData) self._maybeRun();
1587
+ if (self._wave.emittedDirtyThisWave) self._down([["RESOLVED"]]);
1588
+ }
1589
+ function nodeMarkDirty(self) {
1590
+ self._value.status = "dirty";
1591
+ if (self._isPullQuiet()) return;
1592
+ if (!self._wave.emittedDirtyThisWave) {
1593
+ self._wave.emittedDirtyThisWave = true;
1594
+ self._emitToSubs(["DIRTY"]);
1595
+ }
1596
+ }
1597
+ function nodeMaybeRun(self) {
1598
+ if (self._wave.inDepMutation) {
1599
+ self._wave.rewireRunPending = true;
1600
+ return;
1601
+ }
1602
+ if (self._slot.pausable === true && (self._isPaused() || self._isPullQuiet())) {
1603
+ self._control.pausedDepWaveOccurred = true;
1604
+ return;
1605
+ }
1606
+ self._tryRun();
1607
+ }
1608
+ function nodeSettleRewire(self) {
1609
+ if (self._slot.pausable === true && self._isPaused()) {
1610
+ self._control.pausedDepWaveOccurred = true;
1611
+ return;
1612
+ }
1613
+ if (self._wave.pending > 0) return;
1614
+ if (self._slot.handle === null) {
1615
+ self._passthroughEmit();
1616
+ return;
1617
+ }
1618
+ if (!self._wave.hasCalledFnOnce && !(self._slot.partial || self._allDepsSettled())) return;
1619
+ self._markDirty();
1620
+ self._runWave();
1621
+ }
1622
+ function nodeTryRun(self) {
1623
+ if (self._wave.pending > 0) return;
1624
+ if (self._slot.handle === null) {
1625
+ self._passthroughEmit();
1626
+ return;
1627
+ }
1628
+ if (!self._wave.hasCalledFnOnce) {
1629
+ if (self._slot.partial || self._allDepsSettled()) self._runWave();
1630
+ return;
1631
+ }
1632
+ self._runWave();
1633
+ }
1634
+ function nodeAllDepsSettled(self) {
1635
+ for (let i = 0; i < self._slot.deps.length; i++) {
1636
+ if (self._dep.hasData[i]) continue;
1637
+ if (self._slot.terminalAsRealInput && self._dep.terminal[i] !== void 0) continue;
1638
+ return false;
1639
+ }
1640
+ return true;
1641
+ }
1642
+ function nodePassthroughEmit(self) {
1643
+ const b = self._dep.batch[0];
1644
+ if (b !== null && b.length > 0) {
1645
+ self._down([["DATA", b[b.length - 1]]]);
1646
+ } else if (self._wave.emittedDirtyThisWave) {
1647
+ self._down([["RESOLVED"]]);
1648
+ }
1649
+ self._dep.batch[0] = null;
1650
+ self._wave.emittedDirtyThisWave = false;
1651
+ }
1652
+ function nodeRunWave(self) {
1653
+ if (self._wave.insideRunWave)
1654
+ throw new Error(
1655
+ "synchronous feedback cycle: node fn re-entered its own wave (R-reentrancy / D37)"
1656
+ );
1657
+ self._wave.hasCalledFnOnce = true;
1658
+ self._hooks.onInvalidate = [];
1659
+ self._hooks.onDeactivation = [];
1660
+ const ctx = self._buildCtx();
1661
+ const wasDirty = self._wave.emittedDirtyThisWave;
1662
+ self._wave.emittedSettleThisWave = false;
1663
+ self._wave.insideRunWave = true;
1664
+ try {
1665
+ self._slot.dispatcher.invoke(self._slot.handle, ctx);
1666
+ } finally {
1667
+ self._wave.insideRunWave = false;
1668
+ }
1669
+ if (wasDirty && !self._wave.emittedSettleThisWave && self._value.terminal === void 0 && !self._isAsyncPool()) {
1670
+ self._down([["RESOLVED"]]);
1671
+ }
1672
+ for (let i = 0; i < self._dep.batch.length; i++) {
1673
+ self._dep.batch[i] = null;
1674
+ self._dep.waveData[i] = [];
1675
+ self._dep.waveTokens[i] = void 0;
1676
+ self._dep.terminalInput[i] = void 0;
1677
+ }
1678
+ self._wave.emittedDirtyThisWave = false;
1679
+ }
1680
+
1681
+ // src/node/node-runtime-host.ts
1682
+ function nodeRuntimeHost(node) {
1683
+ return node;
1684
+ }
1685
+
1686
+ // src/node/node-lifecycle-runtime.ts
1687
+ function nodeActivate(self) {
1688
+ self._lifecycle.activated = true;
1689
+ const seedRestoredDeps = self._restoredActivationPending;
1690
+ self._restoredActivationPending = false;
1691
+ self._dep.unsubs = new Array(self._slot.deps.length);
1692
+ self._dep.idxBoxes = new Array(self._slot.deps.length);
1693
+ for (const dep of self._slot.deps) self._subscribeDepAt(dep, { seedRestored: seedRestoredDeps });
1694
+ if (self._slot.deps.length === 0 && self._slot.handle !== null && !self._wave.hasCalledFnOnce) {
1695
+ self._runWave();
1696
+ }
1697
+ }
1698
+ function nodeSubscribeDepAt(self, depNode, opts = {}) {
1699
+ const idx0 = self._slot.deps.indexOf(depNode);
1700
+ const box = { v: idx0 };
1701
+ let ignoreInitialPush = opts.seedRestored === true;
1702
+ if (ignoreInitialPush && idx0 !== -1) {
1703
+ self._seedRestoredDepAt(idx0, depNode);
1704
+ const dep = nodeRuntimeHost(depNode);
1705
+ if (dep._value.terminal !== void 0 && !dep._slot.resubscribable) {
1706
+ self._dep.unsubs[idx0] = () => {
1707
+ };
1708
+ self._dep.idxBoxes[idx0] = box;
1709
+ return;
1710
+ }
1711
+ }
1712
+ const unsub = depNode.subscribe((msg, delivery) => {
1713
+ if (ignoreInitialPush && delivery === void 0) return;
1714
+ if (ignoreInitialPush) ignoreInitialPush = false;
1715
+ if (box.v === -1) return;
1716
+ self._receiveFromDep(box.v, msg, delivery);
1717
+ });
1718
+ if (ignoreInitialPush && idx0 !== -1 && box.v !== -1) self._seedRestoredDepAt(idx0, depNode);
1719
+ ignoreInitialPush = false;
1720
+ if (idx0 !== -1) {
1721
+ self._dep.unsubs[idx0] = unsub;
1722
+ self._dep.idxBoxes[idx0] = box;
1723
+ }
1724
+ }
1725
+ function nodeSeedRestoredDepAt(self, idx, depNode) {
1726
+ const dep = nodeRuntimeHost(depNode);
1727
+ const seedData = dep._value.hasData && !dep._slot.pull;
1728
+ self._dep.batch[idx] = null;
1729
+ self._dep.waveData[idx] = [];
1730
+ self._dep.waveTokens[idx] = void 0;
1731
+ self._dep.prev[idx] = seedData ? dep._value.cache : SENTINEL;
1732
+ self._dep.hasData[idx] = seedData;
1733
+ self._dep.dirty[idx] = false;
1734
+ self._dep.tier[idx] = seedData ? 3 : 0;
1735
+ self._dep.terminal[idx] = dep._value.terminal;
1736
+ self._dep.terminalInput[idx] = void 0;
1737
+ }
1738
+ function nodeDeactivate(self) {
1739
+ self._lifecycle.activated = false;
1740
+ for (const u of self._dep.unsubs) if (u) u();
1741
+ self._dep.unsubs = [];
1742
+ self._dep.idxBoxes = [];
1743
+ for (const fn of self._hooks.onDeactivation) fn();
1744
+ self._hooks.onDeactivation = [];
1745
+ self._hooks.onInvalidate = [];
1746
+ const isCompute = self._slot.handle !== null || self._slot.deps.length > 0;
1747
+ if (isCompute) {
1748
+ self._value.cache = SENTINEL;
1749
+ self._value.hasData = false;
1750
+ self._value.status = "sentinel";
1751
+ }
1752
+ self._resetDepState();
1753
+ self._wave.hasCalledFnOnce = false;
1754
+ self._control.pauseLockset.clear();
1755
+ self._control.pauseBuffer = [];
1756
+ self._control.pausedDepWaveOccurred = false;
1757
+ self._control.demandOwed = void 0;
1758
+ self._control.activePull = void 0;
1759
+ self._control.pullDirtyOwed = false;
1760
+ self._value.replayRing = [];
1761
+ if (!self._privateState.persist) self._privateState.value = SENTINEL;
1762
+ }
1763
+ function nodeSubscriberCount(self) {
1764
+ return self._lifecycle.subscribers.size;
1765
+ }
1766
+ function nodeIsRuntimeQuiescentForRelease(self) {
1767
+ return !self._released && self._value.status !== "dirty" && self._value.status !== "pending" && self._wave.pending === 0 && !self._wave.insideRunWave && !self._wave.inDepMutation && !self._wave.rewireRunPending && !self._wave.batchDirtyOwed && self._dep.dirty.every((dirty) => !dirty) && self._control.pauseBuffer.length === 0 && !self._control.pausedDepWaveOccurred && self._control.demandOwed === void 0 && self._control.activePull === void 0 && !self._control.inDeliverDemand && self._control.pauseLockset.size === 0;
1768
+ }
1769
+ function nodeReleaseRuntime(self) {
1770
+ if (self._released) return;
1771
+ self._released = true;
1772
+ const node = self;
1773
+ releasedNodes.add(node);
1774
+ let releaseError;
1775
+ const recordReleaseError = (error) => {
1776
+ if (releaseError === void 0) releaseError = error;
1777
+ };
1778
+ self._lifecycle.activated = false;
1779
+ for (const u of self._dep.unsubs) {
1780
+ try {
1781
+ u();
1782
+ } catch (error) {
1783
+ recordReleaseError(error);
1784
+ }
1785
+ }
1786
+ for (const fn of self._hooks.onDeactivation) {
1787
+ try {
1788
+ fn();
1789
+ } catch (error) {
1790
+ recordReleaseError(error);
1791
+ }
1792
+ }
1793
+ self._dep.unsubs = [];
1794
+ self._dep.idxBoxes = [];
1795
+ self._lifecycle.subscribers.clear();
1796
+ if (self._slot.handle !== null) {
1797
+ self._slot.dispatcher.unregister(self._slot.handle);
1798
+ self._slot.handle = null;
1799
+ }
1800
+ self._slot.deps = [];
1801
+ self._dep.batch = [];
1802
+ self._dep.waveData = [];
1803
+ self._dep.waveTokens = [];
1804
+ self._dep.prev = [];
1805
+ self._dep.hasData = [];
1806
+ self._dep.dirty = [];
1807
+ self._dep.tier = [];
1808
+ self._dep.terminal = [];
1809
+ self._dep.terminalInput = [];
1810
+ self._value.cache = SENTINEL;
1811
+ self._value.hasData = false;
1812
+ self._value.status = "sentinel";
1813
+ self._value.terminal = void 0;
1814
+ self._value.replayRing = [];
1815
+ self._privateState.value = SENTINEL;
1816
+ self._privateState.persist = false;
1817
+ self._syncCtx = null;
1818
+ self._resetDepState();
1819
+ self._hooks.onDeactivation = [];
1820
+ self._hooks.onInvalidate = [];
1821
+ self._control.pauseLockset.clear();
1822
+ self._control.pauseBuffer = [];
1823
+ self._control.pausedDepWaveOccurred = false;
1824
+ self._control.demandOwed = void 0;
1825
+ self._control.activePull = void 0;
1826
+ self._control.pullDirtyOwed = false;
1827
+ self._restoredActivationPending = false;
1828
+ checkpointReaders.delete(node);
1829
+ restoreWriters.delete(node);
1830
+ runtimeReleasers.delete(node);
1831
+ runtimeQuiescenceReaders.delete(node);
1832
+ subscriberCountReaders.delete(node);
1833
+ activationReaders.delete(node);
1834
+ ownerTokens.delete(node);
1835
+ topologyDepsChangedObservers.delete(node);
1836
+ self._core.releaseSlot(self._id);
1837
+ if (releaseError !== void 0) throw releaseError;
1838
+ }
1839
+ function nodeResetDepState(self) {
1840
+ const n = self._slot.deps.length;
1841
+ for (let i = 0; i < n; i++) {
1842
+ self._dep.batch[i] = null;
1843
+ self._dep.waveData[i] = [];
1844
+ self._dep.waveTokens[i] = void 0;
1845
+ self._dep.prev[i] = SENTINEL;
1846
+ self._dep.hasData[i] = false;
1847
+ self._dep.dirty[i] = false;
1848
+ self._dep.tier[i] = 0;
1849
+ self._dep.terminal[i] = void 0;
1850
+ self._dep.terminalInput[i] = void 0;
1851
+ }
1852
+ self._wave.pending = 0;
1853
+ self._wave.emittedDirtyThisWave = false;
1854
+ }
1855
+
1856
+ // src/batch/batch.ts
1857
+ var active = null;
1858
+ var boundaryOwner = null;
1859
+ function currentBatch() {
1860
+ return active !== null;
1861
+ }
1862
+ function currentBoundaryBatchToken() {
1863
+ return active ?? boundaryOwner ?? void 0;
1864
+ }
1865
+ function deferToBatch(target, tier3Wave) {
1866
+ if (active === null) return false;
1867
+ if (!active.deferred.has(target)) active.order.push(target);
1868
+ active.deferred.set(target, tier3Wave);
1869
+ return true;
1870
+ }
1871
+ function deferAfterBatchForTarget(target, fn) {
1872
+ if (active === null || !active.deferred.has(target)) return false;
1873
+ const owner = active;
1874
+ target.__deferBoundary(() => {
1875
+ if (owner.committed) fn();
1876
+ }, owner);
1877
+ return true;
1878
+ }
1879
+
1880
+ // src/json/codec.ts
1881
+ var JS_MIN_NORMAL_NUMBER = 2 ** -1022;
1882
+ function assertStableJsonNumber(value, path) {
1883
+ if (!Number.isFinite(value)) {
1884
+ throw new TypeError(`stableJsonString: non-finite number at ${path}`);
1885
+ }
1886
+ }
1887
+ function assertStrictJsonNumber(value, path) {
1888
+ assertStableJsonNumber(value, path);
1889
+ if (Object.is(value, -0)) {
1890
+ throw new TypeError(`stableJsonString: non-canonical number at ${path}`);
1891
+ }
1892
+ const abs = Math.abs(value);
1893
+ if (abs > 0 && abs < JS_MIN_NORMAL_NUMBER) {
1894
+ throw new TypeError(`stableJsonString: subnormal number at ${path}`);
1895
+ }
1896
+ if (Number.isInteger(value) && !Number.isSafeInteger(value)) {
1897
+ throw new TypeError(`stableJsonString: integer outside safe range at ${path}`);
1898
+ }
1899
+ }
1900
+ function sortedJsonValue(value, seen = /* @__PURE__ */ new Set(), path = "$", strictNumbers = false) {
1901
+ if (value === null) return null;
1902
+ if (typeof value === "string" || typeof value === "boolean") return value;
1903
+ if (typeof value === "number") {
1904
+ if (strictNumbers) assertStrictJsonNumber(value, path);
1905
+ else assertStableJsonNumber(value, path);
1906
+ return value;
1907
+ }
1908
+ if (typeof value !== "object") {
1909
+ throw new TypeError(`stableJsonString: value at ${path} is not JSON-encodable`);
1910
+ }
1911
+ if (seen.has(value)) throw new TypeError(`stableJsonString: circular reference at ${path}`);
1912
+ const proto = Object.getPrototypeOf(value);
1913
+ if (!Array.isArray(value) && proto !== Object.prototype && proto !== null) {
1914
+ throw new TypeError(`stableJsonString: non-plain object at ${path}`);
1915
+ }
1916
+ seen.add(value);
1917
+ try {
1918
+ if (Array.isArray(value)) {
1919
+ if (Object.getOwnPropertySymbols(value).length > 0) {
1920
+ throw new TypeError(`stableJsonString: symbol-keyed properties at ${path}`);
1921
+ }
1922
+ for (const key of Object.getOwnPropertyNames(value)) {
1923
+ const isIndex = /^(0|[1-9]\d*)$/.test(key) && Number.isSafeInteger(Number(key)) && Number(key) < value.length;
1924
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
1925
+ if (descriptor !== void 0 && ("get" in descriptor || "set" in descriptor)) {
1926
+ throw new TypeError(`stableJsonString: accessor property at ${path}.${key}`);
1927
+ }
1928
+ if (key !== "length" && !isIndex) {
1929
+ throw new TypeError(`stableJsonString: non-index array property at ${path}.${key}`);
1930
+ }
1931
+ if (key !== "length" && descriptor !== void 0 && !descriptor.enumerable) {
1932
+ throw new TypeError(`stableJsonString: non-enumerable array property at ${path}.${key}`);
1933
+ }
1934
+ }
1935
+ const out2 = [];
1936
+ for (let i = 0; i < value.length; i += 1) {
1937
+ if (!(i in value)) {
1938
+ throw new TypeError(`stableJsonString: sparse array hole at ${path}[${i}]`);
1939
+ }
1940
+ out2.push(sortedJsonValue(value[i], seen, `${path}[${i}]`, strictNumbers));
1941
+ }
1942
+ return out2;
1943
+ }
1944
+ if (Object.getOwnPropertySymbols(value).length > 0) {
1945
+ throw new TypeError(`stableJsonString: symbol-keyed properties at ${path}`);
1946
+ }
1947
+ for (const key of Object.getOwnPropertyNames(value)) {
1948
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
1949
+ if (descriptor !== void 0 && ("get" in descriptor || "set" in descriptor)) {
1950
+ throw new TypeError(`stableJsonString: accessor property at ${path}.${key}`);
1951
+ }
1952
+ if (descriptor !== void 0 && !descriptor.enumerable) {
1953
+ throw new TypeError(`stableJsonString: non-enumerable property at ${path}.${key}`);
1954
+ }
1955
+ }
1956
+ const out = /* @__PURE__ */ Object.create(null);
1957
+ for (const key of Object.keys(value).sort()) {
1958
+ out[key] = sortedJsonValue(
1959
+ value[key],
1960
+ seen,
1961
+ `${path}.${key}`,
1962
+ strictNumbers
1963
+ );
1964
+ }
1965
+ return out;
1966
+ } finally {
1967
+ seen.delete(value);
1968
+ }
1969
+ }
1970
+ function stableJsonString(value) {
1971
+ return JSON.stringify(sortedJsonValue(value));
1972
+ }
1973
+ function strictStableJsonString(value) {
1974
+ return JSON.stringify(sortedJsonValue(value, /* @__PURE__ */ new Set(), "$", true));
1975
+ }
1976
+ function jsonCodecFor() {
1977
+ const encoder = new TextEncoder();
1978
+ const decoder = new TextDecoder();
1979
+ return {
1980
+ encode(value) {
1981
+ return encoder.encode(stableJsonString(value));
1982
+ },
1983
+ decode(bytes) {
1984
+ return JSON.parse(decoder.decode(bytes));
1985
+ }
1986
+ };
1987
+ }
1988
+ var jsonCodec = jsonCodecFor();
1989
+ function bytesEqual(a, b) {
1990
+ if (a.byteLength !== b.byteLength) return false;
1991
+ for (let i = 0; i < a.byteLength; i += 1) {
1992
+ if (a[i] !== b[i]) return false;
1993
+ }
1994
+ return true;
1995
+ }
1996
+ function hasUnpairedSurrogate(value) {
1997
+ for (let i = 0; i < value.length; i += 1) {
1998
+ const code = value.charCodeAt(i);
1999
+ if (code >= 55296 && code <= 56319) {
2000
+ const next = value.charCodeAt(i + 1);
2001
+ if (next >= 56320 && next <= 57343) {
2002
+ i += 1;
2003
+ continue;
2004
+ }
2005
+ return true;
2006
+ }
2007
+ if (code >= 56320 && code <= 57343) return true;
2008
+ }
2009
+ return false;
2010
+ }
2011
+ function assertNoUnpairedSurrogates(value, seen = /* @__PURE__ */ new Set(), path = "$") {
2012
+ if (typeof value === "string") {
2013
+ if (hasUnpairedSurrogate(value)) {
2014
+ throw new TypeError(`strictJsonCodec: unpaired surrogate at ${path}`);
2015
+ }
2016
+ return;
2017
+ }
2018
+ if (value === null || typeof value !== "object") return;
2019
+ if (seen.has(value)) return;
2020
+ seen.add(value);
2021
+ try {
2022
+ if (Array.isArray(value)) {
2023
+ for (let i = 0; i < value.length; i += 1) {
2024
+ assertNoUnpairedSurrogates(value[i], seen, `${path}[${i}]`);
2025
+ }
2026
+ return;
2027
+ }
2028
+ for (const key of Object.keys(value)) {
2029
+ if (hasUnpairedSurrogate(key)) {
2030
+ throw new TypeError(`strictJsonCodec: unpaired surrogate at ${path}.${key}`);
2031
+ }
2032
+ assertNoUnpairedSurrogates(value[key], seen, `${path}.${key}`);
2033
+ }
2034
+ } finally {
2035
+ seen.delete(value);
2036
+ }
2037
+ }
2038
+ function assertNoDuplicateJsonObjectKeys(text) {
2039
+ let index = 0;
2040
+ function fail(message) {
2041
+ throw new TypeError(`strictJsonCodec: ${message}`);
2042
+ }
2043
+ function skipWhitespace() {
2044
+ while (/\s/.test(text[index] ?? "")) index += 1;
2045
+ }
2046
+ function readJsonString() {
2047
+ const start = index;
2048
+ index += 1;
2049
+ while (index < text.length) {
2050
+ const ch = text[index];
2051
+ if (ch === '"') {
2052
+ index += 1;
2053
+ try {
2054
+ return JSON.parse(text.slice(start, index));
2055
+ } catch {
2056
+ fail("malformed JSON string");
2057
+ }
2058
+ }
2059
+ if (ch === "\\") {
2060
+ index += 2;
2061
+ continue;
2062
+ }
2063
+ index += 1;
2064
+ }
2065
+ fail("unterminated JSON string");
2066
+ }
2067
+ function consumeLiteral(literal) {
2068
+ if (text.slice(index, index + literal.length) !== literal) {
2069
+ fail(`malformed JSON near byte ${index}`);
2070
+ }
2071
+ index += literal.length;
2072
+ }
2073
+ function consumeNumber() {
2074
+ const match = /^-?(0|[1-9]\d*)(\.\d+)?([eE][+-]?\d+)?/.exec(text.slice(index));
2075
+ if (!match) fail(`malformed JSON number near byte ${index}`);
2076
+ index += match[0].length;
2077
+ }
2078
+ function parseValue(path) {
2079
+ skipWhitespace();
2080
+ const ch = text[index];
2081
+ if (ch === "{") {
2082
+ parseObject(path);
2083
+ return;
2084
+ }
2085
+ if (ch === "[") {
2086
+ parseArray(path);
2087
+ return;
2088
+ }
2089
+ if (ch === '"') {
2090
+ readJsonString();
2091
+ return;
2092
+ }
2093
+ if (ch === "t") {
2094
+ consumeLiteral("true");
2095
+ return;
2096
+ }
2097
+ if (ch === "f") {
2098
+ consumeLiteral("false");
2099
+ return;
2100
+ }
2101
+ if (ch === "n") {
2102
+ consumeLiteral("null");
2103
+ return;
2104
+ }
2105
+ if (ch === "-" || ch !== void 0 && ch >= "0" && ch <= "9") {
2106
+ consumeNumber();
2107
+ return;
2108
+ }
2109
+ fail(`malformed JSON near byte ${index}`);
2110
+ }
2111
+ function parseObject(path) {
2112
+ const keys = /* @__PURE__ */ new Set();
2113
+ index += 1;
2114
+ skipWhitespace();
2115
+ if (text[index] === "}") {
2116
+ index += 1;
2117
+ return;
2118
+ }
2119
+ while (index < text.length) {
2120
+ skipWhitespace();
2121
+ if (text[index] !== '"') fail(`expected object key near byte ${index}`);
2122
+ const key = readJsonString();
2123
+ if (keys.has(key)) {
2124
+ throw new TypeError(
2125
+ `strictJsonCodec: duplicate object key ${JSON.stringify(key)} at ${path}`
2126
+ );
2127
+ }
2128
+ keys.add(key);
2129
+ skipWhitespace();
2130
+ if (text[index] !== ":") fail(`expected ':' after object key near byte ${index}`);
2131
+ index += 1;
2132
+ parseValue(`${path}.${key}`);
2133
+ skipWhitespace();
2134
+ if (text[index] === ",") {
2135
+ index += 1;
2136
+ continue;
2137
+ }
2138
+ if (text[index] === "}") {
2139
+ index += 1;
2140
+ return;
2141
+ }
2142
+ fail(`expected ',' or '}' near byte ${index}`);
2143
+ }
2144
+ fail("unterminated JSON object");
2145
+ }
2146
+ function parseArray(path) {
2147
+ index += 1;
2148
+ skipWhitespace();
2149
+ if (text[index] === "]") {
2150
+ index += 1;
2151
+ return;
2152
+ }
2153
+ let item = 0;
2154
+ while (index < text.length) {
2155
+ parseValue(`${path}[${item}]`);
2156
+ item += 1;
2157
+ skipWhitespace();
2158
+ if (text[index] === ",") {
2159
+ index += 1;
2160
+ continue;
2161
+ }
2162
+ if (text[index] === "]") {
2163
+ index += 1;
2164
+ return;
2165
+ }
2166
+ fail(`expected ',' or ']' near byte ${index}`);
2167
+ }
2168
+ fail("unterminated JSON array");
2169
+ }
2170
+ parseValue("$");
2171
+ skipWhitespace();
2172
+ if (index !== text.length) fail(`trailing JSON token near byte ${index}`);
2173
+ }
2174
+ function strictJsonCodecFor() {
2175
+ const encoder = new TextEncoder();
2176
+ const decoder = new TextDecoder("utf-8", { fatal: true });
2177
+ return {
2178
+ encode(value) {
2179
+ assertNoUnpairedSurrogates(value);
2180
+ return encoder.encode(strictStableJsonString(value));
2181
+ },
2182
+ decode(bytes) {
2183
+ const text = decoder.decode(bytes);
2184
+ assertNoDuplicateJsonObjectKeys(text);
2185
+ const decoded = JSON.parse(text);
2186
+ assertNoUnpairedSurrogates(decoded);
2187
+ const canonical = encoder.encode(strictStableJsonString(decoded));
2188
+ if (!bytesEqual(bytes, canonical)) {
2189
+ throw new TypeError("strictJsonCodec: bytes are not canonical stable JSON");
2190
+ }
2191
+ return decoded;
2192
+ }
2193
+ };
2194
+ }
2195
+ var strictJsonCodec = strictJsonCodecFor();
2196
+ function strictCanonicalJsonBytes(value) {
2197
+ return strictJsonCodec.encode(value);
2198
+ }
2199
+
2200
+ // src/node/versioning.ts
2201
+ var ABSENT_V1_SEED = Object.freeze({
2202
+ "@graphrefly/node-version": "v1-absent"
2203
+ });
2204
+ function fnv1a64(input) {
2205
+ let hash = 0xcbf29ce484222325n;
2206
+ const prime = 0x100000001b3n;
2207
+ for (const byte of input) {
2208
+ hash ^= BigInt(byte);
2209
+ hash = BigInt.asUintN(64, hash * prime);
2210
+ }
2211
+ return hash.toString(16).padStart(16, "0");
2212
+ }
2213
+ function defaultNodeVersionHash(bytes) {
2214
+ return `fnv1a64:${fnv1a64(bytes)}`;
2215
+ }
2216
+ function computeV1Cid(policy, value) {
2217
+ return policy.hash(strictCanonicalJsonBytes(value));
2218
+ }
2219
+ function assertNodeVersionDataCompatible(policy, value) {
2220
+ if (!policy.enabled || policy.level === 0) return;
2221
+ strictCanonicalJsonBytes(value);
2222
+ }
2223
+ function snapshotNodeVersionData(policy, value) {
2224
+ if (!policy.enabled || policy.level === 0) return value;
2225
+ const bytes = strictCanonicalJsonBytes(value);
2226
+ return strictJsonCodec.decode(bytes);
2227
+ }
2228
+ function resolveNodeVersioningPolicy(policy) {
2229
+ if (policy === false) return { enabled: false };
2230
+ if (policy === void 0 || policy === 0) return { enabled: true, level: 0 };
2231
+ if (policy === 1) return { enabled: true, level: 1, hash: defaultNodeVersionHash };
2232
+ if (typeof policy === "object" && policy !== null) {
2233
+ if (policy.level === 0) return { enabled: true, level: 0 };
2234
+ if (policy.level === 1) {
2235
+ return { enabled: true, level: 1, hash: policy.hash ?? defaultNodeVersionHash };
2236
+ }
2237
+ }
2238
+ throw new Error("node: versioning level must be 0 or 1; V2/V3 are not locked yet (D109)");
2239
+ }
2240
+ function createNodeVersion(policy, initialValue = ABSENT_V1_SEED) {
2241
+ if (!policy.enabled) return void 0;
2242
+ if (policy.level === 0) return Object.freeze({ level: 0, counter: 0 });
2243
+ return Object.freeze({
2244
+ level: 1,
2245
+ counter: 0,
2246
+ cid: computeV1Cid(policy, initialValue),
2247
+ prev: null
2248
+ });
2249
+ }
2250
+ function advanceNodeVersion(current, policy, value) {
2251
+ if (!policy.enabled) return void 0;
2252
+ if (current === void 0) return createNodeVersion(policy, value);
2253
+ if (policy.level === 0) {
2254
+ return Object.freeze({ level: 0, counter: current.counter + 1 });
2255
+ }
2256
+ const previous = current.level === 1 ? current.cid : null;
2257
+ return Object.freeze({
2258
+ level: 1,
2259
+ counter: current.counter + 1,
2260
+ cid: computeV1Cid(policy, value),
2261
+ prev: previous
2262
+ });
2263
+ }
2264
+ function cloneNodeVersion(version) {
2265
+ if (version === void 0) return void 0;
2266
+ if (version.level === 0) return Object.freeze({ level: 0, counter: version.counter });
2267
+ return Object.freeze({
2268
+ level: 1,
2269
+ counter: version.counter,
2270
+ cid: version.cid,
2271
+ prev: version.prev
2272
+ });
2273
+ }
2274
+ function restoredV1Cid(policy, hasData, cache) {
2275
+ return computeV1Cid(policy, hasData ? cache : ABSENT_V1_SEED);
2276
+ }
2277
+
2278
+ // src/node/node-output-runtime.ts
2279
+ function nodeDown(self, msgs) {
2280
+ if (self._released) return;
2281
+ validateDownPayloads(msgs);
2282
+ const deliveryWave = {};
2283
+ const assertVersionDataCompatible = (wave) => {
2284
+ for (const m of wave) {
2285
+ if (m[0] === "DATA") assertNodeVersionDataCompatible(self._version.policy, m[1]);
2286
+ }
2287
+ };
2288
+ const snapshotVersionData = (wave) => wave.map(
2289
+ (m) => m[0] === "DATA" ? ["DATA", snapshotNodeVersionData(self._version.policy, m[1])] : m
2290
+ );
2291
+ assertVersionDataCompatible(msgs);
2292
+ if (self._value.terminal !== void 0) {
2293
+ if (!msgs.some((m) => m[0] === "TEARDOWN")) return;
2294
+ self._value.hasTorndown = true;
2295
+ if (self._slot.resetOnTeardown) {
2296
+ self._value.cache = SENTINEL;
2297
+ self._value.hasData = false;
2298
+ }
2299
+ self._emitToSubs(["TEARDOWN"], { wave: deliveryWave, last: true });
2300
+ return;
2301
+ }
2302
+ let sorted = [...msgs].sort((a, b) => messageTier(a[0]) - messageTier(b[0]));
2303
+ const firstInvalidate = sorted.findIndex((m) => m[0] === "INVALIDATE");
2304
+ if (firstInvalidate !== -1) {
2305
+ sorted = sorted.filter((m, i) => m[0] !== "INVALIDATE" || i === firstInvalidate);
2306
+ }
2307
+ const hasTeardown = sorted.some((m) => m[0] === "TEARDOWN");
2308
+ const hasTerminal = sorted.some((m) => m[0] === "COMPLETE" || m[0] === "ERROR");
2309
+ if (hasTeardown && !hasTerminal && self._value.terminal === void 0 && !self._value.hasTorndown) {
2310
+ sorted = [["COMPLETE"], ...sorted];
2311
+ }
2312
+ if (!self._wave.insideRunWave && currentBatch()) {
2313
+ const deferred = snapshotVersionData(sorted.filter((m) => isDeferredTier(m[0])));
2314
+ if (deferred.length > 0) {
2315
+ if (!self._wave.emittedDirtyThisWave) {
2316
+ self._wave.emittedDirtyThisWave = true;
2317
+ self._value.status = "dirty";
2318
+ self._emitToSubs(["DIRTY"], { wave: deliveryWave, last: false });
2319
+ }
2320
+ self._wave.batchDirtyOwed = true;
2321
+ deferToBatch(self, deferred);
2322
+ return;
2323
+ }
2324
+ }
2325
+ if (self._shouldBufferOnPause()) {
2326
+ const buffered = snapshotVersionData(sorted.filter((m) => isPauseBufferedTier(m[0])));
2327
+ if (buffered.length > 0) {
2328
+ self._wave.emittedSettleThisWave = true;
2329
+ self._control.pauseBuffer.push(buffered);
2330
+ }
2331
+ sorted = sorted.filter((m) => !isPauseBufferedTier(m[0]));
2332
+ if (sorted.length === 0) return;
2333
+ }
2334
+ let dataCount = 0;
2335
+ let hasTier3 = false;
2336
+ let hasResolved = false;
2337
+ for (const m of sorted) {
2338
+ if (m[0] === "DATA") dataCount++;
2339
+ if (m[0] === "RESOLVED") hasResolved = true;
2340
+ if (isValueTier(m[0])) hasTier3 = true;
2341
+ }
2342
+ if (dataCount >= 1 && hasResolved) {
2343
+ throw new Error(
2344
+ "down: a wave cannot mix DATA and RESOLVED (tier-3 exclusivity, R-resolved-undirty)"
2345
+ );
2346
+ }
2347
+ const plannedVersions = new Array(sorted.length);
2348
+ if (dataCount > 0) {
2349
+ let plannedVersion = self._version.value;
2350
+ for (let i = 0; i < sorted.length; i++) {
2351
+ const m = sorted[i];
2352
+ if (m[0] !== "DATA") continue;
2353
+ plannedVersion = advanceNodeVersion(plannedVersion, self._version.policy, m[1]);
2354
+ plannedVersions[i] = plannedVersion;
2355
+ }
2356
+ }
2357
+ if (hasTier3 && (!self._wave.insideRunWave || self._control.pullDirtyOwed) && !self._wave.emittedDirtyThisWave) {
2358
+ self._wave.emittedDirtyThisWave = true;
2359
+ self._value.status = "dirty";
2360
+ self._emitToSubs(["DIRTY"], { wave: deliveryWave, last: false });
2361
+ }
2362
+ for (let i = 0; i < sorted.length; i++) {
2363
+ const m = sorted[i];
2364
+ const delivery = { wave: deliveryWave, last: i === sorted.length - 1 };
2365
+ if (isDeferredTier(m[0])) self._wave.emittedSettleThisWave = true;
2366
+ if (m[0] === "DIRTY") {
2367
+ if (!self._wave.emittedDirtyThisWave) {
2368
+ self._wave.emittedDirtyThisWave = true;
2369
+ self._value.status = "dirty";
2370
+ self._emitToSubs(["DIRTY"], delivery);
2371
+ }
2372
+ continue;
2373
+ }
2374
+ if (m[0] === "DATA") {
2375
+ const v = m[1];
2376
+ self._value.cache = v;
2377
+ self._value.hasData = true;
2378
+ self._value.status = "settled";
2379
+ self._version.value = plannedVersions[i];
2380
+ if (self._slot.replayN > 0) {
2381
+ self._value.replayRing.push(v);
2382
+ if (self._value.replayRing.length > self._slot.replayN) self._value.replayRing.shift();
2383
+ }
2384
+ self._emitToSubs(["DATA", v], delivery);
2385
+ continue;
2386
+ }
2387
+ if (m[0] === "RESOLVED") {
2388
+ self._value.status = self._value.hasData ? "resolved" : "sentinel";
2389
+ self._emitToSubs(["RESOLVED"], delivery);
2390
+ continue;
2391
+ }
2392
+ if (m[0] === "INVALIDATE") {
2393
+ self._invalidate(delivery);
2394
+ continue;
2395
+ }
2396
+ if (m[0] === "COMPLETE") {
2397
+ if (self._value.terminal !== void 0) continue;
2398
+ self._value.terminal = true;
2399
+ self._control.pauseBuffer = [];
2400
+ self._value.status = "completed";
2401
+ self._emitToSubs(["COMPLETE"], delivery);
2402
+ continue;
2403
+ }
2404
+ if (m[0] === "ERROR") {
2405
+ if (self._value.terminal !== void 0) continue;
2406
+ self._value.terminal = m[1];
2407
+ self._control.pauseBuffer = [];
2408
+ self._value.status = "errored";
2409
+ self._emitToSubs(["ERROR", m[1]], delivery);
2410
+ continue;
2411
+ }
2412
+ if (m[0] === "TEARDOWN") {
2413
+ self._value.hasTorndown = true;
2414
+ if (self._slot.resetOnTeardown) {
2415
+ self._value.cache = SENTINEL;
2416
+ self._value.hasData = false;
2417
+ }
2418
+ self._emitToSubs(["TEARDOWN"], delivery);
2419
+ }
2420
+ }
2421
+ if (!self._wave.insideRunWave) self._wave.emittedDirtyThisWave = false;
2422
+ }
2423
+ function nodeUp(self, msgs, towardDep, route) {
2424
+ if (self._released) return;
2425
+ const routeState = route ?? { demandFired: /* @__PURE__ */ new Map() };
2426
+ for (const m of msgs) {
2427
+ if (!isUpAllowed(m[0])) {
2428
+ throw new Error(
2429
+ `ctx.up: ${m[0]} is down-only (tier ${messageTier(m[0])}); up carries control tiers only (R-ctx-up)`
2430
+ );
2431
+ }
2432
+ }
2433
+ for (const m of msgs) {
2434
+ if (m[0] === "PAUSE") {
2435
+ self._pauseAcquire(m[1]);
2436
+ } else if (m[0] === "RESUME") {
2437
+ if (self._control.pauseLockset.has(m[1])) {
2438
+ self._pauseRelease(m[1]);
2439
+ } else {
2440
+ self._forwardUp(m, towardDep, routeState);
2441
+ }
2442
+ } else if (m[0] === "PULL") {
2443
+ const demand = normalizePullDemand(m[1]);
2444
+ if (self._slot.pull && demand.pullId === self._slot.pullLock) {
2445
+ if (!self._markDemandRouted(demand.pullId, routeState)) self._onDemand(demand);
2446
+ } else {
2447
+ self._forwardUp(["PULL", demand], towardDep, routeState);
2448
+ }
2449
+ } else if (self._slot.deps.length === 0) {
2450
+ if (m[0] === "INVALIDATE") self._down([["INVALIDATE"]]);
2451
+ } else {
2452
+ self._forwardUp(m, towardDep, routeState);
2453
+ }
2454
+ }
2455
+ }
2456
+ function nodeMarkDemandRouted(self, lockId, route) {
2457
+ let holders = route.demandFired.get(lockId);
2458
+ if (holders === void 0) {
2459
+ holders = /* @__PURE__ */ new Set();
2460
+ route.demandFired.set(lockId, holders);
2461
+ }
2462
+ const node = self;
2463
+ if (holders.has(node)) return true;
2464
+ holders.add(node);
2465
+ return false;
2466
+ }
2467
+ function nodeForwardUp(self, m, towardDep, route) {
2468
+ if (self._slot.deps.length === 0) return;
2469
+ if (towardDep !== void 0) {
2470
+ const d = self._slot.deps[towardDep];
2471
+ if (d !== void 0) nodeRuntimeHost(d)._up([m], void 0, route);
2472
+ } else {
2473
+ for (const dep of self._slot.deps) nodeRuntimeHost(dep)._up([m], void 0, route);
2474
+ }
2475
+ }
2476
+ function nodeIsPaused(self) {
2477
+ return self._control.pauseLockset.size > 0;
2478
+ }
2479
+ function nodeHasBoundaryPauseLock(self) {
2480
+ if (self._slot.pausable === false) return false;
2481
+ return self._control.pauseLockset.size > 0;
2482
+ }
2483
+ function nodeIsAsyncPool(self) {
2484
+ return self._slot.handle !== null && self._slot.dispatcher.poolKind(self._slot.handle.poolId) === "async";
2485
+ }
2486
+ function nodePauseAcquire(self, lockId) {
2487
+ self._control.pauseLockset.add(lockId);
2488
+ }
2489
+ function nodePauseRelease(self, lockId) {
2490
+ if (!self._control.pauseLockset.has(lockId)) return;
2491
+ self._control.pauseLockset.delete(lockId);
2492
+ if (self._slot.pull && self._control.demandOwed !== void 0) self._fireOwedDemandIfReady();
2493
+ if (self._hasBoundaryPauseLock()) return;
2494
+ scheduleBoundaryDrain(self._core);
2495
+ if (self._slot.pull) return;
2496
+ self._onResume();
2497
+ }
2498
+ function nodeOnResume(self) {
2499
+ if (self._value.terminal !== void 0) {
2500
+ self._control.pauseBuffer = [];
2501
+ self._control.pausedDepWaveOccurred = false;
2502
+ self._control.demandOwed = void 0;
2503
+ self._control.activePull = void 0;
2504
+ self._control.pullDirtyOwed = false;
2505
+ return;
2506
+ }
2507
+ if (self._control.pauseBuffer.length > 0) {
2508
+ const buf = self._control.pauseBuffer;
2509
+ self._control.pauseBuffer = [];
2510
+ for (const wave of buf) self._down(wave);
2511
+ }
2512
+ if (self._control.pausedDepWaveOccurred) {
2513
+ self._control.pausedDepWaveOccurred = false;
2514
+ self._tryRun();
2515
+ }
2516
+ }
2517
+ function nodeCanFireDemand(self) {
2518
+ if (self._value.terminal !== void 0 || self._wave.pending > 0) return false;
2519
+ return self._control.pauseLockset.size === 0;
2520
+ }
2521
+ function nodeDeliverPullDemand(self, demand) {
2522
+ self._control.demandOwed = void 0;
2523
+ self._control.activePull = demand;
2524
+ self._control.inDeliverDemand = true;
2525
+ try {
2526
+ self._firePullDemand();
2527
+ } finally {
2528
+ self._control.activePull = void 0;
2529
+ self._control.inDeliverDemand = false;
2530
+ }
2531
+ }
2532
+ function nodeOnDemand(self, demand) {
2533
+ if (self._control.inDeliverDemand) return;
2534
+ if (self._canFireDemand()) self._deliverPullDemand(demand);
2535
+ else self._control.demandOwed = demand;
2536
+ }
2537
+ function nodeFirePullDemand(self) {
2538
+ let drainedBuffer = false;
2539
+ if (self._control.pauseBuffer.length > 0) {
2540
+ const buf = self._control.pauseBuffer;
2541
+ self._control.pauseBuffer = [];
2542
+ for (const wave of buf) self._down(wave);
2543
+ drainedBuffer = true;
2544
+ }
2545
+ if (drainedBuffer) return;
2546
+ if (self._control.pausedDepWaveOccurred) {
2547
+ const gated = self._slot.handle !== null && !self._wave.hasCalledFnOnce && !(self._slot.partial || self._allDepsSettled());
2548
+ if (self._wave.pending > 0 || gated) return;
2549
+ self._control.pausedDepWaveOccurred = false;
2550
+ self._wave.emittedDirtyThisWave = false;
2551
+ self._control.pullDirtyOwed = true;
2552
+ try {
2553
+ self._tryRun();
2554
+ } finally {
2555
+ self._control.pullDirtyOwed = false;
2556
+ }
2557
+ return;
2558
+ }
2559
+ if (self._slot.handle !== null) {
2560
+ if (!self._wave.hasCalledFnOnce && !(self._slot.partial || self._allDepsSettled())) return;
2561
+ self._wave.emittedDirtyThisWave = false;
2562
+ self._control.pullDirtyOwed = true;
2563
+ try {
2564
+ self._runWave();
2565
+ } finally {
2566
+ self._control.pullDirtyOwed = false;
2567
+ }
2568
+ }
2569
+ }
2570
+ function nodeFireOwedDemandIfReady(self) {
2571
+ if (self._control.inDeliverDemand) return;
2572
+ if (self._slot.pull && self._control.demandOwed !== void 0 && self._canFireDemand()) {
2573
+ self._deliverPullDemand(self._control.demandOwed);
2574
+ }
2575
+ }
2576
+ function nodeShouldBufferOnPause(self) {
2577
+ if (self._slot.pausable === false) return false;
2578
+ if (!self._isPaused() && !self._isPullQuiet()) return false;
2579
+ if (self._slot.pausable === "resumeAll") return true;
2580
+ if (!self._wave.insideRunWave && self._isAsyncPool() && self._slot.deps.length > 0) return true;
2581
+ return false;
2582
+ }
2583
+ function nodeInvalidate(self, delivery) {
2584
+ if (!self._value.hasData) return;
2585
+ self._value.cache = SENTINEL;
2586
+ self._value.hasData = false;
2587
+ self._value.status = "sentinel";
2588
+ self._value.replayRing = [];
2589
+ for (const fn of self._hooks.onInvalidate) fn();
2590
+ self._emitToSubs(["INVALIDATE"], delivery);
2591
+ }
2592
+ function nodeAllDepsTerminal(self) {
2593
+ if (self._slot.deps.length === 0) return false;
2594
+ for (const tm of self._dep.terminal) if (tm === void 0) return false;
2595
+ return true;
2596
+ }
2597
+ function nodeResetLifecycle(self) {
2598
+ for (const u of self._dep.unsubs) if (u) u();
2599
+ self._dep.unsubs = [];
2600
+ self._dep.idxBoxes = [];
2601
+ self._lifecycle.subscribers.clear();
2602
+ self._lifecycle.activated = false;
2603
+ self._value.terminal = void 0;
2604
+ self._value.hasTorndown = false;
2605
+ self._wave.hasCalledFnOnce = false;
2606
+ self._resetDepState();
2607
+ self._control.pauseLockset.clear();
2608
+ self._control.pauseBuffer = [];
2609
+ self._control.pausedDepWaveOccurred = false;
2610
+ self._control.demandOwed = void 0;
2611
+ self._control.activePull = void 0;
2612
+ self._control.pullDirtyOwed = false;
2613
+ self._value.replayRing = [];
2614
+ const isCompute = self._slot.handle !== null || self._slot.deps.length > 0;
2615
+ if (isCompute) {
2616
+ self._value.cache = SENTINEL;
2617
+ self._value.hasData = false;
2618
+ self._value.status = "sentinel";
2619
+ } else {
2620
+ self._value.status = self._value.hasData ? "settled" : "sentinel";
2621
+ }
2622
+ if (!self._privateState.persist) self._privateState.value = SENTINEL;
2623
+ }
2624
+ function nodeEmitToSubs(self, msg, delivery) {
2625
+ if (self._released) return;
2626
+ const subs = [...self._lifecycle.subscribers];
2627
+ for (const sink of subs) sink(msg, delivery);
2628
+ }
2629
+ function nodeCommitBatchedWave(self, wave) {
2630
+ self._wave.batchDirtyOwed = false;
2631
+ self._down(wave);
2632
+ }
2633
+ function nodeRollbackBatched(self) {
2634
+ if (self._wave.batchDirtyOwed) {
2635
+ self._wave.batchDirtyOwed = false;
2636
+ self._wave.emittedDirtyThisWave = false;
2637
+ self._value.status = self._value.hasData ? "settled" : "sentinel";
2638
+ self._emitToSubs(["RESOLVED"]);
2639
+ }
2640
+ }
2641
+ function nodeDeferBoundary(self, fn, batchToken) {
2642
+ deferRewire(self._core, fn, {
2643
+ batchToken,
2644
+ isReady: () => !self._hasBoundaryPauseLock()
2645
+ });
2646
+ }
2647
+
2648
+ // src/node/node-rewire-runtime.ts
2649
+ function nodeRequestRewireNext(self, op) {
2650
+ deferRewire(self._core, () => self._applyRewireNext(op), {
2651
+ batchToken: currentBoundaryBatchToken(),
2652
+ isReady: () => !self._hasBoundaryPauseLock()
2653
+ });
2654
+ }
2655
+ function nodeRequestUpNext(self, msgs, towardDep) {
2656
+ deferRewire(
2657
+ self._core,
2658
+ () => {
2659
+ if (!self._released) self._up(msgs, towardDep);
2660
+ },
2661
+ {
2662
+ batchToken: currentBoundaryBatchToken(),
2663
+ isReady: () => !self._hasBoundaryPauseLock()
2664
+ }
2665
+ );
2666
+ }
2667
+ function nodeApplyRewireNext(self, op) {
2668
+ if (self._released) return;
2669
+ try {
2670
+ if (op.kind === "add") {
2671
+ const next = self._slot.deps.includes(op.dep) ? [...self._slot.deps] : [...self._slot.deps, op.dep];
2672
+ self._rewire(next, op.fn, { allowTerminalOwner: true });
2673
+ } else if (op.kind === "remove") {
2674
+ self._rewire(
2675
+ self._slot.deps.filter((d) => d !== op.dep),
2676
+ op.fn,
2677
+ { allowTerminalOwner: true }
2678
+ );
2679
+ } else {
2680
+ self._rewire(self._dedupDeps(op.deps), op.fn, { allowTerminalOwner: true });
2681
+ }
2682
+ } catch (e) {
2683
+ self._down([["ERROR", errorPayload(e, "rewireNext op failed")]]);
2684
+ }
2685
+ }
2686
+ function nodeRewire(self, newDeps, fn, opts = {}) {
2687
+ const node = self;
2688
+ if (self._value.terminal !== void 0 && !opts.allowTerminalOwner)
2689
+ throw new Error(
2690
+ "rewire: node is terminal (completed/errored) \u2014 cannot rewire (R-rewire / D42)"
2691
+ );
2692
+ if (self._wave.insideRunWave)
2693
+ throw new Error(
2694
+ "rewire: mid-fn topology mutation \u2014 a fn mutating its own deps mid-wave is the feedback cycle (R-rewire / D37)"
2695
+ );
2696
+ if (self._wave.inDepMutation)
2697
+ throw new Error(
2698
+ "rewire: reentrant dep mutation \u2014 another replaceDeps/subscribeDep/unsubscribeDep is in flight (R-rewire)"
2699
+ );
2700
+ if (newDeps.includes(node)) throw new Error("rewire: self-dependency rejected (R-rewire / D42)");
2701
+ const oldDeps = self._slot.deps;
2702
+ const added = newDeps.filter((d) => !oldDeps.includes(d));
2703
+ for (const d of added) {
2704
+ if (self._reachableUpstream(d, node))
2705
+ throw new Error(
2706
+ "rewire: would create a cycle \u2014 dep already transitively depends on this node (R-rewire / D42)"
2707
+ );
2708
+ const dep = nodeRuntimeHost(d);
2709
+ if (dep._value.terminal !== void 0 && !dep._slot.resubscribable)
2710
+ throw new Error(
2711
+ "rewire: cannot add a non-resubscribable terminal dep \u2014 would wedge (R-rewire / D42)"
2712
+ );
2713
+ self._assertRewireDepOwner(d);
2714
+ }
2715
+ if (deferAfterBatchForTarget(node, () => {
2716
+ self._rewire(newDeps, fn, { ...opts, allowTerminalOwner: true });
2717
+ })) {
2718
+ return true;
2719
+ }
2720
+ if (!self._lifecycle.activated) self._restoredActivationPending = false;
2721
+ self._wave.inDepMutation = true;
2722
+ self._wave.rewireRunPending = false;
2723
+ let zeroDepUnDirty = false;
2724
+ try {
2725
+ const oldHandle = self._slot.handle;
2726
+ self._slot.handle = self._slot.dispatcher.register(fn, self._slot.pool);
2727
+ if (oldHandle !== null) self._slot.dispatcher.unregister(oldHandle);
2728
+ const removed = oldDeps.filter((d) => !newDeps.includes(d));
2729
+ let removedDirtyContributor = false;
2730
+ for (const d of removed) {
2731
+ const oldIdx = oldDeps.indexOf(d);
2732
+ if (self._dep.dirty[oldIdx]) {
2733
+ removedDirtyContributor = true;
2734
+ self._wave.pending--;
2735
+ }
2736
+ if (self._lifecycle.activated) {
2737
+ const box = self._dep.idxBoxes[oldIdx];
2738
+ if (box) box.v = -1;
2739
+ const unsub = self._dep.unsubs[oldIdx];
2740
+ if (unsub) unsub();
2741
+ }
2742
+ }
2743
+ const n = newDeps.length;
2744
+ const newBatch = new Array(n).fill(null);
2745
+ const newPrev = new Array(n).fill(SENTINEL);
2746
+ const newHasData = new Array(n).fill(false);
2747
+ const newDirty = new Array(n).fill(false);
2748
+ const newTier = new Array(n).fill(0);
2749
+ const newTerminal = new Array(n).fill(void 0);
2750
+ const newTerminalInput = new Array(n).fill(void 0);
2751
+ const newUnsubs = new Array(n);
2752
+ const newBoxes = new Array(n);
2753
+ for (let j = 0; j < n; j++) {
2754
+ const oldIdx = oldDeps.indexOf(newDeps[j]);
2755
+ if (oldIdx !== -1) {
2756
+ newBatch[j] = self._dep.batch[oldIdx];
2757
+ newPrev[j] = self._dep.prev[oldIdx];
2758
+ newHasData[j] = self._dep.hasData[oldIdx];
2759
+ newDirty[j] = self._dep.dirty[oldIdx];
2760
+ newTier[j] = self._dep.tier[oldIdx];
2761
+ newTerminal[j] = self._dep.terminal[oldIdx];
2762
+ newUnsubs[j] = self._dep.unsubs[oldIdx];
2763
+ const box = self._dep.idxBoxes[oldIdx];
2764
+ if (box) box.v = j;
2765
+ newBoxes[j] = box;
2766
+ }
2767
+ }
2768
+ self._slot.deps = newDeps;
2769
+ self._dep.batch = newBatch;
2770
+ self._dep.prev = newPrev;
2771
+ self._dep.hasData = newHasData;
2772
+ self._dep.dirty = newDirty;
2773
+ self._dep.tier = newTier;
2774
+ self._dep.terminal = newTerminal;
2775
+ self._dep.terminalInput = newTerminalInput;
2776
+ self._dep.unsubs = newUnsubs;
2777
+ self._dep.idxBoxes = newBoxes;
2778
+ self._dep.waveData = newDeps.map(() => []);
2779
+ self._dep.waveTokens = new Array(newDeps.length).fill(void 0);
2780
+ self._syncCtx = null;
2781
+ if (self._lifecycle.activated) {
2782
+ for (const d of added) self._subscribeDepAt(d);
2783
+ }
2784
+ notifyTopologyDepsChanged(node, oldDeps, newDeps);
2785
+ if (removedDirtyContributor && self._wave.pending === 0 && self._value.status === "dirty") {
2786
+ if (newDeps.length > 0) self._wave.rewireRunPending = true;
2787
+ else zeroDepUnDirty = true;
2788
+ }
2789
+ } finally {
2790
+ self._wave.inDepMutation = false;
2791
+ }
2792
+ if (self._wave.rewireRunPending) {
2793
+ self._wave.rewireRunPending = false;
2794
+ self._settleRewire();
2795
+ } else if (zeroDepUnDirty) {
2796
+ if (self._wave.emittedDirtyThisWave) self._down([["RESOLVED"]]);
2797
+ else self._value.status = self._value.hasData ? "settled" : "sentinel";
2798
+ }
2799
+ return false;
2800
+ }
2801
+
2802
+ // src/node/node.ts
2803
+ var Node = class _Node {
2804
+ _core;
2805
+ _id;
2806
+ _slot;
2807
+ _dep;
2808
+ _value;
2809
+ _wave;
2810
+ _control;
2811
+ _lifecycle;
2812
+ _privateState;
2813
+ _hooks;
2814
+ _syncCtxState;
2815
+ _version;
2816
+ _restoredActivationPending = false;
2817
+ _released = false;
2818
+ get _syncCtx() {
2819
+ return this._syncCtxState.value;
2820
+ }
2821
+ set _syncCtx(ctx) {
2822
+ this._syncCtxState.value = ctx;
2823
+ }
2824
+ static _retainIndirectRuntimeMethods(node) {
2825
+ void node._dep;
2826
+ void node._hooks;
2827
+ void node._restoredActivationPending;
2828
+ void node._requestRewireNext;
2829
+ void node._requestUpNext;
2830
+ void node._applyRewireNext;
2831
+ void node._reachableUpstream;
2832
+ void node._assertRewireDepOwner;
2833
+ void node._subscribeDepAt;
2834
+ void node._seedRestoredDepAt;
2835
+ void node._recordDepProjection;
2836
+ void node._depProjectionHasData;
2837
+ void node._receiveFromDep;
2838
+ void node._releaseDepDirty;
2839
+ void node._settleAfterAbsorbedTerminal;
2840
+ void node._markDirty;
2841
+ void node._maybeRun;
2842
+ void node._settleRewire;
2843
+ void node._tryRun;
2844
+ void node._allDepsSettled;
2845
+ void node._passthroughEmit;
2846
+ void node._runWave;
2847
+ void node._buildCtx;
2848
+ void node._makeCtx;
2849
+ void node._refreshCtx;
2850
+ void node._makeState;
2851
+ void node._markDemandRouted;
2852
+ void node._forwardUp;
2853
+ void node._isPullQuiet;
2854
+ void node._isPaused;
2855
+ void node._hasBoundaryPauseLock;
2856
+ void node._isAsyncPool;
2857
+ void node._pauseAcquire;
2858
+ void node._pauseRelease;
2859
+ void node._onResume;
2860
+ void node._canFireDemand;
2861
+ void node._deliverPullDemand;
2862
+ void node._onDemand;
2863
+ void node._firePullDemand;
2864
+ void node._fireOwedDemandIfReady;
2865
+ void node._shouldBufferOnPause;
2866
+ void node._invalidate;
2867
+ void node._allDepsTerminal;
2868
+ void node._emitToSubs;
2869
+ }
2870
+ constructor(deps, handleOrFn, opts = {}) {
2871
+ const core = takeConstructingNodeCore();
2872
+ const dispatcher = opts.dispatcher ?? defaultDispatcher;
2873
+ const environment = takeConstructingEnvironmentDrivers() ?? EnvironmentDrivers.empty();
2874
+ const pool = opts.pool ?? "sync";
2875
+ const pausable = opts.pausable ?? true;
2876
+ const pullLock = opts.pullId;
2877
+ const pull = opts.pullId !== void 0;
2878
+ if (pull && pausable === false)
2879
+ throw new Error(
2880
+ "node: pullId is incompatible with pausable:false \u2014 a pull node uses the pausable delivery-content axis (R-pull / R-pause-modes / D55,D269)"
2881
+ );
2882
+ let handle;
2883
+ if (handleOrFn === null) handle = null;
2884
+ else if (typeof handleOrFn === "function") handle = dispatcher.register(handleOrFn, pool);
2885
+ else handle = handleOrFn;
2886
+ const n = deps.length;
2887
+ const dep = makeDepBookkeeping(n);
2888
+ const versioning = resolveNodeVersioningPolicy(opts.versioning);
2889
+ const value = {
2890
+ cache: SENTINEL,
2891
+ hasData: false,
2892
+ status: "sentinel",
2893
+ terminal: void 0,
2894
+ hasTorndown: false,
2895
+ replayRing: []
2896
+ };
2897
+ if (opts.initial !== void 0) {
2898
+ value.cache = opts.initial;
2899
+ value.hasData = true;
2900
+ value.status = "settled";
2901
+ }
2902
+ const pauseLockset = /* @__PURE__ */ new Set();
2903
+ this._core = core ?? new NodeCore();
2904
+ const created = this._core.createSlot(
2905
+ {
2906
+ deps,
2907
+ handle,
2908
+ pool,
2909
+ dispatcher,
2910
+ environment,
2911
+ partial: opts.partial ?? false,
2912
+ terminalAsRealInput: opts.terminalAsRealInput ?? false,
2913
+ completeWhenDepsComplete: opts.completeWhenDepsComplete ?? true,
2914
+ errorWhenDepsError: opts.errorWhenDepsError ?? true,
2915
+ resubscribable: opts.resubscribable ?? false,
2916
+ resetOnTeardown: opts.resetOnTeardown ?? false,
2917
+ pausable,
2918
+ pull,
2919
+ pullLock,
2920
+ replayN: opts.replayBuffer ?? 0,
2921
+ dynamic: opts.dynamic ?? false,
2922
+ name: opts.name,
2923
+ factory: opts.factory
2924
+ },
2925
+ {
2926
+ dep,
2927
+ lifecycle: { subscribers: /* @__PURE__ */ new Set(), activated: false },
2928
+ value,
2929
+ wave: {
2930
+ pending: 0,
2931
+ hasCalledFnOnce: false,
2932
+ emittedDirtyThisWave: false,
2933
+ emittedSettleThisWave: false,
2934
+ insideRunWave: false,
2935
+ inDepMutation: false,
2936
+ rewireRunPending: false,
2937
+ batchDirtyOwed: false
2938
+ },
2939
+ control: {
2940
+ pauseLockset,
2941
+ pausedDepWaveOccurred: false,
2942
+ pauseBuffer: [],
2943
+ demandOwed: void 0,
2944
+ activePull: void 0,
2945
+ pullDirtyOwed: false,
2946
+ inDeliverDemand: false
2947
+ },
2948
+ privateState: { value: SENTINEL, persist: false },
2949
+ hooks: { onDeactivation: [], onInvalidate: [] },
2950
+ syncCtx: { value: null },
2951
+ version: {
2952
+ policy: versioning,
2953
+ value: createNodeVersion(
2954
+ versioning,
2955
+ opts.initial !== void 0 ? opts.initial : void 0
2956
+ )
2957
+ }
2958
+ }
2959
+ );
2960
+ this._id = created.id;
2961
+ this._slot = this._core.get(this._id);
2962
+ this._dep = this._core.getDep(this._id);
2963
+ this._value = this._core.getValue(this._id);
2964
+ this._wave = this._core.getWave(this._id);
2965
+ this._control = this._core.getControl(this._id);
2966
+ this._lifecycle = this._core.getLifecycle(this._id);
2967
+ this._privateState = this._core.getPrivateState(this._id);
2968
+ this._hooks = this._core.getHooks(this._id);
2969
+ this._syncCtxState = this._core.getSyncCtx(this._id);
2970
+ this._version = this._core.getVersion(this._id);
2971
+ checkpointReaders.set(this, () => ({
2972
+ cache: this._value.cache,
2973
+ hasData: this._value.hasData,
2974
+ terminal: this._value.terminal,
2975
+ activated: this._lifecycle.activated,
2976
+ hasCalledFnOnce: this._wave.hasCalledFnOnce,
2977
+ ctxState: {
2978
+ value: this._privateState.value,
2979
+ persist: this._privateState.persist
2980
+ },
2981
+ version: cloneNodeVersion(this._version.value),
2982
+ handle: this._slot.handle
2983
+ }));
2984
+ restoreWriters.set(this, (state) => {
2985
+ this._assertNotReleased("restoreGraph");
2986
+ this._value.cache = state.cache;
2987
+ this._value.hasData = state.hasData;
2988
+ this._value.status = state.status;
2989
+ this._value.terminal = state.terminal;
2990
+ this._value.hasTorndown = false;
2991
+ this._value.replayRing = [];
2992
+ this._wave.hasCalledFnOnce = state.hasCalledFnOnce;
2993
+ this._wave.emittedDirtyThisWave = false;
2994
+ this._wave.emittedSettleThisWave = false;
2995
+ this._wave.pending = 0;
2996
+ this._wave.insideRunWave = false;
2997
+ this._wave.inDepMutation = false;
2998
+ this._wave.rewireRunPending = false;
2999
+ this._wave.batchDirtyOwed = false;
3000
+ this._control.pauseBuffer = [];
3001
+ this._control.pausedDepWaveOccurred = false;
3002
+ this._control.demandOwed = void 0;
3003
+ this._control.activePull = void 0;
3004
+ this._control.pullDirtyOwed = false;
3005
+ this._control.inDeliverDemand = false;
3006
+ this._control.pauseLockset.clear();
3007
+ this._privateState.value = state.ctxState.value;
3008
+ this._privateState.persist = state.ctxState.persist;
3009
+ if (state.version === false) {
3010
+ this._version.policy = { enabled: false };
3011
+ this._version.value = void 0;
3012
+ } else if (state.version.level === 0) {
3013
+ this._version.policy = { enabled: true, level: 0 };
3014
+ this._version.value = cloneNodeVersion(state.version);
3015
+ } else {
3016
+ if (!this._version.policy.enabled || this._version.policy.level !== 1) {
3017
+ throw new Error(
3018
+ `restoreGraph: checkpoint node version level ${state.version.level} requires matching node versioning policy`
3019
+ );
3020
+ }
3021
+ if (!state.hasData && state.version.counter > 0) {
3022
+ throw new Error(
3023
+ "restoreGraph: checkpoint node version cid cannot be verified without current DATA under V1 versioning (D109)"
3024
+ );
3025
+ }
3026
+ const expectedCid = restoredV1Cid(this._version.policy, state.hasData, state.cache);
3027
+ if (expectedCid !== state.version.cid) {
3028
+ throw new Error(
3029
+ "restoreGraph: checkpoint node version cid does not match the selected node versioning hash policy (D109)"
3030
+ );
3031
+ }
3032
+ this._version.value = cloneNodeVersion(state.version);
3033
+ }
3034
+ this._syncCtx = null;
3035
+ this._resetDepState();
3036
+ this._lifecycle.activated = false;
3037
+ this._lifecycle.subscribers.clear();
3038
+ this._restoredActivationPending = true;
3039
+ });
3040
+ runtimeReleasers.set(this, () => this._releaseRuntime());
3041
+ runtimeQuiescenceReaders.set(this, () => this._isRuntimeQuiescentForRelease());
3042
+ subscriberCountReaders.set(this, () => this._subscriberCount());
3043
+ activationReaders.set(this, () => this._lifecycle.activated);
3044
+ _Node._retainIndirectRuntimeMethods(this);
3045
+ }
3046
+ /** R-pull (D55/D272): true while a pull node is not serving a PULL demand pulse. */
3047
+ _isPullQuiet() {
3048
+ return this._slot.pull && this._control.activePull === void 0;
3049
+ }
3050
+ /**
3051
+ * R-pull (D269/D272): this pull node's pullId (pure data, like {@link cache}/{@link handle} —
3052
+ * never triggers computation). A consumer demands one delivery by cone-routing PULL of it (no
3053
+ * node reference): `ctx.up([["PULL", { pullId }]])` (immediate; loops back → D37 for a self-read
3054
+ * dep) or `ctx.upNext([["PULL", { pullId }]])` (boundary-deferred self-demand). Undefined for a
3055
+ * non-pull node. The author writes the pullId verbatim; routing matches by identity.
3056
+ */
3057
+ get pullId() {
3058
+ return this._slot.pullLock;
3059
+ }
3060
+ get cache() {
3061
+ return this._value.cache;
3062
+ }
3063
+ get status() {
3064
+ return this._value.status;
3065
+ }
3066
+ get version() {
3067
+ return cloneNodeVersion(this._version.value);
3068
+ }
3069
+ get name() {
3070
+ return this._slot.name;
3071
+ }
3072
+ /** R-describe/D51: real factory name for a standalone graph-less node (a runtime *Map inner). */
3073
+ get factory() {
3074
+ return this._slot.factory;
3075
+ }
3076
+ /**
3077
+ * The node's CURRENT/LIVE deps (R-describe / R-edges-derived / D51) — readonly view of the
3078
+ * live `_deps`, which a rewire (C-8 / C-11) mutates. The graph's describe() reads this (NOT a
3079
+ * construction-time snapshot) so every edge corresponds to a real current subscription (D3).
3080
+ * Inspection-only, like cache/status; never triggers computation.
3081
+ */
3082
+ get deps() {
3083
+ return this._slot.deps;
3084
+ }
3085
+ /**
3086
+ * The fn handle (pure data `(poolId, handleId)`, D7) or null for state/passthrough
3087
+ * nodes. Inspection-only (L1.6 handle is referenceable/inspectable) — lets the graph
3088
+ * layer key a dispatcher-backed profile recorder WITHOUT putting counters on the node
3089
+ * (R-node-thin / D39).
3090
+ */
3091
+ get handle() {
3092
+ return this._slot.handle;
3093
+ }
3094
+ /** R-push-subscribe: a new sink receives START, then cached DATA (or DIRTY if dirty). */
3095
+ subscribe(sink) {
3096
+ this._assertNotReleased("subscribe");
3097
+ enterWave();
3098
+ try {
3099
+ if (this._value.terminal !== void 0) {
3100
+ if (this._slot.resubscribable) {
3101
+ this._restoredActivationPending = false;
3102
+ this._resetLifecycle();
3103
+ } else
3104
+ throw new Error(
3105
+ "subscribe: node is non-resubscribable and has terminated; the stream is permanently over (R-terminal / R2.2.7.b)"
3106
+ );
3107
+ }
3108
+ this._lifecycle.subscribers.add(sink);
3109
+ sink(["START"]);
3110
+ if (this._slot.replayN > 0 && this._value.replayRing.length > 0) {
3111
+ for (const v of this._value.replayRing) sink(["DATA", v]);
3112
+ } else if (this._value.hasData && !this._slot.pull) {
3113
+ sink(["DATA", this._value.cache]);
3114
+ } else if (this._value.status === "dirty" && !this._slot.pull) {
3115
+ sink(["DIRTY"]);
3116
+ }
3117
+ if (!this._lifecycle.activated) this._activate();
3118
+ return () => {
3119
+ if (!this._lifecycle.subscribers.delete(sink)) return;
3120
+ if (this._lifecycle.subscribers.size === 0) this._deactivate();
3121
+ };
3122
+ } finally {
3123
+ exitWave();
3124
+ }
3125
+ }
3126
+ /** External emission toward sinks (state-node push, or async late-emit). One call = one wave. */
3127
+ down(msgs) {
3128
+ this._assertNotReleased("down");
3129
+ enterWave();
3130
+ try {
3131
+ this._down(msgs);
3132
+ } finally {
3133
+ exitWave();
3134
+ }
3135
+ }
3136
+ /**
3137
+ * Emit upstream toward deps — control tiers only (R-ctx-up). `towardDep` (a dep index) routes up
3138
+ * ONE declared edge (R-up-routing directed-up); omitted = broadcast up all deps.
3139
+ */
3140
+ up(msgs, towardDep) {
3141
+ this._assertNotReleased("up");
3142
+ enterWave();
3143
+ try {
3144
+ this._up(msgs, towardDep);
3145
+ } finally {
3146
+ exitWave();
3147
+ }
3148
+ }
3149
+ // ── rewire (R-rewire / D42): intra-graph runtime topology mutation ──
3150
+ /**
3151
+ * Replace this node's deps atomically (surgical, Option-C). Requires an explicit
3152
+ * `fn` (SD-1 fn-deps pairing — user fns read dep input positionally). Kept deps
3153
+ * keep their subscription + per-dep state; only removed deps unsubscribe and only
3154
+ * added deps fresh-subscribe (push-on-subscribe for an added cached dep). The
3155
+ * first-run gate and cache are PRESERVED (R-rewire Q2/Q7). Intra-graph only (D22).
3156
+ */
3157
+ replaceDeps(newDeps, fn) {
3158
+ this._assertNotReleased("replaceDeps");
3159
+ this._rewire(this._dedupDeps(newDeps), fn);
3160
+ }
3161
+ /** Subscribe to one dep (special case of replaceDeps); returns its index. fn required (SD-1). */
3162
+ subscribeDep(depNode, fn) {
3163
+ this._assertNotReleased("subscribeDep");
3164
+ const next = this._slot.deps.includes(depNode) ? [...this._slot.deps] : [...this._slot.deps, depNode];
3165
+ const deferred = this._rewire(next, fn);
3166
+ return deferred ? next.indexOf(depNode) : this._slot.deps.indexOf(depNode);
3167
+ }
3168
+ /** Unsubscribe from one dep (special case of replaceDeps); idempotent if absent (fn swap still applies). */
3169
+ unsubscribeDep(depNode, fn) {
3170
+ this._assertNotReleased("unsubscribeDep");
3171
+ this._rewire(
3172
+ this._slot.deps.filter((d) => d !== depNode),
3173
+ fn
3174
+ );
3175
+ }
3176
+ _requestRewireNext(op) {
3177
+ nodeRequestRewireNext(nodeRuntimeHost(this), op);
3178
+ }
3179
+ _requestUpNext(msgs, towardDep) {
3180
+ nodeRequestUpNext(nodeRuntimeHost(this), msgs, towardDep);
3181
+ }
3182
+ _applyRewireNext(op) {
3183
+ nodeApplyRewireNext(nodeRuntimeHost(this), op);
3184
+ }
3185
+ _dedupDeps(deps) {
3186
+ const seen = /* @__PURE__ */ new Set();
3187
+ const out = [];
3188
+ for (const d of deps)
3189
+ if (!seen.has(d)) {
3190
+ seen.add(d);
3191
+ out.push(d);
3192
+ }
3193
+ return out;
3194
+ }
3195
+ _reachableUpstream(from, target) {
3196
+ const seen = /* @__PURE__ */ new Set();
3197
+ const stack = [from];
3198
+ while (stack.length > 0) {
3199
+ const n = stack.pop();
3200
+ if (n === void 0) continue;
3201
+ if (n === target) return true;
3202
+ if (seen.has(n)) continue;
3203
+ seen.add(n);
3204
+ for (const d of nodeRuntimeHost(n)._slot.deps) stack.push(d);
3205
+ }
3206
+ return false;
3207
+ }
3208
+ _assertRewireDepOwner(dep) {
3209
+ const selfOwner = getNodeOwner(this);
3210
+ const depOwner = getNodeOwner(dep);
3211
+ if (selfOwner !== void 0 && depOwner !== void 0 && selfOwner !== depOwner)
3212
+ throw new Error(
3213
+ "rewire: dep belongs to a different graph; cross-graph deps require a wire bridge (D22 / R-graph-domain)"
3214
+ );
3215
+ }
3216
+ _rewire(newDeps, fn, opts = {}) {
3217
+ return nodeRewire(nodeRuntimeHost(this), newDeps, fn, opts);
3218
+ }
3219
+ // ── activation / deactivation (lazy; R-rom-ram) ──
3220
+ _activate() {
3221
+ nodeActivate(nodeRuntimeHost(this));
3222
+ }
3223
+ _deactivate() {
3224
+ nodeDeactivate(nodeRuntimeHost(this));
3225
+ }
3226
+ _assertNotReleased(op) {
3227
+ if (this._released)
3228
+ throw new Error(`${op}: node has been released from its graph lifecycle (D122)`);
3229
+ }
3230
+ _subscriberCount() {
3231
+ return nodeSubscriberCount(nodeRuntimeHost(this));
3232
+ }
3233
+ _isRuntimeQuiescentForRelease() {
3234
+ return nodeIsRuntimeQuiescentForRelease(nodeRuntimeHost(this));
3235
+ }
3236
+ _releaseRuntime() {
3237
+ nodeReleaseRuntime(nodeRuntimeHost(this));
3238
+ }
3239
+ _resetDepState() {
3240
+ nodeResetDepState(nodeRuntimeHost(this));
3241
+ }
3242
+ _subscribeDepAt(depNode, opts = {}) {
3243
+ nodeSubscribeDepAt(nodeRuntimeHost(this), depNode, opts);
3244
+ }
3245
+ _seedRestoredDepAt(idx, depNode) {
3246
+ nodeSeedRestoredDepAt(nodeRuntimeHost(this), idx, depNode);
3247
+ }
3248
+ _recordDepProjection(idx, delivery) {
3249
+ return nodeRecordDepProjection(nodeRuntimeHost(this), idx, delivery);
3250
+ }
3251
+ _depProjectionHasData(idx) {
3252
+ return nodeDepProjectionHasData(nodeRuntimeHost(this), idx);
3253
+ }
3254
+ _receiveFromDep(idx, msg, delivery) {
3255
+ nodeReceiveFromDep(nodeRuntimeHost(this), idx, msg, delivery);
3256
+ }
3257
+ _releaseDepDirty(idx) {
3258
+ nodeReleaseDepDirty(nodeRuntimeHost(this), idx);
3259
+ }
3260
+ _settleAfterAbsorbedTerminal() {
3261
+ nodeSettleAfterAbsorbedTerminal(nodeRuntimeHost(this));
3262
+ }
3263
+ _markDirty() {
3264
+ nodeMarkDirty(nodeRuntimeHost(this));
3265
+ }
3266
+ _maybeRun() {
3267
+ nodeMaybeRun(nodeRuntimeHost(this));
3268
+ }
3269
+ _settleRewire() {
3270
+ nodeSettleRewire(nodeRuntimeHost(this));
3271
+ }
3272
+ _tryRun() {
3273
+ nodeTryRun(nodeRuntimeHost(this));
3274
+ }
3275
+ _allDepsSettled() {
3276
+ return nodeAllDepsSettled(nodeRuntimeHost(this));
3277
+ }
3278
+ _passthroughEmit() {
3279
+ nodePassthroughEmit(nodeRuntimeHost(this));
3280
+ }
3281
+ _runWave() {
3282
+ nodeRunWave(nodeRuntimeHost(this));
3283
+ }
3284
+ _buildCtx() {
3285
+ return nodeBuildCtx(nodeRuntimeHost(this));
3286
+ }
3287
+ _makeCtx(snapshot) {
3288
+ return nodeMakeCtx(nodeRuntimeHost(this), snapshot);
3289
+ }
3290
+ _refreshCtx(ctx) {
3291
+ nodeRefreshCtx(nodeRuntimeHost(this), ctx);
3292
+ }
3293
+ _makeState() {
3294
+ return nodeMakeState(nodeRuntimeHost(this));
3295
+ }
3296
+ // ── downstream emission pipeline (the unified waist) ──
3297
+ _down(msgs) {
3298
+ nodeDown(nodeRuntimeHost(this), msgs);
3299
+ }
3300
+ _up(msgs, towardDep, route) {
3301
+ nodeUp(nodeRuntimeHost(this), msgs, towardDep, route);
3302
+ }
3303
+ _markDemandRouted(lockId, route) {
3304
+ return nodeMarkDemandRouted(nodeRuntimeHost(this), lockId, route);
3305
+ }
3306
+ _forwardUp(m, towardDep, route) {
3307
+ nodeForwardUp(nodeRuntimeHost(this), m, towardDep, route);
3308
+ }
3309
+ _isPaused() {
3310
+ return nodeIsPaused(nodeRuntimeHost(this));
3311
+ }
3312
+ _hasBoundaryPauseLock() {
3313
+ return nodeHasBoundaryPauseLock(nodeRuntimeHost(this));
3314
+ }
3315
+ _isAsyncPool() {
3316
+ return nodeIsAsyncPool(nodeRuntimeHost(this));
3317
+ }
3318
+ _pauseAcquire(lockId) {
3319
+ nodePauseAcquire(nodeRuntimeHost(this), lockId);
3320
+ }
3321
+ _pauseRelease(lockId) {
3322
+ nodePauseRelease(nodeRuntimeHost(this), lockId);
3323
+ }
3324
+ _onResume() {
3325
+ nodeOnResume(nodeRuntimeHost(this));
3326
+ }
3327
+ _canFireDemand() {
3328
+ return nodeCanFireDemand(nodeRuntimeHost(this));
3329
+ }
3330
+ _deliverPullDemand(demand) {
3331
+ nodeDeliverPullDemand(nodeRuntimeHost(this), demand);
3332
+ }
3333
+ _onDemand(demand) {
3334
+ nodeOnDemand(nodeRuntimeHost(this), demand);
3335
+ }
3336
+ _firePullDemand() {
3337
+ nodeFirePullDemand(nodeRuntimeHost(this));
3338
+ }
3339
+ _fireOwedDemandIfReady() {
3340
+ nodeFireOwedDemandIfReady(nodeRuntimeHost(this));
3341
+ }
3342
+ _shouldBufferOnPause() {
3343
+ return nodeShouldBufferOnPause(nodeRuntimeHost(this));
3344
+ }
3345
+ _invalidate(delivery) {
3346
+ nodeInvalidate(nodeRuntimeHost(this), delivery);
3347
+ }
3348
+ _allDepsTerminal() {
3349
+ return nodeAllDepsTerminal(nodeRuntimeHost(this));
3350
+ }
3351
+ _emitToSubs(msg, delivery) {
3352
+ nodeEmitToSubs(nodeRuntimeHost(this), msg, delivery);
3353
+ }
3354
+ /** R-terminal: resubscribable reset clears terminal + dep state + re-arms the gate. */
3355
+ _resetLifecycle() {
3356
+ nodeResetLifecycle(nodeRuntimeHost(this));
3357
+ }
3358
+ /** Batch commit (R-batch-coalesce): deliver the deferred tier-3 wave now. */
3359
+ __commitBatchedWave(wave) {
3360
+ nodeCommitBatchedWave(nodeRuntimeHost(this), wave);
3361
+ }
3362
+ /** Batch rollback: balance the immediate DIRTY with a RESOLVED so downstream un-dirties. */
3363
+ __rollbackBatched() {
3364
+ nodeRollbackBatched(nodeRuntimeHost(this));
3365
+ }
3366
+ /** B49: enqueue a committed-boundary task on this node's graph-local core. */
3367
+ __deferBoundary(fn, batchToken) {
3368
+ nodeDeferBoundary(nodeRuntimeHost(this), fn, batchToken);
3369
+ }
3370
+ };
3371
+
3372
+ // src/solutions/reactive-layout/types.ts
3373
+ var TEXT_SEGMENTS_MEASUREMENT_KIND = "text-segments";
3374
+ var BLOCKS_MEASUREMENT_KIND = "blocks";
3375
+ var READINESS_MEASUREMENT_KIND = "readiness";
3376
+ var IMAGE_SIZE_MEASUREMENT_KIND = "image-size";
3377
+ var SVG_BOUNDS_MEASUREMENT_KIND = "svg-bounds";
3378
+
3379
+ // src/solutions/reactive-layout/measurements.ts
3380
+ function measurementIssue(code, message, targetId, measurementKind, opts = {}) {
3381
+ return {
3382
+ kind: "issue",
3383
+ code,
3384
+ message,
3385
+ severity: opts.severity ?? "warning",
3386
+ source: opts.source,
3387
+ subjectId: targetId,
3388
+ measurementKind,
3389
+ details: opts.details,
3390
+ metadata: opts.metadata
3391
+ };
3392
+ }
3393
+ function measurementOk(targetId, measurementKind, value, opts = {}) {
3394
+ return {
3395
+ kind: "ok",
3396
+ targetId,
3397
+ measurementKind,
3398
+ value,
3399
+ source: opts.source,
3400
+ metadata: opts.metadata
3401
+ };
3402
+ }
3403
+ function latestMeasurementValue(measurements, targetId, measurementKind) {
3404
+ let value;
3405
+ for (const fact of measurements) {
3406
+ if (fact.kind === "ok" && fact.targetId === targetId && fact.measurementKind === measurementKind) {
3407
+ value = fact.value;
3408
+ }
3409
+ }
3410
+ return value;
3411
+ }
3412
+ function tryMeasureHyphenWidth(adapter, font) {
3413
+ try {
3414
+ return nonNegativeFinite(adapter.measureSegment("-", font).width, 0);
3415
+ } catch {
3416
+ return void 0;
3417
+ }
3418
+ }
3419
+ function validMeasurementSize(size, label) {
3420
+ if (!Number.isFinite(size.width) || !Number.isFinite(size.height) || size.width < 0 || size.height < 0) {
3421
+ throw new Error(`Invalid ${label} measurement size`);
3422
+ }
3423
+ return size;
3424
+ }
3425
+ function textMeasurementFacts(text, font, adapter, cache, segmentAdapter, targetId, source) {
3426
+ try {
3427
+ const segments = analyzeAndMeasure(text, font, adapter, cache, void 0, segmentAdapter);
3428
+ const hyphenWidth = tryMeasureHyphenWidth(adapter, font);
3429
+ const facts = [
3430
+ measurementOk(
3431
+ targetId,
3432
+ TEXT_SEGMENTS_MEASUREMENT_KIND,
3433
+ hyphenWidth === void 0 ? { segments } : { segments, hyphenWidth },
3434
+ { source }
3435
+ )
3436
+ ];
3437
+ if (hyphenWidth === void 0) {
3438
+ facts.push(
3439
+ measurementIssue(
3440
+ "measurement.hyphen.failed",
3441
+ `Hyphen measurement failed for '${targetId}'`,
3442
+ targetId,
3443
+ TEXT_SEGMENTS_MEASUREMENT_KIND,
3444
+ { source, severity: "warning" }
3445
+ )
3446
+ );
3447
+ }
3448
+ return facts;
3449
+ } catch (error) {
3450
+ return [
3451
+ measurementIssue(
3452
+ "measurement.failed",
3453
+ `Text measurement failed for '${targetId}'`,
3454
+ targetId,
3455
+ TEXT_SEGMENTS_MEASUREMENT_KIND,
3456
+ { source, details: error, severity: "error" }
3457
+ )
3458
+ ];
3459
+ }
3460
+ }
3461
+ function inputNode(g, input, fallback, name) {
3462
+ if (input instanceof Node) {
3463
+ return {
3464
+ node: input,
3465
+ set(value) {
3466
+ const maybeState = input;
3467
+ if (typeof maybeState.set !== "function") {
3468
+ throw new TypeError(`reactive-layout input '${name}' is not a writable state node`);
3469
+ }
3470
+ maybeState.set(value);
3471
+ }
3472
+ };
3473
+ }
3474
+ const state = g.state(input ?? fallback, { name });
3475
+ return { node: state, set: (value) => state.set(value) };
3476
+ }
3477
+ function scopedName(scope, local) {
3478
+ return scope === local ? local : `${scope}:${local}`;
3479
+ }
3480
+ function textMeasurementProvider(opts) {
3481
+ const targetId = opts.targetId ?? "text";
3482
+ const name = opts.name ?? `${targetId}-measurements`;
3483
+ const source = opts.source ?? name;
3484
+ const cache = /* @__PURE__ */ new Map();
3485
+ let activeAdapter = null;
3486
+ return opts.graph.node(
3487
+ opts.segmentAdapter ? [opts.text, opts.font, opts.adapter, opts.segmentAdapter] : [opts.text, opts.font, opts.adapter],
3488
+ (ctx) => {
3489
+ const flush = () => {
3490
+ cache.clear();
3491
+ depLatest(ctx, 2).clearCache?.();
3492
+ };
3493
+ ctx.onDeactivation(flush);
3494
+ ctx.onInvalidate(flush);
3495
+ const text = depLatest(ctx, 0);
3496
+ const font = depLatest(ctx, 1);
3497
+ const adapter = depLatest(ctx, 2);
3498
+ if (adapter !== activeAdapter) {
3499
+ cache.clear();
3500
+ activeAdapter = adapter;
3501
+ }
3502
+ const segmentAdapter = opts.segmentAdapter === void 0 ? getDefaultSegmentAdapter() : depLatest(ctx, 3);
3503
+ ctx.down([
3504
+ [
3505
+ "DATA",
3506
+ textMeasurementFacts(text, font, adapter, cache, segmentAdapter, targetId, source)
3507
+ ]
3508
+ ]);
3509
+ },
3510
+ { name }
3511
+ );
3512
+ }
3513
+ function injectedTextMeasurements(opts) {
3514
+ const targetId = opts.targetId ?? "text";
3515
+ const adapter = opts.graph.state(
3516
+ new InjectedMeasureAdapter(opts.measure, { cache: opts.cache }),
3517
+ {
3518
+ name: opts.name ? scopedName(opts.name, "measure-capability") : `${targetId}-measure-capability`
3519
+ }
3520
+ );
3521
+ return textMeasurementProvider({
3522
+ ...opts,
3523
+ adapter,
3524
+ source: opts.source ?? "injectedTextMeasurements"
3525
+ });
3526
+ }
3527
+ function precomputedTextMeasurements(opts) {
3528
+ const targetId = opts.targetId ?? "text";
3529
+ const adapter = opts.graph.state(new PrecomputedMeasureAdapter(opts), {
3530
+ name: opts.name ? scopedName(opts.name, "measure-capability") : `${targetId}-measure-capability`
3531
+ });
3532
+ return textMeasurementProvider({
3533
+ ...opts,
3534
+ adapter,
3535
+ source: opts.source ?? "precomputedTextMeasurements"
3536
+ });
3537
+ }
3538
+ function cellTextMeasurements(opts) {
3539
+ const targetId = opts.targetId ?? "text";
3540
+ const adapter = opts.graph.state(new CellMeasureAdapter(opts), {
3541
+ name: opts.name ? scopedName(opts.name, "measure-capability") : `${targetId}-measure-capability`
3542
+ });
3543
+ return textMeasurementProvider({
3544
+ ...opts,
3545
+ adapter,
3546
+ source: opts.source ?? "cellTextMeasurements"
3547
+ });
3548
+ }
3549
+ function capabilityTextMeasurements(opts) {
3550
+ const targetId = opts.targetId ?? "text";
3551
+ const adapter = opts.graph.node(
3552
+ [opts.capability],
3553
+ (ctx) => {
3554
+ ctx.down([
3555
+ ["DATA", new CapabilityMeasureAdapter(depLatest(ctx, 0))]
3556
+ ]);
3557
+ },
3558
+ {
3559
+ name: opts.name ? scopedName(opts.name, "measure-capability") : `${targetId}-measure-capability`
3560
+ }
3561
+ );
3562
+ return textMeasurementProvider({
3563
+ ...opts,
3564
+ adapter,
3565
+ source: opts.source ?? "capabilityTextMeasurements"
3566
+ });
3567
+ }
3568
+ function readinessTextMeasurements(opts) {
3569
+ const targetId = opts.targetId ?? "text";
3570
+ const name = opts.name ?? `${targetId}-measurements`;
3571
+ const source = opts.source ?? name;
3572
+ const cache = /* @__PURE__ */ new Map();
3573
+ let activeAdapter = null;
3574
+ let activeReadiness = null;
3575
+ const deps = opts.segmentAdapter ? [opts.text, opts.font, opts.adapter, opts.readiness, opts.segmentAdapter] : [opts.text, opts.font, opts.adapter, opts.readiness];
3576
+ return opts.graph.node(
3577
+ deps,
3578
+ (ctx) => {
3579
+ const flush = () => {
3580
+ cache.clear();
3581
+ depLatest(ctx, 2).clearCache?.();
3582
+ };
3583
+ ctx.onDeactivation(flush);
3584
+ ctx.onInvalidate(flush);
3585
+ const text = depLatest(ctx, 0);
3586
+ const font = depLatest(ctx, 1);
3587
+ const adapter = depLatest(ctx, 2);
3588
+ if (adapter !== activeAdapter) {
3589
+ cache.clear();
3590
+ activeAdapter = adapter;
3591
+ }
3592
+ const readiness = depLatest(ctx, 3);
3593
+ if (readiness !== activeReadiness) {
3594
+ cache.clear();
3595
+ activeReadiness = readiness;
3596
+ }
3597
+ if (!readiness.ready) {
3598
+ ctx.down([
3599
+ [
3600
+ "DATA",
3601
+ [
3602
+ measurementIssue(
3603
+ readiness.code ?? "measurement.not-ready",
3604
+ readiness.message ?? `Measurement readiness blocked '${targetId}'`,
3605
+ targetId,
3606
+ TEXT_SEGMENTS_MEASUREMENT_KIND,
3607
+ {
3608
+ source: readiness.source ?? source,
3609
+ details: readiness.details,
3610
+ metadata: readiness.metadata,
3611
+ severity: "warning"
3612
+ }
3613
+ )
3614
+ ]
3615
+ ]
3616
+ ]);
3617
+ return;
3618
+ }
3619
+ const segmentAdapter = opts.segmentAdapter === void 0 ? getDefaultSegmentAdapter() : depLatest(ctx, 4);
3620
+ ctx.down([
3621
+ [
3622
+ "DATA",
3623
+ textMeasurementFacts(text, font, adapter, cache, segmentAdapter, targetId, source)
3624
+ ]
3625
+ ]);
3626
+ },
3627
+ { name }
3628
+ );
3629
+ }
3630
+ function readinessMeasurements(opts) {
3631
+ const targetId = opts.targetId ?? "measurement-readiness";
3632
+ const measurementKind = opts.measurementKind ?? READINESS_MEASUREMENT_KIND;
3633
+ const name = opts.name ?? `${targetId}-measurements`;
3634
+ const source = opts.source ?? name;
3635
+ return opts.graph.node(
3636
+ [opts.readiness],
3637
+ (ctx) => {
3638
+ const readiness = depLatest(ctx, 0);
3639
+ if (!readiness.ready) {
3640
+ ctx.down([
3641
+ [
3642
+ "DATA",
3643
+ [
3644
+ measurementIssue(
3645
+ readiness.code ?? "measurement.not-ready",
3646
+ readiness.message ?? `Measurement readiness blocked '${targetId}'`,
3647
+ targetId,
3648
+ measurementKind,
3649
+ {
3650
+ source: readiness.source ?? source,
3651
+ details: readiness.details,
3652
+ metadata: readiness.metadata,
3653
+ severity: "warning"
3654
+ }
3655
+ )
3656
+ ]
3657
+ ]
3658
+ ]);
3659
+ return;
3660
+ }
3661
+ ctx.down([
3662
+ [
3663
+ "DATA",
3664
+ [
3665
+ measurementOk(targetId, measurementKind, readiness, {
3666
+ source: readiness.source ?? source,
3667
+ metadata: readiness.metadata
3668
+ })
3669
+ ]
3670
+ ]
3671
+ ]);
3672
+ },
3673
+ { name }
3674
+ );
3675
+ }
3676
+ function imageSizeMeasurements(opts) {
3677
+ const measurementKind = opts.measurementKind ?? IMAGE_SIZE_MEASUREMENT_KIND;
3678
+ const name = opts.name ?? "image-size-measurements";
3679
+ const source = opts.source ?? name;
3680
+ return opts.graph.node(
3681
+ [opts.images, opts.measurer],
3682
+ (ctx) => {
3683
+ const images = depLatest(ctx, 0);
3684
+ const measurer = depLatest(ctx, 1);
3685
+ const facts = [];
3686
+ for (let i = 0; i < images.length; i += 1) {
3687
+ const image = images[i];
3688
+ const subjectId = image?.id ?? image?.src ?? `image:${i}`;
3689
+ try {
3690
+ if (image === void 0) throw new Error(`Missing image target at index ${i}`);
3691
+ facts.push(
3692
+ measurementOk(
3693
+ subjectId,
3694
+ measurementKind,
3695
+ validMeasurementSize(measurer.measureImage(image.src), "image"),
3696
+ {
3697
+ source,
3698
+ metadata: image.metadata
3699
+ }
3700
+ )
3701
+ );
3702
+ } catch (error) {
3703
+ facts.push(
3704
+ measurementIssue(
3705
+ "measurement.image-size.failed",
3706
+ `Image size measurement failed for '${subjectId}'`,
3707
+ subjectId,
3708
+ measurementKind,
3709
+ {
3710
+ source,
3711
+ details: { error, index: i, src: image?.src },
3712
+ metadata: image?.metadata,
3713
+ severity: "error"
3714
+ }
3715
+ )
3716
+ );
3717
+ }
3718
+ }
3719
+ ctx.down([["DATA", facts]]);
3720
+ },
3721
+ { name }
3722
+ );
3723
+ }
3724
+ function svgBoundsMeasurements(opts) {
3725
+ const measurementKind = opts.measurementKind ?? SVG_BOUNDS_MEASUREMENT_KIND;
3726
+ const name = opts.name ?? "svg-bounds-measurements";
3727
+ const source = opts.source ?? name;
3728
+ return opts.graph.node(
3729
+ [opts.svgs, opts.measurer],
3730
+ (ctx) => {
3731
+ const svgs = depLatest(ctx, 0);
3732
+ const measurer = depLatest(ctx, 1);
3733
+ const facts = [];
3734
+ for (let i = 0; i < svgs.length; i += 1) {
3735
+ const svg = svgs[i];
3736
+ const subjectId = svg?.id ?? `svg:${i}`;
3737
+ try {
3738
+ if (svg === void 0) throw new Error(`Missing SVG target at index ${i}`);
3739
+ facts.push(
3740
+ measurementOk(
3741
+ subjectId,
3742
+ measurementKind,
3743
+ validMeasurementSize(measurer.measureSvg(svg.svg), "SVG"),
3744
+ {
3745
+ source,
3746
+ metadata: svg.metadata
3747
+ }
3748
+ )
3749
+ );
3750
+ } catch (error) {
3751
+ facts.push(
3752
+ measurementIssue(
3753
+ "measurement.svg-bounds.failed",
3754
+ `SVG bounds measurement failed for '${subjectId}'`,
3755
+ subjectId,
3756
+ measurementKind,
3757
+ {
3758
+ source,
3759
+ details: { error, index: i },
3760
+ metadata: svg?.metadata,
3761
+ severity: "error"
3762
+ }
3763
+ )
3764
+ );
3765
+ }
3766
+ }
3767
+ ctx.down([["DATA", facts]]);
3768
+ },
3769
+ { name }
3770
+ );
3771
+ }
3772
+ function mergeMeasurements(opts) {
3773
+ const sources = [...opts.sources];
3774
+ return opts.graph.node(
3775
+ sources,
3776
+ (ctx) => {
3777
+ const facts = [];
3778
+ for (let i = 0; i < sources.length; i += 1) {
3779
+ facts.push(...depLatest(ctx, i));
3780
+ }
3781
+ ctx.down([["DATA", facts]]);
3782
+ },
3783
+ { name: opts.name ?? "measurements" }
3784
+ );
3785
+ }
3786
+ function blockAdaptersProvider(opts) {
3787
+ const deps = [];
3788
+ const positions = {};
3789
+ if (opts.text) {
3790
+ positions.text = deps.length;
3791
+ deps.push(opts.text);
3792
+ }
3793
+ if (opts.svg) {
3794
+ positions.svg = deps.length;
3795
+ deps.push(opts.svg);
3796
+ }
3797
+ if (opts.image) {
3798
+ positions.image = deps.length;
3799
+ deps.push(opts.image);
3800
+ }
3801
+ return opts.graph.node(
3802
+ deps,
3803
+ (ctx) => {
3804
+ const adapters = {
3805
+ text: positions.text === void 0 ? void 0 : depLatest(ctx, positions.text),
3806
+ svg: positions.svg === void 0 ? void 0 : depLatest(ctx, positions.svg),
3807
+ image: positions.image === void 0 ? void 0 : depLatest(ctx, positions.image)
3808
+ };
3809
+ ctx.down([["DATA", adapters]]);
3810
+ },
3811
+ { name: opts.name ?? "block-adapters" }
3812
+ );
3813
+ }
3814
+ function blockMeasurementProvider(opts) {
3815
+ const targetId = opts.targetId ?? "blocks";
3816
+ const name = opts.name ?? `${targetId}-measurements`;
3817
+ const source = opts.source ?? name;
3818
+ const cache = /* @__PURE__ */ new Map();
3819
+ let activeTextAdapter;
3820
+ const deps = [opts.blocks, opts.maxWidth, opts.adapters];
3821
+ if (opts.font) deps.push(opts.font);
3822
+ if (opts.lineHeight) deps.push(opts.lineHeight);
3823
+ if (opts.segmentAdapter) deps.push(opts.segmentAdapter);
3824
+ return opts.graph.node(
3825
+ deps,
3826
+ (ctx) => {
3827
+ const flush = () => {
3828
+ cache.clear();
3829
+ const adapters = depLatest(ctx, 2);
3830
+ adapters.text?.clearCache?.();
3831
+ };
3832
+ ctx.onDeactivation(flush);
3833
+ ctx.onInvalidate(flush);
3834
+ try {
3835
+ const blocks = depLatest(ctx, 0);
3836
+ const maxWidth = nonNegativeFinite(depLatest(ctx, 1), 0);
3837
+ const adapters = depLatest(ctx, 2);
3838
+ if (adapters.text !== activeTextAdapter) {
3839
+ cache.clear();
3840
+ activeTextAdapter = adapters.text;
3841
+ }
3842
+ let depIndex = 3;
3843
+ const font = opts.font ? depLatest(ctx, depIndex++) : void 0;
3844
+ const lineHeight = opts.lineHeight ? nonNegativeFinite(depLatest(ctx, depIndex++), 0) : void 0;
3845
+ const segmentAdapter = opts.segmentAdapter ? depLatest(ctx, depIndex) : getDefaultSegmentAdapter();
3846
+ const measured = [];
3847
+ const issues = [];
3848
+ for (let i = 0; i < blocks.length; i += 1) {
3849
+ const block = blocks[i];
3850
+ const subjectId = block?.id ?? `${targetId}:${i}`;
3851
+ try {
3852
+ if (block === void 0) {
3853
+ throw new Error(`Missing content block at index ${i}`);
3854
+ }
3855
+ const blockFont = block.kind === "text" ? block.font ?? font ?? "16px sans-serif" : void 0;
3856
+ const hyphenWidth = block.kind === "text" && adapters.text ? tryMeasureHyphenWidth(adapters.text, blockFont ?? "16px sans-serif") : void 0;
3857
+ measured.push(
3858
+ measureBlock(block, {
3859
+ adapters,
3860
+ font,
3861
+ hyphenWidth,
3862
+ lineHeight,
3863
+ maxWidth,
3864
+ cache,
3865
+ segmentAdapter
3866
+ })
3867
+ );
3868
+ if (block.kind === "text" && adapters.text) {
3869
+ if (hyphenWidth === void 0) {
3870
+ issues.push(
3871
+ measurementIssue(
3872
+ "measurement.hyphen.failed",
3873
+ `Hyphen measurement failed for '${subjectId}'`,
3874
+ subjectId,
3875
+ BLOCKS_MEASUREMENT_KIND,
3876
+ {
3877
+ source,
3878
+ details: { targetId, index: i },
3879
+ severity: "warning"
3880
+ }
3881
+ )
3882
+ );
3883
+ }
3884
+ }
3885
+ } catch (error) {
3886
+ issues.push(
3887
+ measurementIssue(
3888
+ "measurement.block.failed",
3889
+ `Block measurement failed for '${subjectId}'`,
3890
+ subjectId,
3891
+ BLOCKS_MEASUREMENT_KIND,
3892
+ {
3893
+ source,
3894
+ details: { error, targetId, index: i, blockKind: block?.kind },
3895
+ severity: "error"
3896
+ }
3897
+ )
3898
+ );
3899
+ }
3900
+ }
3901
+ ctx.down([
3902
+ [
3903
+ "DATA",
3904
+ [
3905
+ measurementOk(
3906
+ targetId,
3907
+ BLOCKS_MEASUREMENT_KIND,
3908
+ { blocks: measured },
3909
+ { source }
3910
+ ),
3911
+ ...issues
3912
+ ]
3913
+ ]
3914
+ ]);
3915
+ } catch (error) {
3916
+ ctx.down([
3917
+ [
3918
+ "DATA",
3919
+ [
3920
+ measurementIssue(
3921
+ "measurement.failed",
3922
+ `Block measurement failed for '${targetId}'`,
3923
+ targetId,
3924
+ BLOCKS_MEASUREMENT_KIND,
3925
+ { source, details: error, severity: "error" }
3926
+ )
3927
+ ]
3928
+ ]
3929
+ ]);
3930
+ }
3931
+ },
3932
+ { name }
3933
+ );
3934
+ }
3935
+
3936
+ // src/solutions/reactive-layout/block.ts
3937
+ function measureBlock(block, opts) {
3938
+ const maxWidth = nonNegativeFinite(opts.maxWidth ?? 800, 800);
3939
+ const marginTop = nonNegativeFinite(block.marginTop ?? 0, 0);
3940
+ const marginBottom = nonNegativeFinite(block.marginBottom ?? 0, 0);
3941
+ if (block.kind === "text") {
3942
+ const adapter = resolveTextAdapter(opts);
3943
+ const font = block.font ?? opts.font ?? "16px sans-serif";
3944
+ const lineHeight = positiveFinite(block.lineHeight ?? opts.lineHeight ?? 20, 20);
3945
+ const cache = opts.cache ?? /* @__PURE__ */ new Map();
3946
+ const width = blockMaxWidth(block.maxWidth, maxWidth);
3947
+ const segments = analyzeAndMeasure(
3948
+ block.text,
3949
+ font,
3950
+ adapter,
3951
+ cache,
3952
+ void 0,
3953
+ opts.segmentAdapter
3954
+ );
3955
+ const hyphenWidth = Object.hasOwn(opts, "hyphenWidth") ? opts.hyphenWidth : tryMeasureHyphenWidth(adapter, font);
3956
+ const lineBreaks = computeLineBreaks(segments, width, {
3957
+ hyphenWidth,
3958
+ segmentAdapter: opts.segmentAdapter
3959
+ });
3960
+ const charPositions = computeCharPositions(
3961
+ lineBreaks,
3962
+ segments,
3963
+ lineHeight,
3964
+ opts.segmentAdapter
3965
+ );
3966
+ return {
3967
+ block,
3968
+ kind: block.kind,
3969
+ id: block.id,
3970
+ width: lineBreaks.lines.reduce((acc, line) => Math.max(acc, line.width), 0),
3971
+ height: lineBreaks.lineCount * lineHeight,
3972
+ marginTop,
3973
+ marginBottom,
3974
+ segments,
3975
+ lineBreaks,
3976
+ charPositions
3977
+ };
3978
+ }
3979
+ if (block.kind === "image") {
3980
+ const explicit2 = block.width !== void 0 && block.height !== void 0 ? { width: clampDimension(block.width), height: clampDimension(block.height) } : opts.adapters?.image?.measureImage(block.src);
3981
+ if (!explicit2) throw new Error("Image blocks require width/height or an ImageMeasurer");
3982
+ const size2 = fitSize(explicit2, blockMaxWidth(block.maxWidth, maxWidth));
3983
+ return {
3984
+ block,
3985
+ kind: block.kind,
3986
+ id: block.id,
3987
+ width: size2.width,
3988
+ height: size2.height,
3989
+ marginTop,
3990
+ marginBottom
3991
+ };
3992
+ }
3993
+ const explicit = block.width !== void 0 && block.height !== void 0 ? { width: clampDimension(block.width), height: clampDimension(block.height) } : opts.adapters?.svg?.measureSvg(block.svg);
3994
+ if (!explicit) throw new Error("SVG blocks require width/height or a SvgMeasurer");
3995
+ const size = fitSize(explicit, blockMaxWidth(block.maxWidth, maxWidth));
3996
+ return {
3997
+ block,
3998
+ kind: block.kind,
3999
+ id: block.id,
4000
+ width: size.width,
4001
+ height: size.height,
4002
+ marginTop,
4003
+ marginBottom
4004
+ };
4005
+ }
4006
+ function measureBlocks(blocks, opts) {
4007
+ const cache = opts.cache ?? /* @__PURE__ */ new Map();
4008
+ return blocks.map((block) => measureBlock(block, { ...opts, cache }));
4009
+ }
4010
+ function computeBlockFlow(blocks, gap = 0) {
4011
+ const spacing = nonNegativeFinite(gap, 0);
4012
+ let y = 0;
4013
+ return blocks.map((block) => {
4014
+ y += block.marginTop;
4015
+ const positioned = { ...block, x: 0, y };
4016
+ y += block.height + block.marginBottom + spacing;
4017
+ return positioned;
4018
+ });
4019
+ }
4020
+ function computeTotalHeight(blocks) {
4021
+ if (blocks.length === 0) return 0;
4022
+ let bottom = 0;
4023
+ for (const block of blocks) {
4024
+ bottom = Math.max(bottom, block.y + block.height + block.marginBottom);
4025
+ }
4026
+ return bottom;
4027
+ }
4028
+
4029
+ // src/solutions/reactive-layout/flow.ts
4030
+ function columnGeometry(container, columns) {
4031
+ const paddingX = nonNegativeFinite(container.paddingX ?? 0, 0);
4032
+ const paddingY = nonNegativeFinite(container.paddingY ?? 0, 0);
4033
+ const count = Math.max(1, Math.floor(nonNegativeFinite(columns?.count ?? 1, 1)));
4034
+ const gap = nonNegativeFinite(columns?.gap ?? 0, 0);
4035
+ const width = nonNegativeFinite(container.width, 0);
4036
+ const height = nonNegativeFinite(container.height, 0);
4037
+ const innerWidth = Math.max(0, width - paddingX * 2 - gap * (count - 1));
4038
+ const columnWidth = count > 0 ? innerWidth / count : 0;
4039
+ return { paddingX, paddingY, count, gap, width, height, columnWidth };
4040
+ }
4041
+ function sanitizeFlowContainer(container) {
4042
+ return {
4043
+ width: nonNegativeFinite(container.width, 0),
4044
+ height: nonNegativeFinite(container.height, 0),
4045
+ paddingX: container.paddingX === void 0 ? void 0 : nonNegativeFinite(container.paddingX, 0),
4046
+ paddingY: container.paddingY === void 0 ? void 0 : nonNegativeFinite(container.paddingY, 0)
4047
+ };
4048
+ }
4049
+ function sanitizeFlowColumns(columns) {
4050
+ return {
4051
+ count: columns.count === void 0 ? void 0 : Math.max(1, Math.floor(nonNegativeFinite(columns.count, 1))),
4052
+ gap: columns.gap === void 0 ? void 0 : nonNegativeFinite(columns.gap, 0)
4053
+ };
4054
+ }
4055
+ function sanitizeObstacles(obstacles) {
4056
+ return obstacles.map((obstacle) => {
4057
+ if (obstacle.kind === "circle") {
4058
+ return {
4059
+ kind: obstacle.kind,
4060
+ cx: finiteNumber(obstacle.cx, 0),
4061
+ cy: finiteNumber(obstacle.cy, 0),
4062
+ r: nonNegativeFinite(obstacle.r, 0)
4063
+ };
4064
+ }
4065
+ return {
4066
+ kind: obstacle.kind,
4067
+ x: finiteNumber(obstacle.x, 0),
4068
+ y: finiteNumber(obstacle.y, 0),
4069
+ width: nonNegativeFinite(obstacle.width, 0),
4070
+ height: nonNegativeFinite(obstacle.height, 0)
4071
+ };
4072
+ });
4073
+ }
4074
+ function circleIntervalForBand(obstacle, bandTop, bandBottom) {
4075
+ const radius = nonNegativeFinite(obstacle.r, 0);
4076
+ const centerY = obstacle.cy;
4077
+ const nearestY = Math.max(bandTop, Math.min(centerY, bandBottom));
4078
+ const dy = nearestY - centerY;
4079
+ if (Math.abs(dy) > radius) return null;
4080
+ const dx = Math.sqrt(Math.max(0, radius * radius - dy * dy));
4081
+ return { left: obstacle.cx - dx, right: obstacle.cx + dx };
4082
+ }
4083
+ function rectIntervalForBand(obstacle, bandTop, bandBottom) {
4084
+ const left = obstacle.x;
4085
+ const right = obstacle.x + nonNegativeFinite(obstacle.width, 0);
4086
+ const top = obstacle.y;
4087
+ const bottom = obstacle.y + nonNegativeFinite(obstacle.height, 0);
4088
+ if (bottom <= bandTop || top >= bandBottom || right <= left) return null;
4089
+ return { left, right };
4090
+ }
4091
+ function blockedIntervalsForBand(obstacles, bandTop, bandBottom) {
4092
+ const intervals = [];
4093
+ for (const obstacle of obstacles) {
4094
+ const interval = obstacle.kind === "circle" ? circleIntervalForBand(obstacle, bandTop, bandBottom) : rectIntervalForBand(obstacle, bandTop, bandBottom);
4095
+ if (interval) intervals.push(interval);
4096
+ }
4097
+ return intervals.sort((a, b) => a.left - b.left);
4098
+ }
4099
+ function computeFlowLines(segments, opts) {
4100
+ const geometry = columnGeometry(opts.container, opts.columns);
4101
+ const lineHeight = positiveFinite(opts.lineHeight, 20);
4102
+ const minSlotWidth = nonNegativeFinite(opts.minSlotWidth ?? 0, 0);
4103
+ const obstacles = opts.obstacles ?? [];
4104
+ const segmentAdapter = opts.segmentAdapter ?? getDefaultSegmentAdapter();
4105
+ const lines = [];
4106
+ let cursor = { segmentIndex: 0, graphemeIndex: 0 };
4107
+ const contentBottom = Math.max(geometry.paddingY, geometry.height - geometry.paddingY);
4108
+ for (let columnIndex = 0; columnIndex < geometry.count; columnIndex += 1) {
4109
+ const columnLeft = geometry.paddingX + columnIndex * (geometry.columnWidth + geometry.gap);
4110
+ const columnRight = columnLeft + geometry.columnWidth;
4111
+ for (let y = geometry.paddingY; y + lineHeight <= contentBottom + 1e-3 && cursor.segmentIndex < segments.length; y += lineHeight) {
4112
+ const blocked = blockedIntervalsForBand(obstacles, y, y + lineHeight);
4113
+ const slots = carveTextLineSlots(
4114
+ { left: columnLeft, right: columnRight },
4115
+ blocked,
4116
+ Math.max(minSlotWidth, 1e-6)
4117
+ );
4118
+ for (const slot of slots) {
4119
+ if (cursor.segmentIndex >= segments.length) break;
4120
+ const slotWidth = slot.right - slot.left;
4121
+ const next = layoutNextLine(segments, cursor, slotWidth, {
4122
+ hyphenWidth: opts.hyphenWidth,
4123
+ segmentAdapter
4124
+ });
4125
+ if (next === null) {
4126
+ cursor = { segmentIndex: segments.length, graphemeIndex: 0 };
4127
+ break;
4128
+ }
4129
+ if (next.end.segmentIndex === cursor.segmentIndex && next.end.graphemeIndex === cursor.graphemeIndex) {
4130
+ break;
4131
+ }
4132
+ cursor = next.end;
4133
+ if (next.text.length === 0 && next.width === 0) break;
4134
+ lines.push({
4135
+ text: next.text,
4136
+ width: next.width,
4137
+ startSegment: next.start.segmentIndex,
4138
+ startGrapheme: next.start.graphemeIndex,
4139
+ endSegment: next.end.segmentIndex,
4140
+ endGrapheme: next.end.graphemeIndex,
4141
+ x: slot.left,
4142
+ y,
4143
+ slotWidth,
4144
+ columnIndex
4145
+ });
4146
+ }
4147
+ }
4148
+ }
4149
+ return {
4150
+ lines,
4151
+ cursor,
4152
+ done: cursor.segmentIndex >= segments.length
4153
+ };
4154
+ }
4155
+
4156
+ // src/solutions/reactive-layout/bundles.ts
4157
+ function reactiveLayout(opts) {
4158
+ const { measurements, segmentAdapter: segmentAdapterOpt, name = "reactive-layout" } = opts;
4159
+ const targetId = opts.targetId ?? "text";
4160
+ const segAdapter = segmentAdapterOpt ?? getDefaultSegmentAdapter();
4161
+ const g = opts.graph;
4162
+ const lineHeightInput = inputNode(
4163
+ g,
4164
+ opts.lineHeight instanceof Node ? opts.lineHeight : nonNegativeFinite(opts.lineHeight ?? 20, 20),
4165
+ nonNegativeFinite(20, 20),
4166
+ scopedName(name, "line-height")
4167
+ );
4168
+ const maxWidthInput = inputNode(
4169
+ g,
4170
+ opts.maxWidth instanceof Node ? opts.maxWidth : nonNegativeFinite(opts.maxWidth ?? 800, 800),
4171
+ nonNegativeFinite(800, 800),
4172
+ scopedName(name, "max-width")
4173
+ );
4174
+ const segments = g.node(
4175
+ [measurements],
4176
+ (ctx) => {
4177
+ try {
4178
+ const measured = latestMeasurementValue(
4179
+ depLatest(ctx, 0),
4180
+ targetId,
4181
+ TEXT_SEGMENTS_MEASUREMENT_KIND
4182
+ );
4183
+ ctx.down([["DATA", measured?.segments ?? []]]);
4184
+ } catch (error) {
4185
+ emitLayoutError(ctx, error, "reactiveLayout segments failed");
4186
+ }
4187
+ },
4188
+ { name: scopedName(name, "segments") }
4189
+ );
4190
+ const lineBreaks = g.node(
4191
+ [segments, maxWidthInput.node, measurements],
4192
+ (ctx) => {
4193
+ try {
4194
+ const measured = latestMeasurementValue(
4195
+ depLatest(ctx, 2),
4196
+ targetId,
4197
+ TEXT_SEGMENTS_MEASUREMENT_KIND
4198
+ );
4199
+ const computed = computeLineBreaks(
4200
+ depLatest(ctx, 0),
4201
+ nonNegativeFinite(depLatest(ctx, 1), 0),
4202
+ { hyphenWidth: measured?.hyphenWidth, segmentAdapter: segAdapter }
4203
+ );
4204
+ ctx.down([["DATA", computed]]);
4205
+ } catch (error) {
4206
+ emitLayoutError(ctx, error, "reactiveLayout line breaks failed");
4207
+ }
4208
+ },
4209
+ { name: scopedName(name, "line-breaks") }
4210
+ );
4211
+ const height = g.node(
4212
+ [lineBreaks, lineHeightInput.node],
4213
+ (ctx) => {
4214
+ try {
4215
+ const lines = depLatest(ctx, 0);
4216
+ const lineHeight = nonNegativeFinite(depLatest(ctx, 1), 0);
4217
+ ctx.down([["DATA", lines.lineCount * lineHeight]]);
4218
+ } catch (error) {
4219
+ emitLayoutError(ctx, error, "reactiveLayout height failed");
4220
+ }
4221
+ },
4222
+ { name: scopedName(name, "height") }
4223
+ );
4224
+ const charPositions = g.node(
4225
+ [lineBreaks, segments, lineHeightInput.node],
4226
+ (ctx) => {
4227
+ try {
4228
+ const positions = computeCharPositions(
4229
+ depLatest(ctx, 0),
4230
+ depLatest(ctx, 1),
4231
+ nonNegativeFinite(depLatest(ctx, 2), 0),
4232
+ segAdapter
4233
+ );
4234
+ ctx.down([["DATA", positions]]);
4235
+ } catch (error) {
4236
+ emitLayoutError(ctx, error, "reactiveLayout char positions failed");
4237
+ }
4238
+ },
4239
+ { name: scopedName(name, "char-positions") }
4240
+ );
4241
+ return {
4242
+ graph: g,
4243
+ input: {
4244
+ lineHeight: lineHeightInput.node,
4245
+ maxWidth: maxWidthInput.node,
4246
+ measurements
4247
+ },
4248
+ setLineHeight(lineHeight) {
4249
+ lineHeightInput.set(nonNegativeFinite(lineHeight, 0));
4250
+ },
4251
+ setMaxWidth(maxWidth) {
4252
+ maxWidthInput.set(nonNegativeFinite(maxWidth, 0));
4253
+ },
4254
+ segments,
4255
+ lineBreaks,
4256
+ height,
4257
+ charPositions
4258
+ };
4259
+ }
4260
+ function reactiveBlockLayout(opts) {
4261
+ const { measurements, name = "reactive-block-layout" } = opts;
4262
+ const targetId = opts.targetId ?? "blocks";
4263
+ const g = opts.graph;
4264
+ const gapInput = inputNode(
4265
+ g,
4266
+ opts.gap instanceof Node ? opts.gap : nonNegativeFinite(opts.gap ?? 0, 0),
4267
+ nonNegativeFinite(0, 0),
4268
+ scopedName(name, "gap")
4269
+ );
4270
+ const measuredBlocks = g.node(
4271
+ [measurements],
4272
+ (ctx) => {
4273
+ try {
4274
+ const measured = latestMeasurementValue(
4275
+ depLatest(ctx, 0),
4276
+ targetId,
4277
+ BLOCKS_MEASUREMENT_KIND
4278
+ );
4279
+ ctx.down([["DATA", measured?.blocks ?? []]]);
4280
+ } catch (error) {
4281
+ emitLayoutError(ctx, error, "reactiveBlockLayout measured-blocks failed");
4282
+ }
4283
+ },
4284
+ { name: scopedName(name, "measured-blocks") }
4285
+ );
4286
+ const blockFlow = g.node(
4287
+ [measuredBlocks, gapInput.node],
4288
+ (ctx) => {
4289
+ try {
4290
+ const positioned = computeBlockFlow(
4291
+ depLatest(ctx, 0),
4292
+ nonNegativeFinite(depLatest(ctx, 1), 0)
4293
+ );
4294
+ ctx.down([["DATA", positioned]]);
4295
+ } catch (error) {
4296
+ emitLayoutError(ctx, error, "reactiveBlockLayout flow failed");
4297
+ }
4298
+ },
4299
+ { name: scopedName(name, "block-flow") }
4300
+ );
4301
+ const totalHeight = g.node(
4302
+ [blockFlow],
4303
+ (ctx) => {
4304
+ try {
4305
+ ctx.down([["DATA", computeTotalHeight(depLatest(ctx, 0))]]);
4306
+ } catch (error) {
4307
+ emitLayoutError(ctx, error, "reactiveBlockLayout total height failed");
4308
+ }
4309
+ },
4310
+ { name: scopedName(name, "total-height") }
4311
+ );
4312
+ return {
4313
+ graph: g,
4314
+ input: {
4315
+ gap: gapInput.node,
4316
+ measurements
4317
+ },
4318
+ setGap(gap) {
4319
+ gapInput.set(nonNegativeFinite(gap, 0));
4320
+ },
4321
+ measuredBlocks,
4322
+ blockFlow,
4323
+ totalHeight
4324
+ };
4325
+ }
4326
+ function reactiveFlowLayout(opts) {
4327
+ const { measurements, segmentAdapter: segmentAdapterOpt, name = "reactive-flow-layout" } = opts;
4328
+ const targetId = opts.targetId ?? "text";
4329
+ const segAdapter = segmentAdapterOpt ?? getDefaultSegmentAdapter();
4330
+ const g = opts.graph;
4331
+ const lineHeightInput = inputNode(
4332
+ g,
4333
+ opts.lineHeight instanceof Node ? opts.lineHeight : nonNegativeFinite(opts.lineHeight ?? 20, 20),
4334
+ nonNegativeFinite(20, 20),
4335
+ scopedName(name, "line-height")
4336
+ );
4337
+ const containerInput = inputNode(
4338
+ g,
4339
+ opts.container,
4340
+ { width: 800, height: 600 },
4341
+ scopedName(name, "container")
4342
+ );
4343
+ const columnsInput = inputNode(
4344
+ g,
4345
+ opts.columns,
4346
+ { count: 1, gap: 0 },
4347
+ scopedName(name, "columns")
4348
+ );
4349
+ const obstaclesInput = inputNode(g, opts.obstacles, [], scopedName(name, "obstacles"));
4350
+ const segments = g.node(
4351
+ [measurements],
4352
+ (ctx) => {
4353
+ try {
4354
+ const measured = latestMeasurementValue(
4355
+ depLatest(ctx, 0),
4356
+ targetId,
4357
+ TEXT_SEGMENTS_MEASUREMENT_KIND
4358
+ );
4359
+ ctx.down([["DATA", measured?.segments ?? []]]);
4360
+ } catch (error) {
4361
+ emitLayoutError(ctx, error, "reactiveFlowLayout segments failed");
4362
+ }
4363
+ },
4364
+ { name: scopedName(name, "segments") }
4365
+ );
4366
+ const flowLines = g.node(
4367
+ [
4368
+ segments,
4369
+ lineHeightInput.node,
4370
+ containerInput.node,
4371
+ columnsInput.node,
4372
+ obstaclesInput.node,
4373
+ measurements
4374
+ ],
4375
+ (ctx) => {
4376
+ try {
4377
+ const measured = latestMeasurementValue(
4378
+ depLatest(ctx, 5),
4379
+ targetId,
4380
+ TEXT_SEGMENTS_MEASUREMENT_KIND
4381
+ );
4382
+ const computed = computeFlowLines(depLatest(ctx, 0), {
4383
+ lineHeight: nonNegativeFinite(depLatest(ctx, 1), 0),
4384
+ container: sanitizeFlowContainer(depLatest(ctx, 2)),
4385
+ columns: sanitizeFlowColumns(depLatest(ctx, 3)),
4386
+ obstacles: sanitizeObstacles(depLatest(ctx, 4)),
4387
+ minSlotWidth: nonNegativeFinite(opts.minSlotWidth ?? 0, 0),
4388
+ hyphenWidth: measured?.hyphenWidth,
4389
+ segmentAdapter: segAdapter
4390
+ });
4391
+ ctx.down([["DATA", computed]]);
4392
+ } catch (error) {
4393
+ emitLayoutError(ctx, error, "reactiveFlowLayout flow lines failed");
4394
+ }
4395
+ },
4396
+ { name: scopedName(name, "flow-lines") }
4397
+ );
4398
+ return {
4399
+ graph: g,
4400
+ input: {
4401
+ lineHeight: lineHeightInput.node,
4402
+ container: containerInput.node,
4403
+ columns: columnsInput.node,
4404
+ obstacles: obstaclesInput.node,
4405
+ measurements
4406
+ },
4407
+ setLineHeight(lineHeight) {
4408
+ lineHeightInput.set(nonNegativeFinite(lineHeight, 0));
4409
+ },
4410
+ setContainer(container) {
4411
+ containerInput.set(container);
4412
+ },
4413
+ setColumns(columns) {
4414
+ columnsInput.set(columns);
4415
+ },
4416
+ setObstacles(obstacles) {
4417
+ obstaclesInput.set(obstacles);
4418
+ },
4419
+ segments,
4420
+ flowLines
4421
+ };
4422
+ }
4423
+ // Annotate the CommonJS export names for ESM import in node:
4424
+ 0 && (module.exports = {
4425
+ BLOCKS_MEASUREMENT_KIND,
4426
+ CapabilityMeasureAdapter,
4427
+ CellMeasureAdapter,
4428
+ IMAGE_SIZE_MEASUREMENT_KIND,
4429
+ ImageSizeAdapter,
4430
+ InjectedMeasureAdapter,
4431
+ PrecomputedMeasureAdapter,
4432
+ READINESS_MEASUREMENT_KIND,
4433
+ SVG_BOUNDS_MEASUREMENT_KIND,
4434
+ SvgBoundsAdapter,
4435
+ TEXT_SEGMENTS_MEASUREMENT_KIND,
4436
+ analyzeAndMeasure,
4437
+ blockAdaptersProvider,
4438
+ blockMaxWidth,
4439
+ blockMeasurementProvider,
4440
+ blockedIntervalsForBand,
4441
+ capabilityTextMeasurements,
4442
+ carveTextLineSlots,
4443
+ cellTextMeasurements,
4444
+ circleIntervalForBand,
4445
+ clampDimension,
4446
+ columnGeometry,
4447
+ computeBlockFlow,
4448
+ computeCharPositions,
4449
+ computeFlowLines,
4450
+ computeLineBreaks,
4451
+ computeTotalHeight,
4452
+ createDefaultSegmentAdapter,
4453
+ emitLayoutError,
4454
+ finiteNumber,
4455
+ fitSize,
4456
+ getDefaultSegmentAdapter,
4457
+ imageSizeMeasurements,
4458
+ injectedTextMeasurements,
4459
+ inputNode,
4460
+ isCJK,
4461
+ kinsokuStart,
4462
+ latestMeasurementValue,
4463
+ layoutNextLine,
4464
+ leftStickyPunctuation,
4465
+ measureBlock,
4466
+ measureBlocks,
4467
+ measuredWidth,
4468
+ measurementIssue,
4469
+ measurementOk,
4470
+ mergeMeasurements,
4471
+ metricKey,
4472
+ nonNegativeFinite,
4473
+ normalizeWhitespace,
4474
+ positiveFinite,
4475
+ precomputedTextMeasurements,
4476
+ reactiveBlockLayout,
4477
+ reactiveFlowLayout,
4478
+ reactiveLayout,
4479
+ readinessMeasurements,
4480
+ readinessTextMeasurements,
4481
+ rectIntervalForBand,
4482
+ resolveTextAdapter,
4483
+ sanitizeFlowColumns,
4484
+ sanitizeFlowContainer,
4485
+ sanitizeObstacles,
4486
+ scopedName,
4487
+ segmentText,
4488
+ svgBoundsMeasurements,
4489
+ textMeasurementFacts,
4490
+ textMeasurementProvider,
4491
+ tryMeasureHyphenWidth,
4492
+ validMeasurementSize
4493
+ });
4494
+ //# sourceMappingURL=index.cjs.map