@isograph/pico 0.0.0-main-5f205c00

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.
package/dist/index.cjs ADDED
@@ -0,0 +1,1154 @@
1
+
2
+ //#region src/graph/marking.ts
3
+ function storeSourceValueAndFindDependentsToMark(source, value) {
4
+ source.value = value;
5
+ if (source.dependentsStatus === 1) return;
6
+ source.dependentsStatus = 1;
7
+ return source.firstDependent;
8
+ }
9
+ /**
10
+ * A source write makes its direct readers DIRTY. Readers farther up the
11
+ * graph become MAYBE_DIRTY. Queue the first node with a callback on each
12
+ * path. If its value changes, its refresh queues the next affected callbacks.
13
+ */
14
+ function markDependentsOfWrittenSource(initialQueue, first) {
15
+ let queue = initialQueue;
16
+ let pendingLazyBranches;
17
+ let firstLazyBranch;
18
+ let beyondCallbackStack;
19
+ let edge = first;
20
+ while (edge !== void 0) {
21
+ const node = edge.dependent;
22
+ edge = edge.nextDependentEdge;
23
+ const status = node.status;
24
+ if (status === 3) {
25
+ node.status = 1;
26
+ if (node.callbackState === 1) {
27
+ queue = queueNodeWithCallback(queue, node);
28
+ const firstDependent = node.firstDependent;
29
+ if (firstDependent !== void 0 && firstDependent !== node.firstKnownMarkedDependentEdge) (beyondCallbackStack ??= []).push(node);
30
+ } else if (node.firstDependent !== void 0) {
31
+ if (firstLazyBranch !== void 0) (pendingLazyBranches ??= []).push(firstLazyBranch);
32
+ firstLazyBranch = node;
33
+ } else if (node.firstRetain === void 0) recordMarkedUnneededNode(node);
34
+ } else if (status === 2) {
35
+ node.status = 1;
36
+ if ((node.traversalFlags & 1) !== 0) {
37
+ node.traversalFlags &= ~1;
38
+ if (node.callbackState === 1) queue = queueNodeWithCallback(queue, node);
39
+ else if (node.firstDependent !== void 0) {
40
+ if (firstLazyBranch !== void 0) (pendingLazyBranches ??= []).push(firstLazyBranch);
41
+ firstLazyBranch = node;
42
+ }
43
+ }
44
+ }
45
+ }
46
+ if (firstLazyBranch !== void 0) return markTransitiveDependentsMaybeDirty(queue, firstLazyBranch, pendingLazyBranches, beyondCallbackStack);
47
+ if (beyondCallbackStack !== void 0) markReadersBeyondQueuedCallbacks(beyondCallbackStack);
48
+ return queue;
49
+ }
50
+ function queueNodeWithCallback(queue, node) {
51
+ if (queue === void 0) return [node];
52
+ queue.push(node);
53
+ return queue;
54
+ }
55
+ function recordMarkedUnneededNode(node) {
56
+ markedUnneeded[markedUnneededCount] = node;
57
+ markedUnneededCount += 1;
58
+ }
59
+ /**
60
+ * Internal invariant: the first `markedUnneededCount` entries of
61
+ * `markedUnneeded` are the nodes that marking took out of `CLEAN` while they
62
+ * were unneeded, and every later entry is `undefined`. `markedUnneededCount`
63
+ * is 0 when an outermost operation returns.
64
+ */
65
+ const markedUnneeded = [];
66
+ let markedUnneededCount = 0;
67
+ /**
68
+ * Follow lazy readers until each path reaches a node with a callback.
69
+ * Queue that node for refresh. Collect its readers for marking beyond the
70
+ * callback after this walk finishes.
71
+ */
72
+ function markTransitiveDependentsMaybeDirty(initialQueue, firstLazyBranch, initialLazyStack, initialBeyondCallbackStack) {
73
+ let queue = initialQueue;
74
+ let pendingLazyBranches = initialLazyStack;
75
+ let beyondCallbackStack = initialBeyondCallbackStack;
76
+ let marked = firstLazyBranch;
77
+ while (marked !== void 0) {
78
+ let dependentEdge = marked.firstDependent;
79
+ while (dependentEdge !== void 0) {
80
+ const dependent = dependentEdge.dependent;
81
+ dependentEdge = dependentEdge.nextDependentEdge;
82
+ switch (dependent.status) {
83
+ case 3:
84
+ dependent.status = 2;
85
+ dependent.traversalFlags &= ~1;
86
+ if (dependent.callbackState === 1) {
87
+ queue = queueNodeWithCallback(queue, dependent);
88
+ const firstDependent = dependent.firstDependent;
89
+ if (firstDependent !== void 0 && firstDependent !== dependent.firstKnownMarkedDependentEdge) (beyondCallbackStack ??= []).push(dependent);
90
+ } else if (dependent.firstDependent !== void 0) if (dependentEdge === void 0) dependentEdge = dependent.firstDependent;
91
+ else (pendingLazyBranches ??= []).push(dependent);
92
+ else if (dependent.firstRetain === void 0) recordMarkedUnneededNode(dependent);
93
+ break;
94
+ case 2:
95
+ if ((dependent.traversalFlags & 1) !== 0) {
96
+ dependent.traversalFlags &= ~1;
97
+ if (dependent.callbackState === 1) queue = queueNodeWithCallback(queue, dependent);
98
+ else if (dependent.firstDependent !== void 0) if (dependentEdge === void 0) dependentEdge = dependent.firstDependent;
99
+ else (pendingLazyBranches ??= []).push(dependent);
100
+ }
101
+ break;
102
+ case 1:
103
+ case 0: break;
104
+ }
105
+ }
106
+ marked = pendingLazyBranches === void 0 ? void 0 : pendingLazyBranches.pop();
107
+ }
108
+ if (beyondCallbackStack !== void 0) markReadersBeyondQueuedCallbacks(beyondCallbackStack);
109
+ return queue;
110
+ }
111
+ /**
112
+ * A queued callback node may keep its value. Mark its readers MAYBE_DIRTY so
113
+ * a nested read can verify them. If the callback node changes, its refresh
114
+ * queues the readers that need to run.
115
+ */
116
+ function markReadersBeyondQueuedCallbacks(beyondCallbackStack) {
117
+ let marked = beyondCallbackStack.pop();
118
+ while (marked !== void 0) {
119
+ let dependentEdge = marked.firstDependent;
120
+ const stop = marked.firstKnownMarkedDependentEdge;
121
+ if (dependentEdge !== stop) {
122
+ marked.firstKnownMarkedDependentEdge = dependentEdge;
123
+ while (dependentEdge !== stop) {
124
+ const dependent = dependentEdge.dependent;
125
+ dependentEdge = dependentEdge.nextDependentEdge;
126
+ if (dependent.status === 3) {
127
+ dependent.status = 2;
128
+ dependent.traversalFlags |= 1;
129
+ const firstDependent = dependent.firstDependent;
130
+ if (firstDependent !== void 0) {
131
+ if (firstDependent !== dependent.firstKnownMarkedDependentEdge) beyondCallbackStack.push(dependent);
132
+ } else if (dependent.firstRetain === void 0) recordMarkedUnneededNode(dependent);
133
+ }
134
+ }
135
+ }
136
+ marked = beyondCallbackStack.pop();
137
+ }
138
+ }
139
+ /**
140
+ * A callback node changed during the flush. Its direct readers now need
141
+ * recomputing. A reader marked only through this callback (MARKED_BEYOND)
142
+ * still needs its callbacks queued. Follow its lazy readers until the
143
+ * next callback on each path, which will propagate its own change in turn.
144
+ *
145
+ * Every direct reader was already marked by the write. A reader reached
146
+ * earlier without crossing a callback already has its callbacks queued.
147
+ */
148
+ function markDependentsOfChangedDerivedNode(flushQueue, node) {
149
+ node.firstKnownMarkedDependentEdge = void 0;
150
+ let pendingLazyBranches;
151
+ let firstLazyBranch;
152
+ let edge = node.firstDependent;
153
+ while (edge !== void 0) {
154
+ const dependent = edge.dependent;
155
+ edge = edge.nextDependentEdge;
156
+ switch (dependent.status) {
157
+ case 2:
158
+ dependent.status = 1;
159
+ if ((dependent.traversalFlags & 1) !== 0) {
160
+ dependent.traversalFlags &= ~1;
161
+ if (dependent.callbackState === 1) flushQueue.push(dependent);
162
+ else if (dependent.firstDependent !== void 0) {
163
+ if (firstLazyBranch !== void 0) (pendingLazyBranches ??= []).push(firstLazyBranch);
164
+ firstLazyBranch = dependent;
165
+ }
166
+ }
167
+ break;
168
+ case 3:
169
+ case 1:
170
+ case 0: break;
171
+ }
172
+ }
173
+ if (firstLazyBranch !== void 0) markTransitiveDependentsMaybeDirty(flushQueue, firstLazyBranch, pendingLazyBranches, void 0);
174
+ }
175
+ function markMaybeDirtyDependentsDirty(first) {
176
+ let edge = first;
177
+ while (edge !== void 0) {
178
+ const node = edge.dependent;
179
+ edge = edge.nextDependentEdge;
180
+ if (node.status === 2) node.status = 1;
181
+ }
182
+ }
183
+ /**
184
+ * Keep the allocated array for the next write without retaining the nodes.
185
+ */
186
+ function clearMarkedUnneededNodes() {
187
+ for (let index = 0; index < markedUnneededCount; index += 1) markedUnneeded[index] = void 0;
188
+ markedUnneededCount = 0;
189
+ }
190
+
191
+ //#endregion
192
+ //#region src/graph/edges.ts
193
+ function createSourceEdge(dependency, dependent) {
194
+ return {
195
+ dependency,
196
+ dependent,
197
+ nextDependencyEdge: void 0,
198
+ previousDependentEdge: void 0,
199
+ nextDependentEdge: void 0
200
+ };
201
+ }
202
+ function addEdgeToSourceDependents(edge) {
203
+ const dependency = edge.dependency;
204
+ const head = dependency.firstDependent;
205
+ edge.previousDependentEdge = void 0;
206
+ edge.nextDependentEdge = head;
207
+ if (head !== void 0) head.previousDependentEdge = edge;
208
+ dependency.firstDependent = edge;
209
+ }
210
+ function addEdgeToDerivedDependents(edge) {
211
+ const dependency = edge.dependency;
212
+ const head = dependency.firstDependent;
213
+ edge.previousDependentEdge = void 0;
214
+ edge.nextDependentEdge = head;
215
+ if (head !== void 0) head.previousDependentEdge = edge;
216
+ dependency.firstDependent = edge;
217
+ }
218
+ function unlinkRemainingSourceDependencies(first) {
219
+ let edge = first;
220
+ do {
221
+ removeEdgeFromSourceDependents(edge);
222
+ edge = edge.nextDependencyEdge;
223
+ } while (edge !== void 0);
224
+ }
225
+ /**
226
+ * Unlinking preserves `nextDependencyEdge` so traversal can continue through the removed edge.
227
+ */
228
+ function removeEdgeFromSourceDependents(edge) {
229
+ const previous = edge.previousDependentEdge;
230
+ const next = edge.nextDependentEdge;
231
+ if (previous === void 0) edge.dependency.firstDependent = next;
232
+ else previous.nextDependentEdge = next;
233
+ if (next !== void 0) next.previousDependentEdge = previous;
234
+ }
235
+ /**
236
+ * Unlinking preserves `nextDependencyEdge` so traversal can continue through the removed edge.
237
+ */
238
+ function removeEdgeFromDerivedDependents(edge) {
239
+ const dependency = edge.dependency;
240
+ const next = edge.nextDependentEdge;
241
+ if (dependency.firstKnownMarkedDependentEdge === edge) dependency.firstKnownMarkedDependentEdge = next;
242
+ const previous = edge.previousDependentEdge;
243
+ if (previous === void 0) dependency.firstDependent = next;
244
+ else previous.nextDependentEdge = next;
245
+ if (next !== void 0) next.previousDependentEdge = previous;
246
+ }
247
+ /**
248
+ * Moves `edge` strictly before `edge.dependency.firstKnownMarkedDependentEdge` so `edge`'s
249
+ * dependent can become `CLEAN` while preserving the `firstKnownMarkedDependentEdge` invariant.
250
+ *
251
+ * Contract: `edge.dependency.firstKnownMarkedDependentEdge !== undefined`.
252
+ */
253
+ function moveEdgeBeforeKnownMarkedDependents(edge) {
254
+ const dependency = edge.dependency;
255
+ if (edge === dependency.firstKnownMarkedDependentEdge) dependency.firstKnownMarkedDependentEdge = edge.nextDependentEdge;
256
+ const previous = edge.previousDependentEdge;
257
+ if (previous !== void 0) {
258
+ const next = edge.nextDependentEdge;
259
+ previous.nextDependentEdge = next;
260
+ if (next !== void 0) next.previousDependentEdge = previous;
261
+ const head = dependency.firstDependent;
262
+ edge.previousDependentEdge = void 0;
263
+ edge.nextDependentEdge = head;
264
+ head.previousDependentEdge = edge;
265
+ dependency.firstDependent = edge;
266
+ }
267
+ }
268
+
269
+ //#endregion
270
+ //#region src/disposal/cleanup.ts
271
+ /**
272
+ * Pops one entry off the cleanup queue and disposes its node if the node is
273
+ * still unneeded and not `UNCOMPUTED`. Disposing a node puts each of its
274
+ * derived dependencies that becomes unneeded on the cleanup queue. Returns
275
+ * whether the cleanup queue is non-empty.
276
+ *
277
+ * Contract: called outside computations, batches, and `onChange` callbacks.
278
+ */
279
+ function disposeNext() {
280
+ const node = cleanupQueue.pop();
281
+ if (node !== void 0 && node.firstRetain === void 0 && node.firstDependent === void 0 && node.status !== 0) disposeNode(node, 0, void 0);
282
+ if (cleanupQueue.length > 0) return true;
283
+ scheduleStatus = 0;
284
+ return false;
285
+ }
286
+ /**
287
+ * The same node can be queued more than once and can become needed again
288
+ * before disposal. Each queue entry must be checked when it is drained.
289
+ * An unneeded node with a cached value belongs here or on the current write's
290
+ * marked-unneeded list. A tracked read can briefly hold it between pulling
291
+ * its value and linking its new dependent.
292
+ */
293
+ const cleanupQueue = [];
294
+ /** A pending request runs at the end of the outermost operation. */
295
+ let scheduleStatus = 0;
296
+ /**
297
+ * During a drain, push dependencies directly to the cleanup queue so the
298
+ * drain cannot schedule itself again. Queue callers pass no stack and can
299
+ * ignore the return value. Only DISPOSE_MARKED can create a stack to return:
300
+ * it collects newly unneeded dirty dependencies for disposal in the same pass.
301
+ * Clean dependencies go on the cleanup queue.
302
+ */
303
+ function disposeNode(node, kind, initialStack) {
304
+ let stack = initialStack;
305
+ const firstSource = node.firstSourceDependency;
306
+ if (firstSource !== void 0) unlinkRemainingSourceDependencies(firstSource);
307
+ let edge = node.firstDerivedDependency;
308
+ while (edge !== void 0) {
309
+ removeEdgeFromDerivedDependents(edge);
310
+ const dependency = edge.dependency;
311
+ if (dependency.firstDependent === void 0 && dependency.firstRetain === void 0) if (kind === 1) if (dependency.status === 3) addToCleanupQueue(dependency);
312
+ else (stack ??= []).push(dependency);
313
+ else cleanupQueue.push(dependency);
314
+ edge = edge.nextDependencyEdge;
315
+ }
316
+ node.firstSourceDependency = void 0;
317
+ node.lastSourceDependency = void 0;
318
+ node.firstDerivedDependency = void 0;
319
+ node.lastDerivedDependency = void 0;
320
+ node.firstKnownMarkedDependentEdge = void 0;
321
+ node.status = 0;
322
+ node.value = void 0;
323
+ return stack;
324
+ }
325
+ function addToCleanupQueue(node) {
326
+ if (cleanupQueue.length === 0) scheduleStatus = 1;
327
+ cleanupQueue.push(node);
328
+ }
329
+ /**
330
+ * Disposes every unneeded node on the cleanup queue, and each node that a
331
+ * disposal leaves unneeded.
332
+ *
333
+ * Guarantee: after `disposeNext` returns false, and after `disposeAll`
334
+ * returns, the cleanup queue is empty and no scheduler call is pending.
335
+ *
336
+ * Contract: as `disposeNext`.
337
+ */
338
+ function disposeAll() {
339
+ while (true) {
340
+ const node = cleanupQueue.pop();
341
+ if (node === void 0) {
342
+ scheduleStatus = 0;
343
+ return;
344
+ }
345
+ if (node.firstRetain === void 0 && node.firstDependent === void 0 && node.status !== 0) disposeNode(node, 0, void 0);
346
+ }
347
+ }
348
+ /**
349
+ * Internal invariant: a dependency that a disposal here leaves unneeded is
350
+ * disposed too if it is not `CLEAN`, because the same write marked it. If it
351
+ * is `CLEAN`, it goes on the cleanup queue with its value.
352
+ */
353
+ function disposeMarkedUnneededNodes() {
354
+ let stack;
355
+ for (let index = 0; index < markedUnneededCount; index += 1) {
356
+ let node = markedUnneeded[index];
357
+ while (node !== void 0) {
358
+ if (node.firstRetain === void 0 && node.firstDependent === void 0 && node.status !== 0 && node.status !== 3) stack = disposeNode(node, 1, stack);
359
+ node = stack?.pop();
360
+ }
361
+ }
362
+ clearMarkedUnneededNodes();
363
+ }
364
+ function requestCleanupScheduling() {
365
+ scheduleStatus = 1;
366
+ }
367
+ function clearPendingCleanupRequest() {
368
+ scheduleStatus = 0;
369
+ }
370
+
371
+ //#endregion
372
+ //#region src/batch/notifications.ts
373
+ /** Called once for each callback node whose recomputation changed its value. */
374
+ function recordChangedNode(node) {
375
+ changedNodes[changedCount] = node;
376
+ changedCount += 1;
377
+ }
378
+ /**
379
+ * Nodes whose callbacks are due after the current flush. Each changed node
380
+ * becomes `CLEAN` during refresh, so a later queue entry for it cannot add it
381
+ * again. Callbacks finish before another flush can reuse this array.
382
+ */
383
+ const changedNodes = [];
384
+ let changedCount = 0;
385
+ /**
386
+ * Calls the `onChange` of each retain of each node whose refresh changed its
387
+ * value, in the order of each node's first refresh that changed it.
388
+ */
389
+ function notifyRetainsOfChangedNodes() {
390
+ for (let index = 0; index < changedCount; index += 1) {
391
+ const node = changedNodes[index];
392
+ changedNodes[index] = void 0;
393
+ const value = node.value;
394
+ let retain = node.firstRetain;
395
+ while (retain !== void 0) {
396
+ if (retain.onChange !== void 0) retain.onChange(value);
397
+ retain = retain.nextRetain;
398
+ }
399
+ }
400
+ changedCount = 0;
401
+ }
402
+
403
+ //#endregion
404
+ //#region src/graph/recompute.ts
405
+ /**
406
+ * The first run starts with empty dependency lists. Every edge it creates
407
+ * belongs to this run, so there are no old edges to unlink.
408
+ */
409
+ function computeInitialDerivedValue(node) {
410
+ const value = node.computation(node, void 0);
411
+ node.status = 3;
412
+ node.value = value;
413
+ return value;
414
+ }
415
+ function recomputeValueAndMarkDependents(node) {
416
+ const previous = node.value;
417
+ const value = rerunComputationAndUpdateDependencies(node, previous);
418
+ if (value === previous) return previous;
419
+ node.value = value;
420
+ markMaybeDirtyDependentsDirty(node.firstDependent);
421
+ return value;
422
+ }
423
+ function rerunComputationAndUpdateDependencies(node, previous) {
424
+ node.lastSourceDependency = void 0;
425
+ node.lastDerivedDependency = void 0;
426
+ const value = node.computation(node, previous);
427
+ unlinkUnreadDependencies(node);
428
+ node.status = 3;
429
+ return value;
430
+ }
431
+ /**
432
+ * Unlink the edges after the last read in each dependency list. If the
433
+ * computation read no inputs of that kind, unlink the whole list.
434
+ */
435
+ function unlinkUnreadDependencies(node) {
436
+ const lastSource = node.lastSourceDependency;
437
+ if (lastSource === void 0) {
438
+ const first = node.firstSourceDependency;
439
+ if (first !== void 0) {
440
+ unlinkRemainingSourceDependencies(first);
441
+ node.firstSourceDependency = void 0;
442
+ }
443
+ } else if (lastSource.nextDependencyEdge !== void 0) {
444
+ unlinkRemainingSourceDependencies(lastSource.nextDependencyEdge);
445
+ lastSource.nextDependencyEdge = void 0;
446
+ }
447
+ const lastDerived = node.lastDerivedDependency;
448
+ if (lastDerived === void 0) {
449
+ const first = node.firstDerivedDependency;
450
+ if (first !== void 0) {
451
+ unlinkRemainingDerivedDependencies(first);
452
+ node.firstDerivedDependency = void 0;
453
+ }
454
+ } else if (lastDerived.nextDependencyEdge !== void 0) {
455
+ unlinkRemainingDerivedDependencies(lastDerived.nextDependencyEdge);
456
+ lastDerived.nextDependencyEdge = void 0;
457
+ }
458
+ }
459
+ function unlinkRemainingDerivedDependencies(first) {
460
+ let edge = first;
461
+ do {
462
+ removeEdgeFromDerivedDependents(edge);
463
+ const dependency = edge.dependency;
464
+ if (dependency.firstDependent === void 0 && dependency.firstRetain === void 0) addToCleanupQueue(dependency);
465
+ edge = edge.nextDependencyEdge;
466
+ } while (edge !== void 0);
467
+ }
468
+ /**
469
+ * A downstream node with a callback can be waiting for this result. If it
470
+ * changes, `markDependentsOfChangedDerivedNode` queues those readers for refresh. Returning
471
+ * `CHANGED` tells `refreshNodeAndRecordChange` to record this node for notification.
472
+ */
473
+ function recomputeAndQueueAffectedDependents(flushQueue, node) {
474
+ const previous = node.value;
475
+ const value = rerunComputationAndUpdateDependencies(node, previous);
476
+ if (value === previous) return 1;
477
+ node.value = value;
478
+ if (node.firstDependent !== void 0) markDependentsOfChangedDerivedNode(flushQueue, node);
479
+ return 0;
480
+ }
481
+
482
+ //#endregion
483
+ //#region src/graph/refresh.ts
484
+ /**
485
+ * Returns the current value of a derived node. During a flush, reading a node
486
+ * with a callback can refresh it ahead of its turn in the queue. The flush
487
+ * records any change so it can notify the callback after all refreshes finish.
488
+ */
489
+ function getCurrentDerivedValue(node) {
490
+ switch (node.status) {
491
+ case 3: return node.value;
492
+ case 1: return node.callbackState === 1 ? getCurrentValueForNodeWithCallback(node) : recomputeValueAndMarkDependents(node);
493
+ case 2: return node.callbackState === 1 ? getCurrentValueForNodeWithCallback(node) : getValueAfterVerifyingDependencies(node);
494
+ case 0: return computeInitialDerivedValue(node);
495
+ }
496
+ }
497
+ function getValueAfterVerifyingDependencies(node) {
498
+ return verifyDerivedDependencies(node) === 1 ? recomputeValueAndMarkDependents(node) : node.value;
499
+ }
500
+ /**
501
+ * During a flush, use the active queue so this read can record a change
502
+ * and queue downstream nodes that need refreshing. Outside a flush,
503
+ * a node can still be `MAYBE_DIRTY` after an input kept its value. A read
504
+ * verifies that input before deciding whether to rerun the node.
505
+ */
506
+ function getCurrentValueForNodeWithCallback(node) {
507
+ const queue = refreshQueue;
508
+ if (queue !== void 0) {
509
+ refreshNodeAndRecordChange(queue, node);
510
+ return node.value;
511
+ }
512
+ return node.status === 1 ? recomputeValueAndMarkDependents(node) : getValueAfterVerifyingDependencies(node);
513
+ }
514
+ /**
515
+ * Can requestedNode reuse its cached value? A write to a direct source
516
+ * already marks its reader DIRTY. Here the reader is MAYBE_DIRTY, so only
517
+ * its derived inputs need checking.
518
+ *
519
+ * Suppose A read B1, then B2. The outer loop checks A → B1 first. If B1
520
+ * is lazy and MAYBE_DIRTY, the loop starts checking B1's inputs. Once B1
521
+ * is up to date, the inner loop recovers A → B1 to get back to A.
522
+ * A must rerun if either B1 or B2 changed. If A is still MAYBE_DIRTY
523
+ * after checking B1, check B2. If either input marks A DIRTY, stop
524
+ * checking. A's rerun will read the inputs it needs. If both inputs kept
525
+ * their values, A becomes CLEAN and keeps its cached value.
526
+ */
527
+ function verifyDerivedDependencies(requestedNode) {
528
+ let savedReaderEdges;
529
+ let nodeBeingVerified = requestedNode;
530
+ let nextInputEdge = requestedNode.firstDerivedDependency;
531
+ while (true) {
532
+ if (nextInputEdge !== void 0) {
533
+ const derivedInput = nextInputEdge.dependency;
534
+ if (derivedInput.firstKnownMarkedDependentEdge !== void 0) moveEdgeBeforeKnownMarkedDependents(nextInputEdge);
535
+ if (derivedInput.status === 2 && derivedInput.callbackState !== 1) {
536
+ if (nextInputEdge.previousDependentEdge !== void 0 || nextInputEdge.nextDependentEdge !== void 0) (savedReaderEdges ??= []).push(nextInputEdge);
537
+ nodeBeingVerified = derivedInput;
538
+ nextInputEdge = derivedInput.firstDerivedDependency;
539
+ continue;
540
+ }
541
+ if (derivedInput.status !== 3) getCurrentDerivedValue(derivedInput);
542
+ if (nodeBeingVerified.status !== 1) {
543
+ nextInputEdge = nextInputEdge.nextDependencyEdge;
544
+ continue;
545
+ }
546
+ if (nodeBeingVerified === requestedNode) return 1;
547
+ recomputeValueAndMarkDependents(nodeBeingVerified);
548
+ } else nodeBeingVerified.status = 3;
549
+ while (true) {
550
+ if (nodeBeingVerified === requestedNode) return 3;
551
+ let edgeBackToReader;
552
+ if (savedReaderEdges !== void 0 && savedReaderEdges.length > 0 && savedReaderEdges[savedReaderEdges.length - 1].dependency === nodeBeingVerified) edgeBackToReader = savedReaderEdges.pop();
553
+ else edgeBackToReader = nodeBeingVerified.firstDependent;
554
+ nodeBeingVerified = edgeBackToReader.dependent;
555
+ if (nodeBeingVerified.status !== 1) {
556
+ nextInputEdge = edgeBackToReader.nextDependencyEdge;
557
+ break;
558
+ }
559
+ if (nodeBeingVerified === requestedNode) return 1;
560
+ recomputeValueAndMarkDependents(nodeBeingVerified);
561
+ }
562
+ }
563
+ }
564
+ function refreshNodeAndRecordChange(flushQueue, node) {
565
+ if (refreshNodeIfItHasCallback(flushQueue, node) === 0) recordChangedNode(node);
566
+ }
567
+ function refreshNodeIfItHasCallback(flushQueue, node) {
568
+ if (node.callbackState !== 1) return 1;
569
+ switch (node.status) {
570
+ case 1: return recomputeAndQueueAffectedDependents(flushQueue, node);
571
+ case 2: return verifyDerivedDependencies(node) === 1 ? recomputeAndQueueAffectedDependents(flushQueue, node) : 1;
572
+ case 3:
573
+ case 0: return 1;
574
+ }
575
+ }
576
+ /**
577
+ * While the flush refreshes A, A's computation can read B before B's turn
578
+ * in the queue. That read refreshes B immediately. If B changes, the pull
579
+ * uses this same queue for B's affected readers and records B for notification.
580
+ * The refresh loop clears this reference before callbacks run.
581
+ */
582
+ let refreshQueue;
583
+ function refreshNodesInFlushQueue(flushQueue) {
584
+ refreshQueue = flushQueue;
585
+ for (let index = 0; index < flushQueue.length; index += 1) refreshNodeAndRecordChange(flushQueue, flushQueue[index]);
586
+ refreshQueue = void 0;
587
+ }
588
+
589
+ //#endregion
590
+ //#region src/batch/flush.ts
591
+ let flushState = 0;
592
+ /**
593
+ * Guarantee: every `onChange` runs after the flush has refreshed every node
594
+ * on the flush queue, in the order of each node's first recompute that
595
+ * changed its value.
596
+ *
597
+ * Internal invariant: an `onChange` writes nothing, so it puts no node on the
598
+ * flush queue and no node on the marked-unneeded list.
599
+ */
600
+ function refreshQueuedNodesAndNotifyCallbacks(flushQueue) {
601
+ flushState = 1;
602
+ refreshNodesInFlushQueue(flushQueue);
603
+ if (markedUnneededCount > 0) disposeMarkedUnneededNodes();
604
+ notifyRetainsOfChangedNodes();
605
+ flushState = 0;
606
+ }
607
+
608
+ //#endregion
609
+ //#region src/disposal/age-drain.ts
610
+ /**
611
+ * Disposes unneeded nodes whose newest queue entry is older than the age
612
+ * boundary, then any dependencies those disposals leave unneeded. Returns
613
+ * the number of remaining entries, excluding the boundary marker.
614
+ *
615
+ * Each boundary in positions must still refer to the same group of surviving
616
+ * entries after compaction. The backward scan counts entries after each
617
+ * boundary. The final pass converts those counts back into queue indices.
618
+ * All SCAN_SEEN bits are clear on entry and again before disposal begins.
619
+ */
620
+ function disposeEligibleCleanupEntries(eligibleEnd, positions, count, marker, outOfTime) {
621
+ const queue = cleanupQueue;
622
+ const originalLength = queue.length;
623
+ let firstKept = originalLength;
624
+ let eligibleCount = 0;
625
+ let boundaryIndex = count - 1;
626
+ for (let index = originalLength - 1; index >= 0; index -= 1) {
627
+ while (boundaryIndex >= 0 && positions[boundaryIndex] > index) {
628
+ positions[boundaryIndex] = originalLength - firstKept;
629
+ boundaryIndex -= 1;
630
+ }
631
+ const node = queue[index];
632
+ if (node.firstRetain !== void 0 || node.firstDependent !== void 0 || node.status === 0 || (node.traversalFlags & 2) !== 0) continue;
633
+ node.traversalFlags |= 2;
634
+ firstKept -= 1;
635
+ queue[firstKept] = node;
636
+ if (index < eligibleEnd) eligibleCount += 1;
637
+ }
638
+ for (let index = firstKept; index < originalLength; index += 1) queue[index].traversalFlags &= ~2;
639
+ const firstYoung = firstKept + eligibleCount;
640
+ let nextEligible = firstKept;
641
+ let budgetExpired = false;
642
+ for (; nextEligible < firstYoung; nextEligible += 1) {
643
+ if (nextEligible > firstKept && outOfTime !== void 0 && outOfTime()) {
644
+ budgetExpired = true;
645
+ break;
646
+ }
647
+ disposeNode(queue[nextEligible], 0, void 0);
648
+ }
649
+ const disposedCount = nextEligible - firstKept;
650
+ let nextCascade = originalLength;
651
+ if (!budgetExpired) for (; nextCascade < queue.length; nextCascade += 1) {
652
+ const node = queue[nextCascade];
653
+ if (node.firstRetain === void 0 && node.firstDependent === void 0 && node.status !== 0) {
654
+ if (outOfTime !== void 0 && outOfTime()) {
655
+ budgetExpired = true;
656
+ break;
657
+ }
658
+ disposeNode(node, 0, void 0);
659
+ }
660
+ }
661
+ const pendingCascade = budgetExpired ? queue.slice(nextCascade) : void 0;
662
+ const pendingCount = pendingCascade === void 0 ? 0 : pendingCascade.length;
663
+ const keptCount = originalLength - firstKept;
664
+ const remainingCount = keptCount - disposedCount;
665
+ queue.copyWithin(pendingCount, firstKept + disposedCount, originalLength);
666
+ if (pendingCascade !== void 0) for (let index = 0; index < pendingCount; index += 1) queue[index] = pendingCascade[index];
667
+ queue.length = pendingCount + remainingCount;
668
+ for (let index = 0; index < count; index += 1) positions[index] = pendingCount + keptCount - positions[index] - disposedCount;
669
+ if (pendingCount + remainingCount > 0) queue.push(marker);
670
+ drainReachedTimeLimit = budgetExpired;
671
+ pendingCascadeCount = pendingCount;
672
+ return pendingCount + remainingCount;
673
+ }
674
+ /** True if the last drain skipped eligible work because its time budget expired. */
675
+ let drainReachedTimeLimit = false;
676
+ /** Nodes left at the front of the queue for disposal regardless of age. */
677
+ let pendingCascadeCount = 0;
678
+
679
+ //#endregion
680
+ //#region src/graph/nodes.ts
681
+ function createSourceNode(value) {
682
+ return {
683
+ value,
684
+ firstDependent: void 0,
685
+ dependentsStatus: 1
686
+ };
687
+ }
688
+ /**
689
+ * Returns an `UNCOMPUTED` derived node.
690
+ *
691
+ * Contract: `computation` is synchronous. `computation` reads other nodes
692
+ * only through `readSource` and `readDerived`, called with the `callingNode`
693
+ * that `computation` receives, and does not keep that `callingNode` for use
694
+ * after it returns. `computation` does not write, start or end a batch, retain,
695
+ * release, dispose, or call `readDerivedOutsideComputation`.
696
+ */
697
+ function createDerivedNode(computation) {
698
+ return {
699
+ value: void 0,
700
+ firstRetain: void 0,
701
+ traversalFlags: 0,
702
+ status: 0,
703
+ callbackState: 0,
704
+ firstSourceDependency: void 0,
705
+ lastSourceDependency: void 0,
706
+ firstDerivedDependency: void 0,
707
+ lastDerivedDependency: void 0,
708
+ firstDependent: void 0,
709
+ firstKnownMarkedDependentEdge: void 0,
710
+ computation
711
+ };
712
+ }
713
+
714
+ //#endregion
715
+ //#region src/disposal/update-counter.ts
716
+ function incrementUpdateCount() {
717
+ updateCount += 1;
718
+ }
719
+ /**
720
+ * Counts outermost updates that reach the end of write processing. Cleanup
721
+ * uses this count to age queue entries.
722
+ */
723
+ let updateCount = 0;
724
+
725
+ //#endregion
726
+ //#region src/disposal/older-than-updates.ts
727
+ /**
728
+ * Disposes unneeded nodes whose newest cleanup entry is at least minAge
729
+ * updates old. Age starts at the first drain that sees an entry. A write
730
+ * or batch commit advances the update count. Repeated drains do not.
731
+ * Disposing a node can leave its inputs unneeded; these are eligible immediately.
732
+ *
733
+ * An optional idle deadline or performance.now() timestamp limits disposal.
734
+ * The queue scan always finishes, and the first eligible disposal always
735
+ * runs. Unfinished entries keep their ages for the next drain. If another
736
+ * disposal strategy removed the boundary marker between drains, the
737
+ * remaining entries start aging again at the current update count.
738
+ *
739
+ * Returns the number of entries still queued. When entries remain, request
740
+ * another scheduler call at the end of the next outermost operation.
741
+ * Call outside computations, batches, and callbacks, with an integer minAge.
742
+ */
743
+ function disposeOlderThanUpdates(minAge, budget) {
744
+ const length = cleanupQueue.length;
745
+ const now = updateCount;
746
+ let count = boundaryCount;
747
+ if (count > 0 && cleanupQueue[positions[count - 1]] !== marker) count = 0;
748
+ let eligibleEnd = minAge <= 0 ? length : 0;
749
+ if (minAge > 0) {
750
+ for (let index = count - 1; index >= 0; index -= 1) if (now - updates[index] >= minAge) {
751
+ eligibleEnd = positions[index];
752
+ break;
753
+ }
754
+ }
755
+ marker ??= createDerivedNode(() => void 0);
756
+ const queued = disposeEligibleCleanupEntries(eligibleEnd, positions, count, marker, budget === void 0 ? void 0 : typeof budget === "number" ? () => performance.now() >= budget : () => budget.timeRemaining() <= 0);
757
+ const front = pendingCascadeCount;
758
+ let next = 0;
759
+ for (let index = 0; index < count; index += 1) {
760
+ const position = positions[index];
761
+ if (position > front) {
762
+ positions[next] = position;
763
+ updates[next] = updates[index];
764
+ next += 1;
765
+ }
766
+ }
767
+ if (front > 0) {
768
+ for (let index = next; index > 0; index -= 1) {
769
+ positions[index] = positions[index - 1];
770
+ updates[index] = updates[index - 1];
771
+ }
772
+ positions[0] = front;
773
+ updates[0] = -Infinity;
774
+ next += 1;
775
+ }
776
+ if (queued === 0) {
777
+ boundaryCount = 0;
778
+ clearPendingCleanupRequest();
779
+ return 0;
780
+ }
781
+ if (next > 0 && positions[next - 1] === queued) boundaryCount = next;
782
+ else if (next > 0 && updates[next - 1] === now) {
783
+ positions[next - 1] = queued;
784
+ boundaryCount = next;
785
+ } else {
786
+ positions[next] = queued;
787
+ updates[next] = now;
788
+ boundaryCount = next + 1;
789
+ }
790
+ requestCleanupScheduling();
791
+ return queued;
792
+ }
793
+ const positions = [];
794
+ const updates = [];
795
+ let boundaryCount = 0;
796
+ /**
797
+ * An `UNCOMPUTED` node that a drain puts at its boundary. A disposal skips an
798
+ * `UNCOMPUTED` node, and nothing else queues this node, so it stays at its
799
+ * index until a call removes it together with every entry above it.
800
+ */
801
+ let marker;
802
+
803
+ //#endregion
804
+ //#region src/disposal/schedule.ts
805
+ /**
806
+ * `scheduler.schedule` is called with no arguments at the end of an outermost
807
+ * operation after the cleanup queue went from empty to non-empty, or after a
808
+ * `disposeOlderThanUpdates` that left entries. A `writeSource` to a source that
809
+ * has no dependents, or that no computation read since the source was created
810
+ * or last written, returns before that call. `schedule` may call `disposeAll`
811
+ * synchronously. The default calls `disposeOlderThanUpdates(2)` once per call
812
+ * of `schedule`, with the time of a `requestIdleCallback` callback where that
813
+ * exists and of a 5 ms `setTimeout` task elsewhere, and requests another
814
+ * callback or task only when that drain ran out of time before an old entry.
815
+ * Assigning `scheduler.schedule` replaces the default.
816
+ *
817
+ * Contract: after a call, the scheduler calls `disposeNext` until it returns
818
+ * false, calls `disposeAll`, or calls `disposeOlderThanUpdates` once.
819
+ */
820
+ const scheduler = { schedule: scheduleCleanupDuringIdleTime };
821
+ function scheduleCleanupDuringIdleTime() {
822
+ if (defaultScheduleStatus === 1) return;
823
+ defaultScheduleStatus = 1;
824
+ if (typeof requestIdleCallback === "function") requestIdleCallback(disposeOldNodesWithinTimeBudget);
825
+ else setTimeout(disposeOldNodesWithinTimeBudget, 0);
826
+ }
827
+ /**
828
+ * One drain with the idle period's time, or 5 ms in a `setTimeout` task,
829
+ * which passes no deadline. A drain disposes at least one old entry before it
830
+ * checks the time, so each callback that a cut-off requests makes progress. A
831
+ * drain that leaves only young entries requests nothing: the next outermost
832
+ * operation calls `schedule` again.
833
+ */
834
+ function disposeOldNodesWithinTimeBudget(deadline) {
835
+ defaultScheduleStatus = 0;
836
+ if (cleanupQueue.length === 0) return;
837
+ disposeOlderThanUpdates(DEFAULT_MIN_AGE, deadline ?? performance.now() + TIMEOUT_DISPOSAL_MS);
838
+ if (drainReachedTimeLimit) {
839
+ clearPendingCleanupRequest();
840
+ scheduleCleanupDuringIdleTime();
841
+ }
842
+ }
843
+ const DEFAULT_MIN_AGE = 2;
844
+ const TIMEOUT_DISPOSAL_MS = 5;
845
+ let defaultScheduleStatus = 0;
846
+ function scheduleCleanupIfRequested() {
847
+ if (scheduleStatus === 1) {
848
+ clearPendingCleanupRequest();
849
+ scheduler.schedule();
850
+ }
851
+ }
852
+
853
+ //#endregion
854
+ //#region src/batch/batch.ts
855
+ /** Stage a write in the open batch, or publish it immediately when no batch is open. */
856
+ function writeSource(source, value) {
857
+ if (firstPendingSource !== CLOSED_BATCH) {
858
+ const pending = source;
859
+ if (firstPendingSource === pending) firstPendingValue = value;
860
+ else if (firstPendingSource === void 0) {
861
+ firstPendingSource = pending;
862
+ firstPendingValue = value;
863
+ } else (otherWrites ??= /* @__PURE__ */ new Map()).set(pending, value);
864
+ return;
865
+ }
866
+ const firstDependentToMark = storeSourceValueAndFindDependentsToMark(source, value);
867
+ if (firstDependentToMark === void 0) return;
868
+ flushQueuedNodesOrDisposeMarkedNodes(markDependentsOfWrittenSource(void 0, firstDependentToMark));
869
+ countUpdateAndScheduleCleanupIfIdle();
870
+ }
871
+ const CLOSED_BATCH = Symbol("closed batch");
872
+ let firstPendingSource = CLOSED_BATCH;
873
+ let firstPendingValue;
874
+ let otherWrites;
875
+ function flushQueuedNodesOrDisposeMarkedNodes(queue) {
876
+ if (queue !== void 0) refreshQueuedNodesAndNotifyCallbacks(queue);
877
+ else if (markedUnneededCount > 0) disposeMarkedUnneededNodes();
878
+ }
879
+ function countUpdateAndScheduleCleanupIfIdle() {
880
+ if (flushState === 0) {
881
+ incrementUpdateCount();
882
+ scheduleCleanupIfRequested();
883
+ }
884
+ }
885
+ /** Open one synchronous write batch. Callers must not nest batches or read or retain nodes inside one. */
886
+ function startWriteBatch() {
887
+ if (firstPendingSource !== CLOSED_BATCH) throw new Error("A write batch is already open.");
888
+ firstPendingSource = void 0;
889
+ }
890
+ /** Publish the last write to each source, refresh the graph, then notify subscribers. */
891
+ function endWriteBatch() {
892
+ const source = firstPendingSource;
893
+ if (source === CLOSED_BATCH) return;
894
+ firstPendingSource = CLOSED_BATCH;
895
+ let queue;
896
+ if (source !== void 0) {
897
+ const firstDependentToMark = storeSourceValueAndFindDependentsToMark(source, firstPendingValue);
898
+ firstPendingValue = void 0;
899
+ if (firstDependentToMark !== void 0) queue = markDependentsOfWrittenSource(void 0, firstDependentToMark);
900
+ if (otherWrites !== void 0) {
901
+ for (const [other, value] of otherWrites) {
902
+ const edge = storeSourceValueAndFindDependentsToMark(other, value);
903
+ if (edge !== void 0) queue = markDependentsOfWrittenSource(queue, edge);
904
+ }
905
+ otherWrites = void 0;
906
+ }
907
+ }
908
+ flushQueuedNodesOrDisposeMarkedNodes(queue);
909
+ countUpdateAndScheduleCleanupIfIdle();
910
+ }
911
+ /**
912
+ * An outermost operation is a call to `writeSource`, `endWriteBatch`,
913
+ * `retainDerivedNode`, `releaseRetain`, or `readDerivedOutsideComputation` made with no
914
+ * batch open and no flush running, or the `endWriteBatch` that commits the writes.
915
+ *
916
+ * Internal invariant: a top-level read never runs inside a computation or a
917
+ * batch body (its contract), so a top-level read inside an `onChange` is the
918
+ * only nesting of operations outside a batch, and the flush state covers it.
919
+ */
920
+ function scheduleCleanupIfOutsideBatchAndFlush() {
921
+ if (firstPendingSource === CLOSED_BATCH && flushState === 0) scheduleCleanupIfRequested();
922
+ }
923
+ /**
924
+ * Top-level reads are forbidden in batch bodies. An onChange callback can
925
+ * still read during a flush.
926
+ */
927
+ function scheduleCleanupIfNotFlushing() {
928
+ if (flushState === 0) scheduleCleanupIfRequested();
929
+ }
930
+
931
+ //#endregion
932
+ //#region src/graph/read.ts
933
+ /**
934
+ * Returns the value of `source` and records it as a dependency of
935
+ * `callingNode`.
936
+ *
937
+ * Contract: called only while the computation of `callingNode` runs.
938
+ */
939
+ function readSource(callingNode, source) {
940
+ const mutableCallingNode = callingNode;
941
+ const mutableSource = source;
942
+ mutableSource.dependentsStatus = 0;
943
+ const lastReadEdge = mutableCallingNode.lastSourceDependency;
944
+ const reusableEdge = lastReadEdge === void 0 ? mutableCallingNode.firstSourceDependency : lastReadEdge.nextDependencyEdge;
945
+ if (reusableEdge !== void 0) {
946
+ if (reusableEdge.dependency !== mutableSource) {
947
+ removeEdgeFromSourceDependents(reusableEdge);
948
+ reusableEdge.dependency = mutableSource;
949
+ addEdgeToSourceDependents(reusableEdge);
950
+ }
951
+ mutableCallingNode.lastSourceDependency = reusableEdge;
952
+ } else if (lastReadEdge === void 0 || lastReadEdge.dependency !== mutableSource) {
953
+ const edge = createSourceEdge(mutableSource, mutableCallingNode);
954
+ addEdgeToSourceDependents(edge);
955
+ if (lastReadEdge === void 0) mutableCallingNode.firstSourceDependency = edge;
956
+ else lastReadEdge.nextDependencyEdge = edge;
957
+ mutableCallingNode.lastSourceDependency = edge;
958
+ }
959
+ return source.value;
960
+ }
961
+ /**
962
+ * Brings `node` up to date, returns its value, and records it as a dependency
963
+ * of `callingNode`.
964
+ *
965
+ * Contract: called only while the computation of `callingNode` runs.
966
+ */
967
+ function readDerived(callingNode, node) {
968
+ const mutableCallingNode = callingNode;
969
+ const mutableNode = node;
970
+ const value = getCurrentDerivedValue(mutableNode);
971
+ const lastReadEdge = mutableCallingNode.lastDerivedDependency;
972
+ const reusableEdge = lastReadEdge === void 0 ? mutableCallingNode.firstDerivedDependency : lastReadEdge.nextDependencyEdge;
973
+ if (reusableEdge !== void 0) {
974
+ if (reusableEdge.dependency !== mutableNode) {
975
+ const previousDependency = reusableEdge.dependency;
976
+ removeEdgeFromDerivedDependents(reusableEdge);
977
+ reusableEdge.dependency = mutableNode;
978
+ addEdgeToDerivedDependents(reusableEdge);
979
+ if (previousDependency.firstDependent === void 0 && previousDependency.firstRetain === void 0) addToCleanupQueue(previousDependency);
980
+ } else if (mutableNode.firstKnownMarkedDependentEdge !== void 0) moveEdgeBeforeKnownMarkedDependents(reusableEdge);
981
+ mutableCallingNode.lastDerivedDependency = reusableEdge;
982
+ } else if (lastReadEdge === void 0 || lastReadEdge.dependency !== mutableNode) {
983
+ const edge = {
984
+ dependency: mutableNode,
985
+ dependent: mutableCallingNode,
986
+ nextDependencyEdge: void 0,
987
+ previousDependentEdge: void 0,
988
+ nextDependentEdge: void 0
989
+ };
990
+ addEdgeToDerivedDependents(edge);
991
+ if (lastReadEdge === void 0) mutableCallingNode.firstDerivedDependency = edge;
992
+ else lastReadEdge.nextDependencyEdge = edge;
993
+ mutableCallingNode.lastDerivedDependency = edge;
994
+ }
995
+ return value;
996
+ }
997
+ /**
998
+ * Top-level read of `node`: brings `node` up to date and returns its value. A
999
+ * recompute links edges as in a tracked read. A node left unneeded goes on the
1000
+ * cleanup queue, so the scheduler can dispose it and each dependency that its
1001
+ * disposal leaves unneeded.
1002
+ *
1003
+ * Contract: called outside computations and write batch bodies. Inside an
1004
+ * `onChange`, it is allowed.
1005
+ */
1006
+ function readDerivedOutsideComputation(node) {
1007
+ const mutableNode = node;
1008
+ const value = getCurrentDerivedValue(mutableNode);
1009
+ if (mutableNode.firstRetain === void 0 && mutableNode.firstDependent === void 0) addToCleanupQueue(mutableNode);
1010
+ scheduleCleanupIfNotFlushing();
1011
+ return value;
1012
+ }
1013
+
1014
+ //#endregion
1015
+ //#region src/retention/retain.ts
1016
+ /**
1017
+ * Brings `node` up to date, adds a retain to the head of its retain list, and
1018
+ * returns the retain. A retained node keeps its value and its edges to its
1019
+ * dependencies until its last retain is released. A retain with an
1020
+ * `onChange` gives the node a callback.
1021
+ *
1022
+ * Guarantee: the flush calls `onChange` with the node's value once for each
1023
+ * update or batch that changed the node's value, after the flush has
1024
+ * refreshed every node on the flush queue. The first recompute of a node does
1025
+ * not call `onChange`.
1026
+ *
1027
+ * Contract: called outside computations, `onChange` callbacks, and write
1028
+ * batch bodies, because retaining computes the node. `onChange` does not
1029
+ * write, start or end a batch, retain, release, or dispose. It may call
1030
+ * `readDerivedOutsideComputation`.
1031
+ */
1032
+ function retainDerivedNode(node, onChange) {
1033
+ const mutableNode = node;
1034
+ getCurrentDerivedValue(mutableNode);
1035
+ const head = mutableNode.firstRetain;
1036
+ const retain = {
1037
+ node: mutableNode,
1038
+ onChange,
1039
+ previousRetain: void 0,
1040
+ nextRetain: head
1041
+ };
1042
+ if (head !== void 0) head.previousRetain = retain;
1043
+ mutableNode.firstRetain = retain;
1044
+ if (onChange !== void 0) mutableNode.callbackState = 1;
1045
+ scheduleCleanupIfRequested();
1046
+ return retain;
1047
+ }
1048
+ /**
1049
+ * Releases `retain`. A release that leaves the node unneeded puts the node on
1050
+ * the cleanup queue. The node keeps its value and its edges until a disposal,
1051
+ * or the marking of a write, reaches it.
1052
+ *
1053
+ * Contract: called once per retain, outside computations and `onChange`
1054
+ * callbacks.
1055
+ */
1056
+ function releaseRetain(retain) {
1057
+ const mutableRetain = retain;
1058
+ const mutableNode = mutableRetain.node;
1059
+ mutableRetain.node = void 0;
1060
+ const previous = mutableRetain.previousRetain;
1061
+ const next = mutableRetain.nextRetain;
1062
+ if (previous === void 0) mutableNode.firstRetain = next;
1063
+ else {
1064
+ previous.nextRetain = next;
1065
+ mutableRetain.previousRetain = void 0;
1066
+ }
1067
+ if (next !== void 0) {
1068
+ next.previousRetain = previous;
1069
+ mutableRetain.nextRetain = void 0;
1070
+ }
1071
+ if (mutableRetain.onChange !== void 0) {
1072
+ mutableRetain.onChange = void 0;
1073
+ clearCallbackStateIfNoCallbackRetainsRemain(mutableNode);
1074
+ }
1075
+ if (mutableNode.firstRetain === void 0 && mutableNode.firstDependent === void 0) addToCleanupQueue(mutableNode);
1076
+ scheduleCleanupIfOutsideBatchAndFlush();
1077
+ }
1078
+ /**
1079
+ * Internal invariant: a node that loses its last callback while `DIRTY` or
1080
+ * `MAYBE_DIRTY` has no `CLEAN` dependents, and its dependents may be
1081
+ * `MAYBE_DIRTY` with `MARKED_BEYOND`, waiting for its refresh to put the
1082
+ * nodes with callbacks among them on the flush queue. The walk through lazy nodes
1083
+ * from the node clears that bit on them, as the dependents of a lazy node that
1084
+ * is `DIRTY` or `MAYBE_DIRTY` require, and puts those nodes with callbacks on the
1085
+ * flush queue. A node that gets a callback was brought
1086
+ * up to date first, so it is `CLEAN`.
1087
+ */
1088
+ function clearCallbackStateIfNoCallbackRetainsRemain(node) {
1089
+ if (hasOnChangeRetain(node)) return;
1090
+ node.callbackState = 0;
1091
+ if (node.status !== 3) flushQueuedNodesOrDisposeMarkedNodes(markTransitiveDependentsMaybeDirty(void 0, node, void 0, void 0));
1092
+ }
1093
+ function hasOnChangeRetain(node) {
1094
+ let retain = node.firstRetain;
1095
+ while (retain !== void 0) {
1096
+ if (retain.onChange !== void 0) return true;
1097
+ retain = retain.nextRetain;
1098
+ }
1099
+ return false;
1100
+ }
1101
+
1102
+ //#endregion
1103
+ //#region src/disposal/take.ts
1104
+ /**
1105
+ * Empties the cleanup queue and returns the node of each entry whose node is
1106
+ * still unneeded and not `UNCOMPUTED`, oldest entry first. A node with several
1107
+ * entries appears once per entry. pico-js no longer holds a taken node for
1108
+ * disposal: it queues the node again only when the node becomes unneeded again
1109
+ * after it is needed, or on a top-level read while it is unneeded.
1110
+ *
1111
+ * Contract: called outside computations, batches, and `onChange` callbacks.
1112
+ */
1113
+ function takeUnneeded() {
1114
+ const taken = cleanupQueue.filter(isUnneededComputedNode);
1115
+ cleanupQueue.length = 0;
1116
+ clearPendingCleanupRequest();
1117
+ return taken;
1118
+ }
1119
+ function isUnneededComputedNode(node) {
1120
+ return node.firstRetain === void 0 && node.firstDependent === void 0 && node.status !== 0;
1121
+ }
1122
+ /**
1123
+ * Disposes `node` if it is unneeded and not `UNCOMPUTED`, and returns whether
1124
+ * it did. The dependencies that the disposal leaves unneeded go on the cleanup
1125
+ * queue.
1126
+ *
1127
+ * Contract: called outside computations, batches, and `onChange` callbacks.
1128
+ */
1129
+ function disposeIfUnneeded(node) {
1130
+ const mutableNode = node;
1131
+ if (!isUnneededComputedNode(mutableNode)) return false;
1132
+ const wasEmpty = cleanupQueue.length === 0;
1133
+ disposeNode(mutableNode, 0, void 0);
1134
+ if (wasEmpty && cleanupQueue.length > 0) requestCleanupScheduling();
1135
+ return true;
1136
+ }
1137
+
1138
+ //#endregion
1139
+ exports.createDerivedNode = createDerivedNode;
1140
+ exports.createSourceNode = createSourceNode;
1141
+ exports.disposeAll = disposeAll;
1142
+ exports.disposeIfUnneeded = disposeIfUnneeded;
1143
+ exports.disposeNext = disposeNext;
1144
+ exports.disposeOlderThanUpdates = disposeOlderThanUpdates;
1145
+ exports.endWriteBatch = endWriteBatch;
1146
+ exports.readDerived = readDerived;
1147
+ exports.readDerivedOutsideComputation = readDerivedOutsideComputation;
1148
+ exports.readSource = readSource;
1149
+ exports.releaseRetain = releaseRetain;
1150
+ exports.retainDerivedNode = retainDerivedNode;
1151
+ exports.scheduler = scheduler;
1152
+ exports.startWriteBatch = startWriteBatch;
1153
+ exports.takeUnneeded = takeUnneeded;
1154
+ exports.writeSource = writeSource;