@graphrefly/graphrefly 0.22.0 → 0.23.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 (78) hide show
  1. package/dist/{chunk-RHI3GHZW.js → chunk-263BEJJO.js} +3 -3
  2. package/dist/{chunk-44HD4BTA.js → chunk-2GQLMQVJ.js} +3 -3
  3. package/dist/chunk-32N5A454.js +36 -0
  4. package/dist/chunk-32N5A454.js.map +1 -0
  5. package/dist/{chunk-IR3KMOLX.js → chunk-CWYPA63G.js} +3 -383
  6. package/dist/chunk-CWYPA63G.js.map +1 -0
  7. package/dist/{chunk-TH6COGOP.js → chunk-HVBX5KIW.js} +2 -2
  8. package/dist/chunk-JFONSPNF.js +391 -0
  9. package/dist/chunk-JFONSPNF.js.map +1 -0
  10. package/dist/{chunk-QA3RP5NH.js → chunk-NZMBRXQV.js} +101 -5
  11. package/dist/chunk-NZMBRXQV.js.map +1 -0
  12. package/dist/{chunk-MQBQOFDS.js → chunk-PNUZM7PC.js} +12 -31
  13. package/dist/chunk-PNUZM7PC.js.map +1 -0
  14. package/dist/{chunk-EQUZ5NLD.js → chunk-PX6PDUJ5.js} +11 -16
  15. package/dist/chunk-PX6PDUJ5.js.map +1 -0
  16. package/dist/{chunk-NXC35KC5.js → chunk-XRFJJ2IU.js} +3 -3
  17. package/dist/{chunk-BLD3IFYF.js → chunk-XTLYW4FR.js} +9 -7
  18. package/dist/{chunk-BLD3IFYF.js.map → chunk-XTLYW4FR.js.map} +1 -1
  19. package/dist/compat/nestjs/index.cjs +100 -4
  20. package/dist/compat/nestjs/index.cjs.map +1 -1
  21. package/dist/compat/nestjs/index.d.cts +6 -6
  22. package/dist/compat/nestjs/index.d.ts +6 -6
  23. package/dist/compat/nestjs/index.js +9 -7
  24. package/dist/core/index.cjs +100 -4
  25. package/dist/core/index.cjs.map +1 -1
  26. package/dist/core/index.d.cts +3 -3
  27. package/dist/core/index.d.ts +3 -3
  28. package/dist/core/index.js +3 -3
  29. package/dist/extra/index.cjs +100 -4
  30. package/dist/extra/index.cjs.map +1 -1
  31. package/dist/extra/index.d.cts +4 -4
  32. package/dist/extra/index.d.ts +4 -4
  33. package/dist/extra/index.js +9 -7
  34. package/dist/graph/index.cjs +100 -4
  35. package/dist/graph/index.cjs.map +1 -1
  36. package/dist/graph/index.d.cts +5 -5
  37. package/dist/graph/index.d.ts +5 -5
  38. package/dist/graph/index.js +4 -4
  39. package/dist/{graph-ab1yPwIB.d.cts → graph-BtdSRHUc.d.cts} +3 -3
  40. package/dist/{graph-DFr0diXB.d.ts → graph-CEO2FkLY.d.ts} +3 -3
  41. package/dist/{index-BvWfZCTt.d.cts → index-B0tfuXwV.d.cts} +3 -3
  42. package/dist/{index-Dy04P4W3.d.cts → index-BFGjXbiP.d.cts} +2 -2
  43. package/dist/{index-DrJq9B1T.d.cts → index-BPlWVAKY.d.cts} +3 -3
  44. package/dist/{index-C9z6rU9P.d.cts → index-BUj3ASVe.d.cts} +25 -7
  45. package/dist/{index-DLE1Sp-L.d.cts → index-C59uSJAH.d.cts} +2 -2
  46. package/dist/{index-DsGxLfwL.d.ts → index-CkElcUY6.d.ts} +2 -2
  47. package/dist/{index-HdJx_BjO.d.ts → index-DSPc5rkv.d.ts} +25 -7
  48. package/dist/{index-D36MAQ3f.d.ts → index-DgscL7v0.d.ts} +3 -3
  49. package/dist/{index-BbYZma8G.d.ts → index-RXN94sHK.d.ts} +3 -3
  50. package/dist/{index-BHm3Ba5q.d.ts → index-jEtF4N7L.d.ts} +2 -2
  51. package/dist/index.cjs +109 -14
  52. package/dist/index.cjs.map +1 -1
  53. package/dist/index.d.cts +15 -15
  54. package/dist/index.d.ts +15 -15
  55. package/dist/index.js +26 -22
  56. package/dist/index.js.map +1 -1
  57. package/dist/{meta-n3FoVWML.d.ts → meta-3QjzotRv.d.ts} +1 -1
  58. package/dist/{meta--fr9sxRM.d.cts → meta-B-Lbs4-O.d.cts} +1 -1
  59. package/dist/{node-C5UD5MGq.d.cts → node-C7PD3sn9.d.cts} +42 -0
  60. package/dist/{node-C5UD5MGq.d.ts → node-C7PD3sn9.d.ts} +42 -0
  61. package/dist/{observable-CQRBtEbq.d.ts → observable-EyO-moQY.d.ts} +1 -1
  62. package/dist/{observable-DWydVy5b.d.cts → observable-axpzv1K2.d.cts} +1 -1
  63. package/dist/patterns/reactive-layout/index.cjs +214 -117
  64. package/dist/patterns/reactive-layout/index.cjs.map +1 -1
  65. package/dist/patterns/reactive-layout/index.d.cts +5 -5
  66. package/dist/patterns/reactive-layout/index.d.ts +5 -5
  67. package/dist/patterns/reactive-layout/index.js +6 -4
  68. package/dist/{storage-C9fZfMfM.d.ts → storage-CHT5WE9m.d.ts} +1 -1
  69. package/dist/{storage-Bew05Xy6.d.cts → storage-DIgAr7M_.d.cts} +1 -1
  70. package/package.json +2 -1
  71. package/dist/chunk-EQUZ5NLD.js.map +0 -1
  72. package/dist/chunk-IR3KMOLX.js.map +0 -1
  73. package/dist/chunk-MQBQOFDS.js.map +0 -1
  74. package/dist/chunk-QA3RP5NH.js.map +0 -1
  75. /package/dist/{chunk-RHI3GHZW.js.map → chunk-263BEJJO.js.map} +0 -0
  76. /package/dist/{chunk-44HD4BTA.js.map → chunk-2GQLMQVJ.js.map} +0 -0
  77. /package/dist/{chunk-TH6COGOP.js.map → chunk-HVBX5KIW.js.map} +0 -0
  78. /package/dist/{chunk-NXC35KC5.js.map → chunk-XRFJJ2IU.js.map} +0 -0
