@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.
Files changed (52) hide show
  1. package/dist/index.d.ts +2 -0
  2. package/dist/index.d.ts.map +1 -1
  3. package/dist/index.js +1 -0
  4. package/dist/index.js.map +1 -1
  5. package/dist/init.d.ts +5 -0
  6. package/dist/init.d.ts.map +1 -1
  7. package/dist/init.js +4 -0
  8. package/dist/init.js.map +1 -1
  9. package/dist/plugins/network/fetch.d.ts.map +1 -1
  10. package/dist/plugins/network/fetch.js +1 -0
  11. package/dist/plugins/network/fetch.js.map +1 -1
  12. package/dist/plugins/network/settings.d.ts +4 -0
  13. package/dist/plugins/network/settings.d.ts.map +1 -1
  14. package/dist/plugins/network/settings.js.map +1 -1
  15. package/dist/plugins/network/timing.d.ts +9 -0
  16. package/dist/plugins/network/timing.d.ts.map +1 -0
  17. package/dist/plugins/network/timing.js +79 -0
  18. package/dist/plugins/network/timing.js.map +1 -0
  19. package/dist/plugins/network/xhr.d.ts.map +1 -1
  20. package/dist/plugins/network/xhr.js +1 -0
  21. package/dist/plugins/network/xhr.js.map +1 -1
  22. package/dist/plugins/network.d.ts.map +1 -1
  23. package/dist/plugins/network.js +4 -1
  24. package/dist/plugins/network.js.map +1 -1
  25. package/dist/plugins/performance/index.d.ts +41 -0
  26. package/dist/plugins/performance/index.d.ts.map +1 -0
  27. package/dist/plugins/performance/index.js +215 -0
  28. package/dist/plugins/performance/index.js.map +1 -0
  29. package/dist/plugins/performance/observe.d.ts +42 -0
  30. package/dist/plugins/performance/observe.d.ts.map +1 -0
  31. package/dist/plugins/performance/observe.js +1280 -0
  32. package/dist/plugins/performance/observe.js.map +1 -0
  33. package/dist/plugins/performance/profile.d.ts +50 -0
  34. package/dist/plugins/performance/profile.d.ts.map +1 -0
  35. package/dist/plugins/performance/profile.js +196 -0
  36. package/dist/plugins/performance/profile.js.map +1 -0
  37. package/dist/plugins/performance/renders.d.ts +13 -0
  38. package/dist/plugins/performance/renders.d.ts.map +1 -0
  39. package/dist/plugins/performance/renders.js +144 -0
  40. package/dist/plugins/performance/renders.js.map +1 -0
  41. package/package.json +2 -2
  42. package/src/index.ts +2 -0
  43. package/src/init.ts +8 -0
  44. package/src/plugins/network/fetch.ts +1 -0
  45. package/src/plugins/network/settings.ts +4 -0
  46. package/src/plugins/network/timing.ts +82 -0
  47. package/src/plugins/network/xhr.ts +1 -0
  48. package/src/plugins/network.ts +3 -1
  49. package/src/plugins/performance/index.ts +243 -0
  50. package/src/plugins/performance/observe.ts +1291 -0
  51. package/src/plugins/performance/profile.ts +232 -0
  52. package/src/plugins/performance/renders.ts +152 -0
