@graphrefly/ts 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (210) hide show
  1. package/LICENSE +21 -0
  2. package/dist/adapters/index.cjs +9015 -0
  3. package/dist/adapters/index.cjs.map +1 -0
  4. package/dist/adapters/index.d.cts +678 -0
  5. package/dist/adapters/index.d.ts +678 -0
  6. package/dist/adapters/index.js +2894 -0
  7. package/dist/adapters/index.js.map +1 -0
  8. package/dist/adapters/observe-storage.cjs +260 -0
  9. package/dist/adapters/observe-storage.cjs.map +1 -0
  10. package/dist/adapters/observe-storage.d.cts +77 -0
  11. package/dist/adapters/observe-storage.d.ts +77 -0
  12. package/dist/adapters/observe-storage.js +161 -0
  13. package/dist/adapters/observe-storage.js.map +1 -0
  14. package/dist/append-log-DisvEReb.d.cts +189 -0
  15. package/dist/append-log-DzKMmjxx.d.ts +189 -0
  16. package/dist/chunk-2ILL7HQI.js +1189 -0
  17. package/dist/chunk-2ILL7HQI.js.map +1 -0
  18. package/dist/chunk-4VLAQHZI.js +330 -0
  19. package/dist/chunk-4VLAQHZI.js.map +1 -0
  20. package/dist/chunk-6PHB5CJS.js +229 -0
  21. package/dist/chunk-6PHB5CJS.js.map +1 -0
  22. package/dist/chunk-COHO25CZ.js +2449 -0
  23. package/dist/chunk-COHO25CZ.js.map +1 -0
  24. package/dist/chunk-D6BG7U6A.js +161 -0
  25. package/dist/chunk-D6BG7U6A.js.map +1 -0
  26. package/dist/chunk-DJC4CHLQ.js +818 -0
  27. package/dist/chunk-DJC4CHLQ.js.map +1 -0
  28. package/dist/chunk-DK554R7P.js +67 -0
  29. package/dist/chunk-DK554R7P.js.map +1 -0
  30. package/dist/chunk-DKP56CSW.js +322 -0
  31. package/dist/chunk-DKP56CSW.js.map +1 -0
  32. package/dist/chunk-G4M3NHRJ.js +688 -0
  33. package/dist/chunk-G4M3NHRJ.js.map +1 -0
  34. package/dist/chunk-GAJW5I5P.js +1 -0
  35. package/dist/chunk-GAJW5I5P.js.map +1 -0
  36. package/dist/chunk-GDL26N2T.js +282 -0
  37. package/dist/chunk-GDL26N2T.js.map +1 -0
  38. package/dist/chunk-GTPCOEOZ.js +741 -0
  39. package/dist/chunk-GTPCOEOZ.js.map +1 -0
  40. package/dist/chunk-H2HTHFVN.js +1 -0
  41. package/dist/chunk-H2HTHFVN.js.map +1 -0
  42. package/dist/chunk-HDRL4VQQ.js +218 -0
  43. package/dist/chunk-HDRL4VQQ.js.map +1 -0
  44. package/dist/chunk-I3IHOHCJ.js +2267 -0
  45. package/dist/chunk-I3IHOHCJ.js.map +1 -0
  46. package/dist/chunk-JIMUDQN3.js +965 -0
  47. package/dist/chunk-JIMUDQN3.js.map +1 -0
  48. package/dist/chunk-JR4IKCR2.js +462 -0
  49. package/dist/chunk-JR4IKCR2.js.map +1 -0
  50. package/dist/chunk-K3FXTC3I.js +165 -0
  51. package/dist/chunk-K3FXTC3I.js.map +1 -0
  52. package/dist/chunk-OOEN33FB.js +65 -0
  53. package/dist/chunk-OOEN33FB.js.map +1 -0
  54. package/dist/chunk-PKVBHGBM.js +554 -0
  55. package/dist/chunk-PKVBHGBM.js.map +1 -0
  56. package/dist/chunk-RIIOUTGM.js +1857 -0
  57. package/dist/chunk-RIIOUTGM.js.map +1 -0
  58. package/dist/chunk-SCRFRCGR.js +33 -0
  59. package/dist/chunk-SCRFRCGR.js.map +1 -0
  60. package/dist/chunk-SWTLEQL6.js +53 -0
  61. package/dist/chunk-SWTLEQL6.js.map +1 -0
  62. package/dist/chunk-SZAETNNA.js +1 -0
  63. package/dist/chunk-SZAETNNA.js.map +1 -0
  64. package/dist/chunk-TEW47IVR.js +49 -0
  65. package/dist/chunk-TEW47IVR.js.map +1 -0
  66. package/dist/chunk-Y3ZLRGHC.js +1482 -0
  67. package/dist/chunk-Y3ZLRGHC.js.map +1 -0
  68. package/dist/chunk-Z2ANQ6JW.js +149 -0
  69. package/dist/chunk-Z2ANQ6JW.js.map +1 -0
  70. package/dist/codec-BB7p8fJc.d.cts +38 -0
  71. package/dist/codec-BB7p8fJc.d.ts +38 -0
  72. package/dist/composition/index.cjs +2505 -0
  73. package/dist/composition/index.cjs.map +1 -0
  74. package/dist/composition/index.d.cts +95 -0
  75. package/dist/composition/index.d.ts +95 -0
  76. package/dist/composition/index.js +19 -0
  77. package/dist/composition/index.js.map +1 -0
  78. package/dist/core/index.cjs +2475 -0
  79. package/dist/core/index.cjs.map +1 -0
  80. package/dist/core/index.d.cts +25 -0
  81. package/dist/core/index.d.ts +25 -0
  82. package/dist/core/index.js +74 -0
  83. package/dist/core/index.js.map +1 -0
  84. package/dist/cqrs/index.cjs +595 -0
  85. package/dist/cqrs/index.cjs.map +1 -0
  86. package/dist/cqrs/index.d.cts +200 -0
  87. package/dist/cqrs/index.d.ts +200 -0
  88. package/dist/cqrs/index.js +557 -0
  89. package/dist/cqrs/index.js.map +1 -0
  90. package/dist/data-structures/index.cjs +4277 -0
  91. package/dist/data-structures/index.cjs.map +1 -0
  92. package/dist/data-structures/index.d.cts +22 -0
  93. package/dist/data-structures/index.d.ts +22 -0
  94. package/dist/data-structures/index.js +31 -0
  95. package/dist/data-structures/index.js.map +1 -0
  96. package/dist/describe-BZb7AS2y.d.ts +57 -0
  97. package/dist/describe-Ciu8SUnN.d.cts +57 -0
  98. package/dist/graph/index.cjs +7832 -0
  99. package/dist/graph/index.cjs.map +1 -0
  100. package/dist/graph/index.d.cts +251 -0
  101. package/dist/graph/index.d.ts +251 -0
  102. package/dist/graph/index.js +131 -0
  103. package/dist/graph/index.js.map +1 -0
  104. package/dist/graph-DfdF9zy4.d.ts +666 -0
  105. package/dist/graph-s23RbbFO.d.cts +666 -0
  106. package/dist/index-CAEmLCYF.d.cts +166 -0
  107. package/dist/index-SnzZu3x7.d.ts +166 -0
  108. package/dist/index.cjs +15409 -0
  109. package/dist/index.cjs.map +1 -0
  110. package/dist/index.d.cts +23 -0
  111. package/dist/index.d.ts +23 -0
  112. package/dist/index.js +582 -0
  113. package/dist/index.js.map +1 -0
  114. package/dist/messages-BZqrGGm1.d.cts +55 -0
  115. package/dist/messages-BZqrGGm1.d.ts +55 -0
  116. package/dist/messaging/index.cjs +818 -0
  117. package/dist/messaging/index.cjs.map +1 -0
  118. package/dist/messaging/index.d.cts +235 -0
  119. package/dist/messaging/index.d.ts +235 -0
  120. package/dist/messaging/index.js +767 -0
  121. package/dist/messaging/index.js.map +1 -0
  122. package/dist/observe-event-log-0SVsx7JG.d.cts +88 -0
  123. package/dist/observe-event-log-Dnm76owp.d.ts +88 -0
  124. package/dist/operators/index.cjs +3774 -0
  125. package/dist/operators/index.cjs.map +1 -0
  126. package/dist/operators/index.d.cts +308 -0
  127. package/dist/operators/index.d.ts +308 -0
  128. package/dist/operators/index.js +112 -0
  129. package/dist/operators/index.js.map +1 -0
  130. package/dist/orchestration/index.cjs +3541 -0
  131. package/dist/orchestration/index.cjs.map +1 -0
  132. package/dist/orchestration/index.d.cts +302 -0
  133. package/dist/orchestration/index.d.ts +302 -0
  134. package/dist/orchestration/index.js +1004 -0
  135. package/dist/orchestration/index.js.map +1 -0
  136. package/dist/patterns/index.cjs +1045 -0
  137. package/dist/patterns/index.cjs.map +1 -0
  138. package/dist/patterns/index.d.cts +39 -0
  139. package/dist/patterns/index.d.ts +39 -0
  140. package/dist/patterns/index.js +33 -0
  141. package/dist/patterns/index.js.map +1 -0
  142. package/dist/reactive-collection-BxBqtIOE.d.cts +344 -0
  143. package/dist/reactive-collection-Cb1II1Fi.d.ts +344 -0
  144. package/dist/reactive-collection-storage-BNiEc-Gd.d.ts +217 -0
  145. package/dist/reactive-collection-storage-D-KmjE0J.d.cts +217 -0
  146. package/dist/reactive-map-BcB4KsQR.d.ts +256 -0
  147. package/dist/reactive-map-D-g3dv8I.d.cts +256 -0
  148. package/dist/read-through-B1CYPfq_.d.cts +82 -0
  149. package/dist/read-through-DwyJhGs1.d.ts +82 -0
  150. package/dist/render/index.cjs +250 -0
  151. package/dist/render/index.cjs.map +1 -0
  152. package/dist/render/index.d.cts +58 -0
  153. package/dist/render/index.d.ts +58 -0
  154. package/dist/render/index.js +20 -0
  155. package/dist/render/index.js.map +1 -0
  156. package/dist/resilience-Dig3Q7n0.d.cts +45 -0
  157. package/dist/resilience-Dig3Q7n0.d.ts +45 -0
  158. package/dist/semantic-memory-graph-BYoIlP35.d.cts +356 -0
  159. package/dist/semantic-memory-graph-CxyXLms3.d.ts +356 -0
  160. package/dist/solutions/index.cjs +3249 -0
  161. package/dist/solutions/index.cjs.map +1 -0
  162. package/dist/solutions/index.d.cts +520 -0
  163. package/dist/solutions/index.d.ts +520 -0
  164. package/dist/solutions/index.js +31 -0
  165. package/dist/solutions/index.js.map +1 -0
  166. package/dist/sources/browser.cjs +3095 -0
  167. package/dist/sources/browser.cjs.map +1 -0
  168. package/dist/sources/browser.d.cts +39 -0
  169. package/dist/sources/browser.d.ts +39 -0
  170. package/dist/sources/browser.js +137 -0
  171. package/dist/sources/browser.js.map +1 -0
  172. package/dist/sources/index.cjs +3021 -0
  173. package/dist/sources/index.cjs.map +1 -0
  174. package/dist/sources/index.d.cts +7 -0
  175. package/dist/sources/index.d.ts +7 -0
  176. package/dist/sources/index.js +63 -0
  177. package/dist/sources/index.js.map +1 -0
  178. package/dist/sources/node.cjs +675 -0
  179. package/dist/sources/node.cjs.map +1 -0
  180. package/dist/sources/node.d.cts +109 -0
  181. package/dist/sources/node.d.ts +109 -0
  182. package/dist/sources/node.js +639 -0
  183. package/dist/sources/node.js.map +1 -0
  184. package/dist/storage/browser.cjs +777 -0
  185. package/dist/storage/browser.cjs.map +1 -0
  186. package/dist/storage/browser.d.cts +40 -0
  187. package/dist/storage/browser.d.ts +40 -0
  188. package/dist/storage/browser.js +275 -0
  189. package/dist/storage/browser.js.map +1 -0
  190. package/dist/storage/index.cjs +1989 -0
  191. package/dist/storage/index.cjs.map +1 -0
  192. package/dist/storage/index.d.cts +92 -0
  193. package/dist/storage/index.d.ts +92 -0
  194. package/dist/storage/index.js +161 -0
  195. package/dist/storage/index.js.map +1 -0
  196. package/dist/storage/node.cjs +898 -0
  197. package/dist/storage/node.cjs.map +1 -0
  198. package/dist/storage/node.d.cts +66 -0
  199. package/dist/storage/node.d.ts +66 -0
  200. package/dist/storage/node.js +402 -0
  201. package/dist/storage/node.js.map +1 -0
  202. package/dist/testing/index.cjs +95 -0
  203. package/dist/testing/index.cjs.map +1 -0
  204. package/dist/testing/index.d.cts +20 -0
  205. package/dist/testing/index.d.ts +20 -0
  206. package/dist/testing/index.js +8 -0
  207. package/dist/testing/index.js.map +1 -0
  208. package/dist/types-bNMSWKqF.d.cts +732 -0
  209. package/dist/types-h12mNYbq.d.ts +732 -0
  210. package/package.json +250 -0
