@solidjs/signals 2.0.0-rc.11 → 2.0.0-rc.14

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 (118) hide show
  1. package/dist/dev-shared.js +2056 -3773
  2. package/dist/dev.attribution.js +159 -91
  3. package/dist/dev.js +7263 -8384
  4. package/dist/observe/affects.js +125 -104
  5. package/dist/observe/boundaries.js +458 -665
  6. package/dist/observe/core/action.js +63 -66
  7. package/dist/observe/core/async.js +240 -383
  8. package/dist/observe/core/attribution-queries.js +1 -1
  9. package/dist/observe/core/attribution.js +271 -199
  10. package/dist/observe/core/constants.js +115 -178
  11. package/dist/observe/core/context.js +3 -3
  12. package/dist/observe/core/core.js +840 -1428
  13. package/dist/observe/core/dev.js +41 -18
  14. package/dist/observe/core/effect.js +75 -86
  15. package/dist/observe/core/external.js +5 -5
  16. package/dist/observe/core/graph.js +61 -70
  17. package/dist/observe/core/heap.js +75 -98
  18. package/dist/observe/core/invariants.js +1 -34
  19. package/dist/observe/core/lanes.js +704 -181
  20. package/dist/observe/core/owner.js +80 -101
  21. package/dist/observe/core/scheduler.js +708 -1351
  22. package/dist/observe/core/verdict.js +302 -621
  23. package/dist/observe/flatten.js +79 -0
  24. package/dist/observe/index.js +15 -13
  25. package/dist/observe/map.js +232 -235
  26. package/dist/observe/reveal.js +212 -0
  27. package/dist/observe/signals.js +133 -215
  28. package/dist/observe/store/affects.js +135 -0
  29. package/dist/observe/store/index.js +29 -24
  30. package/dist/observe/store/optimistic.js +538 -0
  31. package/dist/observe/store/projection.js +302 -0
  32. package/dist/observe/store/reconcile.js +257 -0
  33. package/dist/observe/store/store.js +1945 -277
  34. package/dist/observe/store/storePath.js +1 -1
  35. package/dist/{prod/store/next → observe/store}/target.js +17 -18
  36. package/dist/observe/store/types.js +73 -0
  37. package/dist/observe/store/utils.js +1 -13
  38. package/dist/prod/affects.js +127 -106
  39. package/dist/prod/boundaries.js +442 -654
  40. package/dist/prod/core/action.js +71 -74
  41. package/dist/prod/core/async.js +307 -442
  42. package/dist/prod/core/constants.js +112 -177
  43. package/dist/prod/core/context.js +3 -3
  44. package/dist/prod/core/core.js +852 -1448
  45. package/dist/prod/core/effect.js +88 -99
  46. package/dist/prod/core/external.js +5 -5
  47. package/dist/prod/core/graph.js +61 -70
  48. package/dist/prod/core/heap.js +75 -98
  49. package/dist/prod/core/invariants.js +1 -32
  50. package/dist/prod/core/lanes.js +666 -181
  51. package/dist/prod/core/owner.js +75 -96
  52. package/dist/prod/core/scheduler.js +677 -1332
  53. package/dist/prod/core/verdict.js +297 -621
  54. package/dist/prod/flatten.js +77 -0
  55. package/dist/prod/index.js +15 -13
  56. package/dist/prod/map.js +143 -146
  57. package/dist/prod/reveal.js +212 -0
  58. package/dist/prod/signals.js +144 -226
  59. package/dist/prod/store/affects.js +135 -0
  60. package/dist/prod/store/index.js +28 -19
  61. package/dist/prod/store/optimistic.js +533 -0
  62. package/dist/prod/store/projection.js +295 -0
  63. package/dist/prod/store/reconcile.js +257 -0
  64. package/dist/prod/store/store.js +1840 -272
  65. package/dist/prod/store/storePath.js +1 -1
  66. package/dist/{observe/store/next → prod/store}/target.js +13 -17
  67. package/dist/prod/store/types.js +73 -0
  68. package/dist/prod/store/utils.js +1 -11
  69. package/dist/types/affects.d.ts +11 -30
  70. package/dist/types/boundaries.d.ts +62 -176
  71. package/dist/types/carved.d.ts +1 -0
  72. package/dist/types/core/action.d.ts +5 -6
  73. package/dist/types/core/async.d.ts +10 -5
  74. package/dist/types/core/attribution-hooks.d.ts +48 -1
  75. package/dist/types/core/attribution.d.ts +29 -9
  76. package/dist/types/core/constants.d.ts +125 -171
  77. package/dist/types/core/core.d.ts +104 -264
  78. package/dist/types/core/dev.d.ts +60 -7
  79. package/dist/types/core/effect.d.ts +0 -7
  80. package/dist/types/core/graph.d.ts +7 -1
  81. package/dist/types/core/heap.d.ts +5 -7
  82. package/dist/types/core/index.d.ts +6 -6
  83. package/dist/types/core/invariants.d.ts +0 -29
  84. package/dist/types/core/lanes.d.ts +65 -87
  85. package/dist/types/core/owner.d.ts +3 -3
  86. package/dist/types/core/scheduler.d.ts +249 -331
  87. package/dist/types/core/types.d.ts +51 -85
  88. package/dist/types/core/verdict.d.ts +3 -0
  89. package/dist/types/flatten.d.ts +8 -0
  90. package/dist/types/index.d.ts +7 -5
  91. package/dist/types/reveal.d.ts +19 -0
  92. package/dist/types/signals.d.ts +53 -92
  93. package/dist/types/store/affects.d.ts +1 -0
  94. package/dist/types/store/index.d.ts +35 -15
  95. package/dist/types/store/optimistic.d.ts +23 -0
  96. package/dist/types/store/projection.d.ts +18 -0
  97. package/dist/types/store/reconcile.d.ts +3 -0
  98. package/dist/types/store/store.d.ts +165 -143
  99. package/dist/types/store/storePath.d.ts +1 -1
  100. package/dist/types/store/target.d.ts +151 -0
  101. package/dist/types/store/types.d.ts +84 -0
  102. package/package.json +1 -1
  103. package/dist/observe/core/optimistic.js +0 -669
  104. package/dist/observe/store/next/optimistic.js +0 -717
  105. package/dist/observe/store/next/projection.js +0 -266
  106. package/dist/observe/store/next/reconcile.js +0 -375
  107. package/dist/observe/store/next/store.js +0 -2480
  108. package/dist/prod/core/optimistic.js +0 -658
  109. package/dist/prod/store/next/optimistic.js +0 -710
  110. package/dist/prod/store/next/projection.js +0 -257
  111. package/dist/prod/store/next/reconcile.js +0 -373
  112. package/dist/prod/store/next/store.js +0 -2356
  113. package/dist/types/core/optimistic.d.ts +0 -6
  114. package/dist/types/store/next/optimistic.d.ts +0 -25
  115. package/dist/types/store/next/projection.d.ts +0 -27
  116. package/dist/types/store/next/reconcile.d.ts +0 -10
  117. package/dist/types/store/next/store.d.ts +0 -143
  118. package/dist/types/store/next/target.d.ts +0 -196
@@ -1,331 +1,1999 @@
1
- import "../core/core.js";
1
+ import { attrHooks } from "../core/attribution-hooks.js";
2
2
 
3
- import "../core/dev.js";
3
+ import { CONFIG_MANUAL_WRITE, CONFIG_OVERRIDE, CONFIG_HELD, $REFRESH, NOT_PENDING, STATUS_PENDING, STATUS_ERROR, EFFECT_RENDER, REACTIVE_RECOMPUTING_DEPS, REACTIVE_STAGED_READ, CONFIG_VERDICT, CONFIG_CHILDREN_FORBIDDEN, CONFIG_PROMOTED, REACTIVE_DIRTY, REACTIVE_CHECK } from "../core/constants.js";
4
4
 
5
- import { GlobalQueue } from "../core/scheduler.js";
5
+ import { setSignal, isEqual, read, verdict, context, notePromotedWrite, untrack, slotSignal, stagedScreen, stagedRead } from "../core/core.js";
6
6
 
7
- import "../core/invariants.js";
7
+ import { registerGraph } from "../core/dev.js";
8
8
 
9
- import "../core/verdict.js";
9
+ import { setSlotUnobserved } from "../core/graph.js";
10
10
 
11
- import "../core/effect.js";
11
+ import { getOwner, getObserver } from "../core/owner.js";
12
12
 
13
- import { $OWNER, lookupTarget as lookupTarget$1 } from "./next/target.js";
13
+ import { insertIntoHeap } from "../core/heap.js";
14
+
15
+ import { txOf, flushTransaction, holdNode, joinFuture, insertSubs, schedule, passLane, globalQueue, queuePendingNode, GlobalQueue, joinPassTx, dirtyQueue } from "../core/scheduler.js";
16
+
17
+ import { lookupTarget, storeOwners, setLookup, $OWNER, isOwned, markDescendants, devAssertNeverUserMutation } from "./target.js";
18
+
19
+ import { $TARGET, rawValuesUsed, isRawValue, isWrappable, markRawIngest, writeOverride, markRawOne, $RECORD, $PROXY, $TRACK } from "./types.js";
20
+
21
+ export { markRaw } from "./types.js";
14
22
 
15
23
  /**
16
- * Brand symbols used internally by the store proxy / projection plumbing.
17
- * Cross-package wiring; not part of the user-facing API.
24
+ * Store — plain stores on L2 (plan sec. 31, S1).
25
+ *
26
+ * A store is a tree of L2 nodes and nothing else carries reactive state:
18
27
  *
19
- * @internal
20
- */ const $TRACK = Symbol(0), $TARGET = Symbol(0), $PROXY = Symbol(0),
21
- // The view record behind a merge()/omit() proxy (a `MergeView` or an
22
- // `OmitView`, utils.ts); a store answers `undefined` on its symbol fast
23
- // path. One read classifies any `$PROXY`-marked object — store, view, or
24
- // foreign — where asking `$TARGET` first and then each view kind was two
25
- // to four trap hops (see `viewOf`).
26
- $RECORD = Symbol(0), // Node-map slot carrying a record-level `affects()` mark: any read through
27
- // the record witnesses it into the active isPending() probe.
28
- $AFFECTS = Symbol(0);
29
-
30
- // Structural field names of store targets (StoreNextTarget aliases these, so
31
- // shared machinery — affects walks, tests — reads targets via the consts).
32
- const STORE_VALUE = "v", STORE_NODE = "n", STORE_HAS = "h";
33
-
34
- function lookupTarget(e, t) {
35
- // Family registrations (projections/optimistic) first, then the global
36
- // next lookup. Proxies resolve through $TARGET directly.
37
- return (t ? lookupTarget$1(e, t) : undefined) ?? lookupTarget$1(e, null);
38
- }
39
-
40
- // Values marked raw never acquire a proxy identity: wrap() serves them as-is
41
- // everywhere — deep stores hold them as leaf values replaced by reference.
42
- // Once raw, always raw (identity stays single, just unwrapped). Consulted
43
- // only on wrap-creation and ingest paths; reads never touch it.
44
- const rawValues = new WeakSet;
28
+ * - **Leaf nodes** (one per tracked-or-written key, lazy; `slotSignal`, one
29
+ * literal): `_value` committed, `_pendingValue` this batch's staging.
30
+ * - **Presence nodes** (`in` tracks presence, not value — R13) and the
31
+ * **deep witness** (`deep()` subscribes one node per record).
32
+ * - The **container node** `k` (plan sec. 31.3, Q-A): the `$TRACK` node given a
33
+ * value. `_value` is the committed backing, `_pendingValue` the pending
34
+ * backing the draft mutates — so a write to a key nobody reads has a
35
+ * staging home the scheduler owns, and park/commit/revert of the backing
36
+ * is the hold model's, not a fold ledger of the store's. Structural
37
+ * readers (`ownKeys`, iteration, `$TRACK`, `length`, `deep`) subscribe to
38
+ * it; value readers never do — a key with no leaf reads through the
39
+ * container's visible backing without subscribing (R1: node existence is
40
+ * unobservable).
41
+ *
42
+ * The committed backing (`t.v`) is owned raw (CoW: a user object is shared
43
+ * until the first write privatizes it and its ancestor chain). It mutates at
44
+ * exactly one moment — the flush's commit (`_storeCommit`), after the
45
+ * container node committed its staging. Reads: context-free readers see the
46
+ * committed backing until the flush; a pass sees the staging (signal
47
+ * parity, RUL-1); the draft reads its own staging.
48
+ *
49
+ * Perf contracts (plan sec. 31.4): lazy nodes; one literal per node; O(written) per
50
+ * setter (`wk`); overlay drafts for large plain records; no new named
51
+ * fields on array targets; zero allocation for adopted-but-unread objects.
52
+ */ let optHooks = null;
45
53
 