@@ -0,0 +1,391 @@
1
+ import {
2
+ COMPLETE,
3
+ DATA,
4
+ DIRTY,
5
+ ERROR,
6
+ PAUSE,
7
+ RESUME,
8
+ batch,
9
+ derived,
10
+ state
11
+ } from "./chunk-NZMBRXQV.js";
12
+
13
+ // src/extra/observable.ts
14
+ import { Observable } from "rxjs";
15
+ function toObservable(node, options) {
16
+ if (options?.raw) {
17
+ return new Observable((subscriber) => {
18
+ const unsub = node.subscribe((msgs) => {
19
+ if (subscriber.closed) return;
20
+ subscriber.next(msgs);
21
+ for (const m of msgs) {
22
+ if (m[0] === ERROR) {
23
+ subscriber.error(m[1]);
24
+ return;
25
+ }
26
+ if (m[0] === COMPLETE) {
27
+ subscriber.complete();
28
+ return;
29
+ }
30
+ }
31
+ });
32
+ return unsub;
33
+ });
34
+ }
35
+ return new Observable((subscriber) => {
36
+ const unsub = node.subscribe((msgs) => {
37
+ for (const m of msgs) {
38
+ if (subscriber.closed) return;
39
+ if (m[0] === DATA) {
40
+ subscriber.next(m[1]);
41
+ } else if (m[0] === ERROR) {
42
+ subscriber.error(m[1]);
43
+ return;
44
+ } else if (m[0] === COMPLETE) {
45
+ subscriber.complete();
46
+ return;
47
+ }
48
+ }
49
+ });
50
+ return unsub;
51
+ });
52
+ }
53
+
54
+ // src/extra/backpressure.ts
55
+ var nextLockId = 0;
56
+ function createWatermarkController(sendUp, opts) {
57
+ if (opts.highWaterMark < 1) throw new RangeError("highWaterMark must be >= 1");
58
+ if (opts.lowWaterMark < 0) throw new RangeError("lowWaterMark must be >= 0");
59
+ if (opts.lowWaterMark >= opts.highWaterMark)
60
+ throw new RangeError("lowWaterMark must be < highWaterMark");
61
+ const lockId = /* @__PURE__ */ Symbol(`bp-${++nextLockId}`);
62
+ let pending = 0;
63
+ let paused = false;
64
+ return {
65
+ onEnqueue() {
66
+ pending += 1;
67
+ if (!paused && pending >= opts.highWaterMark) {
68
+ paused = true;
69
+ sendUp([[PAUSE, lockId]]);
70
+ return true;
71
+ }
72
+ return false;
73
+ },
74
+ onDequeue() {
75
+ if (pending > 0) pending -= 1;
76
+ if (paused && pending <= opts.lowWaterMark) {
77
+ paused = false;
78
+ sendUp([[RESUME, lockId]]);
79
+ return true;
80
+ }
81
+ return false;
82
+ },
83
+ get pending() {
84
+ return pending;
85
+ },
86
+ get paused() {
87
+ return paused;
88
+ },
89
+ dispose() {
90
+ if (paused) {
91
+ paused = false;
92
+ sendUp([[RESUME, lockId]]);
93
+ }
94
+ }
95
+ };
96
+ }
97
+
98
+ // src/extra/reactive-log.ts
99
+ var NativeLogBackend = class {
100
+ _version = 0;
101
+ _maxSize;
102
+ _buf;
103
+ _head = 0;
104
+ _size = 0;
105
+ constructor(initial, maxSize) {
106
+ if (maxSize !== void 0 && maxSize < 1) {
107
+ throw new RangeError("maxSize must be >= 1");
108
+ }
109
+ this._maxSize = maxSize;
110
+ if (maxSize !== void 0) {
111
+ this._buf = new Array(maxSize);
112
+ if (initial && initial.length > 0) {
113
+ const take = Math.min(initial.length, maxSize);
114
+ const start = initial.length - take;
115
+ for (let i = 0; i < take; i++) {
116
+ this._buf[i] = initial[start + i];
117
+ }
118
+ this._size = take;
119
+ }
120
+ } else {
121
+ this._buf = initial ? [...initial] : [];
122
+ this._size = this._buf.length;
123
+ }
124
+ }
125
+ get version() {
126
+ return this._version;
127
+ }
128
+ get size() {
129
+ return this._size;
130
+ }
131
+ at(index) {
132
+ if (!Number.isInteger(index)) return void 0;
133
+ const i = index >= 0 ? index : this._size + index;
134
+ if (i < 0 || i >= this._size) return void 0;
135
+ if (this._maxSize !== void 0) {
136
+ return this._buf[(this._head + i) % this._maxSize];
137
+ }
138
+ return this._buf[i];
139
+ }
140
+ append(value) {
141
+ this._rawAppend(value);
142
+ this._version += 1;
143
+ }
144
+ appendMany(values) {
145
+ if (values.length === 0) return;
146
+ const start = this._maxSize !== void 0 && values.length > this._maxSize ? values.length - this._maxSize : 0;
147
+ for (let i = start; i < values.length; i++) {
148
+ this._rawAppend(values[i]);
149
+ }
150
+ this._version += 1;
151
+ }
152
+ clear() {
153
+ if (this._size === 0) return 0;
154
+ const n = this._size;
155
+ if (this._maxSize === void 0) {
156
+ this._buf.length = 0;
157
+ } else {
158
+ for (let i = 0; i < n; i++) {
159
+ this._buf[(this._head + i) % this._maxSize] = void 0;
160
+ }
161
+ }
162
+ this._head = 0;
163
+ this._size = 0;
164
+ this._version += 1;
165
+ return n;
166
+ }
167
+ trimHead(n) {
168
+ if (!Number.isInteger(n) || n < 0) {
169
+ throw new RangeError(`trimHead: n must be a non-negative integer (got ${n})`);
170
+ }
171
+ if (n === 0 || this._size === 0) return 0;
172
+ const removed = Math.min(n, this._size);
173
+ if (this._maxSize === void 0) {
174
+ this._buf.splice(0, removed);
175
+ } else {
176
+ for (let i = 0; i < removed; i++) {
177
+ this._buf[(this._head + i) % this._maxSize] = void 0;
178
+ }
179
+ this._head = (this._head + removed) % this._maxSize;
180
+ }
181
+ this._size -= removed;
182
+ this._version += 1;
183
+ return removed;
184
+ }
185
+ slice(start, stop) {
186
+ if (!Number.isInteger(start) || start < 0) {
187
+ throw new RangeError(`slice: start must be a non-negative integer (got ${start})`);
188
+ }
189
+ if (stop !== void 0 && (!Number.isInteger(stop) || stop < 0)) {
190
+ throw new RangeError(`slice: stop must be a non-negative integer or undefined (got ${stop})`);
191
+ }
192
+ const end = stop === void 0 ? this._size : Math.min(Math.max(stop, 0), this._size);
193
+ const s = Math.min(start, this._size);
194
+ if (s >= end) return [];
195
+ const len = end - s;
196
+ if (this._maxSize === void 0) {
197
+ return this._buf.slice(s, end);
198
+ }
199
+ const out = new Array(len);
200
+ for (let i = 0; i < len; i++) {
201
+ out[i] = this._buf[(this._head + s + i) % this._maxSize];
202
+ }
203
+ return out;
204
+ }
205
+ tail(n) {
206
+ if (!Number.isInteger(n) || n < 0) {
207
+ throw new RangeError(`tail: n must be a non-negative integer (got ${n})`);
208
+ }
209
+ if (n === 0 || this._size === 0) return [];
210
+ const take = Math.min(n, this._size);
211
+ return this.slice(this._size - take, this._size);
212
+ }
213
+ toArray() {
214
+ if (this._maxSize === void 0) {
215
+ return [...this._buf];
216
+ }
217
+ const out = new Array(this._size);
218
+ for (let i = 0; i < this._size; i++) {
219
+ out[i] = this._buf[(this._head + i) % this._maxSize];
220
+ }
221
+ return out;
222
+ }
223
+ /** Internal append without version bump — used by `appendMany`. */
224
+ _rawAppend(value) {
225
+ if (this._maxSize === void 0) {
226
+ this._buf.push(value);
227
+ this._size = this._buf.length;
228
+ return;
229
+ }
230
+ if (this._size < this._maxSize) {
231
+ this._buf[(this._head + this._size) % this._maxSize] = value;
232
+ this._size += 1;
233
+ } else {
234
+ this._buf[this._head] = value;
235
+ this._head = (this._head + 1) % this._maxSize;
236
+ }
237
+ }
238
+ };
239
+ function keepaliveDerived(n) {
240
+ return n.subscribe(() => {
241
+ });
242
+ }
243
+ var DEFAULT_VIEW_CACHE_MAX = 64;
244
+ function reactiveLog(initial, options = {}) {
245
+ const { name, maxSize, versioning, backend: userBackend } = options;
246
+ const backend = userBackend ?? new NativeLogBackend(initial, maxSize);
247
+ const entries = state(backend.toArray(), {
248
+ name,
249
+ describeKind: "state",
250
+ equals: (a, b) => a === b,
251
+ ...versioning != null ? { versioning } : {}
252
+ });
253
+ function pushSnapshot() {
254
+ const snapshot = backend.toArray();
255
+ batch(() => {
256
+ entries.down([[DIRTY]]);
257
+ entries.down([[DATA, snapshot]]);
258
+ });
259
+ }
260
+ const tailCache = /* @__PURE__ */ new Map();
261
+ const sliceCache = /* @__PURE__ */ new Map();
262
+ function sliceKey(start, stop) {
263
+ return `${start}:${stop === void 0 ? "END" : stop}`;
264
+ }
265
+ function evictOldestIfFull(cache) {
266
+ if (cache.size < DEFAULT_VIEW_CACHE_MAX) return;
267
+ const first = cache.keys().next();
268
+ if (first.done) return;
269
+ const oldest = cache.get(first.value);
270
+ if (oldest !== void 0) oldest.dispose();
271
+ cache.delete(first.value);
272
+ }
273
+ function wrapMutation(op) {
274
+ const prev = backend.version;
275
+ try {
276
+ return op();
277
+ } finally {
278
+ if (backend.version !== prev) pushSnapshot();
279
+ }
280
+ }
281
+ return {
282
+ entries,
283
+ get size() {
284
+ return backend.size;
285
+ },
286
+ at(index) {
287
+ return backend.at(index);
288
+ },
289
+ append(value) {
290
+ wrapMutation(() => backend.append(value));
291
+ },
292
+ appendMany(values) {
293
+ if (values.length === 0) return;
294
+ wrapMutation(() => backend.appendMany(values));
295
+ },
296
+ clear() {
297
+ wrapMutation(() => backend.clear());
298
+ },
299
+ trimHead(n) {
300
+ wrapMutation(() => backend.trimHead(n));
301
+ },
302
+ tail(n) {
303
+ if (!Number.isInteger(n) || n < 0) {
304
+ throw new RangeError(`tail: n must be a non-negative integer (got ${n})`);
305
+ }
306
+ const hit = tailCache.get(n);
307
+ if (hit !== void 0) {
308
+ tailCache.delete(n);
309
+ tailCache.set(n, hit);
310
+ return hit.node;
311
+ }
312
+ evictOldestIfFull(tailCache);
313
+ const node_ = derived(
314
+ [entries],
315
+ ([s]) => {
316
+ const list = s;
317
+ if (n === 0 || list.length === 0) return [];
318
+ return list.slice(Math.max(0, list.length - n));
319
+ },
320
+ { initial: backend.tail(n), describeKind: "derived" }
321
+ );
322
+ const dispose = keepaliveDerived(node_);
323
+ tailCache.set(n, { node: node_, dispose });
324
+ return node_;
325
+ },
326
+ slice(start, stop) {
327
+ if (!Number.isInteger(start) || start < 0) {
328
+ throw new RangeError(`slice: start must be a non-negative integer (got ${start})`);
329
+ }
330
+ if (stop !== void 0 && (!Number.isInteger(stop) || stop < 0)) {
331
+ throw new RangeError(
332
+ `slice: stop must be a non-negative integer or undefined (got ${stop})`
333
+ );
334
+ }
335
+ const key = sliceKey(start, stop);
336
+ const hit = sliceCache.get(key);
337
+ if (hit !== void 0) {
338
+ sliceCache.delete(key);
339
+ sliceCache.set(key, hit);
340
+ return hit.node;
341
+ }
342
+ evictOldestIfFull(sliceCache);
343
+ const node_ = derived(
344
+ [entries],
345
+ ([s]) => {
346
+ const list = s;
347
+ return stop === void 0 ? list.slice(start) : list.slice(start, stop);
348
+ },
349
+ { initial: backend.slice(start, stop), describeKind: "derived" }
350
+ );
351
+ const dispose = keepaliveDerived(node_);
352
+ sliceCache.set(key, { node: node_, dispose });
353
+ return node_;
354
+ },
355
+ disposeTail(n) {
356
+ const hit = tailCache.get(n);
357
+ if (hit === void 0) return false;
358
+ hit.dispose();
359
+ tailCache.delete(n);
360
+ return true;
361
+ },
362
+ disposeSlice(start, stop) {
363
+ const key = sliceKey(start, stop);
364
+ const hit = sliceCache.get(key);
365
+ if (hit === void 0) return false;
366
+ hit.dispose();
367
+ sliceCache.delete(key);
368
+ return true;
369
+ },
370
+ disposeAllViews() {
371
+ for (const entry of tailCache.values()) entry.dispose();
372
+ tailCache.clear();
373
+ for (const entry of sliceCache.values()) entry.dispose();
374
+ sliceCache.clear();
375
+ },
376
+ dispose() {
377
+ for (const entry of tailCache.values()) entry.dispose();
378
+ tailCache.clear();
379
+ for (const entry of sliceCache.values()) entry.dispose();
380
+ sliceCache.clear();
381
+ }
382
+ };
383
+ }
384
+
385
+ export {
386
+ toObservable,
387
+ createWatermarkController,
388
+ NativeLogBackend,
389
+ reactiveLog
390
+ };
391
+ //# sourceMappingURL=chunk-JFONSPNF.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/extra/observable.ts","../src/extra/backpressure.ts","../src/extra/reactive-log.ts"],"sourcesContent":["// ---------------------------------------------------------------------------\n// RxJS bridge — reactive interop between GraphReFly nodes and RxJS Observables.\n// ---------------------------------------------------------------------------\n// Usage:\n// import { toObservable } from '@graphrefly/graphrefly-ts/extra';\n// const values$ = toObservable(myNode); // Observable<T>\n// const msgs$ = toObservable(myNode, { raw: true }); // Observable<Messages>\n// ---------------------------------------------------------------------------\n\nimport { Observable } from \"rxjs\";\nimport { COMPLETE, DATA, ERROR, type Messages } from \"../core/messages.js\";\nimport type { Node } from \"../core/node.js\";\n\n/** Options for {@link toObservable}. */\nexport type ToObservableOptions = {\n\t/**\n\t * When `true`, emit raw `Messages` batches instead of extracted `DATA` values.\n\t * Terminal batches are still emitted as the final `next()` before the\n\t * Observable signal (error/complete).\n\t */\n\traw?: boolean;\n};\n\n/**\n * Bridge a `Node<T>` to an RxJS `Observable`.\n *\n * Default mode emits the node's value on each `DATA` message. Maps `ERROR` to\n * `subscriber.error()` and `COMPLETE` to `subscriber.complete()`.\n * Protocol-internal signals (DIRTY, RESOLVED, PAUSE, etc.) are skipped.\n *\n * With `{ raw: true }`, emits full `[[Type, Data?], ...]` message batches.\n * The Observable terminates on ERROR or COMPLETE (the terminal batch is still\n * emitted as the final `next()` before the Observable signal).\n *\n * For graph-level observation, use `toObservable(graph.resolve(path))` or\n * subscribe to `graph.observe()` directly.\n *\n * Unsubscribing the Observable unsubscribes the node.\n */\nexport function toObservable<T>(\n\tnode: Node<T>,\n\toptions?: ToObservableOptions & { raw?: false },\n): Observable<T>;\nexport function toObservable<T>(\n\tnode: Node<T>,\n\toptions: ToObservableOptions & { raw: true },\n): Observable<Messages>;\nexport function toObservable<T>(\n\tnode: Node<T>,\n\toptions?: ToObservableOptions,\n): Observable<T | Messages> {\n\tif (options?.raw) {\n\t\treturn new Observable<Messages>((subscriber) => {\n\t\t\tconst unsub = node.subscribe((msgs) => {\n\t\t\t\tif (subscriber.closed) return;\n\t\t\t\tsubscriber.next(msgs);\n\t\t\t\tfor (const m of msgs) {\n\t\t\t\t\tif (m[0] === ERROR) {\n\t\t\t\t\t\tsubscriber.error(m[1]);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (m[0] === COMPLETE) {\n\t\t\t\t\t\tsubscriber.complete();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t\treturn unsub;\n\t\t});\n\t}\n\n\treturn new Observable<T>((subscriber) => {\n\t\tconst unsub = node.subscribe((msgs) => {\n\t\t\tfor (const m of msgs) {\n\t\t\t\tif (subscriber.closed) return;\n\t\t\t\tif (m[0] === DATA) {\n\t\t\t\t\tsubscriber.next(m[1] as T);\n\t\t\t\t} else if (m[0] === ERROR) {\n\t\t\t\t\tsubscriber.error(m[1]);\n\t\t\t\t\treturn;\n\t\t\t\t} else if (m[0] === COMPLETE) {\n\t\t\t\t\tsubscriber.complete();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\treturn unsub;\n\t});\n}\n","/**\n * Watermark-based backpressure controller — reactive PAUSE/RESUME flow control.\n *\n * Purely synchronous, event-driven. No timers, no polling, no Promises.\n * Each controller instance uses a unique lockId so multiple controllers\n * on the same upstream node do not collide.\n *\n * @module\n */\n\nimport { type Messages, PAUSE, RESUME } from \"../core/messages.js\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport type WatermarkOptions = {\n\t/** Pending count at which PAUSE is sent upstream. */\n\thighWaterMark: number;\n\t/** Pending count at which RESUME is sent upstream (after being paused). */\n\tlowWaterMark: number;\n};\n\nexport type WatermarkController = {\n\t/** Call when a DATA message is buffered/enqueued. Returns `true` if PAUSE was just sent. */\n\tonEnqueue(): boolean;\n\t/** Call when a buffered item is consumed. Returns `true` if RESUME was just sent. */\n\tonDequeue(): boolean;\n\t/** Current un-consumed item count. */\n\treadonly pending: number;\n\t/** Whether upstream is currently paused by this controller. */\n\treadonly paused: boolean;\n\t/** Dispose: if paused, sends RESUME to unblock upstream. */\n\tdispose(): void;\n};\n\n// ---------------------------------------------------------------------------\n// Factory\n// ---------------------------------------------------------------------------\n\nlet nextLockId = 0;\n\n/**\n * Creates a watermark-based backpressure controller.\n *\n * @param sendUp - Callback that delivers messages upstream (typically `handle.up`).\n * @param opts - High/low watermark thresholds (item counts).\n * @returns A {@link WatermarkController}.\n *\n * @example\n * ```ts\n * const handle = graph.observe(\"fast-source\");\n * const wm = createWatermarkController(\n * (msgs) => handle.up(msgs),\n * { highWaterMark: 64, lowWaterMark: 16 },\n * );\n *\n * // In sink callback:\n * handle.subscribe((msgs) => {\n * for (const msg of msgs) {\n * if (msg[0] === DATA) {\n * buffer.push(msg[1]);\n * wm.onEnqueue();\n * }\n * }\n * });\n *\n * // When consumer drains:\n * const item = buffer.shift();\n * wm.onDequeue();\n * ```\n *\n * @category extra\n */\nexport function createWatermarkController(\n\tsendUp: (messages: Messages) => void,\n\topts: WatermarkOptions,\n): WatermarkController {\n\tif (opts.highWaterMark < 1) throw new RangeError(\"highWaterMark must be >= 1\");\n\tif (opts.lowWaterMark < 0) throw new RangeError(\"lowWaterMark must be >= 0\");\n\tif (opts.lowWaterMark >= opts.highWaterMark)\n\t\tthrow new RangeError(\"lowWaterMark must be < highWaterMark\");\n\tconst lockId = Symbol(`bp-${++nextLockId}`);\n\tlet pending = 0;\n\tlet paused = false;\n\n\treturn {\n\t\tonEnqueue(): boolean {\n\t\t\tpending += 1;\n\t\t\tif (!paused && pending >= opts.highWaterMark) {\n\t\t\t\tpaused = true;\n\t\t\t\tsendUp([[PAUSE, lockId]]);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\treturn false;\n\t\t},\n\t\tonDequeue(): boolean {\n\t\t\tif (pending > 0) pending -= 1;\n\t\t\tif (paused && pending <= opts.lowWaterMark) {\n\t\t\t\tpaused = false;\n\t\t\t\tsendUp([[RESUME, lockId]]);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\treturn false;\n\t\t},\n\t\tget pending() {\n\t\t\treturn pending;\n\t\t},\n\t\tget paused() {\n\t\t\treturn paused;\n\t\t},\n\t\tdispose() {\n\t\t\tif (paused) {\n\t\t\t\tpaused = false;\n\t\t\t\tsendUp([[RESUME, lockId]]);\n\t\t\t}\n\t\t},\n\t};\n}\n","/**\n * Reactive append-only log (roadmap §3.2) — emits `readonly T[]` snapshots directly.\n *\n * Internal version counter drives efficient equality without leaking `Versioned`\n * into the public API (spec §5.12).\n *\n * **Wave 4 refactor (2026-04-15):** Introduces the `LogBackend<T>` pluggable-backend\n * interface. The default `NativeLogBackend` uses a ring buffer when `maxSize` is set\n * (O(1) append + trim) and a flat array otherwise. `tail(n)` and `slice(start, stop)`\n * are memoized — repeat calls with identical arguments return the same derived node,\n * bounding the keepalive-subscription footprint. The standalone `logSlice` factory\n * has been removed; use `log.slice(start, stop)` instead.\n */\nimport { batch } from \"../core/batch.js\";\nimport { DATA, DIRTY } from \"../core/messages.js\";\nimport type { Node } from \"../core/node.js\";\nimport { derived, state } from \"../core/sugar.js\";\nimport type { VersioningLevel } from \"../core/versioning.js\";\n\nexport type ReactiveLogOptions<T> = {\n\tname?: string;\n\tmaxSize?: number;\n\t/**\n\t * Optional versioning level for the underlying `entries` state node. Set\n\t * at construction time; cannot be changed later. Pass `0` for V0 identity\n\t * + monotonic version counter, or `1` for V1 + content-addressed cid.\n\t */\n\tversioning?: VersioningLevel;\n\t/**\n\t * Storage backend. Defaults to `NativeLogBackend` (ring buffer if `maxSize` is set,\n\t * flat array otherwise). Users can plug in persistent / RRB-tree backends via\n\t * the {@link LogBackend} interface.\n\t */\n\tbackend?: LogBackend<T>;\n};\n\nexport type ReactiveLogBundle<T> = {\n\t/** Emits `readonly T[]` on each append/clear/trim (two-phase). */\n\treadonly entries: Node<readonly T[]>;\n\t/** Current entry count (O(1)). */\n\treadonly size: number;\n\t/** Positional access (O(1)); returns `undefined` on out-of-range. Supports negative indices (Python-style). */\n\tat: (index: number) => T | undefined;\n\tappend: (value: T) => void;\n\t/**\n\t * Push all values, emit one snapshot. No-op if `values` is empty.\n\t * **Iterable consumption:** `values` is a `readonly T[]` — safe to pass arrays.\n\t */\n\tappendMany: (values: readonly T[]) => void;\n\tclear: () => void;\n\t/** Remove the first `n` entries (clamped to `size`). Throws on non-integer or negative `n`. */\n\ttrimHead: (n: number) => void;\n\t/**\n\t * Last `n` entries (or fewer) as a derived reactive view. Memoized with\n\t * an LRU cache (default cap 64) — repeat calls with the same `n` return\n\t * the same node. Throws on non-integer or negative `n`.\n\t *\n\t * **LRU eviction contract (D3(b)):** when a 65th distinct `n` is passed,\n\t * the least-recently-used cached view is evicted and its keepalive is\n\t * disposed. External holders of the evicted node will NOT receive further\n\t * updates — re-call `tail(n)` for a fresh node, or dispose proactively\n\t * via {@link disposeTail} / {@link disposeAllViews}. To avoid surprise:\n\t * resolve `tail(n)` at the point of use rather than caching the returned\n\t * node across many distinct `n`s.\n\t */\n\ttail: (n: number) => Node<readonly T[]>;\n\t/**\n\t * Reactive view of `entries.slice(start, stop)` — non-negative integer\n\t * `start`, non-negative integer `stop` (exclusive) or `undefined` (to end).\n\t * Memoized with an LRU cache (default cap 64) — repeat calls with the\n\t * same `(start, stop)` return the same node.\n\t *\n\t * Throws on non-integer `start`, negative `start`, non-integer `stop`, or\n\t * negative `stop` (P4 — the backend cannot cheaply honor JS-style\n\t * negative `stop` without scanning length; disallowed for a consistent\n\t * contract between backend, derived recomputation, and cached initial).\n\t *\n\t * **LRU eviction contract (D3(b)):** same as {@link tail} — past 64\n\t * distinct `(start, stop)` pairs, the oldest cached view is evicted and\n\t * its keepalive disposed. External holders stop receiving updates.\n\t */\n\tslice: (start: number, stop?: number) => Node<readonly T[]>;\n\t/**\n\t * Releases the cached `tail(n)` view if present (disposes its keepalive\n\t * subscription). Subsequent `tail(n)` calls create a fresh node. No-op if\n\t * `n` was not cached. Returns `true` if a view was disposed.\n\t */\n\tdisposeTail: (n: number) => boolean;\n\t/**\n\t * Releases the cached `slice(start, stop?)` view if present. No-op if not cached.\n\t */\n\tdisposeSlice: (start: number, stop?: number) => boolean;\n\t/** Releases all cached tail/slice views and their keepalive subscriptions. */\n\tdisposeAllViews: () => void;\n\t/**\n\t * Releases all internal keepalive subscriptions so the bundle can be\n\t * GC'd — currently equivalent to {@link disposeAllViews}, but exposed as\n\t * a uniform API across all reactive data structures for lifecycle\n\t * symmetry (mirrors `reactiveMap.dispose` / `reactiveList.dispose` /\n\t * `reactiveIndex.dispose`). Idempotent. D6(a).\n\t */\n\tdispose: () => void;\n};\n\n// ── Backend interface ─────────────────────────────────────────────────────\n\n/**\n * Storage contract for {@link reactiveLog}. Implementations own the mutable state and\n * expose a monotonic `version` counter that increments on every structural change.\n *\n * The reactive layer reads `version` to decide when to emit; it does not inspect\n * internal representation. Users can plug in persistent / ring-buffer / skip-list\n * backends without touching the reactive emission logic.\n *\n * @remarks Post-1.0 op-log changesets will extend this interface with a\n * `changesSince(version: number): Iterable<Change>` method. Current consumers\n * should treat all methods here as stable.\n *\n * @category extra\n */\nexport interface LogBackend<T> {\n\t/** Monotonic mutation counter; increments on every append/trim/clear that changes state. */\n\treadonly version: number;\n\t/** Number of entries currently stored. */\n\treadonly size: number;\n\t/** O(1) positional access; returns `undefined` on out-of-range. */\n\tat(index: number): T | undefined;\n\t/** Append a value. Applies `maxSize` head-drop if configured. Advances `version`. */\n\tappend(value: T): void;\n\t/** Append a batch; advances `version` once. No-op if `values.length === 0`. */\n\tappendMany(values: readonly T[]): void;\n\t/** Remove all entries. Returns count removed. Advances `version` only if non-zero. */\n\tclear(): number;\n\t/** Remove the first `n` entries (clamped). Returns count removed. Throws on negative `n`. */\n\ttrimHead(n: number): number;\n\t/** Fresh snapshot array for `[start, stop)`. Throws on negative `start`. */\n\tslice(start: number, stop?: number): readonly T[];\n\t/** Last `n` entries as a fresh array. Throws on negative `n`. */\n\ttail(n: number): readonly T[];\n\t/** Full snapshot as a fresh array. */\n\ttoArray(): readonly T[];\n}\n\n/**\n * Default append-only log backend.\n *\n * - When `maxSize` is set: uses a **ring buffer** with `_head` index and circular\n * modular arithmetic. Append and trim become O(1); snapshot is O(size) unrolling.\n * - When `maxSize` is unset: uses a flat array with standard push/splice.\n *\n * `appendMany` pre-trims oversize input: if `values.length > maxSize`, only the\n * tail of `values` is pushed (the rest would be immediately evicted).\n *\n * @category extra\n */\nexport class NativeLogBackend<T> implements LogBackend<T> {\n\tprivate _version = 0;\n\tprivate readonly _maxSize?: number;\n\tprivate readonly _buf: T[];\n\tprivate _head = 0;\n\tprivate _size = 0;\n\n\tconstructor(initial?: readonly T[], maxSize?: number) {\n\t\tif (maxSize !== undefined && maxSize < 1) {\n\t\t\tthrow new RangeError(\"maxSize must be >= 1\");\n\t\t}\n\t\tthis._maxSize = maxSize;\n\t\tif (maxSize !== undefined) {\n\t\t\t// Ring buffer mode — pre-allocate fixed size\n\t\t\tthis._buf = new Array(maxSize);\n\t\t\tif (initial && initial.length > 0) {\n\t\t\t\tconst take = Math.min(initial.length, maxSize);\n\t\t\t\tconst start = initial.length - take;\n\t\t\t\tfor (let i = 0; i < take; i++) {\n\t\t\t\t\tthis._buf[i] = initial[start + i]!;\n\t\t\t\t}\n\t\t\t\tthis._size = take;\n\t\t\t}\n\t\t} else {\n\t\t\t// Unbounded mode — dynamic array\n\t\t\tthis._buf = initial ? [...initial] : [];\n\t\t\tthis._size = this._buf.length;\n\t\t}\n\t}\n\n\tget version(): number {\n\t\treturn this._version;\n\t}\n\n\tget size(): number {\n\t\treturn this._size;\n\t}\n\n\tat(index: number): T | undefined {\n\t\tif (!Number.isInteger(index)) return undefined;\n\t\t// P5: Python-style negative index — `-1` returns the last entry.\n\t\tconst i = index >= 0 ? index : this._size + index;\n\t\tif (i < 0 || i >= this._size) return undefined;\n\t\tif (this._maxSize !== undefined) {\n\t\t\treturn this._buf[(this._head + i) % this._maxSize];\n\t\t}\n\t\treturn this._buf[i];\n\t}\n\n\tappend(value: T): void {\n\t\tthis._rawAppend(value);\n\t\tthis._version += 1;\n\t}\n\n\tappendMany(values: readonly T[]): void {\n\t\tif (values.length === 0) return;\n\t\t// Pre-trim oversize input in ring mode — skip values that would be\n\t\t// immediately evicted. Iterate with a start index instead of\n\t\t// allocating an intermediate slice. F2.\n\t\tconst start =\n\t\t\tthis._maxSize !== undefined && values.length > this._maxSize\n\t\t\t\t? values.length - this._maxSize\n\t\t\t\t: 0;\n\t\tfor (let i = start; i < values.length; i++) {\n\t\t\tthis._rawAppend(values[i] as T);\n\t\t}\n\t\tthis._version += 1;\n\t}\n\n\tclear(): number {\n\t\tif (this._size === 0) return 0;\n\t\tconst n = this._size;\n\t\tif (this._maxSize === undefined) {\n\t\t\tthis._buf.length = 0;\n\t\t} else {\n\t\t\t// Ring buffer: only null the currently-live window so the GC can\n\t\t\t// reclaim ref-typed `T`. Iterating the full capacity would be O(cap)\n\t\t\t// even when only a few slots are in use (P6). Non-live slots are\n\t\t\t// already `undefined` (pre-allocation state) or whatever a prior\n\t\t\t// trim/clear left — they hold no live refs.\n\t\t\tfor (let i = 0; i < n; i++) {\n\t\t\t\tthis._buf[(this._head + i) % this._maxSize] = undefined as unknown as T;\n\t\t\t}\n\t\t}\n\t\tthis._head = 0;\n\t\tthis._size = 0;\n\t\tthis._version += 1;\n\t\treturn n;\n\t}\n\n\ttrimHead(n: number): number {\n\t\tif (!Number.isInteger(n) || n < 0) {\n\t\t\tthrow new RangeError(`trimHead: n must be a non-negative integer (got ${n})`);\n\t\t}\n\t\tif (n === 0 || this._size === 0) return 0;\n\t\tconst removed = Math.min(n, this._size);\n\t\tif (this._maxSize === undefined) {\n\t\t\tthis._buf.splice(0, removed);\n\t\t} else {\n\t\t\t// Null trimmed slots so the GC can reclaim ref-typed T (P4 extension).\n\t\t\tfor (let i = 0; i < removed; i++) {\n\t\t\t\tthis._buf[(this._head + i) % this._maxSize] = undefined as unknown as T;\n\t\t\t}\n\t\t\tthis._head = (this._head + removed) % this._maxSize;\n\t\t}\n\t\tthis._size -= removed;\n\t\tthis._version += 1;\n\t\treturn removed;\n\t}\n\n\tslice(start: number, stop?: number): readonly T[] {\n\t\tif (!Number.isInteger(start) || start < 0) {\n\t\t\tthrow new RangeError(`slice: start must be a non-negative integer (got ${start})`);\n\t\t}\n\t\t// P4: reject negative `stop` explicitly so the bundle / backend / derived\n\t\t// contract stays consistent. Previously stop was silently clamped to 0,\n\t\t// producing `[]` in the backend but a different value under JS semantics\n\t\t// in the derived recomputation — a latent bug for negative inputs.\n\t\tif (stop !== undefined && (!Number.isInteger(stop) || stop < 0)) {\n\t\t\tthrow new RangeError(`slice: stop must be a non-negative integer or undefined (got ${stop})`);\n\t\t}\n\t\tconst end = stop === undefined ? this._size : Math.min(Math.max(stop, 0), this._size);\n\t\tconst s = Math.min(start, this._size);\n\t\tif (s >= end) return [];\n\t\tconst len = end - s;\n\t\tif (this._maxSize === undefined) {\n\t\t\treturn this._buf.slice(s, end);\n\t\t}\n\t\tconst out: T[] = new Array(len);\n\t\tfor (let i = 0; i < len; i++) {\n\t\t\tout[i] = this._buf[(this._head + s + i) % this._maxSize]!;\n\t\t}\n\t\treturn out;\n\t}\n\n\ttail(n: number): readonly T[] {\n\t\tif (!Number.isInteger(n) || n < 0) {\n\t\t\tthrow new RangeError(`tail: n must be a non-negative integer (got ${n})`);\n\t\t}\n\t\tif (n === 0 || this._size === 0) return [];\n\t\tconst take = Math.min(n, this._size);\n\t\treturn this.slice(this._size - take, this._size);\n\t}\n\n\ttoArray(): readonly T[] {\n\t\tif (this._maxSize === undefined) {\n\t\t\treturn [...this._buf];\n\t\t}\n\t\tconst out: T[] = new Array(this._size);\n\t\tfor (let i = 0; i < this._size; i++) {\n\t\t\tout[i] = this._buf[(this._head + i) % this._maxSize]!;\n\t\t}\n\t\treturn out;\n\t}\n\n\t/** Internal append without version bump — used by `appendMany`. */\n\tprivate _rawAppend(value: T): void {\n\t\tif (this._maxSize === undefined) {\n\t\t\tthis._buf.push(value);\n\t\t\tthis._size = this._buf.length;\n\t\t\treturn;\n\t\t}\n\t\tif (this._size < this._maxSize) {\n\t\t\tthis._buf[(this._head + this._size) % this._maxSize] = value;\n\t\t\tthis._size += 1;\n\t\t} else {\n\t\t\t// Overwrite slot at head, advance head.\n\t\t\tthis._buf[this._head] = value;\n\t\t\tthis._head = (this._head + 1) % this._maxSize;\n\t\t}\n\t}\n}\n\n// ── Reactive wrapper ──────────────────────────────────────────────────────\n\n/** Installs a keepalive subscription; returns the disposer so callers can release it. */\nfunction keepaliveDerived(n: Node<unknown>): () => void {\n\treturn n.subscribe(() => {});\n}\n\n/** Default cap on the LRU view cache for `tail(n)` / `slice(start, stop?)`. D2(c). */\nconst DEFAULT_VIEW_CACHE_MAX = 64;\n\n/**\n * Creates an append-only reactive log with immutable array snapshots.\n *\n * @param initial - Optional seed entries (copied; pre-trimmed to `maxSize` if set).\n * @param options - `name`, `maxSize`, and optional pluggable `backend`.\n * @returns Bundle with `entries` (state node), `append`/`appendMany`/`clear`/`trimHead`,\n * `size` / `at`, and memoized derived views `tail(n)` / `slice(start, stop?)`.\n *\n * @remarks\n * **Backend:** The default {@link NativeLogBackend} uses a ring buffer when `maxSize`\n * is set (O(1) append + trim) and a flat array otherwise. For persistent/structural-\n * sharing semantics plug in a custom {@link LogBackend}.\n *\n * **`initial` + custom `backend` (F5):** When you supply `options.backend`, the\n * `initial` argument is IGNORED — seed the backend yourself before passing it in.\n * The `initial` seed only applies to the default `NativeLogBackend`.\n *\n * **Memoized views:** {@link ReactiveLogBundle.tail} and {@link ReactiveLogBundle.slice}\n * cache derived nodes per-argument. Repeat calls with the same `n` / `(start, stop)`\n * return the same node, bounding keepalive-subscription count to one per unique argument.\n *\n * @example\n * ```ts\n * import { reactiveLog } from \"@graphrefly/graphrefly-ts\";\n *\n * const lg = reactiveLog<number>([1, 2], { name: \"audit\", maxSize: 100 });\n * lg.append(3);\n * lg.entries.subscribe((msgs) => console.log(msgs));\n * const last5 = lg.tail(5); // derived node\n * const window = lg.slice(10, 20); // derived node\n * ```\n *\n * @category extra\n */\nexport function reactiveLog<T>(\n\tinitial?: readonly T[],\n\toptions: ReactiveLogOptions<T> = {},\n): ReactiveLogBundle<T> {\n\tconst { name, maxSize, versioning, backend: userBackend } = options;\n\tconst backend: LogBackend<T> = userBackend ?? new NativeLogBackend<T>(initial, maxSize);\n\n\tconst entries = state<readonly T[]>(backend.toArray(), {\n\t\tname,\n\t\tdescribeKind: \"state\",\n\t\tequals: (a, b) => a === b,\n\t\t...(versioning != null ? { versioning } : {}),\n\t});\n\n\tfunction pushSnapshot(): void {\n\t\tconst snapshot = backend.toArray();\n\t\tbatch(() => {\n\t\t\tentries.down([[DIRTY]]);\n\t\t\tentries.down([[DATA, snapshot]]);\n\t\t});\n\t}\n\n\t// Memoization caches for derived views (D2(c)). Each cache is an LRU keyed by\n\t// the unique view argument, bounded by `DEFAULT_VIEW_CACHE_MAX`. On cache miss\n\t// past the cap, the least-recently-used entry is evicted and its keepalive\n\t// disposer is called so the underlying derived node can be GC'd. Callers can\n\t// also release views proactively via `disposeTail` / `disposeSlice` /\n\t// `disposeAllViews`. Iteration order of `Map` is insertion order, so moving\n\t// an entry to the end on hit is the LRU \"touch\".\n\ttype ViewEntry = { node: Node<readonly T[]>; dispose: () => void };\n\tconst tailCache = new Map<number, ViewEntry>();\n\tconst sliceCache = new Map<string, ViewEntry>();\n\n\tfunction sliceKey(start: number, stop?: number): string {\n\t\treturn `${start}:${stop === undefined ? \"END\" : stop}`;\n\t}\n\n\tfunction evictOldestIfFull<K>(cache: Map<K, ViewEntry>): void {\n\t\tif (cache.size < DEFAULT_VIEW_CACHE_MAX) return;\n\t\tconst first = cache.keys().next();\n\t\tif (first.done) return;\n\t\tconst oldest = cache.get(first.value);\n\t\tif (oldest !== undefined) oldest.dispose();\n\t\tcache.delete(first.value);\n\t}\n\n\t/**\n\t * D4(a): try/finally defense-in-depth — if a custom backend op throws\n\t * mid-mutation, surface the partial state via pushSnapshot so subscribers\n\t * don't see a stale cache. Matches the pattern in reactive-map and\n\t * reactive-index. Native ops are atomic by contract; this only matters\n\t * for user-supplied backends.\n\t */\n\tfunction wrapMutation<R>(op: () => R): R {\n\t\tconst prev = backend.version;\n\t\ttry {\n\t\t\treturn op();\n\t\t} finally {\n\t\t\tif (backend.version !== prev) pushSnapshot();\n\t\t}\n\t}\n\n\treturn {\n\t\tentries,\n\n\t\tget size(): number {\n\t\t\treturn backend.size;\n\t\t},\n\n\t\tat(index: number): T | undefined {\n\t\t\treturn backend.at(index);\n\t\t},\n\n\t\tappend(value: T): void {\n\t\t\twrapMutation(() => backend.append(value));\n\t\t},\n\n\t\tappendMany(values: readonly T[]): void {\n\t\t\tif (values.length === 0) return;\n\t\t\twrapMutation(() => backend.appendMany(values));\n\t\t},\n\n\t\tclear(): void {\n\t\t\twrapMutation(() => backend.clear());\n\t\t\t// NOTE: cached tail/slice derived views are intentionally NOT\n\t\t\t// disposed here. Disposing would kill the keepalive on any node\n\t\t\t// a caller already holds externally, silently stopping their\n\t\t\t// updates. The derived nodes recompute from the new empty\n\t\t\t// snapshot when `entries` emits post-clear, so `.cache` on an\n\t\t\t// outstanding view settles to `[]` without any manual\n\t\t\t// reset. (Initial snapshots, if inspected before the next wave,\n\t\t\t// may be stale — callers who care can `disposeTail` / `slice`\n\t\t\t// explicitly.)\n\t\t},\n\n\t\ttrimHead(n: number): void {\n\t\t\twrapMutation(() => backend.trimHead(n));\n\t\t},\n\n\t\ttail(n: number): Node<readonly T[]> {\n\t\t\tif (!Number.isInteger(n) || n < 0) {\n\t\t\t\tthrow new RangeError(`tail: n must be a non-negative integer (got ${n})`);\n\t\t\t}\n\t\t\tconst hit = tailCache.get(n);\n\t\t\tif (hit !== undefined) {\n\t\t\t\t// LRU touch: move to end of insertion order.\n\t\t\t\ttailCache.delete(n);\n\t\t\t\ttailCache.set(n, hit);\n\t\t\t\treturn hit.node;\n\t\t\t}\n\t\t\tevictOldestIfFull(tailCache);\n\t\t\tconst node_ = derived(\n\t\t\t\t[entries],\n\t\t\t\t([s]) => {\n\t\t\t\t\tconst list = s as readonly T[];\n\t\t\t\t\tif (n === 0 || list.length === 0) return [];\n\t\t\t\t\treturn list.slice(Math.max(0, list.length - n));\n\t\t\t\t},\n\t\t\t\t{ initial: backend.tail(n), describeKind: \"derived\" },\n\t\t\t);\n\t\t\tconst dispose = keepaliveDerived(node_);\n\t\t\ttailCache.set(n, { node: node_, dispose });\n\t\t\treturn node_;\n\t\t},\n\n\t\tslice(start: number, stop?: number): Node<readonly T[]> {\n\t\t\tif (!Number.isInteger(start) || start < 0) {\n\t\t\t\tthrow new RangeError(`slice: start must be a non-negative integer (got ${start})`);\n\t\t\t}\n\t\t\t// P4: reject negative stop explicitly to keep bundle / backend / derived\n\t\t\t// consistent (JS `Array.prototype.slice` supports negative stop, but the\n\t\t\t// backend can't cheaply honor it without scanning length, so we disallow).\n\t\t\tif (stop !== undefined && (!Number.isInteger(stop) || stop < 0)) {\n\t\t\t\tthrow new RangeError(\n\t\t\t\t\t`slice: stop must be a non-negative integer or undefined (got ${stop})`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst key = sliceKey(start, stop);\n\t\t\tconst hit = sliceCache.get(key);\n\t\t\tif (hit !== undefined) {\n\t\t\t\tsliceCache.delete(key);\n\t\t\t\tsliceCache.set(key, hit);\n\t\t\t\treturn hit.node;\n\t\t\t}\n\t\t\tevictOldestIfFull(sliceCache);\n\t\t\tconst node_ = derived(\n\t\t\t\t[entries],\n\t\t\t\t([s]) => {\n\t\t\t\t\tconst list = s as readonly T[];\n\t\t\t\t\treturn stop === undefined ? list.slice(start) : list.slice(start, stop);\n\t\t\t\t},\n\t\t\t\t{ initial: backend.slice(start, stop), describeKind: \"derived\" },\n\t\t\t);\n\t\t\tconst dispose = keepaliveDerived(node_);\n\t\t\tsliceCache.set(key, { node: node_, dispose });\n\t\t\treturn node_;\n\t\t},\n\n\t\tdisposeTail(n: number): boolean {\n\t\t\tconst hit = tailCache.get(n);\n\t\t\tif (hit === undefined) return false;\n\t\t\thit.dispose();\n\t\t\ttailCache.delete(n);\n\t\t\treturn true;\n\t\t},\n\n\t\tdisposeSlice(start: number, stop?: number): boolean {\n\t\t\tconst key = sliceKey(start, stop);\n\t\t\tconst hit = sliceCache.get(key);\n\t\t\tif (hit === undefined) return false;\n\t\t\thit.dispose();\n\t\t\tsliceCache.delete(key);\n\t\t\treturn true;\n\t\t},\n\n\t\tdisposeAllViews(): void {\n\t\t\tfor (const entry of tailCache.values()) entry.dispose();\n\t\t\ttailCache.clear();\n\t\t\tfor (const entry of sliceCache.values()) entry.dispose();\n\t\t\tsliceCache.clear();\n\t\t},\n\n\t\tdispose(): void {\n\t\t\t// D6(a): currently identical to disposeAllViews. Exposed as a\n\t\t\t// uniform lifecycle API across all 4 reactive data structures.\n\t\t\tfor (const entry of tailCache.values()) entry.dispose();\n\t\t\ttailCache.clear();\n\t\t\tfor (const entry of sliceCache.values()) entry.dispose();\n\t\t\tsliceCache.clear();\n\t\t},\n\t};\n}\n"],"mappings":";;;;;;;;;;;;;AASA,SAAS,kBAAkB;AAsCpB,SAAS,aACf,MACA,SAC2B;AAC3B,MAAI,SAAS,KAAK;AACjB,WAAO,IAAI,WAAqB,CAAC,eAAe;A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 = [];
242
242
  var drainPhase4 = [];
