@solidjs/signals 2.0.0-rc.0 → 2.0.0-rc.10

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 (149) hide show
  1. package/README.md +1 -1
  2. package/dist/dev-shared.js +7138 -0
  3. package/dist/dev.attribution.js +3307 -0
  4. package/dist/dev.js +8076 -6692
  5. package/dist/observe/affects.js +129 -0
  6. package/dist/observe/attribution.js +7 -0
  7. package/dist/observe/boundaries.js +793 -0
  8. package/dist/observe/core/action.js +177 -0
  9. package/dist/observe/core/async.js +849 -0
  10. package/dist/observe/core/attribution-costs.js +66 -0
  11. package/dist/observe/core/attribution-feedback.js +280 -0
  12. package/dist/observe/core/attribution-hooks.js +83 -0
  13. package/dist/observe/core/attribution-queries.js +43 -0
  14. package/dist/observe/core/attribution.js +2904 -0
  15. package/dist/observe/core/constants.js +283 -0
  16. package/dist/{types-cjs/core/context.d.cts → observe/core/context.js} +37 -12
  17. package/dist/observe/core/core.js +1999 -0
  18. package/dist/observe/core/dev.js +343 -0
  19. package/dist/observe/core/effect.js +200 -0
  20. package/dist/observe/core/error-hooks.js +71 -0
  21. package/dist/observe/core/error.js +80 -0
  22. package/dist/observe/core/external.js +98 -0
  23. package/dist/observe/core/graph.js +155 -0
  24. package/dist/observe/core/heap.js +147 -0
  25. package/dist/observe/core/invariants.js +45 -0
  26. package/dist/observe/core/lanes.js +205 -0
  27. package/dist/observe/core/optimistic.js +627 -0
  28. package/dist/observe/core/owner.js +353 -0
  29. package/dist/observe/core/scheduler.js +1547 -0
  30. package/dist/observe/core/verdict.js +674 -0
  31. package/dist/observe/index.js +59 -0
  32. package/dist/observe/map.js +484 -0
  33. package/dist/observe/signals.js +731 -0
  34. package/dist/observe/store/index.js +44 -0
  35. package/dist/observe/store/next/optimistic.js +717 -0
  36. package/dist/observe/store/next/projection.js +266 -0
  37. package/dist/observe/store/next/reconcile.js +375 -0
  38. package/dist/observe/store/next/store.js +2480 -0
  39. package/dist/observe/store/next/target.js +51 -0
  40. package/dist/observe/store/store.js +331 -0
  41. package/dist/observe/store/storePath.js +103 -0
  42. package/dist/observe/store/utils.js +1070 -0
  43. package/dist/prod/affects.js +10 -9
  44. package/dist/prod/attribution.js +45 -0
  45. package/dist/prod/boundaries.js +388 -178
  46. package/dist/prod/core/action.js +65 -37
  47. package/dist/prod/core/async.js +477 -208
  48. package/dist/prod/core/attribution-hooks.js +3 -0
  49. package/dist/prod/core/constants.js +186 -1
  50. package/dist/prod/core/context.js +10 -16
  51. package/dist/prod/core/core.js +1556 -415
  52. package/dist/prod/core/dev.js +18 -1
  53. package/dist/prod/core/effect.js +119 -79
  54. package/dist/prod/core/error-hooks.js +71 -0
  55. package/dist/prod/core/error.js +13 -1
  56. package/dist/prod/core/external.js +4 -4
  57. package/dist/prod/core/graph.js +105 -54
  58. package/dist/prod/core/heap.js +72 -65
  59. package/dist/prod/core/invariants.js +3 -2
  60. package/dist/prod/core/lanes.js +117 -52
  61. package/dist/prod/core/optimistic.js +474 -103
  62. package/dist/prod/core/owner.js +131 -84
  63. package/dist/prod/core/scheduler.js +1013 -248
  64. package/dist/prod/core/verdict.js +418 -113
  65. package/dist/prod/index.js +25 -13
  66. package/dist/prod/map.js +314 -151
  67. package/dist/prod/signals.js +382 -32
  68. package/dist/prod/store/index.js +38 -0
  69. package/dist/prod/store/next/optimistic.js +710 -0
  70. package/dist/prod/store/next/projection.js +257 -0
  71. package/dist/prod/store/next/reconcile.js +373 -0
  72. package/dist/prod/store/next/store.js +2356 -0
  73. package/dist/prod/store/next/target.js +51 -0
  74. package/dist/prod/store/store.js +129 -881
  75. package/dist/prod/store/utils.js +982 -242
  76. package/dist/types/attribution.d.ts +19 -0
  77. package/dist/types/attribution.prod.d.ts +22 -0
  78. package/dist/types/boundaries.d.ts +78 -5
  79. package/dist/types/core/action.d.ts +12 -5
  80. package/dist/types/core/async.d.ts +3 -1
  81. package/dist/types/core/attribution-costs.d.ts +35 -0
  82. package/dist/types/core/attribution-feedback.d.ts +133 -0
  83. package/dist/types/core/attribution-hooks.d.ts +304 -0
  84. package/dist/types/core/attribution-queries.d.ts +24 -0
  85. package/dist/types/core/attribution.d.ts +892 -0
  86. package/dist/types/core/constants.d.ts +179 -0
  87. package/dist/types/core/core.d.ts +305 -23
  88. package/dist/types/core/dev.d.ts +421 -8
  89. package/dist/types/core/effect.d.ts +8 -1
  90. package/dist/types/core/error-hooks.d.ts +71 -0
  91. package/dist/types/core/error.d.ts +9 -0
  92. package/dist/types/core/graph.d.ts +23 -0
  93. package/dist/types/core/heap.d.ts +5 -3
  94. package/dist/types/core/index.d.ts +6 -3
  95. package/dist/types/core/invariants.d.ts +5 -1
  96. package/dist/types/core/lanes.d.ts +51 -19
  97. package/dist/types/core/owner.d.ts +15 -3
  98. package/dist/types/core/scheduler.d.ts +252 -3
  99. package/dist/types/core/types.d.ts +124 -41
  100. package/dist/types/index.d.ts +18 -5
  101. package/dist/types/map.d.ts +2 -0
  102. package/dist/types/signals.d.ts +164 -13
  103. package/dist/types/store/index.d.ts +16 -5
  104. package/dist/types/store/next/optimistic.d.ts +25 -0
  105. package/dist/types/store/next/projection.d.ts +27 -0
  106. package/dist/types/store/next/reconcile.d.ts +10 -0
  107. package/dist/types/store/next/store.d.ts +143 -0
  108. package/dist/types/store/next/target.d.ts +196 -0
  109. package/dist/types/store/store.d.ts +46 -112
  110. package/dist/types/store/utils.d.ts +188 -40
  111. package/package.json +32 -26
  112. package/dist/node.cjs +0 -7938
  113. package/dist/prod/store/optimistic.js +0 -217
  114. package/dist/prod/store/projection.js +0 -231
  115. package/dist/prod/store/reconcile.js +0 -707
  116. package/dist/types/store/optimistic.d.ts +0 -45
  117. package/dist/types/store/projection.d.ts +0 -70
  118. package/dist/types/store/reconcile.d.ts +0 -46
  119. package/dist/types-cjs/affects.d.cts +0 -47
  120. package/dist/types-cjs/boundaries.d.cts +0 -175
  121. package/dist/types-cjs/core/action.d.cts +0 -64
  122. package/dist/types-cjs/core/async.d.cts +0 -21
  123. package/dist/types-cjs/core/constants.d.cts +0 -71
  124. package/dist/types-cjs/core/core.d.cts +0 -148
  125. package/dist/types-cjs/core/dev.d.cts +0 -64
  126. package/dist/types-cjs/core/effect.d.cts +0 -30
  127. package/dist/types-cjs/core/error.d.cts +0 -47
  128. package/dist/types-cjs/core/external.d.cts +0 -15
  129. package/dist/types-cjs/core/graph.d.cts +0 -5
  130. package/dist/types-cjs/core/heap.d.cts +0 -22
  131. package/dist/types-cjs/core/index.d.cts +0 -13
  132. package/dist/types-cjs/core/invariants.d.cts +0 -59
  133. package/dist/types-cjs/core/lanes.d.cts +0 -56
  134. package/dist/types-cjs/core/optimistic.d.cts +0 -6
  135. package/dist/types-cjs/core/owner.d.cts +0 -124
  136. package/dist/types-cjs/core/scheduler.d.cts +0 -170
  137. package/dist/types-cjs/core/types.d.cts +0 -148
  138. package/dist/types-cjs/core/verdict.d.cts +0 -2
  139. package/dist/types-cjs/index.d.cts +0 -10
  140. package/dist/types-cjs/map.d.cts +0 -69
  141. package/dist/types-cjs/package.json +0 -3
  142. package/dist/types-cjs/signals.d.cts +0 -605
  143. package/dist/types-cjs/store/index.d.cts +0 -9
  144. package/dist/types-cjs/store/optimistic.d.cts +0 -45
  145. package/dist/types-cjs/store/projection.d.cts +0 -70
  146. package/dist/types-cjs/store/reconcile.d.cts +0 -46
  147. package/dist/types-cjs/store/store.d.cts +0 -213
  148. package/dist/types-cjs/store/storePath.d.cts +0 -58
  149. package/dist/types-cjs/store/utils.d.cts +0 -114