@@ -0,0 +1,2475 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/core/index.ts
21
+ var core_exports = {};
22
+ __export(core_exports, {
23
+ Dispatcher: () => Dispatcher,
24
+ Node: () => Node,
25
+ SENTINEL: () => SENTINEL,
26
+ TIER_CONTROL: () => TIER_CONTROL,
27
+ TIER_NOTIFICATION: () => TIER_NOTIFICATION,
28
+ TIER_SETTLE: () => TIER_SETTLE,
29
+ TIER_START: () => TIER_START,
30
+ TIER_TEARDOWN: () => TIER_TEARDOWN,
31
+ TIER_TERMINAL: () => TIER_TERMINAL,
32
+ TIER_VALUE: () => TIER_VALUE,
33
+ batch: () => batch,
34
+ defaultDispatcher: () => defaultDispatcher,
35
+ defaultNodeVersionHash: () => defaultNodeVersionHash,
36
+ depBatch: () => depBatch,
37
+ depCount: () => depCount,
38
+ depLatest: () => depLatest,
39
+ depTerminal: () => depTerminal,
40
+ depWaves: () => depWaves,
41
+ dynamicNode: () => dynamicNode,
42
+ errorPayload: () => errorPayload,
43
+ isDeferredTier: () => isDeferredTier,
44
+ isInvalidErrorPayload: () => isInvalidErrorPayload,
45
+ isPauseBufferedTier: () => isPauseBufferedTier,
46
+ isTerminal: () => isTerminal,
47
+ isTerminalComplete: () => isTerminalComplete,
48
+ isTerminalError: () => isTerminalError,
49
+ isTerminalNone: () => isTerminalNone,
50
+ isUpAllowed: () => isUpAllowed,
51
+ isValueTier: () => isValueTier,
52
+ messageTier: () => messageTier,
53
+ node: () => node,
54
+ terminalErrorValue: () => terminalErrorValue
55
+ });
56
+ module.exports = __toCommonJS(core_exports);
57
+
58
+ // src/batch/boundary.ts
59
+ var depth = 0;
60
+ var pendingCores = [];
61
+ var pendingHead = 0;
62
+ function enterWave() {
63
+ depth++;
64
+ }
65
+ function exitWave() {
66
+ depth--;
67
+ if (depth === 0 && pendingHead < pendingCores.length) drain();
68
+ }
69
+ function deferRewire(core, apply, options = {}) {
70
+ core.enqueueBoundaryTask({ apply, batchToken: options.batchToken, isReady: options.isReady });
71
+ pendingCores.push(core);
72
+ }
73
+ function scheduleBoundaryDrain(core) {
74
+ for (let i = 0; i < core.boundaryTaskCount(); i++) pendingCores.push(core);
75
+ if (depth === 0 && pendingHead < pendingCores.length) drain();
76
+ }
77
+ function dropBoundaryTasksForBatch(batchToken) {
78
+ const seen = /* @__PURE__ */ new Set();
79
+ for (let i = pendingHead; i < pendingCores.length; i++) {
80
+ const core = pendingCores[i];
81
+ if (seen.has(core)) continue;
82
+ seen.add(core);
83
+ core.dropBoundaryTasksForBatch(batchToken);
84
+ }
85
+ }
86
+ function drain() {
87
+ let escaped = null;
88
+ while (pendingHead < pendingCores.length) {
89
+ const core = pendingCores[pendingHead++];
90
+ const task = core.shiftBoundaryTask();
91
+ if (task === void 0) continue;
92
+ if (task.batchToken !== void 0) {
93
+ const committed = task.batchToken.committed === true;
94
+ if (!committed) continue;
95
+ }
96
+ if (task.isReady !== void 0 && !task.isReady()) {
97
+ core.unshiftBoundaryTask(task);
98
+ continue;
99
+ }
100
+ depth++;
101
+ try {
102
+ task.apply();
103
+ } catch (e) {
104
+ if (escaped === null) escaped = { e };
105
+ } finally {
106
+ depth--;
107
+ }
108
+ }
109
+ pendingCores.length = 0;
110
+ pendingHead = 0;
111
+ if (escaped !== null) throw escaped.e;
112
+ }
113
+
114
+ // src/batch/batch.ts
115
+ var active = null;
116
+ var boundaryOwner = null;
117
+ function currentBatch() {
118
+ return active !== null;
119
+ }
120
+ function currentBoundaryBatchToken() {
121
+ return active ?? boundaryOwner ?? void 0;
122
+ }
123
+ function deferToBatch(target, tier3Wave) {
124
+ if (active === null) return false;
125
+ if (!active.deferred.has(target)) active.order.push(target);
126
+ active.deferred.set(target, tier3Wave);
127
+ return true;
128
+ }
129
+ function deferAfterBatchForTarget(target, fn) {
130
+ if (active === null || !active.deferred.has(target)) return false;
131
+ const owner = active;
132
+ target.__deferBoundary(() => {
133
+ if (owner.committed) fn();
134
+ }, owner);
135
+ return true;
136
+ }
137
+ function commit(b) {
138
+ const prev = boundaryOwner;
139
+ boundaryOwner = b;
140
+ try {
141
+ for (const target of b.order) {
142
+ const wave = b.deferred.get(target);
143
+ if (wave) target.__commitBatchedWave(wave);
144
+ }
145
+ b.committed = true;
146
+ } catch (e) {
147
+ dropBoundaryTasksForBatch(b);
148
+ throw e;
149
+ } finally {
150
+ boundaryOwner = prev;
151
+ }
152
+ }
153
+ function rollback(b) {
154
+ dropBoundaryTasksForBatch(b);
155
+ for (const target of b.order) target.__rollbackBatched();
156
+ }
157
+ function batch(fn) {
158
+ enterWave();
159
+ try {
160
+ if (active !== null) {
161
+ const outer = active;
162
+ return fn({
163
+ rollback: () => {
164
+ outer.rolledBack = true;
165
+ }
166
+ });
167
+ }
168
+ const b = { order: [], deferred: /* @__PURE__ */ new Map(), committed: false, rolledBack: false };
169
+ active = b;
170
+ const bctx = {
171
+ rollback: () => {
172
+ b.rolledBack = true;
173
+ }
174
+ };
175
+ let result;
176
+ try {
177
+ result = fn(bctx);
178
+ } catch (e) {
179
+ active = null;
180
+ rollback(b);
181
+ throw e;
182
+ }
183
+ active = null;
184
+ if (b.rolledBack) rollback(b);
185
+ else {
186
+ commit(b);
187
+ }
188
+ return result;
189
+ } finally {
190
+ exitWave();
191
+ }
192
+ }
193
+
194
+ // src/protocol/messages.ts
195
+ var SENTINEL = void 0;
196
+ function isInvalidErrorPayload(v) {
197
+ return v === SENTINEL || typeof v === "boolean";
198
+ }
199
+ function errorPayload(reason, fallback = "error without a valid payload") {
200
+ return isInvalidErrorPayload(reason) ? new Error(fallback) : reason;
201
+ }
202
+ var TIER_START = 0;
203
+ var TIER_CONTROL = 1;
204
+ var TIER_NOTIFICATION = 2;
205
+ var TIER_VALUE = 3;
206
+ var TIER_SETTLE = 4;
207
+ var TIER_TERMINAL = 5;
208
+ var TIER_TEARDOWN = 6;
209
+ var TIER = {
210
+ START: TIER_START,
211
+ PAUSE: TIER_CONTROL,
212
+ RESUME: TIER_CONTROL,
213
+ DIRTY: TIER_NOTIFICATION,
214
+ DATA: TIER_VALUE,
215
+ RESOLVED: TIER_VALUE,
216
+ INVALIDATE: TIER_SETTLE,
217
+ COMPLETE: TIER_TERMINAL,
218
+ ERROR: TIER_TERMINAL,
219
+ TEARDOWN: TIER_TEARDOWN
220
+ };
221
+ function messageTier(t) {
222
+ return TIER[t];
223
+ }
224
+ function isDeferredTier(t) {
225
+ return TIER[t] >= TIER_VALUE;
226
+ }
227
+ function isValueTier(t) {
228
+ return TIER[t] === TIER_VALUE;
229
+ }
230
+ function isPauseBufferedTier(t) {
231
+ const tier = TIER[t];
232
+ return tier === TIER_VALUE || tier === TIER_SETTLE;
233
+ }
234
+ function isTerminal(t) {
235
+ return TIER[t] === TIER_TERMINAL;
236
+ }
237
+ function isUpAllowed(t) {
238
+ const tier = TIER[t];
239
+ return tier !== TIER_VALUE && tier !== TIER_TERMINAL;
240
+ }
241
+
242
+ // src/ctx/types.ts
243
+ var CTX_DEP_CACHE = /* @__PURE__ */ Symbol("graphrefly.ctx.depCache");
244
+ var CTX_NODE_BINDING = /* @__PURE__ */ Symbol("graphrefly.ctx.nodeBinding");
245
+ function isTerminalNone(t) {
246
+ return t === false || t === void 0;
247
+ }
248
+ function isTerminalComplete(t) {
249
+ return t === true;
250
+ }
251
+ function isTerminalError(t) {
252
+ return !isTerminalNone(t) && !isTerminalComplete(t);
253
+ }
254
+ function terminalErrorValue(t) {
255
+ return isTerminalError(t) ? t : void 0;
256
+ }
257
+ function depCount(ctx) {
258
+ return ctx.waveData.length;
259
+ }
260
+ function depWaves(ctx, depIndex) {
261
+ return ctx.waveData[depIndex] ?? [];
262
+ }
263
+ function depBatch(ctx, depIndex) {
264
+ const waves = depWaves(ctx, depIndex);
265
+ if (waves.length === 0) return null;
266
+ const flattened = waves.flat().filter((v) => v !== SENTINEL);
267
+ return flattened.length === 0 ? [] : flattened;
268
+ }
269
+ function depLatest(ctx, depIndex) {
270
+ return ctx[CTX_DEP_CACHE]?.latest[depIndex];
271
+ }
272
+ function depTerminal(ctx, depIndex) {
273
+ const t = ctx.terminal[depIndex];
274
+ return t === void 0 ? false : t;
275
+ }
276
+
277
+ // src/dispatcher/index.ts
278
+ var PoolTable = class {
279
+ constructor(kind) {
280
+ this.kind = kind;
281
+ }
282
+ fns = [];
283
+ free = [];
284
+ register(fn) {
285
+ const reused = this.free.pop();
286
+ if (reused !== void 0) {
287
+ this.fns[reused] = fn;
288
+ return reused;
289
+ }
290
+ const id = this.fns.length;
291
+ this.fns.push(fn);
292
+ return id;
293
+ }
294
+ unregister(handleId) {
295
+ if (this.fns[handleId] === void 0) return;
296
+ this.fns[handleId] = void 0;
297
+ this.free.push(handleId);
298
+ }
299
+ invoke(handleId, ctx) {
300
+ this.fns[handleId](ctx);
301
+ }
302
+ };
303
+ var statKey = (h) => `${h.poolId}:${h.handleId}`;
304
+ var Dispatcher = class {
305
+ pools = [];
306
+ syncPoolId;
307
+ asyncPoolId;
308
+ // opt-in profile recorder (default OFF → zero overhead, F-PERF).
309
+ _recording = false;
310
+ _stats = /* @__PURE__ */ new Map();
311
+ _totalInvokes = 0;
312
+ constructor() {
313
+ this.syncPoolId = this.addPool(new PoolTable("sync"));
314
+ this.asyncPoolId = this.addPool(new PoolTable("async"));
315
+ }
316
+ /** Turn the profile recorder on/off (D39). Off = zero overhead on invoke. */
317
+ setRecording(on) {
318
+ this._recording = on;
319
+ }
320
+ /** Reset accumulated profiling counters. */
321
+ clearStats() {
322
+ this._stats.clear();
323
+ this._totalInvokes = 0;
324
+ }
325
+ /** Read a handle's accumulated counters (undefined if it never ran while recording). */
326
+ statFor(handle) {
327
+ return this._stats.get(statKey(handle));
328
+ }
329
+ /** Total fn invocations recorded across the dispatcher. */
330
+ get totalInvokes() {
331
+ return this._totalInvokes;
332
+ }
333
+ addPool(pool) {
334
+ const id = this.pools.length;
335
+ this.pools.push(pool);
336
+ return id;
337
+ }
338
+ /** Register a fn in a pool, returning its Handle. Default pool = sync (R-sync-core). */
339
+ register(fn, pool = "sync") {
340
+ const poolId = pool === "sync" ? this.syncPoolId : pool === "async" ? this.asyncPoolId : pool;
341
+ const handleId = this.pools[poolId].register(fn);
342
+ return { poolId, handleId };
343
+ }
344
+ /**
345
+ * Release a handle (B15): frees the pool slot (closure GC'd, id reusable) and drops any
346
+ * accumulated profile stat so a reused id never inherits the previous tenant's counters.
347
+ * Called on rewire fn-swap (node._rewire) — the old handle is dropped before the node
348
+ * adopts the new one. Idempotent. NOT called on deactivate (a node's handle survives
349
+ * activate↔deactivate and is reused on reactivation; only a rewire swaps it).
350
+ */
351
+ unregister(handle) {
352
+ this.pools[handle.poolId].unregister(handle.handleId);
353
+ this._stats.delete(statKey(handle));
354
+ }
355
+ /** Uniform sync-void invoke (R-sync-core / R-dispatch-all). */
356
+ invoke(handle, ctx) {
357
+ if (!this._recording) {
358
+ this.pools[handle.poolId].invoke(handle.handleId, ctx);
359
+ return;
360
+ }
361
+ this._totalInvokes++;
362
+ const t0 = performance.now();
363
+ try {
364
+ this.pools[handle.poolId].invoke(handle.handleId, ctx);
365
+ } finally {
366
+ const dur = (performance.now() - t0) * 1e6;
367
+ const key = statKey(handle);
368
+ const s = this._stats.get(key) ?? {
369
+ invokes: 0,
370
+ totalDurationNs: 0,
371
+ lastDurationNs: 0
372
+ };
373
+ s.invokes++;
374
+ s.lastDurationNs = dur;
375
+ s.totalDurationNs += dur;
376
+ this._stats.set(key, s);
377
+ }
378
+ }
379
+ poolKind(poolId) {
380
+ return this.pools[poolId].kind;
381
+ }
382
+ };
383
+ var defaultDispatcher = new Dispatcher();
384
+
385
+ // src/graph/environment.ts
386
+ var EnvironmentDrivers = class _EnvironmentDrivers {
387
+ process;
388
+ http;
389
+ sse;
390
+ websocket;
391
+ webhook;
392
+ constructor(init = {}) {
393
+ this.process = init.process;
394
+ this.http = init.http;
395
+ this.sse = init.sse;
396
+ this.websocket = init.websocket;
397
+ this.webhook = init.webhook;
398
+ Object.freeze(this);
399
+ }
400
+ static empty() {
401
+ return EMPTY_ENVIRONMENT;
402
+ }
403
+ withProcess(driver) {
404
+ return new _EnvironmentDrivers({ ...this, process: driver });
405
+ }
406
+ withHttp(driver) {
407
+ return new _EnvironmentDrivers({ ...this, http: driver });
408
+ }
409
+ withSse(driver) {
410
+ return new _EnvironmentDrivers({ ...this, sse: driver });
411
+ }
412
+ withWebSocket(driver) {
413
+ return new _EnvironmentDrivers({ ...this, websocket: driver });
414
+ }
415
+ withWebhook(driver) {
416
+ return new _EnvironmentDrivers({ ...this, webhook: driver });
417
+ }
418
+ processDriver() {
419
+ return this.process;
420
+ }
421
+ httpDriver() {
422
+ return this.http;
423
+ }
424
+ sseDriver() {
425
+ return this.sse;
426
+ }
427
+ webSocketDriver() {
428
+ return this.websocket;
429
+ }
430
+ webhookDriver() {
431
+ return this.webhook;
432
+ }
433
+ };
434
+ var EMPTY_ENVIRONMENT = new EnvironmentDrivers();
435
+
436
+ // src/node/core.ts
437
+ var NodeCore = class {
438
+ nextId = 0;
439
+ slots = [];
440
+ values = [];
441
+ waves = [];
442
+ controls = [];
443
+ lifecycles = [];
444
+ depStates = [];
445
+ privateStates = [];
446
+ hooks = [];
447
+ syncCtxs = [];
448
+ versionStates = [];
449
+ boundary = { queue: [], head: 0 };
450
+ createSlot(slot, state) {
451
+ const id = this.nextId++;
452
+ const full = { ...slot, id };
453
+ this.slots[id] = full;
454
+ this.depStates[id] = state.dep;
455
+ this.lifecycles[id] = state.lifecycle;
456
+ this.values[id] = state.value;
457
+ this.waves[id] = state.wave;
458
+ this.controls[id] = state.control;
459
+ this.privateStates[id] = state.privateState;
460
+ this.hooks[id] = state.hooks;
461
+ this.syncCtxs[id] = state.syncCtx;
462
+ this.versionStates[id] = state.version;
463
+ return { id, slot: full };
464
+ }
465
+ get(id) {
466
+ const slot = this.slots[id];
467
+ if (slot === void 0) throw new Error("NodeCore: unknown node slot");
468
+ return slot;
469
+ }
470
+ getValue(id) {
471
+ const value = this.values[id];
472
+ if (value === void 0) throw new Error("NodeCore: unknown node value state");
473
+ return value;
474
+ }
475
+ getWave(id) {
476
+ const wave = this.waves[id];
477
+ if (wave === void 0) throw new Error("NodeCore: unknown node wave state");
478
+ return wave;
479
+ }
480
+ getControl(id) {
481
+ const control = this.controls[id];
482
+ if (control === void 0) throw new Error("NodeCore: unknown node control state");
483
+ return control;
484
+ }
485
+ getLifecycle(id) {
486
+ const lifecycle = this.lifecycles[id];
487
+ if (lifecycle === void 0) throw new Error("NodeCore: unknown node lifecycle state");
488
+ return lifecycle;
489
+ }
490
+ getDep(id) {
491
+ const dep = this.depStates[id];
492
+ if (dep === void 0) throw new Error("NodeCore: unknown node dep state");
493
+ return dep;
494
+ }
495
+ getPrivateState(id) {
496
+ const state = this.privateStates[id];
497
+ if (state === void 0) throw new Error("NodeCore: unknown node private state");
498
+ return state;
499
+ }
500
+ getHooks(id) {
501
+ const hooks = this.hooks[id];
502
+ if (hooks === void 0) throw new Error("NodeCore: unknown node cleanup hooks");
503
+ return hooks;
504
+ }
505
+ getSyncCtx(id) {
506
+ const state = this.syncCtxs[id];
507
+ if (state === void 0) throw new Error("NodeCore: unknown node ctx state");
508
+ return state;
509
+ }
510
+ getVersion(id) {
511
+ const state = this.versionStates[id];
512
+ if (state === void 0) throw new Error("NodeCore: unknown node version state");
513
+ return state;
514
+ }
515
+ /** @internal D122: release graph-owned ephemeral node runtime state from core retention. */
516
+ releaseSlot(id) {
517
+ this.slots[id] = void 0;
518
+ this.depStates[id] = void 0;
519
+ this.lifecycles[id] = void 0;
520
+ this.values[id] = void 0;
521
+ this.waves[id] = void 0;
522
+ this.controls[id] = void 0;
523
+ this.privateStates[id] = void 0;
524
+ this.hooks[id] = void 0;
525
+ this.syncCtxs[id] = void 0;
526
+ this.versionStates[id] = void 0;
527
+ }
528
+ /** @internal B49: graph-local deferred-boundary queue (rewireNext/upNext/batch-after-commit). */
529
+ enqueueBoundaryTask(task) {
530
+ this.boundary.queue.push(task);
531
+ }
532
+ /** @internal */
533
+ hasBoundaryTasks() {
534
+ return this.boundary.head < this.boundary.queue.length;
535
+ }
536
+ /** @internal */
537
+ boundaryTaskCount() {
538
+ return this.boundary.queue.length - this.boundary.head;
539
+ }
540
+ /** @internal */
541
+ shiftBoundaryTask() {
542
+ if (!this.hasBoundaryTasks()) {
543
+ this.boundary.queue = [];
544
+ this.boundary.head = 0;
545
+ return void 0;
546
+ }
547
+ const task = this.boundary.queue[this.boundary.head++];
548
+ if (!this.hasBoundaryTasks()) {
549
+ this.boundary.queue = [];
550
+ this.boundary.head = 0;
551
+ }
552
+ return task;
553
+ }
554
+ /** @internal Put a not-yet-ready task back at this core's FIFO head. */
555
+ unshiftBoundaryTask(task) {
556
+ const remaining = this.boundary.queue.slice(this.boundary.head);
557
+ this.boundary.queue = [task, ...remaining];
558
+ this.boundary.head = 0;
559
+ }
560
+ /** @internal D110: discard all pending tasks caused by an uncommitted batch. */
561
+ dropBoundaryTasksForBatch(batchToken) {
562
+ const remaining = this.boundary.queue.slice(this.boundary.head).filter((task) => task.batchToken !== batchToken);
563
+ this.boundary.queue = remaining;
564
+ this.boundary.head = 0;
565
+ }
566
+ };
567
+ function makeDepBookkeeping(depCount2) {
568
+ return {
569
+ batch: new Array(depCount2).fill(null),
570
+ waveData: Array.from({ length: depCount2 }, () => []),
571
+ waveTokens: new Array(depCount2).fill(void 0),
572
+ prev: new Array(depCount2).fill(SENTINEL),
573
+ hasData: new Array(depCount2).fill(false),
574
+ dirty: new Array(depCount2).fill(false),
575
+ tier: new Array(depCount2).fill(0),
576
+ terminal: new Array(depCount2).fill(void 0),
577
+ terminalInput: new Array(depCount2).fill(void 0),
578
+ unsubs: [],
579
+ idxBoxes: []
580
+ };
581
+ }
582
+
583
+ // src/json/codec.ts
584
+ var JS_MIN_NORMAL_NUMBER = 2 ** -1022;
585
+ function assertStableJsonNumber(value, path) {
586
+ if (!Number.isFinite(value)) {
587
+ throw new TypeError(`stableJsonString: non-finite number at ${path}`);
588
+ }
589
+ }
590
+ function assertStrictJsonNumber(value, path) {
591
+ assertStableJsonNumber(value, path);
592
+ if (Object.is(value, -0)) {
593
+ throw new TypeError(`stableJsonString: non-canonical number at ${path}`);
594
+ }
595
+ const abs = Math.abs(value);
596
+ if (abs > 0 && abs < JS_MIN_NORMAL_NUMBER) {
597
+ throw new TypeError(`stableJsonString: subnormal number at ${path}`);
598
+ }
599
+ if (Number.isInteger(value) && !Number.isSafeInteger(value)) {
600
+ throw new TypeError(`stableJsonString: integer outside safe range at ${path}`);
601
+ }
602
+ }
603
+ function sortedJsonValue(value, seen = /* @__PURE__ */ new Set(), path = "$", strictNumbers = false) {
604
+ if (value === null) return null;
605
+ if (typeof value === "string" || typeof value === "boolean") return value;
606
+ if (typeof value === "number") {
607
+ if (strictNumbers) assertStrictJsonNumber(value, path);
608
+ else assertStableJsonNumber(value, path);
609
+ return value;
610
+ }
611
+ if (typeof value !== "object") {
612
+ throw new TypeError(`stableJsonString: value at ${path} is not JSON-encodable`);
613
+ }
614
+ if (seen.has(value)) throw new TypeError(`stableJsonString: circular reference at ${path}`);
615
+ const proto = Object.getPrototypeOf(value);
616
+ if (!Array.isArray(value) && proto !== Object.prototype && proto !== null) {
617
+ throw new TypeError(`stableJsonString: non-plain object at ${path}`);
618
+ }
619
+ seen.add(value);
620
+ try {
621
+ if (Array.isArray(value)) {
622
+ if (Object.getOwnPropertySymbols(value).length > 0) {
623
+ throw new TypeError(`stableJsonString: symbol-keyed properties at ${path}`);
624
+ }
625
+ for (const key of Object.getOwnPropertyNames(value)) {
626
+ const isIndex = /^(0|[1-9]\d*)$/.test(key) && Number.isSafeInteger(Number(key)) && Number(key) < value.length;
627
+ if (key !== "length" && !isIndex) {
628
+ throw new TypeError(`stableJsonString: non-index array property at ${path}.${key}`);
629
+ }
630
+ }
631
+ const out2 = [];
632
+ for (let i = 0; i < value.length; i += 1) {
633
+ if (!(i in value)) {
634
+ throw new TypeError(`stableJsonString: sparse array hole at ${path}[${i}]`);
635
+ }
636
+ out2.push(sortedJsonValue(value[i], seen, `${path}[${i}]`, strictNumbers));
637
+ }
638
+ return out2;
639
+ }
640
+ if (Object.getOwnPropertySymbols(value).length > 0) {
641
+ throw new TypeError(`stableJsonString: symbol-keyed properties at ${path}`);
642
+ }
643
+ const out = /* @__PURE__ */ Object.create(null);
644
+ for (const key of Object.keys(value).sort()) {
645
+ out[key] = sortedJsonValue(
646
+ value[key],
647
+ seen,
648
+ `${path}.${key}`,
649
+ strictNumbers
650
+ );
651
+ }
652
+ return out;
653
+ } finally {
654
+ seen.delete(value);
655
+ }
656
+ }
657
+ function stableJsonString(value) {
658
+ return JSON.stringify(sortedJsonValue(value));
659
+ }
660
+ function strictStableJsonString(value) {
661
+ return JSON.stringify(sortedJsonValue(value, /* @__PURE__ */ new Set(), "$", true));
662
+ }
663
+ function jsonCodecFor() {
664
+ const encoder = new TextEncoder();
665
+ const decoder = new TextDecoder();
666
+ return {
667
+ encode(value) {
668
+ return encoder.encode(stableJsonString(value));
669
+ },
670
+ decode(bytes) {
671
+ return JSON.parse(decoder.decode(bytes));
672
+ }
673
+ };
674
+ }
675
+ var jsonCodec = jsonCodecFor();
676
+ function bytesEqual(a, b) {
677
+ if (a.byteLength !== b.byteLength) return false;
678
+ for (let i = 0; i < a.byteLength; i += 1) {
679
+ if (a[i] !== b[i]) return false;
680
+ }
681
+ return true;
682
+ }
683
+ function hasUnpairedSurrogate(value) {
684
+ for (let i = 0; i < value.length; i += 1) {
685
+ const code = value.charCodeAt(i);
686
+ if (code >= 55296 && code <= 56319) {
687
+ const next = value.charCodeAt(i + 1);
688
+ if (next >= 56320 && next <= 57343) {
689
+ i += 1;
690
+ continue;
691
+ }
692
+ return true;
693
+ }
694
+ if (code >= 56320 && code <= 57343) return true;
695
+ }
696
+ return false;
697
+ }
698
+ function assertNoUnpairedSurrogates(value, seen = /* @__PURE__ */ new Set(), path = "$") {
699
+ if (typeof value === "string") {
700
+ if (hasUnpairedSurrogate(value)) {
701
+ throw new TypeError(`strictJsonCodec: unpaired surrogate at ${path}`);
702
+ }
703
+ return;
704
+ }
705
+ if (value === null || typeof value !== "object") return;
706
+ if (seen.has(value)) return;
707
+ seen.add(value);
708
+ try {
709
+ if (Array.isArray(value)) {
710
+ for (let i = 0; i < value.length; i += 1) {
711
+ assertNoUnpairedSurrogates(value[i], seen, `${path}[${i}]`);
712
+ }
713
+ return;
714
+ }
715
+ for (const key of Object.keys(value)) {
716
+ if (hasUnpairedSurrogate(key)) {
717
+ throw new TypeError(`strictJsonCodec: unpaired surrogate at ${path}.${key}`);
718
+ }
719
+ assertNoUnpairedSurrogates(value[key], seen, `${path}.${key}`);
720
+ }
721
+ } finally {
722
+ seen.delete(value);
723
+ }
724
+ }
725
+ function assertNoDuplicateJsonObjectKeys(text) {
726
+ let index = 0;
727
+ function fail(message) {
728
+ throw new TypeError(`strictJsonCodec: ${message}`);
729
+ }
730
+ function skipWhitespace() {
731
+ while (/\s/.test(text[index] ?? "")) index += 1;
732
+ }
733
+ function readJsonString() {
734
+ const start = index;
735
+ index += 1;
736
+ while (index < text.length) {
737
+ const ch = text[index];
738
+ if (ch === '"') {
739
+ index += 1;
740
+ try {
741
+ return JSON.parse(text.slice(start, index));
742
+ } catch {
743
+ fail("malformed JSON string");
744
+ }
745
+ }
746
+ if (ch === "\\") {
747
+ index += 2;
748
+ continue;
749
+ }
750
+ index += 1;
751
+ }
752
+ fail("unterminated JSON string");
753
+ }
754
+ function consumeLiteral(literal) {
755
+ if (text.slice(index, index + literal.length) !== literal) {
756
+ fail(`malformed JSON near byte ${index}`);
757
+ }
758
+ index += literal.length;
759
+ }
760
+ function consumeNumber() {
761
+ const match = /^-?(0|[1-9]\d*)(\.\d+)?([eE][+-]?\d+)?/.exec(text.slice(index));
762
+ if (!match) fail(`malformed JSON number near byte ${index}`);
763
+ index += match[0].length;
764
+ }
765
+ function parseValue(path) {
766
+ skipWhitespace();
767
+ const ch = text[index];
768
+ if (ch === "{") {
769
+ parseObject(path);
770
+ return;
771
+ }
772
+ if (ch === "[") {
773
+ parseArray(path);
774
+ return;
775
+ }
776
+ if (ch === '"') {
777
+ readJsonString();
778
+ return;
779
+ }
780
+ if (ch === "t") {
781
+ consumeLiteral("true");
782
+ return;
783
+ }
784
+ if (ch === "f") {
785
+ consumeLiteral("false");
786
+ return;
787
+ }
788
+ if (ch === "n") {
789
+ consumeLiteral("null");
790
+ return;
791
+ }
792
+ if (ch === "-" || ch !== void 0 && ch >= "0" && ch <= "9") {
793
+ consumeNumber();
794
+ return;
795
+ }
796
+ fail(`malformed JSON near byte ${index}`);
797
+ }
798
+ function parseObject(path) {
799
+ const keys = /* @__PURE__ */ new Set();
800
+ index += 1;
801
+ skipWhitespace();
802
+ if (text[index] === "}") {
803
+ index += 1;
804
+ return;
805
+ }
806
+ while (index < text.length) {
807
+ skipWhitespace();
808
+ if (text[index] !== '"') fail(`expected object key near byte ${index}`);
809
+ const key = readJsonString();
810
+ if (keys.has(key)) {
811
+ throw new TypeError(
812
+ `strictJsonCodec: duplicate object key ${JSON.stringify(key)} at ${path}`
813
+ );
814
+ }
815
+ keys.add(key);
816
+ skipWhitespace();
817
+ if (text[index] !== ":") fail(`expected ':' after object key near byte ${index}`);
818
+ index += 1;
819
+ parseValue(`${path}.${key}`);
820
+ skipWhitespace();
821
+ if (text[index] === ",") {
822
+ index += 1;
823
+ continue;
824
+ }
825
+ if (text[index] === "}") {
826
+ index += 1;
827
+ return;
828
+ }
829
+ fail(`expected ',' or '}' near byte ${index}`);
830
+ }
831
+ fail("unterminated JSON object");
832
+ }
833
+ function parseArray(path) {
834
+ index += 1;
835
+ skipWhitespace();
836
+ if (text[index] === "]") {
837
+ index += 1;
838
+ return;
839
+ }
840
+ let item = 0;
841
+ while (index < text.length) {
842
+ parseValue(`${path}[${item}]`);
843
+ item += 1;
844
+ skipWhitespace();
845
+ if (text[index] === ",") {
846
+ index += 1;
847
+ continue;
848
+ }
849
+ if (text[index] === "]") {
850
+ index += 1;
851
+ return;
852
+ }
853
+ fail(`expected ',' or ']' near byte ${index}`);
854
+ }
855
+ fail("unterminated JSON array");
856
+ }
857
+ parseValue("$");
858
+ skipWhitespace();
859
+ if (index !== text.length) fail(`trailing JSON token near byte ${index}`);
860
+ }
861
+ function strictJsonCodecFor() {
862
+ const encoder = new TextEncoder();
863
+ const decoder = new TextDecoder("utf-8", { fatal: true });
864
+ return {
865
+ encode(value) {
866
+ assertNoUnpairedSurrogates(value);
867
+ return encoder.encode(strictStableJsonString(value));
868
+ },
869
+ decode(bytes) {
870
+ const text = decoder.decode(bytes);
871
+ assertNoDuplicateJsonObjectKeys(text);
872
+ const decoded = JSON.parse(text);
873
+ assertNoUnpairedSurrogates(decoded);
874
+ const canonical = encoder.encode(strictStableJsonString(decoded));
875
+ if (!bytesEqual(bytes, canonical)) {
876
+ throw new TypeError("strictJsonCodec: bytes are not canonical stable JSON");
877
+ }
878
+ return decoded;
879
+ }
880
+ };
881
+ }
882
+ var strictJsonCodec = strictJsonCodecFor();
883
+ function strictCanonicalJsonBytes(value) {
884
+ return strictJsonCodec.encode(value);
885
+ }
886
+
887
+ // src/node/versioning.ts
888
+ var ABSENT_V1_SEED = Object.freeze({
889
+ "@graphrefly/node-version": "v1-absent"
890
+ });
891
+ function fnv1a64(input) {
892
+ let hash = 0xcbf29ce484222325n;
893
+ const prime = 0x100000001b3n;
894
+ for (const byte of input) {
895
+ hash ^= BigInt(byte);
896
+ hash = BigInt.asUintN(64, hash * prime);
897
+ }
898
+ return hash.toString(16).padStart(16, "0");
899
+ }
900
+ function defaultNodeVersionHash(bytes) {
901
+ return `fnv1a64:${fnv1a64(bytes)}`;
902
+ }
903
+ function computeV1Cid(policy, value) {
904
+ return policy.hash(strictCanonicalJsonBytes(value));
905
+ }
906
+ function assertNodeVersionDataCompatible(policy, value) {
907
+ if (!policy.enabled || policy.level === 0) return;
908
+ strictCanonicalJsonBytes(value);
909
+ }
910
+ function snapshotNodeVersionData(policy, value) {
911
+ if (!policy.enabled || policy.level === 0) return value;
912
+ const bytes = strictCanonicalJsonBytes(value);
913
+ return strictJsonCodec.decode(bytes);
914
+ }
915
+ function resolveNodeVersioningPolicy(policy) {
916
+ if (policy === false) return { enabled: false };
917
+ if (policy === void 0 || policy === 0) return { enabled: true, level: 0 };
918
+ if (policy === 1) return { enabled: true, level: 1, hash: defaultNodeVersionHash };
919
+ if (typeof policy === "object" && policy !== null) {
920
+ if (policy.level === 0) return { enabled: true, level: 0 };
921
+ if (policy.level === 1) {
922
+ return { enabled: true, level: 1, hash: policy.hash ?? defaultNodeVersionHash };
923
+ }
924
+ }
925
+ throw new Error("node: versioning level must be 0 or 1; V2/V3 are not locked yet (D109)");
926
+ }
927
+ function createNodeVersion(policy, initialValue = ABSENT_V1_SEED) {
928
+ if (!policy.enabled) return void 0;
929
+ if (policy.level === 0) return Object.freeze({ level: 0, counter: 0 });
930
+ return Object.freeze({
931
+ level: 1,
932
+ counter: 0,
933
+ cid: computeV1Cid(policy, initialValue),
934
+ prev: null
935
+ });
936
+ }
937
+ function advanceNodeVersion(current, policy, value) {
938
+ if (!policy.enabled) return void 0;
939
+ if (current === void 0) return createNodeVersion(policy, value);
940
+ if (policy.level === 0) {
941
+ return Object.freeze({ level: 0, counter: current.counter + 1 });
942
+ }
943
+ const previous = current.level === 1 ? current.cid : null;
944
+ return Object.freeze({
945
+ level: 1,
946
+ counter: current.counter + 1,
947
+ cid: computeV1Cid(policy, value),
948
+ prev: previous
949
+ });
950
+ }
951
+ function cloneNodeVersion(version) {
952
+ if (version === void 0) return void 0;
953
+ if (version.level === 0) return Object.freeze({ level: 0, counter: version.counter });
954
+ return Object.freeze({
955
+ level: 1,
956
+ counter: version.counter,
957
+ cid: version.cid,
958
+ prev: version.prev
959
+ });
960
+ }
961
+ function restoredV1Cid(policy, hasData, cache) {
962
+ return computeV1Cid(policy, hasData ? cache : ABSENT_V1_SEED);
963
+ }
964
+
965
+ // src/node/node.ts
966
+ var constructingCore;
967
+ var constructingEnvironment;
968
+ var ownerTokens = /* @__PURE__ */ new WeakMap();
969
+ var topologyDepsChangedObservers = /* @__PURE__ */ new WeakMap();
970
+ var checkpointReaders = /* @__PURE__ */ new WeakMap();
971
+ var restoreWriters = /* @__PURE__ */ new WeakMap();
972
+ var runtimeReleasers = /* @__PURE__ */ new WeakMap();
973
+ var runtimeQuiescenceReaders = /* @__PURE__ */ new WeakMap();
974
+ var subscriberCountReaders = /* @__PURE__ */ new WeakMap();
975
+ var activationReaders = /* @__PURE__ */ new WeakMap();
976
+ var releasedNodes = /* @__PURE__ */ new WeakSet();
977
+ function withNodeCore(core, create) {
978
+ const prev = constructingCore;
979
+ constructingCore = core;
980
+ try {
981
+ return create();
982
+ } finally {
983
+ constructingCore = prev;
984
+ }
985
+ }
986
+ function withEnvironmentDrivers(environment, create) {
987
+ const prev = constructingEnvironment;
988
+ constructingEnvironment = environment;
989
+ try {
990
+ return create();
991
+ } finally {
992
+ constructingEnvironment = prev;
993
+ }
994
+ }
995
+ function getNodeOwner(n) {
996
+ return ownerTokens.get(n);
997
+ }
998
+ function notifyTopologyDepsChanged(node2, prevDeps, deps) {
999
+ topologyDepsChangedObservers.get(node2)?.(node2, prevDeps, deps);
1000
+ }
1001
+ function terminalView(t) {
1002
+ return t === void 0 ? false : t;
1003
+ }
1004
+ function validateDownPayloads(msgs) {
1005
+ for (const m of msgs) {
1006
+ if (m[0] === "DATA" && m[1] === void 0) {
1007
+ throw new Error("down: DATA requires a non-SENTINEL payload (R-data-payload)");
1008
+ }
1009
+ if (m[0] === "ERROR" && isInvalidErrorPayload(m[1])) {
1010
+ throw new Error("down: ERROR requires a non-SENTINEL, non-boolean payload (R-data-payload)");
1011
+ }
1012
+ }
1013
+ }
1014
+ var Node = class {
1015
+ _core;
1016
+ _id;
1017
+ _slot;
1018
+ _dep;
1019
+ _value;
1020
+ _wave;
1021
+ _control;
1022
+ _lifecycle;
1023
+ _privateState;
1024
+ _hooks;
1025
+ _syncCtxState;
1026
+ _version;
1027
+ _restoredActivationPending = false;
1028
+ _released = false;
1029
+ get _syncCtx() {
1030
+ return this._syncCtxState.value;
1031
+ }
1032
+ set _syncCtx(ctx) {
1033
+ this._syncCtxState.value = ctx;
1034
+ }
1035
+ constructor(deps, handleOrFn, opts = {}) {
1036
+ const core = constructingCore;
1037
+ constructingCore = void 0;
1038
+ const dispatcher = opts.dispatcher ?? defaultDispatcher;
1039
+ const environment = constructingEnvironment ?? EnvironmentDrivers.empty();
1040
+ constructingEnvironment = void 0;
1041
+ const pool = opts.pool ?? "sync";
1042
+ const pausable = opts.pausable ?? true;
1043
+ const pullLock = opts.pullId;
1044
+ const pull = opts.pullId !== void 0;
1045
+ if (pull && pausable === false)
1046
+ throw new Error(
1047
+ "node: pullId is incompatible with pausable:false \u2014 a pull node is demanded via RESUME, which pausable:false ignores (R-pull / R-pause-modes / D55,D59)"
1048
+ );
1049
+ let handle;
1050
+ if (handleOrFn === null) handle = null;
1051
+ else if (typeof handleOrFn === "function") handle = dispatcher.register(handleOrFn, pool);
1052
+ else handle = handleOrFn;
1053
+ const n = deps.length;
1054
+ const dep = makeDepBookkeeping(n);
1055
+ const versioning = resolveNodeVersioningPolicy(opts.versioning);
1056
+ const value = {
1057
+ cache: SENTINEL,
1058
+ hasData: false,
1059
+ status: "sentinel",
1060
+ terminal: void 0,
1061
+ hasTorndown: false,
1062
+ replayRing: []
1063
+ };
1064
+ if (opts.initial !== void 0) {
1065
+ value.cache = opts.initial;
1066
+ value.hasData = true;
1067
+ value.status = "settled";
1068
+ }
1069
+ const pauseLockset = /* @__PURE__ */ new Set();
1070
+ if (pull) pauseLockset.add(pullLock);
1071
+ this._core = core ?? new NodeCore();
1072
+ const created = this._core.createSlot(
1073
+ {
1074
+ deps,
1075
+ handle,
1076
+ pool,
1077
+ dispatcher,
1078
+ environment,
1079
+ partial: opts.partial ?? false,
1080
+ terminalAsRealInput: opts.terminalAsRealInput ?? false,
1081
+ completeWhenDepsComplete: opts.completeWhenDepsComplete ?? true,
1082
+ errorWhenDepsError: opts.errorWhenDepsError ?? true,
1083
+ resubscribable: opts.resubscribable ?? false,
1084
+ resetOnTeardown: opts.resetOnTeardown ?? false,
1085
+ pausable,
1086
+ pull,
1087
+ pullLock,
1088
+ replayN: opts.replayBuffer ?? 0,
1089
+ dynamic: opts.dynamic ?? false,
1090
+ name: opts.name,
1091
+ factory: opts.factory
1092
+ },
1093
+ {
1094
+ dep,
1095
+ lifecycle: { subscribers: /* @__PURE__ */ new Set(), activated: false },
1096
+ value,
1097
+ wave: {
1098
+ pending: 0,
1099
+ hasCalledFnOnce: false,
1100
+ emittedDirtyThisWave: false,
1101
+ emittedSettleThisWave: false,
1102
+ insideRunWave: false,
1103
+ inDepMutation: false,
1104
+ rewireRunPending: false,
1105
+ batchDirtyOwed: false
1106
+ },
1107
+ control: {
1108
+ pauseLockset,
1109
+ pausedDepWaveOccurred: false,
1110
+ pauseBuffer: [],
1111
+ demandOwed: false,
1112
+ inDeliverDemand: false
1113
+ },
1114
+ privateState: { value: SENTINEL, persist: false },
1115
+ hooks: { onDeactivation: [], onInvalidate: [] },
1116
+ syncCtx: { value: null },
1117
+ version: {
1118
+ policy: versioning,
1119
+ value: createNodeVersion(
1120
+ versioning,
1121
+ opts.initial !== void 0 ? opts.initial : void 0
1122
+ )
1123
+ }
1124
+ }
1125
+ );
1126
+ this._id = created.id;
1127
+ this._slot = this._core.get(this._id);
1128
+ this._dep = this._core.getDep(this._id);
1129
+ this._value = this._core.getValue(this._id);
1130
+ this._wave = this._core.getWave(this._id);
1131
+ this._control = this._core.getControl(this._id);
1132
+ this._lifecycle = this._core.getLifecycle(this._id);
1133
+ this._privateState = this._core.getPrivateState(this._id);
1134
+ this._hooks = this._core.getHooks(this._id);
1135
+ this._syncCtxState = this._core.getSyncCtx(this._id);
1136
+ this._version = this._core.getVersion(this._id);
1137
+ checkpointReaders.set(this, () => ({
1138
+ cache: this._value.cache,
1139
+ hasData: this._value.hasData,
1140
+ terminal: this._value.terminal,
1141
+ activated: this._lifecycle.activated,
1142
+ hasCalledFnOnce: this._wave.hasCalledFnOnce,
1143
+ ctxState: {
1144
+ value: this._privateState.value,
1145
+ persist: this._privateState.persist
1146
+ },
1147
+ version: cloneNodeVersion(this._version.value),
1148
+ handle: this._slot.handle
1149
+ }));
1150
+ restoreWriters.set(this, (state) => {
1151
+ this._assertNotReleased("restoreGraph");
1152
+ this._value.cache = state.cache;
1153
+ this._value.hasData = state.hasData;
1154
+ this._value.status = state.status;
1155
+ this._value.terminal = state.terminal;
1156
+ this._value.hasTorndown = false;
1157
+ this._value.replayRing = [];
1158
+ this._wave.hasCalledFnOnce = state.hasCalledFnOnce;
1159
+ this._wave.emittedDirtyThisWave = false;
1160
+ this._wave.emittedSettleThisWave = false;
1161
+ this._wave.pending = 0;
1162
+ this._wave.insideRunWave = false;
1163
+ this._wave.inDepMutation = false;
1164
+ this._wave.rewireRunPending = false;
1165
+ this._wave.batchDirtyOwed = false;
1166
+ this._control.pauseBuffer = [];
1167
+ this._control.pausedDepWaveOccurred = false;
1168
+ this._control.demandOwed = false;
1169
+ this._control.inDeliverDemand = false;
1170
+ this._control.pauseLockset.clear();
1171
+ if (this._slot.pull) this._control.pauseLockset.add(this._slot.pullLock);
1172
+ this._privateState.value = state.ctxState.value;
1173
+ this._privateState.persist = state.ctxState.persist;
1174
+ if (state.version === false) {
1175
+ this._version.policy = { enabled: false };
1176
+ this._version.value = void 0;
1177
+ } else if (state.version.level === 0) {
1178
+ this._version.policy = { enabled: true, level: 0 };
1179
+ this._version.value = cloneNodeVersion(state.version);
1180
+ } else {
1181
+ if (!this._version.policy.enabled || this._version.policy.level !== 1) {
1182
+ throw new Error(
1183
+ `restoreGraph: checkpoint node version level ${state.version.level} requires matching node versioning policy`
1184
+ );
1185
+ }
1186
+ if (!state.hasData && state.version.counter > 0) {
1187
+ throw new Error(
1188
+ "restoreGraph: checkpoint node version cid cannot be verified without current DATA under V1 versioning (D109)"
1189
+ );
1190
+ }
1191
+ const expectedCid = restoredV1Cid(this._version.policy, state.hasData, state.cache);
1192
+ if (expectedCid !== state.version.cid) {
1193
+ throw new Error(
1194
+ "restoreGraph: checkpoint node version cid does not match the selected node versioning hash policy (D109)"
1195
+ );
1196
+ }
1197
+ this._version.value = cloneNodeVersion(state.version);
1198
+ }
1199
+ this._syncCtx = null;
1200
+ this._resetDepState();
1201
+ this._lifecycle.activated = false;
1202
+ this._lifecycle.subscribers.clear();
1203
+ this._restoredActivationPending = true;
1204
+ });
1205
+ runtimeReleasers.set(this, () => this._releaseRuntime());
1206
+ runtimeQuiescenceReaders.set(this, () => this._isRuntimeQuiescentForRelease());
1207
+ subscriberCountReaders.set(this, () => this._subscriberCount());
1208
+ activationReaders.set(this, () => this._lifecycle.activated);
1209
+ }
1210
+ /** R-pull (D55): true while a pull node is quiet (holds its own pullId/demand lock). */
1211
+ _isPullQuiet() {
1212
+ return this._slot.pull && this._control.pauseLockset.has(this._slot.pullLock);
1213
+ }
1214
+ /**
1215
+ * R-pull (D55/D59): this pull node's pullId (pure data, like {@link cache}/{@link handle} — never
1216
+ * triggers computation). A consumer demands one delivery by cone-routing a RESUME of it (no node
1217
+ * reference): `ctx.up([["RESUME", pullId]])` (immediate; loops back → D37 for a self-read dep) or
1218
+ * `ctx.upNext([["RESUME", pullId]])` (boundary-deferred self-demand, R-up-routing/R-rewire-deferred).
1219
+ * Undefined for a non-pull node. The author writes the pullId verbatim, so this getter is mainly
1220
+ * for inspection/describe; routing matches by the pullId value carried in the RESUME, by identity.
1221
+ */
1222
+ get pullId() {
1223
+ return this._slot.pullLock;
1224
+ }
1225
+ get cache() {
1226
+ return this._value.cache;
1227
+ }
1228
+ get status() {
1229
+ return this._value.status;
1230
+ }
1231
+ get version() {
1232
+ return cloneNodeVersion(this._version.value);
1233
+ }
1234
+ get name() {
1235
+ return this._slot.name;
1236
+ }
1237
+ /** R-describe/D51: real factory name for a standalone graph-less node (a runtime *Map inner). */
1238
+ get factory() {
1239
+ return this._slot.factory;
1240
+ }
1241
+ /**
1242
+ * The node's CURRENT/LIVE deps (R-describe / R-edges-derived / D51) — readonly view of the
1243
+ * live `_deps`, which a rewire (C-8 / C-11) mutates. The graph's describe() reads this (NOT a
1244
+ * construction-time snapshot) so every edge corresponds to a real current subscription (D3).
1245
+ * Inspection-only, like cache/status; never triggers computation.
1246
+ */
1247
+ get deps() {
1248
+ return this._slot.deps;
1249
+ }
1250
+ /**
1251
+ * The fn handle (pure data `(poolId, handleId)`, D7) or null for state/passthrough
1252
+ * nodes. Inspection-only (L1.6 handle is referenceable/inspectable) — lets the graph
1253
+ * layer key a dispatcher-backed profile recorder WITHOUT putting counters on the node
1254
+ * (R-node-thin / D39).
1255
+ */
1256
+ get handle() {
1257
+ return this._slot.handle;
1258
+ }
1259
+ /** R-push-subscribe: a new sink receives START, then cached DATA (or DIRTY if dirty). */
1260
+ subscribe(sink) {
1261
+ this._assertNotReleased("subscribe");
1262
+ enterWave();
1263
+ try {
1264
+ if (this._value.terminal !== void 0) {
1265
+ if (this._slot.resubscribable) {
1266
+ this._restoredActivationPending = false;
1267
+ this._resetLifecycle();
1268
+ } else
1269
+ throw new Error(
1270
+ "subscribe: node is non-resubscribable and has terminated; the stream is permanently over (R-terminal / R2.2.7.b)"
1271
+ );
1272
+ }
1273
+ this._lifecycle.subscribers.add(sink);
1274
+ sink(["START"]);
1275
+ if (this._slot.replayN > 0 && this._value.replayRing.length > 0) {
1276
+ for (const v of this._value.replayRing) sink(["DATA", v]);
1277
+ } else if (this._value.hasData && !this._slot.pull) {
1278
+ sink(["DATA", this._value.cache]);
1279
+ } else if (this._value.status === "dirty" && !this._slot.pull) {
1280
+ sink(["DIRTY"]);
1281
+ }
1282
+ if (!this._lifecycle.activated) this._activate();
1283
+ return () => {
1284
+ if (!this._lifecycle.subscribers.delete(sink)) return;
1285
+ if (this._lifecycle.subscribers.size === 0) this._deactivate();
1286
+ };
1287
+ } finally {
1288
+ exitWave();
1289
+ }
1290
+ }
1291
+ /** External emission toward sinks (state-node push, or async late-emit). One call = one wave. */
1292
+ down(msgs) {
1293
+ this._assertNotReleased("down");
1294
+ enterWave();
1295
+ try {
1296
+ this._down(msgs);
1297
+ } finally {
1298
+ exitWave();
1299
+ }
1300
+ }
1301
+ /**
1302
+ * Emit upstream toward deps — control tiers only (R-ctx-up). `towardDep` (a dep index) routes up
1303
+ * ONE declared edge (R-up-routing directed-up); omitted = broadcast up all deps.
1304
+ */
1305
+ up(msgs, towardDep) {
1306
+ this._assertNotReleased("up");
1307
+ enterWave();
1308
+ try {
1309
+ this._up(msgs, towardDep);
1310
+ } finally {
1311
+ exitWave();
1312
+ }
1313
+ }
1314
+ // ── deferred self-rewire (R-rewire-deferred / D47): ctx.rewireNext drain support ──
1315
+ /**
1316
+ * Enqueue a deferred self-rewire op (issued from this node's fn via `ctx.rewireNext`).
1317
+ * Applied at the committed wave boundary (boundary.ts drain), never in place — the in-fn
1318
+ * immediate path (`subscribeDep`/`replaceDeps`/`unsubscribeDep`) still throws mid-run (D37/R-reentrancy).
1319
+ */
1320
+ _requestRewireNext(op) {
1321
+ deferRewire(this._core, () => this._applyRewireNext(op), {
1322
+ batchToken: currentBoundaryBatchToken(),
1323
+ isReady: () => !this._hasBoundaryPauseLock()
1324
+ });
1325
+ }
1326
+ /**
1327
+ * Enqueue a deferred up-going control wave (R-up-routing / R-pull / D59): at the committed wave
1328
+ * boundary, route `msgs` up from THIS node (broadcast, or up the single `towardDep` edge). The
1329
+ * deferred form of `ctx.up` — the SELF-demand path: a consumer issues `ctx.upNext([[RESUME,
1330
+ * pullId]])` to demand a dep it ALSO reads; the demand applies at the boundary (not mid-fn), so
1331
+ * the pull node's delivery loops back as a FRESH wave rather than re-entering the consumer (D37 /
1332
+ * R-reentrancy). Rides the same R-rewire-deferred (D47) drain as ctx.rewireNext.
1333
+ */
1334
+ _requestUpNext(msgs, towardDep) {
1335
+ deferRewire(
1336
+ this._core,
1337
+ () => {
1338
+ if (!this._released) this._up(msgs, towardDep);
1339
+ },
1340
+ {
1341
+ batchToken: currentBoundaryBatchToken(),
1342
+ isReady: () => !this._hasBoundaryPauseLock()
1343
+ }
1344
+ );
1345
+ }
1346
+ /** Apply one queued self-rewire at the boundary (drain thunk). */
1347
+ _applyRewireNext(op) {
1348
+ if (this._released) return;
1349
+ try {
1350
+ if (op.kind === "add") {
1351
+ const next = this._slot.deps.includes(op.dep) ? [...this._slot.deps] : [...this._slot.deps, op.dep];
1352
+ this._rewire(next, op.fn, { allowTerminalOwner: true });
1353
+ } else if (op.kind === "remove") {
1354
+ this._rewire(
1355
+ this._slot.deps.filter((d) => d !== op.dep),
1356
+ op.fn,
1357
+ { allowTerminalOwner: true }
1358
+ );
1359
+ } else {
1360
+ this._rewire(this._dedupDeps(op.deps), op.fn, { allowTerminalOwner: true });
1361
+ }
1362
+ } catch (e) {
1363
+ this._down([["ERROR", errorPayload(e, "rewireNext op failed")]]);
1364
+ }
1365
+ }
1366
+ // ── rewire (R-rewire / D42): intra-graph runtime topology mutation ──
1367
+ /**
1368
+ * Replace this node's deps atomically (surgical, Option-C). Requires an explicit
1369
+ * `fn` (SD-1 fn-deps pairing — user fns read dep input positionally). Kept deps
1370
+ * keep their subscription + per-dep state; only removed deps unsubscribe and only
1371
+ * added deps fresh-subscribe (push-on-subscribe for an added cached dep). The
1372
+ * first-run gate and cache are PRESERVED (R-rewire Q2/Q7). Intra-graph only (D22).
1373
+ */
1374
+ replaceDeps(newDeps, fn) {
1375
+ this._assertNotReleased("replaceDeps");
1376
+ this._rewire(this._dedupDeps(newDeps), fn);
1377
+ }
1378
+ /** Subscribe to one dep (special case of replaceDeps); returns its index. fn required (SD-1). */
1379
+ subscribeDep(depNode, fn) {
1380
+ this._assertNotReleased("subscribeDep");
1381
+ const next = this._slot.deps.includes(depNode) ? [...this._slot.deps] : [...this._slot.deps, depNode];
1382
+ const deferred = this._rewire(next, fn);
1383
+ return deferred ? next.indexOf(depNode) : this._slot.deps.indexOf(depNode);
1384
+ }
1385
+ /** Unsubscribe from one dep (special case of replaceDeps); idempotent if absent (fn swap still applies). */
1386
+ unsubscribeDep(depNode, fn) {
1387
+ this._assertNotReleased("unsubscribeDep");
1388
+ this._rewire(
1389
+ this._slot.deps.filter((d) => d !== depNode),
1390
+ fn
1391
+ );
1392
+ }
1393
+ _dedupDeps(deps) {
1394
+ const seen = /* @__PURE__ */ new Set();
1395
+ const out = [];
1396
+ for (const d of deps)
1397
+ if (!seen.has(d)) {
1398
+ seen.add(d);
1399
+ out.push(d);
1400
+ }
1401
+ return out;
1402
+ }
1403
+ /** Is `target` reachable upstream from `from` (following deps)? Cycle-prevention DFS. */
1404
+ _reachableUpstream(from, target) {
1405
+ const seen = /* @__PURE__ */ new Set();
1406
+ const stack = [from];
1407
+ while (stack.length > 0) {
1408
+ const n = stack.pop();
1409
+ if (n === void 0) continue;
1410
+ if (n === target) return true;
1411
+ if (seen.has(n)) continue;
1412
+ seen.add(n);
1413
+ for (const d of n._slot.deps) stack.push(d);
1414
+ }
1415
+ return false;
1416
+ }
1417
+ _assertRewireDepOwner(dep) {
1418
+ const selfOwner = getNodeOwner(this);
1419
+ const depOwner = getNodeOwner(dep);
1420
+ if (selfOwner !== void 0 && depOwner !== void 0 && selfOwner !== depOwner) {
1421
+ throw new Error(
1422
+ "rewire: dep belongs to a different graph; cross-graph deps require a wire bridge (D22 / R-graph-domain)"
1423
+ );
1424
+ }
1425
+ }
1426
+ _rewire(newDeps, fn, opts = {}) {
1427
+ if (this._value.terminal !== void 0 && !opts.allowTerminalOwner)
1428
+ throw new Error(
1429
+ "rewire: node is terminal (completed/errored) \u2014 cannot rewire (R-rewire / D42)"
1430
+ );
1431
+ if (this._wave.insideRunWave)
1432
+ throw new Error(
1433
+ "rewire: mid-fn topology mutation \u2014 a fn mutating its own deps mid-wave is the feedback cycle (R-rewire / D37)"
1434
+ );
1435
+ if (this._wave.inDepMutation)
1436
+ throw new Error(
1437
+ "rewire: reentrant dep mutation \u2014 another replaceDeps/subscribeDep/unsubscribeDep is in flight (R-rewire)"
1438
+ );
1439
+ if (newDeps.includes(this))
1440
+ throw new Error("rewire: self-dependency rejected (R-rewire / D42)");
1441
+ const oldDeps = this._slot.deps;
1442
+ const added = newDeps.filter((d) => !oldDeps.includes(d));
1443
+ for (const d of added) {
1444
+ if (this._reachableUpstream(d, this))
1445
+ throw new Error(
1446
+ "rewire: would create a cycle \u2014 dep already transitively depends on this node (R-rewire / D42)"
1447
+ );
1448
+ if (d._value.terminal !== void 0 && !d._slot.resubscribable)
1449
+ throw new Error(
1450
+ "rewire: cannot add a non-resubscribable terminal dep \u2014 would wedge (R-rewire / D42)"
1451
+ );
1452
+ this._assertRewireDepOwner(d);
1453
+ }
1454
+ if (deferAfterBatchForTarget(this, () => {
1455
+ this._rewire(newDeps, fn, { ...opts, allowTerminalOwner: true });
1456
+ })) {
1457
+ return true;
1458
+ }
1459
+ if (!this._lifecycle.activated) this._restoredActivationPending = false;
1460
+ this._wave.inDepMutation = true;
1461
+ this._wave.rewireRunPending = false;
1462
+ let zeroDepUnDirty = false;
1463
+ try {
1464
+ const oldHandle = this._slot.handle;
1465
+ this._slot.handle = this._slot.dispatcher.register(fn, this._slot.pool);
1466
+ if (oldHandle !== null) this._slot.dispatcher.unregister(oldHandle);
1467
+ const removed = oldDeps.filter((d) => !newDeps.includes(d));
1468
+ let removedDirtyContributor = false;
1469
+ for (const d of removed) {
1470
+ const oldIdx = oldDeps.indexOf(d);
1471
+ if (this._dep.dirty[oldIdx]) {
1472
+ removedDirtyContributor = true;
1473
+ this._wave.pending--;
1474
+ }
1475
+ if (this._lifecycle.activated) {
1476
+ const box = this._dep.idxBoxes[oldIdx];
1477
+ if (box) box.v = -1;
1478
+ const unsub = this._dep.unsubs[oldIdx];
1479
+ if (unsub) unsub();
1480
+ }
1481
+ }
1482
+ const n = newDeps.length;
1483
+ const newBatch = new Array(n).fill(null);
1484
+ const newPrev = new Array(n).fill(SENTINEL);
1485
+ const newHasData = new Array(n).fill(false);
1486
+ const newDirty = new Array(n).fill(false);
1487
+ const newTier = new Array(n).fill(0);
1488
+ const newTerminal = new Array(n).fill(void 0);
1489
+ const newTerminalInput = new Array(n).fill(void 0);
1490
+ const newUnsubs = new Array(n);
1491
+ const newBoxes = new Array(n);
1492
+ for (let j = 0; j < n; j++) {
1493
+ const oldIdx = oldDeps.indexOf(newDeps[j]);
1494
+ if (oldIdx !== -1) {
1495
+ newBatch[j] = this._dep.batch[oldIdx];
1496
+ newPrev[j] = this._dep.prev[oldIdx];
1497
+ newHasData[j] = this._dep.hasData[oldIdx];
1498
+ newDirty[j] = this._dep.dirty[oldIdx];
1499
+ newTier[j] = this._dep.tier[oldIdx];
1500
+ newTerminal[j] = this._dep.terminal[oldIdx];
1501
+ newUnsubs[j] = this._dep.unsubs[oldIdx];
1502
+ const box = this._dep.idxBoxes[oldIdx];
1503
+ if (box) box.v = j;
1504
+ newBoxes[j] = box;
1505
+ }
1506
+ }
1507
+ this._slot.deps = newDeps;
1508
+ this._dep.batch = newBatch;
1509
+ this._dep.prev = newPrev;
1510
+ this._dep.hasData = newHasData;
1511
+ this._dep.dirty = newDirty;
1512
+ this._dep.tier = newTier;
1513
+ this._dep.terminal = newTerminal;
1514
+ this._dep.terminalInput = newTerminalInput;
1515
+ this._dep.unsubs = newUnsubs;
1516
+ this._dep.idxBoxes = newBoxes;
1517
+ this._dep.waveData = newDeps.map(() => []);
1518
+ this._dep.waveTokens = new Array(newDeps.length).fill(void 0);
1519
+ this._syncCtx = null;
1520
+ if (this._lifecycle.activated) {
1521
+ for (const d of added) this._subscribeDepAt(d);
1522
+ }
1523
+ notifyTopologyDepsChanged(this, oldDeps, newDeps);
1524
+ if (removedDirtyContributor && this._wave.pending === 0 && this._value.status === "dirty") {
1525
+ if (newDeps.length > 0) this._wave.rewireRunPending = true;
1526
+ else zeroDepUnDirty = true;
1527
+ }
1528
+ } finally {
1529
+ this._wave.inDepMutation = false;
1530
+ }
1531
+ if (this._wave.rewireRunPending) {
1532
+ this._wave.rewireRunPending = false;
1533
+ this._settleRewire();
1534
+ } else if (zeroDepUnDirty) {
1535
+ if (this._wave.emittedDirtyThisWave) this._down([["RESOLVED"]]);
1536
+ else this._value.status = this._value.hasData ? "settled" : "sentinel";
1537
+ }
1538
+ return false;
1539
+ }
1540
+ // ── activation / deactivation (lazy; R-rom-ram) ──
1541
+ _activate() {
1542
+ this._lifecycle.activated = true;
1543
+ const seedRestoredDeps = this._restoredActivationPending;
1544
+ this._restoredActivationPending = false;
1545
+ if (this._slot.pull) this._control.pauseLockset.add(this._slot.pullLock);
1546
+ this._dep.unsubs = new Array(this._slot.deps.length);
1547
+ this._dep.idxBoxes = new Array(this._slot.deps.length);
1548
+ for (const dep of this._slot.deps)
1549
+ this._subscribeDepAt(dep, { seedRestored: seedRestoredDeps });
1550
+ if (this._slot.deps.length === 0 && this._slot.handle !== null && !this._wave.hasCalledFnOnce) {
1551
+ this._runWave();
1552
+ }
1553
+ }
1554
+ /**
1555
+ * Subscribe to a dep. The dispatch callback reads the dep's CURRENT index from a
1556
+ * mutable box (O(1)); a surgical rewire that reorders kept deps just updates the box
1557
+ * (R-rewire Option-C / D42) — no re-subscribe, no per-message indexOf scan. A removed
1558
+ * dep's box is set to -1 so any stale in-flight callback drops (drain).
1559
+ */
1560
+ _subscribeDepAt(depNode, opts = {}) {
1561
+ const idx0 = this._slot.deps.indexOf(depNode);
1562
+ const box = { v: idx0 };
1563
+ let ignoreInitialPush = opts.seedRestored === true;
1564
+ if (ignoreInitialPush && idx0 !== -1) {
1565
+ this._seedRestoredDepAt(idx0, depNode);
1566
+ if (depNode._value.terminal !== void 0 && !depNode._slot.resubscribable) {
1567
+ this._dep.unsubs[idx0] = () => {
1568
+ };
1569
+ this._dep.idxBoxes[idx0] = box;
1570
+ return;
1571
+ }
1572
+ }
1573
+ const unsub = depNode.subscribe((msg, delivery) => {
1574
+ if (ignoreInitialPush && delivery === void 0) return;
1575
+ if (ignoreInitialPush) ignoreInitialPush = false;
1576
+ if (box.v === -1) return;
1577
+ this._receiveFromDep(box.v, msg, delivery);
1578
+ });
1579
+ if (ignoreInitialPush && idx0 !== -1 && box.v !== -1) this._seedRestoredDepAt(idx0, depNode);
1580
+ ignoreInitialPush = false;
1581
+ if (idx0 !== -1) {
1582
+ this._dep.unsubs[idx0] = unsub;
1583
+ this._dep.idxBoxes[idx0] = box;
1584
+ }
1585
+ }
1586
+ _seedRestoredDepAt(idx, depNode) {
1587
+ const seedData = depNode._value.hasData && !depNode._slot.pull;
1588
+ this._dep.batch[idx] = null;
1589
+ this._dep.waveData[idx] = [];
1590
+ this._dep.waveTokens[idx] = void 0;
1591
+ this._dep.prev[idx] = seedData ? depNode._value.cache : SENTINEL;
1592
+ this._dep.hasData[idx] = seedData;
1593
+ this._dep.dirty[idx] = false;
1594
+ this._dep.tier[idx] = seedData ? 3 : 0;
1595
+ this._dep.terminal[idx] = depNode._value.terminal;
1596
+ this._dep.terminalInput[idx] = void 0;
1597
+ }
1598
+ _deactivate() {
1599
+ this._lifecycle.activated = false;
1600
+ for (const u of this._dep.unsubs) if (u) u();
1601
+ this._dep.unsubs = [];
1602
+ this._dep.idxBoxes = [];
1603
+ for (const fn of this._hooks.onDeactivation) fn();
1604
+ this._hooks.onDeactivation = [];
1605
+ this._hooks.onInvalidate = [];
1606
+ const isCompute = this._slot.handle !== null || this._slot.deps.length > 0;
1607
+ if (isCompute) {
1608
+ this._value.cache = SENTINEL;
1609
+ this._value.hasData = false;
1610
+ this._value.status = "sentinel";
1611
+ }
1612
+ this._resetDepState();
1613
+ this._wave.hasCalledFnOnce = false;
1614
+ this._control.pauseLockset.clear();
1615
+ this._control.pauseBuffer = [];
1616
+ this._control.pausedDepWaveOccurred = false;
1617
+ this._control.demandOwed = false;
1618
+ this._value.replayRing = [];
1619
+ if (!this._privateState.persist) this._privateState.value = SENTINEL;
1620
+ }
1621
+ _assertNotReleased(op) {
1622
+ if (this._released)
1623
+ throw new Error(`${op}: node has been released from its graph lifecycle (D122)`);
1624
+ }
1625
+ _subscriberCount() {
1626
+ return this._lifecycle.subscribers.size;
1627
+ }
1628
+ _isRuntimeQuiescentForRelease() {
1629
+ const allowedPullQuietLock = this._slot.pull && this._control.pauseLockset.size === 1 && this._control.pauseLockset.has(this._slot.pullLock);
1630
+ 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 && !this._control.inDeliverDemand && (this._control.pauseLockset.size === 0 || allowedPullQuietLock);
1631
+ }
1632
+ _releaseRuntime() {
1633
+ if (this._released) return;
1634
+ this._released = true;
1635
+ releasedNodes.add(this);
1636
+ let releaseError;
1637
+ const recordReleaseError = (error) => {
1638
+ if (releaseError === void 0) releaseError = error;
1639
+ };
1640
+ this._lifecycle.activated = false;
1641
+ for (const u of this._dep.unsubs) {
1642
+ try {
1643
+ u();
1644
+ } catch (error) {
1645
+ recordReleaseError(error);
1646
+ }
1647
+ }
1648
+ for (const fn of this._hooks.onDeactivation) {
1649
+ try {
1650
+ fn();
1651
+ } catch (error) {
1652
+ recordReleaseError(error);
1653
+ }
1654
+ }
1655
+ this._dep.unsubs = [];
1656
+ this._dep.idxBoxes = [];
1657
+ this._lifecycle.subscribers.clear();
1658
+ if (this._slot.handle !== null) {
1659
+ this._slot.dispatcher.unregister(this._slot.handle);
1660
+ this._slot.handle = null;
1661
+ }
1662
+ this._slot.deps = [];
1663
+ this._dep.batch = [];
1664
+ this._dep.waveData = [];
1665
+ this._dep.waveTokens = [];
1666
+ this._dep.prev = [];
1667
+ this._dep.hasData = [];
1668
+ this._dep.dirty = [];
1669
+ this._dep.tier = [];
1670
+ this._dep.terminal = [];
1671
+ this._dep.terminalInput = [];
1672
+ this._value.cache = SENTINEL;
1673
+ this._value.hasData = false;
1674
+ this._value.status = "sentinel";
1675
+ this._value.terminal = void 0;
1676
+ this._value.replayRing = [];
1677
+ this._privateState.value = SENTINEL;
1678
+ this._privateState.persist = false;
1679
+ this._syncCtx = null;
1680
+ this._resetDepState();
1681
+ this._hooks.onDeactivation = [];
1682
+ this._hooks.onInvalidate = [];
1683
+ this._control.pauseLockset.clear();
1684
+ this._control.pauseBuffer = [];
1685
+ this._control.pausedDepWaveOccurred = false;
1686
+ this._control.demandOwed = false;
1687
+ this._restoredActivationPending = false;
1688
+ checkpointReaders.delete(this);
1689
+ restoreWriters.delete(this);
1690
+ runtimeReleasers.delete(this);
1691
+ runtimeQuiescenceReaders.delete(this);
1692
+ subscriberCountReaders.delete(this);
1693
+ activationReaders.delete(this);
1694
+ ownerTokens.delete(this);
1695
+ topologyDepsChangedObservers.delete(this);
1696
+ this._core.releaseSlot(this._id);
1697
+ if (releaseError !== void 0) throw releaseError;
1698
+ }
1699
+ _resetDepState() {
1700
+ const n = this._slot.deps.length;
1701
+ for (let i = 0; i < n; i++) {
1702
+ this._dep.batch[i] = null;
1703
+ this._dep.waveData[i] = [];
1704
+ this._dep.waveTokens[i] = void 0;
1705
+ this._dep.prev[i] = SENTINEL;
1706
+ this._dep.hasData[i] = false;
1707
+ this._dep.dirty[i] = false;
1708
+ this._dep.tier[i] = 0;
1709
+ this._dep.terminal[i] = void 0;
1710
+ this._dep.terminalInput[i] = void 0;
1711
+ }
1712
+ this._wave.pending = 0;
1713
+ this._wave.emittedDirtyThisWave = false;
1714
+ }
1715
+ // ── upstream wave receive (two-phase + diamond) ──
1716
+ _recordDepProjection(idx, delivery) {
1717
+ const token = delivery?.wave ?? {};
1718
+ if (this._dep.waveTokens[idx] !== token) {
1719
+ this._dep.waveData[idx].push([]);
1720
+ this._dep.waveTokens[idx] = token;
1721
+ }
1722
+ return this._dep.waveData[idx][this._dep.waveData[idx].length - 1];
1723
+ }
1724
+ _depProjectionHasData(idx) {
1725
+ const projection = this._dep.waveData[idx][this._dep.waveData[idx].length - 1];
1726
+ return projection?.some((v) => v !== SENTINEL) ?? false;
1727
+ }
1728
+ _receiveFromDep(idx, msg, delivery) {
1729
+ if (this._released) return;
1730
+ const t = msg[0];
1731
+ if (t === "START") return;
1732
+ const isLastInDeliveredWave = delivery?.last ?? true;
1733
+ if (this._value.terminal !== void 0) {
1734
+ if (t === "TEARDOWN") this._down([["TEARDOWN"]]);
1735
+ return;
1736
+ }
1737
+ if (t === "INVALIDATE") {
1738
+ const projection = this._recordDepProjection(idx, delivery);
1739
+ projection.push(SENTINEL);
1740
+ if (projection.some((v) => v !== SENTINEL) && isLastInDeliveredWave) this._maybeRun();
1741
+ this._dep.prev[idx] = SENTINEL;
1742
+ this._dep.hasData[idx] = false;
1743
+ this._dep.batch[idx] = null;
1744
+ if (this._dep.dirty[idx]) {
1745
+ this._dep.dirty[idx] = false;
1746
+ this._wave.pending--;
1747
+ }
1748
+ if (this._control.pausedDepWaveOccurred && this._dep.batch.every((b) => b === null)) {
1749
+ this._control.pausedDepWaveOccurred = false;
1750
+ }
1751
+ const hadData = this._value.hasData;
1752
+ this._invalidate();
1753
+ if (this._wave.pending === 0 && this._wave.emittedDirtyThisWave) {
1754
+ if (!hadData) this._down([["RESOLVED"]]);
1755
+ else this._wave.emittedDirtyThisWave = false;
1756
+ }
1757
+ this._fireOwedDemandIfReady();
1758
+ return;
1759
+ }
1760
+ if (isTerminal(t)) {
1761
+ const isError = t === "ERROR";
1762
+ const errPayload = isError ? msg[1] : void 0;
1763
+ this._dep.terminal[idx] = isError ? errPayload : true;
1764
+ this._dep.terminalInput[idx] = isError ? errPayload : true;
1765
+ this._releaseDepDirty(idx);
1766
+ const ranValueBeforeTerminal = this._depProjectionHasData(idx) && isLastInDeliveredWave;
1767
+ if (ranValueBeforeTerminal) this._maybeRun();
1768
+ if (isError && this._slot.errorWhenDepsError) {
1769
+ this._down([["ERROR", errPayload]]);
1770
+ } else if (this._slot.terminalAsRealInput) {
1771
+ if (ranValueBeforeTerminal) {
1772
+ this._fireOwedDemandIfReady();
1773
+ return;
1774
+ }
1775
+ this._maybeRun();
1776
+ } else if (this._slot.completeWhenDepsComplete && this._allDepsTerminal()) {
1777
+ this._down([["COMPLETE"]]);
1778
+ } else {
1779
+ this._settleAfterAbsorbedTerminal();
1780
+ }
1781
+ this._fireOwedDemandIfReady();
1782
+ return;
1783
+ }
1784
+ if (t === "TEARDOWN") {
1785
+ this._down([["TEARDOWN"]]);
1786
+ return;
1787
+ }
1788
+ if (t === "DIRTY") {
1789
+ if (!this._dep.dirty[idx]) {
1790
+ this._dep.dirty[idx] = true;
1791
+ this._wave.pending++;
1792
+ this._dep.tier[idx] = 2;
1793
+ this._markDirty();
1794
+ }
1795
+ return;
1796
+ }
1797
+ if (t === "DATA") {
1798
+ const v = msg[1];
1799
+ this._recordDepProjection(idx, delivery).push(v);
1800
+ const b = this._dep.batch[idx];
1801
+ if (b === null) this._dep.batch[idx] = [v];
1802
+ else b.push(v);
1803
+ this._dep.prev[idx] = v;
1804
+ this._dep.hasData[idx] = true;
1805
+ this._dep.tier[idx] = 3;
1806
+ if (this._dep.dirty[idx]) {
1807
+ this._dep.dirty[idx] = false;
1808
+ this._wave.pending--;
1809
+ }
1810
+ if (isLastInDeliveredWave) this._maybeRun();
1811
+ this._fireOwedDemandIfReady();
1812
+ return;
1813
+ }
1814
+ if (t === "RESOLVED") {
1815
+ this._recordDepProjection(idx, delivery);
1816
+ this._dep.tier[idx] = 3;
1817
+ if (this._dep.dirty[idx]) {
1818
+ this._dep.dirty[idx] = false;
1819
+ this._wave.pending--;
1820
+ }
1821
+ if (isLastInDeliveredWave) this._maybeRun();
1822
+ this._fireOwedDemandIfReady();
1823
+ return;
1824
+ }
1825
+ }
1826
+ /**
1827
+ * R-terminal-settles-dirty (B35): release a dep's outstanding in-wave DIRTY contribution.
1828
+ * A settle-class event for that dep (DATA/RESOLVED inline above, INVALIDATE, and now
1829
+ * COMPLETE/ERROR) clears its dirty flag + decrements _pending. No-op if the dep already
1830
+ * settled this wave (DATA/RESOLVED ran first) — so the normal DATA-then-COMPLETE flow is
1831
+ * unaffected. This makes the exactly-one-settle invariant a single, shared step.
1832
+ */
1833
+ _releaseDepDirty(idx) {
1834
+ if (this._dep.dirty[idx]) {
1835
+ this._dep.dirty[idx] = false;
1836
+ this._wave.pending--;
1837
+ }
1838
+ }
1839
+ /**
1840
+ * R-terminal-settles-dirty (B35): settle a node whose dirtied dep was released by an ABSORBED
1841
+ * terminal that is NOT a real input (a plain derived/effect — the common default-node case when
1842
+ * one of several deps completes while others stay live). Runs only when the release drained
1843
+ * _pending while the node still owes a downstream settle (it broadcast DIRTY this wave):
1844
+ * - if some OTHER dep delivered real DATA this wave (a value occurred) → recompute (→ DATA);
1845
+ * - else the terminal's signalled change did not materialise (no value) → one undirty RESOLVED
1846
+ * (R-resolved-undirty), keeping the cache (a terminal, unlike INVALIDATE, leaves the value).
1847
+ * A terminalAsRealInput node instead recomputes unconditionally (its fn reads the terminal).
1848
+ */
1849
+ _settleAfterAbsorbedTerminal() {
1850
+ if (this._wave.pending !== 0 || !this._wave.emittedDirtyThisWave) return;
1851
+ const sawData = this._dep.batch.some((b) => b !== null && b.length > 0);
1852
+ if (sawData) this._maybeRun();
1853
+ if (this._wave.emittedDirtyThisWave) this._down([["RESOLVED"]]);
1854
+ }
1855
+ _markDirty() {
1856
+ this._value.status = "dirty";
1857
+ if (this._isPullQuiet()) return;
1858
+ if (!this._wave.emittedDirtyThisWave) {
1859
+ this._wave.emittedDirtyThisWave = true;
1860
+ this._emitToSubs(["DIRTY"]);
1861
+ }
1862
+ }
1863
+ _maybeRun() {
1864
+ if (this._wave.inDepMutation) {
1865
+ this._wave.rewireRunPending = true;
1866
+ return;
1867
+ }
1868
+ if (this._slot.pausable === true && this._isPaused()) {
1869
+ this._control.pausedDepWaveOccurred = true;
1870
+ return;
1871
+ }
1872
+ this._tryRun();
1873
+ }
1874
+ /**
1875
+ * R-rewire atomic settle (after a rewire that warrants a recompute): emit a proper
1876
+ * two-phase DIRTY→DATA wave (R-dirty-before-data — a rewire-triggered settle is a wave),
1877
+ * once, with every added dep already wired. Mirrors _maybeRun/_tryRun's pause + gate +
1878
+ * pending guards, then injects the phase-1 DIRTY the added dep's [START,DATA] handshake
1879
+ * did not carry.
1880
+ */
1881
+ _settleRewire() {
1882
+ if (this._slot.pausable === true && this._isPaused()) {
1883
+ this._control.pausedDepWaveOccurred = true;
1884
+ return;
1885
+ }
1886
+ if (this._wave.pending > 0) return;
1887
+ if (this._slot.handle === null) {
1888
+ this._passthroughEmit();
1889
+ return;
1890
+ }
1891
+ if (!this._wave.hasCalledFnOnce && !(this._slot.partial || this._allDepsSettled())) return;
1892
+ this._markDirty();
1893
+ this._runWave();
1894
+ }
1895
+ _tryRun() {
1896
+ if (this._wave.pending > 0) return;
1897
+ if (this._slot.handle === null) {
1898
+ this._passthroughEmit();
1899
+ return;
1900
+ }
1901
+ if (!this._wave.hasCalledFnOnce) {
1902
+ if (this._slot.partial || this._allDepsSettled()) this._runWave();
1903
+ return;
1904
+ }
1905
+ this._runWave();
1906
+ }
1907
+ _allDepsSettled() {
1908
+ for (let i = 0; i < this._slot.deps.length; i++) {
1909
+ if (this._dep.hasData[i]) continue;
1910
+ if (this._slot.terminalAsRealInput && this._dep.terminal[i] !== void 0) continue;
1911
+ return false;
1912
+ }
1913
+ return true;
1914
+ }
1915
+ _passthroughEmit() {
1916
+ const b = this._dep.batch[0];
1917
+ if (b !== null && b.length > 0) {
1918
+ this._down([["DATA", b[b.length - 1]]]);
1919
+ } else if (this._wave.emittedDirtyThisWave) {
1920
+ this._down([["RESOLVED"]]);
1921
+ }
1922
+ this._dep.batch[0] = null;
1923
+ this._wave.emittedDirtyThisWave = false;
1924
+ }
1925
+ _runWave() {
1926
+ if (this._wave.insideRunWave)
1927
+ throw new Error(
1928
+ "synchronous feedback cycle: node fn re-entered its own wave (R-reentrancy / D37)"
1929
+ );
1930
+ this._wave.hasCalledFnOnce = true;
1931
+ this._hooks.onInvalidate = [];
1932
+ this._hooks.onDeactivation = [];
1933
+ const ctx = this._buildCtx();
1934
+ const wasDirty = this._wave.emittedDirtyThisWave;
1935
+ this._wave.emittedSettleThisWave = false;
1936
+ this._wave.insideRunWave = true;
1937
+ try {
1938
+ this._slot.dispatcher.invoke(this._slot.handle, ctx);
1939
+ } finally {
1940
+ this._wave.insideRunWave = false;
1941
+ }
1942
+ if (wasDirty && !this._wave.emittedSettleThisWave && this._value.terminal === void 0 && !this._isAsyncPool()) {
1943
+ this._down([["RESOLVED"]]);
1944
+ }
1945
+ for (let i = 0; i < this._dep.batch.length; i++) {
1946
+ this._dep.batch[i] = null;
1947
+ this._dep.waveData[i] = [];
1948
+ this._dep.waveTokens[i] = void 0;
1949
+ this._dep.terminalInput[i] = void 0;
1950
+ }
1951
+ this._wave.emittedDirtyThisWave = false;
1952
+ }
1953
+ // ── ctx construction (L3-Q5: sync = node-stable reused ctx; async = per-invocation) ──
1954
+ _buildCtx() {
1955
+ const kind = this._slot.handle ? this._slot.dispatcher.poolKind(this._slot.handle.poolId) : "sync";
1956
+ if (kind === "sync") {
1957
+ if (this._syncCtx === null) this._syncCtx = this._makeCtx();
1958
+ this._refreshCtx(this._syncCtx);
1959
+ return this._syncCtx;
1960
+ }
1961
+ return this._makeCtx({
1962
+ waveData: this._dep.waveData.map((waves) => waves.map((w) => [...w])),
1963
+ terminal: this._dep.terminalInput.map(terminalView),
1964
+ latest: [...this._dep.prev]
1965
+ });
1966
+ }
1967
+ _makeCtx(snapshot) {
1968
+ const ctx = {
1969
+ // Wave-owner boundary (D47): a SYNC fn's emit nests under the public entry that drove
1970
+ // it (cheap inc/dec, no early drain); an ASYNC-pool fn re-enters here from its stashed
1971
+ // ctx at depth 0, so this is the boundary that drains any rewireNext it issued.
1972
+ up: (msgs, towardDep) => {
1973
+ if (this._released) return;
1974
+ enterWave();
1975
+ try {
1976
+ this._up(msgs, towardDep);
1977
+ } finally {
1978
+ exitWave();
1979
+ }
1980
+ },
1981
+ down: (msgs) => {
1982
+ if (this._released) return;
1983
+ enterWave();
1984
+ try {
1985
+ this._down(msgs);
1986
+ } finally {
1987
+ exitWave();
1988
+ }
1989
+ },
1990
+ waveData: snapshot?.waveData ?? this._dep.waveData,
1991
+ terminal: snapshot?.terminal ?? this._dep.terminalInput.map(terminalView),
1992
+ state: this._makeState(),
1993
+ onDeactivation: (fn) => {
1994
+ if (this._released) return;
1995
+ this._hooks.onDeactivation.push(fn);
1996
+ },
1997
+ onInvalidate: (fn) => {
1998
+ if (this._released) return;
1999
+ this._hooks.onInvalidate.push(fn);
2000
+ },
2001
+ environment: () => this._slot.environment,
2002
+ // R-rewire-deferred (D47): defer a self-dep-set mutation to the committed boundary.
2003
+ rewireNext: {
2004
+ subscribeDep: (dep, fn) => this._requestRewireNext({ kind: "add", dep, fn }),
2005
+ unsubscribeDep: (dep, fn) => this._requestRewireNext({ kind: "remove", dep, fn }),
2006
+ replaceDeps: (deps, fn) => this._requestRewireNext({ kind: "set", deps, fn })
2007
+ },
2008
+ // R-up-routing / R-pull (D59): deferred up — route a control wave (e.g. a RESUME pull
2009
+ // DEMAND) up the declared cone at the committed boundary. The SELF-demand path: an
2010
+ // immediate ctx.up whose delivery loops back re-enters this fn (D37 / R-reentrancy).
2011
+ upNext: (msgs, towardDep) => this._requestUpNext(msgs, towardDep),
2012
+ [CTX_DEP_CACHE]: { latest: snapshot?.latest ?? this._dep.prev },
2013
+ [CTX_NODE_BINDING]: {
2014
+ dispatcher: this._slot.dispatcher,
2015
+ create: (factory) => withEnvironmentDrivers(this._slot.environment, () => withNodeCore(this._core, factory))
2016
+ }
2017
+ };
2018
+ if (this._slot.dynamic) {
2019
+ ctx.track = (i) => ctx[CTX_DEP_CACHE]?.latest[i];
2020
+ }
2021
+ return ctx;
2022
+ }
2023
+ _refreshCtx(ctx) {
2024
+ ctx.waveData = this._dep.waveData;
2025
+ ctx.terminal = this._dep.terminalInput.map(terminalView);
2026
+ ctx[CTX_DEP_CACHE] = { latest: this._dep.prev };
2027
+ }
2028
+ _makeState() {
2029
+ return {
2030
+ get: () => this._privateState.value,
2031
+ set: (v) => {
2032
+ this._privateState.value = v;
2033
+ },
2034
+ persist: (on = true) => {
2035
+ this._privateState.persist = on;
2036
+ }
2037
+ };
2038
+ }
2039
+ // ── downstream emission pipeline (the unified waist) ──
2040
+ _down(msgs) {
2041
+ if (this._released) return;
2042
+ validateDownPayloads(msgs);
2043
+ const deliveryWave = {};
2044
+ const assertVersionDataCompatible = (wave) => {
2045
+ for (const m of wave) {
2046
+ if (m[0] === "DATA") assertNodeVersionDataCompatible(this._version.policy, m[1]);
2047
+ }
2048
+ };
2049
+ const snapshotVersionData = (wave) => wave.map(
2050
+ (m) => m[0] === "DATA" ? ["DATA", snapshotNodeVersionData(this._version.policy, m[1])] : m
2051
+ );
2052
+ assertVersionDataCompatible(msgs);
2053
+ if (this._value.terminal !== void 0) {
2054
+ if (!msgs.some((m) => m[0] === "TEARDOWN")) return;
2055
+ this._value.hasTorndown = true;
2056
+ if (this._slot.resetOnTeardown) {
2057
+ this._value.cache = SENTINEL;
2058
+ this._value.hasData = false;
2059
+ }
2060
+ this._emitToSubs(["TEARDOWN"], { wave: deliveryWave, last: true });
2061
+ return;
2062
+ }
2063
+ let sorted = [...msgs].sort((a, b) => messageTier(a[0]) - messageTier(b[0]));
2064
+ const firstInvalidate = sorted.findIndex((m) => m[0] === "INVALIDATE");
2065
+ if (firstInvalidate !== -1) {
2066
+ sorted = sorted.filter((m, i) => m[0] !== "INVALIDATE" || i === firstInvalidate);
2067
+ }
2068
+ const hasTeardown = sorted.some((m) => m[0] === "TEARDOWN");
2069
+ const hasTerminal = sorted.some((m) => m[0] === "COMPLETE" || m[0] === "ERROR");
2070
+ if (hasTeardown && !hasTerminal && this._value.terminal === void 0 && !this._value.hasTorndown) {
2071
+ sorted = [["COMPLETE"], ...sorted];
2072
+ }
2073
+ if (!this._wave.insideRunWave && currentBatch()) {
2074
+ const deferred = snapshotVersionData(sorted.filter((m) => isDeferredTier(m[0])));
2075
+ if (deferred.length > 0) {
2076
+ if (!this._wave.emittedDirtyThisWave) {
2077
+ this._wave.emittedDirtyThisWave = true;
2078
+ this._value.status = "dirty";
2079
+ this._emitToSubs(["DIRTY"], { wave: deliveryWave, last: false });
2080
+ }
2081
+ this._wave.batchDirtyOwed = true;
2082
+ deferToBatch(this, deferred);
2083
+ return;
2084
+ }
2085
+ }
2086
+ if (this._shouldBufferOnPause()) {
2087
+ const buffered = snapshotVersionData(sorted.filter((m) => isPauseBufferedTier(m[0])));
2088
+ if (buffered.length > 0) {
2089
+ this._wave.emittedSettleThisWave = true;
2090
+ this._control.pauseBuffer.push(buffered);
2091
+ }
2092
+ sorted = sorted.filter((m) => !isPauseBufferedTier(m[0]));
2093
+ if (sorted.length === 0) return;
2094
+ }
2095
+ let dataCount = 0;
2096
+ let hasTier3 = false;
2097
+ let hasResolved = false;
2098
+ for (const m of sorted) {
2099
+ if (m[0] === "DATA") dataCount++;
2100
+ if (m[0] === "RESOLVED") hasResolved = true;
2101
+ if (isValueTier(m[0])) hasTier3 = true;
2102
+ }
2103
+ if (dataCount >= 1 && hasResolved) {
2104
+ throw new Error(
2105
+ "down: a wave cannot mix DATA and RESOLVED (tier-3 exclusivity, R-resolved-undirty)"
2106
+ );
2107
+ }
2108
+ const plannedVersions = new Array(sorted.length);
2109
+ if (dataCount > 0) {
2110
+ let plannedVersion = this._version.value;
2111
+ for (let i = 0; i < sorted.length; i++) {
2112
+ const m = sorted[i];
2113
+ if (m[0] !== "DATA") continue;
2114
+ plannedVersion = advanceNodeVersion(plannedVersion, this._version.policy, m[1]);
2115
+ plannedVersions[i] = plannedVersion;
2116
+ }
2117
+ }
2118
+ if (hasTier3 && !this._wave.insideRunWave && !this._wave.emittedDirtyThisWave) {
2119
+ this._wave.emittedDirtyThisWave = true;
2120
+ this._value.status = "dirty";
2121
+ this._emitToSubs(["DIRTY"], { wave: deliveryWave, last: false });
2122
+ }
2123
+ for (let i = 0; i < sorted.length; i++) {
2124
+ const m = sorted[i];
2125
+ const delivery = { wave: deliveryWave, last: i === sorted.length - 1 };
2126
+ if (isDeferredTier(m[0])) this._wave.emittedSettleThisWave = true;
2127
+ if (m[0] === "DIRTY") {
2128
+ if (!this._wave.emittedDirtyThisWave) {
2129
+ this._wave.emittedDirtyThisWave = true;
2130
+ this._value.status = "dirty";
2131
+ this._emitToSubs(["DIRTY"], delivery);
2132
+ }
2133
+ continue;
2134
+ }
2135
+ if (m[0] === "DATA") {
2136
+ const v = m[1];
2137
+ this._value.cache = v;
2138
+ this._value.hasData = true;
2139
+ this._value.status = "settled";
2140
+ this._version.value = plannedVersions[i];
2141
+ if (this._slot.replayN > 0) {
2142
+ this._value.replayRing.push(v);
2143
+ if (this._value.replayRing.length > this._slot.replayN) this._value.replayRing.shift();
2144
+ }
2145
+ this._emitToSubs(["DATA", v], delivery);
2146
+ continue;
2147
+ }
2148
+ if (m[0] === "RESOLVED") {
2149
+ this._value.status = this._value.hasData ? "resolved" : "sentinel";
2150
+ this._emitToSubs(["RESOLVED"], delivery);
2151
+ continue;
2152
+ }
2153
+ if (m[0] === "INVALIDATE") {
2154
+ this._invalidate(delivery);
2155
+ continue;
2156
+ }
2157
+ if (m[0] === "COMPLETE") {
2158
+ if (this._value.terminal !== void 0) continue;
2159
+ this._value.terminal = true;
2160
+ this._control.pauseBuffer = [];
2161
+ this._value.status = "completed";
2162
+ this._emitToSubs(["COMPLETE"], delivery);
2163
+ continue;
2164
+ }
2165
+ if (m[0] === "ERROR") {
2166
+ if (this._value.terminal !== void 0) continue;
2167
+ this._value.terminal = m[1];
2168
+ this._control.pauseBuffer = [];
2169
+ this._value.status = "errored";
2170
+ this._emitToSubs(["ERROR", m[1]], delivery);
2171
+ continue;
2172
+ }
2173
+ if (m[0] === "TEARDOWN") {
2174
+ this._value.hasTorndown = true;
2175
+ if (this._slot.resetOnTeardown) {
2176
+ this._value.cache = SENTINEL;
2177
+ this._value.hasData = false;
2178
+ }
2179
+ this._emitToSubs(["TEARDOWN"], delivery);
2180
+ }
2181
+ }
2182
+ if (!this._wave.insideRunWave) this._wave.emittedDirtyThisWave = false;
2183
+ }
2184
+ _up(msgs, towardDep, route) {
2185
+ if (this._released) return;
2186
+ const routeState = route ?? { demandFired: /* @__PURE__ */ new Map() };
2187
+ for (const m of msgs) {
2188
+ if (!isUpAllowed(m[0])) {
2189
+ throw new Error(
2190
+ `ctx.up: ${m[0]} is down-only (tier ${messageTier(m[0])}); up carries control tiers only (R-ctx-up)`
2191
+ );
2192
+ }
2193
+ }
2194
+ for (const m of msgs) {
2195
+ if (m[0] === "PAUSE") {
2196
+ this._pauseAcquire(m[1]);
2197
+ } else if (m[0] === "RESUME") {
2198
+ if (this._slot.pull && m[1] === this._slot.pullLock) {
2199
+ if (!this._markDemandRouted(m[1], routeState)) this._onDemand();
2200
+ } else if (this._control.pauseLockset.has(m[1])) {
2201
+ this._pauseRelease(m[1]);
2202
+ } else {
2203
+ this._forwardUp(m, towardDep, routeState);
2204
+ }
2205
+ } else if (this._slot.deps.length === 0) {
2206
+ if (m[0] === "INVALIDATE") this._down([["INVALIDATE"]]);
2207
+ } else {
2208
+ this._forwardUp(m, towardDep, routeState);
2209
+ }
2210
+ }
2211
+ }
2212
+ _markDemandRouted(lockId, route) {
2213
+ let holders = route.demandFired.get(lockId);
2214
+ if (holders === void 0) {
2215
+ holders = /* @__PURE__ */ new Set();
2216
+ route.demandFired.set(lockId, holders);
2217
+ }
2218
+ if (holders.has(this)) return true;
2219
+ holders.add(this);
2220
+ return false;
2221
+ }
2222
+ /**
2223
+ * Forward one up-going control message toward deps (R-up-routing): up the single declared edge
2224
+ * `towardDep` (directed — prunes other branches; only meaningful on the issuer's FIRST hop) or
2225
+ * broadcast up ALL deps. A depless source has no deps → the message DROPS here (the terminus —
2226
+ * e.g. a cone-routed RESUME whose pullId no node up this cone holds, R-up-at-source). Recursive
2227
+ * forwarding carries the same per-wave route state and no `towardDep` → broadcast beyond the
2228
+ * first hop.
2229
+ */
2230
+ _forwardUp(m, towardDep, route) {
2231
+ if (this._slot.deps.length === 0) return;
2232
+ if (towardDep !== void 0) {
2233
+ const d = this._slot.deps[towardDep];
2234
+ if (d !== void 0) d._up([m], void 0, route);
2235
+ } else {
2236
+ for (const dep of this._slot.deps) dep._up([m], void 0, route);
2237
+ }
2238
+ }
2239
+ // ── PAUSE/RESUME lockset (R-pause-lockset) + modes (R-pause-modes) ──
2240
+ _isPaused() {
2241
+ return this._control.pauseLockset.size > 0;
2242
+ }
2243
+ _hasBoundaryPauseLock() {
2244
+ if (this._slot.pausable === false) return false;
2245
+ let locks = this._control.pauseLockset.size;
2246
+ if (this._slot.pull && this._control.pauseLockset.has(this._slot.pullLock)) locks--;
2247
+ return locks > 0;
2248
+ }
2249
+ _isAsyncPool() {
2250
+ return this._slot.handle !== null && this._slot.dispatcher.poolKind(this._slot.handle.poolId) === "async";
2251
+ }
2252
+ _pauseAcquire(lockId) {
2253
+ this._control.pauseLockset.add(lockId);
2254
+ }
2255
+ _pauseRelease(lockId) {
2256
+ if (!this._control.pauseLockset.has(lockId)) return;
2257
+ this._control.pauseLockset.delete(lockId);
2258
+ if (this._slot.pull && this._control.demandOwed) this._fireOwedDemandIfReady();
2259
+ if (this._hasBoundaryPauseLock()) return;
2260
+ scheduleBoundaryDrain(this._core);
2261
+ if (this._control.pauseLockset.size > 0) return;
2262
+ this._onResume();
2263
+ }
2264
+ _onResume() {
2265
+ if (this._value.terminal !== void 0) {
2266
+ this._control.pauseBuffer = [];
2267
+ this._control.pausedDepWaveOccurred = false;
2268
+ this._control.demandOwed = false;
2269
+ return;
2270
+ }
2271
+ if (this._control.pauseBuffer.length > 0) {
2272
+ const buf = this._control.pauseBuffer;
2273
+ this._control.pauseBuffer = [];
2274
+ for (const wave of buf) this._down(wave);
2275
+ }
2276
+ if (this._control.pausedDepWaveOccurred) {
2277
+ this._control.pausedDepWaveOccurred = false;
2278
+ this._tryRun();
2279
+ }
2280
+ }
2281
+ /**
2282
+ * R-pull (D59): can this pull node fire a demand NOW? — not terminal, settle-ready (_pending===0),
2283
+ * and no OTHER (non-pullId) lock holds it paused. The gate that decides fire-now vs OWE.
2284
+ */
2285
+ _canFireDemand() {
2286
+ if (this._value.terminal !== void 0 || this._wave.pending > 0) return false;
2287
+ const own = this._control.pauseLockset.has(this._slot.pullLock) ? 1 : 0;
2288
+ return this._control.pauseLockset.size <= own;
2289
+ }
2290
+ /**
2291
+ * R-pull (D59): deliver ONE demand pulse — release the pullId so the demand wave RELAYS (not
2292
+ * absorbed), fire it, then RE-QUIET (1:1). The pullId re-add + the re-entrancy flag are in a
2293
+ * `finally` so a throwing pull fn (graph-less node, no D30 catch) cannot leave the node
2294
+ * permanently non-quiet (the wedge-fix silently disabled) — QA-found robustness fix.
2295
+ */
2296
+ _deliverPullDemand() {
2297
+ this._control.demandOwed = false;
2298
+ this._control.inDeliverDemand = true;
2299
+ this._control.pauseLockset.delete(this._slot.pullLock);
2300
+ try {
2301
+ this._firePullDemand();
2302
+ } finally {
2303
+ this._control.pauseLockset.add(this._slot.pullLock);
2304
+ this._control.inDeliverDemand = false;
2305
+ }
2306
+ }
2307
+ /**
2308
+ * R-pull (D59): a cone-routed RESUME of THIS node's pullId arrived (R-up-routing) = a DEMAND.
2309
+ * Fire immediately if able; else OWE it — pin-5 (a dep DIRTY in flight, _pending>0) or F4/F5 (an
2310
+ * external PAUSE lock co-holds the node) — and fire when the node next becomes able. A demand
2311
+ * arriving WHILE a delivery is in flight (synchronous re-entry) is DROPPED (1:1, QA guard).
2312
+ */
2313
+ _onDemand() {
2314
+ if (this._control.inDeliverDemand) return;
2315
+ if (this._canFireDemand()) this._deliverPullDemand();
2316
+ else this._control.demandOwed = true;
2317
+ }
2318
+ /**
2319
+ * R-pull (D55): service ONE demand. Delivery content = the orthogonal pausable mode:
2320
+ * - 'resumeAll' → drain the buffered BACKLOG (each `_down` re-synthesizes a leading DIRTY, so
2321
+ * the per-entry replay is DIRTY-before-DATA — R-pause-modes per-entry arrival order);
2322
+ * - true → deliver the coalesced LATEST as ONE DIRTY-before-DATA wave (pin 2: the quiet absorb
2323
+ * suppressed the dep's original DIRTY, so the demand wave restores it before the value).
2324
+ * Neither branch fires when nothing changed since the last demand → the demand is SILENT.
2325
+ * Called by `_deliverPullDemand` only when settle-ready; the caller has released the pullId, so
2326
+ * `_markDirty` relays the leading DIRTY (not absorbed).
2327
+ */
2328
+ _firePullDemand() {
2329
+ if (this._control.pauseBuffer.length > 0) {
2330
+ const buf = this._control.pauseBuffer;
2331
+ this._control.pauseBuffer = [];
2332
+ for (const wave of buf) this._down(wave);
2333
+ }
2334
+ if (this._control.pausedDepWaveOccurred) {
2335
+ const gated = this._slot.handle !== null && !this._wave.hasCalledFnOnce && !(this._slot.partial || this._allDepsSettled());
2336
+ if (this._wave.pending > 0 || gated) return;
2337
+ this._control.pausedDepWaveOccurred = false;
2338
+ this._markDirty();
2339
+ this._tryRun();
2340
+ }
2341
+ }
2342
+ /**
2343
+ * R-pull (D55/D59): fire a demand that was OWED (deferred at demand time) once the node becomes
2344
+ * able — called from the dep-settle arms (DATA/RESOLVED/INVALIDATE/terminal drain _pending, pin-5
2345
+ * + B1/F6) and from `_pauseRelease` (an external PAUSE lock releases, F4/F5).
2346
+ */
2347
+ _fireOwedDemandIfReady() {
2348
+ if (this._control.inDeliverDemand) return;
2349
+ if (this._slot.pull && this._control.demandOwed && this._canFireDemand())
2350
+ this._deliverPullDemand();
2351
+ }
2352
+ /** Should an outgoing settle slice be deferred into the pause buffer? */
2353
+ _shouldBufferOnPause() {
2354
+ if (this._slot.pausable === false) return false;
2355
+ if (!this._isPaused()) return false;
2356
+ if (this._slot.pausable === "resumeAll") return true;
2357
+ if (!this._wave.insideRunWave && this._isAsyncPool() && this._slot.deps.length > 0) return true;
2358
+ return false;
2359
+ }
2360
+ /** R-invalidate-idempotent: clear cache + flush + cascade; no-op if nothing cached. */
2361
+ _invalidate(delivery) {
2362
+ if (!this._value.hasData) return;
2363
+ this._value.cache = SENTINEL;
2364
+ this._value.hasData = false;
2365
+ this._value.status = "sentinel";
2366
+ this._value.replayRing = [];
2367
+ for (const fn of this._hooks.onInvalidate) fn();
2368
+ this._emitToSubs(["INVALIDATE"], delivery);
2369
+ }
2370
+ // B42 (R-deps-terminal): ALL deps TERMINAL = every dep has reached COMPLETE *or* an ABSORBED
2371
+ // ERROR. Block only on a LIVE dep (_depTerminal[i] === undefined); an errored dep (terminal = the
2372
+ // error payload, which R-data-payload guarantees is !== undefined and non-boolean) COUNTS as
2373
+ // terminal-done. Was
2374
+ // `tm !== true`, which wedged a node whose errorWhenDepsError:false dep ERRORed (it never
2375
+ // auto-completed even after every other dep completed). Drives the completeWhenDepsComplete cascade.
2376
+ _allDepsTerminal() {
2377
+ if (this._slot.deps.length === 0) return false;
2378
+ for (const tm of this._dep.terminal) if (tm === void 0) return false;
2379
+ return true;
2380
+ }
2381
+ /** R-terminal: resubscribable reset clears terminal + dep state + re-arms the gate. */
2382
+ _resetLifecycle() {
2383
+ for (const u of this._dep.unsubs) if (u) u();
2384
+ this._dep.unsubs = [];
2385
+ this._dep.idxBoxes = [];
2386
+ this._lifecycle.subscribers.clear();
2387
+ this._lifecycle.activated = false;
2388
+ this._value.terminal = void 0;
2389
+ this._value.hasTorndown = false;
2390
+ this._wave.hasCalledFnOnce = false;
2391
+ this._resetDepState();
2392
+ this._control.pauseLockset.clear();
2393
+ this._control.pauseBuffer = [];
2394
+ this._control.pausedDepWaveOccurred = false;
2395
+ this._control.demandOwed = false;
2396
+ this._value.replayRing = [];
2397
+ const isCompute = this._slot.handle !== null || this._slot.deps.length > 0;
2398
+ if (isCompute) {
2399
+ this._value.cache = SENTINEL;
2400
+ this._value.hasData = false;
2401
+ this._value.status = "sentinel";
2402
+ } else {
2403
+ this._value.status = this._value.hasData ? "settled" : "sentinel";
2404
+ }
2405
+ if (!this._privateState.persist) this._privateState.value = SENTINEL;
2406
+ }
2407
+ _emitToSubs(msg, delivery) {
2408
+ if (this._released) return;
2409
+ const subs = [...this._lifecycle.subscribers];
2410
+ for (const sink of subs) sink(msg, delivery);
2411
+ }
2412
+ /** Batch commit (R-batch-coalesce): deliver the deferred tier-3 wave now. */
2413
+ __commitBatchedWave(wave) {
2414
+ this._wave.batchDirtyOwed = false;
2415
+ this._down(wave);
2416
+ }
2417
+ /** Batch rollback: balance the immediate DIRTY with a RESOLVED so downstream un-dirties. */
2418
+ __rollbackBatched() {
2419
+ if (this._wave.batchDirtyOwed) {
2420
+ this._wave.batchDirtyOwed = false;
2421
+ this._wave.emittedDirtyThisWave = false;
2422
+ this._value.status = this._value.hasData ? "settled" : "sentinel";
2423
+ this._emitToSubs(["RESOLVED"]);
2424
+ }
2425
+ }
2426
+ /** B49: enqueue a committed-boundary task on this node's graph-local core. */
2427
+ __deferBoundary(fn, batchToken) {
2428
+ deferRewire(this._core, fn, {
2429
+ batchToken,
2430
+ isReady: () => !this._hasBoundaryPauseLock()
2431
+ });
2432
+ }
2433
+ };
2434
+ function node(deps = [], handleOrFn = null, opts = {}) {
2435
+ return new Node(deps, handleOrFn, opts);
2436
+ }
2437
+ function dynamicNode(deps, fn, opts = {}) {
2438
+ return new Node(deps, fn, { ...opts, dynamic: true });
2439
+ }
2440
+ // Annotate the CommonJS export names for ESM import in node:
2441
+ 0 && (module.exports = {
2442
+ Dispatcher,
2443
+ Node,
2444
+ SENTINEL,
2445
+ TIER_CONTROL,
2446
+ TIER_NOTIFICATION,
2447
+ TIER_SETTLE,
2448
+ TIER_START,
2449
+ TIER_TEARDOWN,
2450
+ TIER_TERMINAL,
2451
+ TIER_VALUE,
2452
+ batch,
2453
+ defaultDispatcher,
2454
+ defaultNodeVersionHash,
2455
+ depBatch,
2456
+ depCount,
2457
+ depLatest,
2458
+ depTerminal,
2459
+ depWaves,
2460
+ dynamicNode,
2461
+ errorPayload,
2462
+ isDeferredTier,
2463
+ isInvalidErrorPayload,
2464
+ isPauseBufferedTier,
2465
+ isTerminal,
2466
+ isTerminalComplete,
2467
+ isTerminalError,
2468
+ isTerminalNone,
2469
+ isUpAllowed,
2470
+ isValueTier,
2471
+ messageTier,
2472
+ node,
2473
+ terminalErrorValue
2474
+ });
2475
+ //# sourceMappingURL=index.cjs.map