@solidjs/signals 2.0.0-rc.2 → 2.0.0-rc.20

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