243
+ var flushHooks = [];
243
244
  function isBatching() {
244
245
  return batchDepth > 0 || flushInProgress;
245
246
  }
247
+ function isExplicitlyBatching() {
248
+ return batchDepth > 0;
249
+ }
250
+ function registerBatchFlushHook(hook) {
251
+ if (batchDepth > 0) {
252
+ flushHooks.push(hook);
253
+ } else {
254
+ hook();
255
+ }
256
+ }
246
257
  function batch(fn) {
247
258
  batchDepth += 1;
248
259
  let threw = false;
@@ -256,6 +267,13 @@ function batch(fn) {
256
267
  if (batchDepth === 0) {
257
268
  if (threw) {
258
269
  if (!flushInProgress) {
270
+ const hooks = flushHooks.splice(0);
271
+ for (const h of hooks) {
272
+ try {
273
+ h();
274
+ } catch {
275
+ }
276
+ }
259
277
  drainPhase2.length = 0;
260
278
  drainPhase3.length = 0;
261
279
  drainPhase4.length = 0;
@@ -272,7 +290,18 @@ function drainPending() {
272
290
  const errors = [];
273
291
  let iterations = 0;
274
292
  try {
275
- while (drainPhase2.length > 0 || drainPhase3.length > 0 || drainPhase4.length > 0) {
293
+ while (drainPhase2.length > 0 || drainPhase3.length > 0 || drainPhase4.length > 0 || ownsFlush && flushHooks.length > 0) {
294
+ if (ownsFlush && flushHooks.length > 0) {
295
+ const hooks = flushHooks.splice(0);
296
+ for (const h of hooks) {
297
+ try {
298
+ h();
299
+ } catch (e) {
300
+ errors.push(e);
301
+ }
302
+ }
303
+ continue;
304
+ }
276
305
  iterations += 1;
277
306
  if (iterations > MAX_DRAIN_ITERATIONS) {
278
307
  drainPhase2.length = 0;
@@ -962,6 +991,22 @@ var NodeImpl = class _NodeImpl {
962
991
  * treats `0` as "wave settled" — O(1) check for full dep settlement.
963
992
  */
964
993
  _dirtyDepCount = 0;
994
+ // --- Per-batch emit accumulator (Bug 2: K+1 fan-in fix) ---
995
+ /**
996
+ * Inside an explicit `batch(() => ...)` scope, every `_emit` accumulates
997
+ * its already-framed messages here instead of dispatching synchronously.
998
+ * At batch end, `_flushBatchPending` runs (registered via
999
+ * `registerBatchFlushHook`) and delivers the whole accumulated batch as
1000
+ * one `downWithBatch` call — collapsing what would otherwise be K
1001
+ * separate sink invocations into one. This is the fix for the diamond
1002
+ * fan-in K+1 over-fire.
1003
+ *
1004
+ * `null` outside batch (or after flush). Only ever appended to within
1005
+ * a single explicit batch lifetime; reset to `null` on flush. State
1006
+ * updates (cache, version, status) still happen per-emit via
1007
+ * `_updateState` — only the downstream delivery is coalesced.
1008
+ */
1009
+ _batchPendingMessages = null;
965
1010
  // --- PAUSE/RESUME lock tracking (C0) ---
966
1011
  /**
967
1012
  * Set of active pause locks held against this node. Every `[PAUSE, lockId]`
@@ -1339,7 +1384,10 @@ var NodeImpl = class _NodeImpl {
1339
1384
  dep.unsub = noopUnsub;
1340
1385
  dep.unsub = dep.node.subscribe((msgs) => {
1341
1386
  if (dep.unsub === null) return;
1387
+ const tierOf = this._config.tierOf;
1388
+ let sawSettlement = false;
1342
1389
  for (const m of msgs) {
1390
+ if (tierOf(m[0]) >= 3) sawSettlement = true;
1343
1391
  this._config.onMessage(
1344
1392
  this,
1345
1393
  m,
@@ -1347,6 +1395,7 @@ var NodeImpl = class _NodeImpl {
1347
1395
  this._actions
1348
1396
  );
1349
1397
  }
1398
+ if (sawSettlement) this._maybeRunFnOnSettlement();
1350
1399
  });
1351
1400
  subscribedCount++;
1352
1401
  }
@@ -1401,7 +1450,10 @@ var NodeImpl = class _NodeImpl {
1401
1450
  try {
1402
1451
  record.unsub = depNode.subscribe((msgs) => {
1403
1452
  if (record.unsub === null) return;
1453
+ const tierOf = this._config.tierOf;
1454
+ let sawSettlement = false;
1404
1455
  for (const m of msgs) {
1456
+ if (tierOf(m[0]) >= 3) sawSettlement = true;
1405
1457
  this._config.onMessage(
1406
1458
  this,
1407
1459
  m,
@@ -1409,6 +1461,7 @@ var NodeImpl = class _NodeImpl {
1409
1461
  this._actions
1410
1462
  );
1411
1463
  }
1464
+ if (sawSettlement) this._maybeRunFnOnSettlement();
1412
1465
  });
1413
1466
  } catch (err) {
1414
1467
  record.unsub = null;
@@ -1530,7 +1583,6 @@ var NodeImpl = class _NodeImpl {
1530
1583
  }
1531
1584
  return;
1532
1585
  }
1533
- this._maybeRunFnOnSettlement();
1534
1586
  }
1535
1587
  // --- Centralized dep-state transitions (A3 settlement counters) ---
1536
1588
  //
@@ -1902,10 +1954,10 @@ var NodeImpl = class _NodeImpl {
1902
1954
  }
1903
1955
  }
1904
1956
  if (immediate.length > 0) {
1905
- downWithBatch(this._deliverToSinks, immediate, tierOf);
1957
+ this._dispatchOrAccumulate(immediate);
1906
1958
  }
1907
1959
  } else {
1908
- downWithBatch(this._deliverToSinks, finalMessages, this._config.tierOf);
1960
+ this._dispatchOrAccumulate(finalMessages);
1909
1961
  }
1910
1962
  }
1911
1963
  if (equalsError != null) {
@@ -2028,6 +2080,50 @@ var NodeImpl = class _NodeImpl {
2028
2080
  const snapshot = [...this._sinks];
2029
2081
  for (const sink of snapshot) sink(messages);
2030
2082
  };
2083
+ /**
2084
+ * @internal Dispatch entry point that respects the per-batch emit
2085
+ * accumulator (Bug 2). Inside an explicit `batch()` scope, append to
2086
+ * `_batchPendingMessages` and register a flush hook on first append.
2087
+ * Outside batch — or during a drain (where `flushInProgress` is true
2088
+ * but `batchDepth` is 0) — dispatch synchronously through `downWithBatch`.
2089
+ *
2090
+ * Per-emit state updates (`_frameBatch`, `_updateState`) have already
2091
+ * happened by the time we reach here; only the **downstream delivery**
2092
+ * is coalesced. Cache, version, and status are visible mid-batch on
2093
+ * the emitting node itself.
2094
+ */
2095
+ _dispatchOrAccumulate(messages) {
2096
+ if (isExplicitlyBatching()) {
2097
+ if (this._batchPendingMessages === null) {
2098
+ this._batchPendingMessages = [];
2099
+ registerBatchFlushHook(() => this._flushBatchPending());
2100
+ }
2101
+ for (const m of messages) this._batchPendingMessages.push(m);
2102
+ return;
2103
+ }
2104
+ downWithBatch(this._deliverToSinks, messages, this._config.tierOf);
2105
+ }
2106
+ /**
2107
+ * @internal Flushes the accumulated batch through `downWithBatch` and
2108
+ * clears the pending state. Idempotent — safe to call when pending is
2109
+ * already null or empty (e.g. on a `batch()` throw, where the hook
2110
+ * fires for cleanup but the drainPhase queues are wiped after).
2111
+ *
2112
+ * Critical: the accumulated batch is interleaved per-emit framings like
2113
+ * `[DIRTY, DATA(1), DIRTY, DATA(2)]` — non-monotone tier order. We must
2114
+ * re-frame to sort by tier before handing to `downWithBatch`, which
2115
+ * assumes pre-sorted input. `_frameBatch` also handles the synthetic
2116
+ * DIRTY prepend rule (no-op here — `hasDirty` is true since each
2117
+ * accumulated emit already carries its own DIRTY prefix).
2118
+ */
2119
+ _flushBatchPending() {
2120
+ const pending = this._batchPendingMessages;
2121
+ if (pending === null) return;
2122
+ this._batchPendingMessages = null;
2123
+ if (pending.length === 0) return;
2124
+ const framed = this._frameBatch(pending);
2125
+ downWithBatch(this._deliverToSinks, framed, this._config.tierOf);
2126
+ }
2031
2127
  };
2032
2128
  var isNodeArray = (value) => Array.isArray(value);
2033
2129
  var isNodeOptionsObject = (value) => typeof value === "object" && value != null && !Array.isArray(value);
@@ -2231,4 +2327,4 @@ export {
2231
2327
  autoTrackNode,
2232
2328
  pipe
2233
2329
  };
2234
- //# sourceMappingURL=chunk-QA3RP5NH.js.map
2330
+ //# sourceMappingURL=chunk-NZMBRXQV.js.map