deictic 0.8.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 (112) hide show
  1. package/API.md +73 -18
  2. package/README.md +1 -1
  3. package/dist/annotations/client.js +1 -1
  4. package/dist/cli.js +1 -1
  5. package/dist/cli.js.map +1 -1
  6. package/dist/client/index.d.ts +13 -13
  7. package/dist/client/index.d.ts.map +1 -1
  8. package/dist/client/index.js +11 -7
  9. package/dist/client/index.js.map +1 -1
  10. package/dist/react/client.d.ts +19 -0
  11. package/dist/react/client.d.ts.map +1 -0
  12. package/dist/react/client.js +504 -0
  13. package/dist/react/client.js.map +1 -0
  14. package/dist/react/index.d.ts +2 -0
  15. package/dist/react/index.js +1 -0
  16. package/dist/recommended/index.d.ts +15 -7
  17. package/dist/recommended/index.d.ts.map +1 -1
  18. package/dist/recommended/index.js +1 -1
  19. package/dist/recordings/client.d.ts.map +1 -1
  20. package/dist/recordings/client.js +48 -5
  21. package/dist/recordings/client.js.map +1 -1
  22. package/dist/screenshots/client.d.ts +9 -1
  23. package/dist/screenshots/client.d.ts.map +1 -1
  24. package/dist/screenshots/rrweb.d.ts +0 -6
  25. package/dist/screenshots/rrweb.d.ts.map +1 -1
  26. package/dist/screenshots/rrweb.js +53 -10
  27. package/dist/screenshots/rrweb.js.map +1 -1
  28. package/dist/shared/board.js +1 -1
  29. package/dist/shared/canvas.js +30 -0
  30. package/dist/shared/canvas.js.map +1 -0
  31. package/dist/shared/client.js +44 -2
  32. package/dist/shared/client.js.map +1 -1
  33. package/dist/shared/dom.js +7 -1
  34. package/dist/shared/dom.js.map +1 -1
  35. package/dist/shared/drawer.js +1 -1
  36. package/dist/shared/endpoints.js +1 -1
  37. package/dist/shared/find.js +6 -1
  38. package/dist/shared/find.js.map +1 -1
  39. package/dist/shared/frame.js +5 -2
  40. package/dist/shared/frame.js.map +1 -1
  41. package/dist/shared/index.d.ts +6 -0
  42. package/dist/shared/index.d.ts.map +1 -1
  43. package/dist/shared/index10.d.ts +70 -0
  44. package/dist/shared/index10.d.ts.map +1 -0
  45. package/dist/shared/index3.d.ts +11 -0
  46. package/dist/shared/index3.d.ts.map +1 -1
  47. package/dist/shared/index7.d.ts +92 -312
  48. package/dist/shared/index7.d.ts.map +1 -1
  49. package/dist/shared/index8.d.ts +324 -47
  50. package/dist/shared/index8.d.ts.map +1 -1
  51. package/dist/shared/index9.d.ts +45 -63
  52. package/dist/shared/index9.d.ts.map +1 -1
  53. package/dist/shared/init.js +15 -11
  54. package/dist/shared/init.js.map +1 -1
  55. package/dist/shared/marks.js +7 -1
  56. package/dist/shared/marks.js.map +1 -1
  57. package/dist/shared/package.js +3 -1
  58. package/dist/shared/packages.js +1 -1
  59. package/dist/shared/playwright.js +59 -3
  60. package/dist/shared/playwright.js.map +1 -1
  61. package/dist/shared/react.js +25 -0
  62. package/dist/shared/react.js.map +1 -0
  63. package/dist/shared/recommended.js +6 -3
  64. package/dist/shared/recommended.js.map +1 -1
  65. package/dist/shared/recording.js +80 -3
  66. package/dist/shared/recording.js.map +1 -1
  67. package/dist/shared/recordings.js +30 -2
  68. package/dist/shared/recordings.js.map +1 -1
  69. package/dist/shared/screenshots.js.map +1 -1
  70. package/dist/shared/src.js.map +1 -1
  71. package/dist/shared/task.js +1 -0
  72. package/dist/shared/task.js.map +1 -1
  73. package/dist/shared/tasks.js +11 -0
  74. package/dist/shared/tasks.js.map +1 -1
  75. package/dist/tailwind/client.d.ts +1 -1
  76. package/dist/tailwind/index.d.ts +1 -1
  77. package/dist/tasks/client.d.ts +1 -1
  78. package/dist/tasks/client.js +45 -19
  79. package/dist/tasks/client.js.map +1 -1
  80. package/dist/tasks/index.d.ts +1 -1
  81. package/dist/voice/client.d.ts +1 -1
  82. package/dist/voice/client.js +1 -1
  83. package/dist/voice/index.d.ts +1 -1
  84. package/package.json +25 -1
  85. package/src/cli/bun.ts +2 -2
  86. package/src/cli/find.ts +5 -1
  87. package/src/cli/frame.ts +6 -3
  88. package/src/cli/init.ts +14 -9
  89. package/src/cli/recording.ts +90 -4
  90. package/src/cli/task.ts +4 -0
  91. package/src/cli.ts +13 -6
  92. package/src/client/dom.ts +14 -0
  93. package/src/client/index.ts +21 -14
  94. package/src/index.ts +6 -0
  95. package/src/plugins/react/client.ts +162 -0
  96. package/src/plugins/react/index.ts +130 -0
  97. package/src/plugins/react/renders.ts +219 -0
  98. package/src/plugins/react/serialize.ts +139 -0
  99. package/src/plugins/react/timeline.ts +143 -0
  100. package/src/plugins/recommended/index.ts +17 -5
  101. package/src/plugins/recordings/client.ts +64 -4
  102. package/src/plugins/recordings/marks.ts +7 -0
  103. package/src/plugins/recordings/replay.ts +30 -2
  104. package/src/plugins/screenshots/canvas.ts +27 -0
  105. package/src/plugins/screenshots/client.ts +42 -2
  106. package/src/plugins/screenshots/index.ts +11 -0
  107. package/src/plugins/screenshots/playwright.ts +90 -4
  108. package/src/plugins/screenshots/rrweb.ts +57 -9
  109. package/src/plugins/screenshots/states.ts +26 -0
  110. package/src/plugins/tasks/client.ts +41 -6
  111. package/src/plugins/tasks/composer.ts +24 -7
  112. package/src/plugins/tasks/index.ts +16 -2
