@solidjs/signals 2.0.0-rc.7 → 2.0.0-rc.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/dev-shared.js +6357 -0
- package/dist/dev.attribution.js +2485 -0
- package/dist/dev.js +2851 -7027
- package/dist/observe/affects.js +129 -0
- package/dist/observe/attribution.js +7 -0
- package/dist/observe/boundaries.js +641 -0
- package/dist/observe/core/action.js +177 -0
- package/dist/observe/core/async.js +846 -0
- package/dist/observe/core/attribution-costs.js +66 -0
- package/dist/observe/core/attribution-feedback.js +282 -0
- package/dist/observe/core/attribution-hooks.js +82 -0
- package/dist/observe/core/attribution-queries.js +28 -0
- package/dist/observe/core/attribution.js +2095 -0
- package/dist/observe/core/constants.js +248 -0
- package/dist/{types-cjs/core/context.d.cts → observe/core/context.js} +37 -12
- package/dist/observe/core/core.js +1789 -0
- package/dist/observe/core/dev.js +293 -0
- package/dist/observe/core/effect.js +195 -0
- package/dist/observe/core/error-hooks.js +71 -0
- package/dist/observe/core/error.js +80 -0
- package/dist/observe/core/external.js +98 -0
- package/dist/observe/core/graph.js +155 -0
- package/dist/observe/core/heap.js +147 -0
- package/dist/observe/core/invariants.js +45 -0
- package/dist/observe/core/lanes.js +205 -0
- package/dist/observe/core/optimistic.js +585 -0
- package/dist/observe/core/owner.js +322 -0
- package/dist/observe/core/scheduler.js +1428 -0
- package/dist/observe/core/verdict.js +669 -0
- package/dist/observe/index.js +59 -0
- package/dist/observe/map.js +484 -0
- package/dist/{types-cjs/signals.d.cts → observe/signals.js} +311 -317
- package/dist/observe/store/index.js +40 -0
- package/dist/observe/store/next/optimistic.js +660 -0
- package/dist/observe/store/next/projection.js +255 -0
- package/dist/observe/store/next/reconcile.js +375 -0
- package/dist/observe/store/next/store.js +2327 -0
- package/dist/observe/store/next/target.js +51 -0
- package/dist/observe/store/store.js +325 -0
- package/dist/observe/store/storePath.js +103 -0
- package/dist/observe/store/utils.js +1023 -0
- package/dist/prod/attribution.js +41 -0
- package/dist/prod/boundaries.js +128 -76
- package/dist/prod/core/action.js +65 -37
- package/dist/prod/core/async.js +324 -172
- package/dist/prod/core/constants.js +57 -1
- package/dist/prod/core/context.js +3 -3
- package/dist/prod/core/core.js +1003 -364
- package/dist/prod/core/dev.js +17 -1
- package/dist/prod/core/effect.js +76 -42
- package/dist/prod/core/error-hooks.js +71 -0
- package/dist/prod/core/external.js +4 -4
- package/dist/prod/core/graph.js +37 -37
- package/dist/prod/core/heap.js +61 -56
- package/dist/prod/core/lanes.js +107 -63
- package/dist/prod/core/optimistic.js +374 -93
- package/dist/prod/core/owner.js +62 -46
- package/dist/prod/core/scheduler.js +653 -286
- package/dist/prod/core/verdict.js +245 -127
- package/dist/prod/index.js +15 -5
- package/dist/prod/map.js +292 -141
- package/dist/prod/signals.js +29 -16
- package/dist/prod/store/next/optimistic.js +77 -55
- package/dist/prod/store/next/projection.js +31 -20
- package/dist/prod/store/next/reconcile.js +87 -84
- package/dist/prod/store/next/store.js +718 -401
- package/dist/prod/store/next/target.js +32 -10
- package/dist/prod/store/store.js +12 -14
- package/dist/prod/store/utils.js +950 -130
- package/dist/types/attribution.d.ts +20 -0
- package/dist/types/attribution.prod.d.ts +22 -0
- package/dist/types/boundaries.d.ts +10 -1
- package/dist/types/core/action.d.ts +12 -5
- package/dist/types/core/async.d.ts +1 -1
- package/dist/types/core/attribution-costs.d.ts +35 -0
- package/dist/types/core/attribution-feedback.d.ts +133 -0
- package/dist/types/core/attribution-hooks.d.ts +147 -9
- package/dist/types/core/attribution-queries.d.ts +10 -0
- package/dist/types/core/attribution.d.ts +216 -182
- package/dist/types/core/constants.d.ts +56 -0
- package/dist/types/core/core.d.ts +190 -2
- package/dist/types/core/dev.d.ts +246 -28
- package/dist/types/core/effect.d.ts +8 -1
- package/dist/types/core/error-hooks.d.ts +71 -0
- package/dist/types/core/index.d.ts +4 -1
- package/dist/types/core/invariants.d.ts +4 -0
- package/dist/types/core/lanes.d.ts +39 -5
- package/dist/types/core/scheduler.d.ts +153 -0
- package/dist/types/core/types.d.ts +32 -9
- package/dist/types/index.d.ts +10 -3
- package/dist/types/map.d.ts +2 -0
- package/dist/types/signals.d.ts +8 -0
- package/dist/types/store/index.d.ts +2 -0
- package/dist/types/store/next/optimistic.d.ts +1 -1
- package/dist/types/store/next/store.d.ts +11 -5
- package/dist/types/store/next/target.d.ts +37 -10
- package/dist/types/store/utils.d.ts +178 -0
- package/package.json +21 -17
- package/dist/node.cjs +0 -10541
- package/dist/node.dev.cjs +0 -13724
- package/dist/types-cjs/affects.d.cts +0 -47
- package/dist/types-cjs/boundaries.d.cts +0 -175
- package/dist/types-cjs/core/action.d.cts +0 -64
- package/dist/types-cjs/core/async.d.cts +0 -23
- package/dist/types-cjs/core/attribution-hooks.d.cts +0 -127
- package/dist/types-cjs/core/attribution.d.cts +0 -495
- package/dist/types-cjs/core/constants.d.cts +0 -159
- package/dist/types-cjs/core/core.d.cts +0 -185
- package/dist/types-cjs/core/dev.d.cts +0 -136
- package/dist/types-cjs/core/effect.d.cts +0 -30
- package/dist/types-cjs/core/error.d.cts +0 -56
- package/dist/types-cjs/core/external.d.cts +0 -15
- package/dist/types-cjs/core/graph.d.cts +0 -28
- package/dist/types-cjs/core/heap.d.cts +0 -24
- package/dist/types-cjs/core/index.d.cts +0 -13
- package/dist/types-cjs/core/invariants.d.cts +0 -59
- package/dist/types-cjs/core/lanes.d.cts +0 -54
- package/dist/types-cjs/core/optimistic.d.cts +0 -6
- package/dist/types-cjs/core/owner.d.cts +0 -124
- package/dist/types-cjs/core/scheduler.d.cts +0 -236
- package/dist/types-cjs/core/types.d.cts +0 -204
- package/dist/types-cjs/core/verdict.d.cts +0 -2
- package/dist/types-cjs/index.d.cts +0 -10
- package/dist/types-cjs/map.d.cts +0 -69
- package/dist/types-cjs/package.json +0 -3
- package/dist/types-cjs/store/index.d.cts +0 -18
- package/dist/types-cjs/store/next/optimistic.d.cts +0 -25
- package/dist/types-cjs/store/next/projection.d.cts +0 -8
- package/dist/types-cjs/store/next/reconcile.d.cts +0 -10
- package/dist/types-cjs/store/next/store.d.cts +0 -121
- package/dist/types-cjs/store/next/target.d.cts +0 -166
- package/dist/types-cjs/store/store.d.cts +0 -143
- package/dist/types-cjs/store/storePath.d.cts +0 -58
- package/dist/types-cjs/store/utils.d.cts +0 -74
|
@@ -0,0 +1,2485 @@
|
|
|
1
|
+
import {
|
|
2
|
+
bK as setAttributionHooks,
|
|
3
|
+
b as NOT_PENDING,
|
|
4
|
+
ax as reportDiagnostic,
|
|
5
|
+
ay as emitDiagnostic,
|
|
6
|
+
bL as isSuppressed,
|
|
7
|
+
bM as recordSubject,
|
|
8
|
+
bN as anyExcluded,
|
|
9
|
+
bO as isExcluded,
|
|
10
|
+
q as CONFIG_DERIVED_OVERRIDE,
|
|
11
|
+
bP as GRAPH_SIZE_WARN_AT,
|
|
12
|
+
bF as ownerPath,
|
|
13
|
+
bQ as subjectOf,
|
|
14
|
+
aT as $REFRESH
|
|
15
|
+
} from "./dev-shared.js";
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Under an owner the observer marked as its own (`OBSERVE.exclude`): the
|
|
19
|
+
* engine records nothing about the node. Cached per node once any exclusion
|
|
20
|
+
* exists; before that the answer is a flag read.
|
|
21
|
+
*/
|
|
22
|
+
function excludedNode(el) {
|
|
23
|
+
if (!anyExcluded()) return false;
|
|
24
|
+
const node = el;
|
|
25
|
+
if (node._devExcluded === undefined) node._devExcluded = isExcluded(el);
|
|
26
|
+
return node._devExcluded;
|
|
27
|
+
}
|
|
28
|
+
let changeSeq = 0;
|
|
29
|
+
let runSeq = 0;
|
|
30
|
+
const defaultOptions = {
|
|
31
|
+
log: true,
|
|
32
|
+
stacks: false,
|
|
33
|
+
historyLimit: 200,
|
|
34
|
+
hotRuns: { count: 120, windowMs: 1000 },
|
|
35
|
+
wideDeps: 30,
|
|
36
|
+
hotTime: { budgetMs: 8, windowMs: 1000 },
|
|
37
|
+
unstableMemos: 4,
|
|
38
|
+
wideWrites: 250,
|
|
39
|
+
waterfalls: { minFlightMs: 50 },
|
|
40
|
+
holds: { infoMs: 100, warnMs: 200 },
|
|
41
|
+
longHolds: { infoMs: 500, warnMs: 1000 }
|
|
42
|
+
};
|
|
43
|
+
let options = { ...defaultOptions };
|
|
44
|
+
let history = [];
|
|
45
|
+
const recordListeners = {
|
|
46
|
+
rerun: new Set(),
|
|
47
|
+
interaction: new Set(),
|
|
48
|
+
hold: new Set(),
|
|
49
|
+
navigation: new Set()
|
|
50
|
+
};
|
|
51
|
+
function emitRecord(type, record) {
|
|
52
|
+
for (const listener of recordListeners[type]) listener(record);
|
|
53
|
+
}
|
|
54
|
+
function clearListeners() {
|
|
55
|
+
for (const type in recordListeners) recordListeners[type].clear();
|
|
56
|
+
}
|
|
57
|
+
/** @internal The engine's clock: `performance.now()` where it exists. */
|
|
58
|
+
const now = typeof performance !== "undefined" ? () => performance.now() : () => Date.now();
|
|
59
|
+
const frames = [];
|
|
60
|
+
const folds = [];
|
|
61
|
+
/** @internal */
|
|
62
|
+
function registerFold(hooks) {
|
|
63
|
+
folds.push(hooks);
|
|
64
|
+
}
|
|
65
|
+
/** @internal Root cause names of a cause chain — the writes/landings/refreshes the chain bottoms out in. */
|
|
66
|
+
function rootsOf(causes, out) {
|
|
67
|
+
for (const c of causes) {
|
|
68
|
+
if (c.kind === "derived" && c.causes && c.causes.length > 0) rootsOf(c.causes, out);
|
|
69
|
+
else out.add(c.name);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
function nodeName(node) {
|
|
73
|
+
return node._name ?? "anonymous";
|
|
74
|
+
}
|
|
75
|
+
function preview(v) {
|
|
76
|
+
if (v === null) return "null";
|
|
77
|
+
switch (typeof v) {
|
|
78
|
+
case "undefined":
|
|
79
|
+
return "undefined";
|
|
80
|
+
case "string":
|
|
81
|
+
return JSON.stringify(v.length > 40 ? v.slice(0, 40) + "…" : v);
|
|
82
|
+
case "number":
|
|
83
|
+
case "boolean":
|
|
84
|
+
case "bigint":
|
|
85
|
+
return String(v);
|
|
86
|
+
case "function":
|
|
87
|
+
return "[function]";
|
|
88
|
+
case "symbol":
|
|
89
|
+
return v.toString();
|
|
90
|
+
default:
|
|
91
|
+
return Array.isArray(v) ? `Array(${v.length})` : `[${v.constructor?.name ?? "object"}]`;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
function captureStack() {
|
|
95
|
+
if (!options.stacks) return undefined;
|
|
96
|
+
const raw = new Error().stack?.split("\n") ?? [];
|
|
97
|
+
// Drop the message line and every frame inside the reactive core; the first
|
|
98
|
+
// remaining frames are the user code that performed the write.
|
|
99
|
+
return raw
|
|
100
|
+
.slice(1)
|
|
101
|
+
.filter(line => !/(?:^|[/\\])(?:packages[/\\])?signals[/\\](src|dist)[/\\]/.test(line))
|
|
102
|
+
.slice(0, 3)
|
|
103
|
+
.map(line => line.trim());
|
|
104
|
+
}
|
|
105
|
+
/** Sentinel for "no value transition to record" (refresh() stamps). */
|
|
106
|
+
const NO_VALUES = Symbol("no-values");
|
|
107
|
+
// --- Provenance -------------------------------------------------------------
|
|
108
|
+
//
|
|
109
|
+
// Who performed a write is not a graph fact — the graph only sees the write.
|
|
110
|
+
// The engine keeps an ambient answer: a stack of imperative frames the core
|
|
111
|
+
// announces (effect callbacks, action steps) and the interaction the web
|
|
112
|
+
// runtime declares around event dispatch. A write stamps the innermost frame;
|
|
113
|
+
// frames nested under an interaction carry it. Effects run in a later flush
|
|
114
|
+
// than the click that caused them, so their frame inherits the interaction
|
|
115
|
+
// from the run's cause chain instead (recorded at recomputeEnd).
|
|
116
|
+
const EXTERNAL_ORIGIN = { kind: "external" };
|
|
117
|
+
const originFrames = [];
|
|
118
|
+
/** Per action invocation (keyed by its iterator): the interaction its first step ran under. */
|
|
119
|
+
const actionInteractions = new WeakMap();
|
|
120
|
+
/**
|
|
121
|
+
* The interaction frame the core's `withInteraction` opened (via the
|
|
122
|
+
* `interactionStart`/`interactionEnd` hooks) for the duration of a handler.
|
|
123
|
+
* Frames nest strictly, so the enclosing one is kept on a stack to restore.
|
|
124
|
+
* The core pins the engine per frame: an `interactionEnd` can arrive after
|
|
125
|
+
* `disable()` cleared the stack, so popping an empty stack is tolerated.
|
|
126
|
+
*/
|
|
127
|
+
let currentInteraction = null;
|
|
128
|
+
const interactionStack = [];
|
|
129
|
+
function interactionStart(ref) {
|
|
130
|
+
interactionStack.push(currentInteraction);
|
|
131
|
+
const origin = { kind: "interaction", name: ref.type, at: ref.at ?? now() };
|
|
132
|
+
if (ref.target) origin.target = ref.target;
|
|
133
|
+
currentInteraction = origin;
|
|
134
|
+
openInteraction(origin);
|
|
135
|
+
}
|
|
136
|
+
function interactionEnd() {
|
|
137
|
+
const closing = currentInteraction;
|
|
138
|
+
currentInteraction = interactionStack.length ? interactionStack.pop() : null;
|
|
139
|
+
if (closing !== null) closeInteraction(closing);
|
|
140
|
+
}
|
|
141
|
+
/** The interaction an origin runs under (itself, when it is one). */
|
|
142
|
+
function interactionOf(origin) {
|
|
143
|
+
if (origin === undefined) return undefined;
|
|
144
|
+
return origin.kind === "interaction" ? origin : origin.interaction;
|
|
145
|
+
}
|
|
146
|
+
/** The interaction a cause list traces back to — root writes only, derived links walked. */
|
|
147
|
+
function interactionIn(causes) {
|
|
148
|
+
for (const c of causes) {
|
|
149
|
+
const found =
|
|
150
|
+
c.kind === "derived"
|
|
151
|
+
? c.causes !== undefined
|
|
152
|
+
? interactionIn(c.causes)
|
|
153
|
+
: undefined
|
|
154
|
+
: interactionOf(c.origin);
|
|
155
|
+
if (found !== undefined) return found;
|
|
156
|
+
}
|
|
157
|
+
return undefined;
|
|
158
|
+
}
|
|
159
|
+
function currentOrigin() {
|
|
160
|
+
const frame = originFrames[originFrames.length - 1];
|
|
161
|
+
if (frame !== undefined) return frame;
|
|
162
|
+
return currentInteraction ?? EXTERNAL_ORIGIN;
|
|
163
|
+
}
|
|
164
|
+
/** The root origin a cause list traces back to — the stamp of the nearest root write, derived links walked. */
|
|
165
|
+
function originIn(causes) {
|
|
166
|
+
for (const c of causes) {
|
|
167
|
+
const found =
|
|
168
|
+
c.kind === "derived" ? (c.causes !== undefined ? originIn(c.causes) : undefined) : c.origin;
|
|
169
|
+
if (found !== undefined && found.kind !== "external") return found;
|
|
170
|
+
}
|
|
171
|
+
return undefined;
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
* The `currentOrigin` hook: what a runtime recording its own fact right now
|
|
175
|
+
* (a server-function call) should stamp it with. Inside a recompute the
|
|
176
|
+
* fact belongs to the change that caused the run — a `createAsync` calling
|
|
177
|
+
* the server on a navigation's write is the navigation's, and through it the
|
|
178
|
+
* click's — walked down past create runs the way `trackFlightStart` does,
|
|
179
|
+
* since a node born inside a parent's run inherits the parent's causality.
|
|
180
|
+
* Outside one — or when the causes were themselves external (a memo a
|
|
181
|
+
* handler pulls, stale from a timer's write) — it is the write's answer
|
|
182
|
+
* (`currentOrigin`), minus the external sentinel: "none known" is
|
|
183
|
+
* `undefined` on a record, as `HoldEvent.origin` has it. The objects
|
|
184
|
+
* returned are the engine's own frames, so the caller's record joins
|
|
185
|
+
* `InteractionEvent.origin` / `NavigationEvent.origin` by identity.
|
|
186
|
+
*/
|
|
187
|
+
function ambientOrigin() {
|
|
188
|
+
for (let i = frames.length - 1; i >= 0; i--) {
|
|
189
|
+
const causes = frames[i].causes;
|
|
190
|
+
if (causes !== null) {
|
|
191
|
+
const cause = originIn(causes);
|
|
192
|
+
if (cause !== undefined) return cause;
|
|
193
|
+
break;
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
const origin = currentOrigin();
|
|
197
|
+
return origin === EXTERNAL_ORIGIN ? undefined : origin;
|
|
198
|
+
}
|
|
199
|
+
const effectFrames = new WeakMap();
|
|
200
|
+
/** The interaction the innermost open frame runs under, else the ambient one. */
|
|
201
|
+
function enclosingInteraction() {
|
|
202
|
+
const top = originFrames[originFrames.length - 1];
|
|
203
|
+
return (top !== undefined ? interactionOf(top) : undefined) ?? currentInteraction ?? undefined;
|
|
204
|
+
}
|
|
205
|
+
function pushFrame(kind, name, interaction, effect) {
|
|
206
|
+
const frame = { kind };
|
|
207
|
+
if (name) frame.name = name;
|
|
208
|
+
const under = interaction ?? currentInteraction ?? undefined;
|
|
209
|
+
if (under !== undefined) frame.interaction = under;
|
|
210
|
+
if (effect !== undefined) {
|
|
211
|
+
const node = effect;
|
|
212
|
+
if (node._devRunSeq !== undefined) frame.run = node._devRunSeq;
|
|
213
|
+
effectFrames.set(frame, { node: effect, causes: node._devRunCauses });
|
|
214
|
+
}
|
|
215
|
+
originFrames.push(frame);
|
|
216
|
+
}
|
|
217
|
+
function popFrame(kind) {
|
|
218
|
+
// Frames are strictly nested; a mismatch means enable() landed mid-frame
|
|
219
|
+
// (the opener never pushed) — leave the stack alone rather than pop a stranger.
|
|
220
|
+
const top = originFrames[originFrames.length - 1];
|
|
221
|
+
if (top !== undefined && top.kind === kind) originFrames.pop();
|
|
222
|
+
}
|
|
223
|
+
/**
|
|
224
|
+
* `withOrigin` opened a declared frame. The frame object IS the origin every
|
|
225
|
+
* write inside stamps, and the key the navigation record hangs off (see
|
|
226
|
+
* "Navigations" below), so a hold or re-run that later resolves a write's
|
|
227
|
+
* origin lands on the same record. It runs under the interaction of the frame
|
|
228
|
+
* it opened inside — a `navigate()` from an action step, whose ambient
|
|
229
|
+
* interaction is long gone but whose frame remembers it — else the ambient
|
|
230
|
+
* one (a link click's handler).
|
|
231
|
+
*/
|
|
232
|
+
function originStart(ref) {
|
|
233
|
+
// A redirect hop re-enters the pending navigation's frame — the same object,
|
|
234
|
+
// so its writes stamp the same origin and replace the pending write without
|
|
235
|
+
// superseding it (see "Navigations").
|
|
236
|
+
if (ref.redirect !== undefined && ref.redirect > 0) {
|
|
237
|
+
const pending = lastOpenNavigation();
|
|
238
|
+
if (pending !== undefined) {
|
|
239
|
+
redirectNavigation(pending, ref);
|
|
240
|
+
originFrames.push(pending.event.origin);
|
|
241
|
+
return;
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
const frame = { kind: ref.kind, at: ref.at ?? now() };
|
|
245
|
+
if (ref.from !== undefined) frame.from = ref.from;
|
|
246
|
+
const under = enclosingInteraction();
|
|
247
|
+
if (under !== undefined) frame.interaction = under;
|
|
248
|
+
originFrames.push(frame);
|
|
249
|
+
openNavigation(frame, ref);
|
|
250
|
+
}
|
|
251
|
+
function originEnd() {
|
|
252
|
+
const top = originFrames[originFrames.length - 1];
|
|
253
|
+
popFrame("navigation");
|
|
254
|
+
if (top !== undefined && top.kind === "navigation") closeNavigation(top);
|
|
255
|
+
}
|
|
256
|
+
/** `click on button#next "Next →"`, `effect "syncTitle"`, `action "save"`, `navigation to /users/:id`, … */
|
|
257
|
+
function formatOrigin(origin) {
|
|
258
|
+
switch (origin.kind) {
|
|
259
|
+
case "interaction":
|
|
260
|
+
return `${origin.name} on ${origin.target ?? "an element"}`;
|
|
261
|
+
case "effect":
|
|
262
|
+
return `effect${origin.name ? ` "${origin.name}"` : ""}`;
|
|
263
|
+
case "action":
|
|
264
|
+
return `action${origin.name ? ` "${origin.name}"` : ""}`;
|
|
265
|
+
case "async":
|
|
266
|
+
return `async landing${origin.name ? ` on "${origin.name}"` : ""}`;
|
|
267
|
+
case "navigation": {
|
|
268
|
+
// The route pattern is the name consumers group by; the concrete path
|
|
269
|
+
// follows when it adds information, then the destinations a redirect
|
|
270
|
+
// chain abandoned on the way.
|
|
271
|
+
const name = origin.name ?? origin.to;
|
|
272
|
+
if (name === undefined) return "navigation";
|
|
273
|
+
const notes = [];
|
|
274
|
+
if (origin.to !== undefined && origin.to !== name) notes.push(origin.to);
|
|
275
|
+
const redirects = navStates.get(origin)?.event.redirects;
|
|
276
|
+
if (redirects !== undefined)
|
|
277
|
+
notes.push(
|
|
278
|
+
`redirected from ${redirects.map(hop => hop.to ?? hop.name ?? "?").join(" → ")}`
|
|
279
|
+
);
|
|
280
|
+
return `navigation to ${name}${notes.length > 0 ? ` (${notes.join(", ")})` : ""}`;
|
|
281
|
+
}
|
|
282
|
+
default:
|
|
283
|
+
return "outside the reactive system";
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
/** Record a root change (setSignal / refresh / async landing) on the node. */
|
|
287
|
+
/** Live subscriber count, walked on demand — the core keeps no counter. */
|
|
288
|
+
function countSubscribers(node) {
|
|
289
|
+
let n = 0;
|
|
290
|
+
for (let s = node._subs; s !== null; s = s._nextSub) n++;
|
|
291
|
+
return n;
|
|
292
|
+
}
|
|
293
|
+
/**
|
|
294
|
+
* Written-fan-out warning — the engine's lower-bar sibling of the always-on
|
|
295
|
+
* HUGE_FAN_OUT (see dev.ts): a committed root invalidation reaching hundreds
|
|
296
|
+
* of subscribers re-runs all of them this flush. Counts the subscriber list
|
|
297
|
+
* itself (an engine-only walk, on the write; the core keeps no per-node
|
|
298
|
+
* count — a live `_subCount` was a post-construction field that forked node
|
|
299
|
+
* shapes). Once per node; re-warns only when the subscriber count has
|
|
300
|
+
* doubled since the last warning. Stops at GRAPH_SIZE_WARN_AT, where
|
|
301
|
+
* HUGE_FAN_OUT takes over, so the two never fire for the same write.
|
|
302
|
+
*/
|
|
303
|
+
function checkWideWrite(node, kind) {
|
|
304
|
+
const limit = options.wideWrites;
|
|
305
|
+
if (typeof limit !== "number") return;
|
|
306
|
+
const subs = countSubscribers(node);
|
|
307
|
+
const attributed = node;
|
|
308
|
+
if (subs < limit || subs >= GRAPH_SIZE_WARN_AT) return;
|
|
309
|
+
if (subs < (attributed._devWideWriteWarnedAt ?? 0) * 2) return;
|
|
310
|
+
attributed._devWideWriteWarnedAt = subs;
|
|
311
|
+
const verb =
|
|
312
|
+
kind === "refresh" ? "refresh of" : kind === "async" ? "async landing on" : "write to";
|
|
313
|
+
const message =
|
|
314
|
+
`[WIDE_WRITE] ${verb} "${nodeName(node)}" reached ${subs} subscribers — every one ` +
|
|
315
|
+
`re-runs this flush. If consumers ask keyed questions of this value (for example every ` +
|
|
316
|
+
`row comparing against one selected id), invert it: keep the answer in a store used as a ` +
|
|
317
|
+
`map keyed by id, so each consumer reads its own key and only the keys that flipped update.`;
|
|
318
|
+
reportDiagnostic(
|
|
319
|
+
emitDiagnostic(
|
|
320
|
+
{
|
|
321
|
+
code: "WIDE_WRITE",
|
|
322
|
+
kind: "perf",
|
|
323
|
+
severity: "warn",
|
|
324
|
+
message,
|
|
325
|
+
nodeName: nodeName(node),
|
|
326
|
+
data: { subscribers: subs, write: kind }
|
|
327
|
+
},
|
|
328
|
+
node
|
|
329
|
+
)
|
|
330
|
+
);
|
|
331
|
+
}
|
|
332
|
+
function stampWrite(node, kind, prev = NO_VALUES, value = NO_VALUES) {
|
|
333
|
+
const record = { seq: ++changeSeq, kind, name: nodeName(node) };
|
|
334
|
+
if (value !== NO_VALUES) {
|
|
335
|
+
record.prev = prev === NO_VALUES ? undefined : preview(prev);
|
|
336
|
+
record.value = preview(value);
|
|
337
|
+
}
|
|
338
|
+
record.origin = kind === "async" ? asyncOrigin(node) : currentOrigin();
|
|
339
|
+
record.at = now();
|
|
340
|
+
record.stack = captureStack();
|
|
341
|
+
const prior = node._devChange;
|
|
342
|
+
node._devChange = record;
|
|
343
|
+
noteNavigationWrite(prior, record);
|
|
344
|
+
noteInteractionWrite(record.origin, excludedNode(node));
|
|
345
|
+
if (kind === "write") trackEffectWrite(node, record, value);
|
|
346
|
+
// stampWrite is the single funnel for committed root invalidations (sync
|
|
347
|
+
// writes, refresh(), async landings), which makes it the one place the
|
|
348
|
+
// written-fan-out check needs to live.
|
|
349
|
+
checkWideWrite(node, kind);
|
|
350
|
+
}
|
|
351
|
+
/** Record a derived change (memo produced a new value) with its causes. */
|
|
352
|
+
function stampDerived(node, causes) {
|
|
353
|
+
node._devChange = {
|
|
354
|
+
seq: ++changeSeq,
|
|
355
|
+
kind: "derived",
|
|
356
|
+
name: nodeName(node),
|
|
357
|
+
causes
|
|
358
|
+
};
|
|
359
|
+
}
|
|
360
|
+
/**
|
|
361
|
+
* Collect the deps whose committed change is newer than this node's previous
|
|
362
|
+
* run. Called at recompute entry, while `_deps` still holds the previous
|
|
363
|
+
* run's links. A refresh() stamp on the node itself also counts — that is a
|
|
364
|
+
* self-invalidation, not a dep change.
|
|
365
|
+
*/
|
|
366
|
+
function collectCauses(el) {
|
|
367
|
+
const seen = el._devSeenSeq ?? 0;
|
|
368
|
+
const causes = [];
|
|
369
|
+
const self = el._devChange;
|
|
370
|
+
if (self !== undefined && self.seq > seen && self.kind === "refresh") causes.push(self);
|
|
371
|
+
for (let l = el._deps; l !== null; l = l._nextDep) {
|
|
372
|
+
const change = l._dep._devChange;
|
|
373
|
+
if (change !== undefined && change.seq > seen) causes.push(change);
|
|
374
|
+
}
|
|
375
|
+
return causes;
|
|
376
|
+
}
|
|
377
|
+
/** Advance the node's seen-cursor to the present. Call after every run. */
|
|
378
|
+
function markSeen(el) {
|
|
379
|
+
el._devSeenSeq = changeSeq;
|
|
380
|
+
}
|
|
381
|
+
/**
|
|
382
|
+
* Snapshot the dep identities of the node's last pass (call before a run
|
|
383
|
+
* replaces them, or after it to read the fresh set). The validated prefix
|
|
384
|
+
* [`_deps`..`_depsTail`] is that pass's set; links past the tail are a
|
|
385
|
+
* previous pass's, kept linked while the frame they fed is still the
|
|
386
|
+
* committed one (A30 — a staged memo pass, or an effect pass whose run is
|
|
387
|
+
* still owed) and not part of the subscription diff.
|
|
388
|
+
*/
|
|
389
|
+
function captureDeps(el) {
|
|
390
|
+
const deps = [];
|
|
391
|
+
for (let l = el._deps; l !== null; l = l._nextDep) {
|
|
392
|
+
deps.push(l._dep);
|
|
393
|
+
if (l === el._depsTail) break;
|
|
394
|
+
}
|
|
395
|
+
return deps;
|
|
396
|
+
}
|
|
397
|
+
/**
|
|
398
|
+
* Wide-scope warning — the coarse-read / helper-leak signature: one scope
|
|
399
|
+
* subscribed to dozens of sources re-runs when ANY of them change. Fired from
|
|
400
|
+
* recordRerun for re-runs and directly from recompute for creation runs (a
|
|
401
|
+
* memo can be born too wide). Re-warns only on 50% further growth.
|
|
402
|
+
*/
|
|
403
|
+
function checkDepWidth(el) {
|
|
404
|
+
const limit = options.wideDeps;
|
|
405
|
+
if (limit === false) return;
|
|
406
|
+
let count = 0;
|
|
407
|
+
const names = [];
|
|
408
|
+
for (let l = el._deps; l !== null; l = l._nextDep) {
|
|
409
|
+
count++;
|
|
410
|
+
if (names.length < 12) names.push(nodeName(l._dep));
|
|
411
|
+
if (l === el._depsTail) break; // the validated prefix, as captureDeps
|
|
412
|
+
}
|
|
413
|
+
const node = el;
|
|
414
|
+
if (count < limit || count < (node._devWideWarnedAt ?? 0) * 1.5) return;
|
|
415
|
+
node._devWideWarnedAt = count;
|
|
416
|
+
const kind = el._type ? "effect" : "memo";
|
|
417
|
+
const message =
|
|
418
|
+
`[WIDE_SCOPE_DEPS] ${kind} "${nodeName(el)}" is subscribed to ${count} sources — ` +
|
|
419
|
+
`it re-runs when any of them change. Narrow its reads or split it into smaller memos. ` +
|
|
420
|
+
`Sources: ${names.join(", ")}${count > names.length ? ", …" : ""}`;
|
|
421
|
+
reportDiagnostic(
|
|
422
|
+
emitDiagnostic(
|
|
423
|
+
{
|
|
424
|
+
code: "WIDE_SCOPE_DEPS",
|
|
425
|
+
kind: "perf",
|
|
426
|
+
severity: "warn",
|
|
427
|
+
message,
|
|
428
|
+
nodeName: nodeName(el),
|
|
429
|
+
data: { depCount: count, deps: names }
|
|
430
|
+
},
|
|
431
|
+
el
|
|
432
|
+
)
|
|
433
|
+
);
|
|
434
|
+
}
|
|
435
|
+
const hotCauses = new Map();
|
|
436
|
+
const HOT_FANOUT_FIRST_MILESTONE = 5;
|
|
437
|
+
/**
|
|
438
|
+
* Hot-scope warning — flags a scope that re-ran more than `count` times
|
|
439
|
+
* inside one `windowMs` window. Warned once per window, with the most recent
|
|
440
|
+
* cause chain named so the leaking signal is identified in the message.
|
|
441
|
+
* Fan-out spam is folded per root cause (see HotCauseWindow above).
|
|
442
|
+
*/
|
|
443
|
+
function checkHotRuns(el, event) {
|
|
444
|
+
const cfg = options.hotRuns;
|
|
445
|
+
if (cfg === false) return;
|
|
446
|
+
const node = el;
|
|
447
|
+
const now = Date.now();
|
|
448
|
+
if (node._devWinStart === undefined || now - node._devWinStart > cfg.windowMs) {
|
|
449
|
+
node._devWinStart = now;
|
|
450
|
+
node._devWinCount = 0;
|
|
451
|
+
node._devHotWarned = false;
|
|
452
|
+
}
|
|
453
|
+
node._devWinCount = (node._devWinCount ?? 0) + 1;
|
|
454
|
+
if (node._devHotWarned || node._devWinCount < cfg.count) return;
|
|
455
|
+
node._devHotWarned = true;
|
|
456
|
+
// Root-cause key: the set of originating writes behind this scope's latest
|
|
457
|
+
// re-run. Scopes hot from the SAME roots share one aggregation window.
|
|
458
|
+
const roots = new Set();
|
|
459
|
+
rootsOf(event.causes, roots);
|
|
460
|
+
const causeKey = roots.size > 0 ? [...roots].sort().join(", ") : "(untracked)";
|
|
461
|
+
let window = hotCauses.get(causeKey);
|
|
462
|
+
if (window === undefined || now - window.winStart > cfg.windowMs) {
|
|
463
|
+
window = { winStart: now, scopes: 0, runs: 0, nextMilestone: HOT_FANOUT_FIRST_MILESTONE };
|
|
464
|
+
hotCauses.set(causeKey, window);
|
|
465
|
+
}
|
|
466
|
+
window.scopes++;
|
|
467
|
+
window.runs += node._devWinCount;
|
|
468
|
+
if (window.scopes === 1) {
|
|
469
|
+
const rootCause = event.causes.map(c => `"${c.name}" (${c.kind})`).join(", ");
|
|
470
|
+
const message =
|
|
471
|
+
`[HOT_SCOPE_RERUNS] ${event.nodeKind} "${event.nodeName}" re-ran ${node._devWinCount} times ` +
|
|
472
|
+
`in ${Math.max(1, now - node._devWinStart)}ms — a hot signal is likely leaking into this ` +
|
|
473
|
+
`scope. Latest cause: ${rootCause || "(untracked pull)"}`;
|
|
474
|
+
reportDiagnostic(
|
|
475
|
+
emitDiagnostic(
|
|
476
|
+
{
|
|
477
|
+
code: "HOT_SCOPE_RERUNS",
|
|
478
|
+
kind: "perf",
|
|
479
|
+
severity: "warn",
|
|
480
|
+
message,
|
|
481
|
+
nodeName: event.nodeName,
|
|
482
|
+
data: {
|
|
483
|
+
runs: node._devWinCount,
|
|
484
|
+
windowMs: cfg.windowMs,
|
|
485
|
+
causes: event.causes.map(c => c.name)
|
|
486
|
+
}
|
|
487
|
+
},
|
|
488
|
+
el
|
|
489
|
+
)
|
|
490
|
+
);
|
|
491
|
+
return;
|
|
492
|
+
}
|
|
493
|
+
// Additional scopes hot from the same cause: silent until a milestone —
|
|
494
|
+
// the culprit is the cause, and it has already been named once.
|
|
495
|
+
if (window.scopes < window.nextMilestone) return;
|
|
496
|
+
window.nextMilestone *= 10;
|
|
497
|
+
const message =
|
|
498
|
+
`[HOT_SCOPE_FANOUT] ${window.scopes} scopes have gone hot (${window.runs} re-runs) within ` +
|
|
499
|
+
`${cfg.windowMs}ms, all driven by ${causeKey} — one hot cause is re-running a large part ` +
|
|
500
|
+
`of the graph. Per-scope warnings are suppressed; fix the cause. If consumers ask keyed ` +
|
|
501
|
+
`questions of it, invert it: a store used as a map keyed by id, one key per consumer.`;
|
|
502
|
+
// The subject is the shared CAUSE, not this victim scope — no single owner
|
|
503
|
+
// path locates it, so the event carries none.
|
|
504
|
+
reportDiagnostic(
|
|
505
|
+
emitDiagnostic(
|
|
506
|
+
{
|
|
507
|
+
code: "HOT_SCOPE_FANOUT",
|
|
508
|
+
kind: "perf",
|
|
509
|
+
severity: "warn",
|
|
510
|
+
message,
|
|
511
|
+
nodeName: causeKey,
|
|
512
|
+
data: { cause: causeKey, scopes: window.scopes, runs: window.runs, windowMs: cfg.windowMs }
|
|
513
|
+
},
|
|
514
|
+
null
|
|
515
|
+
)
|
|
516
|
+
);
|
|
517
|
+
}
|
|
518
|
+
/**
|
|
519
|
+
* Time-budget warning — the counterpart of checkHotRuns for the
|
|
520
|
+
* few-but-expensive scope: warns when one scope's summed self-time within a
|
|
521
|
+
* window exceeds the budget. Warned once per window.
|
|
522
|
+
*/
|
|
523
|
+
function checkHotTime(el, event) {
|
|
524
|
+
const cfg = options.hotTime;
|
|
525
|
+
if (cfg === false) return;
|
|
526
|
+
const node = el;
|
|
527
|
+
const at = now();
|
|
528
|
+
if (node._devTimeWinStart === undefined || at - node._devTimeWinStart > cfg.windowMs) {
|
|
529
|
+
node._devTimeWinStart = at;
|
|
530
|
+
node._devTimeWinMs = 0;
|
|
531
|
+
node._devTimeWarned = false;
|
|
532
|
+
}
|
|
533
|
+
node._devTimeWinMs = (node._devTimeWinMs ?? 0) + event.selfMs;
|
|
534
|
+
if (node._devTimeWarned || node._devTimeWinMs < cfg.budgetMs) return;
|
|
535
|
+
node._devTimeWarned = true;
|
|
536
|
+
const rootCause = event.causes.map(c => `"${c.name}" (${c.kind})`).join(", ");
|
|
537
|
+
const message =
|
|
538
|
+
`[HOT_SCOPE_TIME] ${event.nodeKind} "${event.nodeName}" spent ` +
|
|
539
|
+
`${node._devTimeWinMs.toFixed(1)}ms of compute inside one ${cfg.windowMs}ms window ` +
|
|
540
|
+
`(budget ${cfg.budgetMs}ms). Latest cause: ${rootCause || "(untracked pull)"}`;
|
|
541
|
+
reportDiagnostic(
|
|
542
|
+
emitDiagnostic(
|
|
543
|
+
{
|
|
544
|
+
code: "HOT_SCOPE_TIME",
|
|
545
|
+
kind: "perf",
|
|
546
|
+
severity: "warn",
|
|
547
|
+
message,
|
|
548
|
+
nodeName: event.nodeName,
|
|
549
|
+
data: {
|
|
550
|
+
spentMs: node._devTimeWinMs,
|
|
551
|
+
budgetMs: cfg.budgetMs,
|
|
552
|
+
windowMs: cfg.windowMs,
|
|
553
|
+
causes: event.causes.map(c => c.name)
|
|
554
|
+
}
|
|
555
|
+
},
|
|
556
|
+
el
|
|
557
|
+
)
|
|
558
|
+
);
|
|
559
|
+
}
|
|
560
|
+
function recordRerun(el, frame, timing, changed, phase, held) {
|
|
561
|
+
const causes = frame.causes;
|
|
562
|
+
const prevDeps = frame.prevDeps;
|
|
563
|
+
const node = el;
|
|
564
|
+
const prevCauses = node._devRunCauses;
|
|
565
|
+
if (excludedNode(el)) {
|
|
566
|
+
// The observer's own computation: keep the per-node bookkeeping its
|
|
567
|
+
// effect phase reads (see effectRunStart) and record nothing.
|
|
568
|
+
node._devRunInteraction = frame.interaction;
|
|
569
|
+
node._devRunSeq = undefined;
|
|
570
|
+
node._devRunCauses = causes;
|
|
571
|
+
return;
|
|
572
|
+
}
|
|
573
|
+
// Subscription diff: `prevDeps` was captured at run entry; `_deps` now
|
|
574
|
+
// holds the fresh set. A changed set is the "helper edit changed distant
|
|
575
|
+
// call sites" signal — surfaced per-event and in the console format.
|
|
576
|
+
const newDeps = captureDeps(el);
|
|
577
|
+
const prevSet = new Set(prevDeps);
|
|
578
|
+
const newSet = new Set(newDeps);
|
|
579
|
+
const depsAdded = [];
|
|
580
|
+
const depsRemoved = [];
|
|
581
|
+
for (const d of newDeps) if (!prevSet.has(d)) depsAdded.push(nodeName(d));
|
|
582
|
+
for (const d of prevDeps) if (!newSet.has(d)) depsRemoved.push(nodeName(d));
|
|
583
|
+
const event = {
|
|
584
|
+
run: ++runSeq,
|
|
585
|
+
at: frame.start,
|
|
586
|
+
nodeRuns: (node._devRunCount = (node._devRunCount ?? 0) + 1),
|
|
587
|
+
nodeKind: el._type ? "effect" : "memo",
|
|
588
|
+
nodeName: nodeName(el),
|
|
589
|
+
nodeId: devId(el),
|
|
590
|
+
causes,
|
|
591
|
+
depCount: newDeps.length,
|
|
592
|
+
depsAdded,
|
|
593
|
+
depsRemoved,
|
|
594
|
+
selfMs: timing.selfMs,
|
|
595
|
+
totalMs: timing.totalMs,
|
|
596
|
+
changed,
|
|
597
|
+
phase,
|
|
598
|
+
held
|
|
599
|
+
};
|
|
600
|
+
const interaction = frame.interaction;
|
|
601
|
+
if (interaction !== undefined) event.interaction = interaction;
|
|
602
|
+
// The effect phase runs later in the flush with no cause list of its own:
|
|
603
|
+
// it inherits this run's interaction and is joined to this run's causes
|
|
604
|
+
// (see effectRunStart / pushFrame).
|
|
605
|
+
node._devRunInteraction = interaction;
|
|
606
|
+
node._devRunSeq = event.run;
|
|
607
|
+
node._devRunCauses = causes;
|
|
608
|
+
// The record is serializable and never carries the node; keep the node
|
|
609
|
+
// beside it for `OBSERVE.subjectOf` and the engine's own joins (effect
|
|
610
|
+
// cycles, relay tears, `why()`), for as long as anyone holds the record.
|
|
611
|
+
recordSubject(event, el);
|
|
612
|
+
history.push(event);
|
|
613
|
+
if (history.length > options.historyLimit) history.shift();
|
|
614
|
+
for (const f of folds) f.rerun?.(el, event);
|
|
615
|
+
noteInteractionRun(interaction, timing.selfMs, false);
|
|
616
|
+
if (event.nodeKind === "effect") checkEffectCycle(el, causes);
|
|
617
|
+
checkRelayTear(el, causes, prevCauses);
|
|
618
|
+
checkHotRuns(el, event);
|
|
619
|
+
checkHotTime(el, event);
|
|
620
|
+
checkDepWidth(el);
|
|
621
|
+
emitRecord("rerun", event);
|
|
622
|
+
if (options.log) logRerun(event);
|
|
623
|
+
}
|
|
624
|
+
function formatCause(cause, depth, out) {
|
|
625
|
+
const pad = " ".repeat(depth + 1);
|
|
626
|
+
let line = `${pad}← ${cause.kind === "derived" ? "memo" : "signal"} "${cause.name}" ${cause.kind === "derived" ? "changed" : cause.kind} (#${cause.seq})`;
|
|
627
|
+
if (cause.prev !== undefined) line += ` ${cause.prev} → ${cause.value}`;
|
|
628
|
+
if (cause.origin !== undefined && cause.origin.kind !== "external") {
|
|
629
|
+
line += ` — ${formatOrigin(cause.origin)}`;
|
|
630
|
+
const under = cause.origin.interaction;
|
|
631
|
+
if (under !== undefined) line += ` (under ${formatOrigin(under)})`;
|
|
632
|
+
}
|
|
633
|
+
out.push(line);
|
|
634
|
+
if (cause.stack) for (const frame of cause.stack) out.push(`${pad} ${frame}`);
|
|
635
|
+
if (cause.causes && depth < 10) {
|
|
636
|
+
for (const upstream of cause.causes) formatCause(upstream, depth + 1, out);
|
|
637
|
+
}
|
|
638
|
+
}
|
|
639
|
+
function formatRerun(event) {
|
|
640
|
+
const out = [
|
|
641
|
+
`[why-run] ${event.nodeKind} "${event.nodeName}" ran (run ${event.nodeRuns}, ` +
|
|
642
|
+
`${event.selfMs.toFixed(2)}ms${event.changed ? "" : ", unchanged"}` +
|
|
643
|
+
`${event.phase === "plain" ? "" : `, ${event.phase}`}${event.held ? ", held" : ""})` +
|
|
644
|
+
(event.causes.length === 0 ? " — no tracked cause (pull or retry)" : "")
|
|
645
|
+
];
|
|
646
|
+
for (const cause of event.causes) formatCause(cause, 0, out);
|
|
647
|
+
if (event.depsAdded.length > 0 || event.depsRemoved.length > 0) {
|
|
648
|
+
const delta = [
|
|
649
|
+
...event.depsAdded.map(n => `+"${n}"`),
|
|
650
|
+
...event.depsRemoved.map(n => `-"${n}"`)
|
|
651
|
+
].join(" ");
|
|
652
|
+
out.push(` deps changed: ${delta} (${event.depCount} total)`);
|
|
653
|
+
}
|
|
654
|
+
return out.join("\n");
|
|
655
|
+
}
|
|
656
|
+
/**
|
|
657
|
+
* Console face of a re-run: the headline as a collapsed group with the
|
|
658
|
+
* why-chain and dep delta inside, so a busy console stays scannable (one line
|
|
659
|
+
* per run, evidence a click away). Consoles without grouping get the text.
|
|
660
|
+
*/
|
|
661
|
+
function logRerun(event) {
|
|
662
|
+
const text = formatRerun(event);
|
|
663
|
+
const nl = text.indexOf("\n");
|
|
664
|
+
if (nl === -1 || typeof console.groupCollapsed !== "function") {
|
|
665
|
+
console.log(text);
|
|
666
|
+
return;
|
|
667
|
+
}
|
|
668
|
+
console.groupCollapsed(text.slice(0, nl));
|
|
669
|
+
console.log(text.slice(nl + 1));
|
|
670
|
+
console.groupEnd();
|
|
671
|
+
}
|
|
672
|
+
/**
|
|
673
|
+
* Values eligible for the unstable-output check: plain objects and arrays
|
|
674
|
+
* only. Promises, iterators, Dates, Maps, class instances etc. all have no
|
|
675
|
+
* (or unrepresentative) own enumerable keys, so a shallow compare would
|
|
676
|
+
* false-positive on them — a fresh Promise is a genuinely new value.
|
|
677
|
+
*/
|
|
678
|
+
function isPlainShape(v) {
|
|
679
|
+
if (v === null || typeof v !== "object") return false;
|
|
680
|
+
if (Array.isArray(v)) return true;
|
|
681
|
+
const proto = Object.getPrototypeOf(v);
|
|
682
|
+
return proto === Object.prototype || proto === null;
|
|
683
|
+
}
|
|
684
|
+
/** Shallow structural equivalence, capped so hot paths stay cheap. */
|
|
685
|
+
const UNSTABLE_KEY_CAP = 64;
|
|
686
|
+
function shallowEquivalent(a, b) {
|
|
687
|
+
const aArr = Array.isArray(a);
|
|
688
|
+
if (aArr !== Array.isArray(b)) return false;
|
|
689
|
+
if (aArr) {
|
|
690
|
+
const arrA = a;
|
|
691
|
+
const arrB = b;
|
|
692
|
+
if (arrA.length !== arrB.length || arrA.length > UNSTABLE_KEY_CAP) return false;
|
|
693
|
+
for (let i = 0; i < arrA.length; i++) if (arrA[i] !== arrB[i]) return false;
|
|
694
|
+
return true;
|
|
695
|
+
}
|
|
696
|
+
const keys = Object.keys(a);
|
|
697
|
+
if (keys.length > UNSTABLE_KEY_CAP || keys.length !== Object.keys(b).length) return false;
|
|
698
|
+
for (const key of keys) {
|
|
699
|
+
if (!(key in b) || a[key] !== b[key]) return false;
|
|
700
|
+
}
|
|
701
|
+
return true;
|
|
702
|
+
}
|
|
703
|
+
/**
|
|
704
|
+
* Unstable-output warning — the fan-out amplifier signature: a memo whose
|
|
705
|
+
* committed value is referentially new but structurally identical run after
|
|
706
|
+
* run has an equality gate that never closes, so ALL its subscribers re-run
|
|
707
|
+
* on EVERY upstream change. Checked only on plain (non-overlay) changed runs;
|
|
708
|
+
* a genuinely different value (or a non-plain shape) resets the streak.
|
|
709
|
+
*/
|
|
710
|
+
function checkUnstableOutput(el, prevValue, newValue) {
|
|
711
|
+
const limit = options.unstableMemos;
|
|
712
|
+
// typeof guard: an explicit `unstableMemos: undefined` in enable() options
|
|
713
|
+
// clobbers the default through the spread — treat any non-number as off.
|
|
714
|
+
if (typeof limit !== "number") return;
|
|
715
|
+
const node = el;
|
|
716
|
+
if (
|
|
717
|
+
prevValue === newValue || // paranoia: changed runs should never hit this
|
|
718
|
+
!isPlainShape(prevValue) ||
|
|
719
|
+
!isPlainShape(newValue) ||
|
|
720
|
+
!shallowEquivalent(prevValue, newValue)
|
|
721
|
+
) {
|
|
722
|
+
node._devUnstableRuns = 0;
|
|
723
|
+
node._devUnstableWarned = false;
|
|
724
|
+
return;
|
|
725
|
+
}
|
|
726
|
+
node._devUnstableRuns = (node._devUnstableRuns ?? 0) + 1;
|
|
727
|
+
if (node._devUnstableWarned || node._devUnstableRuns < limit) return;
|
|
728
|
+
node._devUnstableWarned = true;
|
|
729
|
+
const shape = Array.isArray(newValue) ? "array" : "object";
|
|
730
|
+
const message =
|
|
731
|
+
`[UNSTABLE_MEMO_OUTPUT] memo "${nodeName(el)}" produced a new-but-equivalent ${shape} on ` +
|
|
732
|
+
`${node._devUnstableRuns} consecutive runs — its equality gate never closes, so every ` +
|
|
733
|
+
`subscriber re-runs on every upstream change. Return stable references or pass an ` +
|
|
734
|
+
`\`equals\` option.`;
|
|
735
|
+
reportDiagnostic(
|
|
736
|
+
emitDiagnostic(
|
|
737
|
+
{
|
|
738
|
+
code: "UNSTABLE_MEMO_OUTPUT",
|
|
739
|
+
kind: "perf",
|
|
740
|
+
severity: "warn",
|
|
741
|
+
message,
|
|
742
|
+
nodeName: nodeName(el),
|
|
743
|
+
data: { runs: node._devUnstableRuns, shape }
|
|
744
|
+
},
|
|
745
|
+
el
|
|
746
|
+
)
|
|
747
|
+
);
|
|
748
|
+
}
|
|
749
|
+
const EFFECT_CYCLE_MAX_HOPS = 6;
|
|
750
|
+
const reportedCycles = new Set();
|
|
751
|
+
let nextDevId = 0;
|
|
752
|
+
const devIds = new WeakMap();
|
|
753
|
+
function devId(node) {
|
|
754
|
+
let id = devIds.get(node);
|
|
755
|
+
if (id === undefined) devIds.set(node, (id = ++nextDevId));
|
|
756
|
+
return id;
|
|
757
|
+
}
|
|
758
|
+
function rootWrites(causes, out) {
|
|
759
|
+
for (const c of causes) {
|
|
760
|
+
if (c.kind === "derived") {
|
|
761
|
+
if (c.causes !== undefined) rootWrites(c.causes, out);
|
|
762
|
+
} else out.push(c);
|
|
763
|
+
}
|
|
764
|
+
}
|
|
765
|
+
/**
|
|
766
|
+
* The effect writes leading from an earlier run of `target` to the run whose
|
|
767
|
+
* `causes` these are, in causal order (target's own write first), or null.
|
|
768
|
+
*/
|
|
769
|
+
function findEffectCycle(target, causes, visited, hops) {
|
|
770
|
+
const roots = [];
|
|
771
|
+
rootWrites(causes, roots);
|
|
772
|
+
for (const write of roots) {
|
|
773
|
+
const origin = write.origin;
|
|
774
|
+
if (origin === undefined || origin.kind !== "effect") continue;
|
|
775
|
+
const info = effectFrames.get(origin);
|
|
776
|
+
if (info === undefined) continue;
|
|
777
|
+
if (info.node === target) return [{ effect: info.node, write }];
|
|
778
|
+
if (hops >= EFFECT_CYCLE_MAX_HOPS || visited.has(info.node) || info.causes === undefined)
|
|
779
|
+
continue;
|
|
780
|
+
visited.add(info.node);
|
|
781
|
+
const rest = findEffectCycle(target, info.causes, visited, hops + 1);
|
|
782
|
+
if (rest !== null) {
|
|
783
|
+
rest.push({ effect: info.node, write });
|
|
784
|
+
return rest;
|
|
785
|
+
}
|
|
786
|
+
}
|
|
787
|
+
return null;
|
|
788
|
+
}
|
|
789
|
+
/** Names of the memos between a direct cause of a run and `write`, root-first. */
|
|
790
|
+
function derivedPath(causes, write, path) {
|
|
791
|
+
for (const c of causes) {
|
|
792
|
+
if (c === write) return true;
|
|
793
|
+
if (c.kind === "derived" && c.causes !== undefined) {
|
|
794
|
+
path.unshift(c.name);
|
|
795
|
+
if (derivedPath(c.causes, write, path)) return true;
|
|
796
|
+
path.shift();
|
|
797
|
+
}
|
|
798
|
+
}
|
|
799
|
+
return false;
|
|
800
|
+
}
|
|
801
|
+
function describeWrite(write) {
|
|
802
|
+
if (write.kind === "refresh") return `refreshed "${write.name}"`;
|
|
803
|
+
const values = write.prev !== undefined ? ` (${write.prev} → ${write.value})` : "";
|
|
804
|
+
return `wrote "${write.name}"${values}`;
|
|
805
|
+
}
|
|
806
|
+
function checkEffectCycle(el, causes) {
|
|
807
|
+
const links = findEffectCycle(el, causes, new Set([el]), 0);
|
|
808
|
+
if (links === null) return;
|
|
809
|
+
const key = links
|
|
810
|
+
.map(link => devId(link.effect))
|
|
811
|
+
.sort((a, b) => a - b)
|
|
812
|
+
.join(",");
|
|
813
|
+
if (reportedCycles.has(key)) return;
|
|
814
|
+
reportedCycles.add(key);
|
|
815
|
+
const flushes = links.length + 1;
|
|
816
|
+
let message;
|
|
817
|
+
if (links.length === 1) {
|
|
818
|
+
const [{ write }] = links;
|
|
819
|
+
const path = [];
|
|
820
|
+
derivedPath(causes, write, path);
|
|
821
|
+
const via = path.length > 0 ? ` through ${path.map(n => `memo "${n}"`).join(" → ")}` : "";
|
|
822
|
+
message =
|
|
823
|
+
`[EFFECT_WRITES_OWN_SOURCE] effect "${nodeName(el)}" re-ran because of its own write: it ` +
|
|
824
|
+
`${describeWrite(write)}, which fed back into its inputs${via}. Two flushes to settle, ` +
|
|
825
|
+
`and the screen rendered the pre-write value in between. The written value is a function ` +
|
|
826
|
+
`of what the effect reads — compute it in a memo (or normalize where the source is ` +
|
|
827
|
+
`written) instead of correcting it after the fact.`;
|
|
828
|
+
} else {
|
|
829
|
+
const names = links.map(link => `"${nodeName(link.effect)}"`);
|
|
830
|
+
const steps = links
|
|
831
|
+
.map(
|
|
832
|
+
(link, i) => `effect ${names[i]}${i > 0 ? " re-ran and" : ""} ${describeWrite(link.write)}`
|
|
833
|
+
)
|
|
834
|
+
.join("; ");
|
|
835
|
+
message =
|
|
836
|
+
`[EFFECT_WRITES_OWN_SOURCE] effects ${[...names, names[0]].join(" → ")} relay writes in a ` +
|
|
837
|
+
`cycle: ${steps}; which fed back into effect ${names[0]}'s inputs — ${flushes} flushes to ` +
|
|
838
|
+
`settle after each change, each rendering an intermediate state. Every relayed value is a ` +
|
|
839
|
+
`function of the original inputs: derive them in memos and drop the writes.`;
|
|
840
|
+
}
|
|
841
|
+
const severity = links.length === 1 ? "warn" : "info";
|
|
842
|
+
const entry = emitDiagnostic(
|
|
843
|
+
{
|
|
844
|
+
code: "EFFECT_WRITES_OWN_SOURCE",
|
|
845
|
+
kind: "perf",
|
|
846
|
+
severity,
|
|
847
|
+
message,
|
|
848
|
+
nodeName: nodeName(el),
|
|
849
|
+
data: {
|
|
850
|
+
effects: links.map(link => nodeName(link.effect)),
|
|
851
|
+
writes: links.map(link => ({
|
|
852
|
+
effect: nodeName(link.effect),
|
|
853
|
+
kind: link.write.kind,
|
|
854
|
+
name: link.write.name,
|
|
855
|
+
prev: link.write.prev,
|
|
856
|
+
value: link.write.value
|
|
857
|
+
})),
|
|
858
|
+
flushes
|
|
859
|
+
}
|
|
860
|
+
},
|
|
861
|
+
el
|
|
862
|
+
);
|
|
863
|
+
if (severity === "warn") reportDiagnostic(entry);
|
|
864
|
+
}
|
|
865
|
+
const RELAY_WARN_AT = 3;
|
|
866
|
+
const relays = new Map();
|
|
867
|
+
const copyWrites = new WeakSet();
|
|
868
|
+
const copyReported = new WeakSet();
|
|
869
|
+
/** The node each root write record was stamped on (records are serializable and cannot hold it). */
|
|
870
|
+
const recordNodes = new WeakMap();
|
|
871
|
+
/**
|
|
872
|
+
* Write-side bookkeeping for the relay heuristics: who has written this
|
|
873
|
+
* signal, and whether an effect just copied its compute output into it.
|
|
874
|
+
*/
|
|
875
|
+
function trackEffectWrite(node, record, value) {
|
|
876
|
+
const n = node;
|
|
877
|
+
const origin = record.origin;
|
|
878
|
+
const info =
|
|
879
|
+
origin !== undefined && origin.kind === "effect" ? effectFrames.get(origin) : undefined;
|
|
880
|
+
const writer = info === undefined ? 0 : devId(info.node);
|
|
881
|
+
recordNodes.set(record, node);
|
|
882
|
+
n._devSoleWriter = n._devSoleWriter === undefined || n._devSoleWriter === writer ? writer : null;
|
|
883
|
+
if (info !== undefined && value !== undefined && value === info.node._value) {
|
|
884
|
+
copyWrites.add(record);
|
|
885
|
+
n._devCopyRuns = n._devCopyFrom === writer ? (n._devCopyRuns ?? 0) + 1 : 1;
|
|
886
|
+
n._devCopyFrom = writer;
|
|
887
|
+
if (n._devCopyRuns >= 2 && n._devSoleWriter === writer) checkCopyEffect(info.node, node);
|
|
888
|
+
} else n._devCopyRuns = 0;
|
|
889
|
+
}
|
|
890
|
+
/** The effect's source whose current value the compute output is, if any (the prop-to-state port). */
|
|
891
|
+
function passthroughSource(effect) {
|
|
892
|
+
for (let l = effect._deps; l !== null; l = l._nextDep)
|
|
893
|
+
if (l._dep._value === effect._value) return nodeName(l._dep);
|
|
894
|
+
return undefined;
|
|
895
|
+
}
|
|
896
|
+
/** The repair for a write that is the effect's compute output. */
|
|
897
|
+
function copyRepair(effect, target) {
|
|
898
|
+
const source = passthroughSource(effect);
|
|
899
|
+
return source !== undefined
|
|
900
|
+
? `The written value is "${source}" itself: read "${source}" where "${target}" is read ` +
|
|
901
|
+
`(or createMemo it if a stable derivation is needed) and delete the effect.`
|
|
902
|
+
: `The written value is the effect's compute output — by contract a pure function of ` +
|
|
903
|
+
`what it tracks: make "${target}" a memo of that computation and delete the effect.`;
|
|
904
|
+
}
|
|
905
|
+
function checkCopyEffect(effect, target) {
|
|
906
|
+
if (copyReported.has(target)) return;
|
|
907
|
+
copyReported.add(target);
|
|
908
|
+
const name = nodeName(target);
|
|
909
|
+
const message =
|
|
910
|
+
`[EFFECT_RELAY_TEAR] effect "${nodeName(effect)}" writes its compute output into ` +
|
|
911
|
+
`"${name}" on every run, and nothing else writes "${name}" — it is derived state kept ` +
|
|
912
|
+
`one flush late: everything reading it paints a frame behind everything reading the ` +
|
|
913
|
+
`source. ${copyRepair(effect, name)}`;
|
|
914
|
+
reportDiagnostic(
|
|
915
|
+
emitDiagnostic(
|
|
916
|
+
{
|
|
917
|
+
code: "EFFECT_RELAY_TEAR",
|
|
918
|
+
kind: "perf",
|
|
919
|
+
severity: "warn",
|
|
920
|
+
message,
|
|
921
|
+
nodeName: nodeName(effect),
|
|
922
|
+
data: {
|
|
923
|
+
relay: nodeName(effect),
|
|
924
|
+
wrote: name,
|
|
925
|
+
copy: true,
|
|
926
|
+
passthrough: passthroughSource(effect) ?? null,
|
|
927
|
+
soleWriter: true
|
|
928
|
+
}
|
|
929
|
+
},
|
|
930
|
+
effect
|
|
931
|
+
)
|
|
932
|
+
);
|
|
933
|
+
}
|
|
934
|
+
/**
|
|
935
|
+
* `victim` re-ran with `causes`; its previous run had `prevCauses`. A tear is
|
|
936
|
+
* a re-run whose root writes ALL came from effects (no independent outside
|
|
937
|
+
* cause) and at least one of which was made by a run that shares a root
|
|
938
|
+
* write with the victim's previous run.
|
|
939
|
+
*/
|
|
940
|
+
function checkRelayTear(victim, causes, prevCauses) {
|
|
941
|
+
if (prevCauses === undefined || causes.length === 0) return;
|
|
942
|
+
const roots = [];
|
|
943
|
+
rootWrites(causes, roots);
|
|
944
|
+
if (roots.length === 0) return;
|
|
945
|
+
let relay;
|
|
946
|
+
let write;
|
|
947
|
+
let shared;
|
|
948
|
+
for (const root of roots) {
|
|
949
|
+
const origin = root.origin;
|
|
950
|
+
if (origin === undefined || origin.kind !== "effect") return;
|
|
951
|
+
const info = effectFrames.get(origin);
|
|
952
|
+
// Own-source cycles are EFFECT_WRITES_OWN_SOURCE's; a create-run relay
|
|
953
|
+
// is initial sync, not a tear for one change.
|
|
954
|
+
if (info === undefined || info.node === victim || info.causes === undefined) return;
|
|
955
|
+
if (shared === undefined) {
|
|
956
|
+
const relayRoots = [];
|
|
957
|
+
rootWrites(info.causes, relayRoots);
|
|
958
|
+
const prevRoots = [];
|
|
959
|
+
rootWrites(prevCauses, prevRoots);
|
|
960
|
+
const hit = relayRoots.find(r => prevRoots.includes(r));
|
|
961
|
+
if (hit !== undefined) {
|
|
962
|
+
shared = hit;
|
|
963
|
+
relay = info;
|
|
964
|
+
write = root;
|
|
965
|
+
}
|
|
966
|
+
}
|
|
967
|
+
}
|
|
968
|
+
if (shared === undefined || relay === undefined || write === undefined) return;
|
|
969
|
+
const key = `${devId(relay.node)}:${write.name}`;
|
|
970
|
+
let state = relays.get(key);
|
|
971
|
+
if (state === undefined) relays.set(key, (state = { count: 0, warned: false }));
|
|
972
|
+
state.count++;
|
|
973
|
+
const copy = copyWrites.has(write);
|
|
974
|
+
const target = recordNodes.get(write);
|
|
975
|
+
const soleWriter = target !== undefined && target._devSoleWriter === devId(relay.node);
|
|
976
|
+
// Derivable outright: the value is the compute output and nothing else
|
|
977
|
+
// writes the signal. A copy INTO a signal that has other writers is the
|
|
978
|
+
// "reset editable state from a source" shape — the tear is real, but a memo
|
|
979
|
+
// is not the answer, so it stays advisory like any other non-derivable tear.
|
|
980
|
+
const derivable = copy && soleWriter;
|
|
981
|
+
const severity = derivable || state.count >= RELAY_WARN_AT ? "warn" : "info";
|
|
982
|
+
// First sighting always reports (advisory); afterwards only the escalation.
|
|
983
|
+
if (state.count > 1 && (severity !== "warn" || state.warned)) return;
|
|
984
|
+
// One verdict per derivable signal: the copy report (checkCopyEffect) and
|
|
985
|
+
// the tear report carry the same repair.
|
|
986
|
+
if (derivable && target !== undefined) {
|
|
987
|
+
if (copyReported.has(target)) return;
|
|
988
|
+
copyReported.add(target);
|
|
989
|
+
}
|
|
990
|
+
if (severity === "warn") state.warned = true;
|
|
991
|
+
const victimKind = victim._type ? "effect" : "memo";
|
|
992
|
+
const relayName = nodeName(relay.node);
|
|
993
|
+
const repair = derivable
|
|
994
|
+
? copyRepair(relay.node, write.name)
|
|
995
|
+
: copy
|
|
996
|
+
? `The written value is the effect's compute output, but "${write.name}" has other ` +
|
|
997
|
+
`writers — editable state reset from a source. If the reset is the intent, the tear ` +
|
|
998
|
+
`is its cost; if "${write.name}" only ever mirrors the source, drop the local copy ` +
|
|
999
|
+
`and read the source.`
|
|
1000
|
+
: soleWriter
|
|
1001
|
+
? `Nothing else writes "${write.name}" — it is derived state: make it a memo over what ` +
|
|
1002
|
+
`the effect reads and every reader gets it in the same flush.`
|
|
1003
|
+
: `If "${write.name}" is computed from what the effect reads, make it a memo so readers ` +
|
|
1004
|
+
`get it in the same flush; if the write reads something outside the graph (layout, ` +
|
|
1005
|
+
`time), the tear is the cost of measuring.`;
|
|
1006
|
+
const message =
|
|
1007
|
+
`[EFFECT_RELAY_TEAR] ${victimKind} "${nodeName(victim)}" ran twice for one write of ` +
|
|
1008
|
+
`"${shared.name}": once in the flush where "${shared.name}" changed, and again after ` +
|
|
1009
|
+
`effect "${relayName}" relayed it by writing "${write.name}" — the first frame showed the ` +
|
|
1010
|
+
`new "${shared.name}" with the stale "${write.name}"` +
|
|
1011
|
+
(state.count > 1 ? ` (${state.count} times so far)` : "") +
|
|
1012
|
+
`. ${repair}`;
|
|
1013
|
+
const entry = emitDiagnostic(
|
|
1014
|
+
{
|
|
1015
|
+
code: "EFFECT_RELAY_TEAR",
|
|
1016
|
+
kind: "perf",
|
|
1017
|
+
severity,
|
|
1018
|
+
message,
|
|
1019
|
+
nodeName: nodeName(victim),
|
|
1020
|
+
data: {
|
|
1021
|
+
victim: nodeName(victim),
|
|
1022
|
+
root: shared.name,
|
|
1023
|
+
relay: relayName,
|
|
1024
|
+
wrote: write.name,
|
|
1025
|
+
copy,
|
|
1026
|
+
passthrough: copy ? (passthroughSource(relay.node) ?? null) : null,
|
|
1027
|
+
soleWriter,
|
|
1028
|
+
occurrences: state.count
|
|
1029
|
+
}
|
|
1030
|
+
},
|
|
1031
|
+
victim
|
|
1032
|
+
);
|
|
1033
|
+
if (severity === "warn") reportDiagnostic(entry);
|
|
1034
|
+
}
|
|
1035
|
+
// --- Immutable updates in stores ---------------------------------------------
|
|
1036
|
+
//
|
|
1037
|
+
// `draft.user = { ...draft.user, name }` / `draft.items = [...draft.items,
|
|
1038
|
+
// x]` / `draft.items = draft.items.filter(...)` — the React habit of
|
|
1039
|
+
// producing a fresh container to change one leaf. The store tracks leaves, so
|
|
1040
|
+
// a fresh container is pure cost: every reader of `user` (any path below it)
|
|
1041
|
+
// re-runs for the one leaf that moved, where a draft mutation would re-run
|
|
1042
|
+
// only the readers of `name`. The store's notify sees both containers at the
|
|
1043
|
+
// write and reports a leaf census (identity on unwrapped values, capped); the
|
|
1044
|
+
// verdict is the whole detector: a replacement whose leaves are mostly the
|
|
1045
|
+
// SAME values is a spread-copy, and one whose leaves are mostly different is
|
|
1046
|
+
// new data (reconcile's job — and UNSTABLE_LIST_IDENTITY's, downstream). Once
|
|
1047
|
+
// per store path.
|
|
1048
|
+
const immutableReported = new Set();
|
|
1049
|
+
function checkImmutableUpdate(path, isArray, total, same, prevTotal, owner) {
|
|
1050
|
+
if (immutableReported.has(path) || total < 2) return;
|
|
1051
|
+
// Push/filter/splice copies change the length by a little; a wholesale
|
|
1052
|
+
// resize is a different operation even if some items survive.
|
|
1053
|
+
if (isArray && Math.abs(prevTotal - total) > Math.max(1, total >> 2)) return;
|
|
1054
|
+
// At least half the leaves carried over unchanged, and at least one did.
|
|
1055
|
+
if (same === 0 || same * 2 < total) return;
|
|
1056
|
+
const changed = total - same;
|
|
1057
|
+
const shape = isArray ? "array" : "object";
|
|
1058
|
+
const repair = isArray
|
|
1059
|
+
? `mutate the draft in place (push/splice/index assignment) so only the touched ` +
|
|
1060
|
+
`indices notify`
|
|
1061
|
+
: `assign the leaf on the draft (\`${path}.<key> = …\`) so only readers of that key re-run`;
|
|
1062
|
+
const message =
|
|
1063
|
+
`[IMMUTABLE_UPDATE_IN_STORE] "${path}" was replaced with a fresh ${shape} whose ` +
|
|
1064
|
+
`${isArray ? "items" : "leaves"} are mostly the same values (${same} of ${total} unchanged` +
|
|
1065
|
+
`${changed > 0 ? `, ${changed} changed` : ""}) — a spread-copy update. The store already ` +
|
|
1066
|
+
`tracks ${isArray ? "items" : "leaves"}; a new container makes every reader of "${path}" ` +
|
|
1067
|
+
`re-run for the ${changed === 1 ? "one that" : "few that"} moved. Instead, ${repair}. For ` +
|
|
1068
|
+
`data arriving from outside (a fetch result), merge it with reconcile(data, key)(${path}).`;
|
|
1069
|
+
// The subject is the store's own owner, not the writer's context: the
|
|
1070
|
+
// finding is about the store, and its writes legitimately arrive from
|
|
1071
|
+
// outside the graph (an event handler, an adapter). Falls back to the
|
|
1072
|
+
// ambient context (emitDiagnostic's default) when the store recorded none.
|
|
1073
|
+
const entry = emitDiagnostic(
|
|
1074
|
+
{
|
|
1075
|
+
code: "IMMUTABLE_UPDATE_IN_STORE",
|
|
1076
|
+
kind: "perf",
|
|
1077
|
+
severity: "warn",
|
|
1078
|
+
message,
|
|
1079
|
+
nodeName: path,
|
|
1080
|
+
data: { path, shape, total, unchanged: same, changed }
|
|
1081
|
+
},
|
|
1082
|
+
owner
|
|
1083
|
+
);
|
|
1084
|
+
// Paths are not unique across stores: an excluded owner's store (an
|
|
1085
|
+
// adapter's own "store.list") must not spend the app's once-per-path slot.
|
|
1086
|
+
if (isSuppressed(entry)) return;
|
|
1087
|
+
immutableReported.add(path);
|
|
1088
|
+
reportDiagnostic(entry);
|
|
1089
|
+
}
|
|
1090
|
+
// --- Unstable list identity -----------------------------------------------------
|
|
1091
|
+
//
|
|
1092
|
+
// `<For>` keyed by identity (the default) treats every new object as a new
|
|
1093
|
+
// row. When a re-fetch hands back fresh objects for the same records, or a
|
|
1094
|
+
// spread-copy rebuilds the array, most rows are disposed and recreated —
|
|
1095
|
+
// DOM, state, focus, and all — for data that did not change. mapArray knows
|
|
1096
|
+
// exactly which items exited and entered; pairing them (by `id` when the
|
|
1097
|
+
// items carry one, else by position) and sampling shallow equivalence turns
|
|
1098
|
+
// that into a verdict: churn that replaced equivalent records is unstable
|
|
1099
|
+
// identity, not a new list. A key function that still churns has the same
|
|
1100
|
+
// disease one level up (its keys are not stable). Once per list.
|
|
1101
|
+
const LIST_CHURN_SAMPLE = 8;
|
|
1102
|
+
const listIdentityWarned = new WeakSet();
|
|
1103
|
+
function recordId(item) {
|
|
1104
|
+
if (item === null || typeof item !== "object") return undefined;
|
|
1105
|
+
const o = item;
|
|
1106
|
+
return o.id ?? o.key ?? o._id ?? undefined;
|
|
1107
|
+
}
|
|
1108
|
+
function checkListIdentity(el, removed, created, newLen, keyed) {
|
|
1109
|
+
if (listIdentityWarned.has(el)) return;
|
|
1110
|
+
// Most of the list turned over, and the turnover was a swap (rows out ≈ rows in).
|
|
1111
|
+
if (created.length < 2 || created.length * 2 < newLen) return;
|
|
1112
|
+
if (Math.abs(removed.length - created.length) > Math.max(1, created.length >> 2)) return;
|
|
1113
|
+
// Pair exited with entered: by record id when present, else by position.
|
|
1114
|
+
const byId = new Map();
|
|
1115
|
+
for (const item of removed) {
|
|
1116
|
+
const id = recordId(item);
|
|
1117
|
+
if (id !== undefined) byId.set(id, item);
|
|
1118
|
+
}
|
|
1119
|
+
let sampled = 0;
|
|
1120
|
+
let equivalent = 0;
|
|
1121
|
+
const step = Math.max(1, Math.floor(created.length / LIST_CHURN_SAMPLE));
|
|
1122
|
+
for (let i = 0; i < created.length && sampled < LIST_CHURN_SAMPLE; i += step) {
|
|
1123
|
+
const item = created[i];
|
|
1124
|
+
const id = recordId(item);
|
|
1125
|
+
const prev = id !== undefined ? byId.get(id) : removed[i];
|
|
1126
|
+
if (prev === undefined || !isPlainShape(prev) || !isPlainShape(item)) continue;
|
|
1127
|
+
sampled++;
|
|
1128
|
+
if (shallowEquivalent(prev, item)) equivalent++;
|
|
1129
|
+
}
|
|
1130
|
+
if (sampled === 0 || equivalent * 2 < sampled) return;
|
|
1131
|
+
listIdentityWarned.add(el);
|
|
1132
|
+
const name = nodeName(el);
|
|
1133
|
+
const repair = keyed
|
|
1134
|
+
? `The key function returned different keys for equivalent records — return a stable ` +
|
|
1135
|
+
`field (\`keyed: item => item.id\`), not the object or a computed value that changes ` +
|
|
1136
|
+
`with the fetch.`
|
|
1137
|
+
: `Key the list by a stable field (\`keyed: item => item.id\`), or merge the data into ` +
|
|
1138
|
+
`a store with reconcile(data, "id") so the same records keep the same identity.`;
|
|
1139
|
+
const message =
|
|
1140
|
+
`[UNSTABLE_LIST_IDENTITY] list "${name}" recreated ${created.length} of ${newLen} rows on ` +
|
|
1141
|
+
`an update where the entering items are equivalent to the ones they replaced ` +
|
|
1142
|
+
`(${equivalent} of ${sampled} sampled pairs identical field-for-field) — fresh objects ` +
|
|
1143
|
+
`for the same records, so identity keying threw away every row's DOM and state and ` +
|
|
1144
|
+
`rebuilt it. ${repair}`;
|
|
1145
|
+
reportDiagnostic(
|
|
1146
|
+
emitDiagnostic(
|
|
1147
|
+
{
|
|
1148
|
+
code: "UNSTABLE_LIST_IDENTITY",
|
|
1149
|
+
kind: "perf",
|
|
1150
|
+
severity: "warn",
|
|
1151
|
+
message,
|
|
1152
|
+
nodeName: name,
|
|
1153
|
+
data: {
|
|
1154
|
+
removed: removed.length,
|
|
1155
|
+
created: created.length,
|
|
1156
|
+
length: newLen,
|
|
1157
|
+
sampled,
|
|
1158
|
+
equivalent,
|
|
1159
|
+
keyed
|
|
1160
|
+
}
|
|
1161
|
+
},
|
|
1162
|
+
el
|
|
1163
|
+
)
|
|
1164
|
+
);
|
|
1165
|
+
}
|
|
1166
|
+
/** Provenance of an async landing: the flight, under the interaction that started it. */
|
|
1167
|
+
function asyncOrigin(el) {
|
|
1168
|
+
const origin = { kind: "async", name: nodeName(el) };
|
|
1169
|
+
const interaction = liveFlights.get(el)?.interaction;
|
|
1170
|
+
if (interaction !== undefined) origin.interaction = interaction;
|
|
1171
|
+
return origin;
|
|
1172
|
+
}
|
|
1173
|
+
// WeakMaps: an errored/abandoned flight must not leak its node or block GC.
|
|
1174
|
+
const liveFlights = new WeakMap();
|
|
1175
|
+
const landedFlights = new WeakMap();
|
|
1176
|
+
/**
|
|
1177
|
+
* Flight-object identity → earliest known start. Fed by markFlight() (the
|
|
1178
|
+
* cooperative preload/cache declaration — populated even while attribution
|
|
1179
|
+
* is disabled, so navigation-time marks survive a later enable()) and by
|
|
1180
|
+
* first sightings at registration.
|
|
1181
|
+
*/
|
|
1182
|
+
const flightOrigins = new WeakMap();
|
|
1183
|
+
let waterfallLog = [];
|
|
1184
|
+
/** Deepest landed-flight cause reachable through a cause list (derived links included). */
|
|
1185
|
+
function flightCauseIn(causes) {
|
|
1186
|
+
let best = null;
|
|
1187
|
+
for (const c of causes) {
|
|
1188
|
+
let found = null;
|
|
1189
|
+
if (c.kind === "async") found = landedFlights.get(c) ?? null;
|
|
1190
|
+
else if (c.kind === "derived" && c.causes) found = flightCauseIn(c.causes);
|
|
1191
|
+
if (found !== null && (best === null || found.chain.length > best.chain.length)) best = found;
|
|
1192
|
+
}
|
|
1193
|
+
return best;
|
|
1194
|
+
}
|
|
1195
|
+
function trackFlightStart(el, flight) {
|
|
1196
|
+
const at = now();
|
|
1197
|
+
const origin = flightOrigins.get(flight) ?? at;
|
|
1198
|
+
if (origin === at) flightOrigins.set(flight, at);
|
|
1199
|
+
// Census: a flight still in the air when the node starts another was
|
|
1200
|
+
// superseded — its answer will be discarded.
|
|
1201
|
+
for (const f of folds) f.flightStart?.(el, liveFlights.has(el));
|
|
1202
|
+
// Nearest enclosing frame with causes: create runs carry null (a node born
|
|
1203
|
+
// inside a parent's recompute inherits the parent's causality — the
|
|
1204
|
+
// boundary-reveal case, and the lazy sibling whose first pull is gated
|
|
1205
|
+
// behind an earlier not-ready read), so walk down to the first re-run frame.
|
|
1206
|
+
let causes = null;
|
|
1207
|
+
for (let i = frames.length - 1; i >= 0; i--) {
|
|
1208
|
+
if (frames[i].causes !== null) {
|
|
1209
|
+
causes = frames[i].causes;
|
|
1210
|
+
break;
|
|
1211
|
+
}
|
|
1212
|
+
}
|
|
1213
|
+
const live = { origin, startSeq: changeSeq, chain: [] };
|
|
1214
|
+
// Provenance: the flight belongs to whatever interaction caused the
|
|
1215
|
+
// recompute that started it (a create run under a click's handler — a
|
|
1216
|
+
// freshly mounted async node — inherits the ambient interaction instead).
|
|
1217
|
+
const interaction = causes !== null ? interactionIn(causes) : (currentInteraction ?? undefined);
|
|
1218
|
+
if (interaction !== undefined) live.interaction = interaction;
|
|
1219
|
+
if (options.waterfalls !== false && causes !== null) {
|
|
1220
|
+
let parent = flightCauseIn(causes);
|
|
1221
|
+
// The sequentiality test. A marked/previously-seen flight whose origin
|
|
1222
|
+
// predates the upstream landing was in the air alongside it: parallel.
|
|
1223
|
+
if (parent !== null && origin < parent.landedAt) parent = null;
|
|
1224
|
+
if (parent !== null) live.chain = [...parent.chain, { name: parent.name, ms: parent.ms }];
|
|
1225
|
+
}
|
|
1226
|
+
liveFlights.set(el, live);
|
|
1227
|
+
}
|
|
1228
|
+
/**
|
|
1229
|
+
* Flight landed (whether or not the value committed — the wall time was
|
|
1230
|
+
* spent either way). Attach the measurement to the landing's fresh "async"
|
|
1231
|
+
* stamp so downstream flights can chain through it, then judge the chain.
|
|
1232
|
+
*/
|
|
1233
|
+
function finalizeFlight(el) {
|
|
1234
|
+
const flight = liveFlights.get(el);
|
|
1235
|
+
if (flight === undefined) return;
|
|
1236
|
+
liveFlights.delete(el);
|
|
1237
|
+
const landedAt = now();
|
|
1238
|
+
const ms = landedAt - flight.origin;
|
|
1239
|
+
for (const f of folds) f.flightLanded?.(el, ms);
|
|
1240
|
+
const record = el._devChange;
|
|
1241
|
+
// Only a stamp this landing produced may carry the measurement — a stale
|
|
1242
|
+
// async record from a previous landing must not be re-labeled.
|
|
1243
|
+
if (record !== undefined && record.kind === "async" && record.seq > flight.startSeq)
|
|
1244
|
+
landedFlights.set(record, { name: nodeName(el), ms, chain: flight.chain, landedAt });
|
|
1245
|
+
checkWaterfall(el, flight.chain, ms);
|
|
1246
|
+
}
|
|
1247
|
+
function checkWaterfall(el, chain, ms) {
|
|
1248
|
+
const cfg = options.waterfalls;
|
|
1249
|
+
if (cfg === false) return;
|
|
1250
|
+
if (chain.length > 0) {
|
|
1251
|
+
waterfallLog.push({
|
|
1252
|
+
chain: [...chain, { name: nodeName(el), ms }],
|
|
1253
|
+
sequentialMs: chain.reduce((sum, l) => sum + l.ms, ms)
|
|
1254
|
+
});
|
|
1255
|
+
if (waterfallLog.length > options.historyLimit) waterfallLog.shift();
|
|
1256
|
+
}
|
|
1257
|
+
// The verdict: trailing run of links that were each a real wait. A fast
|
|
1258
|
+
// tail (settled preload/cache hit) or a fast upstream breaks the sequence.
|
|
1259
|
+
if (ms < cfg.minFlightMs) return;
|
|
1260
|
+
let seq = 1;
|
|
1261
|
+
let totalMs = ms;
|
|
1262
|
+
for (let i = chain.length - 1; i >= 0 && chain[i].ms >= cfg.minFlightMs; i--) {
|
|
1263
|
+
seq++;
|
|
1264
|
+
totalMs += chain[i].ms;
|
|
1265
|
+
}
|
|
1266
|
+
if (seq < 2) return;
|
|
1267
|
+
const node = el;
|
|
1268
|
+
if ((node._devWaterfallWarnedAt ?? 0) >= seq) return;
|
|
1269
|
+
node._devWaterfallWarnedAt = seq;
|
|
1270
|
+
const links = [...chain.slice(chain.length - (seq - 1)), { name: nodeName(el), ms }];
|
|
1271
|
+
const path = links.map(l => `"${l.name}" (${l.ms.toFixed(0)}ms)`).join(" → ");
|
|
1272
|
+
const message =
|
|
1273
|
+
`[ASYNC_WATERFALL] ${seq} sequential async flights — ${path} — ` +
|
|
1274
|
+
`${totalMs.toFixed(0)}ms serialized: each began only after the previous resolved ` +
|
|
1275
|
+
`(as far as this graph can see). If a later request doesn't need the earlier ` +
|
|
1276
|
+
`response, derive both from the same inputs so they start together; if the ` +
|
|
1277
|
+
`dependency is intrinsic, preload the dependent data or join the requests ` +
|
|
1278
|
+
`server-side. If this work WAS already started elsewhere (a preloader or request ` +
|
|
1279
|
+
`cache), have that layer stamp its promises with attribution.markFlight() ` +
|
|
1280
|
+
`from "@solidjs/signals/attribution".`;
|
|
1281
|
+
// Depth 2 is advisory-only (structured consumers see it; the console does
|
|
1282
|
+
// not): a 2-chain can be an intrinsic data dependency or an unmarked
|
|
1283
|
+
// preload. A 3+ chain that survived the origin test is near-certainly
|
|
1284
|
+
// structural — that one earns the console.
|
|
1285
|
+
const severity = seq > 2 ? "warn" : "info";
|
|
1286
|
+
const entry = emitDiagnostic(
|
|
1287
|
+
{
|
|
1288
|
+
code: "ASYNC_WATERFALL",
|
|
1289
|
+
kind: "perf",
|
|
1290
|
+
severity,
|
|
1291
|
+
message,
|
|
1292
|
+
nodeName: nodeName(el),
|
|
1293
|
+
data: { chain: links.map(l => ({ name: l.name, ms: l.ms })), sequentialMs: totalMs }
|
|
1294
|
+
},
|
|
1295
|
+
el
|
|
1296
|
+
);
|
|
1297
|
+
if (severity === "warn") reportDiagnostic(entry);
|
|
1298
|
+
}
|
|
1299
|
+
const holdStates = new WeakMap();
|
|
1300
|
+
let activeHold = null;
|
|
1301
|
+
let holdLog = [];
|
|
1302
|
+
/** Companions are optimistic nodes too; `_parentSource` marks them. So is a
|
|
1303
|
+
* memo carrying a DERIVED override (lanes stage, #3479) — a lane pass's
|
|
1304
|
+
* result, not a write anyone made: neither is an acknowledgement. */
|
|
1305
|
+
function isCompanion(node) {
|
|
1306
|
+
return (
|
|
1307
|
+
(!!node._x && node._x._parentSource !== undefined) ||
|
|
1308
|
+
(node._config & CONFIG_DERIVED_OVERRIDE) !== 0
|
|
1309
|
+
);
|
|
1310
|
+
}
|
|
1311
|
+
const HOLD_CENSUS_CAP = 10_000;
|
|
1312
|
+
function acknowledge(state, kind, source, reader) {
|
|
1313
|
+
const key = `${kind}:${source}`;
|
|
1314
|
+
const existing = state.acknowledgements.get(key);
|
|
1315
|
+
const path = reader !== null ? ownerPath(reader) : undefined;
|
|
1316
|
+
// A later census (a merged transition, the settle pass) may find the
|
|
1317
|
+
// reader an earlier one missed.
|
|
1318
|
+
if (existing === undefined)
|
|
1319
|
+
state.acknowledgements.set(
|
|
1320
|
+
key,
|
|
1321
|
+
path !== undefined ? { kind, source, reader: path } : { kind, source }
|
|
1322
|
+
);
|
|
1323
|
+
else if (path !== undefined) existing.reader ??= path;
|
|
1324
|
+
}
|
|
1325
|
+
function censusRegistrations(t, state) {
|
|
1326
|
+
const budget = { left: HOLD_CENSUS_CAP };
|
|
1327
|
+
for (const node of t._optimisticNodes)
|
|
1328
|
+
if (!isCompanion(node))
|
|
1329
|
+
acknowledge(state, "optimistic", nodeName(node), reachesEffect(node, budget));
|
|
1330
|
+
for (const store of t._optimisticStores)
|
|
1331
|
+
acknowledge(state, "optimistic", store?._name ?? "store", null);
|
|
1332
|
+
for (const node of t._affectsNodes)
|
|
1333
|
+
acknowledge(state, "affects", nodeName(node), reachesEffect(node, budget));
|
|
1334
|
+
}
|
|
1335
|
+
/**
|
|
1336
|
+
* Does anything that paints read `companion` — an effect, through however many
|
|
1337
|
+
* memos? A subscriber alone is not acknowledgement: memos compute eagerly, so a
|
|
1338
|
+
* router's `createMemo(() => isPending(location))` subscribes to the companion
|
|
1339
|
+
* whether or not the app ever renders the memo. Only an effect is the screen.
|
|
1340
|
+
* Returns the first effect found (the reader), or null.
|
|
1341
|
+
*/
|
|
1342
|
+
function reachesEffect(companion, budget) {
|
|
1343
|
+
const seen = new Set([companion]);
|
|
1344
|
+
const stack = [companion];
|
|
1345
|
+
while (stack.length > 0 && budget.left-- > 0) {
|
|
1346
|
+
const node = stack.pop();
|
|
1347
|
+
for (let s = node._subs; s !== null; s = s._nextSub) {
|
|
1348
|
+
const sub = s._sub;
|
|
1349
|
+
if (sub._type) return sub;
|
|
1350
|
+
if (!seen.has(sub)) {
|
|
1351
|
+
seen.add(sub);
|
|
1352
|
+
stack.push(sub);
|
|
1353
|
+
}
|
|
1354
|
+
}
|
|
1355
|
+
}
|
|
1356
|
+
return null;
|
|
1357
|
+
}
|
|
1358
|
+
/** Companions an effect reads, anywhere downstream of the hold's nodes. */
|
|
1359
|
+
function censusCompanions(roots, state) {
|
|
1360
|
+
const visited = new Set();
|
|
1361
|
+
const stack = [...roots];
|
|
1362
|
+
const budget = { left: HOLD_CENSUS_CAP };
|
|
1363
|
+
while (stack.length > 0 && visited.size < HOLD_CENSUS_CAP) {
|
|
1364
|
+
const node = stack.pop();
|
|
1365
|
+
if (visited.has(node)) continue;
|
|
1366
|
+
visited.add(node);
|
|
1367
|
+
const x = node._x;
|
|
1368
|
+
if (x) {
|
|
1369
|
+
let reader;
|
|
1370
|
+
if (x._pendingSignal !== undefined && (reader = reachesEffect(x._pendingSignal, budget)))
|
|
1371
|
+
acknowledge(state, "isPending", nodeName(node), reader);
|
|
1372
|
+
if (
|
|
1373
|
+
x._latestValueComputed !== undefined &&
|
|
1374
|
+
(reader = reachesEffect(x._latestValueComputed, budget))
|
|
1375
|
+
)
|
|
1376
|
+
acknowledge(state, "latest", nodeName(node), reader);
|
|
1377
|
+
for (let child = x._child ?? null; child !== null; child = child._nextChild ?? null)
|
|
1378
|
+
stack.push(child);
|
|
1379
|
+
}
|
|
1380
|
+
for (let s = node._subs; s !== null; s = s._nextSub) stack.push(s._sub);
|
|
1381
|
+
}
|
|
1382
|
+
}
|
|
1383
|
+
function holdState(t) {
|
|
1384
|
+
let state = holdStates.get(t);
|
|
1385
|
+
if (state === undefined) {
|
|
1386
|
+
state = {
|
|
1387
|
+
start: now(),
|
|
1388
|
+
flushes: 0,
|
|
1389
|
+
blockers: new Set(),
|
|
1390
|
+
acknowledgements: new Map(),
|
|
1391
|
+
painted: 0,
|
|
1392
|
+
action: false
|
|
1393
|
+
};
|
|
1394
|
+
holdStates.set(t, state);
|
|
1395
|
+
}
|
|
1396
|
+
return state;
|
|
1397
|
+
}
|
|
1398
|
+
function trackHoldStart(t) {
|
|
1399
|
+
// Navigations and interactions learn they are held regardless of hold
|
|
1400
|
+
// tracking: their settle must wait for the transition either way (see flushEnd).
|
|
1401
|
+
markNavigationsHeld(t);
|
|
1402
|
+
markInteractionsHeld(t);
|
|
1403
|
+
if (options.holds === false) return;
|
|
1404
|
+
const state = holdState(t);
|
|
1405
|
+
state.flushes++;
|
|
1406
|
+
if (t._actions.length > 0) state.action = true;
|
|
1407
|
+
for (const [source, reporters] of t._asyncReporters)
|
|
1408
|
+
if (reporters.size > 0) state.blockers.add(source);
|
|
1409
|
+
censusRegistrations(t, state);
|
|
1410
|
+
activeHold = state;
|
|
1411
|
+
}
|
|
1412
|
+
function trackHoldMerge(target, outgoing) {
|
|
1413
|
+
mergeInteractionsHeld(target, outgoing);
|
|
1414
|
+
const from = holdStates.get(outgoing);
|
|
1415
|
+
if (from === undefined) return;
|
|
1416
|
+
holdStates.delete(outgoing);
|
|
1417
|
+
const into = holdState(target);
|
|
1418
|
+
if (from.start < into.start) into.start = from.start;
|
|
1419
|
+
into.flushes += from.flushes;
|
|
1420
|
+
into.painted += from.painted;
|
|
1421
|
+
into.action ||= from.action;
|
|
1422
|
+
for (const b of from.blockers) into.blockers.add(b);
|
|
1423
|
+
for (const [key, a] of from.acknowledgements)
|
|
1424
|
+
if (!into.acknowledgements.has(key)) into.acknowledgements.set(key, a);
|
|
1425
|
+
}
|
|
1426
|
+
function trackHoldSettled(t) {
|
|
1427
|
+
const state = holdStates.get(t);
|
|
1428
|
+
if (state === undefined) {
|
|
1429
|
+
// No hold was recorded (the transition completed in its first flush, or
|
|
1430
|
+
// hold tracking is off): navigations and interactions staged in it still
|
|
1431
|
+
// settle here.
|
|
1432
|
+
settleNavigations(t, undefined);
|
|
1433
|
+
settleInteractionsHeld(t, undefined);
|
|
1434
|
+
return;
|
|
1435
|
+
}
|
|
1436
|
+
holdStates.delete(t);
|
|
1437
|
+
// Root writes only: a memo in _pendingNodes is a derived hold, and the
|
|
1438
|
+
// question is whether the USER's input went unanswered.
|
|
1439
|
+
const heldWrites = [];
|
|
1440
|
+
let subject = null;
|
|
1441
|
+
let interaction;
|
|
1442
|
+
let origin;
|
|
1443
|
+
let lastJoinAt = -Infinity;
|
|
1444
|
+
for (const node of t._pendingNodes) {
|
|
1445
|
+
if (typeof node._fn === "function" || isCompanion(node)) continue;
|
|
1446
|
+
const change = node._devChange;
|
|
1447
|
+
if (change === undefined || change.kind !== "write") continue;
|
|
1448
|
+
if (subject === null) subject = node;
|
|
1449
|
+
const held = { name: nodeName(node), prev: change.prev, value: change.value };
|
|
1450
|
+
if (change.origin !== undefined) held.origin = change.origin;
|
|
1451
|
+
heldWrites.push(held);
|
|
1452
|
+
// Earliest interaction among the held writes: the user has been waiting
|
|
1453
|
+
// since the first thing they did that this transaction is holding.
|
|
1454
|
+
const under = interactionOf(change.origin);
|
|
1455
|
+
if (under !== undefined && (interaction === undefined || under.at < interaction.at))
|
|
1456
|
+
interaction = under;
|
|
1457
|
+
// The declared frame the writes belong to — earliest navigation, by the
|
|
1458
|
+
// same reasoning.
|
|
1459
|
+
if (
|
|
1460
|
+
change.origin?.kind === "navigation" &&
|
|
1461
|
+
(origin === undefined || change.origin.at < origin.at)
|
|
1462
|
+
)
|
|
1463
|
+
origin = change.origin;
|
|
1464
|
+
// Latest write: a signal written twice while held carries the later
|
|
1465
|
+
// stamp, so this is the user's final input, not their first.
|
|
1466
|
+
if (change.at !== undefined && change.at > lastJoinAt) lastJoinAt = change.at;
|
|
1467
|
+
}
|
|
1468
|
+
if (heldWrites.length === 0) {
|
|
1469
|
+
settleNavigations(t, undefined);
|
|
1470
|
+
settleInteractionsHeld(t, undefined);
|
|
1471
|
+
return;
|
|
1472
|
+
}
|
|
1473
|
+
censusRegistrations(t, state);
|
|
1474
|
+
censusCompanions([...t._pendingNodes, ...state.blockers], state);
|
|
1475
|
+
const end = now();
|
|
1476
|
+
// The hold began no later than its first parked flush; an interaction stamp
|
|
1477
|
+
// reaches further back (dispatch). A node rewritten mid-hold keeps only its
|
|
1478
|
+
// latest record, so the surviving interaction may be a later one — the
|
|
1479
|
+
// flush clock keeps the first wait from being forgotten.
|
|
1480
|
+
const at = Math.min(state.start, interaction !== undefined ? interaction.at : Infinity);
|
|
1481
|
+
const holdMs = end - at;
|
|
1482
|
+
const event = {
|
|
1483
|
+
at,
|
|
1484
|
+
holdMs,
|
|
1485
|
+
tailMs: lastJoinAt === -Infinity ? holdMs : Math.min(holdMs, end - lastJoinAt),
|
|
1486
|
+
flushes: state.flushes,
|
|
1487
|
+
heldWrites,
|
|
1488
|
+
blockers: [...state.blockers].map(nodeName),
|
|
1489
|
+
acknowledgements: [...state.acknowledgements.values()],
|
|
1490
|
+
paintedDuringHold: state.painted,
|
|
1491
|
+
action: state.action
|
|
1492
|
+
};
|
|
1493
|
+
if (interaction !== undefined) event.interaction = interaction;
|
|
1494
|
+
if (origin !== undefined) event.origin = origin;
|
|
1495
|
+
holdLog.push(event);
|
|
1496
|
+
if (holdLog.length > options.historyLimit) holdLog.shift();
|
|
1497
|
+
// Bottom-up delivery: the hold, then the navigations it held, then the
|
|
1498
|
+
// interactions those belong to — each record complete when its parent is.
|
|
1499
|
+
emitRecord("hold", event);
|
|
1500
|
+
settleNavigations(t, event);
|
|
1501
|
+
settleInteractionsHeld(t, event);
|
|
1502
|
+
for (const f of folds) f.hold?.(event);
|
|
1503
|
+
if (isSilentHold(event)) checkSilentHold(event, subject);
|
|
1504
|
+
else checkLongHold(event, subject);
|
|
1505
|
+
}
|
|
1506
|
+
/** `isLongHold` — the tail outlasted `longHolds.infoMs`. */
|
|
1507
|
+
/** @internal */
|
|
1508
|
+
function isLongHold(event) {
|
|
1509
|
+
const cfg = options.longHolds;
|
|
1510
|
+
return cfg !== false && cfg !== undefined && event.tailMs >= cfg.infoMs;
|
|
1511
|
+
}
|
|
1512
|
+
function describeHeldWrites(event) {
|
|
1513
|
+
return event.heldWrites
|
|
1514
|
+
.map(w => (w.prev !== undefined ? `"${w.name}" (${w.prev} → ${w.value})` : `"${w.name}"`))
|
|
1515
|
+
.join(", ");
|
|
1516
|
+
}
|
|
1517
|
+
function describeBlockers(event, lead) {
|
|
1518
|
+
return event.blockers.length > 0
|
|
1519
|
+
? ` ${lead} ${event.blockers.map(b => `"${b}"`).join(", ")}`
|
|
1520
|
+
: "";
|
|
1521
|
+
}
|
|
1522
|
+
/**
|
|
1523
|
+
* The boundary repair, shared by LONG_HOLD and a long SILENT_HOLD: a wait
|
|
1524
|
+
* this long should show a fallback, not a stale screen. A `Loading` boundary
|
|
1525
|
+
* lifts the write out of the hold only when it has not revealed yet or its
|
|
1526
|
+
* `on` prop changed — a revealed boundary with no `on` IS the stale screen.
|
|
1527
|
+
*/
|
|
1528
|
+
function boundaryRepair(event) {
|
|
1529
|
+
const key = event.heldWrites[0]?.name ?? "key";
|
|
1530
|
+
return (
|
|
1531
|
+
`A wait this long is past what a stale screen should carry: show a fallback instead. Put ` +
|
|
1532
|
+
`the reader behind a Loading boundary keyed on what changed — <Loading on={${key}()} ` +
|
|
1533
|
+
`fallback={…}> — so the write commits at once and the fallback shows where the data lands; ` +
|
|
1534
|
+
`a boundary that has already revealed keeps the old content unless \`on\` changes. If the ` +
|
|
1535
|
+
`data itself is the problem, preload it or cache it so the wait never gets this long.`
|
|
1536
|
+
);
|
|
1537
|
+
}
|
|
1538
|
+
function holdData(event) {
|
|
1539
|
+
const data = {
|
|
1540
|
+
holdMs: event.holdMs,
|
|
1541
|
+
tailMs: event.tailMs,
|
|
1542
|
+
flushes: event.flushes,
|
|
1543
|
+
heldWrites: event.heldWrites.map(w => w.name),
|
|
1544
|
+
blockers: event.blockers,
|
|
1545
|
+
action: event.action
|
|
1546
|
+
};
|
|
1547
|
+
if (event.interaction !== undefined)
|
|
1548
|
+
data.interaction = { type: event.interaction.name, target: event.interaction.target };
|
|
1549
|
+
if (event.origin?.kind === "navigation") data.navigation = navigationData(event.origin);
|
|
1550
|
+
return data;
|
|
1551
|
+
}
|
|
1552
|
+
/**
|
|
1553
|
+
* Who the verdict sentence starts from: the interaction, with the navigation
|
|
1554
|
+
* it performed in parentheses — `click on a.nav (navigation to /users/:id)`;
|
|
1555
|
+
* the navigation alone when nothing user-dispatched is known (a redirect);
|
|
1556
|
+
* empty when neither is.
|
|
1557
|
+
*/
|
|
1558
|
+
function holdActor(event) {
|
|
1559
|
+
const via = event.origin !== undefined ? formatOrigin(event.origin) : "";
|
|
1560
|
+
if (event.interaction !== undefined)
|
|
1561
|
+
return `${formatOrigin(event.interaction)}${via ? ` (${via})` : ""}`;
|
|
1562
|
+
return via;
|
|
1563
|
+
}
|
|
1564
|
+
function checkSilentHold(event, subject) {
|
|
1565
|
+
const cfg = options.holds;
|
|
1566
|
+
if (cfg === false) return;
|
|
1567
|
+
if (event.holdMs < cfg.infoMs) return;
|
|
1568
|
+
const ms = event.holdMs.toFixed(0);
|
|
1569
|
+
const writes = describeHeldWrites(event);
|
|
1570
|
+
const waitedOn = describeBlockers(event, "waiting on");
|
|
1571
|
+
// With the interaction (or navigation) stamped the sentence starts from
|
|
1572
|
+
// what the user did; without it, from the writes.
|
|
1573
|
+
const actor = holdActor(event);
|
|
1574
|
+
const who = actor ? `${actor} ` : "";
|
|
1575
|
+
let message = event.action
|
|
1576
|
+
? `[SILENT_HOLD] ${who}${who ? "started an action that" : "an action"} held ${writes} for ` +
|
|
1577
|
+
`${ms}ms${waitedOn} and the screen showed nothing for the whole round-trip: no optimistic ` +
|
|
1578
|
+
`value, no isPending() reader, no affects() mark, and no effect ran while it was held. ` +
|
|
1579
|
+
`Pair the action with a createOptimistic/createOptimisticStore write for the expected ` +
|
|
1580
|
+
`outcome (it reverts on failure), or co-write a createOptimistic(false) "saving" flag ` +
|
|
1581
|
+
`the UI reads.`
|
|
1582
|
+
: `[SILENT_HOLD] ${who}${who ? "wrote" : "writes to"} ${writes}${who ? "; the write was" : " were"} ` +
|
|
1583
|
+
`held ${ms}ms${waitedOn} and the screen showed nothing for the wait: no ` +
|
|
1584
|
+
`isPending()/latest() reader downstream, no optimistic value, no affects() mark, and no ` +
|
|
1585
|
+
`effect ran while it was held — the interaction was dead for ${ms}ms. Show the wait: ` +
|
|
1586
|
+
`read isPending(() => ${event.blockers[0] ?? "source"}()) to render a busy state, or ` +
|
|
1587
|
+
`latest(${event.heldWrites[0].name}) to reveal the new input immediately while the data ` +
|
|
1588
|
+
`catches up. The hold itself is correct — do not "fix" this by moving the write off the ` +
|
|
1589
|
+
`async path.`;
|
|
1590
|
+
const long = isLongHold(event);
|
|
1591
|
+
if (long) message += ` ${boundaryRepair(event)}`;
|
|
1592
|
+
const severity = event.holdMs >= cfg.warnMs ? "warn" : "info";
|
|
1593
|
+
const data = holdData(event);
|
|
1594
|
+
data.long = long;
|
|
1595
|
+
const entry = emitDiagnostic(
|
|
1596
|
+
{
|
|
1597
|
+
code: "SILENT_HOLD",
|
|
1598
|
+
kind: "responsiveness",
|
|
1599
|
+
severity,
|
|
1600
|
+
message,
|
|
1601
|
+
nodeName: nodeName(subject),
|
|
1602
|
+
data
|
|
1603
|
+
},
|
|
1604
|
+
subject
|
|
1605
|
+
);
|
|
1606
|
+
if (severity === "warn") reportDiagnostic(entry);
|
|
1607
|
+
}
|
|
1608
|
+
function checkLongHold(event, subject) {
|
|
1609
|
+
const cfg = options.longHolds;
|
|
1610
|
+
if (cfg === false || cfg === undefined) return;
|
|
1611
|
+
if (event.tailMs < cfg.infoMs) return;
|
|
1612
|
+
const tail = event.tailMs.toFixed(0);
|
|
1613
|
+
const writes = describeHeldWrites(event);
|
|
1614
|
+
const waitedOn = describeBlockers(event, "waiting on");
|
|
1615
|
+
const actor = holdActor(event);
|
|
1616
|
+
const who = actor ? `${actor} ` : "";
|
|
1617
|
+
const answered =
|
|
1618
|
+
event.acknowledgements.length > 0
|
|
1619
|
+
? `${event.acknowledgements.map(a => `"${a.kind}:${a.source}"`).join(", ")} said it was pending`
|
|
1620
|
+
: `an effect painted meanwhile`;
|
|
1621
|
+
const sinceLast =
|
|
1622
|
+
event.tailMs < event.holdMs - 1
|
|
1623
|
+
? ` after the last input (${event.holdMs.toFixed(0)}ms in all)`
|
|
1624
|
+
: "";
|
|
1625
|
+
const message =
|
|
1626
|
+
`[LONG_HOLD] ${who}${who ? "wrote" : "writes to"} ${writes}; the screen kept the old ` +
|
|
1627
|
+
`content for ${tail}ms${sinceLast}${waitedOn} — ${answered}, but the hold ran on well past ` +
|
|
1628
|
+
`the point where "loading" over stale content reads as broken. ${boundaryRepair(event)}`;
|
|
1629
|
+
const severity = event.tailMs >= cfg.warnMs ? "warn" : "info";
|
|
1630
|
+
const data = holdData(event);
|
|
1631
|
+
data.acknowledgements = event.acknowledgements;
|
|
1632
|
+
const entry = emitDiagnostic(
|
|
1633
|
+
{
|
|
1634
|
+
code: "LONG_HOLD",
|
|
1635
|
+
kind: "responsiveness",
|
|
1636
|
+
severity,
|
|
1637
|
+
message,
|
|
1638
|
+
nodeName: nodeName(subject),
|
|
1639
|
+
data
|
|
1640
|
+
},
|
|
1641
|
+
subject
|
|
1642
|
+
);
|
|
1643
|
+
if (severity === "warn") reportDiagnostic(entry);
|
|
1644
|
+
}
|
|
1645
|
+
const navStates = new WeakMap();
|
|
1646
|
+
/** Opened, not yet settled. */
|
|
1647
|
+
const openNavs = new Set();
|
|
1648
|
+
let navigationLog = [];
|
|
1649
|
+
/** Drains completed since enable() — the clock `writeDrain` reads. */
|
|
1650
|
+
let drainSeq = 0;
|
|
1651
|
+
/**
|
|
1652
|
+
* Copy what the router currently says onto the frame (what writes stamped —
|
|
1653
|
+
* `formatOrigin` reads it) and the event. Called when the frame opens, when a
|
|
1654
|
+
* redirect re-describes it, and when the record settles, so a description
|
|
1655
|
+
* refined during the hold is what every consumer ends up reading.
|
|
1656
|
+
*/
|
|
1657
|
+
function syncNavigation(state) {
|
|
1658
|
+
const { event, ref } = state;
|
|
1659
|
+
const frame = event.origin;
|
|
1660
|
+
if (ref.name === undefined) {
|
|
1661
|
+
delete frame.name;
|
|
1662
|
+
delete event.name;
|
|
1663
|
+
} else frame.name = event.name = ref.name;
|
|
1664
|
+
if (ref.to === undefined) {
|
|
1665
|
+
delete frame.to;
|
|
1666
|
+
delete event.to;
|
|
1667
|
+
} else frame.to = event.to = ref.to;
|
|
1668
|
+
if (ref.params === undefined) {
|
|
1669
|
+
delete frame.params;
|
|
1670
|
+
delete event.params;
|
|
1671
|
+
} else frame.params = event.params = ref.params;
|
|
1672
|
+
}
|
|
1673
|
+
function openNavigation(frame, ref) {
|
|
1674
|
+
const event = { at: frame.at, writes: 0, origin: frame };
|
|
1675
|
+
if (frame.from !== undefined) event.from = frame.from;
|
|
1676
|
+
if (frame.interaction !== undefined) event.interaction = frame.interaction;
|
|
1677
|
+
const state = {
|
|
1678
|
+
event,
|
|
1679
|
+
ref,
|
|
1680
|
+
open: 1,
|
|
1681
|
+
held: false,
|
|
1682
|
+
writeDrain: drainSeq
|
|
1683
|
+
};
|
|
1684
|
+
syncNavigation(state);
|
|
1685
|
+
navStates.set(frame, state);
|
|
1686
|
+
openNavs.add(state);
|
|
1687
|
+
navigationLog.push(event);
|
|
1688
|
+
if (navigationLog.length > options.historyLimit) navigationLog.shift();
|
|
1689
|
+
noteInteractionNavigation(event);
|
|
1690
|
+
}
|
|
1691
|
+
/** The navigation a redirect hop folds onto: the most recently opened one still pending. */
|
|
1692
|
+
function lastOpenNavigation() {
|
|
1693
|
+
let last;
|
|
1694
|
+
for (const state of openNavs) last = state;
|
|
1695
|
+
return last;
|
|
1696
|
+
}
|
|
1697
|
+
/** A redirect re-describes `state`: the current destination becomes a hop it abandoned. */
|
|
1698
|
+
function redirectNavigation(state, ref) {
|
|
1699
|
+
const event = state.event;
|
|
1700
|
+
// As the router last described the destination being left behind.
|
|
1701
|
+
syncNavigation(state);
|
|
1702
|
+
const hop = { at: ref.at ?? now() };
|
|
1703
|
+
if (event.name !== undefined) hop.name = event.name;
|
|
1704
|
+
if (event.to !== undefined) hop.to = event.to;
|
|
1705
|
+
if (event.params !== undefined) hop.params = event.params;
|
|
1706
|
+
(event.redirects ??= []).push(hop);
|
|
1707
|
+
state.ref = ref;
|
|
1708
|
+
state.open++;
|
|
1709
|
+
syncNavigation(state);
|
|
1710
|
+
}
|
|
1711
|
+
function closeNavigation(frame) {
|
|
1712
|
+
const state = navStates.get(frame);
|
|
1713
|
+
if (state === undefined || --state.open > 0) return;
|
|
1714
|
+
syncNavigation(state);
|
|
1715
|
+
// Nothing to wait for: no write survived the equality gate (navigating to
|
|
1716
|
+
// where we already are), or a drain inside the frame already committed
|
|
1717
|
+
// them (`flush(() => setLocation(…))`) with no hold.
|
|
1718
|
+
if (state.event.writes === 0 || (!state.held && drainSeq > state.writeDrain))
|
|
1719
|
+
settleNavigation(state, "committed");
|
|
1720
|
+
}
|
|
1721
|
+
/** stampWrite: the record replacing `prior` on a node was just stamped. */
|
|
1722
|
+
function noteNavigationWrite(prior, record) {
|
|
1723
|
+
const origin = record.origin;
|
|
1724
|
+
if (origin.kind === "navigation") {
|
|
1725
|
+
const state = navStates.get(origin);
|
|
1726
|
+
if (state !== undefined) {
|
|
1727
|
+
state.event.writes++;
|
|
1728
|
+
state.writeDrain = drainSeq;
|
|
1729
|
+
}
|
|
1730
|
+
}
|
|
1731
|
+
// The node now carries a different frame's record: whatever `prior`'s
|
|
1732
|
+
// navigation was waiting to show on it will never land as that navigation.
|
|
1733
|
+
const before = prior?.origin;
|
|
1734
|
+
if (before !== undefined && before !== origin && before.kind === "navigation") {
|
|
1735
|
+
const state = navStates.get(before);
|
|
1736
|
+
if (state !== undefined && openNavs.has(state)) settleNavigation(state, "superseded");
|
|
1737
|
+
}
|
|
1738
|
+
}
|
|
1739
|
+
/** holdStart: `t`'s staged writes are parked — their navigations settle with `t`. */
|
|
1740
|
+
function markNavigationsHeld(t) {
|
|
1741
|
+
if (openNavs.size === 0) return;
|
|
1742
|
+
for (const node of t._pendingNodes) {
|
|
1743
|
+
const origin = node._devChange?.origin;
|
|
1744
|
+
if (origin?.kind !== "navigation") continue;
|
|
1745
|
+
const state = navStates.get(origin);
|
|
1746
|
+
if (state !== undefined) state.held = true;
|
|
1747
|
+
}
|
|
1748
|
+
}
|
|
1749
|
+
/** transitionSettled: `t` commits — the navigations whose writes it staged are done. */
|
|
1750
|
+
function settleNavigations(t, hold) {
|
|
1751
|
+
if (openNavs.size === 0) return;
|
|
1752
|
+
for (const node of t._pendingNodes) {
|
|
1753
|
+
const origin = node._devChange?.origin;
|
|
1754
|
+
if (origin?.kind !== "navigation") continue;
|
|
1755
|
+
const state = navStates.get(origin);
|
|
1756
|
+
if (state === undefined || !openNavs.has(state)) continue;
|
|
1757
|
+
// A navigation whose frame is still open when its transition commits
|
|
1758
|
+
// (`until()` inside the frame) settles here too: its writes are through.
|
|
1759
|
+
settleNavigation(state, state.held ? "held" : "committed", hold);
|
|
1760
|
+
}
|
|
1761
|
+
}
|
|
1762
|
+
/** flushEnd: every open, closed, unheld navigation's (and interaction's) writes just committed. */
|
|
1763
|
+
function trackFlushEnd() {
|
|
1764
|
+
drainSeq++;
|
|
1765
|
+
for (const state of openNavs)
|
|
1766
|
+
if (state.open === 0 && !state.held) settleNavigation(state, "committed");
|
|
1767
|
+
for (const state of openInteractions) maybeSettleInteraction(state);
|
|
1768
|
+
}
|
|
1769
|
+
function settleNavigation(state, outcome, hold) {
|
|
1770
|
+
if (!openNavs.has(state)) return;
|
|
1771
|
+
openNavs.delete(state);
|
|
1772
|
+
syncNavigation(state);
|
|
1773
|
+
const event = state.event;
|
|
1774
|
+
event.settledMs = now() - event.at;
|
|
1775
|
+
event.outcome = outcome;
|
|
1776
|
+
if (hold !== undefined) event.hold = hold;
|
|
1777
|
+
for (const f of folds) f.navigation?.(event);
|
|
1778
|
+
emitRecord("navigation", event);
|
|
1779
|
+
// The interaction that performed it may have been waiting only on this.
|
|
1780
|
+
const under = openInteractionOf(event.interaction);
|
|
1781
|
+
if (under !== undefined) maybeSettleInteraction(under);
|
|
1782
|
+
}
|
|
1783
|
+
const interactionStates = new WeakMap();
|
|
1784
|
+
/** Opened, not yet settled. */
|
|
1785
|
+
const openInteractions = new Set();
|
|
1786
|
+
let interactionLog = [];
|
|
1787
|
+
function openInteraction(frame) {
|
|
1788
|
+
const event = {
|
|
1789
|
+
name: frame.name,
|
|
1790
|
+
at: frame.at,
|
|
1791
|
+
handlerMs: 0,
|
|
1792
|
+
writes: 0,
|
|
1793
|
+
runs: 0,
|
|
1794
|
+
created: 0,
|
|
1795
|
+
runMs: 0,
|
|
1796
|
+
holds: [],
|
|
1797
|
+
navigations: [],
|
|
1798
|
+
origin: frame
|
|
1799
|
+
};
|
|
1800
|
+
if (frame.target !== undefined) event.target = frame.target;
|
|
1801
|
+
const state = {
|
|
1802
|
+
event,
|
|
1803
|
+
open: true,
|
|
1804
|
+
writeDrain: drainSeq,
|
|
1805
|
+
heldIn: new Set(),
|
|
1806
|
+
held: false,
|
|
1807
|
+
excludedWrites: 0
|
|
1808
|
+
};
|
|
1809
|
+
interactionStates.set(frame, state);
|
|
1810
|
+
openInteractions.add(state);
|
|
1811
|
+
interactionLog.push(event);
|
|
1812
|
+
if (interactionLog.length > options.historyLimit) interactionLog.shift();
|
|
1813
|
+
}
|
|
1814
|
+
/** interactionEnd: the handler returned. */
|
|
1815
|
+
function closeInteraction(frame) {
|
|
1816
|
+
const state = interactionStates.get(frame);
|
|
1817
|
+
if (state === undefined) return;
|
|
1818
|
+
state.open = false;
|
|
1819
|
+
const end = now();
|
|
1820
|
+
state.event.handlerMs = end - state.event.at;
|
|
1821
|
+
maybeSettleInteraction(state, end);
|
|
1822
|
+
}
|
|
1823
|
+
/** The open record a frame runs under, if any. */
|
|
1824
|
+
function openInteractionOf(origin) {
|
|
1825
|
+
const interaction = interactionOf(origin);
|
|
1826
|
+
if (interaction === undefined) return undefined;
|
|
1827
|
+
const state = interactionStates.get(interaction);
|
|
1828
|
+
return state !== undefined && openInteractions.has(state) ? state : undefined;
|
|
1829
|
+
}
|
|
1830
|
+
/** stampWrite: a root write stamped `origin`. */
|
|
1831
|
+
function noteInteractionWrite(origin, excluded) {
|
|
1832
|
+
const state = openInteractionOf(origin);
|
|
1833
|
+
if (state === undefined) return;
|
|
1834
|
+
if (excluded) {
|
|
1835
|
+
state.excludedWrites++;
|
|
1836
|
+
return;
|
|
1837
|
+
}
|
|
1838
|
+
state.event.writes++;
|
|
1839
|
+
state.writeDrain = drainSeq;
|
|
1840
|
+
}
|
|
1841
|
+
/** recordRerun / a create run: work attributed to the interaction. */
|
|
1842
|
+
function noteInteractionRun(interaction, selfMs, created) {
|
|
1843
|
+
const state = openInteractionOf(interaction);
|
|
1844
|
+
if (state === undefined) return;
|
|
1845
|
+
state.event[created ? "created" : "runs"]++;
|
|
1846
|
+
state.event.runMs += selfMs;
|
|
1847
|
+
}
|
|
1848
|
+
/** openNavigation: a navigation frame opened under the interaction. */
|
|
1849
|
+
function noteInteractionNavigation(event) {
|
|
1850
|
+
const state = openInteractionOf(event.interaction);
|
|
1851
|
+
if (state !== undefined) state.event.navigations.push(event);
|
|
1852
|
+
}
|
|
1853
|
+
/** holdStart: `t` parked writes — the interactions that performed them wait for `t`. */
|
|
1854
|
+
function markInteractionsHeld(t) {
|
|
1855
|
+
if (openInteractions.size === 0) return;
|
|
1856
|
+
for (const node of t._pendingNodes) {
|
|
1857
|
+
const state = openInteractionOf(node._devChange?.origin);
|
|
1858
|
+
if (state !== undefined) {
|
|
1859
|
+
state.heldIn.add(t);
|
|
1860
|
+
state.held = true;
|
|
1861
|
+
}
|
|
1862
|
+
}
|
|
1863
|
+
}
|
|
1864
|
+
/** transitionMerged: whoever waited for `outgoing` now waits for `target`. */
|
|
1865
|
+
function mergeInteractionsHeld(target, outgoing) {
|
|
1866
|
+
for (const state of openInteractions) if (state.heldIn.delete(outgoing)) state.heldIn.add(target);
|
|
1867
|
+
}
|
|
1868
|
+
/** transitionSettled: `t` committed — its holders' writes are through. */
|
|
1869
|
+
function settleInteractionsHeld(t, hold) {
|
|
1870
|
+
if (openInteractions.size === 0) return;
|
|
1871
|
+
for (const state of openInteractions) {
|
|
1872
|
+
if (!state.heldIn.delete(t)) continue;
|
|
1873
|
+
if (hold !== undefined) state.event.holds.push(hold);
|
|
1874
|
+
maybeSettleInteraction(state);
|
|
1875
|
+
}
|
|
1876
|
+
}
|
|
1877
|
+
function maybeSettleInteraction(state, end = now()) {
|
|
1878
|
+
const event = state.event;
|
|
1879
|
+
if (state.open || state.heldIn.size > 0) return;
|
|
1880
|
+
// A drain must have committed the last write (the handler's, or a redirect
|
|
1881
|
+
// hop's after the click's own drain) — the handler returning is not the
|
|
1882
|
+
// screen having it.
|
|
1883
|
+
if (event.writes > 0 && drainSeq <= state.writeDrain) return;
|
|
1884
|
+
for (const nav of event.navigations) if (nav.outcome === undefined) return;
|
|
1885
|
+
openInteractions.delete(state);
|
|
1886
|
+
// Every write went to an excluded subject and nothing of the app's ran: the
|
|
1887
|
+
// click was on the observer's own UI (a devtools panel's button). Not a
|
|
1888
|
+
// fact about the app — forget it rather than report a dead interaction.
|
|
1889
|
+
if (event.writes === 0 && state.excludedWrites > 0 && event.runs === 0 && event.created === 0) {
|
|
1890
|
+
const i = interactionLog.indexOf(event);
|
|
1891
|
+
if (i !== -1) interactionLog.splice(i, 1);
|
|
1892
|
+
return;
|
|
1893
|
+
}
|
|
1894
|
+
event.settledMs = end - event.at;
|
|
1895
|
+
event.outcome = event.writes === 0 ? "idle" : state.held ? "held" : "committed";
|
|
1896
|
+
emitRecord("interaction", event);
|
|
1897
|
+
}
|
|
1898
|
+
/** The serializable face of a navigation origin for diagnostic `data`. */
|
|
1899
|
+
function navigationData(origin) {
|
|
1900
|
+
const data = {};
|
|
1901
|
+
if (origin.name !== undefined) data.name = origin.name;
|
|
1902
|
+
if (origin.to !== undefined) data.to = origin.to;
|
|
1903
|
+
if (origin.from !== undefined) data.from = origin.from;
|
|
1904
|
+
if (origin.params !== undefined) data.params = origin.params;
|
|
1905
|
+
return data;
|
|
1906
|
+
}
|
|
1907
|
+
/** @internal No affordance answered and nothing painted while held. */
|
|
1908
|
+
function isSilentHold(event) {
|
|
1909
|
+
return event.paintedDuringHold === 0 && event.acknowledgements.length === 0;
|
|
1910
|
+
}
|
|
1911
|
+
// The engine's implementation of the core's dev hook points. Installed by
|
|
1912
|
+
// enable(), uninstalled by disable() — while uninstalled the core pays one
|
|
1913
|
+
// null check per site and nothing else.
|
|
1914
|
+
let asyncStartSeq = 0;
|
|
1915
|
+
let asyncStartTime = 0;
|
|
1916
|
+
let asyncStartValue;
|
|
1917
|
+
const engineHooks = {
|
|
1918
|
+
interactionStart,
|
|
1919
|
+
interactionEnd,
|
|
1920
|
+
originStart,
|
|
1921
|
+
originEnd,
|
|
1922
|
+
flushEnd() {
|
|
1923
|
+
trackFlushEnd();
|
|
1924
|
+
},
|
|
1925
|
+
recomputeStart(el, create) {
|
|
1926
|
+
const causes = create ? null : collectCauses(el);
|
|
1927
|
+
frames.push({
|
|
1928
|
+
start: now(),
|
|
1929
|
+
childMs: 0,
|
|
1930
|
+
causes,
|
|
1931
|
+
prevDeps: create ? null : captureDeps(el),
|
|
1932
|
+
// Mirror recompute's own prev-value resolution: an earlier run in the
|
|
1933
|
+
// same flush may still be holding in _pendingValue.
|
|
1934
|
+
prevValue: el._pendingValue !== NOT_PENDING ? el._pendingValue : el._value,
|
|
1935
|
+
// A create run inherits the interaction of whatever is building it: the
|
|
1936
|
+
// enclosing recompute (a parent's fn creating children) or, at the top
|
|
1937
|
+
// of the recompute stack, the effect callback / handler frame.
|
|
1938
|
+
interaction:
|
|
1939
|
+
causes !== null
|
|
1940
|
+
? interactionIn(causes)
|
|
1941
|
+
: frames.length > 0
|
|
1942
|
+
? frames[frames.length - 1].interaction
|
|
1943
|
+
: enclosingInteraction()
|
|
1944
|
+
});
|
|
1945
|
+
},
|
|
1946
|
+
derivedChanged(el) {
|
|
1947
|
+
const frame = frames[frames.length - 1];
|
|
1948
|
+
stampDerived(el, frame !== undefined && frame.causes !== null ? frame.causes : []);
|
|
1949
|
+
},
|
|
1950
|
+
recomputeEnd(el, _create, changed, optimistic, transition, held) {
|
|
1951
|
+
const frame = frames.pop();
|
|
1952
|
+
// enable() can land mid-recompute: no opening frame, nothing to report.
|
|
1953
|
+
if (frame === undefined) return;
|
|
1954
|
+
const totalMs = now() - frame.start;
|
|
1955
|
+
if (frames.length > 0) frames[frames.length - 1].childMs += totalMs;
|
|
1956
|
+
const selfMs = Math.max(0, totalMs - frame.childMs);
|
|
1957
|
+
// Effect-output honesty: effects run with `_equals: false`, so core
|
|
1958
|
+
// reports EVERY effect recompute as changed — which made effect waste
|
|
1959
|
+
// invisible to costs() (and compiled JSX bindings are effects: the
|
|
1960
|
+
// fan-out waste a naive selected-row produces is all effects). The
|
|
1961
|
+
// engine re-derives the fact from its own snapshot: an identical
|
|
1962
|
+
// committed compute output is an unchanged run. `undefined` outputs are
|
|
1963
|
+
// exempt — a side-effect-only compute's work IS its effect phase, and
|
|
1964
|
+
// identity of `undefined` proves nothing.
|
|
1965
|
+
if (changed && frame.causes !== null && el._type) {
|
|
1966
|
+
const committed = el._pendingValue !== NOT_PENDING ? el._pendingValue : el._value;
|
|
1967
|
+
if (committed !== undefined && committed === frame.prevValue) changed = false;
|
|
1968
|
+
}
|
|
1969
|
+
// Unstable-output check: memos only, non-create, plain runs with a
|
|
1970
|
+
// committed change. The fresh value sits in `_pendingValue` for held
|
|
1971
|
+
// plain-flush memo commits and in `_value` for direct ones. Overlay runs
|
|
1972
|
+
// are excluded — an optimistic re-derive legitimately produces fresh
|
|
1973
|
+
// equivalents while the lane settles.
|
|
1974
|
+
if (frame.causes !== null && changed && !optimistic && !transition && !el._type)
|
|
1975
|
+
checkUnstableOutput(
|
|
1976
|
+
el,
|
|
1977
|
+
frame.prevValue,
|
|
1978
|
+
el._pendingValue !== NOT_PENDING ? el._pendingValue : el._value
|
|
1979
|
+
);
|
|
1980
|
+
if (frame.causes !== null)
|
|
1981
|
+
recordRerun(
|
|
1982
|
+
el,
|
|
1983
|
+
frame,
|
|
1984
|
+
{ selfMs, totalMs },
|
|
1985
|
+
changed,
|
|
1986
|
+
optimistic ? "optimistic" : transition ? "held" : "plain",
|
|
1987
|
+
held
|
|
1988
|
+
);
|
|
1989
|
+
else if (!excludedNode(el)) {
|
|
1990
|
+
// Creation runs still get the wide-scope check: a memo can be born with
|
|
1991
|
+
// its coarse-read problem already in place — and their time is charged
|
|
1992
|
+
// to the interaction building them (the interaction record's `created`).
|
|
1993
|
+
checkDepWidth(el);
|
|
1994
|
+
noteInteractionRun(frame.interaction, selfMs, true);
|
|
1995
|
+
}
|
|
1996
|
+
markSeen(el);
|
|
1997
|
+
},
|
|
1998
|
+
write(el, prev, value) {
|
|
1999
|
+
stampWrite(el, "write", prev, value);
|
|
2000
|
+
},
|
|
2001
|
+
refreshed(el) {
|
|
2002
|
+
stampWrite(el, "refresh");
|
|
2003
|
+
},
|
|
2004
|
+
flightStart(el, flight) {
|
|
2005
|
+
trackFlightStart(el, flight);
|
|
2006
|
+
},
|
|
2007
|
+
asyncStart(el) {
|
|
2008
|
+
asyncStartSeq = el._devChange?.seq ?? 0;
|
|
2009
|
+
asyncStartTime = el._time;
|
|
2010
|
+
asyncStartValue = el._value;
|
|
2011
|
+
},
|
|
2012
|
+
asyncEnd(el, prev, value, direct) {
|
|
2013
|
+
if (direct) {
|
|
2014
|
+
// Core calls this unconditionally (hook calls cannot live inside its
|
|
2015
|
+
// try blocks — see attribution-hooks.ts), so committed-ness is detected
|
|
2016
|
+
// here against the asyncStart snapshot: a direct commit moves `_value`
|
|
2017
|
+
// (or `_time`, for a same-reference commit under `equals: false`), and
|
|
2018
|
+
// a transition hold parks the value in `_pendingValue`. A landing the
|
|
2019
|
+
// equality gate swallowed moves none of them and must leave no stamp.
|
|
2020
|
+
const committed =
|
|
2021
|
+
el._value !== asyncStartValue || el._time !== asyncStartTime || el._pendingValue === value;
|
|
2022
|
+
if (committed) stampWrite(el, "async", prev === undefined ? NO_VALUES : prev, value);
|
|
2023
|
+
// Flight over either way — an equality-swallowed landing still spent
|
|
2024
|
+
// the wall time (finalizeFlight only chains through a fresh stamp).
|
|
2025
|
+
finalizeFlight(el);
|
|
2026
|
+
return;
|
|
2027
|
+
}
|
|
2028
|
+
// Landed through setSignal: reclassify its "write" stamp as an async
|
|
2029
|
+
// landing — but only if it actually stamped (the value changed) since
|
|
2030
|
+
// asyncStart; a no-change landing must leave no fresh stamp behind.
|
|
2031
|
+
const change = el._devChange;
|
|
2032
|
+
if (change !== undefined && change.seq > asyncStartSeq && change.kind === "write")
|
|
2033
|
+
stampWrite(el, "async", NO_VALUES, value);
|
|
2034
|
+
finalizeFlight(el);
|
|
2035
|
+
},
|
|
2036
|
+
effectRunStart(el) {
|
|
2037
|
+
pushFrame("effect", nodeName(el), el._devRunInteraction, el);
|
|
2038
|
+
},
|
|
2039
|
+
effectRunEnd() {
|
|
2040
|
+
popFrame("effect");
|
|
2041
|
+
if (activeHold !== null) activeHold.painted++;
|
|
2042
|
+
},
|
|
2043
|
+
actionStepStart(it, name) {
|
|
2044
|
+
// Steps after a yield resume from a promise callback with no ambient
|
|
2045
|
+
// interaction; the one that started the action (its first step) is the
|
|
2046
|
+
// action's interaction for every step.
|
|
2047
|
+
let interaction = actionInteractions.get(it);
|
|
2048
|
+
if (interaction === undefined && !actionInteractions.has(it)) {
|
|
2049
|
+
interaction = currentInteraction ?? undefined;
|
|
2050
|
+
actionInteractions.set(it, interaction);
|
|
2051
|
+
}
|
|
2052
|
+
pushFrame("action", name, interaction);
|
|
2053
|
+
},
|
|
2054
|
+
actionStepEnd() {
|
|
2055
|
+
popFrame("action");
|
|
2056
|
+
},
|
|
2057
|
+
holdStart(t) {
|
|
2058
|
+
trackHoldStart(t);
|
|
2059
|
+
},
|
|
2060
|
+
holdEnd() {
|
|
2061
|
+
activeHold = null;
|
|
2062
|
+
},
|
|
2063
|
+
transitionSettled(t) {
|
|
2064
|
+
trackHoldSettled(t);
|
|
2065
|
+
},
|
|
2066
|
+
transitionMerged(target, outgoing) {
|
|
2067
|
+
trackHoldMerge(target, outgoing);
|
|
2068
|
+
},
|
|
2069
|
+
storeReplaced(path, isArray, total, unchanged, prevTotal, owner) {
|
|
2070
|
+
checkImmutableUpdate(path, isArray, total, unchanged, prevTotal, owner);
|
|
2071
|
+
},
|
|
2072
|
+
listChurn(el, removed, created, newLen, keyed) {
|
|
2073
|
+
checkListIdentity(el, removed, created, newLen, keyed);
|
|
2074
|
+
},
|
|
2075
|
+
boundaryFallback(boundary, tree, shown) {
|
|
2076
|
+
for (const f of folds) f.fallback?.(boundary, tree, shown);
|
|
2077
|
+
},
|
|
2078
|
+
currentOrigin() {
|
|
2079
|
+
return ambientOrigin();
|
|
2080
|
+
}
|
|
2081
|
+
};
|
|
2082
|
+
const attribution = {
|
|
2083
|
+
enable(opts) {
|
|
2084
|
+
options = { ...defaultOptions, ...opts };
|
|
2085
|
+
frames.length = 0;
|
|
2086
|
+
waterfallLog = [];
|
|
2087
|
+
holdLog = [];
|
|
2088
|
+
activeHold = null;
|
|
2089
|
+
navigationLog = [];
|
|
2090
|
+
openNavs.clear();
|
|
2091
|
+
interactionLog = [];
|
|
2092
|
+
openInteractions.clear();
|
|
2093
|
+
drainSeq = 0;
|
|
2094
|
+
reportedCycles.clear();
|
|
2095
|
+
relays.clear();
|
|
2096
|
+
immutableReported.clear();
|
|
2097
|
+
originFrames.length = 0;
|
|
2098
|
+
interactionStack.length = 0;
|
|
2099
|
+
currentInteraction = null;
|
|
2100
|
+
hotCauses.clear();
|
|
2101
|
+
for (const f of folds) f.reset?.();
|
|
2102
|
+
setAttributionHooks(engineHooks);
|
|
2103
|
+
},
|
|
2104
|
+
disable() {
|
|
2105
|
+
clearListeners();
|
|
2106
|
+
history = [];
|
|
2107
|
+
frames.length = 0;
|
|
2108
|
+
waterfallLog = [];
|
|
2109
|
+
holdLog = [];
|
|
2110
|
+
activeHold = null;
|
|
2111
|
+
navigationLog = [];
|
|
2112
|
+
openNavs.clear();
|
|
2113
|
+
interactionLog = [];
|
|
2114
|
+
openInteractions.clear();
|
|
2115
|
+
drainSeq = 0;
|
|
2116
|
+
reportedCycles.clear();
|
|
2117
|
+
relays.clear();
|
|
2118
|
+
immutableReported.clear();
|
|
2119
|
+
originFrames.length = 0;
|
|
2120
|
+
interactionStack.length = 0;
|
|
2121
|
+
currentInteraction = null;
|
|
2122
|
+
hotCauses.clear();
|
|
2123
|
+
for (const f of folds) f.reset?.();
|
|
2124
|
+
setAttributionHooks(null);
|
|
2125
|
+
},
|
|
2126
|
+
subscribe(typeOrListener, listener) {
|
|
2127
|
+
const type = typeof typeOrListener === "string" ? typeOrListener : "rerun";
|
|
2128
|
+
const fn = typeof typeOrListener === "string" ? listener : typeOrListener;
|
|
2129
|
+
const set = recordListeners[type];
|
|
2130
|
+
set.add(fn);
|
|
2131
|
+
return () => set.delete(fn);
|
|
2132
|
+
},
|
|
2133
|
+
history() {
|
|
2134
|
+
return history;
|
|
2135
|
+
},
|
|
2136
|
+
waterfalls() {
|
|
2137
|
+
return waterfallLog;
|
|
2138
|
+
},
|
|
2139
|
+
holds() {
|
|
2140
|
+
return holdLog;
|
|
2141
|
+
},
|
|
2142
|
+
navigations() {
|
|
2143
|
+
return navigationLog;
|
|
2144
|
+
},
|
|
2145
|
+
interactions() {
|
|
2146
|
+
return interactionLog;
|
|
2147
|
+
},
|
|
2148
|
+
markFlight(flight, startedAt = now()) {
|
|
2149
|
+
// Earliest wins: re-marking (a cache re-serving the same promise) must
|
|
2150
|
+
// not move the origin later.
|
|
2151
|
+
const existing = flightOrigins.get(flight);
|
|
2152
|
+
if (existing === undefined || startedAt < existing) flightOrigins.set(flight, startedAt);
|
|
2153
|
+
}
|
|
2154
|
+
};
|
|
2155
|
+
|
|
2156
|
+
/**
|
|
2157
|
+
* `costs()` — the cost tables: scopes ranked by the self-time they burn,
|
|
2158
|
+
* root writes ranked by the downstream re-run time they cause. Folded from
|
|
2159
|
+
* every `RerunEvent` as the engine records it.
|
|
2160
|
+
*
|
|
2161
|
+
* Its own module on purpose: the tables register with the engine's fold seam
|
|
2162
|
+
* when this module is evaluated, so an observe-tier consumer that only
|
|
2163
|
+
* subscribes to records (an APM adapter) never ships the accumulation or the
|
|
2164
|
+
* tables; a consumer that imports `costs` gets both. Reset with the engine on
|
|
2165
|
+
* `enable()`/`disable()`.
|
|
2166
|
+
*/
|
|
2167
|
+
const scopeCosts = new Map();
|
|
2168
|
+
const writeCosts = new Map();
|
|
2169
|
+
function recordCosts(el, event) {
|
|
2170
|
+
let scope = scopeCosts.get(el);
|
|
2171
|
+
if (scope === undefined) {
|
|
2172
|
+
scope = {
|
|
2173
|
+
name: event.nodeName,
|
|
2174
|
+
kind: event.nodeKind,
|
|
2175
|
+
runs: 0,
|
|
2176
|
+
selfMs: 0,
|
|
2177
|
+
wastedMs: 0,
|
|
2178
|
+
overlayMs: 0
|
|
2179
|
+
};
|
|
2180
|
+
scopeCosts.set(el, scope);
|
|
2181
|
+
}
|
|
2182
|
+
scope.runs++;
|
|
2183
|
+
scope.selfMs += event.selfMs;
|
|
2184
|
+
if (event.phase !== "plain") scope.overlayMs += event.selfMs;
|
|
2185
|
+
else if (!event.changed && !event.held) scope.wastedMs += event.selfMs;
|
|
2186
|
+
const roots = new Set();
|
|
2187
|
+
rootsOf(event.causes, roots);
|
|
2188
|
+
for (const name of roots) {
|
|
2189
|
+
let write = writeCosts.get(name);
|
|
2190
|
+
if (write === undefined) writeCosts.set(name, (write = { name, runs: 0, downstreamMs: 0 }));
|
|
2191
|
+
write.runs++;
|
|
2192
|
+
write.downstreamMs += event.selfMs;
|
|
2193
|
+
}
|
|
2194
|
+
}
|
|
2195
|
+
registerFold({
|
|
2196
|
+
rerun: recordCosts,
|
|
2197
|
+
reset() {
|
|
2198
|
+
scopeCosts.clear();
|
|
2199
|
+
writeCosts.clear();
|
|
2200
|
+
}
|
|
2201
|
+
});
|
|
2202
|
+
/**
|
|
2203
|
+
* Aggregated cost tables since `enable()`: `scopes` ranked by self-time
|
|
2204
|
+
* (with `wastedMs` = time spent on unchanged-value runs), `writes` ranked by
|
|
2205
|
+
* total downstream re-run time each root write caused.
|
|
2206
|
+
*/
|
|
2207
|
+
function costs() {
|
|
2208
|
+
return {
|
|
2209
|
+
scopes: [...scopeCosts.values()].sort((a, b) => b.selfMs - a.selfMs),
|
|
2210
|
+
writes: [...writeCosts.values()].sort((a, b) => b.downstreamMs - a.downstreamMs)
|
|
2211
|
+
};
|
|
2212
|
+
}
|
|
2213
|
+
|
|
2214
|
+
/**
|
|
2215
|
+
* `feedback()` — what the user waited on, as ranked tables. Folded from the
|
|
2216
|
+
* records the engine already keeps (holds, the interaction on each re-run,
|
|
2217
|
+
* navigations) and two censuses the engine reports as they happen (flights
|
|
2218
|
+
* started/landed/abandoned per async source; fallback shows per boundary).
|
|
2219
|
+
*
|
|
2220
|
+
* Its own module on purpose: the tables register with the engine's fold seam
|
|
2221
|
+
* when this module is evaluated, so an observe-tier consumer that only
|
|
2222
|
+
* subscribes to records never ships them. Reset with the engine on
|
|
2223
|
+
* `enable()`/`disable()`.
|
|
2224
|
+
*/
|
|
2225
|
+
const feedbackSources = new Map();
|
|
2226
|
+
const feedbackInteractions = new Map();
|
|
2227
|
+
const feedbackNavigations = new Map();
|
|
2228
|
+
const flightStats = new Map();
|
|
2229
|
+
const fallbackStats = new Map();
|
|
2230
|
+
const FALLBACK_FLASH_MS = 150;
|
|
2231
|
+
function flightBucket(el) {
|
|
2232
|
+
let row = flightStats.get(el);
|
|
2233
|
+
if (row === undefined) {
|
|
2234
|
+
row = { source: nodeName(el), flights: 0, landed: 0, abandoned: 0, landedMs: 0, worstMs: 0 };
|
|
2235
|
+
flightStats.set(el, row);
|
|
2236
|
+
}
|
|
2237
|
+
return row;
|
|
2238
|
+
}
|
|
2239
|
+
function trackFallback(boundary, tree, shown) {
|
|
2240
|
+
let bucket = fallbackStats.get(boundary);
|
|
2241
|
+
if (bucket === undefined) {
|
|
2242
|
+
bucket = {
|
|
2243
|
+
row: { boundary: "boundary", shows: 0, shownMs: 0, worstMs: 0, flashes: 0 },
|
|
2244
|
+
shownAt: null
|
|
2245
|
+
};
|
|
2246
|
+
fallbackStats.set(boundary, bucket);
|
|
2247
|
+
}
|
|
2248
|
+
// The first show can fire before the subtree exists; name on first sight.
|
|
2249
|
+
if (bucket.row.boundary === "boundary" && tree !== undefined) {
|
|
2250
|
+
const path = ownerPath(tree);
|
|
2251
|
+
if (path !== undefined) bucket.row.boundary = path.join(" › ");
|
|
2252
|
+
}
|
|
2253
|
+
if (shown) {
|
|
2254
|
+
if (bucket.shownAt === null) {
|
|
2255
|
+
bucket.shownAt = now();
|
|
2256
|
+
bucket.row.shows++;
|
|
2257
|
+
}
|
|
2258
|
+
return;
|
|
2259
|
+
}
|
|
2260
|
+
if (bucket.shownAt === null) return;
|
|
2261
|
+
const ms = now() - bucket.shownAt;
|
|
2262
|
+
bucket.shownAt = null;
|
|
2263
|
+
bucket.row.shownMs += ms;
|
|
2264
|
+
if (ms > bucket.row.worstMs) bucket.row.worstMs = ms;
|
|
2265
|
+
if (ms < FALLBACK_FLASH_MS) bucket.row.flashes++;
|
|
2266
|
+
}
|
|
2267
|
+
function interactionBucket(interaction) {
|
|
2268
|
+
const key = formatOrigin(interaction);
|
|
2269
|
+
let bucket = feedbackInteractions.get(key);
|
|
2270
|
+
if (bucket === undefined) {
|
|
2271
|
+
bucket = {
|
|
2272
|
+
row: {
|
|
2273
|
+
interaction: key,
|
|
2274
|
+
dispatches: 0,
|
|
2275
|
+
runs: 0,
|
|
2276
|
+
selfMs: 0,
|
|
2277
|
+
worstDispatchMs: 0,
|
|
2278
|
+
holds: 0,
|
|
2279
|
+
heldMs: 0,
|
|
2280
|
+
silentMs: 0,
|
|
2281
|
+
worstHoldMs: 0
|
|
2282
|
+
},
|
|
2283
|
+
dispatches: new Map()
|
|
2284
|
+
};
|
|
2285
|
+
feedbackInteractions.set(key, bucket);
|
|
2286
|
+
}
|
|
2287
|
+
const at = interaction.at ?? 0;
|
|
2288
|
+
if (!bucket.dispatches.has(at)) {
|
|
2289
|
+
bucket.dispatches.set(at, 0);
|
|
2290
|
+
bucket.row.dispatches++;
|
|
2291
|
+
}
|
|
2292
|
+
return bucket;
|
|
2293
|
+
}
|
|
2294
|
+
function recordFeedbackRun(event) {
|
|
2295
|
+
if (event.interaction === undefined) return;
|
|
2296
|
+
const bucket = interactionBucket(event.interaction);
|
|
2297
|
+
bucket.row.runs++;
|
|
2298
|
+
bucket.row.selfMs += event.selfMs;
|
|
2299
|
+
const at = event.interaction.at ?? 0;
|
|
2300
|
+
const dispatchMs = bucket.dispatches.get(at) + event.selfMs;
|
|
2301
|
+
bucket.dispatches.set(at, dispatchMs);
|
|
2302
|
+
if (dispatchMs > bucket.row.worstDispatchMs) bucket.row.worstDispatchMs = dispatchMs;
|
|
2303
|
+
}
|
|
2304
|
+
function recordFeedbackHold(event) {
|
|
2305
|
+
const sources = [...event.blockers].sort();
|
|
2306
|
+
const key = sources.join("\u0000");
|
|
2307
|
+
let bucket = feedbackSources.get(key);
|
|
2308
|
+
if (bucket === undefined) {
|
|
2309
|
+
bucket = {
|
|
2310
|
+
row: {
|
|
2311
|
+
sources,
|
|
2312
|
+
holds: 0,
|
|
2313
|
+
heldMs: 0,
|
|
2314
|
+
worstMs: 0,
|
|
2315
|
+
silent: 0,
|
|
2316
|
+
silentMs: 0,
|
|
2317
|
+
latestOnly: 0,
|
|
2318
|
+
long: 0,
|
|
2319
|
+
longMs: 0,
|
|
2320
|
+
acknowledgedBy: [],
|
|
2321
|
+
interactions: [],
|
|
2322
|
+
writes: [],
|
|
2323
|
+
actions: 0
|
|
2324
|
+
},
|
|
2325
|
+
acks: new Map(),
|
|
2326
|
+
interactions: new Map(),
|
|
2327
|
+
writes: new Set()
|
|
2328
|
+
};
|
|
2329
|
+
feedbackSources.set(key, bucket);
|
|
2330
|
+
}
|
|
2331
|
+
const row = bucket.row;
|
|
2332
|
+
const silent = isSilentHold(event);
|
|
2333
|
+
row.holds++;
|
|
2334
|
+
row.heldMs += event.holdMs;
|
|
2335
|
+
if (event.holdMs > row.worstMs) row.worstMs = event.holdMs;
|
|
2336
|
+
if (silent) {
|
|
2337
|
+
row.silent++;
|
|
2338
|
+
row.silentMs += event.holdMs;
|
|
2339
|
+
} else if (
|
|
2340
|
+
event.acknowledgements.length > 0 &&
|
|
2341
|
+
event.acknowledgements.every(a => a.kind === "latest")
|
|
2342
|
+
)
|
|
2343
|
+
row.latestOnly++;
|
|
2344
|
+
if (isLongHold(event)) {
|
|
2345
|
+
row.long++;
|
|
2346
|
+
row.longMs += event.tailMs;
|
|
2347
|
+
}
|
|
2348
|
+
if (event.action) row.actions++;
|
|
2349
|
+
for (const a of event.acknowledgements) {
|
|
2350
|
+
const by = `${a.kind}:${a.source}`;
|
|
2351
|
+
bucket.acks.set(by, (bucket.acks.get(by) ?? 0) + 1);
|
|
2352
|
+
}
|
|
2353
|
+
for (const w of event.heldWrites) bucket.writes.add(w.name);
|
|
2354
|
+
if (event.interaction !== undefined) {
|
|
2355
|
+
const key = formatOrigin(event.interaction);
|
|
2356
|
+
bucket.interactions.set(key, (bucket.interactions.get(key) ?? 0) + 1);
|
|
2357
|
+
const ib = interactionBucket(event.interaction);
|
|
2358
|
+
ib.row.holds++;
|
|
2359
|
+
ib.row.heldMs += event.holdMs;
|
|
2360
|
+
if (silent) ib.row.silentMs += event.holdMs;
|
|
2361
|
+
if (event.holdMs > ib.row.worstHoldMs) ib.row.worstHoldMs = event.holdMs;
|
|
2362
|
+
}
|
|
2363
|
+
}
|
|
2364
|
+
function recordFeedbackNavigation(event) {
|
|
2365
|
+
const name = event.name ?? event.to;
|
|
2366
|
+
if (name === undefined) return;
|
|
2367
|
+
let row = feedbackNavigations.get(name);
|
|
2368
|
+
if (row === undefined) {
|
|
2369
|
+
row = {
|
|
2370
|
+
name,
|
|
2371
|
+
navigations: 0,
|
|
2372
|
+
settledMs: 0,
|
|
2373
|
+
worstMs: 0,
|
|
2374
|
+
held: 0,
|
|
2375
|
+
heldMs: 0,
|
|
2376
|
+
silent: 0,
|
|
2377
|
+
superseded: 0,
|
|
2378
|
+
redirected: 0
|
|
2379
|
+
};
|
|
2380
|
+
feedbackNavigations.set(name, row);
|
|
2381
|
+
}
|
|
2382
|
+
row.navigations++;
|
|
2383
|
+
if (event.redirects !== undefined) row.redirected++;
|
|
2384
|
+
if (event.outcome === "superseded") {
|
|
2385
|
+
row.superseded++;
|
|
2386
|
+
return;
|
|
2387
|
+
}
|
|
2388
|
+
const ms = event.settledMs;
|
|
2389
|
+
row.settledMs += ms;
|
|
2390
|
+
if (ms > row.worstMs) row.worstMs = ms;
|
|
2391
|
+
if (event.outcome === "held") {
|
|
2392
|
+
row.held++;
|
|
2393
|
+
row.heldMs += event.hold?.holdMs ?? ms;
|
|
2394
|
+
if (event.hold !== undefined && isSilentHold(event.hold)) row.silent++;
|
|
2395
|
+
}
|
|
2396
|
+
}
|
|
2397
|
+
function rankedCounts(counts, key) {
|
|
2398
|
+
return [...counts].sort((a, b) => b[1] - a[1]).map(([name, holds]) => ({ [key]: name, holds }));
|
|
2399
|
+
}
|
|
2400
|
+
registerFold({
|
|
2401
|
+
rerun: (_el, event) => recordFeedbackRun(event),
|
|
2402
|
+
hold: recordFeedbackHold,
|
|
2403
|
+
navigation: recordFeedbackNavigation,
|
|
2404
|
+
flightStart(el, abandoned) {
|
|
2405
|
+
const stats = flightBucket(el);
|
|
2406
|
+
stats.flights++;
|
|
2407
|
+
if (abandoned) stats.abandoned++;
|
|
2408
|
+
},
|
|
2409
|
+
flightLanded(el, ms) {
|
|
2410
|
+
const stats = flightBucket(el);
|
|
2411
|
+
stats.landed++;
|
|
2412
|
+
stats.landedMs += ms;
|
|
2413
|
+
if (ms > stats.worstMs) stats.worstMs = ms;
|
|
2414
|
+
},
|
|
2415
|
+
fallback: trackFallback,
|
|
2416
|
+
reset() {
|
|
2417
|
+
feedbackSources.clear();
|
|
2418
|
+
feedbackInteractions.clear();
|
|
2419
|
+
feedbackNavigations.clear();
|
|
2420
|
+
flightStats.clear();
|
|
2421
|
+
fallbackStats.clear();
|
|
2422
|
+
}
|
|
2423
|
+
});
|
|
2424
|
+
/**
|
|
2425
|
+
* What the user waited on, folded from holds and the interaction on each
|
|
2426
|
+
* re-run: `sources` ranks async sources by the silent time writes spent held
|
|
2427
|
+
* behind them (with which affordances answered, how often, and which
|
|
2428
|
+
* interactions were held); `interactions` ranks user events by the total time
|
|
2429
|
+
* they cost — re-run work caused (long-flush hazard) beside time held
|
|
2430
|
+
* (silent-hold hazard). Facts at every duration; SILENT_HOLD is the
|
|
2431
|
+
* thresholded verdict. Three more tables round out the picture: `navigations`
|
|
2432
|
+
* ranks routes by the time spent held navigating to them (folded from settled
|
|
2433
|
+
* navigations), `flights` counts each async source's flights and how many
|
|
2434
|
+
* were abandoned before landing (the re-ask storm), and `fallbacks` measures
|
|
2435
|
+
* how long each loading boundary showed its fallback and how often that was a
|
|
2436
|
+
* flash.
|
|
2437
|
+
*/
|
|
2438
|
+
function feedback() {
|
|
2439
|
+
const navigations = [...feedbackNavigations.values()]
|
|
2440
|
+
.map(row => ({ ...row }))
|
|
2441
|
+
.sort((a, b) => b.heldMs - a.heldMs || b.settledMs - a.settledMs);
|
|
2442
|
+
const flights = [...flightStats.values()]
|
|
2443
|
+
.map(row => ({ ...row }))
|
|
2444
|
+
.sort((a, b) => b.abandoned - a.abandoned || b.flights - a.flights);
|
|
2445
|
+
const fallbacks = [...fallbackStats.values()]
|
|
2446
|
+
.map(bucket => ({ ...bucket.row }))
|
|
2447
|
+
.sort((a, b) => b.flashes - a.flashes || b.shownMs - a.shownMs);
|
|
2448
|
+
const sources = [...feedbackSources.values()]
|
|
2449
|
+
.map(bucket => ({
|
|
2450
|
+
...bucket.row,
|
|
2451
|
+
acknowledgedBy: rankedCounts(bucket.acks, "by"),
|
|
2452
|
+
interactions: rankedCounts(bucket.interactions, "interaction"),
|
|
2453
|
+
writes: [...bucket.writes]
|
|
2454
|
+
}))
|
|
2455
|
+
.sort((a, b) => b.silentMs - a.silentMs || b.heldMs - a.heldMs);
|
|
2456
|
+
// Ranked by the total time the user spent on it: held plus synchronous work.
|
|
2457
|
+
const interactions = [...feedbackInteractions.values()]
|
|
2458
|
+
.map(bucket => ({ ...bucket.row }))
|
|
2459
|
+
.sort((a, b) => b.heldMs + b.selfMs - (a.heldMs + a.selfMs));
|
|
2460
|
+
return { sources, interactions, navigations, flights, fallbacks };
|
|
2461
|
+
}
|
|
2462
|
+
|
|
2463
|
+
/**
|
|
2464
|
+
* Point queries over the engine's live state — the devtools/console view of
|
|
2465
|
+
* one scope. Their own module so a records-only consumer never ships them;
|
|
2466
|
+
* they read the engine's ring buffer and the graph, and register nothing.
|
|
2467
|
+
*/
|
|
2468
|
+
/** The node behind a memo/effect accessor, or the raw node passed through. */
|
|
2469
|
+
function nodeOf(target) {
|
|
2470
|
+
return target?.[$REFRESH] ?? target;
|
|
2471
|
+
}
|
|
2472
|
+
/** Re-run history for one node — pass a memo/effect accessor or raw node. */
|
|
2473
|
+
function why(target) {
|
|
2474
|
+
const node = nodeOf(target);
|
|
2475
|
+
return attribution.history().filter(event => subjectOf(event) === node);
|
|
2476
|
+
}
|
|
2477
|
+
/** Current dependency names of one scope — the devtools subscription view. */
|
|
2478
|
+
function subscriptions(target) {
|
|
2479
|
+
const node = nodeOf(target);
|
|
2480
|
+
const names = [];
|
|
2481
|
+
for (let l = node?._deps ?? null; l !== null; l = l._nextDep) names.push(nodeName(l._dep));
|
|
2482
|
+
return names;
|
|
2483
|
+
}
|
|
2484
|
+
|
|
2485
|
+
export { attribution, costs, feedback, formatOrigin, formatRerun, subscriptions, why };
|