@capybara-devtools/core 0.7.0 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/init.d.ts +5 -0
- package/dist/init.d.ts.map +1 -1
- package/dist/init.js +4 -0
- package/dist/init.js.map +1 -1
- package/dist/plugins/network/fetch.d.ts.map +1 -1
- package/dist/plugins/network/fetch.js +1 -0
- package/dist/plugins/network/fetch.js.map +1 -1
- package/dist/plugins/network/settings.d.ts +4 -0
- package/dist/plugins/network/settings.d.ts.map +1 -1
- package/dist/plugins/network/settings.js.map +1 -1
- package/dist/plugins/network/timing.d.ts +9 -0
- package/dist/plugins/network/timing.d.ts.map +1 -0
- package/dist/plugins/network/timing.js +79 -0
- package/dist/plugins/network/timing.js.map +1 -0
- package/dist/plugins/network/xhr.d.ts.map +1 -1
- package/dist/plugins/network/xhr.js +1 -0
- package/dist/plugins/network/xhr.js.map +1 -1
- package/dist/plugins/network.d.ts.map +1 -1
- package/dist/plugins/network.js +4 -1
- package/dist/plugins/network.js.map +1 -1
- package/dist/plugins/performance/index.d.ts +41 -0
- package/dist/plugins/performance/index.d.ts.map +1 -0
- package/dist/plugins/performance/index.js +215 -0
- package/dist/plugins/performance/index.js.map +1 -0
- package/dist/plugins/performance/observe.d.ts +42 -0
- package/dist/plugins/performance/observe.d.ts.map +1 -0
- package/dist/plugins/performance/observe.js +1280 -0
- package/dist/plugins/performance/observe.js.map +1 -0
- package/dist/plugins/performance/profile.d.ts +50 -0
- package/dist/plugins/performance/profile.d.ts.map +1 -0
- package/dist/plugins/performance/profile.js +196 -0
- package/dist/plugins/performance/profile.js.map +1 -0
- package/dist/plugins/performance/renders.d.ts +13 -0
- package/dist/plugins/performance/renders.d.ts.map +1 -0
- package/dist/plugins/performance/renders.js +144 -0
- package/dist/plugins/performance/renders.js.map +1 -0
- package/package.json +2 -2
- package/src/index.ts +2 -0
- package/src/init.ts +8 -0
- package/src/plugins/network/fetch.ts +1 -0
- package/src/plugins/network/settings.ts +4 -0
- package/src/plugins/network/timing.ts +82 -0
- package/src/plugins/network/xhr.ts +1 -0
- package/src/plugins/network.ts +3 -1
- package/src/plugins/performance/index.ts +243 -0
- package/src/plugins/performance/observe.ts +1291 -0
- package/src/plugins/performance/profile.ts +232 -0
- package/src/plugins/performance/renders.ts +152 -0
|
@@ -0,0 +1,1280 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Observes the page's performance entries and Web Vitals and emits them as `perf.*` events, in batches once a
|
|
3
|
+
* second. Callbacks only file entries; what costs (selectors, payloads) waits for the batch, so measuring adds as
|
|
4
|
+
* little as it can to the interactions it measures. Self-contained: Capybara also injects it into pages without the
|
|
5
|
+
* SDK through `toString()`, so it must not reference anything outside its own body.
|
|
6
|
+
*/
|
|
7
|
+
export function observePerformance(emit, isConnected, options) {
|
|
8
|
+
// As in @capybara-devtools/protocol (PERF_MAX_*), which this function cannot import.
|
|
9
|
+
const MAX_SCRIPTS = 10;
|
|
10
|
+
const MAX_URL = 512;
|
|
11
|
+
const MAX_RESOURCES = 100;
|
|
12
|
+
const MAX_DETAIL = 1_024;
|
|
13
|
+
const FLUSH_MS = 1_000;
|
|
14
|
+
/** Sent per batch; the rest are counted as skipped. */
|
|
15
|
+
const PER_BATCH = { interactions: 20, frames: 10, shifts: 20, timings: 100 };
|
|
16
|
+
/** Held while Capybara is not connected yet, oldest dropped first. */
|
|
17
|
+
const WAITING = { resources: 2_000, other: 200 };
|
|
18
|
+
/** Interactions remembered, so late entries of one still join it. */
|
|
19
|
+
const REMEMBERED = 200;
|
|
20
|
+
/** An interaction this slow keeps the long frames during it, past the batch's limit. */
|
|
21
|
+
const SLOW = 200;
|
|
22
|
+
/** Likely causes of a layout shift: at most this many, looked for at most this often a second. */
|
|
23
|
+
const MAX_CAUSES = 3;
|
|
24
|
+
const CAUSE_LOOKS = 5;
|
|
25
|
+
/** Shifts at most this far apart that move the same elements are one run. */
|
|
26
|
+
const RUN_GAP_MS = 100;
|
|
27
|
+
/** Reading the page after load: images read, and time it may take, before it stops. */
|
|
28
|
+
const PAGE_IMAGES = 300;
|
|
29
|
+
const PAGE_BUDGET_MS = 5;
|
|
30
|
+
const MAX_PAGE_IMAGES = 10;
|
|
31
|
+
const MAX_PAGE_FONTS = 20;
|
|
32
|
+
const INSPECT_EVERY_MS = 10_000;
|
|
33
|
+
const MAX_NOT_RESTORED = 10;
|
|
34
|
+
const scope = globalThis;
|
|
35
|
+
const perf = scope.performance;
|
|
36
|
+
const Observer = scope.PerformanceObserver;
|
|
37
|
+
if (!perf || typeof Observer !== 'function')
|
|
38
|
+
return () => { };
|
|
39
|
+
const supported = Array.isArray(Observer.supportedEntryTypes) ? Observer.supportedEntryTypes : [];
|
|
40
|
+
const round = (value) => Math.round(value * 10) / 10;
|
|
41
|
+
const cutUrl = (url) => (url.length > MAX_URL ? url.slice(0, MAX_URL) : url);
|
|
42
|
+
const ignored = options.ignore.map((pattern) => new RegExp(pattern.source, pattern.flags));
|
|
43
|
+
const isIgnored = (url) => ignored.some((pattern) => {
|
|
44
|
+
pattern.lastIndex = 0;
|
|
45
|
+
return pattern.test(url);
|
|
46
|
+
});
|
|
47
|
+
const pageOrigin = scope.location?.origin;
|
|
48
|
+
// ---------------------------------------------------------------------------
|
|
49
|
+
// Elements
|
|
50
|
+
// ---------------------------------------------------------------------------
|
|
51
|
+
const escapeIdent = (value) => typeof scope.CSS?.escape === 'function' ? scope.CSS.escape(value) : value.replace(/[^\w-]/g, (c) => `\\${c}`);
|
|
52
|
+
/** Ids a library made up (React's useId, Radix, Headless UI, MUI): they change between runs and name nothing. */
|
|
53
|
+
const GENERATED_ID = /^(?:radix-|headlessui-|mui-|react-aria|rc[-_])|[:«»]|_r_\w*_?$|\d{4,}/i;
|
|
54
|
+
/** Siblings past which an element's place is told by `:nth-child`. */
|
|
55
|
+
const LONG_LIST = 100;
|
|
56
|
+
/** Up to four levels, up to an id, with `:nth-of-type` where siblings share the tag, so it finds the element again. */
|
|
57
|
+
const selectorOf = (node) => {
|
|
58
|
+
let element = node && node.nodeType === 1 ? node : (node?.parentElement ?? null);
|
|
59
|
+
const parts = [];
|
|
60
|
+
while (element && element.nodeType === 1 && parts.length < 4) {
|
|
61
|
+
const tag = String(element.localName || element.nodeName || '').toLowerCase();
|
|
62
|
+
if (!tag)
|
|
63
|
+
break;
|
|
64
|
+
if (tag === 'html' || tag === 'body') {
|
|
65
|
+
// A press on the page itself, outside every element (beside an open menu), still has a target.
|
|
66
|
+
if (parts.length === 0)
|
|
67
|
+
parts.push(tag);
|
|
68
|
+
break;
|
|
69
|
+
}
|
|
70
|
+
if (element.id && !GENERATED_ID.test(element.id)) {
|
|
71
|
+
parts.unshift(`${tag}#${escapeIdent(element.id)}`);
|
|
72
|
+
break;
|
|
73
|
+
}
|
|
74
|
+
let part = tag;
|
|
75
|
+
// Utility classes such as Tailwind's `md:flex` would need escaping and say little.
|
|
76
|
+
const classes = [...(element.classList ?? [])].filter((name) => /^[a-zA-Z_][\w-]*$/.test(name)).slice(0, 2);
|
|
77
|
+
if (classes.length > 0)
|
|
78
|
+
part += `.${classes.join('.')}`;
|
|
79
|
+
const parent = element.parentElement;
|
|
80
|
+
if (parent && parent.children.length > LONG_LIST) {
|
|
81
|
+
// A long list's rows: the browser finds the place natively, where a loop over thousands of rows in script
|
|
82
|
+
// costs a frame.
|
|
83
|
+
part += `:nth-child(${Array.prototype.indexOf.call(parent.children, element) + 1})`;
|
|
84
|
+
}
|
|
85
|
+
else if (parent) {
|
|
86
|
+
let same = 0;
|
|
87
|
+
let index = 0;
|
|
88
|
+
for (const child of parent.children) {
|
|
89
|
+
if (child.localName !== element.localName)
|
|
90
|
+
continue;
|
|
91
|
+
same++;
|
|
92
|
+
if (child === element)
|
|
93
|
+
index = same;
|
|
94
|
+
}
|
|
95
|
+
if (same > 1)
|
|
96
|
+
part += `:nth-of-type(${index})`;
|
|
97
|
+
}
|
|
98
|
+
parts.unshift(part);
|
|
99
|
+
element = parent;
|
|
100
|
+
}
|
|
101
|
+
return parts.length > 0 ? parts.join(' > ').slice(0, 160) : undefined;
|
|
102
|
+
};
|
|
103
|
+
const clip = (text) => {
|
|
104
|
+
const trimmed = String(text ?? '')
|
|
105
|
+
.replace(/\s+/g, ' ')
|
|
106
|
+
.trim();
|
|
107
|
+
return trimmed ? (trimmed.length > 40 ? `${trimmed.slice(0, 39)}…` : trimmed) : undefined;
|
|
108
|
+
};
|
|
109
|
+
const FIELD = /^(?:input|textarea|select)$/;
|
|
110
|
+
/**
|
|
111
|
+
* What a person presses: a click lands on the text or icon inside it. Also the only elements whose text is read:
|
|
112
|
+
* other elements' text, and what is typed into fields, can be personal.
|
|
113
|
+
*/
|
|
114
|
+
const CONTROL = 'button, a, summary, label, input, select, textarea, [role="button"], [role="link"], [role="tab"], [role="menuitem"], [role="menuitemradio"], [role="menuitemcheckbox"], [role="option"], [role="switch"], [role="checkbox"], [role="radio"], [role="treeitem"]';
|
|
115
|
+
/** An element's text, its parts a space apart, without what a field inside it holds (a textarea's text). */
|
|
116
|
+
const ownText = (root) => {
|
|
117
|
+
let text = '';
|
|
118
|
+
const walk = (node) => {
|
|
119
|
+
for (const child of node.childNodes ?? []) {
|
|
120
|
+
// A label's worth is all that is kept.
|
|
121
|
+
if (text.length > 120)
|
|
122
|
+
return;
|
|
123
|
+
if (child.nodeType === 3)
|
|
124
|
+
text += ` ${child.nodeValue}`;
|
|
125
|
+
else if (child.nodeType === 1 && !FIELD.test(child.localName))
|
|
126
|
+
walk(child);
|
|
127
|
+
}
|
|
128
|
+
};
|
|
129
|
+
walk(root);
|
|
130
|
+
return text;
|
|
131
|
+
};
|
|
132
|
+
const textOf = (element) => {
|
|
133
|
+
if (!element?.closest)
|
|
134
|
+
return undefined;
|
|
135
|
+
if (FIELD.test(element.localName)) {
|
|
136
|
+
if (/^(?:submit|button|reset)$/i.test(element.type ?? ''))
|
|
137
|
+
return clip(element.value);
|
|
138
|
+
// The field's label, never what is in it.
|
|
139
|
+
const label = element.labels?.[0];
|
|
140
|
+
return clip(element.getAttribute('aria-label')) ?? (label ? clip(ownText(label)) : undefined) ?? clip(element.getAttribute('placeholder'));
|
|
141
|
+
}
|
|
142
|
+
const control = element.closest(CONTROL);
|
|
143
|
+
if (!control)
|
|
144
|
+
return undefined;
|
|
145
|
+
// An icon button has no text of its own.
|
|
146
|
+
return clip(control.getAttribute('aria-label')) ?? clip(ownText(control)) ?? clip(control.querySelector?.('img[alt]')?.getAttribute('alt')) ?? clip(control.getAttribute('title'));
|
|
147
|
+
};
|
|
148
|
+
// One gesture fires several events, the first often pointerdown: look for the handler of the whole gesture,
|
|
149
|
+
// the one people write first.
|
|
150
|
+
const POINTER = ['onClick', 'onPointerDown', 'onPointerUp', 'onMouseDown', 'onMouseUp', 'onTouchStart', 'onTouchEnd', 'onClickCapture'];
|
|
151
|
+
const KEYBOARD = ['onKeyDown', 'onChange', 'onInput', 'onKeyUp', 'onKeyPress', 'onBeforeInput'];
|
|
152
|
+
const HANDLERS = {
|
|
153
|
+
click: POINTER,
|
|
154
|
+
pointerdown: POINTER,
|
|
155
|
+
pointerup: POINTER,
|
|
156
|
+
mousedown: POINTER,
|
|
157
|
+
mouseup: POINTER,
|
|
158
|
+
auxclick: ['onAuxClick', ...POINTER],
|
|
159
|
+
contextmenu: ['onContextMenu', ...POINTER],
|
|
160
|
+
keydown: KEYBOARD,
|
|
161
|
+
keyup: KEYBOARD,
|
|
162
|
+
keypress: KEYBOARD,
|
|
163
|
+
input: KEYBOARD,
|
|
164
|
+
beforeinput: KEYBOARD,
|
|
165
|
+
};
|
|
166
|
+
/** Function, class, forwardRef and memo components. */
|
|
167
|
+
const COMPONENTS = [0, 1, 11, 14, 15];
|
|
168
|
+
const HOST = 5;
|
|
169
|
+
const fiberOf = (element) => {
|
|
170
|
+
// Own keys only: `for in` would go through the hundreds of properties an element inherits when React put
|
|
171
|
+
// none on it. React 17 and later; 16 used `__reactInternalInstance$`.
|
|
172
|
+
for (const key of Object.keys(element)) {
|
|
173
|
+
if (key.startsWith('__reactFiber$') || key.startsWith('__reactInternalInstance$'))
|
|
174
|
+
return element[key];
|
|
175
|
+
}
|
|
176
|
+
return undefined;
|
|
177
|
+
};
|
|
178
|
+
const componentName = (fiber) => {
|
|
179
|
+
const kind = fiber?.type;
|
|
180
|
+
if (!kind || typeof kind === 'string')
|
|
181
|
+
return undefined;
|
|
182
|
+
return kind.displayName || kind.name || kind.render?.displayName || kind.render?.name || kind.type?.displayName || kind.type?.name || undefined;
|
|
183
|
+
};
|
|
184
|
+
/** The component whose render wrote this fiber's element; a development build's. Server components' are not fibers. */
|
|
185
|
+
const ownerOf = (fiber) => (typeof fiber?._debugOwner?.tag === 'number' ? fiber._debugOwner : undefined);
|
|
186
|
+
/** Whether `fiber` is all that `owner` renders. Either may be the other copy React keeps of the same fiber. */
|
|
187
|
+
const rendersOnly = (owner, fiber) => {
|
|
188
|
+
const child = owner.child ?? owner.alternate?.child;
|
|
189
|
+
return Boolean(child) && (child === fiber || child === fiber.alternate) && !child.sibling;
|
|
190
|
+
};
|
|
191
|
+
const renderedOf = (element, type) => {
|
|
192
|
+
if (!options.react || !element || typeof element !== 'object')
|
|
193
|
+
return undefined;
|
|
194
|
+
const first = fiberOf(element);
|
|
195
|
+
if (!first)
|
|
196
|
+
return undefined;
|
|
197
|
+
// Shifted elements ran no handler; only their component is looked for.
|
|
198
|
+
const names = HANDLERS[type] ?? [];
|
|
199
|
+
let handler;
|
|
200
|
+
let prop;
|
|
201
|
+
let host;
|
|
202
|
+
let nearest;
|
|
203
|
+
for (let fiber = first, depth = 0; fiber && depth < 60 && !((handler || names.length === 0) && nearest); depth++, fiber = fiber.return) {
|
|
204
|
+
if (!handler && fiber.tag === HOST) {
|
|
205
|
+
const props = fiber.memoizedProps;
|
|
206
|
+
for (const name of names) {
|
|
207
|
+
if (typeof props?.[name] !== 'function')
|
|
208
|
+
continue;
|
|
209
|
+
handler = props[name];
|
|
210
|
+
prop = name;
|
|
211
|
+
host = fiber;
|
|
212
|
+
break;
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
else if (!nearest && COMPONENTS.includes(fiber.tag)) {
|
|
216
|
+
nearest = fiber;
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
const chain = [];
|
|
220
|
+
for (let fiber = host ?? first; fiber && chain.length < 30;) {
|
|
221
|
+
const owner = ownerOf(fiber);
|
|
222
|
+
chain.push({ fiber, props: fiber.memoizedProps, only: owner !== undefined && rendersOnly(owner, fiber) });
|
|
223
|
+
fiber = owner;
|
|
224
|
+
}
|
|
225
|
+
return { handler, prop, chain, nearest };
|
|
226
|
+
};
|
|
227
|
+
/** The frames between where React records an element and the code that wrote it. */
|
|
228
|
+
const JSX_RUNTIME = /(?:^|[.\s])(?:jsxDEV|jsxs?|jsxDEVImpl|createElement|cloneElement)$/;
|
|
229
|
+
/** A function's name in a stack frame, without what engines put around it; a class component's is its `render`. */
|
|
230
|
+
const frameName = (name) => {
|
|
231
|
+
const plain = name.replace(/^(?:async |new )/, '').replace(/^(?:Object|Module)\./, '').replace(/\.render$/, '');
|
|
232
|
+
return /^[A-Za-z_$][\w$]*$/.test(plain) ? plain : undefined;
|
|
233
|
+
};
|
|
234
|
+
/**
|
|
235
|
+
* Where a fiber's element was written, and by which component. React's development builds keep it: 19 as the
|
|
236
|
+
* stack of the element's creation, with positions in the scripts as served; 18 as the source file and line.
|
|
237
|
+
*/
|
|
238
|
+
const writtenAt = (fiber) => {
|
|
239
|
+
const source = fiber?._debugSource;
|
|
240
|
+
if (source && typeof source.fileName === 'string' && source.lineNumber > 0) {
|
|
241
|
+
return { place: { file: source.fileName, line: source.lineNumber, column: source.columnNumber > 0 ? source.columnNumber : 1 } };
|
|
242
|
+
}
|
|
243
|
+
const stack = fiber?._debugStack?.stack;
|
|
244
|
+
if (typeof stack !== 'string')
|
|
245
|
+
return undefined;
|
|
246
|
+
let place;
|
|
247
|
+
let last;
|
|
248
|
+
let top = true;
|
|
249
|
+
for (const line of stack.split('\n').slice(0, 14)) {
|
|
250
|
+
// Chrome: `at name (url:1:2)` or `at url:1:2`. Safari and Firefox: `name@url:1:2`.
|
|
251
|
+
const frame = /^\s*at (?:(.*?) \()?(\S+?):(\d+):(\d+)\)?$/.exec(line) ?? /^(.*?)@(\S+?):(\d+):(\d+)$/.exec(line);
|
|
252
|
+
if (!frame)
|
|
253
|
+
continue;
|
|
254
|
+
const name = frame[1] ?? '';
|
|
255
|
+
// React calls a component's render from this frame: the one before it is the component. With no frame
|
|
256
|
+
// before it React made the element itself, or the component returned it in a tail call, whose frame Safari
|
|
257
|
+
// drops: then nothing says where it was written.
|
|
258
|
+
if (/react[_-]stack[_-]bottom[_-]frame/.test(name))
|
|
259
|
+
return place && { place, by: last };
|
|
260
|
+
// The top frame is the JSX function that made the record. Chrome names it; Safari gives it no name.
|
|
261
|
+
const runtime = !place && (JSX_RUNTIME.test(name) || (top && name === '' && PACKAGE_URL.test(frame[2])));
|
|
262
|
+
top = false;
|
|
263
|
+
if (runtime)
|
|
264
|
+
continue;
|
|
265
|
+
place ??= { url: cutUrl(frame[2]), line: Number(frame[3]), column: Number(frame[4]) };
|
|
266
|
+
last = frameName(name);
|
|
267
|
+
}
|
|
268
|
+
// Written outside a render, or deeper in calls than the stack React keeps.
|
|
269
|
+
return place && { place };
|
|
270
|
+
};
|
|
271
|
+
/** The name of the function a component is, which stacks have; `componentName` prefers the name it was given to show. */
|
|
272
|
+
const functionName = (fiber) => {
|
|
273
|
+
const kind = fiber?.type;
|
|
274
|
+
return (typeof kind === 'function' ? kind.name : kind?.render?.name || kind?.type?.name) || undefined;
|
|
275
|
+
};
|
|
276
|
+
/**
|
|
277
|
+
* Packages as dev servers serve them: under node_modules (Vite, webpack), in chunks named after it (Turbopack,
|
|
278
|
+
* which cuts long names down to `…next_dist_…`), and the dev server's own modules.
|
|
279
|
+
*/
|
|
280
|
+
const PACKAGE_URL = /node_modules|next_dist_|turbopack|\/@(?:vite|react-refresh|id)\//i;
|
|
281
|
+
/**
|
|
282
|
+
* Whether a place is in a package rather than in the app's own code. A chunk named by a hash alone can hold
|
|
283
|
+
* either, so whoever shows the place checks again where it maps to.
|
|
284
|
+
*/
|
|
285
|
+
const inPackage = (place) => ('file' in place ? /[\\/]node_modules[\\/]/.test(place.file) : PACKAGE_URL.test(place.url));
|
|
286
|
+
/** A place whose source file the server can find: a file already, or a script of the page's own dev server. */
|
|
287
|
+
const findable = (place) => 'file' in place || place.url.startsWith(`${pageOrigin}/`);
|
|
288
|
+
const hands = (props, handler) => props !== null && typeof props === 'object' && Object.values(props).includes(handler);
|
|
289
|
+
/**
|
|
290
|
+
* The names and the place of what was taken from React. Development builds of React know who wrote each element,
|
|
291
|
+
* which tells the app's code from a package's: a UI library's button is written by the library's component and
|
|
292
|
+
* runs the library's handler, and neither says where in the app to look.
|
|
293
|
+
*/
|
|
294
|
+
const describe = (rendered, pressed = true) => {
|
|
295
|
+
const found = {};
|
|
296
|
+
if (!rendered)
|
|
297
|
+
return found;
|
|
298
|
+
const { chain } = rendered;
|
|
299
|
+
const nearest = componentName(rendered.nearest);
|
|
300
|
+
if (nearest)
|
|
301
|
+
found.component = nearest;
|
|
302
|
+
/**
|
|
303
|
+
* The component whose code a place is in: the one that wrote `chain[index]`, which is the next of the chain,
|
|
304
|
+
* unless the stack names another. It does for an element a package cloned (Radix's `asChild`): React then
|
|
305
|
+
* takes the package's component for its owner, though the app wrote it.
|
|
306
|
+
*/
|
|
307
|
+
const authorOf = (index, by) => {
|
|
308
|
+
const owner = chain[index + 1]?.fiber;
|
|
309
|
+
if (by && by !== functionName(owner))
|
|
310
|
+
return { name: by, owner: false };
|
|
311
|
+
return { name: componentName(owner) ?? by, owner: owner !== undefined };
|
|
312
|
+
};
|
|
313
|
+
const settle = (name, place) => {
|
|
314
|
+
if (name)
|
|
315
|
+
found.component = name;
|
|
316
|
+
if (findable(place))
|
|
317
|
+
found.source = place;
|
|
318
|
+
};
|
|
319
|
+
let { handler } = rendered;
|
|
320
|
+
if (handler && chain.length > 0) {
|
|
321
|
+
// The handler was written where the highest component that was handed it is used. A component hands the
|
|
322
|
+
// same function on, or, when the element is all it renders, wraps the one it was given under the same prop.
|
|
323
|
+
let at = 0;
|
|
324
|
+
for (; at + 1 < chain.length && at < 12; at++) {
|
|
325
|
+
const props = chain[at + 1].props;
|
|
326
|
+
if (hands(props, handler))
|
|
327
|
+
continue;
|
|
328
|
+
const given = chain[at].only && rendered.prop ? props?.[rendered.prop] : undefined;
|
|
329
|
+
if (typeof given !== 'function')
|
|
330
|
+
break;
|
|
331
|
+
handler = given;
|
|
332
|
+
}
|
|
333
|
+
found.handler = handler.name || 'anonymous';
|
|
334
|
+
const written = writtenAt(chain[at].fiber);
|
|
335
|
+
// Nothing tells whose code it is: a production build, or a React that keeps no such record.
|
|
336
|
+
if (!written)
|
|
337
|
+
return found;
|
|
338
|
+
if (!inPackage(written.place)) {
|
|
339
|
+
settle(authorOf(at, written.by).name, written.place);
|
|
340
|
+
return found;
|
|
341
|
+
}
|
|
342
|
+
// A package's own handler (a menu's trigger, a router's link) says nothing about the app.
|
|
343
|
+
delete found.handler;
|
|
344
|
+
}
|
|
345
|
+
// Else the first place in the app's own code, going up through who wrote what.
|
|
346
|
+
for (let index = 0; index < chain.length; index++) {
|
|
347
|
+
let written = writtenAt(chain[index].fiber);
|
|
348
|
+
if (!written || inPackage(written.place))
|
|
349
|
+
continue;
|
|
350
|
+
let author = authorOf(index, written.by);
|
|
351
|
+
// A component that renders nothing but this, as the app's own wrapper around a UI kit's control, names less
|
|
352
|
+
// than the component that uses it. Not for an element that painted or moved: that one is changed where it
|
|
353
|
+
// is written.
|
|
354
|
+
for (let hops = 0; pressed && hops < 4 && author.owner && chain[index].only; hops++) {
|
|
355
|
+
const above = writtenAt(chain[index + 1].fiber);
|
|
356
|
+
if (!above || inPackage(above.place))
|
|
357
|
+
break;
|
|
358
|
+
index++;
|
|
359
|
+
written = above;
|
|
360
|
+
author = authorOf(index, written.by);
|
|
361
|
+
}
|
|
362
|
+
settle(author.name, written.place);
|
|
363
|
+
break;
|
|
364
|
+
}
|
|
365
|
+
return found;
|
|
366
|
+
};
|
|
367
|
+
const elementOf = (node) => (node?.nodeType === 1 ? node : node?.parentElement);
|
|
368
|
+
/** An interaction is named by the control, not by the text or icon inside it that the pointer hit. */
|
|
369
|
+
const controlOf = (node) => {
|
|
370
|
+
const element = elementOf(node);
|
|
371
|
+
return element?.closest?.(CONTROL) ?? element;
|
|
372
|
+
};
|
|
373
|
+
/**
|
|
374
|
+
* Whether the page gave an image, video or iframe its size, so it has its room before it loads: width and height
|
|
375
|
+
* attributes (which become a ratio, `auto 300 / 200`), an `aspect-ratio`, or both sizes inline. A size set by a
|
|
376
|
+
* stylesheet class reads as none.
|
|
377
|
+
*/
|
|
378
|
+
const hasSize = (element) => {
|
|
379
|
+
if (element.hasAttribute?.('width') && element.hasAttribute?.('height'))
|
|
380
|
+
return true;
|
|
381
|
+
if (element.style?.width && element.style?.height)
|
|
382
|
+
return true;
|
|
383
|
+
// Last, as it can make the browser work out styles: an aspect-ratio from a stylesheet.
|
|
384
|
+
try {
|
|
385
|
+
return scope.getComputedStyle(element).aspectRatio !== 'auto';
|
|
386
|
+
}
|
|
387
|
+
catch {
|
|
388
|
+
return true;
|
|
389
|
+
}
|
|
390
|
+
};
|
|
391
|
+
const lazyOf = (element) => String(element.loading || element.getAttribute?.('loading') || '').toLowerCase() === 'lazy';
|
|
392
|
+
/** `rendered` is what was taken from React when the element was pressed; without it, React is read now. */
|
|
393
|
+
const targetOf = (node, type, rendered) => {
|
|
394
|
+
const hit = elementOf(node);
|
|
395
|
+
const element = type === 'shift' ? hit : controlOf(hit);
|
|
396
|
+
const selector = selectorOf(element);
|
|
397
|
+
if (!selector)
|
|
398
|
+
return undefined;
|
|
399
|
+
// A handler can sit on an element inside the control, so React is read from what was hit.
|
|
400
|
+
const target = { selector, ...describe(rendered ?? renderedOf(hit, type), type !== 'shift') };
|
|
401
|
+
const text = textOf(element);
|
|
402
|
+
if (text)
|
|
403
|
+
target.text = text;
|
|
404
|
+
return target;
|
|
405
|
+
};
|
|
406
|
+
/** Events kept per interaction, the longest ones: a key held down repeats. */
|
|
407
|
+
const MAX_EVENTS = 8;
|
|
408
|
+
/** Which event names an interaction: what it is to the person, over what began it. */
|
|
409
|
+
const RANK = { click: 6, keydown: 5, pointerup: 4, keyup: 3, pointerdown: 2, input: 1 };
|
|
410
|
+
let stopped = false;
|
|
411
|
+
let timer;
|
|
412
|
+
let sentNavigation = false;
|
|
413
|
+
let restoreId = 0;
|
|
414
|
+
let restored = 0;
|
|
415
|
+
/** The navigation the page is in now, which what it is made of belongs to. */
|
|
416
|
+
let current = 0;
|
|
417
|
+
let page;
|
|
418
|
+
const interactions = new Map();
|
|
419
|
+
const navigations = [];
|
|
420
|
+
const metrics = new Map();
|
|
421
|
+
let shifts = [];
|
|
422
|
+
let frames = [];
|
|
423
|
+
let timings = [];
|
|
424
|
+
let resources = [];
|
|
425
|
+
const skipped = { interactions: 0, frames: 0, shifts: 0, timings: 0, resources: 0, presses: 0 };
|
|
426
|
+
const observers = [];
|
|
427
|
+
const schedule = () => {
|
|
428
|
+
if (!stopped && timer === undefined)
|
|
429
|
+
timer = setTimeout(flush, FLUSH_MS);
|
|
430
|
+
};
|
|
431
|
+
const observe = (type, handle, extra = {}) => {
|
|
432
|
+
if (!supported.includes(type))
|
|
433
|
+
return;
|
|
434
|
+
try {
|
|
435
|
+
const observer = new Observer((list) => {
|
|
436
|
+
if (stopped)
|
|
437
|
+
return;
|
|
438
|
+
try {
|
|
439
|
+
handle(list.getEntries());
|
|
440
|
+
schedule();
|
|
441
|
+
}
|
|
442
|
+
catch {
|
|
443
|
+
// never surface SDK failures to the app
|
|
444
|
+
}
|
|
445
|
+
});
|
|
446
|
+
observer.observe({ type, buffered: true, ...extra });
|
|
447
|
+
observers.push(observer);
|
|
448
|
+
}
|
|
449
|
+
catch {
|
|
450
|
+
// an entry type the browser lists but refuses
|
|
451
|
+
}
|
|
452
|
+
};
|
|
453
|
+
const pressed = [];
|
|
454
|
+
const PRESSES = ['pointerdown', 'pointerup', 'click', 'keydown', 'keyup'];
|
|
455
|
+
const MAX_PRESSES = 24;
|
|
456
|
+
/** Longer than an interaction takes to be reported, which is once its frame is painted. */
|
|
457
|
+
const KEEP_PRESS_MS = 10_000;
|
|
458
|
+
let sweep;
|
|
459
|
+
/** Lets go of the elements, so that what a press took off the page can be collected. */
|
|
460
|
+
const forget = () => {
|
|
461
|
+
sweep = undefined;
|
|
462
|
+
const stale = perf.now() - KEEP_PRESS_MS;
|
|
463
|
+
while (pressed.length > 0 && pressed[0].time < stale)
|
|
464
|
+
pressed.shift();
|
|
465
|
+
if (pressed.length > 0 && !stopped)
|
|
466
|
+
sweep = setTimeout(forget, KEEP_PRESS_MS);
|
|
467
|
+
};
|
|
468
|
+
/** Presses to send, a press by where it began: the browser times none under 16 ms, a baseline needs them all. */
|
|
469
|
+
let starts = [];
|
|
470
|
+
const remember = (event) => {
|
|
471
|
+
if (stopped)
|
|
472
|
+
return;
|
|
473
|
+
try {
|
|
474
|
+
const target = event.target;
|
|
475
|
+
const last = pressed[pressed.length - 1];
|
|
476
|
+
// The events of one press hit the same element and look for the same handlers.
|
|
477
|
+
const same = last !== undefined && last.target === target && HANDLERS[last.type] === HANDLERS[event.type];
|
|
478
|
+
const press = { type: event.type, time: event.timeStamp, target, rendered: same ? last.rendered : renderedOf(elementOf(target), event.type) };
|
|
479
|
+
pressed.push(press);
|
|
480
|
+
if (pressed.length > MAX_PRESSES)
|
|
481
|
+
pressed.shift();
|
|
482
|
+
if (sweep === undefined)
|
|
483
|
+
sweep = setTimeout(forget, KEEP_PRESS_MS);
|
|
484
|
+
if ((event.type === 'pointerdown' || event.type === 'keydown') && !event.repeat) {
|
|
485
|
+
starts.push(press);
|
|
486
|
+
if (starts.length > WAITING.other) {
|
|
487
|
+
skipped.presses += starts.length - WAITING.other;
|
|
488
|
+
starts = starts.slice(-WAITING.other);
|
|
489
|
+
}
|
|
490
|
+
schedule();
|
|
491
|
+
}
|
|
492
|
+
}
|
|
493
|
+
catch {
|
|
494
|
+
// never surface SDK failures to the app
|
|
495
|
+
}
|
|
496
|
+
};
|
|
497
|
+
for (const name of PRESSES)
|
|
498
|
+
scope.addEventListener?.(name, remember, { capture: true, passive: true });
|
|
499
|
+
/** An entry starts at its event's time stamp. */
|
|
500
|
+
const pressedAt = (type, time) => {
|
|
501
|
+
for (let index = pressed.length - 1; index >= 0; index--) {
|
|
502
|
+
const press = pressed[index];
|
|
503
|
+
if (press.type === type && Math.abs(press.time - time) < 2)
|
|
504
|
+
return press;
|
|
505
|
+
}
|
|
506
|
+
return undefined;
|
|
507
|
+
};
|
|
508
|
+
observe('event', (entries) => {
|
|
509
|
+
for (const entry of entries) {
|
|
510
|
+
// INP counts taps, clicks and key presses; the other events of a gesture (mouseup…) come without an id.
|
|
511
|
+
const id = entry.interactionId;
|
|
512
|
+
if (!id)
|
|
513
|
+
continue;
|
|
514
|
+
let item = interactions.get(id);
|
|
515
|
+
if (!item) {
|
|
516
|
+
item = { id, type: entry.name, rank: RANK[entry.name] ?? 0, events: [], changed: true };
|
|
517
|
+
interactions.set(id, item);
|
|
518
|
+
if (interactions.size > REMEMBERED)
|
|
519
|
+
interactions.delete(interactions.keys().next().value);
|
|
520
|
+
}
|
|
521
|
+
else if ((RANK[entry.name] ?? 0) > item.rank) {
|
|
522
|
+
item.type = entry.name;
|
|
523
|
+
item.rank = RANK[entry.name] ?? 0;
|
|
524
|
+
}
|
|
525
|
+
const part = { start: entry.startTime, duration: entry.duration, processingStart: entry.processingStart, processingEnd: entry.processingEnd };
|
|
526
|
+
if (item.events.length < MAX_EVENTS) {
|
|
527
|
+
item.events.push(part);
|
|
528
|
+
item.changed = true;
|
|
529
|
+
}
|
|
530
|
+
else {
|
|
531
|
+
let shortest = 0;
|
|
532
|
+
for (let i = 1; i < item.events.length; i++)
|
|
533
|
+
if (item.events[i].duration < item.events[shortest].duration)
|
|
534
|
+
shortest = i;
|
|
535
|
+
if (part.duration > item.events[shortest].duration) {
|
|
536
|
+
item.events[shortest] = part;
|
|
537
|
+
item.changed = true;
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
const press = pressedAt(entry.name, entry.startTime);
|
|
541
|
+
const node = entry.target ?? press?.target;
|
|
542
|
+
// The element may leave the page before the batch, so it is described now.
|
|
543
|
+
if (!item.target && node)
|
|
544
|
+
item.target = targetOf(node, entry.name, press?.rendered);
|
|
545
|
+
// Enter or Space on a button runs its click handler, which the names looked for at the key press miss.
|
|
546
|
+
else if (entry.name === 'click' && item.target && !item.target.handler && node) {
|
|
547
|
+
const react = describe(press?.rendered ?? renderedOf(elementOf(node), 'click'));
|
|
548
|
+
if (react.handler)
|
|
549
|
+
Object.assign(item.target, react);
|
|
550
|
+
}
|
|
551
|
+
}
|
|
552
|
+
}, { durationThreshold: Math.max(16, options.threshold) });
|
|
553
|
+
// ---------------------------------------------------------------------------
|
|
554
|
+
// Why the page moved: the browser tells what moved, the page what had just changed
|
|
555
|
+
// ---------------------------------------------------------------------------
|
|
556
|
+
/** Web fonts as they finished loading: the event comes after the shift a font made, and is matched afterwards. */
|
|
557
|
+
const fontsLoaded = [];
|
|
558
|
+
const onFontsLoaded = (event) => {
|
|
559
|
+
for (const face of event.fontfaces ?? [])
|
|
560
|
+
fontsLoaded.push({ family: String(face.family ?? '').replace(/^["']|["']$/g, ''), at: perf.now() });
|
|
561
|
+
if (fontsLoaded.length > 10)
|
|
562
|
+
fontsLoaded.splice(0, fontsLoaded.length - 10);
|
|
563
|
+
};
|
|
564
|
+
scope.document?.fonts?.addEventListener?.('loadingdone', onFontsLoaded);
|
|
565
|
+
const FONT_FILE = /\.(?:woff2?|ttf|otf)(?:[?#]|$)/i;
|
|
566
|
+
/** Keyframe properties that change layout, as `getKeyframes()` names them. */
|
|
567
|
+
const LAYOUT_PROPERTY = /^(?:top|left|right|bottom|inset|(?:min|max)?(?:width|height)|margin|padding|fontSize|lineHeight|border\w*Width)/i;
|
|
568
|
+
let looks = [];
|
|
569
|
+
/**
|
|
570
|
+
* What likely moved the page, looked for as the shift arrives, while the page is as the shift left it: media with
|
|
571
|
+
* no size given that finished loading in the 500 ms before, above what moved, by about its own height; a web font
|
|
572
|
+
* that finished then; an animation of a layout property on or above what moved.
|
|
573
|
+
*/
|
|
574
|
+
const causesOf = (entry) => {
|
|
575
|
+
const now = perf.now();
|
|
576
|
+
// An animation moves the page a little every frame: a few looks a second say enough.
|
|
577
|
+
looks = looks.filter((time) => now - time < 1_000);
|
|
578
|
+
if (looks.length >= CAUSE_LOOKS)
|
|
579
|
+
return undefined;
|
|
580
|
+
looks.push(now);
|
|
581
|
+
const moved = [...(entry.sources ?? [])].filter((source) => source.previousRect && source.currentRect);
|
|
582
|
+
if (moved.length === 0)
|
|
583
|
+
return undefined;
|
|
584
|
+
const top = Math.min(...moved.map((source) => source.previousRect.y));
|
|
585
|
+
const down = Math.max(0, ...moved.map((source) => source.currentRect.y - source.previousRect.y));
|
|
586
|
+
const across = Math.max(0, ...moved.map((source) => source.currentRect.x - source.previousRect.x));
|
|
587
|
+
const start = entry.startTime;
|
|
588
|
+
const causes = [];
|
|
589
|
+
const media = [];
|
|
590
|
+
let elements;
|
|
591
|
+
for (const resource of perf.getEntriesByType?.('resource') ?? []) {
|
|
592
|
+
if (resource.responseEnd > start + 1 || resource.responseEnd < start - 500)
|
|
593
|
+
continue;
|
|
594
|
+
const url = String(resource.name);
|
|
595
|
+
if (FONT_FILE.test(url)) {
|
|
596
|
+
if (causes.some((cause) => cause.kind === 'font'))
|
|
597
|
+
continue;
|
|
598
|
+
const family = fontsLoaded.find((font) => font.at >= start - 500)?.family;
|
|
599
|
+
causes.push({ kind: 'font', url: cutUrl(url), ...(family && { family }) });
|
|
600
|
+
continue;
|
|
601
|
+
}
|
|
602
|
+
elements ??= [...(scope.document?.querySelectorAll?.('img,iframe,video') ?? [])].slice(0, 200);
|
|
603
|
+
const element = elements.find((item) => (item.currentSrc || item.src) === url);
|
|
604
|
+
if (!element || hasSize(element))
|
|
605
|
+
continue;
|
|
606
|
+
const position = scope.getComputedStyle?.(element)?.position;
|
|
607
|
+
if (position === 'fixed' || position === 'absolute')
|
|
608
|
+
continue;
|
|
609
|
+
const box = element.getBoundingClientRect();
|
|
610
|
+
if (box.width === 0 || box.height === 0 || box.top > top + 1)
|
|
611
|
+
continue;
|
|
612
|
+
const kind = element.localName === 'img' ? 'image' : element.localName;
|
|
613
|
+
const target = targetOf(element, 'shift');
|
|
614
|
+
media.push({ cause: { kind, ...(target && { target }), url: cutUrl(url) }, width: box.width, height: box.height });
|
|
615
|
+
}
|
|
616
|
+
// It pushed what moved by about its own height, or with the others by their heights together.
|
|
617
|
+
const near = (distance, size) => size > 0 && Math.abs(distance - size) <= size * 0.15;
|
|
618
|
+
const together = media.reduce((total, item) => total + item.height, 0);
|
|
619
|
+
for (const item of media)
|
|
620
|
+
if (near(down, item.height) || near(down, together) || near(across, item.width))
|
|
621
|
+
causes.push(item.cause);
|
|
622
|
+
for (const animation of (scope.document?.getAnimations?.() ?? []).slice(0, 20)) {
|
|
623
|
+
const element = animation.effect?.target;
|
|
624
|
+
if (!element || animation.playState !== 'running')
|
|
625
|
+
continue;
|
|
626
|
+
const property = (animation.effect.getKeyframes?.() ?? []).flatMap((frame) => Object.keys(frame)).find((key) => LAYOUT_PROPERTY.test(key));
|
|
627
|
+
if (!property)
|
|
628
|
+
continue;
|
|
629
|
+
const holds = moved.some((source) => source.node && (element === source.node || element.contains?.(source.node)));
|
|
630
|
+
if (!holds && element.getBoundingClientRect().top > top + 1)
|
|
631
|
+
continue;
|
|
632
|
+
const target = targetOf(element, 'shift');
|
|
633
|
+
causes.push({ kind: 'animation', ...(target && { target }), property: property.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`) });
|
|
634
|
+
}
|
|
635
|
+
return causes.length > 0 ? causes.slice(0, MAX_CAUSES) : undefined;
|
|
636
|
+
};
|
|
637
|
+
observe('layout-shift', (entries) => {
|
|
638
|
+
for (const entry of entries) {
|
|
639
|
+
if (entry.value < 0.001)
|
|
640
|
+
continue;
|
|
641
|
+
const rect = (box) => (box ? [round(box.x), round(box.y), round(box.width), round(box.height)] : undefined);
|
|
642
|
+
let causes;
|
|
643
|
+
try {
|
|
644
|
+
// A shift right after input is the page answering it, and counts for nothing.
|
|
645
|
+
if (!entry.hadRecentInput)
|
|
646
|
+
causes = causesOf(entry);
|
|
647
|
+
}
|
|
648
|
+
catch {
|
|
649
|
+
causes = undefined;
|
|
650
|
+
}
|
|
651
|
+
const shift = {
|
|
652
|
+
start: round(entry.startTime),
|
|
653
|
+
value: Math.round(entry.value * 10_000) / 10_000,
|
|
654
|
+
hadRecentInput: Boolean(entry.hadRecentInput),
|
|
655
|
+
sources: (entry.sources ?? []).slice(0, 3).map((source) => ({
|
|
656
|
+
target: source.node ? targetOf(source.node, 'shift') : undefined,
|
|
657
|
+
from: rect(source.previousRect),
|
|
658
|
+
to: rect(source.currentRect),
|
|
659
|
+
})),
|
|
660
|
+
...(causes && { causes }),
|
|
661
|
+
};
|
|
662
|
+
// An animation moves the same elements a little every frame: one entry for the run, while it is not sent.
|
|
663
|
+
const last = shifts.at(-1);
|
|
664
|
+
const moved = (one) => one.sources.map((source) => source.target?.selector ?? '').join('|');
|
|
665
|
+
if (last && last.hadRecentInput === shift.hadRecentInput && shift.start - (last.start + (last.duration ?? 0)) <= RUN_GAP_MS && moved(last) === moved(shift)) {
|
|
666
|
+
last.value = Math.round((last.value + shift.value) * 10_000) / 10_000;
|
|
667
|
+
last.count = (last.count ?? 1) + 1;
|
|
668
|
+
last.duration = round(shift.start - last.start);
|
|
669
|
+
shift.sources.forEach((source, index) => {
|
|
670
|
+
if (last.sources[index])
|
|
671
|
+
last.sources[index].to = source.to;
|
|
672
|
+
});
|
|
673
|
+
for (const cause of shift.causes ?? []) {
|
|
674
|
+
const known = (last.causes ??= []).some((one) => one.kind === cause.kind && one.url === cause.url && one.target?.selector === cause.target?.selector && one.property === cause.property);
|
|
675
|
+
if (!known && last.causes.length < MAX_CAUSES)
|
|
676
|
+
last.causes.push(cause);
|
|
677
|
+
}
|
|
678
|
+
}
|
|
679
|
+
else {
|
|
680
|
+
shifts.push(shift);
|
|
681
|
+
}
|
|
682
|
+
}
|
|
683
|
+
if (shifts.length > WAITING.other)
|
|
684
|
+
shifts = shifts.slice(-WAITING.other);
|
|
685
|
+
});
|
|
686
|
+
observe('long-animation-frame', (entries) => {
|
|
687
|
+
for (const entry of entries) {
|
|
688
|
+
const scripts = [...(entry.scripts ?? [])]
|
|
689
|
+
.sort((a, b) => b.duration - a.duration)
|
|
690
|
+
.slice(0, MAX_SCRIPTS)
|
|
691
|
+
.map((script) => ({
|
|
692
|
+
invoker: String(script.invoker ?? ''),
|
|
693
|
+
invokerType: String(script.invokerType ?? ''),
|
|
694
|
+
...(script.sourceURL && { url: cutUrl(script.sourceURL) }),
|
|
695
|
+
...(script.sourceFunctionName && { fn: script.sourceFunctionName }),
|
|
696
|
+
...(script.sourceCharPosition >= 0 && { char: script.sourceCharPosition }),
|
|
697
|
+
start: round(script.startTime),
|
|
698
|
+
duration: round(script.duration),
|
|
699
|
+
...(script.forcedStyleAndLayoutDuration > 0 && { forcedLayout: round(script.forcedStyleAndLayoutDuration) }),
|
|
700
|
+
...(script.pauseDuration > 0 && { pause: round(script.pauseDuration) }),
|
|
701
|
+
}));
|
|
702
|
+
frames.push({
|
|
703
|
+
type: 'loaf',
|
|
704
|
+
start: round(entry.startTime),
|
|
705
|
+
duration: round(entry.duration),
|
|
706
|
+
blocking: round(entry.blockingDuration ?? 0),
|
|
707
|
+
...(entry.renderStart > 0 && { renderStart: round(entry.renderStart) }),
|
|
708
|
+
...(entry.styleAndLayoutStart > 0 && { styleStart: round(entry.styleAndLayoutStart) }),
|
|
709
|
+
scripts,
|
|
710
|
+
});
|
|
711
|
+
}
|
|
712
|
+
if (frames.length > WAITING.other)
|
|
713
|
+
frames = frames.slice(-WAITING.other);
|
|
714
|
+
});
|
|
715
|
+
if (options.resources) {
|
|
716
|
+
observe('resource', (entries) => {
|
|
717
|
+
for (const entry of entries) {
|
|
718
|
+
const url = String(entry.name);
|
|
719
|
+
if (isIgnored(url))
|
|
720
|
+
continue;
|
|
721
|
+
// Steps are 0 when the server did not allow timing (another origin without Timing-Allow-Origin).
|
|
722
|
+
const steps = entry.requestStart > 0;
|
|
723
|
+
const type = String(entry.initiatorType || 'other');
|
|
724
|
+
let dev = false;
|
|
725
|
+
if (options.devModules && (type === 'script' || type === 'other' || type === 'link' || type === 'css')) {
|
|
726
|
+
try {
|
|
727
|
+
dev = new URL(url, scope.location?.href).origin === pageOrigin;
|
|
728
|
+
}
|
|
729
|
+
catch {
|
|
730
|
+
dev = false;
|
|
731
|
+
}
|
|
732
|
+
}
|
|
733
|
+
resources.push({
|
|
734
|
+
url: cutUrl(url),
|
|
735
|
+
type,
|
|
736
|
+
start: round(entry.startTime),
|
|
737
|
+
duration: round(entry.duration),
|
|
738
|
+
...(steps && {
|
|
739
|
+
dns: round(entry.domainLookupEnd - entry.domainLookupStart),
|
|
740
|
+
connect: round(entry.connectEnd - entry.connectStart),
|
|
741
|
+
...(entry.secureConnectionStart > 0 && { tls: round(entry.connectEnd - entry.secureConnectionStart) }),
|
|
742
|
+
waiting: round(entry.responseStart - entry.requestStart),
|
|
743
|
+
download: round(entry.responseEnd - entry.responseStart),
|
|
744
|
+
}),
|
|
745
|
+
...(typeof entry.transferSize === 'number' && { transfer: entry.transferSize }),
|
|
746
|
+
...(typeof entry.decodedBodySize === 'number' && entry.decodedBodySize > 0 && { size: entry.decodedBodySize }),
|
|
747
|
+
...(entry.nextHopProtocol && { protocol: entry.nextHopProtocol }),
|
|
748
|
+
...(entry.responseStatus > 0 && { status: entry.responseStatus }),
|
|
749
|
+
...(entry.renderBlockingStatus === 'blocking' && { renderBlocking: true }),
|
|
750
|
+
// Empty when the file came as it is; missing where the browser does not say.
|
|
751
|
+
...(typeof entry.contentEncoding === 'string' && { encoding: entry.contentEncoding }),
|
|
752
|
+
...(entry.deliveryType && { delivery: String(entry.deliveryType) }),
|
|
753
|
+
...(dev && { dev: true }),
|
|
754
|
+
});
|
|
755
|
+
}
|
|
756
|
+
if (resources.length > WAITING.resources) {
|
|
757
|
+
skipped.resources += resources.length - WAITING.resources;
|
|
758
|
+
resources = resources.slice(-WAITING.resources);
|
|
759
|
+
}
|
|
760
|
+
});
|
|
761
|
+
}
|
|
762
|
+
observe('navigation', (entries) => {
|
|
763
|
+
// Chrome reports the page load's entry twice to a buffered observer.
|
|
764
|
+
const entry = entries[0];
|
|
765
|
+
if (!entry || sentNavigation)
|
|
766
|
+
return;
|
|
767
|
+
sentNavigation = true;
|
|
768
|
+
const at = (value) => (value > 0 ? round(value) : undefined);
|
|
769
|
+
const type = entry.activationStart > 0 ? 'prerender' : String(entry.type || 'navigate').replace(/_/g, '-');
|
|
770
|
+
// Why going back did not restore the page from the back/forward cache, the frames in it included.
|
|
771
|
+
const reasons = [];
|
|
772
|
+
const collect = (node, depth) => {
|
|
773
|
+
if (!node || depth > 5)
|
|
774
|
+
return;
|
|
775
|
+
for (const item of node.reasons ?? []) {
|
|
776
|
+
const reason = typeof item === 'string' ? item : item?.reason;
|
|
777
|
+
if (typeof reason === 'string' && !reasons.includes(reason) && reasons.length < MAX_NOT_RESTORED)
|
|
778
|
+
reasons.push(reason);
|
|
779
|
+
}
|
|
780
|
+
for (const child of node.children ?? [])
|
|
781
|
+
collect(child, depth + 1);
|
|
782
|
+
};
|
|
783
|
+
if (type === 'back-forward')
|
|
784
|
+
collect(entry.notRestoredReasons, 0);
|
|
785
|
+
current = entry.navigationId || 0;
|
|
786
|
+
navigations.push({
|
|
787
|
+
id: entry.navigationId || 0,
|
|
788
|
+
type: type,
|
|
789
|
+
url: cutUrl(String(entry.name || scope.location?.href || '')),
|
|
790
|
+
start: 0,
|
|
791
|
+
...(reasons.length > 0 && { notRestored: reasons }),
|
|
792
|
+
timing: {
|
|
793
|
+
requestStart: at(entry.requestStart),
|
|
794
|
+
responseStart: at(entry.responseStart),
|
|
795
|
+
responseEnd: at(entry.responseEnd),
|
|
796
|
+
domInteractive: at(entry.domInteractive),
|
|
797
|
+
domContentLoaded: at(entry.domContentLoadedEventEnd),
|
|
798
|
+
load: at(entry.loadEventEnd),
|
|
799
|
+
...(entry.requestStart > 0 && {
|
|
800
|
+
dns: round(entry.domainLookupEnd - entry.domainLookupStart),
|
|
801
|
+
connect: round(entry.connectEnd - entry.connectStart),
|
|
802
|
+
}),
|
|
803
|
+
...(entry.redirectEnd > 0 && { redirect: round(entry.redirectEnd - entry.redirectStart) }),
|
|
804
|
+
...(typeof entry.transferSize === 'number' && { transferSize: entry.transferSize }),
|
|
805
|
+
...(entry.nextHopProtocol && { protocol: entry.nextHopProtocol }),
|
|
806
|
+
},
|
|
807
|
+
});
|
|
808
|
+
});
|
|
809
|
+
observe('soft-navigation', (entries) => {
|
|
810
|
+
for (const entry of entries) {
|
|
811
|
+
current = entry.navigationId || 0;
|
|
812
|
+
navigations.push({ id: current, type: 'soft-navigation', url: cutUrl(String(entry.name)), start: round(entry.startTime) });
|
|
813
|
+
}
|
|
814
|
+
});
|
|
815
|
+
const serializeDetail = (detail) => {
|
|
816
|
+
if (detail === undefined || detail === null)
|
|
817
|
+
return undefined;
|
|
818
|
+
try {
|
|
819
|
+
const value = options.serialize ? options.serialize(detail) : JSON.parse(JSON.stringify(detail));
|
|
820
|
+
return JSON.stringify(value).length > MAX_DETAIL ? { $t: 'limit', name: 'detail' } : value;
|
|
821
|
+
}
|
|
822
|
+
catch {
|
|
823
|
+
return undefined;
|
|
824
|
+
}
|
|
825
|
+
};
|
|
826
|
+
const onTiming = (entries) => {
|
|
827
|
+
for (const entry of entries) {
|
|
828
|
+
const name = String(entry.name);
|
|
829
|
+
// React's performance tracks: measures for DevTools, named with a zero-width space.
|
|
830
|
+
if (name.startsWith('') || (entry.detail && typeof entry.detail === 'object' && 'devtools' in entry.detail))
|
|
831
|
+
continue;
|
|
832
|
+
const detail = serializeDetail(entry.detail);
|
|
833
|
+
timings.push({
|
|
834
|
+
kind: entry.entryType === 'measure' ? 'measure' : 'mark',
|
|
835
|
+
name: name.slice(0, 200),
|
|
836
|
+
start: round(entry.startTime),
|
|
837
|
+
...(entry.entryType === 'measure' && { duration: round(entry.duration) }),
|
|
838
|
+
...(detail !== undefined && { detail: detail }),
|
|
839
|
+
});
|
|
840
|
+
}
|
|
841
|
+
if (timings.length > WAITING.other)
|
|
842
|
+
timings = timings.slice(-WAITING.other);
|
|
843
|
+
};
|
|
844
|
+
observe('mark', onTiming);
|
|
845
|
+
observe('measure', onTiming);
|
|
846
|
+
const onPageShow = (event) => {
|
|
847
|
+
if (!event.persisted || stopped)
|
|
848
|
+
return;
|
|
849
|
+
// web-vitals reports a restore under the page load's navigationId; it gets its own here, so both stay.
|
|
850
|
+
restoreId--;
|
|
851
|
+
restored = restoreId;
|
|
852
|
+
current = restoreId;
|
|
853
|
+
navigations.push({ id: restoreId, type: 'back-forward-cache', url: cutUrl(String(scope.location?.href ?? '')), start: round(event.timeStamp) });
|
|
854
|
+
schedule();
|
|
855
|
+
};
|
|
856
|
+
// web-vitals sends its final CLS and INP when the page is hidden; they leave in the same moment.
|
|
857
|
+
const onHidden = () => {
|
|
858
|
+
if (scope.document?.visibilityState === 'hidden')
|
|
859
|
+
flush();
|
|
860
|
+
};
|
|
861
|
+
scope.addEventListener?.('pageshow', onPageShow, true);
|
|
862
|
+
scope.document?.addEventListener?.('visibilitychange', onHidden, true);
|
|
863
|
+
// ---------------------------------------------------------------------------
|
|
864
|
+
// What the page is made of, read once after it loaded and when a viewer asks
|
|
865
|
+
// ---------------------------------------------------------------------------
|
|
866
|
+
/**
|
|
867
|
+
* The images worth a word (larger than shown, far out of view and not lazy, given no size), web fonts, the viewport
|
|
868
|
+
* tag and the number of elements. Stops at its time budget or at the images it reads, and says so.
|
|
869
|
+
*/
|
|
870
|
+
const readPage = () => {
|
|
871
|
+
const document = scope.document;
|
|
872
|
+
if (!document)
|
|
873
|
+
return;
|
|
874
|
+
const began = perf.now();
|
|
875
|
+
const dpr = Number(scope.devicePixelRatio) || 1;
|
|
876
|
+
const width = Number(scope.innerWidth) || 0;
|
|
877
|
+
const height = Number(scope.innerHeight) || 0;
|
|
878
|
+
const scrolled = Number(scope.scrollY) || 0;
|
|
879
|
+
const facts = {
|
|
880
|
+
navigation: current,
|
|
881
|
+
dpr,
|
|
882
|
+
viewport: document.querySelector?.('meta[name="viewport"]')?.getAttribute?.('content') ?? null,
|
|
883
|
+
...(scope.matchMedia?.('(pointer: coarse)')?.matches && { touch: true }),
|
|
884
|
+
elements: document.getElementsByTagName?.('*')?.length ?? 0,
|
|
885
|
+
};
|
|
886
|
+
const found = [];
|
|
887
|
+
let read = 0;
|
|
888
|
+
for (const element of document.getElementsByTagName?.('img') ?? []) {
|
|
889
|
+
if (read >= PAGE_IMAGES || perf.now() - began > PAGE_BUDGET_MS) {
|
|
890
|
+
facts.partial = true;
|
|
891
|
+
break;
|
|
892
|
+
}
|
|
893
|
+
read++;
|
|
894
|
+
const url = String(element.currentSrc || element.src || '');
|
|
895
|
+
if (!element.complete || !element.naturalWidth || !url || url.startsWith('data:') || /\.svg(?:[?#]|$)/i.test(url))
|
|
896
|
+
continue;
|
|
897
|
+
const box = element.getBoundingClientRect();
|
|
898
|
+
const shown = [Math.round(box.width), Math.round(box.height)];
|
|
899
|
+
const natural = [element.naturalWidth, element.naturalHeight];
|
|
900
|
+
const needed = shown[0] * shown[1] * dpr * dpr;
|
|
901
|
+
const oversized = needed > 0 && natural[0] * natural[1] >= 2 * needed;
|
|
902
|
+
const offscreen = box.top + scrolled > height * 3 || box.left > width + 100 || box.right < -100;
|
|
903
|
+
const sized = hasSize(element);
|
|
904
|
+
if (!oversized && !(offscreen && !element.hasAttribute('loading')) && sized)
|
|
905
|
+
continue;
|
|
906
|
+
found.push({
|
|
907
|
+
element,
|
|
908
|
+
image: {
|
|
909
|
+
url: cutUrl(url),
|
|
910
|
+
natural,
|
|
911
|
+
shown,
|
|
912
|
+
...(lazyOf(element) && { lazy: true }),
|
|
913
|
+
...(offscreen && { offscreen: true }),
|
|
914
|
+
...((element.hasAttribute('srcset') || element.parentElement?.localName === 'picture') && { responsive: true }),
|
|
915
|
+
...(!sized && { sized: false }),
|
|
916
|
+
},
|
|
917
|
+
excess: Math.max(0, natural[0] * natural[1] - needed),
|
|
918
|
+
});
|
|
919
|
+
}
|
|
920
|
+
// The worst first: the most pixels sent past what the screen shows.
|
|
921
|
+
const images = found.sort((a, b) => b.excess - a.excess).slice(0, MAX_PAGE_IMAGES);
|
|
922
|
+
if (images.length > 0) {
|
|
923
|
+
facts.images = images.map(({ element, image }) => {
|
|
924
|
+
const target = targetOf(element, 'shift');
|
|
925
|
+
return target ? { target, ...image } : image;
|
|
926
|
+
});
|
|
927
|
+
}
|
|
928
|
+
const fonts = [];
|
|
929
|
+
for (const face of document.fonts ?? []) {
|
|
930
|
+
if (fonts.length >= MAX_PAGE_FONTS)
|
|
931
|
+
break;
|
|
932
|
+
// A face no text uses is never loaded, and costs nothing.
|
|
933
|
+
if (face.status === 'unloaded')
|
|
934
|
+
continue;
|
|
935
|
+
fonts.push({ family: String(face.family ?? '').replace(/^["']|["']$/g, ''), display: String(face.display || 'auto'), status: String(face.status ?? '') });
|
|
936
|
+
}
|
|
937
|
+
if (fonts.length > 0)
|
|
938
|
+
facts.fonts = fonts;
|
|
939
|
+
page = facts;
|
|
940
|
+
schedule();
|
|
941
|
+
};
|
|
942
|
+
let pageTimer;
|
|
943
|
+
let lastInspect = Number.NEGATIVE_INFINITY;
|
|
944
|
+
const readSoon = () => {
|
|
945
|
+
if (stopped)
|
|
946
|
+
return;
|
|
947
|
+
const run = () => {
|
|
948
|
+
pageTimer = undefined;
|
|
949
|
+
if (stopped)
|
|
950
|
+
return;
|
|
951
|
+
try {
|
|
952
|
+
readPage();
|
|
953
|
+
}
|
|
954
|
+
catch {
|
|
955
|
+
// never surface SDK failures to the app
|
|
956
|
+
}
|
|
957
|
+
};
|
|
958
|
+
// A second after load, when the page is idle: an image the page shows after load is in by then.
|
|
959
|
+
pageTimer = setTimeout(() => {
|
|
960
|
+
if (typeof scope.requestIdleCallback === 'function')
|
|
961
|
+
scope.requestIdleCallback(run, { timeout: 2_000 });
|
|
962
|
+
else
|
|
963
|
+
run();
|
|
964
|
+
}, 1_000);
|
|
965
|
+
};
|
|
966
|
+
if (scope.document?.readyState === 'complete')
|
|
967
|
+
readSoon();
|
|
968
|
+
else
|
|
969
|
+
scope.addEventListener?.('load', readSoon, { once: true });
|
|
970
|
+
const inspect = () => {
|
|
971
|
+
const now = perf.now();
|
|
972
|
+
if (stopped || now - lastInspect < INSPECT_EVERY_MS)
|
|
973
|
+
return false;
|
|
974
|
+
lastInspect = now;
|
|
975
|
+
try {
|
|
976
|
+
readPage();
|
|
977
|
+
return true;
|
|
978
|
+
}
|
|
979
|
+
catch {
|
|
980
|
+
return false;
|
|
981
|
+
}
|
|
982
|
+
};
|
|
983
|
+
// ---------------------------------------------------------------------------
|
|
984
|
+
// Web Vitals
|
|
985
|
+
// ---------------------------------------------------------------------------
|
|
986
|
+
/**
|
|
987
|
+
* What React knows of the elements LCP named, by their selector. Taken when the browser names one, which is while
|
|
988
|
+
* it is on the page; the metric can be reported after a route change took it away.
|
|
989
|
+
*/
|
|
990
|
+
const painted = new Map();
|
|
991
|
+
const paintedTarget = (node) => {
|
|
992
|
+
const selector = selectorOf(node);
|
|
993
|
+
if (selector) {
|
|
994
|
+
const { component, source } = describe(renderedOf(elementOf(node), 'shift'), false);
|
|
995
|
+
painted.delete(selector);
|
|
996
|
+
painted.set(selector, { ...(component && { component }), ...(source && { source }) });
|
|
997
|
+
// A page names a few as it loads, and a few more with each route.
|
|
998
|
+
if (painted.size > 20)
|
|
999
|
+
painted.delete(painted.keys().next().value);
|
|
1000
|
+
}
|
|
1001
|
+
return selector;
|
|
1002
|
+
};
|
|
1003
|
+
/** The LCP element as the page has it now, while the browser names it: read only, no layout. */
|
|
1004
|
+
const lcpElement = (entry, url) => {
|
|
1005
|
+
const element = entry?.element;
|
|
1006
|
+
if (element?.nodeType !== 1)
|
|
1007
|
+
return undefined;
|
|
1008
|
+
const tag = String(element.localName || '').toLowerCase();
|
|
1009
|
+
const facts = { tag };
|
|
1010
|
+
if (url && tag !== 'img' && tag !== 'image' && tag !== 'video')
|
|
1011
|
+
facts.background = true;
|
|
1012
|
+
if (tag === 'img') {
|
|
1013
|
+
if (lazyOf(element))
|
|
1014
|
+
facts.lazy = true;
|
|
1015
|
+
const priority = String(element.fetchPriority || element.getAttribute?.('fetchpriority') || '').toLowerCase();
|
|
1016
|
+
if (priority === 'high' || priority === 'low')
|
|
1017
|
+
facts.priority = priority;
|
|
1018
|
+
if (!hasSize(element))
|
|
1019
|
+
facts.sized = false;
|
|
1020
|
+
const width = element.naturalWidth;
|
|
1021
|
+
const height = element.naturalHeight;
|
|
1022
|
+
if (width > 0 && height > 0) {
|
|
1023
|
+
facts.natural = [width, height];
|
|
1024
|
+
// The area the browser painted, at the image's own ratio.
|
|
1025
|
+
if (entry.size > 0) {
|
|
1026
|
+
const across = Math.sqrt((entry.size * width) / height);
|
|
1027
|
+
facts.shown = [Math.round(across), Math.round(entry.size / across)];
|
|
1028
|
+
}
|
|
1029
|
+
}
|
|
1030
|
+
}
|
|
1031
|
+
if (url) {
|
|
1032
|
+
for (const link of scope.document?.querySelectorAll?.('link[rel="preload"][as="image"]') ?? []) {
|
|
1033
|
+
if (link.href === url)
|
|
1034
|
+
facts.preloaded = true;
|
|
1035
|
+
}
|
|
1036
|
+
}
|
|
1037
|
+
return facts;
|
|
1038
|
+
};
|
|
1039
|
+
const metricOf = (metric) => {
|
|
1040
|
+
const a = metric.attribution ?? {};
|
|
1041
|
+
const navigation = metric.navigationType === 'back-forward-cache' && restored ? restored : metric.navigationId || 0;
|
|
1042
|
+
const value = metric.name === 'CLS' ? Math.round(metric.value * 10_000) / 10_000 : round(metric.value);
|
|
1043
|
+
const base = { value, rating: metric.rating, id: String(metric.id), navigation };
|
|
1044
|
+
switch (metric.name) {
|
|
1045
|
+
case 'LCP': {
|
|
1046
|
+
const element = lcpElement(a.lcpEntry, a.url);
|
|
1047
|
+
return {
|
|
1048
|
+
...base,
|
|
1049
|
+
name: 'LCP',
|
|
1050
|
+
attribution: {
|
|
1051
|
+
...(a.target && { target: a.target, ...painted.get(a.target) }),
|
|
1052
|
+
...(a.url && { url: cutUrl(a.url) }),
|
|
1053
|
+
...(element && { element }),
|
|
1054
|
+
ttfb: round(a.timeToFirstByte ?? 0),
|
|
1055
|
+
loadDelay: round(a.resourceLoadDelay ?? 0),
|
|
1056
|
+
loadDuration: round(a.resourceLoadDuration ?? 0),
|
|
1057
|
+
renderDelay: round(a.elementRenderDelay ?? 0),
|
|
1058
|
+
},
|
|
1059
|
+
};
|
|
1060
|
+
}
|
|
1061
|
+
case 'INP': {
|
|
1062
|
+
const longest = a.longestScript;
|
|
1063
|
+
return {
|
|
1064
|
+
...base,
|
|
1065
|
+
name: 'INP',
|
|
1066
|
+
attribution: {
|
|
1067
|
+
...(a.interactionTarget && { target: a.interactionTarget }),
|
|
1068
|
+
...(a.interactionType && { type: a.interactionType }),
|
|
1069
|
+
...(typeof a.interactionTime === 'number' && { time: round(a.interactionTime) }),
|
|
1070
|
+
inputDelay: round(a.inputDelay ?? 0),
|
|
1071
|
+
processing: round(a.processingDuration ?? 0),
|
|
1072
|
+
presentation: round(a.presentationDelay ?? 0),
|
|
1073
|
+
...(a.loadState && { loadState: a.loadState }),
|
|
1074
|
+
...(longest?.entry && {
|
|
1075
|
+
longestScript: {
|
|
1076
|
+
invoker: String(longest.entry.invoker ?? ''),
|
|
1077
|
+
...(longest.entry.sourceURL && { url: cutUrl(longest.entry.sourceURL) }),
|
|
1078
|
+
...(longest.entry.sourceFunctionName && { fn: longest.entry.sourceFunctionName }),
|
|
1079
|
+
...(longest.entry.sourceCharPosition >= 0 && { char: longest.entry.sourceCharPosition }),
|
|
1080
|
+
duration: round(longest.entry.duration),
|
|
1081
|
+
...(longest.subpart && { subpart: longest.subpart }),
|
|
1082
|
+
},
|
|
1083
|
+
}),
|
|
1084
|
+
...(typeof a.totalScriptDuration === 'number' && { scriptTime: round(a.totalScriptDuration) }),
|
|
1085
|
+
...(typeof a.totalStyleAndLayoutDuration === 'number' && { layoutTime: round(a.totalStyleAndLayoutDuration) }),
|
|
1086
|
+
...(typeof a.totalPaintDuration === 'number' && { paintTime: round(a.totalPaintDuration) }),
|
|
1087
|
+
},
|
|
1088
|
+
};
|
|
1089
|
+
}
|
|
1090
|
+
case 'CLS':
|
|
1091
|
+
return {
|
|
1092
|
+
...base,
|
|
1093
|
+
name: 'CLS',
|
|
1094
|
+
attribution: {
|
|
1095
|
+
...(a.largestShiftTarget && { target: a.largestShiftTarget }),
|
|
1096
|
+
...(typeof a.largestShiftTime === 'number' && { time: round(a.largestShiftTime) }),
|
|
1097
|
+
...(typeof a.largestShiftValue === 'number' && { value: Math.round(a.largestShiftValue * 10_000) / 10_000 }),
|
|
1098
|
+
...(a.loadState && { loadState: a.loadState }),
|
|
1099
|
+
},
|
|
1100
|
+
};
|
|
1101
|
+
case 'FCP':
|
|
1102
|
+
return { ...base, name: 'FCP', attribution: { ttfb: round(a.timeToFirstByte ?? 0), toFcp: round(a.firstByteToFCP ?? 0), ...(a.loadState && { loadState: a.loadState }) } };
|
|
1103
|
+
case 'TTFB':
|
|
1104
|
+
return {
|
|
1105
|
+
...base,
|
|
1106
|
+
name: 'TTFB',
|
|
1107
|
+
attribution: {
|
|
1108
|
+
waiting: round(a.waitingDuration ?? 0),
|
|
1109
|
+
cache: round(a.cacheDuration ?? 0),
|
|
1110
|
+
dns: round(a.dnsDuration ?? 0),
|
|
1111
|
+
connection: round(a.connectionDuration ?? 0),
|
|
1112
|
+
request: round(a.requestDuration ?? 0),
|
|
1113
|
+
},
|
|
1114
|
+
};
|
|
1115
|
+
default:
|
|
1116
|
+
return undefined;
|
|
1117
|
+
}
|
|
1118
|
+
};
|
|
1119
|
+
const vitals = options.vitals;
|
|
1120
|
+
if (vitals) {
|
|
1121
|
+
const report = (metric) => {
|
|
1122
|
+
if (stopped)
|
|
1123
|
+
return;
|
|
1124
|
+
try {
|
|
1125
|
+
const payload = metricOf(metric);
|
|
1126
|
+
if (!payload)
|
|
1127
|
+
return;
|
|
1128
|
+
// Only the latest value of each metric matters; a burst of updates goes out once.
|
|
1129
|
+
metrics.set(`${payload.navigation} ${payload.name}`, payload);
|
|
1130
|
+
schedule();
|
|
1131
|
+
}
|
|
1132
|
+
catch {
|
|
1133
|
+
// never surface SDK failures to the app
|
|
1134
|
+
}
|
|
1135
|
+
};
|
|
1136
|
+
const shared = { reportAllChanges: true, generateTarget: selectorOf, reportSoftNavs: supported.includes('soft-navigation') };
|
|
1137
|
+
try {
|
|
1138
|
+
vitals.onTTFB(report, shared);
|
|
1139
|
+
vitals.onFCP(report, shared);
|
|
1140
|
+
vitals.onLCP(report, { ...shared, generateTarget: paintedTarget });
|
|
1141
|
+
vitals.onCLS(report, shared);
|
|
1142
|
+
// INP names the control, as the interaction it points at does.
|
|
1143
|
+
vitals.onINP(report, { ...shared, generateTarget: (node) => selectorOf(controlOf(node)), durationThreshold: Math.max(16, options.threshold) });
|
|
1144
|
+
}
|
|
1145
|
+
catch {
|
|
1146
|
+
// a web-vitals that does not run in this browser
|
|
1147
|
+
}
|
|
1148
|
+
}
|
|
1149
|
+
// ---------------------------------------------------------------------------
|
|
1150
|
+
// Batches
|
|
1151
|
+
// ---------------------------------------------------------------------------
|
|
1152
|
+
/**
|
|
1153
|
+
* An interaction as INP measures it: its longest event, with the events painted in the same frame. Events of
|
|
1154
|
+
* other frames stay out: a key or button held down has its release handled frames later, and that wait is not
|
|
1155
|
+
* time the page took.
|
|
1156
|
+
*/
|
|
1157
|
+
function measure(events) {
|
|
1158
|
+
let longest = events[0];
|
|
1159
|
+
for (const part of events) {
|
|
1160
|
+
if (part.duration > longest.duration || (part.duration === longest.duration && part.start < longest.start))
|
|
1161
|
+
longest = part;
|
|
1162
|
+
}
|
|
1163
|
+
const painted = longest.start + longest.duration;
|
|
1164
|
+
let processingStart = longest.processingStart;
|
|
1165
|
+
let processingEnd = longest.processingEnd;
|
|
1166
|
+
for (const part of events) {
|
|
1167
|
+
// Durations are rounded to 8 ms, so the events of one frame can seem to end that far apart.
|
|
1168
|
+
if (Math.abs(part.start + part.duration - painted) > 8)
|
|
1169
|
+
continue;
|
|
1170
|
+
processingStart = Math.min(processingStart, part.processingStart);
|
|
1171
|
+
processingEnd = Math.max(processingEnd, part.processingEnd);
|
|
1172
|
+
}
|
|
1173
|
+
// Clamped so the three phases add up to the duration, whatever the rounding did.
|
|
1174
|
+
const begin = Math.min(Math.max(processingStart, longest.start), painted);
|
|
1175
|
+
const end = Math.min(Math.max(processingEnd, begin), painted);
|
|
1176
|
+
return { start: longest.start, duration: longest.duration, inputDelay: begin - longest.start, processing: end - begin, presentation: painted - end };
|
|
1177
|
+
}
|
|
1178
|
+
function flush() {
|
|
1179
|
+
if (timer !== undefined)
|
|
1180
|
+
clearTimeout(timer);
|
|
1181
|
+
timer = undefined;
|
|
1182
|
+
if (stopped)
|
|
1183
|
+
return;
|
|
1184
|
+
// Held until Capybara is there, so the SDK's own buffer keeps room for the logs of a slow start.
|
|
1185
|
+
if (!isConnected()) {
|
|
1186
|
+
if (navigations.length + metrics.size + shifts.length + frames.length + timings.length + resources.length + starts.length > 0 || page || [...interactions.values()].some((item) => item.changed)) {
|
|
1187
|
+
schedule();
|
|
1188
|
+
}
|
|
1189
|
+
return;
|
|
1190
|
+
}
|
|
1191
|
+
for (const navigation of navigations.splice(0))
|
|
1192
|
+
emit('perf.navigation', navigation);
|
|
1193
|
+
for (const metric of metrics.values())
|
|
1194
|
+
emit('perf.metric', metric);
|
|
1195
|
+
metrics.clear();
|
|
1196
|
+
if (page)
|
|
1197
|
+
emit('perf.page', page);
|
|
1198
|
+
page = undefined;
|
|
1199
|
+
if (starts.length > 0) {
|
|
1200
|
+
const presses = starts.splice(0).map((press) => {
|
|
1201
|
+
const target = targetOf(press.target, press.type, press.rendered);
|
|
1202
|
+
return { type: press.type, start: round(press.time), ...(target && { target }) };
|
|
1203
|
+
});
|
|
1204
|
+
emit('perf.presses', skipped.presses > 0 ? { presses, skipped: skipped.presses } : { presses });
|
|
1205
|
+
skipped.presses = 0;
|
|
1206
|
+
}
|
|
1207
|
+
const changed = [...interactions.values()].filter((item) => item.changed);
|
|
1208
|
+
for (const item of changed)
|
|
1209
|
+
item.changed = false;
|
|
1210
|
+
const slow = changed
|
|
1211
|
+
.map((item) => ({ item, ...measure(item.events) }))
|
|
1212
|
+
.filter((measured) => measured.duration >= options.threshold)
|
|
1213
|
+
.sort((a, b) => b.duration - a.duration);
|
|
1214
|
+
skipped.interactions += Math.max(0, slow.length - PER_BATCH.interactions);
|
|
1215
|
+
for (const { item, start, duration, inputDelay, processing, presentation } of slow.slice(0, PER_BATCH.interactions).sort((a, b) => a.start - b.start)) {
|
|
1216
|
+
emit('perf.interaction', {
|
|
1217
|
+
id: item.id,
|
|
1218
|
+
type: item.type,
|
|
1219
|
+
...(item.target && { target: item.target }),
|
|
1220
|
+
start: round(start),
|
|
1221
|
+
duration,
|
|
1222
|
+
inputDelay: round(inputDelay),
|
|
1223
|
+
processing: round(processing),
|
|
1224
|
+
presentation: round(presentation),
|
|
1225
|
+
...(skipped.interactions > 0 && { skipped: skipped.interactions }),
|
|
1226
|
+
});
|
|
1227
|
+
skipped.interactions = 0;
|
|
1228
|
+
}
|
|
1229
|
+
// Frames during a slow interaction explain it, so they go first.
|
|
1230
|
+
const during = (frame) => slow.some((item) => item.duration >= SLOW && frame.start < item.start + item.duration && frame.start + frame.duration > item.start);
|
|
1231
|
+
const ranked = frames.splice(0).sort((a, b) => Number(during(b)) - Number(during(a)) || b.duration - a.duration);
|
|
1232
|
+
skipped.frames += Math.max(0, ranked.length - PER_BATCH.frames);
|
|
1233
|
+
for (const frame of ranked.slice(0, PER_BATCH.frames).sort((a, b) => a.start - b.start)) {
|
|
1234
|
+
emit('perf.frame', skipped.frames > 0 ? { ...frame, skipped: skipped.frames } : frame);
|
|
1235
|
+
skipped.frames = 0;
|
|
1236
|
+
}
|
|
1237
|
+
const sendable = (list, limit, key, kind) => {
|
|
1238
|
+
skipped[key] += Math.max(0, list.length - limit);
|
|
1239
|
+
for (const item of list.slice(-limit)) {
|
|
1240
|
+
emit(kind, (skipped[key] > 0 ? { ...item, skipped: skipped[key] } : item));
|
|
1241
|
+
skipped[key] = 0;
|
|
1242
|
+
}
|
|
1243
|
+
};
|
|
1244
|
+
sendable(shifts.splice(0), PER_BATCH.shifts, 'shifts', 'perf.shift');
|
|
1245
|
+
sendable(timings.splice(0), PER_BATCH.timings, 'timings', 'perf.timing');
|
|
1246
|
+
const batch = resources.splice(0);
|
|
1247
|
+
for (let index = 0; index < batch.length; index += MAX_RESOURCES) {
|
|
1248
|
+
const entries = batch.slice(index, index + MAX_RESOURCES);
|
|
1249
|
+
emit('perf.resources', skipped.resources > 0 ? { entries, skipped: skipped.resources } : { entries });
|
|
1250
|
+
skipped.resources = 0;
|
|
1251
|
+
}
|
|
1252
|
+
}
|
|
1253
|
+
const stop = () => {
|
|
1254
|
+
stopped = true;
|
|
1255
|
+
if (timer !== undefined)
|
|
1256
|
+
clearTimeout(timer);
|
|
1257
|
+
if (pageTimer !== undefined)
|
|
1258
|
+
clearTimeout(pageTimer);
|
|
1259
|
+
scope.removeEventListener?.('load', readSoon);
|
|
1260
|
+
scope.document?.fonts?.removeEventListener?.('loadingdone', onFontsLoaded);
|
|
1261
|
+
for (const observer of observers) {
|
|
1262
|
+
try {
|
|
1263
|
+
observer.disconnect();
|
|
1264
|
+
}
|
|
1265
|
+
catch {
|
|
1266
|
+
// already gone
|
|
1267
|
+
}
|
|
1268
|
+
}
|
|
1269
|
+
scope.removeEventListener?.('pageshow', onPageShow, true);
|
|
1270
|
+
scope.document?.removeEventListener?.('visibilitychange', onHidden, true);
|
|
1271
|
+
for (const name of PRESSES)
|
|
1272
|
+
scope.removeEventListener?.(name, remember, { capture: true });
|
|
1273
|
+
if (sweep !== undefined)
|
|
1274
|
+
clearTimeout(sweep);
|
|
1275
|
+
pressed.length = 0;
|
|
1276
|
+
};
|
|
1277
|
+
stop.inspect = inspect;
|
|
1278
|
+
return stop;
|
|
1279
|
+
}
|
|
1280
|
+
//# sourceMappingURL=observe.js.map
|