@@ -0,0 +1,232 @@
1
+ import {
2
+ PERF_MAX_PROFILE_BYTES,
3
+ PERF_MAX_PROFILE_FRAMES,
4
+ PERF_MAX_PROFILE_SAMPLES,
5
+ PERF_MAX_PROFILE_STACKS,
6
+ type PerfEnvPayload,
7
+ type PerfProfilePayload,
8
+ } from '@capybara-devtools/protocol';
9
+
10
+ // Samples of the page's call stacks with the JS Self-Profiling API, for the slow moments the collector reports. A
11
+ // profiler gives its samples only once stopped, so one runs all the time and is swapped for a new one to read it.
12
+
13
+ export type ProfilerState = NonNullable<PerfEnvPayload['profiler']>['state'];
14
+
15
+ /** The browser's `ProfilerTrace`. */
16
+ interface Trace {
17
+ resources: string[];
18
+ frames: Array<{ name: string; resourceId?: number; line?: number; column?: number }>;
19
+ stacks: Array<{ frameId: number; parentId?: number }>;
20
+ samples: Array<{ timestamp: number; stackId?: number }>;
21
+ }
22
+
23
+ interface BrowserProfiler {
24
+ readonly sampleInterval: number;
25
+ stop(): Promise<Trace>;
26
+ addEventListener?(type: 'samplebufferfull', listener: () => void): void;
27
+ }
28
+
29
+ type ProfilerConstructor = new (options: { sampleInterval: number; maxBufferSize: number }) => BrowserProfiler;
30
+
31
+ export interface StackSampler {
32
+ state(): ProfilerState;
33
+ /** Profiles of the spans of page time, read from the samples taken so far. */
34
+ cut(spans: Array<[number, number]>): Promise<PerfProfilePayload[]>;
35
+ /** Stops or starts sampling as `active` now says, unless held. */
36
+ check(): void;
37
+ /** Keeps sampling stopped while true, e.g. while a trace is recorded: its profiler would show in the trace. */
38
+ hold(held: boolean): void;
39
+ stop(): void;
40
+ }
41
+
42
+ export interface SamplerOptions {
43
+ /** Ms between samples asked for; the browser rounds it up. */
44
+ interval: number;
45
+ /** Samples a profiler keeps; it stops taking them when full. */
46
+ buffer: number;
47
+ /** Whether sampling is worth its cost now: someone is connected, the page is in view. */
48
+ active: () => boolean;
49
+ }
50
+
51
+ /** Samples of a stopped profiler are kept this long, for a span that began before the swap. */
52
+ const KEEP_MS = 10_000;
53
+ /** Swapped before it fills: a full profiler takes no more samples. */
54
+ const FILL = 0.8;
55
+
56
+ /**
57
+ * Starts sampling the page's call stacks when the browser can and the page was served with
58
+ * `Document-Policy: js-profiling`. `scope` is the page's global object.
59
+ */
60
+ export function sampleStacks(scope: Record<string, any>, options: SamplerOptions): StackSampler {
61
+ const Profiler = scope.Profiler as ProfilerConstructor | undefined;
62
+ const now = () => scope.performance.now() as number;
63
+ let state: ProfilerState = typeof Profiler === 'function' ? 'paused' : 'unsupported';
64
+ let current: BrowserProfiler | undefined;
65
+ /** Traces of stopped profilers, newest last, as long as a span may still want them. */
66
+ let stopped: Array<{ trace: Promise<Trace | undefined>; until: number }> = [];
67
+ let timer: ReturnType<typeof setTimeout> | undefined;
68
+ let held = false;
69
+
70
+ const create = (): boolean => {
71
+ try {
72
+ const profiler = new Profiler!({ sampleInterval: options.interval, maxBufferSize: options.buffer });
73
+ current = profiler;
74
+ // Chrome still gives the whole trace once full; a browser that follows the spec to the letter would not.
75
+ profiler.addEventListener?.('samplebufferfull', () => swap());
76
+ state = 'on';
77
+ schedule(profiler.sampleInterval || options.interval);
78
+ return true;
79
+ } catch (error) {
80
+ current = undefined;
81
+ // The page was served without the header the browser needs.
82
+ state = (error as { name?: string })?.name === 'NotAllowedError' ? 'blocked' : 'off';
83
+ return false;
84
+ }
85
+ };
86
+ const schedule = (interval: number) => {
87
+ if (timer !== undefined) clearTimeout(timer);
88
+ timer = setTimeout(() => swap(), interval * options.buffer * FILL);
89
+ };
90
+ /** Stops the running profiler, keeps what it took, and starts the next one at once: the smallest gap. */
91
+ const swap = (restart = true) => {
92
+ const old = current;
93
+ current = undefined;
94
+ if (old) {
95
+ let trace: Promise<Trace | undefined>;
96
+ try {
97
+ trace = old.stop().catch(() => undefined);
98
+ } catch {
99
+ trace = Promise.resolve(undefined);
100
+ }
101
+ stopped.push({ trace, until: now() + KEEP_MS });
102
+ }
103
+ const time = now();
104
+ stopped = stopped.filter((kept) => kept.until > time);
105
+ if (restart && !held && options.active() && state !== 'blocked' && state !== 'off') create();
106
+ else if (state === 'on') state = 'paused';
107
+ };
108
+ const check = () => {
109
+ if (held || !options.active()) {
110
+ if (current) swap(false);
111
+ if (timer !== undefined) clearTimeout(timer);
112
+ } else if (!current && state === 'paused') create();
113
+ };
114
+
115
+ if (state === 'paused') check();
116
+ scope.document?.addEventListener?.('visibilitychange', check);
117
+
118
+ return {
119
+ state: () => state,
120
+ async cut(spans) {
121
+ if (spans.length === 0 || (state !== 'on' && stopped.length === 0)) return [];
122
+ // Reading means stopping: the samples so far end up in the stopped traces.
123
+ swap(options.active());
124
+ const traces = (await Promise.all(stopped.map((kept) => kept.trace))).filter((trace): trace is Trace => trace !== undefined);
125
+ const interval = current?.sampleInterval || options.interval;
126
+ return spans.flatMap(([from, to]) => {
127
+ const profile = profileOf(traces, from, to, interval);
128
+ return profile ? [profile] : [];
129
+ });
130
+ },
131
+ check,
132
+ hold(next) {
133
+ held = next;
134
+ check();
135
+ },
136
+ stop() {
137
+ if (timer !== undefined) clearTimeout(timer);
138
+ scope.document?.removeEventListener?.('visibilitychange', check);
139
+ swap(false);
140
+ stopped = [];
141
+ if (state === 'on' || state === 'paused') state = 'off';
142
+ },
143
+ };
144
+ }
145
+
146
+ /**
147
+ * One profile of a span of page time from the traces that cover it: only the samples in the span, and only the
148
+ * stacks, frames and scripts they use, numbered anew. Cut to the limits by dropping the latest samples.
149
+ */
150
+ export function profileOf(traces: readonly Trace[], from: number, to: number, interval: number): PerfProfilePayload | undefined {
151
+ const picked: Array<{ trace: Trace; timestamp: number; stackId?: number }> = [];
152
+ for (const trace of traces) {
153
+ for (const sample of trace.samples) {
154
+ if (sample.timestamp >= from && sample.timestamp <= to) picked.push({ trace, timestamp: sample.timestamp, stackId: sample.stackId });
155
+ }
156
+ }
157
+ picked.sort((a, b) => a.timestamp - b.timestamp);
158
+ if (!picked.some((sample) => sample.stackId !== undefined)) return undefined;
159
+ let count = Math.min(picked.length, PERF_MAX_PROFILE_SAMPLES);
160
+ for (;;) {
161
+ const profile = build(picked.slice(0, count), from, to, interval);
162
+ const truncated = count < picked.length;
163
+ const fits = profile.frames.length <= PERF_MAX_PROFILE_FRAMES && profile.stacks.length <= PERF_MAX_PROFILE_STACKS && JSON.stringify(profile).length <= PERF_MAX_PROFILE_BYTES - 32;
164
+ if (fits) return truncated ? { ...profile, truncated: true } : profile;
165
+ if (count <= 1) return undefined;
166
+ count = Math.floor(count / 2);
167
+ }
168
+ }
169
+
170
+ function build(samples: Array<{ trace: Trace; timestamp: number; stackId?: number }>, from: number, to: number, interval: number): PerfProfilePayload {
171
+ const resources: string[] = [];
172
+ const frames: PerfProfilePayload['frames'] = [];
173
+ const stacks: PerfProfilePayload['stacks'] = [];
174
+ // Ids are per trace: the next profiler's trace has its own for the same function and the same stack, which become
175
+ // one by what they are.
176
+ const resourceIds = new Map<string, number>();
177
+ const frameIds = new Map<string, number>();
178
+ const stackIds = new Map<string, number>();
179
+ const known = new Map<Trace, Map<number, number>>();
180
+ const resourceOf = (url: string) => {
181
+ let id = resourceIds.get(url);
182
+ if (id === undefined) {
183
+ id = resources.push(url) - 1;
184
+ resourceIds.set(url, id);
185
+ }
186
+ return id;
187
+ };
188
+ const frameOf = (trace: Trace, id: number) => {
189
+ const frame = trace.frames[id];
190
+ const url = frame?.resourceId === undefined ? undefined : trace.resources[frame.resourceId]?.slice(0, 512);
191
+ const name = (frame?.name ?? '').slice(0, 120);
192
+ const key = `${name}\u0000${url ?? ''}\u0000${frame?.line ?? ''}\u0000${frame?.column ?? ''}`;
193
+ let mine = frameIds.get(key);
194
+ if (mine === undefined) {
195
+ mine =
196
+ frames.push({
197
+ name,
198
+ ...(url !== undefined && { resource: resourceOf(url) }),
199
+ ...(frame?.line !== undefined && { line: frame.line }),
200
+ ...(frame?.column !== undefined && { column: frame.column }),
201
+ }) - 1;
202
+ frameIds.set(key, mine);
203
+ }
204
+ return mine;
205
+ };
206
+ const stackOf = (trace: Trace, id: number): number => {
207
+ const ofTrace = known.get(trace) ?? known.set(trace, new Map()).get(trace)!;
208
+ const seen = ofTrace.get(id);
209
+ if (seen !== undefined) return seen;
210
+ const stack = trace.stacks[id];
211
+ if (!stack) return -1;
212
+ const parent = stack.parentId === undefined ? -1 : stackOf(trace, stack.parentId);
213
+ const frame = frameOf(trace, stack.frameId);
214
+ const key = `${frame}:${parent}`;
215
+ let mine = stackIds.get(key);
216
+ if (mine === undefined) {
217
+ mine = stacks.push({ frame, ...(parent >= 0 && { parent }) }) - 1;
218
+ stackIds.set(key, mine);
219
+ }
220
+ ofTrace.set(id, mine);
221
+ return mine;
222
+ };
223
+ const times: number[] = [];
224
+ const stackList: number[] = [];
225
+ for (const sample of samples) {
226
+ times.push(tenth(sample.timestamp - from));
227
+ stackList.push(sample.stackId === undefined ? -1 : stackOf(sample.trace, sample.stackId));
228
+ }
229
+ return { start: tenth(from), end: tenth(to), interval, resources, frames, stacks, times, stackOf: stackList };
230
+ }
231
+
232
+ const tenth = (ms: number) => Math.round(ms * 10) / 10;
@@ -0,0 +1,152 @@
1
+ import { PERF_MAX_COMPONENTS, type PerfCommit, type PerfComponentTime } from '@capybara-devtools/protocol';
2
+ import { now } from '../../utils.js';
3
+ import type { Fiber, FiberRoot } from '../state/fibers.js';
4
+ import { installReactHook } from '../state/react-hook.js';
5
+
6
+ /** React's profiler fields, set in development builds when the DevTools hook was there before react-dom loaded. */
7
+ interface ProfiledFiber extends Fiber {
8
+ flags?: number;
9
+ actualDuration?: number;
10
+ actualStartTime?: number;
11
+ }
12
+
13
+ export interface ReactInfo {
14
+ version?: string;
15
+ profiling: boolean;
16
+ /** Why render times are missing, when React is a development build that does not report them. */
17
+ note?: string;
18
+ }
19
+
20
+ /**
21
+ * A commit's walk stops past its time or its fibers, and the commit is marked truncated: what it did not reach would
22
+ * count toward the components above. The time is 2 ms, or this share of what the commit took to render when that is
23
+ * more. Chrome walks a fiber in about 0.03 µs (12 000 in 0.4 ms); Safari took ten times as long on a page's first
24
+ * large commit, and 2 ms cut a list of 3 000 rows short.
25
+ */
26
+ const BUDGET_MS = 2;
27
+ const BUDGET_SHARE = 0.02;
28
+ const MAX_FIBERS = 50_000;
29
+ /** Commits quicker than this are not reported: they are the bulk of commits and explain no slowness. */
30
+ const MIN_COMMIT_MS = 1;
31
+ /** React sets it on fibers that rendered rather than bailed out. */
32
+ const PERFORMED_WORK = 1;
33
+ /** Function, class, forwardRef, memo and simple memo components. */
34
+ const COMPONENTS = new Set([0, 1, 11, 14, 15]);
35
+ const HOST_ROOT = 3;
36
+
37
+ /**
38
+ * Reports what React rendered in each commit, from the profiler timings of its development builds: each component's
39
+ * time without its child components, but with the DOM elements it renders, which is what it costs to render it.
40
+ */
41
+ export function watchRenders(report: (commit: PerfCommit) => void, onReact: (info: ReactInfo) => void, onFail: (error: unknown) => void): () => void {
42
+ let stopped = false;
43
+ /** What was last announced. Next.js's dev overlay is a root of its own without timings: one profiled root wins. */
44
+ let announced: boolean | undefined;
45
+
46
+ const onCommit = (root: FiberRoot) => {
47
+ if (stopped) return;
48
+ try {
49
+ const current = root?.current as ProfiledFiber | undefined;
50
+ if (!current || current.tag !== HOST_ROOT) return;
51
+ const profiling = typeof current.actualDuration === 'number';
52
+ if (announced === undefined || (profiling && !announced)) {
53
+ announced = profiling;
54
+ onReact({
55
+ version: rendererVersion(installed.hook),
56
+ profiling,
57
+ // `_debugOwner` exists only in development builds.
58
+ ...(!profiling &&
59
+ '_debugOwner' in current && { note: 'React reports render times only when Capybara starts before react-dom loads: import the file that calls init() first.' }),
60
+ });
61
+ }
62
+ if (!profiling) return;
63
+ const duration = current.actualDuration!;
64
+ if (duration < MIN_COMMIT_MS) return;
65
+ report(walk(current, duration));
66
+ } catch (error) {
67
+ stopped = true;
68
+ installed.undo();
69
+ onFail(error);
70
+ }
71
+ };
72
+
73
+ const installed = installReactHook(onCommit);
74
+ return () => {
75
+ stopped = true;
76
+ installed.undo();
77
+ };
78
+ }
79
+
80
+ function walk(root: ProfiledFiber, duration: number): PerfCommit {
81
+ const started = now();
82
+ const budget = Math.max(BUDGET_MS, duration * BUDGET_SHARE);
83
+ const found: Array<PerfComponentTime & { fiberSelf: number }> = [];
84
+ // Each fiber with the nearest rendered component above it, which its own work counts toward.
85
+ const stack: Array<[ProfiledFiber, (PerfComponentTime & { fiberSelf: number }) | undefined]> = [];
86
+ if (root.child) stack.push([root.child as ProfiledFiber, undefined]);
87
+ let visited = 0;
88
+ let truncated = false;
89
+ while (stack.length > 0) {
90
+ if (visited >= MAX_FIBERS || (visited % 256 === 255 && now() - started > budget)) {
91
+ truncated = true;
92
+ break;
93
+ }
94
+ const [fiber, owner] = stack.pop()!;
95
+ visited++;
96
+ const previous = fiber.alternate as ProfiledFiber | null;
97
+ let next = owner;
98
+ const rendered = !previous || ((fiber.flags ?? 0) & PERFORMED_WORK) === PERFORMED_WORK;
99
+ if (rendered && COMPONENTS.has(fiber.tag) && typeof fiber.actualDuration === 'number') {
100
+ const time = fiber.actualDuration;
101
+ const entry = { name: nameOf(fiber), self: time, total: time, count: 1, ...(!previous && { mounts: 1 }), fiberSelf: time };
102
+ if (owner) owner.fiberSelf -= time;
103
+ found.push(entry);
104
+ next = entry;
105
+ }
106
+ if (fiber.sibling) stack.push([fiber.sibling as ProfiledFiber, owner]);
107
+ // A subtree React skipped keeps the same child as before.
108
+ if (fiber.child && (!previous || fiber.child !== previous.child)) stack.push([fiber.child as ProfiledFiber, next]);
109
+ }
110
+
111
+ const byName = new Map<string, PerfComponentTime>();
112
+ for (const entry of found) {
113
+ const known = byName.get(entry.name);
114
+ const self = Math.max(0, entry.fiberSelf);
115
+ if (known) {
116
+ known.self += self;
117
+ known.total += entry.total;
118
+ known.count++;
119
+ if (entry.mounts) known.mounts = (known.mounts ?? 0) + 1;
120
+ } else {
121
+ byName.set(entry.name, { name: entry.name, self, total: entry.total, count: 1, ...(entry.mounts && { mounts: 1 }) });
122
+ }
123
+ }
124
+ const round = (value: number) => Math.round(value * 10) / 10;
125
+ const components = [...byName.values()]
126
+ .sort((a, b) => b.self - a.self)
127
+ .slice(0, PERF_MAX_COMPONENTS)
128
+ .map((component) => ({ ...component, self: round(component.self), total: round(component.total) }));
129
+ const start = typeof root.actualStartTime === 'number' && root.actualStartTime > 0 ? root.actualStartTime : started - duration;
130
+ return { start: round(start), duration: round(duration), components, ...(truncated && { truncated: true }) };
131
+ }
132
+
133
+ function nameOf(fiber: Fiber): string {
134
+ const type = fiber.type;
135
+ if (typeof type === 'function') return type.displayName || type.name || 'Anonymous';
136
+ if (type && typeof type === 'object') {
137
+ // forwardRef keeps the function in `render`, memo the wrapped component in `type`.
138
+ const inner = type.render ?? type.type;
139
+ return type.displayName || inner?.displayName || inner?.name || 'Anonymous';
140
+ }
141
+ return 'Anonymous';
142
+ }
143
+
144
+ function rendererVersion(hook: { renderers?: unknown } | undefined): string | undefined {
145
+ const renderers = hook?.renderers;
146
+ if (!(renderers instanceof Map)) return undefined;
147
+ for (const renderer of renderers.values()) {
148
+ const version = (renderer as { version?: unknown } | null)?.version;
149
+ if (typeof version === 'string') return version;
150
+ }
151
+ return undefined;
152
+ }