@@ -0,0 +1,2904 @@
1
+ import { setAttributionHooks } from "./attribution-hooks.js";
2
+
3
+ import { NOT_PENDING, CONFIG_PLUMBING, CONFIG_DERIVED_OVERRIDE } from "./constants.js";
4
+
5
+ import { OBSERVE, liveRootOwners, emitDiagnostic, ownerPath, reportDiagnostic, isSuppressed, anyExcluded, isExcluded, GRAPH_SIZE_WARN_AT, noteFanOut } from "./dev.js";
6
+
7
+ /** A fallback shown for less than this is a flash: feedback for a wait too short to need it. */ const FALLBACK_FLASH_MS = 150;
8
+
9
+ /**
10
+ * Under an owner the observer marked as its own (`OBSERVE.exclude`), or
11
+ * framework plumbing itself (`CONFIG_PLUMBING` — the HMR memo between a
12
+ * component's root and its body, which is nobody's node): the engine records
13
+ * nothing about the node. Plumbing is a bit read and excludes the node alone,
14
+ * not what it owns; the observer exclusion is cached per node once any
15
+ * exists, before that a flag read.
16
+ */ function excludedNode(e) {
17
+ if ((e.C & CONFIG_PLUMBING) !== 0) return true;
18
+ if (!anyExcluded()) return false;
19
+ const n = e;
20
+ if (n.$e === undefined) n.$e = isExcluded(e);
21
+ return n.$e;
22
+ }
23
+
24
+ let attributionActive = false;
25
+
26
+ let changeSeq = 0;
27
+
28
+ let runSeq = 0;
29
+
30
+ const defaultOptions = {
31
+ log: true,
32
+ // Tier-dependent (see `AttributionOptions.values`): dev output is for the
33
+ // developer at the console and shows everything; an observe build is a
34
+ // production artifact and carries no user data unless a holder asks. The
35
+ // literal folds per build — the observe engine ships `"none"` only.
36
+ values: "none",
37
+ checks: true,
38
+ stacks: false,
39
+ historyLimit: 200,
40
+ hotRuns: {
41
+ count: 120,
42
+ windowMs: 1e3
43
+ },
44
+ wideDeps: 30,
45
+ hotTime: {
46
+ budgetMs: 8,
47
+ windowMs: 1e3
48
+ },
49
+ unstableMemos: 4,
50
+ wastedRecompute: {
51
+ minRuns: 5,
52
+ ratio: .8,
53
+ budgetMs: 2,
54
+ windowMs: 1e3
55
+ },
56
+ fanOut: 250,
57
+ waterfalls: {
58
+ minFlightMs: 50
59
+ },
60
+ holds: {
61
+ infoMs: 100,
62
+ warnMs: 200
63
+ },
64
+ longHolds: {
65
+ infoMs: 500,
66
+ warnMs: 1e3
67
+ },
68
+ graphGrowth: {
69
+ visits: 3,
70
+ ratio: 1.25
71
+ },
72
+ abandonedFlights: {
73
+ count: 3,
74
+ windowMs: 1e3
75
+ },
76
+ fallbackFlashes: true,
77
+ optimisticReverts: true,
78
+ stackedHolds: {
79
+ count: 3
80
+ }
81
+ };
82
+
83
+ let options = {
84
+ ...defaultOptions
85
+ };
86
+
87
+ let history = [];
88
+
89
+ /**
90
+ * The engine's records go out on the core's channel, `OBSERVE.records` —
91
+ * the one every runtime emits on — under the types `RecordTypes` declares
92
+ * for it (`rerun`, `create`, `effect`, `flush`, `flight`, `fallback`,
93
+ * `interaction`, `hold`, `navigation`, `graph`), each with the live node as
94
+ * `live` where the record has one. `records.observed(type)` is the
95
+ * pre-check the listener-gated records cost nothing without; the channel
96
+ * is process-wide and the subscriptions on it are the consumer's, so the
97
+ * engine neither holds nor clears listeners of its own.
98
+ */ const records = OBSERVE.records;
99
+
100
+ /** @internal The engine's clock: `performance.now()` where it exists. */ const now = typeof performance !== "undefined" ? () => performance.now() : () => Date.now();
101
+
102
+ const frames = [];
103
+
104
+ const folds = [];
105
+
106
+ /** @internal */ function registerFold(e) {
107
+ folds.push(e);
108
+ }
109
+
110
+ /** @internal Root cause names of a cause chain — the writes/landings/refreshes the chain bottoms out in. */ function rootsOf(e, n) {
111
+ for (const t of e) {
112
+ if (t.kind === "derived" && t.causes && t.causes.length > 0) rootsOf(t.causes, n); else n.add(t.name);
113
+ }
114
+ }
115
+
116
+ function nodeName(e) {
117
+ return e._name ?? "anonymous";
118
+ }
119
+
120
+ /** The record vocabulary for a computation's kind: effects carry a `_type`, memos do not. */ function nodeKind(e) {
121
+ return e.He ? "effect" : "memo";
122
+ }
123
+
124
+ /**
125
+ * Whether a re-run record has an audience — a listener on the channel, an
126
+ * imported fold (`costs`/`feedback`), or the console log. Read at recompute
127
+ * START (the subscription diff needs the deps as they were), so a listener
128
+ * arriving mid-run hears the next one. Without an audience the engine still
129
+ * runs every check and keeps every per-node fact; only the record — its
130
+ * cause list copy, dep diff, previews — is not built, and `history("rerun")`
131
+ * stays empty.
132
+ */ function wantsRerun() {
133
+ return options.log || folds.length > 0 || records.observed("rerun");
134
+ }
135
+
136
+ /**
137
+ * A short preview of a written value for a record — only ever called under
138
+ * `values: "full"` (`stampWrite`, OPTIMISTIC_REVERTED): the other levels
139
+ * carry no previews, and the check is made at the call site so the value is
140
+ * not even looked at.
141
+ */ function preview(e) {
142
+ if (e === null) return "null";
143
+ switch (typeof e) {
144
+ case "undefined":
145
+ return "undefined";
146
+
147
+ case "string":
148
+ return JSON.stringify(e.length > 40 ? e.slice(0, 40) + "…" : e);
149
+
150
+ case "number":
151
+ case "boolean":
152
+ case "bigint":
153
+ return String(e);
154
+
155
+ case "function":
156
+ return "[function]";
157
+
158
+ case "symbol":
159
+ return e.toString();
160
+
161
+ default:
162
+ return Array.isArray(e) ? `Array(${e.length})` : `[${e.constructor?.name ?? "object"}]`;
163
+ }
164
+ }
165
+
166
+ function captureStack() {
167
+ if (!options.stacks) return undefined;
168
+ const e = (new Error).stack?.split("\n") ?? [];
169
+ // Drop the message line and every frame inside the reactive core; the first
170
+ // remaining frames are the user code that performed the write.
171
+ return e.slice(1).filter(e => !/(?:^|[/\\])(?:packages[/\\])?signals[/\\](src|dist)[/\\]/.test(e)).slice(0, 3).map(e => e.trim());
172
+ }
173
+
174
+ /** Sentinel for "no value transition to record" (refresh() stamps). */ const NO_VALUES = Symbol("no-values");
175
+
176
+ // --- Provenance -------------------------------------------------------------
177
+
178
+ // Who performed a write is not a graph fact — the graph only sees the write.
179
+ // The engine keeps an ambient answer: a stack of imperative frames the core
180
+ // announces (effect callbacks, action steps) and the interaction the web
181
+ // runtime declares around event dispatch. A write stamps the innermost frame;
182
+ // frames nested under an interaction carry it. Effects run in a later flush
183
+ // than the click that caused them, so their frame inherits the interaction
184
+ // from the run's cause chain instead (recorded at recomputeEnd).
185
+ const EXTERNAL_ORIGIN = {
186
+ kind: "external"
187
+ };
188
+
189
+ const originFrames = [];
190
+
191
+ /** Per action invocation (keyed by its iterator): the interaction its first step ran under. */ const actionInteractions = new WeakMap;
192
+
193
+ /**
194
+ * The interaction frame the core's `withInteraction` opened (via the
195
+ * `interactionStart`/`interactionEnd` hooks) for the duration of a handler.
196
+ * Frames nest strictly, so the enclosing one is kept on a stack to restore.
197
+ * The core pins the engine per frame: an `interactionEnd` can arrive after
198
+ * `disable()` cleared the stack, so popping an empty stack is tolerated.
199
+ */ let currentInteraction = null;
200
+
201
+ const interactionStack = [];
202
+
203
+ /**
204
+ * The element label an interaction record carries, from the one the runtime
205
+ * described (`tag`, then `#id` or `[name=…]`, then the element's text in
206
+ * quotes — `button#next "Next →"`), cut to what `options.values` allows: the
207
+ * text is the part after the first ` "`; under `"labels"` it stays on a
208
+ * `button` or an `a`, under `"none"` never. The ref's own string is never
209
+ * mutated — the runtime's object is the runtime's.
210
+ */ function targetLabel(e) {
211
+ const n = options.values;
212
+ if (n === "full") return e;
213
+ const t = e.indexOf(' "');
214
+ if (t === -1) return e;
215
+ if (n === "labels") {
216
+ const n = e.slice(0, t);
217
+ const o = n.search(/[#[]/);
218
+ const i = o === -1 ? n : n.slice(0, o);
219
+ if (i === "button" || i === "a") return e;
220
+ }
221
+ return e.slice(0, t);
222
+ }
223
+
224
+ function interactionStart(e) {
225
+ interactionStack.push(currentInteraction);
226
+ // One clock read: the frame opens now; the interaction began at `ref.at`
227
+ // when the runtime dated it (the event's own timestamp), else now too.
228
+ const n = now();
229
+ const t = {
230
+ kind: "interaction",
231
+ name: e.type,
232
+ at: e.at ?? n
233
+ };
234
+ if (e.target) t.target = targetLabel(e.target);
235
+ currentInteraction = t;
236
+ openInteraction(t, n);
237
+ }
238
+
239
+ function interactionEnd(e) {
240
+ const n = currentInteraction;
241
+ currentInteraction = interactionStack.length ? interactionStack.pop() : null;
242
+ if (n !== null) closeInteraction(n, e);
243
+ }
244
+
245
+ /** The interaction an origin runs under (itself, when it is one). */ function interactionOf(e) {
246
+ if (e === undefined) return undefined;
247
+ return e.kind === "interaction" ? e : e.interaction;
248
+ }
249
+
250
+ /** The interaction a cause list traces back to — root writes only, derived links walked. */ function interactionIn(e) {
251
+ for (const n of e) {
252
+ const e = n.kind === "derived" ? n.causes !== undefined ? interactionIn(n.causes) : undefined : interactionOf(n.origin);
253
+ if (e !== undefined) return e;
254
+ }
255
+ return undefined;
256
+ }
257
+
258
+ function currentOrigin() {
259
+ const e = originFrames[originFrames.length - 1];
260
+ if (e !== undefined) return e;
261
+ return currentInteraction ?? EXTERNAL_ORIGIN;
262
+ }
263
+
264
+ /** The root origin a cause list traces back to — the stamp of the nearest root write, derived links walked. */ function originIn(e) {
265
+ for (const n of e) {
266
+ const e = n.kind === "derived" ? n.causes !== undefined ? originIn(n.causes) : undefined : n.origin;
267
+ if (e !== undefined && e.kind !== "external") return e;
268
+ }
269
+ return undefined;
270
+ }
271
+
272
+ /**
273
+ * The `currentOrigin` hook: what a runtime recording its own fact right now
274
+ * (a server-function call) should stamp it with. Inside a recompute the
275
+ * fact belongs to the change that caused the run — a `createAsync` calling
276
+ * the server on a navigation's write is the navigation's, and through it the
277
+ * click's — walked down past create runs the way `trackFlightStart` does,
278
+ * since a node born inside a parent's run inherits the parent's causality.
279
+ * Outside one — or when the causes were themselves external (a memo a
280
+ * handler pulls, stale from a timer's write) — it is the write's answer
281
+ * (`currentOrigin`), minus the external sentinel: "none known" is
282
+ * `undefined` on a record, as `HoldEvent.origin` has it. The objects
283
+ * returned are the engine's own frames, so the caller's record joins
284
+ * `InteractionEvent.origin` / `NavigationEvent.origin` by identity.
285
+ */ function ambientOrigin() {
286
+ for (let e = frames.length - 1; e >= 0; e--) {
287
+ const n = frames[e].causes;
288
+ if (n !== null) {
289
+ const e = originIn(n);
290
+ if (e !== undefined) return e;
291
+ break;
292
+ }
293
+ }
294
+ const e = currentOrigin();
295
+ return e === EXTERNAL_ORIGIN ? undefined : e;
296
+ }
297
+
298
+ const effectFrames = new WeakMap;
299
+
300
+ /**
301
+ * The nodes of the open effect frames, innermost last — parallel to the
302
+ * `effect` entries of `originFrames`, so the frame on top resolves to its
303
+ * node without a map. A stack, not a single slot: a render effect created
304
+ * inside a callback runs its own callback synchronously.
305
+ */ const effectStack = [];
306
+
307
+ /**
308
+ * A write just stamped `origin`. If it is the innermost effect frame (a
309
+ * root write's origin is always the innermost open frame, see `stampWrite`)
310
+ * and no earlier write registered it, register it now with the node on top
311
+ * of the effect stack. An origin that is an effect frame but not the top is
312
+ * inherited — reached through an earlier write's record — and that write
313
+ * registered it.
314
+ */ function noteEffectOrigin(e) {
315
+ if (e.kind !== "effect" || effectFrames.has(e)) return;
316
+ if (originFrames[originFrames.length - 1] !== e) return;
317
+ const n = effectStack[effectStack.length - 1];
318
+ if (n !== undefined) effectFrames.set(e, {
319
+ node: n,
320
+ causes: n.Ke
321
+ });
322
+ }
323
+
324
+ /** The interaction the innermost open frame runs under, else the ambient one. */ function enclosingInteraction() {
325
+ const e = originFrames[originFrames.length - 1];
326
+ return (e !== undefined ? interactionOf(e) : undefined) ?? currentInteraction ?? undefined;
327
+ }
328
+
329
+ function pushFrame(e, n, t, o) {
330
+ const i = {
331
+ kind: e
332
+ };
333
+ if (n) i.name = n;
334
+ const s = t ?? currentInteraction ?? undefined;
335
+ if (s !== undefined) i.interaction = s;
336
+ if (o !== undefined) {
337
+ const e = o;
338
+ if (e.Ye !== undefined) i.run = e.Ye;
339
+ // The frame → node map is filled by the first write inside the callback
340
+ // (noteEffectOrigin), not here: most callbacks never write.
341
+ effectStack.push(o);
342
+ }
343
+ originFrames.push(i);
344
+ }
345
+
346
+ function popFrame(e) {
347
+ // Frames are strictly nested; a mismatch means enable() landed mid-frame
348
+ // (the opener never pushed) — leave the stack alone rather than pop a stranger.
349
+ const n = originFrames[originFrames.length - 1];
350
+ if (n !== undefined && n.kind === e) {
351
+ originFrames.pop();
352
+ if (e === "effect") effectStack.pop();
353
+ }
354
+ }
355
+
356
+ /**
357
+ * `withOrigin` opened a declared frame. The frame object IS the origin every
358
+ * write inside stamps, and the key the navigation record hangs off (see
359
+ * "Navigations" below), so a hold or re-run that later resolves a write's
360
+ * origin lands on the same record. It runs under the interaction of the frame
361
+ * it opened inside — a `navigate()` from an action step, whose ambient
362
+ * interaction is long gone but whose frame remembers it — else the ambient
363
+ * one (a link click's handler).
364
+ */ function originStart(e) {
365
+ // A redirect hop re-enters the pending navigation's frame — the same object,
366
+ // so its writes stamp the same origin and replace the pending write without
367
+ // superseding it (see "Navigations").
368
+ if (e.redirect !== undefined && e.redirect > 0) {
369
+ const n = lastOpenNavigation();
370
+ if (n !== undefined) {
371
+ redirectNavigation(n, e);
372
+ originFrames.push(n.event.origin);
373
+ return;
374
+ }
375
+ }
376
+ const n = {
377
+ kind: e.kind,
378
+ at: e.at ?? now()
379
+ };
380
+ if (e.from !== undefined) n.from = e.from;
381
+ const t = enclosingInteraction();
382
+ if (t !== undefined) n.interaction = t;
383
+ originFrames.push(n);
384
+ openNavigation(n, e);
385
+ }
386
+
387
+ function originEnd() {
388
+ const e = originFrames[originFrames.length - 1];
389
+ popFrame("navigation");
390
+ if (e !== undefined && e.kind === "navigation") closeNavigation(e);
391
+ }
392
+
393
+ /** `click on button#next "Next →"`, `effect "syncTitle"`, `action "save"`, `navigation to /users/:id`, … */ function formatOrigin(e) {
394
+ switch (e.kind) {
395
+ case "interaction":
396
+ return `${e.name} on ${e.target ?? "an element"}`;
397
+
398
+ case "effect":
399
+ return `effect${e.name ? ` "${e.name}"` : ""}`;
400
+
401
+ case "action":
402
+ return `action${e.name ? ` "${e.name}"` : ""}`;
403
+
404
+ case "async":
405
+ return `async landing${e.name ? ` on "${e.name}"` : ""}`;
406
+
407
+ case "navigation":
408
+ {
409
+ // The route pattern is the name consumers group by; the concrete path
410
+ // follows when it adds information, then the destinations a redirect
411
+ // chain abandoned on the way.
412
+ const n = e.name ?? e.to;
413
+ if (n === undefined) return "navigation";
414
+ const t = [];
415
+ if (e.to !== undefined && e.to !== n) t.push(e.to);
416
+ const o = navStates.get(e)?.event.redirects;
417
+ if (o !== undefined) t.push(`redirected from ${o.map(e => e.to ?? e.name ?? "?").join(" → ")}`);
418
+ return `navigation to ${n}${t.length > 0 ? ` (${t.join(", ")})` : ""}`;
419
+ }
420
+
421
+ default:
422
+ return "outside the reactive system";
423
+ }
424
+ }
425
+
426
+ /** Record a root change (setSignal / refresh / async landing) on the node. */
427
+ /** Live subscriber count, walked on demand — the core keeps no counter. */ function countSubscribers(e) {
428
+ let n = 0;
429
+ for (let t = e.u; t !== null; t = t.Pe) n++;
430
+ return n;
431
+ }
432
+
433
+ /**
434
+ * HUGE_FAN_OUT from the engine's lower `fanOut` threshold (see dev.ts): a
435
+ * committed root invalidation reaching hundreds of subscribers re-runs all
436
+ * of them this flush. Counts the subscriber list itself (an engine-only
437
+ * walk, on the write; the core keeps no per-node count — a live `_subCount`
438
+ * was a post-construction field that forked node shapes). Stops at
439
+ * GRAPH_SIZE_WARN_AT, where the always-on core check takes over, so the two
440
+ * never fire for the same write; the once-per-node dedupe is the core's.
441
+ */ function checkFanOut(e, n) {
442
+ const t = options.fanOut;
443
+ if (typeof t !== "number") return;
444
+ const o = countSubscribers(e);
445
+ if (o < t || o >= GRAPH_SIZE_WARN_AT) return;
446
+ noteFanOut(e, o, n);
447
+ }
448
+
449
+ function stampWrite(e, n, t = NO_VALUES, o = NO_VALUES) {
450
+ const i = {
451
+ seq: ++changeSeq,
452
+ kind: n,
453
+ name: nodeName(e),
454
+ nodeId: devId(e)
455
+ };
456
+ // The previews are the record's one look at the written values: under
457
+ // any level but `"full"` they are not taken, so the record never carries
458
+ // them (nor does the `HeldWrite` copied from it, nor a sentence built on it).
459
+ if (o !== NO_VALUES && options.values === "full") {
460
+ i.prev = t === NO_VALUES ? undefined : preview(t);
461
+ i.value = preview(o);
462
+ }
463
+ i.origin = n === "async" ? asyncOrigin(e) : currentOrigin();
464
+ i.at = now();
465
+ i.stack = captureStack();
466
+ const s = e.ze;
467
+ e.ze = i;
468
+ noteNavigationWrite(s, i);
469
+ noteInteractionWrite(i.origin, excludedNode(e));
470
+ if (n === "write") trackEffectWrite(e, i, o);
471
+ // stampWrite is the single funnel for committed root invalidations (sync
472
+ // writes, refresh(), async landings), which makes it the one place the
473
+ // engine's fan-out check needs to live.
474
+ checkFanOut(e, n);
475
+ }
476
+
477
+ /** Record a derived change (memo produced a new value) with its causes. */ function stampDerived(e, n) {
478
+ e.ze = {
479
+ seq: ++changeSeq,
480
+ kind: "derived",
481
+ name: nodeName(e),
482
+ nodeId: devId(e),
483
+ causes: n
484
+ };
485
+ }
486
+
487
+ /**
488
+ * Collect the deps whose committed change is newer than this node's previous
489
+ * run. Called at recompute entry, while `_deps` still holds the previous
490
+ * run's links. A refresh() stamp on the node itself also counts — that is a
491
+ * self-invalidation, not a dep change.
492
+ */ function collectCauses(e) {
493
+ const n = e.Xe ?? 0;
494
+ const t = [];
495
+ const o = e.ze;
496
+ if (o !== undefined && o.seq > n && o.kind === "refresh") t.push(o);
497
+ for (let o = e.Ee; o !== null; o = o.Ie) {
498
+ const e = o.De.ze;
499
+ if (e !== undefined && e.seq > n) t.push(e);
500
+ }
501
+ return t;
502
+ }
503
+
504
+ /** Advance the node's seen-cursor to the present. Call after every run. */ function markSeen(e) {
505
+ e.Xe = changeSeq;
506
+ }
507
+
508
+ /**
509
+ * Snapshot the dep identities of the node's last pass (call before a run
510
+ * replaces them, or after it to read the fresh set). The validated prefix
511
+ * [`_deps`..`_depsTail`] is that pass's set; links past the tail are a
512
+ * previous pass's, kept linked while the frame they fed is still the
513
+ * committed one (A30 — a staged memo pass, or an effect pass whose run is
514
+ * still owed) and not part of the subscription diff.
515
+ */ function captureDeps(e) {
516
+ const n = [];
517
+ for (let t = e.Ee; t !== null; t = t.Ie) {
518
+ n.push(t.De);
519
+ if (t === e.Je) break;
520
+ }
521
+ return n;
522
+ }
523
+
524
+ /**
525
+ * Wide-scope warning — the coarse-read / helper-leak signature: one scope
526
+ * subscribed to dozens of sources re-runs when ANY of them change. Fired from
527
+ * recordRerun for re-runs and directly from recompute for creation runs (a
528
+ * memo can be born too wide). Re-warns only on 50% further growth.
529
+ */ function checkDepWidth(e) {
530
+ const n = options.wideDeps;
531
+ if (n === false) return;
532
+ let t = 0;
533
+ const o = [];
534
+ for (let n = e.Ee; n !== null; n = n.Ie) {
535
+ t++;
536
+ if (o.length < 12) o.push(nodeName(n.De));
537
+ if (n === e.Je) break;
538
+ // the validated prefix, as captureDeps
539
+ }
540
+ const i = e;
541
+ if (t < n || t < (i.en ?? 0) * 1.5) return;
542
+ i.en = t;
543
+ const s = `[WIDE_SCOPE_DEPS] ${nodeKind(e)} "${nodeName(e)}" is subscribed to ${t} sources — ` + `it re-runs when any of them change. Narrow its reads or split it into smaller memos. ` + `Sources: ${o.join(", ")}${t > o.length ? ", …" : ""}`;
544
+ reportDiagnostic(emitDiagnostic({
545
+ code: "WIDE_SCOPE_DEPS",
546
+ kind: "perf",
547
+ severity: "warn",
548
+ message: s,
549
+ nodeName: nodeName(e),
550
+ data: {
551
+ depCount: t,
552
+ deps: o
553
+ }
554
+ }, e));
555
+ }
556
+
557
+ const hotCauses = new Map;
558
+
559
+ const HOT_FANOUT_FIRST_MILESTONE = 5;
560
+
561
+ /**
562
+ * Hot-scope warning — flags a scope that re-ran more than `count` times
563
+ * inside one `windowMs` window. Warned once per window, with the most recent
564
+ * cause chain named so the leaking signal is identified in the message.
565
+ * Fan-out spam is folded per root cause (see HotCauseWindow above).
566
+ */ function checkHotRuns(e, n) {
567
+ const t = options.hotRuns;
568
+ if (t === false) return;
569
+ const o = e;
570
+ const i = Date.now();
571
+ if (o.nn === undefined || i - o.nn > t.windowMs) {
572
+ o.nn = i;
573
+ o.tn = 0;
574
+ o.sn = false;
575
+ }
576
+ o.tn = (o.tn ?? 0) + 1;
577
+ if (o.sn || o.tn < t.count) return;
578
+ o.sn = true;
579
+ // Root-cause key: the set of originating writes behind this scope's latest
580
+ // re-run. Scopes hot from the SAME roots share one aggregation window.
581
+ const s = new Set;
582
+ rootsOf(n, s);
583
+ const r = s.size > 0 ? [ ...s ].sort().join(", ") : "(untracked)";
584
+ let a = hotCauses.get(r);
585
+ if (a === undefined || i - a.winStart > t.windowMs) {
586
+ a = {
587
+ winStart: i,
588
+ scopes: 0,
589
+ runs: 0,
590
+ nextMilestone: HOT_FANOUT_FIRST_MILESTONE
591
+ };
592
+ hotCauses.set(r, a);
593
+ }
594
+ a.scopes++;
595
+ a.runs += o.tn;
596
+ if (a.scopes === 1) {
597
+ const s = n.map(e => `"${e.name}" (${e.kind})`).join(", ");
598
+ const r = `[HOT_SCOPE_RERUNS] ${nodeKind(e)} "${nodeName(e)}" re-ran ${o.tn} times ` + `in ${Math.max(1, i - o.nn)}ms — a hot signal is likely leaking into this ` + `scope. Latest cause: ${s || "(untracked pull)"}`;
599
+ reportDiagnostic(emitDiagnostic({
600
+ code: "HOT_SCOPE_RERUNS",
601
+ kind: "perf",
602
+ severity: "warn",
603
+ message: r,
604
+ nodeName: nodeName(e),
605
+ data: {
606
+ runs: o.tn,
607
+ windowMs: t.windowMs,
608
+ causes: n.map(e => e.name)
609
+ }
610
+ }, e));
611
+ return;
612
+ }
613
+ // Additional scopes hot from the same cause: silent until a milestone —
614
+ // the culprit is the cause, and it has already been named once.
615
+ if (a.scopes < a.nextMilestone) return;
616
+ a.nextMilestone *= 10;
617
+ const c = `[HOT_SCOPE_FANOUT] ${a.scopes} scopes have gone hot (${a.runs} re-runs) within ` + `${t.windowMs}ms, all driven by ${r} — one hot cause is re-running a large part ` + `of the graph. Per-scope warnings are suppressed; fix the cause. If consumers ask keyed ` + `questions of it, invert it: a store used as a map keyed by id, one key per consumer.`;
618
+ // The subject is the shared CAUSE, not this victim scope — no single owner
619
+ // path locates it, so the event carries none.
620
+ reportDiagnostic(emitDiagnostic({
621
+ code: "HOT_SCOPE_FANOUT",
622
+ kind: "perf",
623
+ severity: "warn",
624
+ message: c,
625
+ nodeName: r,
626
+ data: {
627
+ cause: r,
628
+ scopes: a.scopes,
629
+ runs: a.runs,
630
+ windowMs: t.windowMs
631
+ }
632
+ }, null));
633
+ }
634
+
635
+ /**
636
+ * Time-budget warning — the counterpart of checkHotRuns for the
637
+ * few-but-expensive scope: warns when one scope's summed self-time within a
638
+ * window exceeds the budget. Warned once per window.
639
+ */ function checkHotTime(e, n, t) {
640
+ const o = options.hotTime;
641
+ if (o === false) return;
642
+ const i = e;
643
+ const s = now();
644
+ if (i.rn === undefined || s - i.rn > o.windowMs) {
645
+ i.rn = s;
646
+ i.an = 0;
647
+ i.cn = false;
648
+ }
649
+ i.an = (i.an ?? 0) + n;
650
+ if (i.cn || i.an < o.budgetMs) return;
651
+ i.cn = true;
652
+ const r = t.map(e => `"${e.name}" (${e.kind})`).join(", ");
653
+ const a = `[HOT_SCOPE_TIME] ${nodeKind(e)} "${nodeName(e)}" spent ` + `${i.an.toFixed(1)}ms of compute inside one ${o.windowMs}ms window ` + `(budget ${o.budgetMs}ms). Latest cause: ${r || "(untracked pull)"}`;
654
+ reportDiagnostic(emitDiagnostic({
655
+ code: "HOT_SCOPE_TIME",
656
+ kind: "perf",
657
+ severity: "warn",
658
+ message: a,
659
+ nodeName: nodeName(e),
660
+ data: {
661
+ spentMs: i.an,
662
+ budgetMs: o.budgetMs,
663
+ windowMs: o.windowMs,
664
+ causes: t.map(e => e.name)
665
+ }
666
+ }, e));
667
+ }
668
+
669
+ /**
670
+ * A scope whose equality gate closes almost every time: it re-ran because
671
+ * an input changed, computed, compared equal to its last value and told
672
+ * nobody — the run was pure cost. `costs().wastedMs` sums this; the finding
673
+ * names it while it happens, with the input that keeps triggering it. The
674
+ * fix is upstream: an equality boundary on the part of the input the scope
675
+ * depends on, or a narrower read. Plain runs only — a held or overlay run
676
+ * may be replayed and is never blamed as waste.
677
+ */ function checkWastedRecompute(e, n, t, o, i, s) {
678
+ const r = options.wastedRecompute;
679
+ if (r === false || t !== "plain") return;
680
+ // This runs on every re-run: fields on the node (one property read each,
681
+ // like hotRuns) and the run's own `at` — no clock read, no map lookup.
682
+ const a = e;
683
+ if (a.dn === undefined || n - a.dn > r.windowMs) {
684
+ a.dn = n;
685
+ a.fn = 0;
686
+ a.un = 0;
687
+ a.ln = 0;
688
+ a.hn = false;
689
+ }
690
+ a.fn = a.fn + 1;
691
+ if (!o) {
692
+ a.un = a.un + 1;
693
+ a.ln = a.ln + i;
694
+ }
695
+ if (a.hn || a.fn < r.minRuns || a.un / a.fn < r.ratio || a.ln < r.budgetMs) return;
696
+ a.hn = true;
697
+ const c = {
698
+ runs: a.fn,
699
+ wasted: a.un,
700
+ wastedMs: a.ln
701
+ };
702
+ const d = s.map(e => `"${e.name}" (${e.kind})`).join(", ");
703
+ const f = `[WASTED_RECOMPUTE] ${nodeKind(e)} "${nodeName(e)}" re-ran ${c.runs} times in ` + `${r.windowMs}ms and ${c.wasted} of those produced the same value — ` + `${c.wastedMs.toFixed(1)}ms of compute the equality gate then discarded. Its inputs ` + `change without changing its result: put an equality boundary upstream (a memo over the ` + `part of the input it reads, or an \`equals\` on the source), or read a narrower slice ` + `(the property, not the object). Latest cause: ${d || "(untracked pull)"}`;
704
+ reportDiagnostic(emitDiagnostic({
705
+ code: "WASTED_RECOMPUTE",
706
+ kind: "perf",
707
+ severity: "warn",
708
+ message: f,
709
+ nodeName: nodeName(e),
710
+ data: {
711
+ runs: c.runs,
712
+ wasted: c.wasted,
713
+ wastedMs: c.wastedMs,
714
+ windowMs: r.windowMs,
715
+ causes: s.map(e => e.name)
716
+ }
717
+ }, e));
718
+ }
719
+
720
+ function recordRerun(e, n, t, o, i, s) {
721
+ const r = n.causes;
722
+ const a = e;
723
+ const c = a.Ke;
724
+ const d = n.interaction;
725
+ if (excludedNode(e)) {
726
+ // The observer's own computation: keep the per-node bookkeeping its
727
+ // effect phase reads (see effectRunStart) and record nothing.
728
+ a.pn = d;
729
+ a.Ye = undefined;
730
+ a.Ke = r;
731
+ return;
732
+ }
733
+ // The facts every run leaves on the node, record or not: the run sequence
734
+ // (`ChangeOrigin.run` joins an effect-phase write to it), the run count,
735
+ // and what the effect phase inherits — it runs later in the flush with no
736
+ // cause list of its own, so it takes this run's interaction and causes
737
+ // (see effectRunStart / pushFrame).
738
+ const f = ++runSeq;
739
+ const u = a.mn = (a.mn ?? 0) + 1;
740
+ a.pn = d;
741
+ a.Ye = f;
742
+ a.Ke = r;
743
+ noteInteractionRun(d, t.selfMs, false);
744
+ if (openFlush !== null) noteFlushRun(openFlush, false, d);
745
+ // The checks read the facts, not the record, so they run with or without
746
+ // an audience for it.
747
+ const l = nodeKind(e);
748
+ if (l === "effect") checkEffectCycle(e, r);
749
+ checkRelayTear(e, r, c);
750
+ checkHotRuns(e, r);
751
+ checkHotTime(e, t.selfMs, r);
752
+ checkWastedRecompute(e, n.start, i, o, t.selfMs, r);
753
+ checkDepWidth(e);
754
+ // The record: built only when something wanted it at run start (see
755
+ // `wantsRerun`) — a listener, a fold, the log.
756
+ const h = n.prevDeps;
757
+ if (h === null) return;
758
+ // Subscription diff: `prevDeps` was captured at run entry; `_deps` now
759
+ // holds the fresh set. A changed set is the "helper edit changed distant
760
+ // call sites" signal — surfaced per-event and in the console format.
761
+ const p = captureDeps(e);
762
+ const m = new Set(h);
763
+ const g = new Set(p);
764
+ const w = [];
765
+ const v = [];
766
+ for (const e of p) if (!m.has(e)) w.push(nodeName(e));
767
+ for (const e of h) if (!g.has(e)) v.push(nodeName(e));
768
+ const k = {
769
+ run: f,
770
+ at: n.start,
771
+ nodeRuns: u,
772
+ nodeKind: l,
773
+ nodeName: nodeName(e),
774
+ nodeId: devId(e),
775
+ causes: r,
776
+ depCount: p.length,
777
+ depsAdded: w,
778
+ depsRemoved: v,
779
+ selfMs: t.selfMs,
780
+ totalMs: t.totalMs,
781
+ changed: o,
782
+ phase: i,
783
+ held: s
784
+ };
785
+ if (d !== undefined) k.interaction = d;
786
+ history.push(k);
787
+ if (history.length > options.historyLimit) history.shift();
788
+ for (const n of folds) n.rerun?.(e, k);
789
+ records.emit("rerun", k, e);
790
+ if (options.log) logRerun(k);
791
+ }
792
+
793
+ function formatCause(e, n, t) {
794
+ const o = " ".repeat(n + 1);
795
+ let i = `${o}← ${e.kind === "derived" ? "memo" : "signal"} "${e.name}" ${e.kind === "derived" ? "changed" : e.kind} (#${e.seq})`;
796
+ if (e.prev !== undefined) i += ` ${e.prev} → ${e.value}`;
797
+ if (e.origin !== undefined && e.origin.kind !== "external") {
798
+ i += ` — ${formatOrigin(e.origin)}`;
799
+ const n = e.origin.interaction;
800
+ if (n !== undefined) i += ` (under ${formatOrigin(n)})`;
801
+ }
802
+ t.push(i);
803
+ if (e.stack) for (const n of e.stack) t.push(`${o} ${n}`);
804
+ if (e.causes && n < 10) {
805
+ for (const o of e.causes) formatCause(o, n + 1, t);
806
+ }
807
+ }
808
+
809
+ function formatRerun(e) {
810
+ const n = [ `[why-run] ${e.nodeKind} "${e.nodeName}" ran (run ${e.nodeRuns}, ` + `${e.selfMs.toFixed(2)}ms${e.changed ? "" : ", unchanged"}` + `${e.phase === "plain" ? "" : `, ${e.phase}`}${e.held ? ", held" : ""})` + (e.causes.length === 0 ? " — no tracked cause (pull or retry)" : "") ];
811
+ for (const t of e.causes) formatCause(t, 0, n);
812
+ if (e.depsAdded.length > 0 || e.depsRemoved.length > 0) {
813
+ const t = [ ...e.depsAdded.map(e => `+"${e}"`), ...e.depsRemoved.map(e => `-"${e}"`) ].join(" ");
814
+ n.push(` deps changed: ${t} (${e.depCount} total)`);
815
+ }
816
+ return n.join("\n");
817
+ }
818
+
819
+ /**
820
+ * Console face of a re-run: the headline as a collapsed group with the
821
+ * why-chain and dep delta inside, so a busy console stays scannable (one line
822
+ * per run, evidence a click away). Consoles without grouping get the text.
823
+ */ function logRerun(e) {
824
+ const n = formatRerun(e);
825
+ const t = n.indexOf("\n");
826
+ if (t === -1 || typeof console.groupCollapsed !== "function") {
827
+ console.log(n);
828
+ return;
829
+ }
830
+ console.groupCollapsed(n.slice(0, t));
831
+ console.log(n.slice(t + 1));
832
+ console.groupEnd();
833
+ }
834
+
835
+ /**
836
+ * Values eligible for the unstable-output check: plain objects and arrays
837
+ * only. Promises, iterators, Dates, Maps, class instances etc. all have no
838
+ * (or unrepresentative) own enumerable keys, so a shallow compare would
839
+ * false-positive on them — a fresh Promise is a genuinely new value.
840
+ */ function isPlainShape(e) {
841
+ if (e === null || typeof e !== "object") return false;
842
+ if (Array.isArray(e)) return true;
843
+ const n = Object.getPrototypeOf(e);
844
+ return n === Object.prototype || n === null;
845
+ }
846
+
847
+ /** Shallow structural equivalence, capped so hot paths stay cheap. */ const UNSTABLE_KEY_CAP = 64;
848
+
849
+ function shallowEquivalent(e, n) {
850
+ const t = Array.isArray(e);
851
+ if (t !== Array.isArray(n)) return false;
852
+ if (t) {
853
+ const t = e;
854
+ const o = n;
855
+ if (t.length !== o.length || t.length > UNSTABLE_KEY_CAP) return false;
856
+ for (let e = 0; e < t.length; e++) if (t[e] !== o[e]) return false;
857
+ return true;
858
+ }
859
+ const o = Object.keys(e);
860
+ if (o.length > UNSTABLE_KEY_CAP || o.length !== Object.keys(n).length) return false;
861
+ for (const t of o) {
862
+ if (!(t in n) || e[t] !== n[t]) return false;
863
+ }
864
+ return true;
865
+ }
866
+
867
+ /**
868
+ * Unstable-output warning — the fan-out amplifier signature: a memo whose
869
+ * committed value is referentially new but structurally identical run after
870
+ * run has an equality gate that never closes, so ALL its subscribers re-run
871
+ * on EVERY upstream change. Checked only on plain (non-overlay) changed runs;
872
+ * a genuinely different value (or a non-plain shape) resets the streak.
873
+ */ function checkUnstableOutput(e, n, t) {
874
+ const o = options.unstableMemos;
875
+ // typeof guard: an explicit `unstableMemos: undefined` in enable() options
876
+ // clobbers the default through the spread — treat any non-number as off.
877
+ if (typeof o !== "number") return;
878
+ const i = e;
879
+ if (n === t || // paranoia: changed runs should never hit this
880
+ !isPlainShape(n) || !isPlainShape(t) || !shallowEquivalent(n, t)) {
881
+ i.gn = 0;
882
+ i.wn = false;
883
+ return;
884
+ }
885
+ i.gn = (i.gn ?? 0) + 1;
886
+ if (i.wn || i.gn < o) return;
887
+ i.wn = true;
888
+ const s = Array.isArray(t) ? "array" : "object";
889
+ const r = `[UNSTABLE_MEMO_OUTPUT] memo "${nodeName(e)}" produced a new-but-equivalent ${s} on ` + `${i.gn} consecutive runs — its equality gate never closes, so every ` + `subscriber re-runs on every upstream change. Return stable references or pass an ` + `\`equals\` option.`;
890
+ reportDiagnostic(emitDiagnostic({
891
+ code: "UNSTABLE_MEMO_OUTPUT",
892
+ kind: "perf",
893
+ severity: "warn",
894
+ message: r,
895
+ nodeName: nodeName(e),
896
+ data: {
897
+ runs: i.gn,
898
+ shape: s
899
+ }
900
+ }, e));
901
+ }
902
+
903
+ const EFFECT_CYCLE_MAX_HOPS = 6;
904
+
905
+ const reportedCycles = new Set;
906
+
907
+ let nextDevId = 0;
908
+
909
+ const devIds = new WeakMap;
910
+
911
+ function devId(e) {
912
+ let n = devIds.get(e);
913
+ if (n === undefined) devIds.set(e, n = ++nextDevId);
914
+ return n;
915
+ }
916
+
917
+ /** @internal The id the engine's records name `node` by, if it has one yet — read without assigning. */ function nodeIdOf(e) {
918
+ return devIds.get(e);
919
+ }
920
+
921
+ function rootWrites(e, n) {
922
+ for (const t of e) {
923
+ if (t.kind === "derived") {
924
+ if (t.causes !== undefined) rootWrites(t.causes, n);
925
+ } else n.push(t);
926
+ }
927
+ }
928
+
929
+ /**
930
+ * The effect writes leading from an earlier run of `target` to the run whose
931
+ * `causes` these are, in causal order (target's own write first), or null.
932
+ */ function findEffectCycle(e, n, t, o) {
933
+ const i = [];
934
+ rootWrites(n, i);
935
+ for (const n of i) {
936
+ const i = n.origin;
937
+ if (i === undefined || i.kind !== "effect") continue;
938
+ const s = effectFrames.get(i);
939
+ if (s === undefined) continue;
940
+ if (s.node === e) return [ {
941
+ effect: s.node,
942
+ write: n
943
+ } ];
944
+ if (o >= EFFECT_CYCLE_MAX_HOPS || t.has(s.node) || s.causes === undefined) continue;
945
+ t.add(s.node);
946
+ const r = findEffectCycle(e, s.causes, t, o + 1);
947
+ if (r !== null) {
948
+ r.push({
949
+ effect: s.node,
950
+ write: n
951
+ });
952
+ return r;
953
+ }
954
+ }
955
+ return null;
956
+ }
957
+
958
+ /** Names of the memos between a direct cause of a run and `write`, root-first. */ function derivedPath(e, n, t) {
959
+ for (const o of e) {
960
+ if (o === n) return true;
961
+ if (o.kind === "derived" && o.causes !== undefined) {
962
+ t.unshift(o.name);
963
+ if (derivedPath(o.causes, n, t)) return true;
964
+ t.shift();
965
+ }
966
+ }
967
+ return false;
968
+ }
969
+
970
+ function describeWrite(e) {
971
+ if (e.kind === "refresh") return `refreshed "${e.name}"`;
972
+ const n = e.prev !== undefined ? ` (${e.prev} → ${e.value})` : "";
973
+ return `wrote "${e.name}"${n}`;
974
+ }
975
+
976
+ function checkEffectCycle(e, n) {
977
+ const t = findEffectCycle(e, n, new Set([ e ]), 0);
978
+ if (t === null) return;
979
+ const o = t.map(e => devId(e.effect)).sort((e, n) => e - n).join(",");
980
+ if (reportedCycles.has(o)) return;
981
+ reportedCycles.add(o);
982
+ const i = t.length + 1;
983
+ let s;
984
+ if (t.length === 1) {
985
+ const [{write: o}] = t;
986
+ const i = [];
987
+ derivedPath(n, o, i);
988
+ const r = i.length > 0 ? ` through ${i.map(e => `memo "${e}"`).join(" → ")}` : "";
989
+ s = `[EFFECT_WRITES_OWN_SOURCE] effect "${nodeName(e)}" re-ran because of its own write: it ` + `${describeWrite(o)}, which fed back into its inputs${r}. Two flushes to settle, ` + `and the screen rendered the pre-write value in between. The written value is a function ` + `of what the effect reads — compute it in a memo (or normalize where the source is ` + `written) instead of correcting it after the fact.`;
990
+ } else {
991
+ const e = t.map(e => `"${nodeName(e.effect)}"`);
992
+ const n = t.map((n, t) => `effect ${e[t]}${t > 0 ? " re-ran and" : ""} ${describeWrite(n.write)}`).join("; ");
993
+ s = `[EFFECT_WRITES_OWN_SOURCE] effects ${[ ...e, e[0] ].join(" → ")} relay writes in a ` + `cycle: ${n}; which fed back into effect ${e[0]}'s inputs — ${i} flushes to ` + `settle after each change, each rendering an intermediate state. Every relayed value is a ` + `function of the original inputs: derive them in memos and drop the writes.`;
994
+ }
995
+ const r = t.length === 1 ? "warn" : "info";
996
+ emitDiagnostic({
997
+ code: "EFFECT_WRITES_OWN_SOURCE",
998
+ kind: "perf",
999
+ severity: r,
1000
+ message: s,
1001
+ nodeName: nodeName(e),
1002
+ data: {
1003
+ effects: t.map(e => nodeName(e.effect)),
1004
+ writes: t.map(e => ({
1005
+ effect: nodeName(e.effect),
1006
+ kind: e.write.kind,
1007
+ name: e.write.name,
1008
+ prev: e.write.prev,
1009
+ value: e.write.value
1010
+ })),
1011
+ flushes: i
1012
+ }
1013
+ }, e);
1014
+ }
1015
+
1016
+ const RELAY_WARN_AT = 3;
1017
+
1018
+ const relays = new Map;
1019
+
1020
+ const copyWrites = new WeakSet;
1021
+
1022
+ const copyReported = new WeakSet;
1023
+
1024
+ /** The node each root write record was stamped on (records are serializable and cannot hold it). */ const recordNodes = new WeakMap;
1025
+
1026
+ /**
1027
+ * Write-side bookkeeping for the relay heuristics: who has written this
1028
+ * signal, and whether an effect just copied its compute output into it.
1029
+ */ function trackEffectWrite(e, n, t) {
1030
+ const o = e;
1031
+ const i = n.origin;
1032
+ if (i !== undefined) noteEffectOrigin(i);
1033
+ const s = i !== undefined && i.kind === "effect" ? effectFrames.get(i) : undefined;
1034
+ const r = s === undefined ? 0 : devId(s.node);
1035
+ recordNodes.set(n, e);
1036
+ o.vn = o.vn === undefined || o.vn === r ? r : null;
1037
+ if (s !== undefined && t !== undefined && t === s.node.ce) {
1038
+ copyWrites.add(n);
1039
+ o.kn = o.Sn === r ? (o.kn ?? 0) + 1 : 1;
1040
+ o.Sn = r;
1041
+ if (o.kn >= 2 && o.vn === r) checkCopyEffect(s.node, e);
1042
+ } else o.kn = 0;
1043
+ }
1044
+
1045
+ /** The effect's source whose current value the compute output is, if any (the prop-to-state port). */ function passthroughSource(e) {
1046
+ for (let n = e.Ee; n !== null; n = n.Ie) if (n.De.ce === e.ce) return nodeName(n.De);
1047
+ return undefined;
1048
+ }
1049
+
1050
+ /** The repair for a write that is the effect's compute output. */ function copyRepair(e, n) {
1051
+ const t = passthroughSource(e);
1052
+ return t !== undefined ? `The written value is "${t}" itself: read "${t}" where "${n}" is read ` + `(or createMemo it if a stable derivation is needed) and delete the effect.` : `The written value is the effect's compute output — by contract a pure function of ` + `what it tracks: make "${n}" a memo of that computation and delete the effect.`;
1053
+ }
1054
+
1055
+ function checkCopyEffect(e, n) {
1056
+ if (copyReported.has(n)) return;
1057
+ copyReported.add(n);
1058
+ const t = nodeName(n);
1059
+ const o = `[EFFECT_RELAY_TEAR] effect "${nodeName(e)}" writes its compute output into ` + `"${t}" on every run, and nothing else writes "${t}" — it is derived state kept ` + `one flush late: everything reading it paints a frame behind everything reading the ` + `source. ${copyRepair(e, t)}`;
1060
+ reportDiagnostic(emitDiagnostic({
1061
+ code: "EFFECT_RELAY_TEAR",
1062
+ kind: "perf",
1063
+ severity: "warn",
1064
+ message: o,
1065
+ nodeName: nodeName(e),
1066
+ data: {
1067
+ relay: nodeName(e),
1068
+ wrote: t,
1069
+ copy: true,
1070
+ passthrough: passthroughSource(e) ?? null,
1071
+ soleWriter: true
1072
+ }
1073
+ }, e));
1074
+ }
1075
+
1076
+ /**
1077
+ * `victim` re-ran with `causes`; its previous run had `prevCauses`. A tear is
1078
+ * a re-run whose root writes ALL came from effects (no independent outside
1079
+ * cause) and at least one of which was made by a run that shares a root
1080
+ * write with the victim's previous run.
1081
+ */ function checkRelayTear(e, n, t) {
1082
+ if (t === undefined || n.length === 0) return;
1083
+ const o = [];
1084
+ rootWrites(n, o);
1085
+ if (o.length === 0) return;
1086
+ let i;
1087
+ let s;
1088
+ let r;
1089
+ for (const n of o) {
1090
+ const o = n.origin;
1091
+ if (o === undefined || o.kind !== "effect") return;
1092
+ const a = effectFrames.get(o);
1093
+ // Own-source cycles are EFFECT_WRITES_OWN_SOURCE's; a create-run relay
1094
+ // is initial sync, not a tear for one change.
1095
+ if (a === undefined || a.node === e || a.causes === undefined) return;
1096
+ if (r === undefined) {
1097
+ const e = [];
1098
+ rootWrites(a.causes, e);
1099
+ const o = [];
1100
+ rootWrites(t, o);
1101
+ const c = e.find(e => o.includes(e));
1102
+ if (c !== undefined) {
1103
+ r = c;
1104
+ i = a;
1105
+ s = n;
1106
+ }
1107
+ }
1108
+ }
1109
+ if (r === undefined || i === undefined || s === undefined) return;
1110
+ const a = `${devId(i.node)}:${s.name}`;
1111
+ let c = relays.get(a);
1112
+ if (c === undefined) relays.set(a, c = {
1113
+ count: 0,
1114
+ warned: false
1115
+ });
1116
+ c.count++;
1117
+ const d = copyWrites.has(s);
1118
+ const f = recordNodes.get(s);
1119
+ const u = f !== undefined && f.vn === devId(i.node);
1120
+ // Derivable outright: the value is the compute output and nothing else
1121
+ // writes the signal. A copy INTO a signal that has other writers is the
1122
+ // "reset editable state from a source" shape — the tear is real, but a memo
1123
+ // is not the answer, so it stays advisory like any other non-derivable tear.
1124
+ const l = d && u;
1125
+ const h = l || c.count >= RELAY_WARN_AT ? "warn" : "info";
1126
+ // First sighting always reports (advisory); afterwards only the escalation.
1127
+ if (c.count > 1 && (h !== "warn" || c.warned)) return;
1128
+ // One verdict per derivable signal: the copy report (checkCopyEffect) and
1129
+ // the tear report carry the same repair.
1130
+ if (l && f !== undefined) {
1131
+ if (copyReported.has(f)) return;
1132
+ copyReported.add(f);
1133
+ }
1134
+ if (h === "warn") c.warned = true;
1135
+ const p = e.He ? "effect" : "memo";
1136
+ const m = nodeName(i.node);
1137
+ const g = l ? copyRepair(i.node, s.name) : d ? `The written value is the effect's compute output, but "${s.name}" has other ` + `writers — editable state reset from a source. If the reset is the intent, the tear ` + `is its cost; if "${s.name}" only ever mirrors the source, drop the local copy ` + `and read the source.` : u ? `Nothing else writes "${s.name}" — it is derived state: make it a memo over what ` + `the effect reads and every reader gets it in the same flush.` : `If "${s.name}" is computed from what the effect reads, make it a memo so readers ` + `get it in the same flush; if the write reads something outside the graph (layout, ` + `time), the tear is the cost of measuring.`;
1138
+ const w = `[EFFECT_RELAY_TEAR] ${p} "${nodeName(e)}" ran twice for one write of ` + `"${r.name}": once in the flush where "${r.name}" changed, and again after ` + `effect "${m}" relayed it by writing "${s.name}" — the first frame showed the ` + `new "${r.name}" with the stale "${s.name}"` + (c.count > 1 ? ` (${c.count} times so far)` : "") + `. ${g}`;
1139
+ emitDiagnostic({
1140
+ code: "EFFECT_RELAY_TEAR",
1141
+ kind: "perf",
1142
+ severity: h,
1143
+ message: w,
1144
+ nodeName: nodeName(e),
1145
+ data: {
1146
+ victim: nodeName(e),
1147
+ root: r.name,
1148
+ relay: m,
1149
+ wrote: s.name,
1150
+ copy: d,
1151
+ passthrough: d ? passthroughSource(i.node) ?? null : null,
1152
+ soleWriter: u,
1153
+ occurrences: c.count
1154
+ }
1155
+ }, e);
1156
+ }
1157
+
1158
+ // --- Immutable updates in stores ---------------------------------------------
1159
+
1160
+ // `draft.user = { ...draft.user, name }` / `draft.items = [...draft.items,
1161
+ // x]` / `draft.items = draft.items.filter(...)` — the React habit of
1162
+ // producing a fresh container to change one leaf. The store tracks leaves, so
1163
+ // a fresh container is pure cost: every reader of `user` (any path below it)
1164
+ // re-runs for the one leaf that moved, where a draft mutation would re-run
1165
+ // only the readers of `name`. The store's notify sees both containers at the
1166
+ // write and reports a leaf census (identity on unwrapped values, capped); the
1167
+ // verdict is the whole detector: a replacement whose leaves are mostly the
1168
+ // SAME values is a spread-copy, and one whose leaves are mostly different is
1169
+ // new data (reconcile's job — and UNSTABLE_LIST_IDENTITY's, downstream). Once
1170
+ // per store path.
1171
+ const immutableReported = new Set;
1172
+
1173
+ function checkImmutableUpdate(e, n, t, o, i, s) {
1174
+ if (immutableReported.has(e) || t < 2) return;
1175
+ // Push/filter/splice copies change the length by a little; a wholesale
1176
+ // resize is a different operation even if some items survive.
1177
+ if (n && Math.abs(i - t) > Math.max(1, t >> 2)) return;
1178
+ // At least half the leaves carried over unchanged, and at least one did.
1179
+ if (o === 0 || o * 2 < t) return;
1180
+ const r = t - o;
1181
+ const a = n ? "array" : "object";
1182
+ const c = n ? `mutate the draft in place (push/splice/index assignment) so only the touched ` + `indices notify` : `assign the leaf on the draft (\`${e}.<key> = …\`) so only readers of that key re-run`;
1183
+ const d = `[IMMUTABLE_UPDATE_IN_STORE] "${e}" was replaced with a fresh ${a} whose ` + `${n ? "items" : "leaves"} are mostly the same values (${o} of ${t} unchanged` + `${r > 0 ? `, ${r} changed` : ""}) — a spread-copy update. The store already ` + `tracks ${n ? "items" : "leaves"}; a new container makes every reader of "${e}" ` + `re-run for the ${r === 1 ? "one that" : "few that"} moved. Instead, ${c}. For ` + `data arriving from outside (a fetch result), merge it with reconcile(data, key)(${e}).`;
1184
+ // The subject is the store's own owner, not the writer's context: the
1185
+ // finding is about the store, and its writes legitimately arrive from
1186
+ // outside the graph (an event handler, an adapter). Falls back to the
1187
+ // ambient context (emitDiagnostic's default) when the store recorded none.
1188
+ const f = emitDiagnostic({
1189
+ code: "IMMUTABLE_UPDATE_IN_STORE",
1190
+ kind: "perf",
1191
+ severity: "warn",
1192
+ message: d,
1193
+ nodeName: e,
1194
+ data: {
1195
+ path: e,
1196
+ shape: a,
1197
+ total: t,
1198
+ unchanged: o,
1199
+ changed: r
1200
+ }
1201
+ }, s);
1202
+ // Paths are not unique across stores: an excluded owner's store (an
1203
+ // adapter's own "store.list") must not spend the app's once-per-path slot.
1204
+ if (isSuppressed(f)) return;
1205
+ immutableReported.add(e);
1206
+ }
1207
+
1208
+ // --- Unstable list identity -----------------------------------------------------
1209
+
1210
+ // `<For>` keyed by identity (the default) treats every new object as a new
1211
+ // row. When a re-fetch hands back fresh objects for the same records, or a
1212
+ // spread-copy rebuilds the array, most rows are disposed and recreated —
1213
+ // DOM, state, focus, and all — for data that did not change. mapArray knows
1214
+ // exactly which items exited and entered; pairing them (by `id` when the
1215
+ // items carry one, else by position) and sampling shallow equivalence turns
1216
+ // that into a verdict: churn that replaced equivalent records is unstable
1217
+ // identity, not a new list. A key function that still churns has the same
1218
+ // disease one level up (its keys are not stable). Once per list.
1219
+ const LIST_CHURN_SAMPLE = 8;
1220
+
1221
+ const listIdentityWarned = new WeakSet;
1222
+
1223
+ function recordId(e) {
1224
+ if (e === null || typeof e !== "object") return undefined;
1225
+ const n = e;
1226
+ return n.id ?? n.key ?? n.yn ?? undefined;
1227
+ }
1228
+
1229
+ function checkListIdentity(e, n, t, o, i) {
1230
+ if (listIdentityWarned.has(e)) return;
1231
+ // Most of the list turned over, and the turnover was a swap (rows out ≈ rows in).
1232
+ if (t.length < 2 || t.length * 2 < o) return;
1233
+ if (Math.abs(n.length - t.length) > Math.max(1, t.length >> 2)) return;
1234
+ // Pair exited with entered: by record id when present, else by position.
1235
+ const s = new Map;
1236
+ for (const e of n) {
1237
+ const n = recordId(e);
1238
+ if (n !== undefined) s.set(n, e);
1239
+ }
1240
+ let r = 0;
1241
+ let a = 0;
1242
+ const c = Math.max(1, Math.floor(t.length / LIST_CHURN_SAMPLE));
1243
+ for (let e = 0; e < t.length && r < LIST_CHURN_SAMPLE; e += c) {
1244
+ const o = t[e];
1245
+ const i = recordId(o);
1246
+ const c = i !== undefined ? s.get(i) : n[e];
1247
+ if (c === undefined || !isPlainShape(c) || !isPlainShape(o)) continue;
1248
+ r++;
1249
+ if (shallowEquivalent(c, o)) a++;
1250
+ }
1251
+ if (r === 0 || a * 2 < r) return;
1252
+ listIdentityWarned.add(e);
1253
+ const d = nodeName(e);
1254
+ const f = i ? `The key function returned different keys for equivalent records — return a stable ` + `field (\`keyed: item => item.id\`), not the object or a computed value that changes ` + `with the fetch.` : `Key the list by a stable field (\`keyed: item => item.id\`), or merge the data into ` + `a store with reconcile(data, "id") so the same records keep the same identity.`;
1255
+ const u = `[UNSTABLE_LIST_IDENTITY] list "${d}" recreated ${t.length} of ${o} rows on ` + `an update where the entering items are equivalent to the ones they replaced ` + `(${a} of ${r} sampled pairs identical field-for-field) — fresh objects ` + `for the same records, so identity keying threw away every row's DOM and state and ` + `rebuilt it. ${f}`;
1256
+ reportDiagnostic(emitDiagnostic({
1257
+ code: "UNSTABLE_LIST_IDENTITY",
1258
+ kind: "perf",
1259
+ severity: "warn",
1260
+ message: u,
1261
+ nodeName: d,
1262
+ data: {
1263
+ removed: n.length,
1264
+ created: t.length,
1265
+ length: o,
1266
+ sampled: r,
1267
+ equivalent: a,
1268
+ keyed: i
1269
+ }
1270
+ }, e));
1271
+ }
1272
+
1273
+ /** Provenance of an async landing: the flight, under the interaction that started it. */ function asyncOrigin(e) {
1274
+ const n = {
1275
+ kind: "async",
1276
+ name: nodeName(e)
1277
+ };
1278
+ const t = liveFlights.get(e)?.interaction;
1279
+ if (t !== undefined) n.interaction = t;
1280
+ return n;
1281
+ }
1282
+
1283
+ // WeakMaps: an errored/abandoned flight must not leak its node or block GC.
1284
+ const liveFlights = new WeakMap;
1285
+
1286
+ const landedFlights = new WeakMap;
1287
+
1288
+ /**
1289
+ * Flight-object identity → earliest known start. Fed by markFlight() (the
1290
+ * cooperative preload/cache declaration — populated even while attribution
1291
+ * is disabled, so navigation-time marks survive a later enable()) and by
1292
+ * first sightings at registration.
1293
+ */ const flightOrigins = new WeakMap;
1294
+
1295
+ let waterfallLog = [];
1296
+
1297
+ /** Deepest landed-flight cause reachable through a cause list (derived links included). */ function flightCauseIn(e) {
1298
+ let n = null;
1299
+ for (const t of e) {
1300
+ let e = null;
1301
+ if (t.kind === "async") e = landedFlights.get(t) ?? null; else if (t.kind === "derived" && t.causes) e = flightCauseIn(t.causes);
1302
+ if (e !== null && (n === null || e.chain.length > n.chain.length)) n = e;
1303
+ }
1304
+ return n;
1305
+ }
1306
+
1307
+ /**
1308
+ * The nearest enclosing frame with causes: create runs carry null (a node
1309
+ * born inside a parent's recompute inherits the parent's causality — the
1310
+ * boundary-reveal case, and the lazy sibling whose first pull is gated behind
1311
+ * an earlier not-ready read), so walk down to the first re-run frame.
1312
+ */ function enclosingCauses() {
1313
+ for (let e = frames.length - 1; e >= 0; e--) {
1314
+ const n = frames[e].causes;
1315
+ if (n !== null) return n;
1316
+ }
1317
+ return null;
1318
+ }
1319
+
1320
+ /** The flight's face as a record, at the moment it landed or was superseded. */ function emitFlight(e, n, t, o) {
1321
+ if (excludedNode(e)) return;
1322
+ const i = {
1323
+ nodeId: devId(e),
1324
+ nodeName: nodeName(e),
1325
+ at: n.origin,
1326
+ durationMs: t - n.origin,
1327
+ outcome: o
1328
+ };
1329
+ const s = ownerPath(e);
1330
+ if (s !== undefined) i.ownerPath = s;
1331
+ if (n.interaction !== undefined) i.interaction = n.interaction;
1332
+ records.emit("flight", i, e);
1333
+ }
1334
+
1335
+ function trackFlightStart(e, n) {
1336
+ const t = now();
1337
+ const o = flightOrigins.get(n) ?? t;
1338
+ if (o === t) flightOrigins.set(n, t);
1339
+ // Census: a flight still in the air when the node starts another was
1340
+ // superseded — its answer will be discarded.
1341
+ const i = liveFlights.get(e);
1342
+ for (const n of folds) n.flightStart?.(e, i !== undefined);
1343
+ if (i !== undefined) {
1344
+ if (records.observed("flight")) emitFlight(e, i, t, "abandoned");
1345
+ checkAbandonedFlights(e, i);
1346
+ }
1347
+ const s = enclosingCauses();
1348
+ const r = {
1349
+ origin: o,
1350
+ startSeq: changeSeq,
1351
+ chain: []
1352
+ };
1353
+ // Provenance: the flight belongs to whatever interaction caused the
1354
+ // recompute that started it (a create run under a click's handler — a
1355
+ // freshly mounted async node — inherits the ambient interaction instead).
1356
+ const a = s !== null ? interactionIn(s) : currentInteraction ?? undefined;
1357
+ if (a !== undefined) r.interaction = a;
1358
+ if (options.waterfalls !== false && s !== null) {
1359
+ let e = flightCauseIn(s);
1360
+ // The sequentiality test. A marked/previously-seen flight whose origin
1361
+ // predates the upstream landing was in the air alongside it: parallel.
1362
+ if (e !== null && o < e.landedAt) e = null;
1363
+ if (e !== null) r.chain = [ ...e.chain, {
1364
+ name: e.name,
1365
+ ms: e.ms
1366
+ } ];
1367
+ }
1368
+ liveFlights.set(e, r);
1369
+ }
1370
+
1371
+ /**
1372
+ * Flight landed (whether or not the value committed — the wall time was
1373
+ * spent either way). Attach the measurement to the landing's fresh "async"
1374
+ * stamp so downstream flights can chain through it, then judge the chain.
1375
+ */ function finalizeFlight(e) {
1376
+ const n = liveFlights.get(e);
1377
+ if (n === undefined) return;
1378
+ liveFlights.delete(e);
1379
+ const t = now();
1380
+ const o = t - n.origin;
1381
+ for (const n of folds) n.flightLanded?.(e, o);
1382
+ if (records.observed("flight")) emitFlight(e, n, t, "landed");
1383
+ const i = e.ze;
1384
+ // Only a stamp this landing produced may carry the measurement — a stale
1385
+ // async record from a previous landing must not be re-labeled.
1386
+ if (i !== undefined && i.kind === "async" && i.seq > n.startSeq) landedFlights.set(i, {
1387
+ name: nodeName(e),
1388
+ ms: o,
1389
+ chain: n.chain,
1390
+ landedAt: t
1391
+ });
1392
+ checkWaterfall(e, n.chain, o);
1393
+ }
1394
+
1395
+ function checkWaterfall(e, n, t) {
1396
+ const o = options.waterfalls;
1397
+ if (o === false) return;
1398
+ if (n.length > 0) {
1399
+ waterfallLog.push({
1400
+ chain: [ ...n, {
1401
+ name: nodeName(e),
1402
+ ms: t
1403
+ } ],
1404
+ sequentialMs: n.reduce((e, n) => e + n.ms, t)
1405
+ });
1406
+ if (waterfallLog.length > options.historyLimit) waterfallLog.shift();
1407
+ }
1408
+ // The verdict: trailing run of links that were each a real wait. A fast
1409
+ // tail (settled preload/cache hit) or a fast upstream breaks the sequence.
1410
+ if (t < o.minFlightMs) return;
1411
+ let i = 1;
1412
+ let s = t;
1413
+ for (let e = n.length - 1; e >= 0 && n[e].ms >= o.minFlightMs; e--) {
1414
+ i++;
1415
+ s += n[e].ms;
1416
+ }
1417
+ if (i < 2) return;
1418
+ const r = e;
1419
+ if ((r.Nn ?? 0) >= i) return;
1420
+ r.Nn = i;
1421
+ const a = [ ...n.slice(n.length - (i - 1)), {
1422
+ name: nodeName(e),
1423
+ ms: t
1424
+ } ];
1425
+ const c = a.map(e => `"${e.name}" (${e.ms.toFixed(0)}ms)`).join(" → ");
1426
+ const d = `[ASYNC_WATERFALL] ${i} sequential async flights — ${c} — ` + `${s.toFixed(0)}ms serialized: each began only after the previous resolved ` + `(as far as this graph can see). If a later request doesn't need the earlier ` + `response, derive both from the same inputs so they start together; if the ` + `dependency is intrinsic, preload the dependent data or join the requests ` + `server-side. If this work WAS already started elsewhere (a preloader or request ` + `cache), have that layer stamp its promises with attribution.markFlight() ` + `from "@solidjs/signals/attribution".`;
1427
+ // Depth 2 is advisory-only (structured consumers see it; the console does
1428
+ // not): a 2-chain can be an intrinsic data dependency or an unmarked
1429
+ // preload. A 3+ chain that survived the origin test is near-certainly
1430
+ // structural — that one earns the console.
1431
+ const f = i > 2 ? "warn" : "info";
1432
+ emitDiagnostic({
1433
+ code: "ASYNC_WATERFALL",
1434
+ kind: "perf",
1435
+ severity: f,
1436
+ message: d,
1437
+ nodeName: nodeName(e),
1438
+ data: {
1439
+ chain: a.map(e => ({
1440
+ name: e.name,
1441
+ ms: e.ms
1442
+ })),
1443
+ sequentialMs: s
1444
+ }
1445
+ }, e);
1446
+ }
1447
+
1448
+ const holdStates = new WeakMap;
1449
+
1450
+ let activeHold = null;
1451
+
1452
+ let holdLog = [];
1453
+
1454
+ /** Companions are optimistic nodes too; `_parentSource` marks them. So is a
1455
+ * memo carrying a DERIVED override (lanes stage, #3479) — a lane pass's
1456
+ * result, not a write anyone made: neither is an acknowledgement. */ function isCompanion(e) {
1457
+ return !!e.o && e.o.$n !== undefined || (e.C & CONFIG_DERIVED_OVERRIDE) !== 0;
1458
+ }
1459
+
1460
+ const HOLD_CENSUS_CAP = 1e4;
1461
+
1462
+ function acknowledge(e, n, t, o) {
1463
+ const i = `${n}:${t}`;
1464
+ const s = e.acknowledgements.get(i);
1465
+ const r = o !== null ? ownerPath(o) : undefined;
1466
+ // A later census (a merged transition, the settle pass) may find the
1467
+ // reader an earlier one missed.
1468
+ if (s === undefined) e.acknowledgements.set(i, r !== undefined ? {
1469
+ kind: n,
1470
+ source: t,
1471
+ reader: r
1472
+ } : {
1473
+ kind: n,
1474
+ source: t
1475
+ }); else if (r !== undefined) s.reader ??= r;
1476
+ }
1477
+
1478
+ function censusRegistrations(e, n) {
1479
+ const t = {
1480
+ left: HOLD_CENSUS_CAP
1481
+ };
1482
+ for (const o of e.bn) if (!isCompanion(o)) acknowledge(n, "optimistic", nodeName(o), reachesEffect(o, t));
1483
+ for (const t of e.En) acknowledge(n, "optimistic", t?._name ?? "store", null);
1484
+ for (const o of e.A) acknowledge(n, "affects", nodeName(o), reachesEffect(o, t));
1485
+ }
1486
+
1487
+ /**
1488
+ * Does anything that paints read `companion` — an effect, through however many
1489
+ * memos? A subscriber alone is not acknowledgement: memos compute eagerly, so a
1490
+ * router's `createMemo(() => isPending(location))` subscribes to the companion
1491
+ * whether or not the app ever renders the memo. Only an effect is the screen.
1492
+ * Returns the first effect found (the reader), or null.
1493
+ */ function reachesEffect(e, n) {
1494
+ const t = new Set([ e ]);
1495
+ const o = [ e ];
1496
+ while (o.length > 0 && n.left-- > 0) {
1497
+ const e = o.pop();
1498
+ for (let n = e.u; n !== null; n = n.Pe) {
1499
+ const e = n.Ae;
1500
+ if (e.He) return e;
1501
+ if (!t.has(e)) {
1502
+ t.add(e);
1503
+ o.push(e);
1504
+ }
1505
+ }
1506
+ }
1507
+ return null;
1508
+ }
1509
+
1510
+ /** Companions an effect reads, anywhere downstream of the hold's nodes. */ function censusCompanions(e, n) {
1511
+ const t = new Set;
1512
+ const o = [ ...e ];
1513
+ const i = {
1514
+ left: HOLD_CENSUS_CAP
1515
+ };
1516
+ while (o.length > 0 && t.size < HOLD_CENSUS_CAP) {
1517
+ const e = o.pop();
1518
+ if (t.has(e)) continue;
1519
+ t.add(e);
1520
+ const s = e.o;
1521
+ if (s) {
1522
+ let t;
1523
+ if (s.xe !== undefined && (t = reachesEffect(s.xe, i))) acknowledge(n, "isPending", nodeName(e), t);
1524
+ if (s.Me !== undefined && (t = reachesEffect(s.Me, i))) acknowledge(n, "latest", nodeName(e), t);
1525
+ for (let e = s.i ?? null; e !== null; e = e.ge ?? null) o.push(e);
1526
+ }
1527
+ for (let n = e.u; n !== null; n = n.Pe) o.push(n.Ae);
1528
+ }
1529
+ }
1530
+
1531
+ function holdState(e) {
1532
+ let n = holdStates.get(e);
1533
+ if (n === undefined) {
1534
+ n = {
1535
+ start: now(),
1536
+ flushes: 0,
1537
+ blockers: new Set,
1538
+ acknowledgements: new Map,
1539
+ painted: 0,
1540
+ action: false
1541
+ };
1542
+ holdStates.set(e, n);
1543
+ }
1544
+ return n;
1545
+ }
1546
+
1547
+ function trackHoldStart(e) {
1548
+ // Navigations and interactions learn they are held regardless of hold
1549
+ // tracking: their settle must wait for the transition either way (see flushEnd).
1550
+ markNavigationsHeld(e);
1551
+ markInteractionsHeld(e);
1552
+ if (options.holds === false) return;
1553
+ const n = holdState(e);
1554
+ n.flushes++;
1555
+ if (e.tt.length > 0) n.action = true;
1556
+ for (const [t, o] of e.ae) if (o.size > 0) n.blockers.add(t);
1557
+ censusRegistrations(e, n);
1558
+ activeHold = n;
1559
+ }
1560
+
1561
+ function trackHoldMerge(e, n) {
1562
+ mergeInteractionsHeld(e, n);
1563
+ const t = holdStates.get(n);
1564
+ if (t === undefined) return;
1565
+ holdStates.delete(n);
1566
+ const o = holdState(e);
1567
+ if (t.start < o.start) o.start = t.start;
1568
+ o.flushes += t.flushes;
1569
+ o.painted += t.painted;
1570
+ o.action ||= t.action;
1571
+ for (const e of t.blockers) o.blockers.add(e);
1572
+ for (const [e, n] of t.acknowledgements) if (!o.acknowledgements.has(e)) o.acknowledgements.set(e, n);
1573
+ }
1574
+
1575
+ function trackHoldSettled(e) {
1576
+ const n = holdStates.get(e);
1577
+ if (n === undefined) {
1578
+ // No hold was recorded (the transition completed in its first flush, or
1579
+ // hold tracking is off): navigations and interactions staged in it still
1580
+ // settle here.
1581
+ settleNavigations(e, undefined);
1582
+ settleInteractionsHeld(e, undefined);
1583
+ return;
1584
+ }
1585
+ holdStates.delete(e);
1586
+ // Root writes only: a memo in _pendingNodes is a derived hold, and the
1587
+ // question is whether the USER's input went unanswered.
1588
+ const t = [];
1589
+ let o = null;
1590
+ let i;
1591
+ let s;
1592
+ let r = -Infinity;
1593
+ for (const n of e.In) {
1594
+ if (typeof n.Se === "function" || isCompanion(n)) continue;
1595
+ const e = n.ze;
1596
+ if (e === undefined || e.kind !== "write") continue;
1597
+ if (o === null) o = n;
1598
+ const a = {
1599
+ name: nodeName(n),
1600
+ prev: e.prev,
1601
+ value: e.value
1602
+ };
1603
+ if (e.origin !== undefined) a.origin = e.origin;
1604
+ t.push(a);
1605
+ // Earliest interaction among the held writes: the user has been waiting
1606
+ // since the first thing they did that this transaction is holding.
1607
+ const c = interactionOf(e.origin);
1608
+ if (c !== undefined && (i === undefined || c.at < i.at)) i = c;
1609
+ // The declared frame the writes belong to — earliest navigation, by the
1610
+ // same reasoning.
1611
+ if (e.origin?.kind === "navigation" && (s === undefined || e.origin.at < s.at)) s = e.origin;
1612
+ // Latest write: a signal written twice while held carries the later
1613
+ // stamp, so this is the user's final input, not their first.
1614
+ if (e.at !== undefined && e.at > r) r = e.at;
1615
+ }
1616
+ if (t.length === 0) {
1617
+ settleNavigations(e, undefined);
1618
+ settleInteractionsHeld(e, undefined);
1619
+ return;
1620
+ }
1621
+ censusRegistrations(e, n);
1622
+ censusCompanions([ ...e.In, ...n.blockers ], n);
1623
+ const a = now();
1624
+ // The hold began no later than its first parked flush; an interaction stamp
1625
+ // reaches further back (dispatch). A node rewritten mid-hold keeps only its
1626
+ // latest record, so the surviving interaction may be a later one — the
1627
+ // flush clock keeps the first wait from being forgotten.
1628
+ const c = Math.min(n.start, i !== undefined ? i.at : Infinity);
1629
+ const d = a - c;
1630
+ const f = r === -Infinity ? d : Math.min(d, a - r);
1631
+ const u = [ ...n.acknowledgements.values() ];
1632
+ // The verdicts, stamped on the record so a consumer — in-process or
1633
+ // offline — applies the engine's own tiering rather than a threshold of
1634
+ // its own: silent is duration-free (the finding adds the floor); long is
1635
+ // the tail against `longHolds.infoMs` as the options stand at settle.
1636
+ const l = options.longHolds;
1637
+ const h = {
1638
+ at: c,
1639
+ holdMs: d,
1640
+ tailMs: f,
1641
+ flushes: n.flushes,
1642
+ heldWrites: t,
1643
+ blockers: [ ...n.blockers ].map(nodeName),
1644
+ acknowledgements: u,
1645
+ paintedDuringHold: n.painted,
1646
+ action: n.action,
1647
+ silent: n.painted === 0 && u.length === 0,
1648
+ long: l !== false && l !== undefined && f >= l.infoMs
1649
+ };
1650
+ if (i !== undefined) h.interaction = i;
1651
+ if (s !== undefined) h.origin = s;
1652
+ holdLog.push(h);
1653
+ if (holdLog.length > options.historyLimit) holdLog.shift();
1654
+ // Bottom-up delivery: the hold, then the navigations it held, then the
1655
+ // interactions those belong to — each record complete when its parent is.
1656
+ // `live` is the first held root write's signal: the subject the findings
1657
+ // below name.
1658
+ records.emit("hold", h, o);
1659
+ checkStackedHolds(e, h, o);
1660
+ settleNavigations(e, h);
1661
+ settleInteractionsHeld(e, h);
1662
+ for (const e of folds) e.hold?.(h);
1663
+ if (h.silent) checkSilentHold(h, o); else checkLongHold(h, o);
1664
+ }
1665
+
1666
+ function describeHeldWrites(e) {
1667
+ return e.heldWrites.map(e => e.prev !== undefined ? `"${e.name}" (${e.prev} → ${e.value})` : `"${e.name}"`).join(", ");
1668
+ }
1669
+
1670
+ function describeBlockers(e, n) {
1671
+ return e.blockers.length > 0 ? ` ${n} ${e.blockers.map(e => `"${e}"`).join(", ")}` : "";
1672
+ }
1673
+
1674
+ /**
1675
+ * The boundary repair, shared by LONG_HOLD and a long SILENT_HOLD: a wait
1676
+ * this long should show a fallback, not a stale screen. A `Loading` boundary
1677
+ * lifts the write out of the hold only when it has not revealed yet or its
1678
+ * `on` prop changed — a revealed boundary with no `on` IS the stale screen.
1679
+ */ function boundaryRepair(e) {
1680
+ const n = e.heldWrites[0]?.name ?? "key";
1681
+ return `A wait this long is past what a stale screen should carry: show a fallback instead. Put ` + `the reader behind a Loading boundary keyed on what changed — <Loading on={${n}()} ` + `fallback={…}> — so the write commits at once and the fallback shows where the data lands; ` + `a boundary that has already revealed keeps the old content unless \`on\` changes. If the ` + `data itself is the problem, preload it or cache it so the wait never gets this long.`;
1682
+ }
1683
+
1684
+ function holdData(e) {
1685
+ const n = {
1686
+ holdMs: e.holdMs,
1687
+ tailMs: e.tailMs,
1688
+ flushes: e.flushes,
1689
+ heldWrites: e.heldWrites.map(e => e.name),
1690
+ blockers: e.blockers,
1691
+ action: e.action
1692
+ };
1693
+ if (e.interaction !== undefined) n.interaction = {
1694
+ type: e.interaction.name,
1695
+ target: e.interaction.target
1696
+ };
1697
+ if (e.origin?.kind === "navigation") n.navigation = navigationData(e.origin);
1698
+ return n;
1699
+ }
1700
+
1701
+ /**
1702
+ * Who the verdict sentence starts from: the interaction, with the navigation
1703
+ * it performed in parentheses — `click on a.nav (navigation to /users/:id)`;
1704
+ * the navigation alone when nothing user-dispatched is known (a redirect);
1705
+ * empty when neither is.
1706
+ */ function holdActor(e) {
1707
+ const n = e.origin !== undefined ? formatOrigin(e.origin) : "";
1708
+ if (e.interaction !== undefined) return `${formatOrigin(e.interaction)}${n ? ` (${n})` : ""}`;
1709
+ return n;
1710
+ }
1711
+
1712
+ function checkSilentHold(e, n) {
1713
+ const t = options.holds;
1714
+ if (t === false) return;
1715
+ if (e.holdMs < t.infoMs) return;
1716
+ const o = e.holdMs.toFixed(0);
1717
+ const i = describeHeldWrites(e);
1718
+ const s = describeBlockers(e, "waiting on");
1719
+ // With the interaction (or navigation) stamped the sentence starts from
1720
+ // what the user did; without it, from the writes.
1721
+ const r = holdActor(e);
1722
+ const a = r ? `${r} ` : "";
1723
+ let c = e.action ? `[SILENT_HOLD] ${a}${a ? "started an action that" : "an action"} held ${i} for ` + `${o}ms${s} and the screen showed nothing for the whole round-trip: no optimistic ` + `value, no isPending() reader, no affects() mark, and no effect ran while it was held. ` + `Pair the action with a createOptimistic/createOptimisticStore write for the expected ` + `outcome (it reverts on failure), or co-write a createOptimistic(false) "saving" flag ` + `the UI reads.` : `[SILENT_HOLD] ${a}${a ? "wrote" : "writes to"} ${i}${a ? "; the write was" : " were"} ` + `held ${o}ms${s} and the screen showed nothing for the wait: no ` + `isPending()/latest() reader downstream, no optimistic value, no affects() mark, and no ` + `effect ran while it was held — the interaction was dead for ${o}ms. Show the wait: ` + `read isPending(() => ${e.blockers[0] ?? "source"}()) to render a busy state, or ` + `latest(${e.heldWrites[0].name}) to reveal the new input immediately while the data ` + `catches up. The hold itself is correct — do not "fix" this by moving the write off the ` + `async path.`;
1724
+ const d = e.long;
1725
+ if (d) c += ` ${boundaryRepair(e)}`;
1726
+ const f = e.holdMs >= t.warnMs ? "warn" : "info";
1727
+ const u = holdData(e);
1728
+ u.long = d;
1729
+ emitDiagnostic({
1730
+ code: "SILENT_HOLD",
1731
+ kind: "responsiveness",
1732
+ severity: f,
1733
+ message: c,
1734
+ nodeName: nodeName(n),
1735
+ data: u
1736
+ }, n);
1737
+ }
1738
+
1739
+ function checkLongHold(e, n) {
1740
+ const t = options.longHolds;
1741
+ if (t === false || t === undefined) return;
1742
+ if (e.tailMs < t.infoMs) return;
1743
+ const o = e.tailMs.toFixed(0);
1744
+ const i = describeHeldWrites(e);
1745
+ const s = describeBlockers(e, "waiting on");
1746
+ const r = holdActor(e);
1747
+ const a = r ? `${r} ` : "";
1748
+ const c = e.acknowledgements.length > 0 ? `${e.acknowledgements.map(e => `"${e.kind}:${e.source}"`).join(", ")} said it was pending` : `an effect painted meanwhile`;
1749
+ const d = e.tailMs < e.holdMs - 1 ? ` after the last input (${e.holdMs.toFixed(0)}ms in all)` : "";
1750
+ const f = `[LONG_HOLD] ${a}${a ? "wrote" : "writes to"} ${i}; the screen kept the old ` + `content for ${o}ms${d}${s} — ${c}, but the hold ran on well past ` + `the point where "loading" over stale content reads as broken. ${boundaryRepair(e)}`;
1751
+ const u = e.tailMs >= t.warnMs ? "warn" : "info";
1752
+ const l = holdData(e);
1753
+ l.acknowledgements = e.acknowledgements;
1754
+ emitDiagnostic({
1755
+ code: "LONG_HOLD",
1756
+ kind: "responsiveness",
1757
+ severity: u,
1758
+ message: f,
1759
+ nodeName: nodeName(n),
1760
+ data: l
1761
+ }, n);
1762
+ }
1763
+
1764
+ /**
1765
+ * The person saw the guess, then the correction. An optimistic value is a
1766
+ * promise the UI makes about the outcome; when the outcome differs — the
1767
+ * action failed and the override lifted back to the old value, or the
1768
+ * source answered with something else — the screen changes twice for one
1769
+ * intent. Expected on failure and correct by construction (the override
1770
+ * reverts; that is the feature), so `info`: a count that grows for one
1771
+ * source is what says the guess, or the failure rate, is wrong. Judged by
1772
+ * the node's own equality, so a structurally equal replacement is not a
1773
+ * revert.
1774
+ */ function checkOptimisticRevert(e, n, t, o) {
1775
+ // The runtime's own optimistic nodes are not guesses the person saw: an
1776
+ // `isPending()` companion goes true while pending and back to false at
1777
+ // commit by design — the acknowledgement SILENT_HOLD asks for — and a
1778
+ // derived override promotes rather than reverts. Same predicate the hold
1779
+ // census uses to skip them.
1780
+ if (!options.optimisticReverts || isCompanion(e)) return;
1781
+ const i = e.Fe;
1782
+ if (i && i(n, t)) return;
1783
+ const s = nodeName(e);
1784
+ // The two values are user data: quoted only under `values: "full"`; the
1785
+ // other levels say what happened without saying what was shown.
1786
+ const r = options.values === "full";
1787
+ const a = o === "superseded" ? "settled to" : "reverted to";
1788
+ const c = `[OPTIMISTIC_REVERTED] the optimistic value of ${s} ` + (r ? `showed ${preview(n)}; it ${a} ${preview(t)}.` : `${o === "superseded" ? "was superseded by the settled value" : "reverted at settle"}.`) + ` The person saw the guess, then the correction. A revert on failure is the feature; one ` + `that recurs says the guess is wrong for this input or the action fails often — show the ` + `failure where the value renders (the action's catch, an Errored boundary) rather than ` + `letting the value snap back on its own.`;
1789
+ const d = {
1790
+ source: s,
1791
+ how: o
1792
+ };
1793
+ if (r) {
1794
+ d.shown = preview(n);
1795
+ d.truth = preview(t);
1796
+ }
1797
+ emitDiagnostic({
1798
+ code: "OPTIMISTIC_REVERTED",
1799
+ kind: "responsiveness",
1800
+ severity: "info",
1801
+ message: c,
1802
+ nodeName: s,
1803
+ data: d
1804
+ }, e);
1805
+ }
1806
+
1807
+ // --- Graph growth -----------------------------------------------------------------
1808
+ /** Per route: the graph's size at its last `visits` settles, oldest first. */ const routeCounts = new Map;
1809
+
1810
+ /**
1811
+ * The live graph's size — a walk, not a counter: nothing is charged at node
1812
+ * creation, disposal, write or re-run; the engine asks at a navigation's
1813
+ * settle. Two passes. The owner tree from the registered top-level roots
1814
+ * gives `owners` and seeds the computations. Then each computation's
1815
+ * dependency links give `edges` and the `signals` and computations they
1816
+ * reach, and each newly met source's subscriber list gives the computations
1817
+ * that read it — including one created with no owner, which no chain holds
1818
+ * and only its sources keep alive: the subscription leak a heap snapshot
1819
+ * finds. Measured at 5–10 ns per link; a 50k-owner graph walks in under a
1820
+ * millisecond. Dormant nodes are spliced out of their chain and are not
1821
+ * counted unless a subscription still reaches them.
1822
+ */ function graphSize() {
1823
+ const e = liveRootOwners();
1824
+ const n = {
1825
+ roots: e.length,
1826
+ owners: 0,
1827
+ computations: 0,
1828
+ signals: 0,
1829
+ edges: 0
1830
+ };
1831
+ const t = new Set;
1832
+ // A worklist, not recursion: a subscriber chain can be thousands deep.
1833
+ const o = [];
1834
+ const i = [];
1835
+ const meet = e => {
1836
+ if (t.has(e)) return;
1837
+ t.add(e);
1838
+ if (typeof e.Se === "function") n.computations++; else n.signals++;
1839
+ o.push(e);
1840
+ };
1841
+ for (const t of e) {
1842
+ n.owners++;
1843
+ // Iterative: a deep tree must not grow the call stack.
1844
+ let e = t._n;
1845
+ for (;;) {
1846
+ while (e !== null) {
1847
+ n.owners++;
1848
+ if (typeof e.Se === "function") meet(e);
1849
+ if (e._n !== null) i.push(e);
1850
+ e = e.Fn;
1851
+ }
1852
+ const t = i.pop();
1853
+ if (t === undefined) break;
1854
+ e = t._n;
1855
+ }
1856
+ }
1857
+ for (let e = 0; e < o.length; e++) {
1858
+ const t = o[e];
1859
+ // Whoever reads this node: owned computations are already known; an
1860
+ // ownerless one is met only here.
1861
+ for (let e = t.u; e !== null; e = e.Pe) meet(e.Ae);
1862
+ if (typeof t.Se === "function") for (let e = t.Ee; e !== null; e = e.Ie) {
1863
+ n.edges++;
1864
+ meet(e.De);
1865
+ }
1866
+ }
1867
+ return n;
1868
+ }
1869
+
1870
+ /**
1871
+ * settleNavigation: the app has finished moving to a route — count the live
1872
+ * graph. One record per settle for a listener; the growth check compares
1873
+ * this settle of the route with its previous ones. A count that climbs on
1874
+ * consecutive visits is something the previous visit left behind: a
1875
+ * `createRoot` in an effect with no dispose, a subscription a component
1876
+ * registered outside its owner. Nothing here runs per node; the walk is
1877
+ * the cost, at navigation cadence.
1878
+ */ const GRAPH_SERIES = [ "owners", "computations", "signals", "edges" ];
1879
+
1880
+ function trackGraph(e) {
1881
+ const n = options.graphGrowth;
1882
+ if (n === false && !records.observed("graph")) return;
1883
+ const t = graphSize();
1884
+ const o = e.name ?? e.to;
1885
+ const i = {
1886
+ at: now(),
1887
+ ...t,
1888
+ navigation: e
1889
+ };
1890
+ if (o !== undefined) i.route = o;
1891
+ records.emit("graph", i, undefined);
1892
+ if (n === false || o === undefined) return;
1893
+ let s = routeCounts.get(o);
1894
+ if (s === undefined) routeCounts.set(o, s = []);
1895
+ s.push(t);
1896
+ if (s.length > n.visits) s.shift();
1897
+ if (s.length < n.visits) return;
1898
+ // Any series climbing on every visit to the ratio is growth; which ones
1899
+ // did says what leaked — computations with owners flat is an ownerless
1900
+ // effect per visit, edges alone is a subscription per visit to something
1901
+ // long-lived, owners is an undisposed root.
1902
+ const r = GRAPH_SERIES.filter(e => {
1903
+ for (let n = 1; n < s.length; n++) if (s[n][e] <= s[n - 1][e]) return false;
1904
+ return s[s.length - 1][e] >= s[0][e] * n.ratio;
1905
+ });
1906
+ if (r.length === 0) return;
1907
+ // The count is the whole graph's, so a leak shows at every route's settle;
1908
+ // the first route to complete its climb reports, naming the others seen.
1909
+ const a = [ ...routeCounts.keys() ];
1910
+ const c = r.map(e => `${e} ${s.map(n => n[e]).join(" → ")}`).join("; ");
1911
+ const d = r.includes("owners") ? "a createRoot() in an effect or handler with no dispose, or a Portal or panel mounted per visit" : r.includes("computations") ? "an effect or memo created with no owner (a module-level or callback createEffect) that only its sources keep alive" : "a subscription per visit to something long-lived — a global store or signal read by a computation that outlives the visit";
1912
+ const f = `[GRAPH_GROWTH] the live graph grew on ${n.visits} consecutive visits to ${o}: ${c} ` + `(${t.roots} roots)${a.length > 1 ? `, across visits to ${a.join(", ")}` : ""}. Each ` + `visit left something behind that the next did not reclaim — the shape says ${d}. Dispose ` + `what a visit creates (onCleanup, or return the disposer from onSettled) and own it under the ` + `route's component so leaving the route tears it down.`;
1913
+ const u = {
1914
+ route: o,
1915
+ grew: r,
1916
+ history: s.map(e => ({
1917
+ ...e
1918
+ })),
1919
+ roots: t.roots,
1920
+ routes: a
1921
+ };
1922
+ if (e.interaction !== undefined) u.interaction = {
1923
+ type: e.interaction.name,
1924
+ target: e.interaction.target
1925
+ };
1926
+ reportDiagnostic(emitDiagnostic({
1927
+ code: "GRAPH_GROWTH",
1928
+ kind: "perf",
1929
+ severity: "warn",
1930
+ message: f,
1931
+ data: u
1932
+ }, null));
1933
+ // Judged once for the graph, not once per route: the next verdict needs
1934
+ // another `visits` climbing settles.
1935
+ routeCounts.clear();
1936
+ }
1937
+
1938
+ // --- Feedback-table findings -----------------------------------------------------
1939
+ /** Per async source: abandoned flights inside the current window. Engine-side; the node carries nothing. */ const abandonWindows = new WeakMap;
1940
+
1941
+ /**
1942
+ * One source abandoning flight after flight inside a window: every input
1943
+ * asked again and the earlier answers were thrown away — the
1944
+ * request-per-keystroke signature `feedback().flights[].abandoned` counts,
1945
+ * as a finding while it happens. Warned once per window per source.
1946
+ */ function checkAbandonedFlights(e, n) {
1947
+ const t = options.abandonedFlights;
1948
+ if (t === false || excludedNode(e)) return;
1949
+ const o = Date.now();
1950
+ let i = abandonWindows.get(e);
1951
+ if (i === undefined || o - i.start > t.windowMs) {
1952
+ i = {
1953
+ start: o,
1954
+ count: 0,
1955
+ warned: false
1956
+ };
1957
+ abandonWindows.set(e, i);
1958
+ }
1959
+ i.count++;
1960
+ if (i.warned || i.count < t.count) return;
1961
+ i.warned = true;
1962
+ const s = nodeName(e);
1963
+ const r = n.interaction !== undefined ? ` (${formatOrigin(n.interaction)} started the first)` : "";
1964
+ const a = `[ABANDONED_FLIGHTS] "${s}" abandoned ${i.count} flights in ${t.windowMs}ms` + `${r}: each was superseded by the next before it landed, so every input asked again and the ` + `answers were discarded. Put a debounced or equality-gated derivation between the input and ` + `the fetch, or key the fetch on what changes rather than on every keystroke; a preload the ` + `flights share (markFlight) reads as one flight, not many.`;
1965
+ const c = {
1966
+ source: s,
1967
+ abandoned: i.count,
1968
+ windowMs: t.windowMs
1969
+ };
1970
+ if (n.interaction !== undefined) c.interaction = {
1971
+ type: n.interaction.name,
1972
+ target: n.interaction.target
1973
+ };
1974
+ emitDiagnostic({
1975
+ code: "ABANDONED_FLIGHTS",
1976
+ kind: "responsiveness",
1977
+ severity: "warn",
1978
+ message: a,
1979
+ nodeName: s,
1980
+ data: c
1981
+ }, e);
1982
+ }
1983
+
1984
+ /**
1985
+ * A fallback that appeared and vanished: the other end of the SILENT_HOLD
1986
+ * spectrum — feedback for a wait too short to need it, which reads as a
1987
+ * flicker. `info`, once per flash; `feedback().fallbacks[].flashes` is the
1988
+ * count. The repair is a preload, a cache, or lifting the fetch above the
1989
+ * boundary so the data is there before the boundary asks.
1990
+ */ function checkFallbackFlash(e, n, t) {
1991
+ if (e !== undefined && excludedNode(e)) return;
1992
+ const o = e !== undefined ? ownerPath(e)?.join(" › ") : undefined;
1993
+ const i = t !== undefined ? `${formatOrigin(t)}: ` : "";
1994
+ const s = `[FALLBACK_FLASH] ${i}the Loading fallback${o ? ` at ${o}` : ""} showed for ` + `${n.toFixed(0)}ms — a spinner that appeared and vanished, feedback for a wait too short ` + `to need it. Preload or cache the data so it is there before the boundary asks, or lift the ` + `read above the boundary; a fallback under ${FALLBACK_FLASH_MS}ms reads as a flicker.`;
1995
+ const r = {
1996
+ shownMs: n
1997
+ };
1998
+ if (t !== undefined) r.interaction = {
1999
+ type: t.name,
2000
+ target: t.target
2001
+ };
2002
+ emitDiagnostic({
2003
+ code: "FALLBACK_FLASH",
2004
+ kind: "responsiveness",
2005
+ severity: "info",
2006
+ message: s,
2007
+ data: r
2008
+ }, e ?? null);
2009
+ }
2010
+
2011
+ /**
2012
+ * Several interactions waiting in one hold when it commits: the person kept
2013
+ * clicking or typing while the first answer was in the air, and all of them
2014
+ * waited on the same source. The pile is the symptom; the hold's own verdict
2015
+ * (SILENT_HOLD / LONG_HOLD) is the cause, so the repair is the same
2016
+ * acknowledgement, plus a control that does not accept the repeat.
2017
+ */ function checkStackedHolds(e, n, t) {
2018
+ const o = options.stackedHolds;
2019
+ if (o === false) return;
2020
+ let i = 0;
2021
+ for (const n of openInteractions) if (n.heldIn.has(e)) i++;
2022
+ if (i < o.count) return;
2023
+ const s = describeBlockers(n, "waiting on");
2024
+ const r = `[STACKED_HOLDS] ${i} interactions queued behind one hold${s} for ` + `${n.holdMs.toFixed(0)}ms: the person kept ${n.interaction?.name === "input" ? "typing" : "clicking"} ` + `while the first answer was in the air, and every repeat waited on the same source. ` + `Acknowledge the wait where the control is (isPending() to disable or dim it) so the repeats ` + `stop, or debounce the input; the hold itself is judged by SILENT_HOLD/LONG_HOLD.`;
2025
+ const a = holdData(n);
2026
+ a.interactions = i;
2027
+ emitDiagnostic({
2028
+ code: "STACKED_HOLDS",
2029
+ kind: "responsiveness",
2030
+ severity: "warn",
2031
+ message: r,
2032
+ nodeName: nodeName(t),
2033
+ data: a
2034
+ }, t);
2035
+ }
2036
+
2037
+ const navStates = new WeakMap;
2038
+
2039
+ /** Opened, not yet settled. */ const openNavs = new Set;
2040
+
2041
+ let navigationLog = [];
2042
+
2043
+ /** Drains completed since enable() — the clock `writeDrain` reads. */ let drainSeq = 0;
2044
+
2045
+ /**
2046
+ * Copy what the router currently says onto the frame (what writes stamped —
2047
+ * `formatOrigin` reads it) and the event. Called when the frame opens, when a
2048
+ * redirect re-describes it, and when the record settles, so a description
2049
+ * refined during the hold is what every consumer ends up reading.
2050
+ */ function syncNavigation(e) {
2051
+ const {event: n, ref: t} = e;
2052
+ const o = n.origin;
2053
+ if (t.name === undefined) {
2054
+ delete o.name;
2055
+ delete n.name;
2056
+ } else o.name = n.name = t.name;
2057
+ if (t.to === undefined) {
2058
+ delete o.to;
2059
+ delete n.to;
2060
+ } else o.to = n.to = t.to;
2061
+ if (t.params === undefined) {
2062
+ delete o.params;
2063
+ delete n.params;
2064
+ } else o.params = n.params = t.params;
2065
+ }
2066
+
2067
+ function openNavigation(e, n) {
2068
+ const t = {
2069
+ at: e.at,
2070
+ writes: 0,
2071
+ origin: e
2072
+ };
2073
+ if (e.from !== undefined) t.from = e.from;
2074
+ if (e.interaction !== undefined) t.interaction = e.interaction;
2075
+ const o = {
2076
+ event: t,
2077
+ ref: n,
2078
+ open: 1,
2079
+ held: false,
2080
+ writeDrain: drainSeq
2081
+ };
2082
+ syncNavigation(o);
2083
+ navStates.set(e, o);
2084
+ openNavs.add(o);
2085
+ navigationLog.push(t);
2086
+ if (navigationLog.length > options.historyLimit) navigationLog.shift();
2087
+ noteInteractionNavigation(t);
2088
+ }
2089
+
2090
+ /** The navigation a redirect hop folds onto: the most recently opened one still pending. */ function lastOpenNavigation() {
2091
+ let e;
2092
+ for (const n of openNavs) e = n;
2093
+ return e;
2094
+ }
2095
+
2096
+ /** A redirect re-describes `state`: the current destination becomes a hop it abandoned. */ function redirectNavigation(e, n) {
2097
+ const t = e.event;
2098
+ // As the router last described the destination being left behind.
2099
+ syncNavigation(e);
2100
+ const o = {
2101
+ at: n.at ?? now()
2102
+ };
2103
+ if (t.name !== undefined) o.name = t.name;
2104
+ if (t.to !== undefined) o.to = t.to;
2105
+ if (t.params !== undefined) o.params = t.params;
2106
+ (t.redirects ??= []).push(o);
2107
+ e.ref = n;
2108
+ e.open++;
2109
+ syncNavigation(e);
2110
+ }
2111
+
2112
+ function closeNavigation(e) {
2113
+ const n = navStates.get(e);
2114
+ if (n === undefined || --n.open > 0) return;
2115
+ syncNavigation(n);
2116
+ // Nothing to wait for: no write survived the equality gate (navigating to
2117
+ // where we already are), or a drain inside the frame already committed
2118
+ // them (`flush(() => setLocation(…))`) with no hold.
2119
+ if (n.event.writes === 0 || !n.held && drainSeq > n.writeDrain) settleNavigation(n, "committed");
2120
+ }
2121
+
2122
+ /** stampWrite: the record replacing `prior` on a node was just stamped. */ function noteNavigationWrite(e, n) {
2123
+ const t = n.origin;
2124
+ if (t.kind === "navigation") {
2125
+ const e = navStates.get(t);
2126
+ if (e !== undefined) {
2127
+ e.event.writes++;
2128
+ e.writeDrain = drainSeq;
2129
+ }
2130
+ }
2131
+ // The node now carries a different frame's record: whatever `prior`'s
2132
+ // navigation was waiting to show on it will never land as that navigation.
2133
+ const o = e?.origin;
2134
+ if (o !== undefined && o !== t && o.kind === "navigation") {
2135
+ const e = navStates.get(o);
2136
+ if (e !== undefined && openNavs.has(e)) settleNavigation(e, "superseded");
2137
+ }
2138
+ }
2139
+
2140
+ /** holdStart: `t`'s staged writes are parked — their navigations settle with `t`. */ function markNavigationsHeld(e) {
2141
+ if (openNavs.size === 0) return;
2142
+ for (const n of e.In) {
2143
+ const e = n.ze?.origin;
2144
+ if (e?.kind !== "navigation") continue;
2145
+ const t = navStates.get(e);
2146
+ if (t !== undefined) t.held = true;
2147
+ }
2148
+ }
2149
+
2150
+ /** transitionSettled: `t` commits — the navigations whose writes it staged are done. */ function settleNavigations(e, n) {
2151
+ if (openNavs.size === 0) return;
2152
+ for (const t of e.In) {
2153
+ const e = t.ze?.origin;
2154
+ if (e?.kind !== "navigation") continue;
2155
+ const o = navStates.get(e);
2156
+ if (o === undefined || !openNavs.has(o)) continue;
2157
+ // A navigation whose frame is still open when its transition commits
2158
+ // (`until()` inside the frame) settles here too: its writes are through.
2159
+ settleNavigation(o, o.held ? "held" : "committed", n);
2160
+ }
2161
+ }
2162
+
2163
+ let openFlush = null;
2164
+
2165
+ function noteFlushRun(e, n, t) {
2166
+ if (n) e.created++; else e.runs++;
2167
+ if (t === undefined || e.interaction === null) return;
2168
+ if (e.interaction === undefined) e.interaction = t; else if (e.interaction !== t) e.interaction = null;
2169
+ }
2170
+
2171
+ function trackFlushStart() {
2172
+ if (!records.observed("flush")) return;
2173
+ openFlush = {
2174
+ at: now(),
2175
+ runs: 0,
2176
+ created: 0,
2177
+ held: false,
2178
+ interaction: undefined
2179
+ };
2180
+ }
2181
+
2182
+ /** The key for swaps no transaction carries — an object, so the map below can be weak. */ const DRAIN = {
2183
+ drain: true
2184
+ };
2185
+
2186
+ const openFallbacks = new WeakMap;
2187
+
2188
+ // Weak on the transaction: one that is dropped without settling or merging
2189
+ // (its boundary disposed, its queues discarded) takes its staged opens with it.
2190
+ const stagedFallbacks = new WeakMap;
2191
+
2192
+ /** Bumped by `resetTracking` — the engine's install generation. */ let trackingGen = 0;
2193
+
2194
+ function trackFallback(e, n, t, o) {
2195
+ if (t) {
2196
+ // Folds count showings too, and the flash finding needs the show's
2197
+ // clock: an open is kept for any of the three audiences.
2198
+ const t = records.observed("fallback");
2199
+ if (!t && folds.length === 0 && options.fallbackFlashes === false) return;
2200
+ // The wait is the enclosing recompute's cause's interaction — the read
2201
+ // that registered the pending source runs inside one — else the ambient.
2202
+ const i = enclosingCauses();
2203
+ const s = o ?? DRAIN;
2204
+ const r = {
2205
+ at: now(),
2206
+ gen: trackingGen,
2207
+ record: t,
2208
+ boundary: e,
2209
+ tree: n,
2210
+ interaction: i !== null ? interactionIn(i) : currentInteraction ?? undefined,
2211
+ staged: s
2212
+ };
2213
+ openFallbacks.set(e, r);
2214
+ const a = stagedFallbacks.get(s);
2215
+ if (a === undefined) stagedFallbacks.set(s, [ r ]); else a.push(r);
2216
+ return;
2217
+ }
2218
+ const i = openFallbacks.get(e);
2219
+ if (i === undefined) return;
2220
+ openFallbacks.delete(e);
2221
+ if (i.staged !== null) {
2222
+ // Cleared before its commit: never on screen.
2223
+ const e = stagedFallbacks.get(i.staged);
2224
+ e.splice(e.indexOf(i), 1);
2225
+ if (e.length === 0) stagedFallbacks.delete(i.staged);
2226
+ return;
2227
+ }
2228
+ if (i.gen !== trackingGen) return;
2229
+ // The hide has the subtree the first show may have lacked.
2230
+ const s = n ?? i.tree;
2231
+ for (const n of folds) n.fallback?.(e, s, false);
2232
+ const r = now() - i.at;
2233
+ if (options.fallbackFlashes !== false && r < FALLBACK_FLASH_MS) checkFallbackFlash(s, r, i.interaction);
2234
+ if (!i.record) return;
2235
+ const a = {
2236
+ at: i.at,
2237
+ shownMs: r
2238
+ };
2239
+ const c = s !== undefined ? ownerPath(s) : undefined;
2240
+ if (c !== undefined) a.ownerPath = c;
2241
+ if (i.interaction !== undefined) a.interaction = i.interaction;
2242
+ records.emit("fallback", a, s);
2243
+ }
2244
+
2245
+ /** flushEnd: the drain's committed swaps have rendered — those fallbacks are on screen from here. */ function displayFallbacks() {
2246
+ const e = stagedFallbacks.get(DRAIN);
2247
+ if (e === undefined) return;
2248
+ stagedFallbacks.delete(DRAIN);
2249
+ const n = now();
2250
+ for (const t of e) {
2251
+ t.staged = null;
2252
+ t.at = n;
2253
+ if (t.gen === trackingGen) for (const e of folds) e.fallback?.(t.boundary, t.tree, true);
2254
+ }
2255
+ }
2256
+
2257
+ /** transitionSettled (`from` a transaction, into this drain) and
2258
+ * transitionMerged (`from` the outgoing, into the surviving transaction):
2259
+ * the swaps staged under `from` now land with `into`. */ function rebaseFallbacks(e, n) {
2260
+ const t = stagedFallbacks.get(e);
2261
+ if (t === undefined) return;
2262
+ stagedFallbacks.delete(e);
2263
+ for (const e of t) e.staged = n;
2264
+ const o = stagedFallbacks.get(n);
2265
+ if (o === undefined) stagedFallbacks.set(n, t); else o.push(...t);
2266
+ }
2267
+
2268
+ /** flushEnd: every open, closed, unheld navigation's (and interaction's) writes just committed. */ function trackFlushEnd() {
2269
+ // The drain's own record first: the interactions it settles below waited on it.
2270
+ const e = openFlush;
2271
+ if (e !== null) {
2272
+ openFlush = null;
2273
+ const n = {
2274
+ at: e.at,
2275
+ durationMs: now() - e.at,
2276
+ runs: e.runs,
2277
+ created: e.created,
2278
+ held: e.held
2279
+ };
2280
+ if (e.interaction != null) n.interaction = e.interaction;
2281
+ records.emit("flush", n, undefined);
2282
+ }
2283
+ drainSeq++;
2284
+ // The swaps this drain committed have rendered.
2285
+ displayFallbacks();
2286
+ for (const e of openNavs) if (e.open === 0 && !e.held) settleNavigation(e, "committed");
2287
+ for (const e of openInteractions) maybeSettleInteraction(e);
2288
+ }
2289
+
2290
+ function settleNavigation(e, n, t) {
2291
+ if (!openNavs.has(e)) return;
2292
+ openNavs.delete(e);
2293
+ syncNavigation(e);
2294
+ const o = e.event;
2295
+ o.settledMs = now() - o.at;
2296
+ o.outcome = n;
2297
+ if (t !== undefined) o.hold = t;
2298
+ for (const e of folds) e.navigation?.(o);
2299
+ records.emit("navigation", o, undefined);
2300
+ trackGraph(o);
2301
+ // The interaction that performed it may have been waiting only on this.
2302
+ const i = openInteractionOf(o.interaction);
2303
+ if (i !== undefined) maybeSettleInteraction(i);
2304
+ }
2305
+
2306
+ const interactionStates = new WeakMap;
2307
+
2308
+ /** Opened, not yet settled. */ const openInteractions = new Set;
2309
+
2310
+ let interactionLog = [];
2311
+
2312
+ function openInteraction(e, n) {
2313
+ const t = {
2314
+ name: e.name,
2315
+ at: e.at,
2316
+ handlerMs: 0,
2317
+ writes: 0,
2318
+ runs: 0,
2319
+ created: 0,
2320
+ runMs: 0,
2321
+ holds: [],
2322
+ navigations: [],
2323
+ origin: e
2324
+ };
2325
+ if (e.target !== undefined) t.target = e.target;
2326
+ // The runtime may date the frame from the event's own timestamp (before
2327
+ // any queued task ran); the gap to here is the input delay the browser's
2328
+ // INP counts first.
2329
+ if (n > t.at) t.inputDelayMs = n - t.at;
2330
+ const o = {
2331
+ event: t,
2332
+ open: true,
2333
+ opened: n,
2334
+ writeDrain: drainSeq,
2335
+ heldIn: new Set,
2336
+ held: false,
2337
+ excludedWrites: 0,
2338
+ awaiting: false,
2339
+ actioned: false
2340
+ };
2341
+ interactionStates.set(e, o);
2342
+ openInteractions.add(o);
2343
+ interactionLog.push(t);
2344
+ if (interactionLog.length > options.historyLimit) interactionLog.shift();
2345
+ }
2346
+
2347
+ /**
2348
+ * How long the record waits on a handler's returned promise before settling
2349
+ * without it: a promise that never settles (a hung request, a listener
2350
+ * awaiting an event that never comes) must not keep the record open forever.
2351
+ */ const ASYNC_HANDLER_CAP_MS = 1e4;
2352
+
2353
+ /** interactionEnd: the handler returned. */ function closeInteraction(e, n) {
2354
+ const t = interactionStates.get(e);
2355
+ if (t === undefined) return;
2356
+ t.open = false;
2357
+ const o = now();
2358
+ t.event.handlerMs = o - t.opened;
2359
+ // `async () => { await save(); set(…) }` returns a promise and continues
2360
+ // past the frame; the person's wait is that continuation. The record stays
2361
+ // open until it settles (or the cap), then judges whether anything on
2362
+ // screen could have shown the wait.
2363
+ const i = n !== null && (typeof n === "object" || typeof n === "function") && typeof n.then === "function" ? n : null;
2364
+ if (i !== null) {
2365
+ t.awaiting = true;
2366
+ let e = false;
2367
+ let n;
2368
+ const settle = () => {
2369
+ if (e) return;
2370
+ e = true;
2371
+ if (n !== undefined) clearTimeout(n);
2372
+ if (!openInteractions.has(t)) return;
2373
+ t.awaiting = false;
2374
+ const i = now();
2375
+ t.event.continuationMs = i - o;
2376
+ checkUntrackedAsyncHandler(t);
2377
+ maybeSettleInteraction(t, i);
2378
+ };
2379
+ n = setTimeout(settle, ASYNC_HANDLER_CAP_MS);
2380
+ // A pending cap must not hold a Node process (tests, SSR harnesses) open.
2381
+ n.unref?.();
2382
+ // Both branches: a rejected handler promise still ended the wait.
2383
+ i.then(settle, settle);
2384
+ return;
2385
+ }
2386
+ maybeSettleInteraction(t, o);
2387
+ }
2388
+
2389
+ /**
2390
+ * The handler awaited past its frame with nothing in the graph carrying the
2391
+ * wait: no root write before the `await` (a pending flag, an optimistic
2392
+ * value) and no action step (an action's steps stay attributed across
2393
+ * yields, and its holds are judged by SILENT_HOLD). From the person's side
2394
+ * the click did nothing for `continuationMs`; from the engine's side the
2395
+ * wait is invisible — no hold opened, so no hold could be acknowledged.
2396
+ * Thresholds are the hold thresholds: it is the same wait.
2397
+ */ function checkUntrackedAsyncHandler(e) {
2398
+ const n = options.holds;
2399
+ if (n === false) return;
2400
+ const t = e.event;
2401
+ const o = t.continuationMs;
2402
+ if (e.actioned || t.writes > 0 || o < n.infoMs) return;
2403
+ const i = formatOrigin(t.origin);
2404
+ const s = `[UNTRACKED_ASYNC_HANDLER] ${i}'s handler awaited ${o.toFixed(0)}ms past its frame with no ` + `write before the await: no hold opened, so nothing on screen could show the wait — the ` + `interaction was dead for ${o.toFixed(0)}ms. Make the async work an action() (its steps stay ` + `attributed across yields and its hold is judged), or write the pending state first: a ` + `createOptimistic(false) "saving" flag the UI reads.`;
2405
+ const r = o >= n.warnMs ? "warn" : "info";
2406
+ const a = {
2407
+ interaction: {
2408
+ type: t.name,
2409
+ target: t.target
2410
+ },
2411
+ continuationMs: o,
2412
+ capped: o >= ASYNC_HANDLER_CAP_MS
2413
+ };
2414
+ emitDiagnostic({
2415
+ code: "UNTRACKED_ASYNC_HANDLER",
2416
+ kind: "responsiveness",
2417
+ severity: r,
2418
+ message: s,
2419
+ data: a
2420
+ }, null);
2421
+ }
2422
+
2423
+ /** The open record a frame runs under, if any. */ function openInteractionOf(e) {
2424
+ const n = interactionOf(e);
2425
+ if (n === undefined) return undefined;
2426
+ const t = interactionStates.get(n);
2427
+ return t !== undefined && openInteractions.has(t) ? t : undefined;
2428
+ }
2429
+
2430
+ /** stampWrite: a root write stamped `origin`. */ function noteInteractionWrite(e, n) {
2431
+ const t = openInteractionOf(e);
2432
+ if (t === undefined) return;
2433
+ if (n) {
2434
+ t.excludedWrites++;
2435
+ return;
2436
+ }
2437
+ t.event.writes++;
2438
+ t.writeDrain = drainSeq;
2439
+ }
2440
+
2441
+ /** recordRerun / a create run: work attributed to the interaction. */ function noteInteractionRun(e, n, t) {
2442
+ const o = openInteractionOf(e);
2443
+ if (o === undefined) return;
2444
+ o.event[t ? "created" : "runs"]++;
2445
+ o.event.runMs += n;
2446
+ }
2447
+
2448
+ /** openNavigation: a navigation frame opened under the interaction. */ function noteInteractionNavigation(e) {
2449
+ const n = openInteractionOf(e.interaction);
2450
+ if (n !== undefined) n.event.navigations.push(e);
2451
+ }
2452
+
2453
+ /** holdStart: `t` parked writes — the interactions that performed them wait for `t`. */ function markInteractionsHeld(e) {
2454
+ if (openInteractions.size === 0) return;
2455
+ for (const n of e.In) {
2456
+ const t = openInteractionOf(n.ze?.origin);
2457
+ if (t !== undefined) {
2458
+ t.heldIn.add(e);
2459
+ t.held = true;
2460
+ }
2461
+ }
2462
+ }
2463
+
2464
+ /** transitionMerged: whoever waited for `outgoing` now waits for `target`. */ function mergeInteractionsHeld(e, n) {
2465
+ for (const t of openInteractions) if (t.heldIn.delete(n)) t.heldIn.add(e);
2466
+ }
2467
+
2468
+ /** transitionSettled: `t` committed — its holders' writes are through. */ function settleInteractionsHeld(e, n) {
2469
+ if (openInteractions.size === 0) return;
2470
+ for (const t of openInteractions) {
2471
+ if (!t.heldIn.delete(e)) continue;
2472
+ if (n !== undefined) t.event.holds.push(n);
2473
+ maybeSettleInteraction(t);
2474
+ }
2475
+ }
2476
+
2477
+ function maybeSettleInteraction(e, n = now()) {
2478
+ const t = e.event;
2479
+ if (e.open || e.awaiting || e.heldIn.size > 0) return;
2480
+ // A drain must have committed the last write (the handler's, or a redirect
2481
+ // hop's after the click's own drain) — the handler returning is not the
2482
+ // screen having it.
2483
+ if (t.writes > 0 && drainSeq <= e.writeDrain) return;
2484
+ for (const e of t.navigations) if (e.outcome === undefined) return;
2485
+ openInteractions.delete(e);
2486
+ // Every write went to an excluded subject and nothing of the app's ran: the
2487
+ // click was on the observer's own UI (a devtools panel's button). Not a
2488
+ // fact about the app — forget it rather than report a dead interaction.
2489
+ if (t.writes === 0 && e.excludedWrites > 0 && t.runs === 0 && t.created === 0) {
2490
+ const e = interactionLog.indexOf(t);
2491
+ if (e !== -1) interactionLog.splice(e, 1);
2492
+ return;
2493
+ }
2494
+ t.settledMs = n - t.at;
2495
+ t.outcome = t.writes === 0 ? "idle" : e.held ? "held" : "committed";
2496
+ records.emit("interaction", t, undefined);
2497
+ }
2498
+
2499
+ /** The serializable face of a navigation origin for diagnostic `data`. */ function navigationData(e) {
2500
+ const n = {};
2501
+ if (e.name !== undefined) n.name = e.name;
2502
+ if (e.to !== undefined) n.to = e.to;
2503
+ if (e.from !== undefined) n.from = e.from;
2504
+ if (e.params !== undefined) n.params = e.params;
2505
+ return n;
2506
+ }
2507
+
2508
+ // The engine's implementation of the core's dev hook points. Installed by
2509
+ // enable(), uninstalled by disable() — while uninstalled the core pays one
2510
+ // null check per site and nothing else.
2511
+ let asyncStartSeq = 0;
2512
+
2513
+ let asyncStartTime = 0;
2514
+
2515
+ let asyncStartValue;
2516
+
2517
+ const engineHooks = {
2518
+ interactionStart: interactionStart,
2519
+ interactionEnd: interactionEnd,
2520
+ originStart: originStart,
2521
+ originEnd: originEnd,
2522
+ flushStart() {
2523
+ trackFlushStart();
2524
+ },
2525
+ flushEnd() {
2526
+ trackFlushEnd();
2527
+ },
2528
+ recomputeStart(e, n) {
2529
+ const t = n ? null : collectCauses(e);
2530
+ frames.push({
2531
+ start: now(),
2532
+ childMs: 0,
2533
+ causes: t,
2534
+ // The record's dep diff needs the deps as they were: captured here,
2535
+ // and only when the record will have an audience (see wantsRerun).
2536
+ prevDeps: n || !wantsRerun() ? null : captureDeps(e),
2537
+ // Mirror recompute's own prev-value resolution: an earlier run in the
2538
+ // same flush may still be holding in _pendingValue.
2539
+ prevValue: e._e !== NOT_PENDING ? e._e : e.ce,
2540
+ // A create run inherits the interaction of whatever is building it: the
2541
+ // enclosing recompute (a parent's fn creating children) or, at the top
2542
+ // of the recompute stack, the effect callback / handler frame.
2543
+ interaction: t !== null ? interactionIn(t) : frames.length > 0 ? frames[frames.length - 1].interaction : enclosingInteraction()
2544
+ });
2545
+ },
2546
+ derivedChanged(e) {
2547
+ const n = frames[frames.length - 1];
2548
+ stampDerived(e, n !== undefined && n.causes !== null ? n.causes : []);
2549
+ },
2550
+ recomputeEnd(e, n, t, o, i, s) {
2551
+ const r = frames.pop();
2552
+ // enable() can land mid-recompute: no opening frame, nothing to report.
2553
+ if (r === undefined) return;
2554
+ const a = now() - r.start;
2555
+ if (frames.length > 0) frames[frames.length - 1].childMs += a;
2556
+ const c = Math.max(0, a - r.childMs);
2557
+ // Effect-output honesty: effects run with `_equals: false`, so core
2558
+ // reports EVERY effect recompute as changed — which made effect waste
2559
+ // invisible to costs() (and compiled JSX bindings are effects: the
2560
+ // fan-out waste a naive selected-row produces is all effects). The
2561
+ // engine re-derives the fact from its own snapshot: an identical
2562
+ // committed compute output is an unchanged run. `undefined` outputs are
2563
+ // exempt — a side-effect-only compute's work IS its effect phase, and
2564
+ // identity of `undefined` proves nothing.
2565
+ if (t && r.causes !== null && e.He) {
2566
+ const n = e._e !== NOT_PENDING ? e._e : e.ce;
2567
+ if (n !== undefined && n === r.prevValue) t = false;
2568
+ }
2569
+ // Unstable-output check: memos only, non-create, plain runs with a
2570
+ // committed change. The fresh value sits in `_pendingValue` for held
2571
+ // plain-flush memo commits and in `_value` for direct ones. Overlay runs
2572
+ // are excluded — an optimistic re-derive legitimately produces fresh
2573
+ // equivalents while the lane settles.
2574
+ if (r.causes !== null && t && !o && !i && !e.He) checkUnstableOutput(e, r.prevValue, e._e !== NOT_PENDING ? e._e : e.ce);
2575
+ if (r.causes !== null) recordRerun(e, r, {
2576
+ selfMs: c,
2577
+ totalMs: a
2578
+ }, t, o ? "optimistic" : i ? "held" : "plain", s); else if (!excludedNode(e)) {
2579
+ // Creation runs still get the wide-scope check: a memo can be born with
2580
+ // its coarse-read problem already in place — and their time is charged
2581
+ // to the interaction building them (the interaction record's `created`).
2582
+ checkDepWidth(e);
2583
+ noteInteractionRun(r.interaction, c, true);
2584
+ // The first effect callback runs with no re-run record to inherit from;
2585
+ // hand it the interaction that built the node (see effectRunStart).
2586
+ e.pn = r.interaction;
2587
+ if (openFlush !== null) noteFlushRun(openFlush, true, r.interaction);
2588
+ if (records.observed("create")) {
2589
+ const n = {
2590
+ at: r.start,
2591
+ nodeKind: nodeKind(e),
2592
+ nodeName: nodeName(e),
2593
+ nodeId: devId(e),
2594
+ depCount: captureDeps(e).length,
2595
+ selfMs: c,
2596
+ totalMs: a,
2597
+ phase: o ? "optimistic" : i ? "held" : "plain",
2598
+ held: s
2599
+ };
2600
+ if (r.interaction !== undefined) n.interaction = r.interaction;
2601
+ records.emit("create", n, e);
2602
+ }
2603
+ }
2604
+ markSeen(e);
2605
+ },
2606
+ write(e, n, t) {
2607
+ stampWrite(e, "write", n, t);
2608
+ },
2609
+ refreshed(e) {
2610
+ stampWrite(e, "refresh");
2611
+ },
2612
+ flightStart(e, n) {
2613
+ trackFlightStart(e, n);
2614
+ },
2615
+ asyncStart(e) {
2616
+ asyncStartSeq = e.ze?.seq ?? 0;
2617
+ asyncStartTime = e.Ge;
2618
+ asyncStartValue = e.ce;
2619
+ },
2620
+ asyncEnd(e, n, t, o) {
2621
+ if (o) {
2622
+ // Core calls this unconditionally (hook calls cannot live inside its
2623
+ // try blocks — see attribution-hooks.ts), so committed-ness is detected
2624
+ // here against the asyncStart snapshot: a direct commit moves `_value`
2625
+ // (or `_time`, for a same-reference commit under `equals: false`), and
2626
+ // a transition hold parks the value in `_pendingValue`. A landing the
2627
+ // equality gate swallowed moves none of them and must leave no stamp.
2628
+ const o = e.ce !== asyncStartValue || e.Ge !== asyncStartTime || e._e === t;
2629
+ if (o) stampWrite(e, "async", n === undefined ? NO_VALUES : n, t);
2630
+ // Flight over either way — an equality-swallowed landing still spent
2631
+ // the wall time (finalizeFlight only chains through a fresh stamp).
2632
+ finalizeFlight(e);
2633
+ return;
2634
+ }
2635
+ // Landed through setSignal: reclassify its "write" stamp as an async
2636
+ // landing — but only if it actually stamped (the value changed) since
2637
+ // asyncStart; a no-change landing must leave no fresh stamp behind.
2638
+ const i = e.ze;
2639
+ if (i !== undefined && i.seq > asyncStartSeq && i.kind === "write") stampWrite(e, "async", NO_VALUES, t);
2640
+ finalizeFlight(e);
2641
+ },
2642
+ effectRunStart(e) {
2643
+ pushFrame("effect", nodeName(e), e.pn, e);
2644
+ // The frame's own `at` doubles as the record's start: set only while
2645
+ // listened, so a listener arriving mid-callback finds no start and the
2646
+ // end emits nothing for it — and an unlistened callback pays no clock read.
2647
+ if (records.observed("effect")) originFrames[originFrames.length - 1].at = now();
2648
+ },
2649
+ effectRunEnd(e) {
2650
+ const n = originFrames[originFrames.length - 1];
2651
+ if (n !== undefined && n.kind === "effect" && n.at !== undefined) {
2652
+ if (!excludedNode(e)) {
2653
+ const t = {
2654
+ at: n.at,
2655
+ durationMs: now() - n.at,
2656
+ nodeId: devId(e),
2657
+ nodeName: nodeName(e)
2658
+ };
2659
+ if (n.run !== undefined) t.run = n.run;
2660
+ if (n.interaction !== undefined) t.interaction = n.interaction;
2661
+ records.emit("effect", t, e);
2662
+ }
2663
+ }
2664
+ popFrame("effect");
2665
+ if (activeHold !== null) activeHold.painted++;
2666
+ },
2667
+ actionStepStart(e, n) {
2668
+ // Steps after a yield resume from a promise callback with no ambient
2669
+ // interaction; the one that started the action (its first step) is the
2670
+ // action's interaction for every step.
2671
+ let t = actionInteractions.get(e);
2672
+ if (t === undefined && !actionInteractions.has(e)) {
2673
+ t = currentInteraction ?? undefined;
2674
+ actionInteractions.set(e, t);
2675
+ // The handler's async work is an action's: tracked across yields.
2676
+ const n = t !== undefined ? interactionStates.get(t) : undefined;
2677
+ if (n !== undefined) n.actioned = true;
2678
+ }
2679
+ pushFrame("action", n, t);
2680
+ },
2681
+ actionStepEnd() {
2682
+ popFrame("action");
2683
+ },
2684
+ holdStart(e) {
2685
+ if (openFlush !== null) openFlush.held = true;
2686
+ trackHoldStart(e);
2687
+ },
2688
+ holdEnd() {
2689
+ activeHold = null;
2690
+ },
2691
+ transitionSettled(e) {
2692
+ trackHoldSettled(e);
2693
+ rebaseFallbacks(e, DRAIN);
2694
+ },
2695
+ transitionMerged(e, n) {
2696
+ trackHoldMerge(e, n);
2697
+ rebaseFallbacks(n, e);
2698
+ },
2699
+ storeReplaced(e, n, t, o, i, s) {
2700
+ checkImmutableUpdate(e, n, t, o, i, s);
2701
+ },
2702
+ listChurn(e, n, t, o, i) {
2703
+ checkListIdentity(e, n, t, o, i);
2704
+ },
2705
+ boundaryFallback(e, n, t, o) {
2706
+ // The folds hear the show at its display (see trackFallback), not here.
2707
+ trackFallback(e, n, t, o ?? null);
2708
+ },
2709
+ optimisticReverted(e, n, t, o) {
2710
+ checkOptimisticRevert(e, n, t, o);
2711
+ },
2712
+ currentOrigin() {
2713
+ return ambientOrigin();
2714
+ }
2715
+ };
2716
+
2717
+ const holds = [];
2718
+
2719
+ /**
2720
+ * The windows: what a consumer reads back — the ring buffers, the once-only
2721
+ * warning memories (so a new window can warn again), the hot-cause windows,
2722
+ * the folds' tables. Reset by every `enable()` (each opens a fresh window)
2723
+ * and by the last `disable()`. Never touches the live tracking state —
2724
+ * open frames, open interactions and navigations, the active hold,
2725
+ * `drainSeq` — which belongs to whoever is mid-flight when a second
2726
+ * consumer arrives.
2727
+ */ function resetWindows() {
2728
+ history = [];
2729
+ waterfallLog = [];
2730
+ holdLog = [];
2731
+ navigationLog = [];
2732
+ interactionLog = [];
2733
+ reportedCycles.clear();
2734
+ relays.clear();
2735
+ immutableReported.clear();
2736
+ hotCauses.clear();
2737
+ for (const e of folds) e.reset?.();
2738
+ }
2739
+
2740
+ /** The live tracking state — reset only when the engine is (un)installed. */ function resetTracking() {
2741
+ frames.length = 0;
2742
+ activeHold = null;
2743
+ openFlush = null;
2744
+ stagedFallbacks.delete(DRAIN);
2745
+ trackingGen++;
2746
+ openNavs.clear();
2747
+ openInteractions.clear();
2748
+ routeCounts.clear();
2749
+ drainSeq = 0;
2750
+ originFrames.length = 0;
2751
+ effectStack.length = 0;
2752
+ interactionStack.length = 0;
2753
+ currentInteraction = null;
2754
+ }
2755
+
2756
+ /**
2757
+ * One hold's request in full: the defaults for what it left unsaid (an
2758
+ * explicit `undefined` is unsaid), and `checks: false` folding its five cost
2759
+ * checks off before anyone else's request is considered.
2760
+ */ function resolveHold(e) {
2761
+ const n = {
2762
+ ...defaultOptions
2763
+ };
2764
+ if (e !== undefined) {
2765
+ for (const t of Object.keys(e)) {
2766
+ const o = e[t];
2767
+ if (o !== undefined) n[t] = o;
2768
+ }
2769
+ }
2770
+ if (!n.checks) {
2771
+ n.hotRuns = false;
2772
+ n.hotTime = false;
2773
+ n.wideDeps = false;
2774
+ n.unstableMemos = false;
2775
+ n.fanOut = false;
2776
+ n.wastedRecompute = false;
2777
+ }
2778
+ return n;
2779
+ }
2780
+
2781
+ /** `values` levels by how much they carry: the merge takes the lowest. */ const VALUES_RANK = {
2782
+ none: 0,
2783
+ labels: 1,
2784
+ full: 2
2785
+ };
2786
+
2787
+ /**
2788
+ * The more demanding of two settings for one key: `true` over `false`, the
2789
+ * larger `historyLimit`, a threshold config over `false`, and between two
2790
+ * configs the field values that fire sooner — the lower count, budget or
2791
+ * millisecond bound, the longer `windowMs`. For `values` "more demanding"
2792
+ * is LESS data: the level that carries the least wins, so a holder that
2793
+ * must not see user data is never overruled by one that wants it.
2794
+ */ function demanding(e, n, t) {
2795
+ if (e === "values") return VALUES_RANK[n] <= VALUES_RANK[t] ? n : t;
2796
+ if (typeof n === "boolean") return n || t;
2797
+ if (e === "historyLimit") return Math.max(n, t);
2798
+ if (n === false) return t;
2799
+ if (t === false) return n;
2800
+ if (typeof n === "number") return Math.min(n, t);
2801
+ const o = {};
2802
+ for (const e in n) {
2803
+ const i = n[e];
2804
+ const s = t[e];
2805
+ o[e] = e === "windowMs" ? Math.max(i, s) : Math.min(i, s);
2806
+ }
2807
+ return o;
2808
+ }
2809
+
2810
+ /**
2811
+ * Recompute the options in effect: each live hold's request resolved, then
2812
+ * combined per key by the most demanding value — the one that has the
2813
+ * engine observe more, report more or keep more. A hold says what it wants
2814
+ * and can only add to what another hold asked for, never take it away, so
2815
+ * the result does not depend on the order the holds were taken: the console
2816
+ * log prints while any holder wants it, a check runs while any holder wants
2817
+ * it and at the most sensitive threshold anyone asked for, the ring buffer
2818
+ * is the largest requested, and records carry the least user data any
2819
+ * holder allows (`values`). With no hold outstanding the defaults stand.
2820
+ */ function applyOptions() {
2821
+ if (holds.length === 0) {
2822
+ options = {
2823
+ ...defaultOptions
2824
+ };
2825
+ return;
2826
+ }
2827
+ const e = resolveHold(holds[0].opts);
2828
+ for (let n = 1; n < holds.length; n++) {
2829
+ const t = resolveHold(holds[n].opts);
2830
+ for (const n in e) e[n] = demanding(n, e[n], t[n]);
2831
+ }
2832
+ options = e;
2833
+ }
2834
+
2835
+ /** The last hold is gone (or `disable()` was called): uninstall and clear everything. */ function uninstall() {
2836
+ holds.length = 0;
2837
+ applyOptions();
2838
+ attributionActive = false;
2839
+ resetWindows();
2840
+ resetTracking();
2841
+ setAttributionHooks(null);
2842
+ }
2843
+
2844
+ const attribution = {
2845
+ enable(e) {
2846
+ const n = {
2847
+ opts: e
2848
+ };
2849
+ holds.push(n);
2850
+ applyOptions();
2851
+ resetWindows();
2852
+ if (!attributionActive) {
2853
+ attributionActive = true;
2854
+ resetTracking();
2855
+ setAttributionHooks(engineHooks);
2856
+ }
2857
+ return () => {
2858
+ const e = holds.indexOf(n);
2859
+ if (e === -1) return;
2860
+ holds.splice(e, 1);
2861
+ if (holds.length === 0) uninstall(); else applyOptions();
2862
+ };
2863
+ },
2864
+ disable() {
2865
+ uninstall();
2866
+ },
2867
+ history(e) {
2868
+ let n;
2869
+ switch (e) {
2870
+ case "rerun":
2871
+ n = history;
2872
+ break;
2873
+
2874
+ case "waterfall":
2875
+ n = waterfallLog;
2876
+ break;
2877
+
2878
+ case "hold":
2879
+ n = holdLog;
2880
+ break;
2881
+
2882
+ case "navigation":
2883
+ n = navigationLog;
2884
+ break;
2885
+
2886
+ case "interaction":
2887
+ n = interactionLog;
2888
+ break;
2889
+
2890
+ default:
2891
+ throw new Error(`attribution.history: unknown record type "${String(e)}"`);
2892
+ }
2893
+ // The buffers are typed by their variable; the switch is the proof.
2894
+ return n;
2895
+ },
2896
+ markFlight(e, n = now()) {
2897
+ // Earliest wins: re-marking (a cache re-serving the same promise) must
2898
+ // not move the origin later.
2899
+ const t = flightOrigins.get(e);
2900
+ if (t === undefined || n < t) flightOrigins.set(e, n);
2901
+ }
2902
+ };
2903
+
2904
+ export { FALLBACK_FLASH_MS, attribution, formatOrigin, formatRerun, graphSize, nodeIdOf, nodeName, now, registerFold, rootsOf };