@graphrefly/ts 0.0.0 → 0.0.1

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