46
- /**
47
- * Marks a value as raw: no store will ever wrap it — every store presents it
48
- * as-is, tracked by reference at whatever slot holds it and updated by
49
- * replacement. Useful for class instances and external objects (editors,
50
- * scene graphs, Maps) and for record-shaped data updated wholesale. Sticky
51
- * for the value's lifetime.
52
- */
53
- // Flipped on the first mark and exported as a LIVE binding: reconcile
54
- // consults it on every recursable pair, and importing the boolean directly
55
- // lets those sites skip even the function call when no shallow store or raw
56
- // mark exists anywhere in the app.
57
- let rawValuesUsed = false;
58
-
59
- function isRawValue(e) {
60
- return rawValuesUsed && rawValues.has(e);
61
- }
62
-
63
- function markRawOne(e) {
64
- if (isWrappable(e)) {
65
- // A store proxy is already tracked elsewhere: the shallow boundary passes
66
- // it through by reference (replaced, never edited — same slot semantics
67
- // as a raw) instead of claiming it raw. The sticky mark is global, so
68
- // marking a live proxy would make wrap() serve it verbatim through every
69
- // OTHER store too — downstream deep stores then captured it instead of
70
- // wrapping it in their own family, and their writes landed in the
71
- // upstream store's override layer (#2932).
72
- if (e[$TARGET] !== undefined) return;
73
- rawValuesUsed = true;
74
- rawValues.add(e);
75
- }
76
- }
77
-
78
- function markRawIngest(e) {
79
- if (Array.isArray(e)) {
80
- for (let t = 0, o = e.length; t < o; t++) markRawOne(e[t]);
81
- } else {
82
- for (const t in e) markRawOne(e[t]);
83
- }
84
- }
85
-
86
- const OBJECT_PROTO = Object.prototype;
87
-
88
- // Per-prototype memo for the custom-proto branch of isWrappable: the verdict
89
- // is fully determined by the prototype (tag and Node lineage both live on
90
- // the chain), so each class pays the tag call once — not per read.
91
- const wrappableProtos = new WeakMap;
92
-
93
- function isWrappable(e) {
94
- if (e == null || typeof e !== "object" || Object.isFrozen(e)) return false;
95
- // Plain data and user class instances wrap; platform objects never do
96
- // (#2952). Native code brand-checks internal slots and throws through a
97
- // proxy (`Map.prototype.size`, `Date.prototype.getTime`, ...), so
98
- // collections and other built-ins can't honestly be stores — they get the
99
- // markRaw-children contract automatically: served raw, mutations land raw,
100
- // the property holding them still tracks (reassignment notifies). The tag
101
- // check separates them structurally: user classes stringify as
102
- // `[object Object]` while every native/host object carries its own brand
103
- // (`[object Map]`, `[object Date]`, `[object Headers]`, ...), including
104
- // subclasses, which inherit the tag. getPrototypeOf keeps the hot path
105
- // (plain and null-proto objects) intrinsic-only — no property lookup.
106
- const t = Object.getPrototypeOf(e);
107
- if (t === OBJECT_PROTO || t === null) return true;
108
- if (Array.isArray(e)) return true;
109
- let o = wrappableProtos.get(t);
54
+ function installOptHooks(e) {
55
+ optHooks = e;
56
+ }
57
+
58
+ let affectsHooks = null;
59
+
60
+ function installAffectsHooks(e) {
61
+ affectsHooks = e;
62
+ }
63
+
64
+ /** Key of the deep-witness slot node (never a user key). */ const $DEEP = Symbol(0);
65
+
66
+ // ---------------------------------------------------------------------------
67
+ // wrap / dedupe
68
+ /** Pre-shaped constructor for OBJECT proxy targets: V8 tips a bare `{}` into
69
+ * dictionary mode once ~19 named properties are assigned onto it (the #3044
70
+ * `ovl`/`del` fields crossed that line — every trap's field read became a
71
+ * hash lookup, a 15% deep-dbmon tick regression). Declaring every field in a
72
+ * constructor pre-allocates in-object slots so the map stays fast, with
73
+ * headroom for future fields. The prototype is reset to `Object.prototype`
74
+ * so proxy-forwarded semantics (getPrototypeOf, constructor) are exactly a
75
+ * plain object's. Array targets keep the bare-`[]` path — they must carry
76
+ * the array exotic class for `Array.isArray(proxy)`.
77
+ *
78
+ * ARRAY SHAPE RULE: arrays normalize their named properties to dictionary
79
+ * mode as the count grows (V8 13.x: counts ≡ 0 mod 3 from 18 up), so the
80
+ * target's named field count is capped at 20 — any future write-side state
81
+ * beyond `wk` must ride an extension object (see target.ts), never new
82
+ * named fields here. */ function TargetShape() {
83
+ this.v = undefined;
84
+ this.ch = undefined;
85
+ this.pb = undefined;
86
+ this.n = undefined;
87
+ this.h = undefined;
88
+ this.k = undefined;
89
+ this.dk = undefined;
90
+ this.u = undefined;
91
+ this.pk = undefined;
92
+ this.px = undefined;
93
+ this.d = undefined;
94
+ this.a = undefined;
95
+ this.sc = undefined;
96
+ this.kc = undefined;
97
+ this.nc = undefined;
98
+ this.fam = undefined;
99
+ this.s = undefined;
100
+ this.ovl = undefined;
101
+ this.del = undefined;
102
+ this.wk = undefined;
103
+ }
104
+
105
+ TargetShape.prototype = Object.prototype;
106
+
107
+ function createTarget(e, n, t, r = n?.fam ?? null) {
108
+ // The proxy target carries the array exotic class when the value is an
109
+ // array, so Array.isArray(proxy) is true; the fields live on it directly.
110
+ // Direct field assignment in one fixed order (no Object.assign literal
111
+ // copy): every target shares a hidden-class transition chain — createTarget
112
+ // was the #2 store cost in the uibench creation profile.
113
+ const o = Array.isArray(e) ? [] : new TargetShape;
114
+ o.v = e;
115
+ // Chained-backing flag (backing IS another store's proxy, §7b) — cached so
116
+ // the hot read path never does a per-read symbol lookup on the backing.
117
+ o.ch = e[$TARGET] !== undefined;
118
+ o.pb = null;
119
+ o.n = null;
120
+ o.h = null;
121
+ o.k = null;
122
+ o.dk = null;
123
+ o.wk = null;
124
+ o.u = n;
125
+ o.pk = t;
126
+ o.px = null;
127
+ o.d = false;
128
+ o.a = false;
129
+ o.sc = 0;
130
+ o.kc = 0;
131
+ o.nc = 0;
132
+ o.fam = r;
133
+ o.s = false;
134
+ o.ovl = false;
135
+ o.del = null;
136
+ o.px = new Proxy(o, traps);
137
+ setLookup(e, o);
138
+ return o;
139
+ }
140
+
141
+ function wrap(e, n = null, t = null, r = n?.fam ?? null) {
142
+ // markRaw'd values never wrap through ANY store (R42; sticky raw-marking
143
+ // is one half of the never-both-wrapped-and-raw invariant, RUL-12).
144
+ if (rawValuesUsed && isRawValue(e)) return e;
145
+ const o = lookupTarget(e, r);
146
+ if (o !== undefined) return o.px;
147
+ const i = e[$TARGET];
148
+ if (i !== undefined && i.px === e) {
149
+ // Foreign-family proxies re-wrap into THIS family (writes stay isolated);
150
+ // same-family and plain-store proxies pass through.
151
+ if (r === null || i.fam === r) return e;
152
+ return createTarget(e, n, t, r).px;
153
+ }
154
+ return createTarget(e, n, t, r).px;
155
+ }
156
+
157
+ /** Unwrap our own proxies to their current backing; leave everything else.
158
+ * A projection draft wrapper is registered as its target's alias
159
+ * (projection.ts `wrapDraft`) — adopted as a backing, it would forward to
160
+ * itself (#3767). */ function unwrapValue(e) {
161
+ if (e == null || typeof e !== "object") return e;
162
+ const n = e[$TARGET];
163
+ if (n !== undefined && (n.px === e || lookupTarget(e, n.fam) === n) && n.v !== undefined) {
164
+ // A draft escaping into other storage must be a REAL container that
165
+ // becomes this target's committed backing at fold (the shared-raw
166
+ // contract) — a prototype overlay is neither.
167
+ if (n.ovl) materializePB(n);
168
+ return n.pb ?? n.v;
169
+ }
170
+ return e;
171
+ }
172
+
173
+ // ---------------------------------------------------------------------------
174
+ // nodes: pure subscription points (values used only for equality gating)
175
+ // Shared slot-node equality (create-floor diet): ONE function for every
176
+ // leaf — `this` is the node (method-call convention at every _equals site),
177
+ // `_host` is the baked-in target backref. Logical-slot equality: values
178
+ // resolving to the same child target are the same slot (privatization/
179
+ // adoption swap raw identity without changing the logical value — only
180
+ // changed leaves notify, R9).
181
+ const slotNodeEquals = function(e, n) {
182
+ return isEqual(e, n) || sameLogicalSlot(this.yt, e, n);
183
+ };
184
+
185
+ /** The deep witness: the store decides when it notifies. */ const never = false;
186
+
187
+ function sameKey(e, n) {
188
+ return e === n || e !== e && n !== n;
189
+ }
190
+
191
+ /** The container node's arrangement guess: the rows (or keys) the setter
192
+ * left the container with, in order. Its comparator judges a landing or a
193
+ * revert against it by row identity — by key when the family has one
194
+ * (the server's object for a guessed row is the same row). */ class LaneView {
195
+ rows;
196
+ base;
197
+ removed;
198
+ constructor(e,
199
+ /** The backing the guess is shown over: the committed one at the
200
+ * guess, the composed arrangement after a re-base (optimistic.ts). */
201
+ n,
202
+ /** Keys the setter REMOVED from the view it saw (a deliberate delete,
203
+ * not a row the truth has yet to show): a re-base does not restore
204
+ * them. `null` when none. */
205
+ t = null) {
206
+ this.rows = e;
207
+ this.base = n;
208
+ this.removed = t;
209
+ }
210
+ }
211
+
212
+ /** A container node's value as a backing: the base an arrangement guess is
213
+ * shown over, else the value itself. */ function asBacking(e) {
214
+ return e instanceof LaneView ? e.base : e;
215
+ }
216
+
217
+ /** The container node's comparator: a staging is a backing (identity — a
218
+ * pending backing is never "equal" to the committed one); a lane value is
219
+ * an arrangement (`LaneView`), judged by the optimistic machinery. */ const containerEquals = function(e, n) {
220
+ return e === n || optHooks !== null && optHooks.arrangement(this.yt, e, n);
221
+ };
222
+
223
+ function sameLogicalSlot(e, n, t) {
224
+ if (n === null || typeof n !== "object" || t === null || typeof t !== "object") return false;
225
+ const r = lookupTarget(n, e.fam);
226
+ return r !== undefined && r === lookupTarget(t, e.fam);
227
+ }
228
+
229
+ /** Slot nodes whose last subscriber left while they still held a staging:
230
+ * released at the commit that resolves it (`drainFolds`). */ const deferredReleases = new Set;
231
+
232
+ function releaseSlot(e) {
233
+ const n = e.yt;
234
+ const t = e.bt;
235
+ if (t === $TRACK) {
236
+ if (n.k === e) n.k = null;
237
+ } else if (t === $DEEP) {
238
+ if (n.dk === e) n.dk = null;
239
+ } else if (n.n !== null && n.n[t] === e) {
240
+ delete n.n[t];
241
+ n.nc--;
242
+ } else if (n.h !== null && n.h[t] === e) delete n.h[t];
243
+ // The family's index keeps only targets that still carry a node.
244
+ if (n.fam !== null && n.nc === 0 && n.k === null && n.dk === null && (n.h === null || Reflect.ownKeys(n.h).length === 0)) n.fam.live.delete(n);
245
+ }
246
+
247
+ /** A node was born on `target`: a family target enters the live index. */ function noteNode(e, n, t) {
248
+ if (e.fam !== null) e.fam.live.add(e);
249
+ markDescendants(e);
250
+ if (affectsHooks !== null) affectsHooks.born(e, n, t);
251
+ }
252
+
253
+ // Shared slot-node release handler: registered once; the core sweep
254
+ // dispatches CONFIG_SLOT_NODE nodes here (graph.ts) instead of holding a
255
+ // per-node closure in a per-node NodeExtension. A dropped node is
256
+ // unreachable through the store — a fresh read makes a fresh node.
257
+ setSlotUnobserved(e => {
258
+ // A staged write — or a lane's value (a guess, S4) — is state only the
259
+ // node holds: defer the release to the commit that resolves it.
260
+ if (e.Ae !== NOT_PENDING || e.u & CONFIG_OVERRIDE) deferredReleases.add(e); else releaseSlot(e);
261
+ });
262
+
263
+ /** A node born while its container has a staging is born from the two
264
+ * frames (A29): committed from the committed backing, the staging from the
265
+ * pending one — and held by the container's transaction when the container
266
+ * is held (#3706: the unit of the hold is the key — a key the batch left
267
+ * unchanged stages nothing and holds no one). */ function bornStaged(e, n, t, r) {
268
+ if (n.tn && n.tn(n.pe, t)) return;
269
+ queuePendingNode(n);
270
+ n.Ae = t;
271
+ const o = e.k;
272
+ if (o === null) return;
273
+ // a node-less staging holds nothing (`stageOn`)
274
+ // Held by the container's transaction only for a key the HELD staging
275
+ // changed — a mainline layer's change above it stages mainline. (A
276
+ // container carrying a guess is a lane's: the flush's park decides.)
277
+ if ((o.u & (CONFIG_HELD | CONFIG_OVERRIDE)) === CONFIG_HELD && heldKeyChanged(e, r)) holdNode(n, txOf(o));
278
+ // A28 (4): a batch written inside a creation-time pass is promoted — its
279
+ // late-materialized leaf with it.
280
+ if (o.u & CONFIG_PROMOTED) notePromotedWrite(n);
281
+ }
282
+
283
+ function getNode(e, n,
284
+ // First-read dedupe (create-floor slice 2): the get trap probes
285
+ // accessor-ness right before creating the node — pass the verdict through
286
+ // so creation skips the second descriptor scan. -1 = unknown (other
287
+ // callers), 0/1 = probed.
288
+ t = -1) {
289
+ const r = e.n ??= Object.create(null);
290
+ let o = r[n];
110
291
  if (o === undefined) {
111
- o = Object.prototype.toString.call(e) === "[object Object]" && (
112
- // Dynamic Node check (kept dynamic so test/SSR overrides of
113
- // `globalThis.Node` are observed at call time): shimmed DOMs implement
114
- // nodes as plain user classes, which pass the tag check.
115
- typeof Node === "undefined" || !(e instanceof Node));
116
- wrappableProtos.set(t, o);
292
+ // Accessor-ness resolved ONCE per node (no per-object descriptor scan
293
+ // on reads): accessor keys serve through Reflect.get with the proxy
294
+ // receiver.
295
+ const i = e.pb;
296
+ const l = o = slotSignal(committed(e)[n], slotNodeEquals, e, n, t === -1 ? isOwnAccessor(i ?? e.v, n) : t === 1);
297
+ if (i !== null && !l.acc) bornStaged(e, l, e.del !== null && e.del.has(n) ? undefined : i[n], n);
298
+ // Attribution-only: name store property nodes by path segment so
299
+ // attribution chains and wide-scope warnings read "store.todos" (or
300
+ // "todos.title" when the store was declared with a name), not
301
+ // "signal". Gated on the engine being installed — node creation is
302
+ // the hottest store path, and the disabled cost must stay one null
303
+ // check (nodes created before enable() stay generically named).
304
+ if (attrHooks !== null) {
305
+ l._name = storeLabel(e) + "." + String(n);
306
+ stampNodeOwner(l, e);
307
+ }
308
+ r[n] = o;
309
+ e.nc++;
310
+ noteNode(e, l, n);
117
311
  }
118
312
  return o;
119
313
  }
120
314
 
121
- let writeOverride = false;
315
+ function getHasNode(e, n) {
316
+ const t = e.h ??= Object.create(null);
317
+ let r = t[n];
318
+ if (r === undefined) {
319
+ const o = r = slotSignal(n in committed(e), isEqual, e, n, false);
320
+ const i = e.pb;
321
+ if (i !== null) bornStaged(e, o, n in i && !(e.del !== null && e.del.has(n)), n);
322
+ if (attrHooks !== null) stampNodeOwner(o, e);
323
+ t[n] = r;
324
+ noteNode(e, o, n);
325
+ }
326
+ return r;
327
+ }
328
+
329
+ /** The container node (plan sec. 31.3): created by the first structural subscription
330
+ * or the first write that needs to stage. Its committed value is the
331
+ * committed backing. */ function getContainerNode(e) {
332
+ let n = e.k;
333
+ if (n === null) {
334
+ n = e.k = slotSignal(e.v, containerEquals, e, $TRACK, false);
335
+ if (attrHooks !== null) stampNodeOwner(n, e);
336
+ noteNode(e, n, $TRACK);
337
+ // Born while a batch is staged without a node (`stageOn`): the node
338
+ // takes the staging as its own — the pre-batch backing committed, the
339
+ // pending backing staged — so whoever asked for it reads the frame it
340
+ // would have read had the node been there from the write.
341
+ if (e.pb !== null && !directCommit) {
342
+ n.pe = preBatch(e);
343
+ n.Ae = e.pb;
344
+ queuePendingNode(n);
345
+ }
346
+ }
347
+ return n;
348
+ }
122
349
 
123
- function setWriteOverride(e) {
124
- writeOverride = e;
350
+ /** Q-A's escape hatch (plan sec. 33; measured plan sec. 41.4): a staging needs the container
351
+ * node as its home only when something can read the frame through it — a
352
+ * structural subscriber (the node exists), lane work (the staging is the
353
+ * lane's), a pass outside a flush (its write is promoted at the pass's end,
354
+ * A28 (4)), or a derive a transaction holds (the staging is the derive's,
355
+ * `holdWithDerive`). Otherwise the backing and the fold queue are the whole
356
+ * staging: nothing allocates, nothing is swept at the commit (dbmon's tick
357
+ * re-created, queued, swept and dropped ~7000 container nodes). If the
358
+ * flush parks, the seam materializes and holds the node then
359
+ * (`_storePark`) — the one case the staging home exists for. */ function stageOn(e, n) {
360
+ if (e.k === null && passLane === null && (context === null || globalQueue.ee) && !deriveHolds(e)) return;
361
+ const t = getContainerNode(e);
362
+ if (t.Ae === NOT_PENDING) queuePendingNode(t);
363
+ t.Ae = n;
364
+ // A28 (4): a write issued inside a pass outside a flush (a creation-time
365
+ // derive) is promoted at the pass's end — the batch with it.
366
+ if (context !== null) notePromotedWrite(t);
367
+ if (e.fam !== null) holdWithDerive(e, t);
125
368
  }
126
369
 
127
- function getWriteOverride() {
128
- return writeOverride;
370
+ /** The projection's derive is held by a transaction and this is its own
371
+ * write (not a user setter's): the staging is the derive's (`holdWithDerive`). */ function deriveHolds(e) {
372
+ const n = e.fam?.node;
373
+ return n != null && !userWrite && (n.u & CONFIG_HELD) !== 0;
129
374
  }
130
375
 
131
- // Own enumerable keys including symbols (`Object.keys` drops symbol-keyed props). #2769
132
- function ownEnumerableKeys(e) {
133
- return Reflect.ownKeys(e).filter(t => Object.prototype.propertyIsEnumerable.call(e, t));
376
+ GlobalQueue.hn = e => {
377
+ for (let n = 0; n < foldList.length; n++) {
378
+ const t = foldList[n];
379
+ if (t.k === null && t.pb !== null) holdNode(getContainerNode(t), e);
380
+ }
381
+ };
382
+
383
+ function getDeepNode(e) {
384
+ let n = e.dk;
385
+ if (n === null) {
386
+ n = e.dk = slotSignal(0, never, e, $DEEP, false);
387
+ if (attrHooks !== null) stampNodeOwner(n, e);
388
+ noteNode(e, n, $DEEP);
389
+ }
390
+ return n;
134
391
  }
135
392
 
136
- /**
137
- * Scope inheritance for late-created nodes: every live mark whose identity
138
- * scope contains the owning record's raw — and, for keyed marks, whose key
139
- * is this property — gets counted on the new node. Inherited marks live
140
- * exactly as long as the scope's carrier — the release hook below drops
141
- * them with the entry.
142
- */ function inheritAffectsMarks(e, t, o) {
143
- // A live scope exists, so affects.ts already installed the mark engine.
144
- for (const [r, s] of affectsScopes) {
145
- if (r.o?.t && s.scope.has(t) && (s.key === undefined || s.key === o)) {
146
- GlobalQueue.M(e);
147
- s.inherited.push(e);
148
- }
393
+ function bumpDeep(e) {
394
+ if (e.dk !== null) setSignal(e.dk, 1);
395
+ }
396
+
397
+ /** The structural readers' one notification: a membership/arrangement
398
+ * change on the container (the staging is already on the node; `setSignal`
399
+ * re-stages the same backing and walks the subscribers — and, on later
400
+ * steps, routes a held or lane-owned container the way any node is). */ function notifyContainer(e, n) {
401
+ // A container carrying an arrangement guess takes the write as a landing
402
+ // on the guess (`laneWrite` → `supersede`, judged by `containerEquals`);
403
+ // otherwise the structural readers are walked (the staging is already on
404
+ // the node; the comparator is the store's, done).
405
+ if (e.u & CONFIG_OVERRIDE) setSignal(e, n); else {
406
+ if (e.u & CONFIG_HELD) joinFuture(txOf(e));
407
+ insertSubs(e);
408
+ schedule();
149
409
  }
150
410
  }
151
411
 
152
- const affectsScopes = new Map;
412
+ // Observe-tier labels and owners (attribution).
413
+ function storeRoot(e) {
414
+ let n = e;
415
+ while (n.u !== null) n = n.u;
416
+ return n;
417
+ }
153
418
 
154
- /** Next-store node factory for affects carriers/slots: injected by the
155
- * rewrite module (next targets alias the legacy field names, so everything
156
- * here EXCEPT node creation works on them structurally). */ let nextAffectsNodeResolver = null;
419
+ function storeRootOwner(e) {
420
+ return storeOwners.get(storeRoot(e));
421
+ }
157
422
 
158
- function setNextAffectsNodeResolver(e) {
159
- nextAffectsNodeResolver = e;
423
+ function stampNodeOwner(e, n) {
424
+ e.H = storeRootOwner(n) ?? null;
160
425
  }
161
426
 
162
- /** Next-store optimistic view for the declaration walk (optimistic rows
163
- * pushed before the declaration are in motion too — legacy reads its write
164
- * overlays; next composes armed-node overrides). */ let nextOptimisticViewResolver = null;
427
+ const storeNames = new WeakMap;
165
428
 
166
- function setNextOptimisticViewResolver(e) {
167
- nextOptimisticViewResolver = e;
429
+ function nameStore(e, n) {
430
+ if (attrHooks !== null && n) storeNames.set(e[$TARGET], n);
168
431
  }
169
432
 
170
- /** @internal birth inheritance for nodes created inside a live mark window —
171
- * exported for the rewrite's node factories. */ function affectsScopesLive() {
172
- return affectsScopes.size > 0;
433
+ function storeLabel(e) {
434
+ return storeNames.get(storeRoot(e)) ?? "store";
173
435
  }
174
436
 
175
- /**
176
- * Snapshots the identities reachable from `value` into `scope`, reading
177
- * through write overlays (an optimistic row pushed before the declaration is
178
- * in motion too). Untracked by construction: walks raw values, never traps.
179
- * Every LIVE node under each reachable record — property leaves, `$TRACK`,
180
- * and has-nodes — collects into `found`: those are the graph edges existing
181
- * readers subscribed through, so the mark registers on them directly and
182
- * rides the status rails to everything derived. (Nodes born later inherit
183
- * from the scope in `getNode`.)
184
- */ function walkAffectsScope(e, t, o, r,
185
- // Cycle guard, fresh per declaration: the scope itself can't serve — a
186
- // re-declaration on the same carrier unions into a scope that already
187
- // holds the root, and must still descend to pick up records added since.
188
- s) {
189
- if (!isWrappable(e)) return;
190
- const f = e[$TARGET] || lookupTarget(e, r);
191
- // Next targets: walk the pending backing when present (a draft's writes are
192
- // in motion too) and cover BOTH identities in the scope.
193
- let n = f ? f.pb ?? f[STORE_VALUE] : e;
194
- if (s.has(n)) return;
195
- s.add(n);
196
- t.scope.add(n);
197
- if (f && f.pb) t.scope.add(f[STORE_VALUE]);
198
- // Next optimistic families: enumerate the VISIBLE view (armed-node
199
- // overrides compose membership/values the raw doesn't carry).
200
- if (f && f.fam?.opt && nextOptimisticViewResolver) n = nextOptimisticViewResolver(f, n);
201
- if (f) {
202
- collectRecordNodes(f[STORE_NODE], o);
203
- collectRecordNodes(f[STORE_HAS], o);
204
- // The key-set and deep-witness nodes are record-level channels: a deep()
205
- // probe reads ONLY these (one pair per record), so a declared affects
206
- // scope must mark them like any property node.
207
- if (f.k) o.push(f.k);
208
- if (f.dk) o.push(f.dk);
209
- // Carry the effective family into untouched descendants (projections/
210
- // optimistic stores register children under their family).
211
- r = f.fam ?? r;
212
- }
213
- // Overlays are gone (next has no layer): raw enumeration; the optimistic
214
- // view composition above already folded armed-node membership/values in.
215
- if (Array.isArray(n)) {
216
- for (let e = 0, f = n.length; e < f; e++) {
217
- walkAffectsScope(n[e], t, o, r, s);
218
- }
219
- const e = Object.getOwnPropertySymbols(n);
220
- for (let f = 0, c = e.length; f < c; f++) {
221
- if (e[f] === $OWNER) continue;
222
- const c = Object.getOwnPropertyDescriptor(n, e[f]);
223
- if (!c || c.get) continue;
224
- walkAffectsScope(c.value, t, o, r, s);
437
+ // ---------------------------------------------------------------------------
438
+ // clones (CoW privatization)
439
+ const hasOwn = Object.prototype.hasOwnProperty;
440
+
441
+ const lookupGetter = Object.prototype.__lookupGetter__;
442
+
443
+ const lookupSetter = Object.prototype.__lookupSetter__;
444
+
445
+ const propertyIsEnumerable = Object.prototype.propertyIsEnumerable;
446
+
447
+ function isOwnAccessor(e, n) {
448
+ return hasOwn.call(e, n) && (lookupGetter.call(e, n) !== undefined || lookupSetter.call(e, n) !== undefined);
449
+ }
450
+
451
+ /** Shallow clone into store ownership. Plain data (grade 2) spreads; anything
452
+ * else copies descriptors (accessors kept, everything made configurable). */ function cloneRaw(e, n) {
453
+ n.sc || scanAccessorsOnce(n);
454
+ if (n.sc === 2) {
455
+ const t = {
456
+ ...e
457
+ };
458
+ t[$OWNER] = n;
459
+ return t;
460
+ }
461
+ const t = Object.getOwnPropertyDescriptors(e);
462
+ for (const r of Reflect.ownKeys(t)) {
463
+ const o = t[r];
464
+ if (r === "length" && Array.isArray(e)) continue;
465
+ o.configurable = true;
466
+ if (!o.get && !o.set) o.writable = true; else n.a = true;
467
+ }
468
+ const r = Array.isArray(e) ? Object.defineProperties([], t) : Object.create(Object.getPrototypeOf(e), t);
469
+ r[$OWNER] = n;
470
+ return r;
471
+ }
472
+
473
+ /** Wide plain clone (many keys): null-prototype build, then reset. */ function wideClone(e, n) {
474
+ const t = Object.create(null);
475
+ for (const n of Reflect.ownKeys(e)) t[n] = e[n];
476
+ Object.setPrototypeOf(t, Object.prototype);
477
+ t[$OWNER] = n;
478
+ return t;
479
+ }
480
+
481
+ function copyOwn(e, n, t) {
482
+ const r = Object.getOwnPropertyDescriptor(n, t);
483
+ if (r.get || r.set || !r.enumerable || !r.writable || !r.configurable) Object.defineProperty(e, t, r); else e[t] = r.value;
484
+ }
485
+
486
+ /** One descriptor scan per container (grade 1/2, `a`, `kc`). */ function scanAccessorsOnce(e) {
487
+ const n = e.v;
488
+ const t = Reflect.ownKeys(n);
489
+ let r = Object.getPrototypeOf(n) === Object.prototype;
490
+ for (const o of t) {
491
+ if (lookupGetter.call(n, o) !== undefined || lookupSetter.call(n, o) !== undefined) {
492
+ e.a = true;
493
+ r = false;
494
+ break;
225
495
  }
496
+ if (r && !propertyIsEnumerable.call(n, o)) r = false;
497
+ }
498
+ e.sc = r ? 2 : 1;
499
+ e.kc = t.length;
500
+ return !e.a;
501
+ }
502
+
503
+ // ---------------------------------------------------------------------------
504
+ // the pending backing
505
+ const OVERLAY_MIN_KEYS = 32;
506
+
507
+ const OVERLAY_REBUILD_MAX_KEYS = 1024;
508
+
509
+ const OVERLAY_REBUILD_MIN_ADDS = 16;
510
+
511
+ const WK_ALL = new Set;
512
+
513
+ const plainProto = e => {
514
+ const n = Object.getPrototypeOf(e);
515
+ return n === Object.prototype || n === Array.prototype || n === null;
516
+ };
517
+
518
+ /** An overlay with many adds (or any delete) rebuilds the committed
519
+ * container at flatten so its shape stays fast (#3689). */ function overlayRebuilds(e, n) {
520
+ if (e.kc > OVERLAY_REBUILD_MAX_KEYS) return false;
521
+ if (e.del !== null && e.del.size !== 0) return true;
522
+ const t = e.wk;
523
+ if (t !== null && t !== WK_ALL && t.size <= OVERLAY_REBUILD_MIN_ADDS) return false;
524
+ const r = e.v;
525
+ let o = 0;
526
+ for (const e of Reflect.ownKeys(n)) if (!hasOwn.call(r, e) && ++o > OVERLAY_REBUILD_MIN_ADDS) return true;
527
+ return false;
528
+ }
529
+
530
+ /** Downgrade an overlay to a real clone (a consumer needs a container). */ function materializePB(e) {
531
+ const n = e.pb;
532
+ if (!e.ovl) return n;
533
+ const t = e.sc === 2 ? wideClone(e.v, e) : cloneRaw(e.v, e);
534
+ if (e.del !== null) {
535
+ for (const n of e.del) delete t[n];
536
+ e.kc -= e.del.size;
537
+ e.del = null;
538
+ }
539
+ for (const r of Reflect.ownKeys(n)) e.sc === 2 ? t[r] = n[r] : copyOwn(t, n, r);
540
+ e.pb = t;
541
+ e.ovl = false;
542
+ // The staging IS the pending backing: re-point the container node.
543
+ if (e.k !== null && e.k.Ae === n) e.k.Ae = t;
544
+ return t;
545
+ }
546
+
547
+ /** The batch's pending backing, created on the first draft write: an overlay
548
+ * of an owned plain-data record above the key threshold, a clone otherwise.
549
+ * Staged on the container node (the scheduler owns its lifetime) and queued
550
+ * for the fold at the flush's commit. */ function ensurePB(e) {
551
+ let n = e.pb;
552
+ // An optimistic edit composes on the view the user saw and becomes
553
+ // guesses at the setter's exit: nothing is staged, nothing folds
554
+ // (optimistic.ts).
555
+ if (userWrite && e.fam?.opt === true && !pendingNotify.has(e)) return e.pb = optHooks.draft(e);
556
+ if (n !== null && !isOwned(n)) {
557
+ // An adopted object awaiting its fold is the user's: the draft writes a
558
+ // clone of it. The clone is the batch's staging — unless the adoption is
559
+ // HELD (another transaction's): then the held staging stays the
560
+ // adoption and the draft is a mainline layer above it (#3612/#3688: a
561
+ // mainline setter mid-hold publishes mainline; the held keys stay held).
562
+ n = e.pb = cloneRaw(n, e);
563
+ const t = e.k;
564
+ if (t !== null && !(t.u & CONFIG_HELD)) t.Ae = n;
565
+ } else if (n === null) {
566
+ const t = e.v;
567
+ if (!directCommit) queueFold(e);
568
+ if (!e.ch && !Array.isArray(t) && (e.sc !== 0 ? !e.a : scanAccessorsOnce(e)) && e.kc > OVERLAY_MIN_KEYS && isOwned(t)) {
569
+ n = e.pb = Object.create(t);
570
+ e.ovl = true;
571
+ } else n = e.pb = cloneRaw(t, e);
572
+ if (!directCommit) stageOn(e, n);
573
+ }
574
+ return n;
575
+ }
576
+
577
+ /** Privatize `target`'s committed backing (and its ancestor chain — a shared
578
+ * parent cannot point at an owned child). Not a reactive event. */ function privatizeCommitted(e) {
579
+ if (isOwned(e.v)) return;
580
+ const n = e.v;
581
+ const t = cloneRaw(n, e);
582
+ // Mid-batch (a staging is open on this target) the fold still sees the
583
+ // backing the batch started from: the queue recorded it (`foldOlds`).
584
+ e.v = t;
585
+ e.ch = false;
586
+ if (e.u) {
587
+ privatizeCommitted(e.u);
588
+ devAssertNeverUserMutation(e.u.v);
589
+ const t = e.u.v;
590
+ const r = parentSlotKey(e, n);
591
+ if (t[r] === n) t[r] = e.v;
592
+ }
593
+ }
594
+
595
+ /** The key this target sits under in its parent — re-resolved by identity
596
+ * when an array parent moved it (#3282). Not searched when the slot already
597
+ * holds this target's backing (a parent adopted whole carries its children's
598
+ * new raws before the children fold — the miss was O(rows) per changed row
599
+ * of a keyed reconcile). */ function parentSlotKey(e, n) {
600
+ const t = e.pk;
601
+ const r = e.u.v;
602
+ if (r[t] === n || r[t] === e.v || !Array.isArray(r)) return t;
603
+ const o = r.indexOf(n);
604
+ if (o === -1) return t;
605
+ e.pk = o;
606
+ return o;
607
+ }
608
+
609
+ /** Overlay flatten (#3044): own keys onto the owned committed backing in
610
+ * place — the backing keeps its identity. */ function flattenOverlay(e, n) {
611
+ privatizeCommitted(e);
612
+ const t = e.v;
613
+ for (const r of Reflect.ownKeys(n)) e.sc === 2 ? t[r] = n[r] : copyOwn(t, n, r);
614
+ if (e.del !== null) {
615
+ for (const n of e.del) delete t[n];
616
+ e.kc -= e.del.size;
617
+ e.del = null;
618
+ }
619
+ e.pb = null;
620
+ e.ovl = false;
621
+ e.wk = null;
622
+ // written-keys window closes with the commit
623
+ }
624
+
625
+ /** Adoption (a setter's returned replacement; reconcile and projection
626
+ * landings in S3): the incoming object becomes the backing by reference at
627
+ * the fold — no clones, no user-object mutation, ownership resets to
628
+ * shared. It is the container's staging until then (signal parity: a
629
+ * handler reads the committed frame until the flush; a hold keeps it
630
+ * staged with the rest). The nodes are told now, diffed against the view
631
+ * they were LAST told (#3296): the draft's pending backing when one
632
+ * preceded the adoption this batch — its node writes were real, and the
633
+ * adoption's re-stage cancels or confirms each — else the committed
634
+ * backing. */ function adoptPB(e, n, t = true) {
635
+ if (!directCommit) queueFold(e);
636
+ let r;
637
+ if (e.pb !== null) {
638
+ if (e.ovl) materializePB(e);
639
+ r = e.pb;
640
+ } else r = e.v;
641
+ if (directCommit) {
642
+ e.pb = null;
643
+ if (e.k !== null) e.k.pe = n;
226
644
  } else {
227
- const e = Reflect.ownKeys(n);
228
- for (let f = 0, c = e.length; f < c; f++) {
229
- if (e[f] === $OWNER) continue;
230
- const c = Object.getOwnPropertyDescriptor(n, e[f]);
231
- if (!c || c.get) continue;
232
- walkAffectsScope(c.value, t, o, r, s);
645
+ // Eager (INTERNALS §3): the backing swaps now — handlers read the
646
+ // adopted object before the flush — while the container node, when
647
+ // there is one (`stageOn`), keeps the committed frame (`_value`) for
648
+ // readers a hold keeps on it, and stages the adoption for the fold's
649
+ // path copy.
650
+ e.pb = n;
651
+ stageOn(e, n);
652
+ }
653
+ e.v = n;
654
+ e.ch = n[$TARGET] !== undefined;
655
+ e.ovl = false;
656
+ e.del = null;
657
+ e.sc = 0;
658
+ e.a = false;
659
+ e.wk = null;
660
+ // adoption supersedes staged trap writes
661
+ const o = n[$OWNER];
662
+ if (o !== undefined && o.fam === e.fam) n[$OWNER] = e; else setLookup(n, e);
663
+ if (t && r !== n) notifyFold(e, r, n);
664
+ }
665
+
666
+ // ---------------------------------------------------------------------------
667
+ // the fold: owned raw's one mutation point, at the flush's commit
668
+ /** The fold queue: the targets with a batch open (`pb !== null` IS the
669
+ * membership — a target is queued exactly while it carries a staging; the
670
+ * drain skips one already folded), in two reusable arrays. Nothing here
671
+ * allocates per batch once warm: a dbmon tick queues ~7000 containers, and
672
+ * a map built and drained per tick cost ~540 KB of table allocation — most
673
+ * of the tick's young-generation GC, and the whole of its gap to `next`
674
+ * (plan sec. 41.5).
675
+ *
676
+ * Beside each target, its PRE-BATCH committed backing — `t.v` as the batch
677
+ * opened on it (`foldOlds`, parallel to `foldList`). That one record is the
678
+ * fold's base in every case: a draft's backing does not move until the fold
679
+ * (so the record is `t.v` still), an adoption swaps it eagerly (the record
680
+ * is the frame committed readers keep), a mid-batch privatization or a
681
+ * draft over an adopted raw moves it again (the record is what the batch
682
+ * started from, which is all the fold wants to know). The record lives
683
+ * exactly as long as the batch: a weak map keyed by target kept every
684
+ * container's LAST adopted-away backing alive until its next adoption —
685
+ * for a keyed reconcile, the whole previous tree promoted out of the
686
+ * nursery every tick (the saturated listened-paths shape ran 15–25% over
687
+ * the fork, all of it this; plan sec. 43.2) — and for a store adopted
688
+ * once, for its lifetime.
689
+ *
690
+ * The target carries no slot for its record (ARRAY SHAPE RULE, target.ts),
691
+ * so a lookup by target (`preBatch`: a container node born onto an open
692
+ * staging, a committed-frame read of a node-less staging, a park) indexes
693
+ * the list through a map built on first use per batch — the drain itself
694
+ * walks the two lists in step and never builds it. */ let foldList = [];
695
+
696
+ let foldOlds = [];
697
+
698
+ let foldSpare = [];
699
+
700
+ let foldOldsSpare = [];
701
+
702
+ let foldIndex = null;
703
+
704
+ /** Before the staging is set and before an adoption swaps the backing. */ function queueFold(e) {
705
+ if (e.pb !== null) return;
706
+ schedule();
707
+ if (foldIndex !== null) foldIndex.set(e, foldList.length);
708
+ foldList.push(e);
709
+ foldOlds.push(e.v);
710
+ }
711
+
712
+ /** The committed backing before this batch (valid while `pb !== null`). */ function preBatch(e) {
713
+ if (foldIndex === null) {
714
+ foldIndex = new Map;
715
+ for (let e = 0; e < foldList.length; e++) foldIndex.set(foldList[e], e);
716
+ }
717
+ const n = foldIndex.get(e);
718
+ return n === undefined ? e.v : foldOlds[n];
719
+ }
720
+
721
+ /** The flush committed its pending nodes: fold every pending backing whose
722
+ * container node committed (its staging is gone — `_value` is the backing
723
+ * now) into the committed home; one a later step holds (its node still
724
+ * staged) waits for the flush that commits it. Then the deferred slot
725
+ * releases. */ function drainFolds() {
726
+ if (foldList.length !== 0) {
727
+ const e = foldList;
728
+ const n = foldOlds;
729
+ foldList = foldSpare;
730
+ foldOlds = foldOldsSpare;
731
+ foldSpare = e;
732
+ foldOldsSpare = n;
733
+ foldIndex = null;
734
+ for (let t = 0; t < e.length; t++) {
735
+ const r = e[t];
736
+ if (r.pb === null) continue;
737
+ // folded already (a direct commit)
738
+ const o = r.k;
739
+ if (o !== null && o.Ae !== NOT_PENDING) {
740
+ // held: commits with its hold
741
+ foldList.push(r);
742
+ foldOlds.push(n[t]);
743
+ } else foldTarget(r, n[t]);
744
+ }
745
+ e.length = 0;
746
+ n.length = 0;
747
+ }
748
+ if (deferredReleases.size !== 0) {
749
+ for (const e of deferredReleases) {
750
+ if (e.Ae === NOT_PENDING && !(e.u & CONFIG_OVERRIDE) && e.t === null) {
751
+ deferredReleases.delete(e);
752
+ releaseSlot(e);
753
+ }
233
754
  }
234
755
  }
235
756
  }
236
757
 
237
- /** All live signal nodes of one record's node map (string + symbol keyed). */ function collectRecordNodes(e, t) {
238
- if (!e) return;
239
- for (const o of Object.keys(e)) t.push(e[o]);
240
- const o = Object.getOwnPropertySymbols(e);
241
- for (let r = 0, s = o.length; r < s; r++) {
242
- // Another mark's carrier is its own channel — counting it here would
243
- // extend that sibling scope's lifetime to this declaration's.
244
- if (o[r] !== $AFFECTS) t.push(e[o[r]]);
758
+ /** Core asks: is a slot node's truth in flight? Its family's derive is —
759
+ * lanes (A17, #2864: a guess mid-refetch stands in for the flight) and
760
+ * marks (an ambient `affects()` over a declared reload lives to the
761
+ * landing) read it. */ GlobalQueue.F = e => {
762
+ const n = e.yt?.fam;
763
+ return n != null && n.node !== null && (n.node.G & STATUS_PENDING) !== 0;
764
+ };
765
+
766
+ /** Core asks (lanes.ts `covered`): the value a slot node's guess covered.
767
+ * A chained link's committed value is the inner store's at the last
768
+ * read-through — refreshed here, since a guess served the reads since
769
+ * (#3672: the revert compares against the base's live value). */ GlobalQueue.Nn = e => {
770
+ const n = e.yt;
771
+ if (n.ch) {
772
+ const t = e.bt;
773
+ const r = n.v;
774
+ if (n.h !== null && n.h[t] === e) e.pe = untrack(() => t in r); else if (n.n !== null && n.n[t] === e) e.pe = untrack(() => unwrapValue(r[t]));
775
+ }
776
+ return e.pe;
777
+ };
778
+
779
+ GlobalQueue.Sn = () => {
780
+ drainFolds();
781
+ optHooks?.sweep();
782
+ };
783
+
784
+ /** A projection's creation run commits directly (a memo's first value is
785
+ * its `_value`, not a staging): the draft still writes a clone of the seed,
786
+ * nothing is staged on the nodes, and the setter's exit folds the touched
787
+ * containers at once. Only the synchronous first run. */ let directCommit = false;
788
+
789
+ function runDirect(e) {
790
+ const n = directCommit;
791
+ directCommit = true;
792
+ try {
793
+ e();
794
+ } finally {
795
+ directCommit = n;
245
796
  }
246
797
  }
247
798
 
248
- /**
249
- * Witness live mark coverage of a record into the active isPending() probe.
250
- * Tracked reads don't need this — they go through real signal nodes, which
251
- * carry marks directly (declaration walk or birth inheritance). This covers
252
- * UNTRACKED probes reading through records whose nodes never materialized
253
- * (no observer ever subscribed, so no node exists to carry the mark).
254
- * Callers guard on `pendingCheckActive`, so plain reads never pay for this.
255
- *
256
- * @internal
257
- */ function witnessAffectsMark(e, t) {
258
- // Callers guard on `pendingCheckActive`, which only flips inside
259
- // isPending() — the verdict layer is loaded and its hook installed.
260
- const o = e[STORE_NODE]?.[$AFFECTS];
261
- if (o?.o?.t) GlobalQueue.ri(o);
262
- if (affectsScopes.size) {
263
- // Chained backings (§7b): a wrapper's STORE_VALUE can be another store's
264
- // proxy — marks cover by identity of the BASE raw, so resolve the chain
265
- // and check every identity along it.
266
- let r = e[STORE_VALUE];
267
- for (const [e, s] of affectsScopes) {
268
- if (e !== o && e.o?.t && (s.key === undefined || s.key === t)) {
269
- let t = r;
270
- for (;;) {
271
- if (s.scope.has(t)) {
272
- GlobalQueue.ri(e);
799
+ /** Fold one target's pending backing into its committed home. */ function foldTarget(e, n) {
800
+ {
801
+ {
802
+ const t = e.k;
803
+ const r = e.pb;
804
+ if (r !== null) {
805
+ if (r === e.v) {
806
+ // An eager adoption nothing wrote after: the backing is already
807
+ // the adopted object (shared ownership — never cloned).
808
+ e.pb = null;
809
+ e.wk = null;
810
+ } else if (e.ovl && (e.v !== n || !overlayRebuilds(e, r))) {
811
+ // Overlay flatten (#3044): the backing keeps its identity, so the
812
+ // `t.v === old` gate below skips path copying (the parent slot
813
+ // already points here) and the adopted-notify (setter
814
+ // notifications happened at write time). A backing privatized
815
+ // mid-batch is a fresh clone the parent already points at.
816
+ flattenOverlay(e, r);
817
+ } else if (e.v !== n) {
818
+ // Privatized mid-batch (a child's path copy repointed us): the
819
+ // owned backing takes the written keys.
820
+ privatizeCommitted(e);
821
+ const t = e.v;
822
+ const o = e.wk;
823
+ if (o !== null && o !== WK_ALL) {
824
+ for (const e of o) {
825
+ if (hasOwn.call(r, e)) copyOwn(t, r, e); else delete t[e];
826
+ }
827
+ } else {
828
+ for (const e of Reflect.ownKeys(r)) {
829
+ const o = Object.getOwnPropertyDescriptor(r, e);
830
+ if (o.get || o.set || !o.enumerable || !o.writable || !o.configurable) Object.defineProperty(t, e, o); else if (o.value !== n[e] || !hasOwn.call(n, e)) t[e] = o.value;
831
+ }
832
+ for (const e of Reflect.ownKeys(n)) {
833
+ if (!hasOwn.call(r, e)) delete t[e];
834
+ }
835
+ }
836
+ e.pb = null;
837
+ e.wk = null;
838
+ } else {
839
+ // The clone (or adopted object) becomes the committed backing
840
+ // (path copy below).
841
+ e.v = e.ovl ? materializePB(e) : r;
842
+ e.ch = e.v[$TARGET] !== undefined;
843
+ e.pb = null;
844
+ e.wk = null;
845
+ }
846
+ }
847
+ if (t !== null) {
848
+ // The node's committed value is the backing. A container nobody
849
+ // subscribes to was a transient staging home (INTERNALS §5: an
850
+ // observer-less write holds a transient record until the fold,
851
+ // discarded with it) — gone with the batch.
852
+ if (t.t === null) e.k = null; else if (t.pe instanceof LaneView) t.pe.base = e.v; else t.pe = e.v;
853
+ }
854
+ if (e.v !== n && e.u) {
855
+ const t = parentSlotKey(e, n);
856
+ if (e.u.v[t] === n) {
857
+ privatizeCommitted(e.u);
858
+ devAssertNeverUserMutation(e.u.v);
859
+ e.u.v[t] = e.v;
860
+ }
861
+ }
862
+ }
863
+ }
864
+ }
865
+
866
+ // ---------------------------------------------------------------------------
867
+ // write-time notification (setter exit)
868
+ /** Devtools and attribution: the containers a setter replaced wholesale. */ function storePathOf(e) {
869
+ let n = "";
870
+ for (let t = e; t !== null; t = t.u) n = t.pk === null ? "store" + n : "." + String(t.pk) + n;
871
+ return n;
872
+ }
873
+
874
+ const REPLACED_CENSUS_MAX = 64;
875
+
876
+ function sameLeaf(e, n) {
877
+ if (e === n) return true;
878
+ if (e === null || n === null || typeof e !== "object" || typeof n !== "object") return false;
879
+ return unwrapValue(e) === unwrapValue(n) || targetsEqual(e, n);
880
+ }
881
+
882
+ function reportReplacedContainers(e, n, t, r) {
883
+ const o = r ?? Reflect.ownKeys(t);
884
+ const i = Array.isArray(t);
885
+ const l = storeRootOwner(e);
886
+ for (const r of o) {
887
+ if (i && r === "length" || r === $OWNER) continue;
888
+ if (e.del !== null && e.del.has(r)) continue;
889
+ const o = unwrapValue(n[r]);
890
+ const u = unwrapValue(t[r]);
891
+ if (o === null || u === null || typeof o !== "object" || typeof u !== "object" || o === u || targetsEqual(o, u)) continue;
892
+ const f = Array.isArray(u);
893
+ if (f !== Array.isArray(o)) continue;
894
+ let s;
895
+ let a = 0;
896
+ if (f) {
897
+ s = u.length;
898
+ if (s > REPLACED_CENSUS_MAX) continue;
899
+ const e = new Set;
900
+ for (const n of o) e.add(unwrapValue(n));
901
+ for (const n of u) if (e.has(unwrapValue(n))) a++;
902
+ } else {
903
+ const e = Object.keys(u);
904
+ s = e.length;
905
+ if (s > REPLACED_CENSUS_MAX) continue;
906
+ for (const n of e) if (sameLeaf(o[n], u[n])) a++;
907
+ }
908
+ attrHooks.storeReplaced(storePathOf(e) + "." + String(r), f, s, a, f ? o.length : Object.keys(o).length, l);
909
+ }
910
+ }
911
+
912
+ /** A user setter wrote a key whose staging is a derivation another
913
+ * transaction holds (A34 (3), #3612): the hold re-derives over the write. */ let heldDerivationHit = false;
914
+
915
+ /** The open setter is a USER'S (`storeSetter(…, guard = true)`), not the
916
+ * derive's draft or landing. */ let userWrite = false;
917
+
918
+ /** Is the open setter a user's? (reconcile.ts: a user's reconcile on an
919
+ * optimistic family writes the draft.) */ function userWriting() {
920
+ return userWrite;
921
+ }
922
+
923
+ function heldDerivation(e, n, t) {
924
+ if (e.fam === null || !userWrite) return false;
925
+ if (n !== undefined) return (n.u & (CONFIG_HELD | CONFIG_MANUAL_WRITE)) === CONFIG_HELD && txOf(n) !== flushTransaction;
926
+ const r = e.k;
927
+ return r !== null && (r.u & CONFIG_HELD) !== 0 && txOf(r) !== flushTransaction && heldKeyChanged(e, t);
928
+ }
929
+
930
+ /** Setter exit: one node write per changed observed key (the leaves stage
931
+ * like signals — holds and lanes engage here on later steps), presence and
932
+ * deep witnesses, and the container when membership changed. */ function notifyWrites(e) {
933
+ let n = e.pb;
934
+ if (n === null) return;
935
+ // Optimistic channel: a user's writes on an optimistic family become
936
+ // guesses on the nodes (lanes); the draft is discarded, the committed
937
+ // backing never touched.
938
+ if (userWrite && e.fam?.opt === true) {
939
+ // The draft is discarded first: the diff reads the target (its nodes
940
+ // are born from the committed frame, not the draft).
941
+ e.pb = null;
942
+ e.wk = null;
943
+ e.pb = optHooks.writes(e, n);
944
+ return;
945
+ }
946
+ const t = e.v;
947
+ const r = e.n;
948
+ // Written-keys bound: trap writes record their keys, so the notify visits
949
+ // O(written) nodes instead of every subscription on the record (a selection
950
+ // map with thousands of per-key subscribers pays two visits per select,
951
+ // not a full scan). Falls back to the full node scan when the bound can't
952
+ // hold: no trap granularity (wk null), an array length write (WK_ALL —
953
+ // implicit index deletes), accessors on the record (t.a — a getter node's
954
+ // value can change when ANY key is written), or a non-plain prototype
955
+ // (class instances: prototype getters derive from arbitrary fields).
956
+ // Overlay pbs chain to the COMMITTED object (#3044) — plainness is the
957
+ // committed container's prototype, not the overlay's.
958
+ const o = e.wk;
959
+ const i = o === WK_ALL || e.a === true || !plainProto(e.ovl ? e.v : n) ? null : o;
960
+ if (attrHooks !== null) reportReplacedContainers(e, t, n, i);
961
+ if (e.fam !== null && !heldDerivationHit && i !== null) for (const n of i) if (heldDerivation(e, r?.[n], n)) {
962
+ heldDerivationHit = true;
963
+ break;
964
+ }
965
+ if (r !== null) {
966
+ const o = i ?? Reflect.ownKeys(r);
967
+ for (const i of o) {
968
+ const o = r[i];
969
+ if (o === undefined) continue;
970
+ if (o.acc === true || hasOwn.call(n, i) && lookupGetter.call(n, i) !== undefined) {
971
+ // Accessor keys: the node is linked for shape-change notification,
972
+ // its value is never served (the getter runs with the proxy
973
+ // receiver on read) — FORCE wakes the readers.
974
+ o.acc = isOwnAccessor(n, i);
975
+ const e = Object.getOwnPropertyDescriptor(t, i);
976
+ const r = Object.getOwnPropertyDescriptor(n, i);
977
+ if (e && (e.get || e.set) || r && (r.get || r.set)) {
978
+ if (e?.get !== r?.get || e?.set !== r?.set || e?.value !== r?.value) setSignal(o, () => FORCE);
979
+ continue;
980
+ }
981
+ if (!isEqual(e?.value, r?.value)) setSignal(o, () => r?.value);
982
+ continue;
983
+ }
984
+ const l = e.del !== null && e.del.has(i) ? undefined : n[i];
985
+ setSignal(o, () => l);
986
+ if (e.fam !== null) {
987
+ // The derive's write is a derivation; a user setter's is a proposal
988
+ // (A34 (3)'s discriminator).
989
+ if (!userWrite) {
990
+ o.u &= ~CONFIG_MANUAL_WRITE;
991
+ holdWithDerive(e, o);
992
+ } else o.u |= CONFIG_MANUAL_WRITE;
993
+ }
994
+ }
995
+ }
996
+ const l = e.h;
997
+ if (l !== null) {
998
+ const t = i ?? Reflect.ownKeys(l);
999
+ for (const r of t) {
1000
+ const t = l[r];
1001
+ if (t !== undefined) {
1002
+ setSignal(t, r in n && !(e.del !== null && e.del.has(r)));
1003
+ if (e.fam !== null) holdWithDerive(e, t);
1004
+ }
1005
+ }
1006
+ }
1007
+ if (e.dk !== null) {
1008
+ if (e.del !== null && e.del.size !== 0) bumpDeep(e); else for (const r of i ?? Reflect.ownKeys(n)) {
1009
+ if (r === $OWNER) continue;
1010
+ const o = n[r];
1011
+ const i = t[r];
1012
+ if (o !== null && typeof o === "object" ? !targetsEqual(i, o) : !isEqual(i, o)) {
1013
+ bumpDeep(e);
1014
+ break;
1015
+ }
1016
+ }
1017
+ }
1018
+ // The container: structural readers hear membership/arrangement changes
1019
+ // only (R9) — the compare is the store's, against the committed frame. A
1020
+ // container carrying an arrangement guess is told whether or not anyone
1021
+ // subscribes: the write is a landing on the guess (`notifyContainer`).
1022
+ const u = e.k;
1023
+ if (u !== null && (u.t !== null || u.u & CONFIG_OVERRIDE)) {
1024
+ let r;
1025
+ if (e.ovl) {
1026
+ r = e.del !== null && e.del.size !== 0;
1027
+ if (!r) {
1028
+ for (const e of Reflect.ownKeys(n)) {
1029
+ if (!hasOwn.call(t, e)) {
1030
+ r = true;
273
1031
  break;
274
1032
  }
275
- const o = t?.[$TARGET];
276
- if (o === undefined) break;
277
- const r = o.pb ?? o[STORE_VALUE];
278
- if (r === t) break;
279
- t = r;
280
1033
  }
281
1034
  }
1035
+ } else {
1036
+ r = Array.isArray(n) && Array.isArray(t) ? arrayStructureChanged(t, n) : membershipChanged(t, n);
282
1037
  }
1038
+ if (r) notifyContainer(u, n);
283
1039
  }
284
1040
  }
285
1041
 
286
- /**
287
- * Resolves the store nodes an `affects()` declaration marks: with a `key`,
288
- * the named slot's leaf node (upserted so the mark has an addressable
289
- * carrier); without, the record's $AFFECTS carrier plus every LIVE node in
290
- * its subtree (the edges existing readers subscribed through), with the
291
- * subtree's identities snapshotted into the mark's scope so nodes created
292
- * during the window — and untracked probes over captured proxies — resolve
293
- * against it (#2882).
1042
+ /** Accessor-node wake sentinel: readers re-run and re-invoke the getter. */ const FORCE = Symbol();
1043
+
1044
+ /** Two raws that wrap to the same target are the same logical value. */ function targetsEqual(e, n) {
1045
+ if (e === null || typeof e !== "object" || n === null || typeof n !== "object") return false;
1046
+ const t = lookupTarget(e, null);
1047
+ return t !== undefined && t === lookupTarget(n, null);
1048
+ }
1049
+
1050
+ /** Positional identity IS content for arrays (R15). */ function arrayStructureChanged(e, n) {
1051
+ if (e.length !== n.length) return true;
1052
+ for (let t = 0; t < n.length; t++) {
1053
+ const r = e[t];
1054
+ const o = n[t];
1055
+ if (!isEqual(r, o) && !targetsEqual(r, o)) return true;
1056
+ }
1057
+ return false;
1058
+ }
1059
+
1060
+ function membershipChanged(e, n) {
1061
+ const t = Reflect.ownKeys(n);
1062
+ if (Reflect.ownKeys(e).length - +isOwned(e) !== t.length - +isOwned(n)) return true;
1063
+ for (const n of t) if (n !== $OWNER && !(n in e)) return true;
1064
+ return false;
1065
+ }
1066
+
1067
+ /** One leaf's notification for an adoption diff (descriptor-aware). */ function notifyKeyDiff(e, n, t, r, o = true) {
1068
+ if (e.acc === true || o && hasOwn.call(r, n) && lookupGetter.call(r, n) !== undefined) {
1069
+ e.acc = isOwnAccessor(r, n);
1070
+ const o = Object.getOwnPropertyDescriptor(t, n);
1071
+ const i = Object.getOwnPropertyDescriptor(r, n);
1072
+ if (o && (o.get || o.set) || i && (i.get || i.set)) {
1073
+ if (o?.get !== i?.get || o?.set !== i?.set || o?.value !== i?.value) setSignal(e, () => FORCE);
1074
+ return;
1075
+ }
1076
+ const l = o?.value;
1077
+ const u = i?.value;
1078
+ if (!isEqual(l, u) && !targetsEqual(l, u)) setSignal(e, typeof u === "function" ? () => u : u);
1079
+ } else {
1080
+ const o = t[n];
1081
+ const i = r[n];
1082
+ if (!isEqual(o, i) && !targetsEqual(o, i)) setSignal(e, typeof i === "function" ? () => i : i);
1083
+ }
1084
+ }
1085
+
1086
+ function hasAccessorFlag(e) {
1087
+ return e.acc === true;
1088
+ }
1089
+
1090
+ /** One leaf's notification when the caller already has both values. */ function notifyKeyValue(e, n, t, r, o, i) {
1091
+ if (e.acc === true) {
1092
+ notifyKeyDiff(e, n, o, i, false);
1093
+ return;
1094
+ }
1095
+ if (!isEqual(t, r) && !targetsEqual(t, r)) setSignal(e, typeof r === "function" ? () => r : r);
1096
+ }
1097
+
1098
+ /** The structural half of an adoption's notifications (reconcile does the
1099
+ * leaves itself): presence by `in`, the container by membership. Presence
1100
+ * is DIFFED `old` → `neu` like the leaves (#3743): a presence node is
1101
+ * written only where `in` changed between the view it was last told
1102
+ * (#3296) and the adoption — `setSignal` joins a held node's transaction
1103
+ * before its equality gate (A34 (1)), so repeating an unchanged absence to
1104
+ * a node an action holds would make the whole tick the action's (an
1105
+ * unrelated `a.value` stayed stale until the action settled). A real
1106
+ * change still writes, and on a held node still proposes. A live chained
1107
+ * `old` (a store proxy, §7b) reflects the inner store, not what the node
1108
+ * was last told — written unconditionally, as before.
294
1109
  *
295
- * @internal
296
- */ function getStoreAffectsNodes(e, t) {
297
- GlobalQueue.p ||= e => {
298
- const t = affectsScopes.get(e);
299
- if (!t) return;
300
- affectsScopes.delete(e);
301
- for (let e = 0; e < t.inherited.length; e++) GlobalQueue.j(t.inherited[e]);
302
- };
303
- if (t === undefined) {
304
- const t = nextAffectsNodeResolver(e, $AFFECTS);
305
- let o = affectsScopes.get(t);
306
- if (!o) affectsScopes.set(t, o = {
307
- scope: new Set,
308
- inherited: []
309
- });
310
- const r = [ t ];
311
- walkAffectsScope(e[$PROXY], o, r, e.fam, new Set);
1110
+ * The container is told of an arrangement change when it has structural
1111
+ * subscribers OR carries an arrangement guess (S4): for a guessed
1112
+ * container the write is the landing that judges the guess (Q-D, plan
1113
+ * sec. 39 — confirm, supersede, or hold beneath), not a subscriber
1114
+ * notification, and a landing whose truth changed no guessed key's value
1115
+ * or presence (a newer question's rows beneath an optimistic push) still
1116
+ * answers the arrangement — before, only the presence write reached the
1117
+ * lane, by accident of being unconditional. */ function notifyFoldTail(e, n, t) {
1118
+ const r = e.h;
1119
+ if (r !== null) {
1120
+ const e = n[$TARGET];
1121
+ for (const o of Reflect.ownKeys(r)) if (e || o in n !== o in t) setSignal(r[o], o in t);
1122
+ }
1123
+ const o = e.k;
1124
+ if (o !== null && (o.t !== null || o.u & CONFIG_OVERRIDE)) {
1125
+ const e = Array.isArray(t) && Array.isArray(n) ? arrayStructureChanged(n, t) : membershipChanged(n, t);
1126
+ if (e) notifyContainer(o, t);
1127
+ }
1128
+ }
1129
+
1130
+ /** An adoption's notifications: every node of the target, diffed `old` →
1131
+ * `neu` (value nodes by key, presence by `in`, the container by
1132
+ * membership, the deep witness by identity). */ function notifyFold(e, n, t) {
1133
+ if (e.dk !== null && n !== t) bumpDeep(e);
1134
+ const r = e.n;
1135
+ if (r !== null) {
1136
+ for (const e of Reflect.ownKeys(r)) notifyKeyDiff(r[e], e, n, t);
1137
+ }
1138
+ notifyFoldTail(e, n, t);
1139
+ }
1140
+
1141
+ // ---------------------------------------------------------------------------
1142
+ // visibility
1143
+ let writing = 0;
1144
+
1145
+ /** Roots of the stores with an open setter: reads of THEIR drafts are the
1146
+ * writer's (no tracking, pending backing served); every other store reads
1147
+ * normally — a derive's external reads are its dependencies (#3037). */ let writeScopes = null;
1148
+
1149
+ const pendingNotify = new Set;
1150
+
1151
+ function scopeKey(e) {
1152
+ if (e.fam !== null) return e.fam;
1153
+ let n = e;
1154
+ while (n.u !== null) n = n.u;
1155
+ return n;
1156
+ }
1157
+
1158
+ function inDraft(e) {
1159
+ return writeScopes !== null && writeScopes.has(scopeKey(e));
1160
+ }
1161
+
1162
+ /** Shallow store: values served verbatim (a nested store proxy still wraps
1163
+ * into the family so writes stay isolated). */ function serveShallow(e, n, t) {
1164
+ if (t !== null && typeof t === "object" && t[$TARGET] !== undefined) return draftServe(e, wrap(t, e, n));
1165
+ return t;
1166
+ }
1167
+
1168
+ /** A child proxy served to a draft joins the draft's scope. */ function draftServe(e, n) {
1169
+ if (writeScopes !== null && inDraft(e)) {
1170
+ const e = n?.[$TARGET];
1171
+ if (e !== undefined && e.v !== undefined) writeScopes.add(scopeKey(e));
1172
+ }
1173
+ return n;
1174
+ }
1175
+
1176
+ /** The committed backing: the container node's committed value while a
1177
+ * batch is staged on it (an adoption swaps `t.v` eagerly — INTERNALS §3,
1178
+ * "adoption is eager by contract" — and the node keeps the frame committed
1179
+ * readers under a hold still see), `t.v` otherwise. */ function committed(e) {
1180
+ const n = e.k;
1181
+ if (n !== null) return n.Ae !== NOT_PENDING ? asBacking(n.pe) : e.v;
1182
+ // A node-less staging (`stageOn`): the fold queue remembers the frame.
1183
+ return e.pb !== null ? preBatch(e) : e.v;
1184
+ }
1185
+
1186
+ /** The pass that sees this flush's staging (signal parity — `read()`'s
1187
+ * staged arm): the computation running (`context`, never the owner — a
1188
+ * handler, an effect callback or `onSettled` has an owner but no pass),
1189
+ * unless it is a frame reader (children-forbidden, A32). Null = the
1190
+ * committed frame. */ function stagingReader() {
1191
+ let e = context;
1192
+ if (e === null) return null;
1193
+ if (e.Ht) e = e.gt ?? null;
1194
+ return e === null || e.u & CONFIG_CHILDREN_FORBIDDEN ? null : e;
1195
+ }
1196
+
1197
+ /** The backing a read serves (RUL-1, signal parity): the draft and the write
1198
+ * override read the pending backing; a tracked reader reads it too — only
1199
+ * for presence and descriptors, its leaf (born from the two frames) decides
1200
+ * the value through core; a context-free or frame reader the committed
1201
+ * backing; a pass reading UNTRACKED asks the container node — `read()`
1202
+ * without a link: the node's value is the backing, chosen by the hold rules
1203
+ * (a render effect outside the parking flush sees committed and re-derives
1204
+ * at the landing; a memo joins the future; a staging is marked read). */
1205
+ /** The backing a read of `target` is served from — the truth (committed,
1206
+ * or the staging a pass may see). An optimistic family's lane values are
1207
+ * NOT composed here: a guessed key always has its node, and the node is
1208
+ * what serves its value (`nodeValue`); presence and enumeration compose
1209
+ * per key / per walk (`optimisticHas`, `enumerationSource`). */ function readSource(e, n, t = false) {
1210
+ // An optimistic setter's read before its first write sees what the writer
1211
+ // sees — the lanes' values and the tick's own guesses over the truth
1212
+ // (#3665), never a staging awaiting its fold: the draft is born on the
1213
+ // read (and notified at the setter's exit like any).
1214
+ if (userWrite && e.fam !== null && e.fam.opt === true && !pendingNotify.has(e) && inDraft(e)) {
1215
+ const n = ensurePB(e);
1216
+ pendingNotify.add(e);
1217
+ return n;
1218
+ }
1219
+ const r = e.pb;
1220
+ if (r === null) return e.v;
1221
+ if (inDraft(e) || writeOverride) {
1222
+ // The derive reads its own store through its draft: a key (or the
1223
+ // container) a transaction holds — a user's write inside an action,
1224
+ // held with it — is the future, and the pass that reads it derives
1225
+ // from the future (L2: a read of something already held joins it): the
1226
+ // derive's whole result reveals with the action (core R31 / #3733:
1227
+ // "under the transaction and revealed with it"), not key by key. A
1228
+ // user's setter reading its draft is no pass and joins nothing here.
1229
+ if (writeOverride && !userWrite) {
1230
+ const t = n !== undefined ? e.n?.[n] : undefined;
1231
+ if (t !== undefined) {
1232
+ if ((t.u & (CONFIG_HELD | CONFIG_OVERRIDE)) === CONFIG_HELD) joinPassTx(txOf(t));
1233
+ } else {
1234
+ const t = e.k;
1235
+ if (t !== null && (t.u & (CONFIG_HELD | CONFIG_OVERRIDE)) === CONFIG_HELD && (n === undefined || heldKeyChanged(e, n))) joinPassTx(txOf(t));
1236
+ }
1237
+ }
1238
+ return r;
1239
+ }
1240
+ const o = e.k;
1241
+ // A key whose leaf carries a lane's value (a guess, S4): the leaf serves
1242
+ // it — the container's frame is not consulted (a reader is not made a
1243
+ // stale reader of the container's hold for a key it does not see through
1244
+ // it).
1245
+ if (n !== undefined) {
1246
+ const t = e.n?.[n];
1247
+ if (t !== undefined && t.u & CONFIG_OVERRIDE) return committed(e);
1248
+ }
1249
+ const i = o !== null && (o.u & CONFIG_HELD) !== 0;
1250
+ // A held container: the hold's unit is the key (#3706). A key the HELD
1251
+ // staging left unchanged reads the ambient view — a mainline layer's
1252
+ // write above the hold publishes mainline (#3688, #3612); a key it
1253
+ // changed reads the frame core serves this reader.
1254
+ if (i && n !== undefined && !heldKeyChanged(e, n, t)) return r;
1255
+ const l = stagingReader();
1256
+ if (l === null) {
1257
+ if (getObserver() !== null) return r;
1258
+ // a frame reader's leaf decides the value
1259
+ // A projection's writes are its truth as soon as made (the derive is
1260
+ // the authority, nothing it writes is a proposal): a context-free reader
1261
+ // sees them before the flush — unless a hold keeps them staged.
1262
+ if (familyAhead(e)) return r;
1263
+ // A verdict window (`isPending`/`latest`) with no reader (a top-level
1264
+ // probe) judges the container like any node — for a key the batch
1265
+ // changed; an unchanged key is committed and final (A22: pending is per
1266
+ // key). A held container's committed frame is the node's.
1267
+ if (verdict === null || !i && n !== undefined && !keyChanged(e, n, t)) return i ? asBacking(o.pe) : e.v;
1268
+ return o === null ? committed(e) : asBacking(read(o));
1269
+ }
1270
+ // A pass reading a key the batch left unchanged: the same value in both
1271
+ // frames — committed, holding no one. Otherwise the container's frame by
1272
+ // core's rules — `read()` of the node WITHOUT a link (a value reader never
1273
+ // subscribes to the container): a render effect outside a hold's flush
1274
+ // sees committed and re-derives at the landing, a memo joins the future,
1275
+ // a staging read is marked. The key's own leaf, when it has one, decides
1276
+ // the value the same way.
1277
+ if (!i) {
1278
+ // A plain pass this flush already served a staging as the screen
1279
+ // (REACTIVE_STAGED_READ — what `read()` would set again here) reads an
1280
+ // unheld staging directly: an unchanged key is the same value in both
1281
+ // frames, a changed one is what the mark already stands for. The
1282
+ // per-key question is asked once per pass, not once per key (a
1283
+ // `mapArray` over 1k shifted rows asked it 1k times).
1284
+ if (l.R & REACTIVE_STAGED_READ && !(l.u & (CONFIG_VERDICT | CONFIG_CHILDREN_FORBIDDEN))) return r;
1285
+ if (n !== undefined && !keyChanged(e, n, t)) return committed(e);
1286
+ // A node-less staging (`stageOn`): what `read()` of its node would do
1287
+ // for this pass — a verdict reader sees the screen, any other derives
1288
+ // from the staging and is marked as having read it.
1289
+ if (o === null) {
1290
+ if (l.u & CONFIG_VERDICT && stagedScreen(l)) return committed(e);
1291
+ stagedRead(l);
1292
+ return r;
1293
+ }
1294
+ }
1295
+ return asBacking(untrack(() => read(o)));
1296
+ }
1297
+
1298
+ /** Did the HELD staging (the container node's, not a mainline layer above
1299
+ * it) change `key`? */ function heldKeyChanged(e, n, t = true) {
1300
+ return changedBetween(e, e.k.pe, e.k.Ae, n, t);
1301
+ }
1302
+
1303
+ /** A family target's unheld staging, read with no pass (a handler). */ function familyAhead(e) {
1304
+ return e.fam !== null && context === null && !(e.k !== null && e.k.u & CONFIG_HELD);
1305
+ }
1306
+
1307
+ /** Did this batch change `key` — value (slot equality), presence, and (for
1308
+ * a `shape` reader — a descriptor read, a node's hold) enumerability or
1309
+ * accessor-ness? A swapped or non-plain prototype, or a chained backing,
1310
+ * changes every key (#3706: those hold the whole container).
1311
+ *
1312
+ * A VALUE read asks without `shape`: a key whose value is the same in both
1313
+ * frames serves the same value from either, whatever its descriptor did —
1314
+ * and the descriptor probes (`__lookupGetter__`, `propertyIsEnumerable`,
1315
+ * twice each) are the cost of the question on a wide container read under
1316
+ * a staging (a keyed reconcile's 1k rows, read by `mapArray` in the flush
1317
+ * that staged them: ~3× the tick). A container with accessors seen (`a`)
1318
+ * keeps the full test — a getter's answer is not a slot's. */ function keyChanged(e, n, t = true) {
1319
+ return changedBetween(e, committed(e), e.pb, n, t);
1320
+ }
1321
+
1322
+ function changedBetween(e, n, t, r, o) {
1323
+ if (e.ch || t[$TARGET] !== undefined || Object.getPrototypeOf(t) !== Object.getPrototypeOf(n) || !plainProto(n)) return true;
1324
+ if (e.del !== null && e.del.has(r)) return r in n;
1325
+ const i = hasOwn.call(t, r) || e.ovl && hasOwn.call(e.v, r);
1326
+ if (i !== hasOwn.call(n, r)) return true;
1327
+ if (!i) return false;
1328
+ if ((o || e.a) && (isOwnAccessor(n, r) || isOwnAccessor(t, r) || propertyIsEnumerable.call(n, r) !== propertyIsEnumerable.call(t, r))) return true;
1329
+ const l = t[r];
1330
+ const u = n[r];
1331
+ return !isEqual(u, l) && !sameLogicalSlot(e, u, l);
1332
+ }
1333
+
1334
+ /** Value of a key with a leaf: core's — `read()` links a tracked reader and,
1335
+ * tracked or not, applies the hold and A28 rules a signal's read does. A
1336
+ * projection's unheld staging is ahead for a handler (`familyAhead`). */ function nodeValue(e, n, t) {
1337
+ let r = read(e);
1338
+ if (e.Ae !== NOT_PENDING && !(e.u & CONFIG_HELD) && context === null && t.fam !== null) r = e.Ae;
1339
+ return r === FORCE ? n : r;
1340
+ }
1341
+
1342
+ /** Serve a present data key: link the leaf for a tracked reader (creating it
1343
+ * on first read), wrap a wrappable child through the per-node wrap cache. */ function serveDataKey(e, n, t, r, o, i = -1) {
1344
+ // Read-through (§7b): the inner store's node is the truth; the outer's is
1345
+ // a subscription point only — unless it carries a guess (an optimistic
1346
+ // store over a store: the guess is the outer's, shown over the inner).
1347
+ const l = e.ch && r === e.v;
1348
+ let u = t;
1349
+ // A write-override read (a derive's draft) serves the backing: the derive
1350
+ // composes on the truth, never on a lane's or a hold's frame.
1351
+ if (!inDraft(e) && !writeOverride) {
1352
+ if (o === undefined && getObserver() !== null) o = getNode(e, n, i);
1353
+ if (o !== undefined) {
1354
+ const n = nodeValue(o, t, e);
1355
+ if (l) {
1356
+ // The link's committed value follows the inner store's (what a lane
1357
+ // over it covers — its reveal and revert compare against it, S4).
1358
+ o.pe = t;
1359
+ if (o.u & CONFIG_OVERRIDE) u = n;
1360
+ } else u = n;
1361
+ }
1362
+ }
1363
+ if (e.s) return serveShallow(e, n, u);
1364
+ // A derive's draft wrapper answers `$TARGET` without being a proxy: the
1365
+ // inner store's alias (#3767), resolved like a raw (#3859).
1366
+ if (e.ch && !l && u !== null && typeof u === "object" && u[$TARGET]?.px !== u) u = resolveChainedRaw(e, n, u);
1367
+ if (o !== undefined) {
1368
+ if (o.pxv === u && u !== undefined) return draftServe(e, o.px);
1369
+ if (!isWrappable(u)) return u;
1370
+ const t = wrap(u, e, n);
1371
+ o.px = t;
1372
+ o.pxv = u;
1373
+ return draftServe(e, t);
1374
+ }
1375
+ if (!isWrappable(u)) return u;
1376
+ return draftServe(e, wrap(u, e, n));
1377
+ }
1378
+
1379
+ /** Is `n` among `c`'s dependencies (any pass's — a kept tail included)? */ function linkedTo(e, n) {
1380
+ for (let t = e._; t !== null; t = t.p) if (t.I === n) return true;
1381
+ return false;
1382
+ }
1383
+
1384
+ /** The projection's obligation (plan sec. 31.7 Q-B): before any value is served
1385
+ * through a family target, the derive — the firewall — is brought up to
1386
+ * date WITHOUT the reader subscribing to it. Core's `read()` of the
1387
+ * firewall with no link does all of it: the pull, the status gate
1388
+ * (uninitialized / pending → NotReady, errored → the error; a verdict
1389
+ * window judges it; a pending source registers the reader for the landing)
1390
+ * and the reader's height. The derive's own draft ops are exempt (the write
1391
+ * override): the derive is the author. */ function pullFamily(e) {
1392
+ const n = e.fam.node;
1393
+ if (n === null || writeOverride || inDraft(e)) return;
1394
+ // A settled derive: the pull alone, no link (the barrier). A derive with a
1395
+ // flight up (or errored): the reader observes the flight exactly as a
1396
+ // reader of a memo would — linked, so it re-runs at the landing (the
1397
+ // next settled pass pulls without linking and the stale link trims), a
1398
+ // verdict reader registered, a tracked pass suspended.
1399
+ if (n.G & (STATUS_PENDING | STATUS_ERROR)) {
1400
+ // A render effect outside the flight's own flush is the frame, not a
1401
+ // derivation: it keeps what it shows and learns of the landing from the
1402
+ // leaves the landing changes (unchanged leaves say nothing — it is not a
1403
+ // stale reader of the derive). Inside the flush it suspends like any.
1404
+ // One that already observes the flight (linked by the pass that saw it
1405
+ // go up — the frame's hold, `blocked`) keeps observing it: a re-run for
1406
+ // another reason (a guess it read, the seam) that dropped the link would
1407
+ // release the hold with the flight still up.
1408
+ const t = context;
1409
+ if (t !== null && t.i === EFFECT_RENDER && n.u & CONFIG_HELD && flushTransaction !== txOf(n) && !linkedTo(t, n)) return;
1410
+ // An optimistic family carrying guesses that stand in for the flight
1411
+ // (A17): the guesses are the display — a reader is served the leaves
1412
+ // (committed plus the guesses) and does not suspend on the derive; a
1413
+ // verdict window still asks it (`isPending` is true while the flight is
1414
+ // up). The family's, not the target's: the edit stands in for the one
1415
+ // flight the family has.
1416
+ const r = e.fam.overlaid;
1417
+ if (verdict === null && n.G & STATUS_PENDING && r !== undefined && r.size !== 0) return;
1418
+ read(n);
1419
+ } else untrack(() => read(n));
1420
+ }
1421
+
1422
+ /** A projection's writes are its derive's: a staging made while the derive
1423
+ * is held (a flight up — its continuation writes after an `await`, a
1424
+ * callback's late write) belongs to the derive's transaction and reveals
1425
+ * with it, never drained early — and answers the derive's question: a quiet
1426
+ * re-ask's landing is quiet through its reveal (A19 exc. 2; the leaf's own
1427
+ * classification, as core reads it — `heldNotFinal`). */ function holdWithDerive(e, n) {
1428
+ const t = e.fam?.node;
1429
+ if (t !== undefined && t !== null && !userWrite && // the derive's own write (its draft or landing), not a user setter's
1430
+ t.u & CONFIG_HELD && n.Ae !== NOT_PENDING &&
1431
+ // A node carrying a guess is the lane's: its staging is the truth beneath
1432
+ // the guess (`setSignal` → `laneWrite`), never re-homed by the store.
1433
+ !(n.u & (CONFIG_HELD | CONFIG_OVERRIDE))) {
1434
+ holdNode(n, txOf(t));
1435
+ n.m.It = t.m.It;
1436
+ }
1437
+ }
1438
+
1439
+ /** A chained backing's child (§7b): a raw the inner family owns, or holds
1440
+ * at this key, is served as the inner store's wrapper — never a fresh
1441
+ * raw-keyed one — so the chained targets are the same objects across
1442
+ * settled and pending views. */ function resolveChainedRaw(e, n, t) {
1443
+ const r = e.v[$TARGET];
1444
+ if (r.ch) {
1445
+ const e = resolveChainedRaw(r, n, t);
1446
+ return e === t ? t : wrap(e, r, n);
1447
+ }
1448
+ const o = lookupTarget(t, r.fam);
1449
+ if (o !== undefined) return o.px;
1450
+ if ((r.v[n] === t || r.pb?.[n] === t) && isWrappable(t)) return wrap(t, r, n);
1451
+ return t;
1452
+ }
1453
+
1454
+ /** The backing a structural read serves: a tracked reader subscribes to the
1455
+ * container and reads the frame core serves it — committed or staging by
1456
+ * the hold rules (`read()` on the node: the node's value IS the backing);
1457
+ * anyone else reads by `readSource`. */ function enumerationSource(e) {
1458
+ if (!inDraft(e) && !writeOverride && getObserver() !== null) {
1459
+ // A container's arrangement guess is not a backing: the view composes
1460
+ // over the base it is shown over.
1461
+ const n = asBacking(read(getContainerNode(e)));
1462
+ return e.fam?.opt === true ? optHooks.view(e, n) : n;
1463
+ }
1464
+ const n = readSource(e);
1465
+ return optRead(e) ? optHooks.view(e, n) : n;
1466
+ }
1467
+
1468
+ /** A read on an optimistic family that composes the lanes' values: not the
1469
+ * draft's (it composed already), not a derive's write-override read (the
1470
+ * derive composes on the truth). */ function optRead(e) {
1471
+ return e.fam !== null && e.fam.opt === true && !inDraft(e) && !writeOverride;
1472
+ }
1473
+
1474
+ /** Pollution keys are never served from the prototype (core R30). */ const UNSAFE_KEYS = new Set([ "__proto__", "prototype", "constructor" ]);
1475
+
1476
+ // ---------------------------------------------------------------------------
1477
+ // traps
1478
+ const traps = {
1479
+ get(e, n, t) {
1480
+ // One typeof gates every brand-symbol compare off the hot string path.
1481
+ if (typeof n !== "string") {
1482
+ if (n === $TARGET) return e;
1483
+ if (n === $PROXY) return t;
1484
+ if (n === $OWNER) return undefined;
1485
+ // ownership stamp: never a user key
1486
+ if (n === $RECORD) return undefined;
1487
+ // a store is no view (see `viewOf`)
1488
+ // refresh()/isPending resolve the projection computed through $REFRESH.
1489
+ if (n === $REFRESH) return e.fam?.node ?? undefined;
1490
+ if (n === $TRACK) {
1491
+ if (e.fam !== null) pullFamily(e);
1492
+ if (!inDraft(e) && getObserver() !== null) {
1493
+ read(getContainerNode(e));
1494
+ // Structural chaining (§7b): a chained backing's $TRACK reads
1495
+ // through to the INNER store's container — structural
1496
+ // notifications land on the source's own node.
1497
+ const n = readSource(e);
1498
+ if (n[$TARGET] !== undefined) n[$TRACK];
1499
+ }
1500
+ return undefined;
1501
+ }
1502
+ // user symbols fall through to the generic path
1503
+ }
1504
+ // (The witness before the pull: a mark on an uninitialized derived
1505
+ // store is witnessed, then the pull throws — loading, declared pending.)
1506
+ if (verdict !== null && affectsHooks !== null && getObserver() === null) affectsHooks.witness(e, n);
1507
+ if (e.fam !== null) pullFamily(e);
1508
+ // Hot inline case: existing PLAIN node (non-accessor) read outside any
1509
+ // draft — the dbmon/uibench effect re-read shape. Core's `read()` serves
1510
+ // it (linking a tracked reader; the hold rules either way). Skips
1511
+ // serveDataKey's frame, the FORCE compare (only accessor keys ever hold
1512
+ // the sentinel), and isWrappable for primitives. ONE node-map lookup
1513
+ // serves this block and the accessor probe below. Before the backing is
1514
+ // consulted: a deleted key's node serves `undefined` (notifyWrites), and
1515
+ // a chained target's node carrying a GUESS is the value (A17 — the base
1516
+ // beneath it, and any hold there, is not this reader's concern; a link
1517
+ // without one reads through below).
1518
+ const r = e.n?.[n];
1519
+ if (writeScopes === null && !writeOverride) {
1520
+ const t = r;
1521
+ if (t !== undefined && t.acc !== true && (!e.ch || t.u & CONFIG_OVERRIDE)) {
1522
+ const r = nodeValue(t, undefined, e);
1523
+ if (r === null || typeof r !== "object") return r;
1524
+ if (e.s) return serveShallow(e, n, r);
1525
+ if (t.pxv === r) return t.px;
1526
+ if (isWrappable(r)) {
1527
+ const o = wrap(r, e, n);
1528
+ t.px = o;
1529
+ t.pxv = r;
1530
+ return o;
1531
+ }
1532
+ return r;
1533
+ }
1534
+ }
1535
+ const o = readSource(e, n);
1536
+ // Overlay delete (#3044): a prototype overlay cannot shadow a delete, so
1537
+ // deleted keys are tracked aside and read as absent in the pending view.
1538
+ if (e.del !== null && o === e.pb && e.del.has(n)) {
1539
+ if (!inDraft(e) && getObserver() !== null) read(getNode(e, n));
1540
+ return undefined;
1541
+ }
1542
+ // Accessor keys serve through Reflect.get with the PROXY receiver
1543
+ // (R20/R29: internal reads track; the node is linked for shape-change
1544
+ // notification but its value is never served). Accessor-ness comes from
1545
+ // the node's cached flag; the first TRACKED read (which creates the
1546
+ // node) probes once — untracked node-less reads take the plain path,
1547
+ // where a raw-receiver getter still returns correct committed values.
1548
+ // Tracking suppression is PER-TARGET (inDraft), never global (#3037).
1549
+ let i = -1;
1550
+ {
1551
+ let l;
1552
+ if (r !== undefined) l = r.acc === true; else if (!inDraft(e) && getObserver() !== null) {
1553
+ l = isOwnAccessor(o, n);
1554
+ if (o === (e.pb ?? e.v)) i = l ? 1 : 0;
1555
+ } else l = false;
1556
+ if (l) {
1557
+ if (!inDraft(e) && getObserver() !== null) read(r ?? getNode(e, n, i));
1558
+ const l = Reflect.get(o, n, t);
1559
+ if (e.s) return serveShallow(e, n, l);
1560
+ return isWrappable(l) ? draftServe(e, wrap(l, e, n)) : l;
1561
+ }
1562
+ }
1563
+ // Plain-data fast path: no descriptor allocation per read. Inherited
1564
+ // pollution keys are never served (core R30) — checked before the
1565
+ // proto-function branch can leak `constructor`. Overlay pending backings
1566
+ // chain to the committed backing, so "own in the view" means own on
1567
+ // either layer — a genuine prototype method is one that is own on
1568
+ // NEITHER.
1569
+ const l = e.ovl && o === e.pb;
1570
+ if ((n === "constructor" || n === "__proto__" || n === "prototype") && !hasOwn.call(o, n) && !(l && hasOwn.call(e.v, n))) return undefined;
1571
+ let u = o[n];
1572
+ if (u === undefined ? !hasOwn.call(o, n) && !(l && hasOwn.call(e.v, n)) : false) {
1573
+ // Inherited: prototype getters/methods run with the proxy receiver.
1574
+ u = Reflect.get(o, n, t);
1575
+ if (typeof u === "function") return u;
1576
+ // proto methods untracked
1577
+ // Read-through (§7b): the inner store answers an absent key too — the
1578
+ // outer's node is a subscription point unless it carries a guess.
1579
+ if (e.ch && o === e.v) return serveDataKey(e, n, u, o, r, i);
1580
+ // Reading a currently-absent own key subscribes to it (R12) — for any
1581
+ // target OUTSIDE its own draft scope, even mid-setter (#3037, above).
1582
+ if (u === undefined && !inDraft(e)) {
1583
+ if (getObserver() !== null) read(getNode(e, n, i));
1584
+ const t = e.n?.[n];
1585
+ if (t) {
1586
+ const r = nodeValue(t, undefined, e);
1587
+ if (e.s) return serveShallow(e, n, r);
1588
+ return isWrappable(r) ? draftServe(e, wrap(r, e, n)) : r;
1589
+ }
1590
+ }
1591
+ if (e.s) return serveShallow(e, n, u);
1592
+ return isWrappable(u) ? draftServe(e, wrap(u, e, n)) : u;
1593
+ }
1594
+ if (typeof u === "function" && !hasOwn.call(o, n) && !(l && hasOwn.call(e.v, n))) return u;
1595
+ // proto method
1596
+ return serveDataKey(e, n, u, o, r, i);
1597
+ },
1598
+ has(e, n) {
1599
+ if (n === $TARGET || n === $PROXY || n === $TRACK) return true;
1600
+ if (n === $OWNER || n === $RECORD) return false;
1601
+ // (The witness before the pull: a mark on an uninitialized derived
1602
+ // store is witnessed, then the pull throws — loading, declared pending.)
1603
+ if (verdict !== null && affectsHooks !== null && getObserver() === null) affectsHooks.witness(e, n);
1604
+ if (e.fam !== null) pullFamily(e);
1605
+ const t = readSource(e, n);
1606
+ // A tracked reader's presence node answers (born from the two frames;
1607
+ // core decides which it sees); everyone else reads the backing. A
1608
+ // chained target's node is a subscription point (§7b): the inner store
1609
+ // answers through the backing — unless the outer node carries a guess.
1610
+ if (!inDraft(e) && !writeOverride) {
1611
+ if (getObserver() !== null) {
1612
+ const r = getHasNode(e, n);
1613
+ const o = read(r);
1614
+ if (!e.ch || t !== e.v) return !!o;
1615
+ const i = n in t;
1616
+ r.pe = i;
1617
+ // the link follows the inner store (S4)
1618
+ if (r.u & CONFIG_OVERRIDE) return !!o;
1619
+ return i;
1620
+ } else if (optRead(e)) {
1621
+ const t = optHooks.has(e, n);
1622
+ if (t !== undefined) return t;
1623
+ }
1624
+ }
1625
+ return n in t && !(e.del !== null && t === e.pb && e.del.has(n));
1626
+ },
1627
+ ownKeys(e) {
1628
+ if (verdict !== null && affectsHooks !== null && getObserver() === null) affectsHooks.witness(e, undefined);
1629
+ if (e.fam !== null) pullFamily(e);
1630
+ return visibleKeys(e, enumerationSource(e));
1631
+ },
1632
+ getOwnPropertyDescriptor(e, n) {
1633
+ if (n === $OWNER || n === $RECORD) return undefined;
1634
+ const t = getObserver();
1635
+ if (verdict !== null && affectsHooks !== null && t === null) affectsHooks.witness(e, n);
1636
+ if (e.fam !== null) pullFamily(e);
1637
+ // An enumerator (spread, Object.entries) already holds the container
1638
+ // node and reads its frame; a descriptor read on its own tracks
1639
+ // presence (R13).
1640
+ const r = t !== null && !inDraft(e) && !writeOverride;
1641
+ const o = r && observerHoldsContainer(e, t);
1642
+ let i;
1643
+ if (o) i = enumerationSource(e); else if (r) {
1644
+ // The presence node's frame (core decides which) is the one described
1645
+ // (a chained target's inner store answers through the backing, §7b);
1646
+ // the descriptor itself comes from the backing the container's frame
1647
+ // serves this reader (`readSource`: a held container's changed key —
1648
+ // enumerability, accessor-ness — reads committed for a stale reader,
1649
+ // the staging for a member; #3706 contrast).
1650
+ const t = getHasNode(e, n);
1651
+ const r = read(t);
1652
+ i = readSource(e, n, true);
1653
+ if (!r && (!e.ch || t.u & CONFIG_OVERRIDE || !(n in i))) return undefined;
1654
+ } else i = readSource(e, n, true);
1655
+ let l;
1656
+ if (!o && optRead(e)) {
1657
+ const t = optHooks.descriptor(e, n);
1658
+ if (t === null) return undefined;
1659
+ l = t;
1660
+ }
1661
+ l ??= visibleDescriptor(e, i, n);
1662
+ if (l === undefined) return undefined;
1663
+ if (!(n === "length" && Array.isArray(e))) l.configurable = true;
1664
+ return l;
1665
+ },
1666
+ set(e, n, t) {
1667
+ const r = inDraft(e);
1668
+ const o = !r && writeOverride;
1669
+ if (!r && !o) return true;
1670
+ if (n === "__proto__") return true;
1671
+ // pollution guard (core R30)
1672
+ const i = e.s ? t : unwrapValue(t);
1673
+ const l = ensurePB(e);
1674
+ pendingNotify.add(e);
1675
+ if (Array.isArray(l)) {
1676
+ if (n === "length") e.wk = WK_ALL; else if (e.wk !== WK_ALL) {
1677
+ const t = e.wk ??= new Set;
1678
+ t.add(n);
1679
+ t.add("length");
1680
+ }
1681
+ } else {
1682
+ if (e.wk !== WK_ALL) (e.wk ??= new Set).add(n);
1683
+ if (!(n in l)) e.kc++;
1684
+ }
1685
+ if (UNSAFE_KEYS.has(n)) {
1686
+ Object.defineProperty(l, n, {
1687
+ value: i,
1688
+ writable: true,
1689
+ enumerable: true,
1690
+ configurable: true
1691
+ });
1692
+ if (e.del !== null) e.del.delete(n);
1693
+ return true;
1694
+ }
1695
+ if (e.ovl && e.sc !== 2 && !hasOwn.call(l, n)) {
1696
+ Object.defineProperty(l, n, {
1697
+ value: i,
1698
+ writable: true,
1699
+ enumerable: true,
1700
+ configurable: true
1701
+ });
1702
+ } else l[n] = i;
1703
+ if (e.del !== null) e.del.delete(n);
1704
+ if (e.s && i !== null && typeof i === "object") markRawOne(i);
1705
+ if (o) notifyWrites(e);
1706
+ return true;
1707
+ },
1708
+ defineProperty(e, n, t) {
1709
+ const r = inDraft(e);
1710
+ const o = !r && writeOverride;
1711
+ if (!r && !o) return true;
1712
+ if (n === "__proto__") return true;
1713
+ if (t.get || t.set) e.a = true;
1714
+ if ("value" in t) t = {
1715
+ ...t,
1716
+ value: unwrapValue(t.value)
1717
+ };
1718
+ const i = ensurePB(e);
1719
+ if (e.a || !(t.enumerable && t.writable && t.configurable)) e.sc = 1;
1720
+ pendingNotify.add(e);
1721
+ if (e.wk !== WK_ALL) (e.wk ??= new Set).add(n);
1722
+ Object.defineProperty(i, n, t);
1723
+ if (e.del !== null) e.del.delete(n);
1724
+ if (o) notifyWrites(e);
1725
+ return true;
1726
+ },
1727
+ deleteProperty(e, n) {
1728
+ const t = inDraft(e);
1729
+ const r = !t && writeOverride;
1730
+ if (!t && !r) return true;
1731
+ const o = ensurePB(e);
1732
+ pendingNotify.add(e);
1733
+ if (e.wk !== WK_ALL) (e.wk ??= new Set).add(n);
1734
+ delete o[n];
1735
+ if (e.ovl && hasOwn.call(e.v, n)) (e.del ??= new Set).add(n);
1736
+ if (r) notifyWrites(e);
1737
+ return true;
1738
+ }
1739
+ };
1740
+
1741
+ /** Is `obs` subscribed to the container BY THIS PASS (its enumerator holds
1742
+ * it)? A link left from a previous pass is stale — the reader must subscribe
1743
+ * to the key's presence node or a later add never re-runs it. */ function observerHoldsContainer(e, n) {
1744
+ const t = e.k;
1745
+ if (t === null) return false;
1746
+ const r = t.Dt;
1747
+ return r !== null && r.o === n && (!(n.R & REACTIVE_RECOMPUTING_DEPS) || r.Ue === n.he);
1748
+ }
1749
+
1750
+ function storeSetter(e, n, t = true) {
1751
+ const r = e[$TARGET];
1752
+ const o = writeScopes;
1753
+ writeScopes = new Set;
1754
+ writeScopes.add(scopeKey(r));
1755
+ const i = userWrite;
1756
+ userWrite = t;
1757
+ writing++;
1758
+ let l;
1759
+ try {
1760
+ // No untrack: the writing flag already disables store-node linking
1761
+ // (draft reads never self-track, proj R2), while EXTERNAL reads (signals
1762
+ // inside a projection derive) must keep tracking — they are the derive's
1763
+ // dependencies.
1764
+ l = n(e);
1765
+ } finally {
1766
+ writing--;
1767
+ writeScopes = o;
1768
+ // Outermost setter exit: emit write-time notifications (one node write
1769
+ // per changed observed key) so holds and lanes engage now.
1770
+ if (writing === 0 && pendingNotify.size) {
1771
+ const e = [ ...pendingNotify ];
1772
+ pendingNotify.clear();
1773
+ for (const n of e) notifyWrites(n);
1774
+ // A direct commit (a projection's creation run) folds at the setter's
1775
+ // exit, unqueued: the backing is the pre-batch one (nothing swapped).
1776
+ if (directCommit) for (const n of e) if (n.pb !== null) foldTarget(n, n.v);
1777
+ }
1778
+ userWrite = i;
1779
+ }
1780
+ if (l !== undefined && l !== e && isWrappable(l)) {
1781
+ // A returned replacement: on an optimistic family a user's is itself an
1782
+ // optimistic edit — diffed against the view as guesses (`next` parity);
1783
+ // otherwise it is adopted as the incoming truth.
1784
+ if (t && r.fam?.opt === true && !writeOverride) optHooks.writes(r, unwrapValue(l)); else adoptPB(r, unwrapValue(l));
1785
+ }
1786
+ // A34 (3), #3612 — the derived store's twin of `setMemo`: a user write to
1787
+ // a derivation another transaction holds is nobody's proposal; it becomes
1788
+ // the draft's prior state and the hold re-derives over it (the writes
1789
+ // joined the hold through `setSignal`; the derive re-runs under it).
1790
+ if (t && heldDerivationHit) {
1791
+ heldDerivationHit = false;
1792
+ const e = r.fam.node;
1793
+ if (!(e.R & REACTIVE_DIRTY)) {
1794
+ e.R = e.R & ~REACTIVE_CHECK | REACTIVE_DIRTY;
1795
+ insertIntoHeap(e, dirtyQueue);
1796
+ schedule();
1797
+ }
1798
+ }
1799
+ }
1800
+
1801
+ function createStore(e, n) {
1802
+ const t = n?.shallow === true;
1803
+ const r = wrap(e);
1804
+ if (t) {
1805
+ r[$TARGET].s = true;
1806
+ markRawIngest(e);
1807
+ }
1808
+ {
1809
+ const e = getOwner();
1810
+ // Dev-tier graph registration (owner signal lists, onGraph); the
1811
+ // `_owner` write itself never reaches the proxy, see storeOwners.
1812
+ registerGraph(r, e);
1813
+ // Only once the engine is installed, like the node stamping it feeds: a
1814
+ // WeakMap.set per fresh store is a growing ephemeron table and,
1815
+ // disabled, buys nothing.
1816
+ if (attrHooks !== null) {
1817
+ storeOwners.set(r[$TARGET], e);
1818
+ nameStore(r, n?.name);
1819
+ }
1820
+ }
1821
+ const setter = e => storeSetter(r, e);
1822
+ return [ r, setter ];
1823
+ }
1824
+
1825
+ /** True when `proxy` is a SHALLOW store (children served verbatim, slots
1826
+ * replaced by reference — #2932). The list driver uses this to choose the
1827
+ * slot-patch channel (collected row bodies) over per-record registration. */ function storeIsShallow(e) {
1828
+ const n = e?.[$TARGET];
1829
+ return n !== undefined && n.s === true;
1830
+ }
1831
+
1832
+ /** True when `proxy` belongs to a projection family (S3). */ function storeHasFamily(e) {
1833
+ const n = e?.[$TARGET];
1834
+ return n !== undefined && n.fam !== null;
1835
+ }
1836
+
1837
+ /** True when `proxy` belongs to an OPTIMISTIC family (S4). */ function storeHasOptimisticFamily(e) {
1838
+ const n = e?.[$TARGET];
1839
+ return n !== undefined && n.fam?.opt === true;
1840
+ }
1841
+
1842
+ // ---------------------------------------------------------------------------
1843
+ // enumeration views (one visibility rule for the traps AND the deep walk)
1844
+ function visibleKeys(e, n) {
1845
+ let t;
1846
+ if (e.ovl && n === e.pb) {
1847
+ t = Reflect.ownKeys(e.v);
1848
+ const r = e.del;
1849
+ if (r !== null && r.size !== 0) t = t.filter(e => !r.has(e));
1850
+ for (const r of Reflect.ownKeys(n)) {
1851
+ if (!hasOwn.call(e.v, r)) t.push(r);
1852
+ }
1853
+ } else t = Reflect.ownKeys(n);
1854
+ // The ownership stamp is the last symbol on an owned backing: hide it.
1855
+ for (let e = t.length - 1; e >= 0 && typeof t[e] === "symbol"; e--) {
1856
+ if (t[e] === $OWNER) {
1857
+ t.splice(e, 1);
1858
+ break;
1859
+ }
1860
+ }
1861
+ return t;
1862
+ }
1863
+
1864
+ function visibleDescriptor(e, n, t) {
1865
+ let r = Object.getOwnPropertyDescriptor(n, t);
1866
+ if (e.ovl && n === e.pb) {
1867
+ if (e.del !== null && e.del.has(t)) return undefined;
1868
+ if (r === undefined) r = Object.getOwnPropertyDescriptor(e.v, t);
1869
+ }
1870
+ return r;
1871
+ }
1872
+
1873
+ // ---------------------------------------------------------------------------
1874
+ // deep / snapshot
1875
+ /** Tracking snapshot: subscribes every reachable record's container and deep
1876
+ * witness (one node per record, not one per path), then snapshots. */ function deep(e) {
1877
+ const n = e?.[$TARGET];
1878
+ if (n === undefined || n.px !== e) return e;
1879
+ const t = new Set;
1880
+ const childTarget = (e, n, t) => {
1881
+ let r = lookupTarget(n, e.fam);
1882
+ if (r === undefined) {
1883
+ if (!isWrappable(n)) return undefined;
1884
+ wrap(n, e, t);
1885
+ r = lookupTarget(n, e.fam) ?? n[$TARGET];
1886
+ }
312
1887
  return r;
1888
+ };
1889
+ const walkT = e => {
1890
+ if (e.fam !== null) pullFamily(e);
1891
+ const n = enumerationSource(e);
1892
+ if (t.has(n)) return;
1893
+ t.add(n);
1894
+ read(getDeepNode(e));
1895
+ // Through a chain (#3323): every inner record's container AND deep
1896
+ // witness — base writes bump the inner witnesses.
1897
+ for (let n = e; n.ch; ) {
1898
+ n = n.v[$TARGET];
1899
+ read(getContainerNode(n));
1900
+ read(getDeepNode(n));
1901
+ }
1902
+ for (const t of visibleKeys(e, n)) {
1903
+ const r = visibleDescriptor(e, n, t);
1904
+ if (r === undefined) continue;
1905
+ if (r.get || r.set) {
1906
+ e.a = true;
1907
+ continue;
1908
+ // accessors track through their own reads when invoked
1909
+ }
1910
+ let o = r.value;
1911
+ if (o === null || typeof o !== "object") continue;
1912
+ if (e.ch && o[$TARGET] === undefined) o = resolveChainedRaw(e, t, o);
1913
+ const i = childTarget(e, o, t);
1914
+ if (i === undefined) continue;
1915
+ // raw-marked: leaf by contract
1916
+ walkT(i);
1917
+ }
1918
+ };
1919
+ walkT(n);
1920
+ return snapshot(e);
1921
+ }
1922
+
1923
+ /** Non-tracking snapshot: source identity for unowned subtrees (zero copy),
1924
+ * a copy for owned ones (they are by definition modified relative to the
1925
+ * source). Sees the pending backing (R27). */ function snapshot(e) {
1926
+ const n = e?.[$TARGET];
1927
+ return snapshotWalk(e, new Map, n?.fam ?? null);
1928
+ }
1929
+
1930
+ function snapshotWalk(e, n, t) {
1931
+ if (e === null || typeof e !== "object") return e;
1932
+ let r = e;
1933
+ for (let e = true; ;e = false) {
1934
+ const n = r?.[$TARGET]?.v !== undefined;
1935
+ let o = n ? r[$TARGET] : undefined;
1936
+ if (o === undefined && t !== null) o = lookupTarget(r, t);
1937
+ if (o === undefined) o = lookupTarget(r, null);
1938
+ if (o === undefined) break;
1939
+ if (e && !n && t !== null && o.fam !== t) {
1940
+ const e = t.map.get(o.px);
1941
+ if (e !== undefined) o = e;
1942
+ }
1943
+ if (o.fam !== null) t = o.fam;
1944
+ // R27: a snapshot sees the batch's pending backing — a held one (another
1945
+ // transaction's future) only from its own draft.
1946
+ let i = o.v;
1947
+ if (o.pb !== null && (inDraft(o) || writeOverride || o.k === null || !(o.k.u & CONFIG_HELD))) {
1948
+ if (o.ovl) materializePB(o);
1949
+ i = o.pb;
1950
+ }
1951
+ if (optRead(o)) i = optHooks.view(o, i);
1952
+ if (i === r) break;
1953
+ r = i;
1954
+ }
1955
+ if (!isWrappable(r)) return r;
1956
+ const o = n.get(r);
1957
+ if (o !== undefined) return o;
1958
+ if (isOwned(r)) {
1959
+ const e = Array.isArray(r);
1960
+ const o = e ? [] : Object.create(Object.getPrototypeOf(r));
1961
+ n.set(r, o);
1962
+ for (const i of Reflect.ownKeys(r)) {
1963
+ if (e && i === "length" || i === $OWNER) continue;
1964
+ const l = Object.getOwnPropertyDescriptor(r, i);
1965
+ if (typeof i === "symbol" && !l.enumerable) continue;
1966
+ if (l.get || l.set) {
1967
+ Object.defineProperty(o, i, l);
1968
+ continue;
1969
+ }
1970
+ const u = l.value;
1971
+ const f = u !== null && typeof u === "object" ? snapshotWalk(u, n, t) : u;
1972
+ if (l.enumerable && l.writable && l.configurable) o[i] = f; else Object.defineProperty(o, i, {
1973
+ ...l,
1974
+ value: f
1975
+ });
1976
+ }
1977
+ if (e && o.length !== r.length) o.length = r.length;
1978
+ return o;
313
1979
  }
314
- const o = e.n?.[t] ?? nextAffectsNodeResolver(e, t);
315
- // Keyed marks resolve by identity too (#2904): another store family's
316
- // proxy can share this record's raw (a derived store swaps its backing to
317
- // the source's raw when its projection lands), and reads through it never
318
- // touch this target's node map. Scope is exactly the owning record's raw,
319
- // narrowed to this key for witness and birth inheritance.
320
- let r = affectsScopes.get(o);
321
- if (!r) affectsScopes.set(o, r = {
322
- scope: new Set,
323
- inherited: [],
324
- key: t
325
- });
326
- r.scope.add(e[STORE_VALUE]);
327
- if (e.pb) r.scope.add(e.pb);
328
- return [ o ];
329
- }
330
-
331
- export { $AFFECTS, $PROXY, $RECORD, $TARGET, $TRACK, STORE_HAS, STORE_NODE, STORE_VALUE, affectsScopesLive, getStoreAffectsNodes, getWriteOverride, inheritAffectsMarks, isRawValue, isWrappable, markRawIngest, markRawOne, nextAffectsNodeResolver, nextOptimisticViewResolver, ownEnumerableKeys, rawValuesUsed, setNextAffectsNodeResolver, setNextOptimisticViewResolver, setWriteOverride, witnessAffectsMark };
1980
+ n.set(r, r);
1981
+ let i = null;
1982
+ for (const e of Reflect.ownKeys(r)) {
1983
+ const o = Object.getOwnPropertyDescriptor(r, e);
1984
+ if (!o || o.get || o.set) continue;
1985
+ const l = o.value;
1986
+ if (l === null || typeof l !== "object") continue;
1987
+ const u = snapshotWalk(l, n, t);
1988
+ if (u !== l) {
1989
+ if (i === null) {
1990
+ i = Array.isArray(r) ? [ ...r ] : Object.create(Object.getPrototypeOf(r), Object.getOwnPropertyDescriptors(r));
1991
+ n.set(r, i);
1992
+ }
1993
+ i[e] = u;
1994
+ }
1995
+ }
1996
+ return i ?? r;
1997
+ }
1998
+
1999
+ export { $PROXY, $TARGET, $TRACK, LaneView, adoptPB, affectsHooks, arrayStructureChanged, asBacking, bumpDeep, cloneRaw, committed, containerEquals, createStore, deep, getContainerNode, getHasNode, getNode, hasAccessorFlag, installAffectsHooks, installOptHooks, materializePB, membershipChanged, nameStore, notifyFold, notifyFoldTail, notifyKeyDiff, notifyKeyValue, optHooks, resolveChainedRaw, runDirect, sameKey, snapshot, storeHasFamily, storeHasOptimisticFamily, storeIsShallow, storeSetter, targetsEqual, unwrapValue, userWriting, wrap };