@@ -0,0 +1,162 @@
1
+ /**
2
+ * The react plugin's page half: what React's DevTools would show of the components that wrote an element, read off
3
+ * its fibers with bippy (an optional peer, imported as a task first asks for it), for a task to attach.
4
+ */
5
+ import type * as Main from 'bippy';
6
+ import type * as Source from 'bippy/source';
7
+
8
+ import { componentOf, fiberOf, type Owner, ownerOf } from '#src/client/component.ts';
9
+ import { defineClientPlugin } from '#src/index.ts';
10
+
11
+ import type { Commit, Component, Hook, ReactOptions, Snapshot } from './index.ts';
12
+ import { countRenders, type Fiber } from './renders.ts';
13
+ import { serialize } from './serialize.ts';
14
+ import { timeline } from './timeline.ts';
15
+
16
+ /** What a task asks of the plugin, and a recording. */
17
+ export interface Inspector {
18
+ /** The snapshot of the element's components, as the JSON a task attaches: `undefined` where React didn't render it in development. */
19
+ snapshot(el: Element): Promise<string | undefined>;
20
+ /**
21
+ * React's commits from now, an entry a frame (`emit` hears each), until what's answered stops it: for a recording.
22
+ * `undefined` where renders aren't counted (`renders: false`, or no DevTools hook on the page).
23
+ */
24
+ commits?: (emit: (commit: Commit) => void) => () => void;
25
+ }
26
+
27
+ declare module 'deictic' {
28
+ interface ClientApis {
29
+ react: Inspector;
30
+ }
31
+ }
32
+
33
+ /** How long hook names may take: their source, and its map, are fetched from the dev server. */
34
+ const NAMES_WAIT = 3000;
35
+ /** What's attached at most, in characters: a page's values may be its whole store. */
36
+ const MOST = 200_000;
37
+
38
+ /** Hooks whose values are functions to run, which say nothing of what the component shows. */
39
+ const SILENT = new Set(['Effect', 'LayoutEffect', 'InsertionEffect', 'ImperativeHandle', 'EffectEvent']);
40
+
41
+ type Bippy = typeof Main & typeof Source;
42
+
43
+ let loading: Promise<Bippy> | undefined;
44
+
45
+ /**
46
+ * bippy, with a renderer to inspect hooks through. React hands its renderer to DevTools' hook as it loads, which
47
+ * React Refresh (Vite's, Next's) installs first in development; where nothing did, the page's React is asked for its
48
+ * dispatcher, which is all hook inspection needs of one.
49
+ */
50
+ const bippy = (): Promise<Bippy> =>
51
+ (loading ??= (async () => {
52
+ const [main, source] = await Promise.all([import('bippy'), import('bippy/source')]).catch((e: unknown) => {
53
+ loading = undefined;
54
+ throw new Error('react needs bippy: add it to your devDependencies', { cause: e });
55
+ });
56
+ if (main.getRDTHook().renderers.size === 0 && main._renderers.size === 0) {
57
+ const React = (await import('react')) as unknown as Record<string, unknown>;
58
+ const internals = (React.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE ??
59
+ (React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED as { ReactCurrentDispatcher?: unknown } | undefined)
60
+ ?.ReactCurrentDispatcher) as { H: unknown } | { current: unknown } | undefined;
61
+ if (internals !== undefined) main._renderers.add({ currentDispatcherRef: internals } as never);
62
+ }
63
+ return { ...main, ...source };
64
+ })());
65
+
66
+ const parentOf = (el: Element): Element | undefined => {
67
+ if (el.parentElement !== null) return el.parentElement;
68
+ const root = el.getRootNode();
69
+ return root instanceof ShadowRoot ? root.host : undefined;
70
+ };
71
+
72
+ /** `src/Plan.tsx:12`: where the nearest element around `el` that `owner` wrote is, which is in its JSX. */
73
+ function placeOf(el: Element, owner: Owner): string | undefined {
74
+ for (let at: Element | undefined = el; at !== undefined; at = parentOf(at)) {
75
+ const by = ownerOf(fiberOf(at));
76
+ // A component's fiber is one of two, by turns: an element may name either.
77
+ if (by === undefined || (by !== owner && by !== owner.alternate)) continue;
78
+ const mark = at.getAttribute('data-deictic');
79
+ if (mark !== null) return mark.replace(/:\d+$/, '');
80
+ }
81
+ return undefined;
82
+ }
83
+
84
+ export default defineClientPlugin<never, never, Inspector>({
85
+ name: 'react',
86
+ setup: ({ options }) => {
87
+ const { components = 4, mask = [], names = true, renders = true } = (options ?? {}) as ReactOptions;
88
+ // From now, before any task: what rendered before the page started deictic goes uncounted.
89
+ const counted = renders ? countRenders() : undefined;
90
+ const value = (of: unknown) => serialize(of, mask);
91
+
92
+ /** A hook as DevTools lists it: its kind (`State`, or a custom hook's name less `use`), what the code calls it, its value. */
93
+ const hookOf = (node: Source.HooksNode, named: Map<string, string>): Hook | undefined => {
94
+ if (SILENT.has(node.name)) return undefined;
95
+ const { fileName, lineNumber, columnNumber } = node.hookSource ?? {};
96
+ const as = fileName ? named.get(`${fileName}:${lineNumber ?? 0}:${columnNumber ?? 0}`) : undefined;
97
+ const inner = node.subHooks.flatMap((sub) => hookOf(sub, named) ?? []);
98
+ const read = node.subHooks.length > 0 && node.value === undefined ? undefined : value(node.value);
99
+ return {
100
+ hook: node.name,
101
+ ...(as === undefined ? {} : { as }),
102
+ ...(read === undefined ? {} : { value: read }),
103
+ ...(inner.length === 0 ? {} : { hooks: inner }),
104
+ };
105
+ };
106
+
107
+ return {
108
+ ...(counted === undefined ? {} : { commits: (emit: (commit: Commit) => void) => timeline(counted.subscribe, emit) }),
109
+ snapshot: async (el) => {
110
+ const wrote = ownerOf(fiberOf(el));
111
+ if (wrote === undefined) return undefined;
112
+ const b = await bippy();
113
+ const found: Component[] = [];
114
+ for (let owner: Owner | undefined = wrote; owner !== undefined && found.length < components; owner = ownerOf(owner)) {
115
+ const name = componentOf(owner) ?? 'Anonymous';
116
+ // A server component: it has a name and no fiber, so no props or state the page holds.
117
+ if (typeof owner.name === 'string') {
118
+ found.push({ name, server: true });
119
+ continue;
120
+ }
121
+ const fiber = b.getLatestFiber(owner as never) as unknown as Owner & {
122
+ memoizedProps?: unknown;
123
+ memoizedState?: unknown;
124
+ stateNode?: { state?: unknown } | null;
125
+ };
126
+ const at = placeOf(el, owner);
127
+ const component: Component = { name, ...(at === undefined ? {} : { at }) };
128
+ const props = value(fiber.memoizedProps);
129
+ if (props !== undefined) component.props = props;
130
+ const rendered = counted?.read(fiber as unknown as Fiber);
131
+ if (rendered !== undefined) component.renders = rendered;
132
+ // A class's state is its instance's; a function's is its hooks.
133
+ if (fiber.stateNode !== null && typeof fiber.stateNode === 'object' && 'state' in fiber.stateNode) {
134
+ const state = value(fiber.stateNode.state);
135
+ if (state !== undefined) component.state = state;
136
+ } else {
137
+ try {
138
+ const tree = b.getFiberHooks(fiber as never);
139
+ let named = new Map<string, string>();
140
+ if (names && tree.length > 0) {
141
+ // Read off the source, which may not answer: the hooks go unnamed then.
142
+ named = await b.parseHookNames(tree, undefined, { timeoutMs: NAMES_WAIT }).catch(() => new Map());
143
+ }
144
+ const hooks = tree.flatMap((node) => hookOf(node, named) ?? []);
145
+ if (hooks.length > 0) component.hooks = hooks;
146
+ } catch (e) {
147
+ component.problem = `its hooks couldn't be read: ${e instanceof Error ? e.message : String(e)}`;
148
+ }
149
+ }
150
+ found.push(component);
151
+ }
152
+ if (found.length === 0) return undefined;
153
+ const snapshot: Snapshot = { components: found };
154
+ const json = JSON.stringify(snapshot, null, 2);
155
+ if (json.length <= MOST) return json;
156
+ // Too much: the nearest component's alone, the one that wrote the element.
157
+ const less = JSON.stringify({ components: found.slice(0, 1) } satisfies Snapshot, null, 2);
158
+ return less.length <= MOST ? less : `${less.slice(0, MOST)}\n… cut short`;
159
+ },
160
+ };
161
+ },
162
+ });
@@ -0,0 +1,130 @@
1
+ /**
2
+ * `deictic/react`: what React's DevTools would show of the element a task is about, attached to the task as
3
+ * `react.json`. The component that wrote the element and the ones that wrote it in turn, each with its props, and
4
+ * its state: a class's, or a function's hooks, named as the code names them where the source says (`count`, not
5
+ * `State`). Read with bippy (an optional peer, imported as a task first asks for it) in development only, as React
6
+ * keeps who wrote an element only there. Each says how often it rendered, how long that took and why, as DevTools'
7
+ * profiler would, counted from React's commits. No tab, and nothing in the page of its own: the tasks plugin asks it, and
8
+ * sends what it answers beside the element's HTML, while the panel's HTML snapshot box is ticked.
9
+ *
10
+ * Values are what the page holds, so they're masked as the network plugin's are, by their names (`token`,
11
+ * `password`, `auth`…, and `mask`'s), and cut where they're deep or long.
12
+ */
13
+ import { definePlugin } from '#src/index.ts';
14
+
15
+ export interface ReactOptions {
16
+ /** How many components, out from the one that wrote the element: 4 by default. */
17
+ components?: number;
18
+ /** More names whose values are blanked: a part of the name, in any case. */
19
+ mask?: string[];
20
+ /**
21
+ * Whether hooks are named as the code names them, read off the source and its map (fetched from the dev server, as
22
+ * DevTools does): true by default. Without, each is its kind alone, `State` or `Memo`, in the order they're called.
23
+ */
24
+ names?: boolean;
25
+ /**
26
+ * Whether each component's renders are counted, timed and explained, from React's commits as DevTools' hook hears
27
+ * them: true by default. That hook is React Refresh's, in development; without one there's nothing to count.
28
+ */
29
+ renders?: boolean;
30
+ }
31
+
32
+ /** What JSON holds of a value: anything it can't hold says what it was, in brackets (`[function onClick]`). */
33
+ export type Value = null | boolean | number | string | Value[] | { [key: string]: Value };
34
+
35
+ /** A hook as DevTools lists it. */
36
+ export interface Hook {
37
+ /** Its kind: `State`, `Memo`, `Context`, or a custom hook's name less `use` (`Auth`), whose `hooks` it called. */
38
+ hook: string;
39
+ /** What the code calls it: `const [count, setCount] = useState(0)` is `count`. */
40
+ as?: string;
41
+ value?: Value;
42
+ hooks?: Hook[];
43
+ }
44
+
45
+ /** A component's renders, counted from when the page started deictic, not from its first. */
46
+ export interface Renders {
47
+ count: number;
48
+ /** In the 10 seconds before the task: a loop, or a burst on each keystroke. */
49
+ recent: number;
50
+ /** How long ago it last rendered, in milliseconds. */
51
+ lastAgo: number;
52
+ /** How long its last render took, with what it rendered, in milliseconds: where React times them. */
53
+ lastMs?: number;
54
+ /** Its own part of it. */
55
+ selfMs?: number;
56
+ /** Why it last rendered: `mounted`, `props changed: chosen`, `state changed`, `context changed`, `its parent rendered`. */
57
+ why: string;
58
+ }
59
+
60
+ /** A component that rendered in a recording's commit, once for each time it did in the entry. */
61
+ export interface Rendered {
62
+ name: string;
63
+ /** Where its JSX has the first element it wrote, `src/Plan.tsx:12`, where it wrote one. */
64
+ at?: string;
65
+ /** How many times it rendered in the entry, where that's more than once. */
66
+ count?: number;
67
+ /** How long it took, with what it rendered, in milliseconds, all its renders in the entry together. */
68
+ ms?: number;
69
+ /** Its own part of it. */
70
+ selfMs?: number;
71
+ /** Why it last rendered, as `Renders.why`. */
72
+ why: string;
73
+ }
74
+
75
+ /**
76
+ * A recording's entry of React's commits, `deictic.react` events: commits a frame apart, as one, with the components
77
+ * they rendered, the slowest first. `{ on: boolean }` events say where the recording starts and stops having them.
78
+ */
79
+ export interface Commit {
80
+ /** How many commits it is. */
81
+ commits: number;
82
+ /** How long rendering them took, in milliseconds, where React times it. */
83
+ ms?: number;
84
+ /** Of several, the slowest one's, in milliseconds: one past a frame is what makes a page stutter. */
85
+ slowest?: number;
86
+ /**
87
+ * The rest of a busy second, past ten entries in it: how long it spans, in milliseconds, up to this entry's
88
+ * moment. A page that renders without stop is ten entries and this one a second.
89
+ */
90
+ over?: number;
91
+ /** React's scheduler priority for the last: `immediate` (a click, a key), `user-blocking`, `normal`, `low`, `idle`. */
92
+ priority?: string;
93
+ /** Twenty at most. */
94
+ components: Rendered[];
95
+ /** How many more components rendered than it names. */
96
+ more?: number;
97
+ }
98
+
99
+ /** A component that wrote the element, or wrote one that did. */
100
+ export interface Component {
101
+ name: string;
102
+ /** Where its JSX has the nearest element around this one, `src/Plan.tsx:12`: none for one that only passed it on. */
103
+ at?: string;
104
+ /** A server component: React kept its name, and nothing of it is in the page. */
105
+ server?: true;
106
+ props?: Value;
107
+ /** A class component's state. */
108
+ state?: Value;
109
+ /** A function component's hooks, in the order it calls them, effects left out. */
110
+ hooks?: Hook[];
111
+ renders?: Renders;
112
+ /** Why what's missing is. */
113
+ problem?: string;
114
+ }
115
+
116
+ /** `react.json`: the component that wrote the element first, then the one that wrote it, and on out. */
117
+ export interface Snapshot {
118
+ components: Component[];
119
+ }
120
+
121
+ export function reactState(options: ReactOptions = {}) {
122
+ return definePlugin<never, never>({
123
+ name: 'react',
124
+ client: 'deictic/react/client',
125
+ packages: ['bippy'],
126
+ clientOptions: { ...options },
127
+ });
128
+ }
129
+
130
+ export default reactState;
@@ -0,0 +1,219 @@
1
+ /**
2
+ * How often each component rendered, how long it took and why, as React's DevTools profiler tells it: each commit
3
+ * React hands DevTools' hook (`onCommitFiberRoot`) is walked for the components it rendered. The hook is React
4
+ * Refresh's in development (Vite's, Next's, webpack's and Rspack's), which React found as it loaded, and calls on
5
+ * every commit whoever answers it later: so it's counted from when deictic's page half starts, not from the page's
6
+ * first render.
7
+ */
8
+ import type { Renders } from './index.ts';
9
+
10
+ /** What a fiber holds that this reads: React's own, in development. */
11
+ export interface Fiber {
12
+ tag: number;
13
+ flags?: number;
14
+ alternate: Fiber | null;
15
+ child: Fiber | null;
16
+ sibling: Fiber | null;
17
+ memoizedProps?: unknown;
18
+ memoizedState?: unknown;
19
+ dependencies?: { firstContext?: Dependency | null } | null;
20
+ /** In profiling mode, which React is in where DevTools' hook was there as it loaded: this render, with what's under it. */
21
+ actualDuration?: number;
22
+ /** And its own part of it. */
23
+ selfBaseDuration?: number;
24
+ /** The component, or a host element's tag. */
25
+ type?: unknown;
26
+ /** Who wrote it, in development. */
27
+ _debugOwner?: Fiber | null;
28
+ /** A host element's DOM node. */
29
+ stateNode?: unknown;
30
+ }
31
+
32
+ /** A component that rendered in a commit: its timings as they were then, as the next render overwrites a fiber's. */
33
+ export interface RenderedFiber {
34
+ fiber: Fiber;
35
+ why: string;
36
+ ms?: number;
37
+ selfMs?: number;
38
+ }
39
+
40
+ /** A commit, as it was made: for whoever listens to them (a recording's timeline). */
41
+ export interface Rendering {
42
+ /** The whole commit's render, in milliseconds, where React times it. */
43
+ ms?: number;
44
+ /** React's scheduler priority for it. */
45
+ priority?: number;
46
+ rendered: RenderedFiber[];
47
+ }
48
+
49
+ interface Dependency {
50
+ memoizedValue?: unknown;
51
+ next?: Dependency | null;
52
+ }
53
+
54
+ /** A hook of a function component: React keeps them as a list. */
55
+ interface HookNode {
56
+ memoizedState?: unknown;
57
+ next?: HookNode | null;
58
+ }
59
+
60
+ /** Function, class, `forwardRef` and simple `memo` components: those that render (a `memo` wrapper's is its child). */
61
+ const COMPOSITE = new Set([0, 1, 11, 15]);
62
+ const CLASS = 1;
63
+ /** React's flag for a fiber whose component ran in this render, rather than bailed out. */
64
+ const PERFORMED_WORK = 1;
65
+ /** How many render times are kept per component, for how many were recent. */
66
+ const KEPT = 100;
67
+ /** What's recent: renders this long before a task, a loop or a burst. */
68
+ export const RECENT = 10_000;
69
+ /** How many changed props a reason names. */
70
+ const NAMED = 10;
71
+
72
+ interface Stats {
73
+ count: number;
74
+ at: number[];
75
+ lastMs?: number;
76
+ selfMs?: number;
77
+ why: string;
78
+ }
79
+
80
+ /** A hook's state that's an effect: a new one each render, which says nothing changed. */
81
+ const isEffect = (state: unknown) => typeof state === 'object' && state !== null && 'create' in state && 'tag' in state;
82
+
83
+ /** Why `next` rendered, `prev` being what it was: its props, its state, a context, or its parent rendering it again. */
84
+ export function whyOf(next: Fiber, prev: Fiber | null): string {
85
+ if (prev === null) return 'mounted';
86
+ const reasons: string[] = [];
87
+ if (next.memoizedProps !== prev.memoizedProps) {
88
+ const before = (prev.memoizedProps ?? {}) as Record<string, unknown>;
89
+ const now = (next.memoizedProps ?? {}) as Record<string, unknown>;
90
+ const keys = [...new Set([...Object.keys(before), ...Object.keys(now)])].filter((k) => !Object.is(before[k], now[k]));
91
+ if (keys.length > 0)
92
+ reasons.push(`props changed: ${keys.slice(0, NAMED).join(', ')}${keys.length > NAMED ? ` and ${keys.length - NAMED} more` : ''}`);
93
+ }
94
+ if (stateChanged(next, prev)) reasons.push('state changed');
95
+ if (contextChanged(next, prev)) reasons.push('context changed');
96
+ // Props of a new object with the same values: what a parent passes each time it renders.
97
+ return reasons.length > 0 ? reasons.join('; ') : 'its parent rendered';
98
+ }
99
+
100
+ function stateChanged(next: Fiber, prev: Fiber): boolean {
101
+ if (next.memoizedState === prev.memoizedState) return false;
102
+ if (next.tag === CLASS) return true;
103
+ let a = prev.memoizedState as HookNode | null | undefined;
104
+ let b = next.memoizedState as HookNode | null | undefined;
105
+ for (; a != null && b != null; a = a.next, b = b.next) {
106
+ if (Object.is(a.memoizedState, b.memoizedState) || isEffect(b.memoizedState)) continue;
107
+ return true;
108
+ }
109
+ return false;
110
+ }
111
+
112
+ function contextChanged(next: Fiber, prev: Fiber): boolean {
113
+ let a = prev.dependencies?.firstContext;
114
+ let b = next.dependencies?.firstContext;
115
+ for (; a != null && b != null; a = a.next, b = b.next) if (!Object.is(a.memoizedValue, b.memoizedValue)) return true;
116
+ return false;
117
+ }
118
+
119
+ /** The stats of every component the page rendered since it started being counted, read by its fiber, either of its two. */
120
+ export function renderStats(now: () => number = () => performance.now()) {
121
+ const stats = new WeakMap<Fiber, Stats>();
122
+
123
+ const listeners = new Set<(commit: Rendering) => void>();
124
+
125
+ const record = (fiber: Fiber, prev: Fiber | null): RenderedFiber => {
126
+ const kept = stats.get(fiber) ?? (fiber.alternate === null ? undefined : stats.get(fiber.alternate));
127
+ const entry: Stats = kept ?? { count: 0, at: [], why: '' };
128
+ entry.count++;
129
+ entry.at.push(now());
130
+ if (entry.at.length > KEPT) entry.at.shift();
131
+ entry.why = whyOf(fiber, prev);
132
+ if (typeof fiber.actualDuration === 'number') entry.lastMs = fiber.actualDuration;
133
+ if (typeof fiber.selfBaseDuration === 'number') entry.selfMs = fiber.selfBaseDuration;
134
+ stats.set(fiber, entry);
135
+ if (fiber.alternate !== null) stats.set(fiber.alternate, entry);
136
+ return {
137
+ fiber,
138
+ why: entry.why,
139
+ ...(typeof fiber.actualDuration === 'number' ? { ms: fiber.actualDuration } : {}),
140
+ ...(typeof fiber.selfBaseDuration === 'number' ? { selfMs: fiber.selfBaseDuration } : {}),
141
+ };
142
+ };
143
+
144
+ /** A committed tree, from its root's current fiber: what was rendered in it, and nothing React left as it was. */
145
+ const commit = (root: Fiber, priority?: number) => {
146
+ const rendered: RenderedFiber[] = [];
147
+ const stack: Fiber[] = [];
148
+ for (let child = root.child; child !== null; child = child.sibling) stack.push(child);
149
+ while (stack.length > 0) {
150
+ const fiber = stack.pop()!;
151
+ const prev = fiber.alternate;
152
+ if ((prev === null || ((fiber.flags ?? 0) & PERFORMED_WORK) !== 0) && COMPOSITE.has(fiber.tag)) rendered.push(record(fiber, prev));
153
+ // Children React didn't clone weren't rendered, nor anything under them.
154
+ if (prev !== null && fiber.child === prev.child) continue;
155
+ for (let child = fiber.child; child !== null; child = child.sibling) stack.push(child);
156
+ }
157
+ if (listeners.size === 0) return;
158
+ const made: Rendering = {
159
+ rendered,
160
+ ...(typeof root.actualDuration === 'number' ? { ms: root.actualDuration } : {}),
161
+ ...(priority === undefined ? {} : { priority }),
162
+ };
163
+ for (const listen of listeners) listen(made);
164
+ };
165
+
166
+ /** Hears each commit from now, until what's answered stops it. */
167
+ const subscribe = (listen: (commit: Rendering) => void) => {
168
+ listeners.add(listen);
169
+ return () => void listeners.delete(listen);
170
+ };
171
+
172
+ const read = (fiber: Fiber): Renders | undefined => {
173
+ const entry = stats.get(fiber) ?? (fiber.alternate === null ? undefined : stats.get(fiber.alternate));
174
+ if (entry === undefined) return undefined;
175
+ const at = now();
176
+ const round = (ms: number) => Math.round(ms * 100) / 100;
177
+ return {
178
+ count: entry.count,
179
+ recent: entry.at.filter((t) => at - t <= RECENT).length,
180
+ lastAgo: Math.round(at - entry.at.at(-1)!),
181
+ ...(entry.lastMs === undefined ? {} : { lastMs: round(entry.lastMs) }),
182
+ ...(entry.selfMs === undefined ? {} : { selfMs: round(entry.selfMs) }),
183
+ why: entry.why,
184
+ };
185
+ };
186
+
187
+ return { commit, read, subscribe };
188
+ }
189
+
190
+ /** DevTools' hook, as React calls it. */
191
+ interface Hook {
192
+ onCommitFiberRoot?: (id: number, root: { current: Fiber }, priority?: number, ...rest: unknown[]) => unknown;
193
+ }
194
+
195
+ /**
196
+ * Counts every commit from now on, where the page has DevTools' hook: answers what reads the counts and what hears
197
+ * each commit, or nothing where
198
+ * there's no hook (React then calls nothing, and keeps no timings either). The hook's own handler (React Refresh's,
199
+ * or the DevTools extension's) goes on being called first.
200
+ */
201
+ export function countRenders(target: { __REACT_DEVTOOLS_GLOBAL_HOOK__?: Hook } = globalThis as never) {
202
+ const hook = target.__REACT_DEVTOOLS_GLOBAL_HOOK__;
203
+ if (hook === undefined) return undefined;
204
+ const counts = renderStats();
205
+ let warned = false;
206
+ const before = hook.onCommitFiberRoot;
207
+ hook.onCommitFiberRoot = function (this: unknown, id, root, priority, ...rest) {
208
+ const answer = before?.call(this, id, root, priority, ...rest);
209
+ try {
210
+ counts.commit(root.current, priority);
211
+ } catch (e) {
212
+ // Never the page's render: a fiber of a React this doesn't know. Said once, not on each commit.
213
+ if (!warned) console.warn("deictic: renders aren't counted on this page", e);
214
+ warned = true;
215
+ }
216
+ return answer;
217
+ };
218
+ return { read: counts.read, subscribe: counts.subscribe };
219
+ }
@@ -0,0 +1,139 @@
1
+ /**
2
+ * A component's props, state and hooks as JSON: what a person would see of them in React's DevTools, for an agent
3
+ * to read in a file. Anything JSON can't hold says what it was, in brackets (`[function onClick]`, `[<Button>]`,
4
+ * `[circular]`), and what's too deep or too long is cut where it says so, as a page's values may be its whole store.
5
+ */
6
+ import { MASKED, sensitive } from '#src/plugins/network/mask.ts';
7
+
8
+ import type { Value } from './index.ts';
9
+
10
+ export interface Limits {
11
+ /** How deep into objects and arrays. */
12
+ depth: number;
13
+ /** How many keys of an object, and items of an array, a Map or a Set. */
14
+ items: number;
15
+ /** How long a string, in characters. */
16
+ text: number;
17
+ }
18
+
19
+ export const LIMITS: Limits = { depth: 5, items: 50, text: 1000 };
20
+
21
+ const ELEMENTS = new Set([Symbol.for('react.transitional.element'), Symbol.for('react.element')]);
22
+
23
+ /** A function's or a class's name, or nothing for one with none. */
24
+ const nameOf = (fn: unknown): string | undefined => {
25
+ if (typeof fn !== 'function' && (typeof fn !== 'object' || fn === null)) return undefined;
26
+ const { displayName, name } = fn as { displayName?: unknown; name?: unknown };
27
+ const found = displayName ?? name;
28
+ return typeof found === 'string' && found !== '' ? found : undefined;
29
+ };
30
+
31
+ /** `<Button>` for a React element: its tag, or its component's name through `memo` and `forwardRef`. */
32
+ function elementName(type: unknown): string {
33
+ if (typeof type === 'string') return type;
34
+ let at = type as { render?: unknown; type?: unknown } | null | undefined;
35
+ for (let depth = 0; depth < 4 && at !== null && at !== undefined; depth++) {
36
+ const name = nameOf(at);
37
+ if (name !== undefined) return name;
38
+ at = (at.render ?? at.type) as typeof at;
39
+ }
40
+ return 'Anonymous';
41
+ }
42
+
43
+ const cut = (text: string, limit: number) => (text.length > limit ? `${text.slice(0, limit)}… (${text.length - limit} more)` : text);
44
+
45
+ /** What a value read as, as JSON, its secrets blanked by their names (and `mask`'s, a part of a name in any case). */
46
+ export function serialize(value: unknown, mask: readonly string[] = [], limits: Limits = LIMITS): Value | undefined {
47
+ const above = new Set<object>();
48
+ const walk = (value: unknown, depth: number): Value | undefined => {
49
+ switch (typeof value) {
50
+ case 'undefined':
51
+ return undefined;
52
+ case 'boolean':
53
+ return value;
54
+ case 'number':
55
+ return Number.isFinite(value) ? value : `[${value}]`;
56
+ case 'bigint':
57
+ return `[${value}n]`;
58
+ case 'string':
59
+ return cut(value, limits.text);
60
+ case 'symbol':
61
+ return `[${value.toString()}]`;
62
+ case 'function':
63
+ return `[function${nameOf(value) === undefined ? '' : ` ${nameOf(value)}`}]`;
64
+ case 'object':
65
+ break;
66
+ }
67
+ if (value === null || typeof value !== 'object') return null;
68
+ const object = value as Record<PropertyKey, unknown>;
69
+ if (ELEMENTS.has(object.$$typeof as symbol)) return `[<${elementName(object.type)}>]`;
70
+ // A DOM node, told by its shape: `instanceof Node` is another window's in an iframe.
71
+ if (typeof object.nodeType === 'number' && typeof object.nodeName === 'string') {
72
+ const { nodeType, nodeName } = object as { nodeType: number; nodeName: string };
73
+ return nodeType === 1 ? `[<${nodeName.toLowerCase()}>]` : `[${nodeName}]`;
74
+ }
75
+ if (typeof window !== 'undefined' && value === window) return '[window]';
76
+ if (value instanceof Date) return Number.isNaN(value.getTime()) ? '[Invalid Date]' : value.toISOString();
77
+ if (value instanceof RegExp) return `[${value.toString()}]`;
78
+ if (value instanceof Error) return `[${value.name}: ${cut(value.message, limits.text)}]`;
79
+ if (typeof object.then === 'function') return '[Promise]';
80
+ if (ArrayBuffer.isView(value) || value instanceof ArrayBuffer)
81
+ return `[${nameOf(value.constructor) ?? 'Buffer'}(${value.byteLength} bytes)]`;
82
+ if (above.has(value)) return '[circular]';
83
+ const many = Array.isArray(value) ? value.length : value instanceof Map || value instanceof Set ? value.size : undefined;
84
+ if (depth >= limits.depth) {
85
+ if (Array.isArray(value)) return `[Array(${value.length})]`;
86
+ if (value instanceof Map) return `[Map(${value.size})]`;
87
+ if (value instanceof Set) return `[Set(${value.size})]`;
88
+ return `[${nameOf(value.constructor) ?? 'Object'}]`;
89
+ }
90
+ above.add(value);
91
+ try {
92
+ const items = (entries: Iterable<unknown>, of: (item: unknown) => Value) => {
93
+ const out: Value[] = [];
94
+ for (const item of entries) {
95
+ if (out.length === limits.items) {
96
+ out.push(`[… ${(many ?? 0) - limits.items} more]`);
97
+ break;
98
+ }
99
+ out.push(of(item));
100
+ }
101
+ return out;
102
+ };
103
+ // Undefined, in an array, is a hole JSON writes as null: said, so it isn't read as null.
104
+ const inside = (item: unknown) => walk(item, depth + 1) ?? '[undefined]';
105
+ if (Array.isArray(value)) return items(value, inside);
106
+ if (value instanceof Set) return { [`Set(${value.size})`]: items(value, inside) };
107
+ if (value instanceof Map) {
108
+ const pair = (entry: unknown) => {
109
+ const [key, item] = entry as [unknown, unknown];
110
+ return [inside(key), typeof key === 'string' && sensitive(key, mask) ? MASKED : inside(item)];
111
+ };
112
+ return { [`Map(${value.size})`]: items(value, pair) };
113
+ }
114
+ const out: { [key: string]: Value } = {};
115
+ // A class's instance says which, as DevTools does; a plain object, or one of no prototype, doesn't.
116
+ const proto = Object.getPrototypeOf(value) as object | null;
117
+ const made = proto === null || proto === Object.prototype ? undefined : nameOf(proto.constructor);
118
+ if (made !== undefined) out['@'] = made;
119
+ const keys = Object.keys(value);
120
+ for (const key of keys.slice(0, limits.items)) {
121
+ let item: unknown;
122
+ try {
123
+ item = object[key];
124
+ } catch {
125
+ // A getter that throws.
126
+ out[key] = '[unreadable]';
127
+ continue;
128
+ }
129
+ const read = sensitive(key, mask) ? MASKED : walk(item, depth + 1);
130
+ if (read !== undefined) out[key] = read;
131
+ }
132
+ if (keys.length > limits.items) out['…'] = `${keys.length - limits.items} more keys`;
133
+ return out;
134
+ } finally {
135
+ above.delete(value);
136
+ }
137
+ };
138
+ return walk(value, 0);
139
+ }