deictic 0.8.1 → 0.10.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 (128) hide show
  1. package/API.md +81 -17
  2. package/README.md +1 -1
  3. package/dist/annotations/client.js +1 -1
  4. package/dist/bun.d.ts.map +1 -1
  5. package/dist/bun.js +26 -8
  6. package/dist/bun.js.map +1 -1
  7. package/dist/cli.js +1 -1
  8. package/dist/cli.js.map +1 -1
  9. package/dist/client/index.d.ts +13 -13
  10. package/dist/client/index.d.ts.map +1 -1
  11. package/dist/client/index.js +19 -7
  12. package/dist/client/index.js.map +1 -1
  13. package/dist/next.d.ts.map +1 -1
  14. package/dist/next.js +45 -25
  15. package/dist/next.js.map +1 -1
  16. package/dist/react/client.d.ts +19 -0
  17. package/dist/react/client.d.ts.map +1 -0
  18. package/dist/react/client.js +504 -0
  19. package/dist/react/client.js.map +1 -0
  20. package/dist/react/index.d.ts +2 -0
  21. package/dist/react/index.js +1 -0
  22. package/dist/recommended/index.d.ts +15 -7
  23. package/dist/recommended/index.d.ts.map +1 -1
  24. package/dist/recommended/index.js +1 -1
  25. package/dist/recordings/client.d.ts.map +1 -1
  26. package/dist/recordings/client.js +48 -5
  27. package/dist/recordings/client.js.map +1 -1
  28. package/dist/screenshots/client.d.ts +9 -1
  29. package/dist/screenshots/client.d.ts.map +1 -1
  30. package/dist/screenshots/rrweb.d.ts +0 -6
  31. package/dist/screenshots/rrweb.d.ts.map +1 -1
  32. package/dist/screenshots/rrweb.js +46 -12
  33. package/dist/screenshots/rrweb.js.map +1 -1
  34. package/dist/shared/board.js +1 -1
  35. package/dist/shared/client.js +44 -2
  36. package/dist/shared/client.js.map +1 -1
  37. package/dist/shared/dom.js +7 -1
  38. package/dist/shared/dom.js.map +1 -1
  39. package/dist/shared/drawer.js +1 -1
  40. package/dist/shared/endpoints.js +15 -4
  41. package/dist/shared/endpoints.js.map +1 -1
  42. package/dist/shared/index.d.ts +11 -0
  43. package/dist/shared/index.d.ts.map +1 -1
  44. package/dist/shared/index10.d.ts +70 -0
  45. package/dist/shared/index10.d.ts.map +1 -0
  46. package/dist/shared/index3.d.ts +11 -0
  47. package/dist/shared/index3.d.ts.map +1 -1
  48. package/dist/shared/index7.d.ts +92 -312
  49. package/dist/shared/index7.d.ts.map +1 -1
  50. package/dist/shared/index8.d.ts +324 -47
  51. package/dist/shared/index8.d.ts.map +1 -1
  52. package/dist/shared/index9.d.ts +45 -63
  53. package/dist/shared/index9.d.ts.map +1 -1
  54. package/dist/shared/init.js +15 -11
  55. package/dist/shared/init.js.map +1 -1
  56. package/dist/shared/integration.d.ts +6 -0
  57. package/dist/shared/integration.d.ts.map +1 -1
  58. package/dist/shared/integration.js +28 -1
  59. package/dist/shared/integration.js.map +1 -1
  60. package/dist/shared/marks.js +7 -1
  61. package/dist/shared/marks.js.map +1 -1
  62. package/dist/shared/package.js +3 -1
  63. package/dist/shared/packages.js +1 -1
  64. package/dist/shared/playwright.js +39 -1
  65. package/dist/shared/playwright.js.map +1 -1
  66. package/dist/shared/react.js +25 -0
  67. package/dist/shared/react.js.map +1 -0
  68. package/dist/shared/recommended.js +6 -3
  69. package/dist/shared/recommended.js.map +1 -1
  70. package/dist/shared/recording.js +80 -3
  71. package/dist/shared/recording.js.map +1 -1
  72. package/dist/shared/recordings.js +30 -2
  73. package/dist/shared/recordings.js.map +1 -1
  74. package/dist/shared/screenshots.js.map +1 -1
  75. package/dist/shared/src.js.map +1 -1
  76. package/dist/shared/task.js +1 -0
  77. package/dist/shared/task.js.map +1 -1
  78. package/dist/shared/tasks.js +11 -0
  79. package/dist/shared/tasks.js.map +1 -1
  80. package/dist/shared/vite.d.ts +1 -1
  81. package/dist/shared/vite.d.ts.map +1 -1
  82. package/dist/shared/vite.js +28 -10
  83. package/dist/shared/vite.js.map +1 -1
  84. package/dist/tailwind/client.d.ts +1 -1
  85. package/dist/tailwind/index.d.ts +1 -1
  86. package/dist/tasks/client.d.ts +1 -1
  87. package/dist/tasks/client.js +45 -19
  88. package/dist/tasks/client.js.map +1 -1
  89. package/dist/tasks/index.d.ts +1 -1
  90. package/dist/voice/client.d.ts +1 -1
  91. package/dist/voice/client.js +1 -1
  92. package/dist/voice/index.d.ts +1 -1
  93. package/dist/webpack.d.ts +4 -0
  94. package/dist/webpack.d.ts.map +1 -1
  95. package/dist/webpack.js +37 -15
  96. package/dist/webpack.js.map +1 -1
  97. package/package.json +25 -1
  98. package/src/bun.ts +32 -8
  99. package/src/cli/bun.ts +2 -2
  100. package/src/cli/init.ts +14 -9
  101. package/src/cli/recording.ts +90 -4
  102. package/src/cli/task.ts +4 -0
  103. package/src/cli.ts +13 -6
  104. package/src/client/dom.ts +14 -0
  105. package/src/client/index.ts +25 -14
  106. package/src/index.ts +11 -0
  107. package/src/next.ts +34 -15
  108. package/src/plugins/react/client.ts +162 -0
  109. package/src/plugins/react/index.ts +130 -0
  110. package/src/plugins/react/renders.ts +219 -0
  111. package/src/plugins/react/serialize.ts +139 -0
  112. package/src/plugins/react/timeline.ts +143 -0
  113. package/src/plugins/recommended/index.ts +17 -5
  114. package/src/plugins/recordings/client.ts +64 -4
  115. package/src/plugins/recordings/marks.ts +7 -0
  116. package/src/plugins/recordings/replay.ts +30 -2
  117. package/src/plugins/screenshots/client.ts +42 -2
  118. package/src/plugins/screenshots/index.ts +11 -0
  119. package/src/plugins/screenshots/playwright.ts +65 -1
  120. package/src/plugins/screenshots/rrweb.ts +55 -28
  121. package/src/plugins/screenshots/states.ts +26 -0
  122. package/src/plugins/tasks/client.ts +41 -6
  123. package/src/plugins/tasks/composer.ts +24 -7
  124. package/src/plugins/tasks/index.ts +16 -2
  125. package/src/tools/integration.ts +33 -0
  126. package/src/tools/source.ts +14 -2
  127. package/src/vite.ts +31 -10
  128. package/src/webpack.ts +48 -16
@@ -24,7 +24,7 @@ import { gestureOf, type Shortcut } from '#src/shortcut.ts';
24
24
 
25
25
  import { dropAway, keepAway, keptAway } from './away.ts';
26
26
  import { named, tell } from './component.ts';
27
- import { ATTRIBUTE, div, nameOf, reduced, sameAs, targetOf } from './dom.ts';
27
+ import { ATTRIBUTE, div, nameOf, POPUP_CLOSED, POPUP_OPENED, type PopupOpened, reduced, sameAs, targetOf } from './dom.ts';
28
28
  import { drawerIn } from './drawer.ts';
29
29
  import { openLightbox } from './lightbox.ts';
30
30
  import { CLEAR, type Lighting, spotlight, spotOf } from './lighting.ts';
@@ -98,19 +98,8 @@ interface Started {
98
98
 
99
99
  let started: Started | undefined;
100
100
 
101
- /**
102
- * What the page hears on `window` as the popup opens over it on an element (its `detail` a `PopupOpened`) and as
103
- * it closes: for a page that moves on its own to hold still meanwhile, as deictic's site does. Not for one pinned.
104
- */
105
- export const POPUP_OPENED = 'deictic:open';
106
- export const POPUP_CLOSED = 'deictic:close';
107
-
108
- export interface PopupOpened {
109
- /** The element it's open on. */
110
- element: Element;
111
- /** The plugin whose tab it opened at. */
112
- tab: string;
113
- }
101
+ // The events the page hears as the popup opens and closes: kept beside the mark, where a plugin's page half reads them.
102
+ export { POPUP_CLOSED, POPUP_OPENED, type PopupOpened } from './dom.ts';
114
103
 
115
104
  /**
116
105
  * Opens the popup over the page on `element`, as deictic's own shortcut does: at `tab` (a plugin's name), or at the
@@ -242,6 +231,10 @@ export function start({ base, shortcut: own, plugins: given, server }: StartOpti
242
231
  use: (other) => apis.get(other) as never,
243
232
  request: (route, init) => send(`${base}__deictic/plugins/${name}/${route}`, init),
244
233
  report: (problem) => report({ ...problem, plugin: name }),
234
+ edit: async ({ file, line, column }) => {
235
+ const res = await send(`${base}__deictic/open?${new URLSearchParams({ file, line: String(line), column: String(column) })}`);
236
+ if (!res.ok) throw new Error(await res.text());
237
+ },
245
238
  // Not from under something unsaved, which a press on the page wouldn't close either: its button shakes.
246
239
  open: (plugin, element, at) => panel?.guard() !== true && openAt(plugin, element, at),
247
240
  lightbox: (items, options) => openLightbox(root, items, options),
@@ -430,6 +423,24 @@ export function start({ base, shortcut: own, plugins: given, server }: StartOpti
430
423
  );
431
424
  let press = {};
432
425
  let opened: object | undefined;
426
+ // The page as it is under the press, for whoever keeps it (`pressed`): before the page's own handlers, which may
427
+ // close what was open, and before the popup takes the pointer and the focus.
428
+ window.addEventListener(
429
+ 'pointerdown',
430
+ (e) => {
431
+ if (e.composedPath().includes(host) || pressedBy(e) === undefined) return;
432
+ const hit = hitAt(e.clientX, e.clientY);
433
+ if (hit === undefined) return;
434
+ for (const { plugin } of given) {
435
+ try {
436
+ plugin.pressed?.(contextOf(plugin.name), hit.el);
437
+ } catch (e) {
438
+ report(failed(plugin.name, 'keep what the page showed as it was pressed', e));
439
+ }
440
+ }
441
+ },
442
+ true,
443
+ );
433
444
  // Alt-click on a link would otherwise download it, and on a field focus it.
434
445
  window.addEventListener(
435
446
  'mousedown',
package/src/index.ts CHANGED
@@ -282,6 +282,11 @@ export interface ClientContext {
282
282
  request: (route: string, init?: RequestInit) => Promise<Response>;
283
283
  /** Says a problem of the plugin's own to the dev server, as the server half's `report` does: its `plugin` is this one. */
284
284
  report: (problem: Problem) => void;
285
+ /**
286
+ * Opens a place in a file under the root in the editor, as the popup's own link opens the element's: through the
287
+ * dev server, or what answers in its place (`Standalone`). Rejects with why it couldn't.
288
+ */
289
+ edit: (place: Loc) => Promise<void>;
285
290
  /**
286
291
  * Opens the popup on an element at a plugin's tab, as its shortcut would, or with `at` on a spot in it: the
287
292
  * popup is then beside the spot, which is what's lit, and the tab's context has it. An element rendered again
@@ -401,6 +406,12 @@ export interface ClientPlugin<Model = unknown, Op = unknown, Api = unknown> {
401
406
  * plugin pins each task where its element is. Answers what takes it away.
402
407
  */
403
408
  pointing?(context: ClientContext): () => void;
409
+ /**
410
+ * A shortcut's press on a marked element, before the page hears it and before the popup opens: the page as the
411
+ * person saw it, a tooltip still open under the pointer, a menu still focused. Called as the press goes down, so
412
+ * it must be quick; the screenshots plugin keeps what a shot needs here, and renders it later.
413
+ */
414
+ pressed?(context: ClientContext, element: Element): void;
404
415
  /** Draws into `panel`, inside deictic's shadow root. Returns what to undo on the page when the panel closes. */
405
416
  mount?: (panel: HTMLElement, context: PanelContext<Model, Op>) => (() => void) | void;
406
417
  }
package/src/next.ts CHANGED
@@ -14,6 +14,11 @@
14
14
  *
15
15
  * Both bundlers' rules are always set, as the config can't tell which will run: Next refuses a Turbopack
16
16
  * build whose config has a `webpack` key only where it has no `turbopack` one, and ours always does.
17
+ *
18
+ * A config may be wrapped more than once: by the app, and by a package that adds its own plugin (`defaults`), as
19
+ * `withProsebook` does. The config each returns carries the options it was given (`GIVEN`), so the next one out adds
20
+ * no rules of its own: it writes the client again with all of them merged (`merge`), and the endpoints, made at the
21
+ * first request, load them all.
17
22
  */
18
23
  import { createServer } from 'node:http';
19
24
  import type { AddressInfo } from 'node:net';
@@ -22,7 +27,7 @@ import { resolve } from 'node:path';
22
27
  import type { ServerPlugin } from './index.ts';
23
28
  import type { LoaderOptions } from './loader.ts';
24
29
  import { endpoints, nodeMiddleware, redirect } from './tools/endpoints.ts';
25
- import { beside, type DeicticOptions, prepare, writeClient } from './tools/integration.ts';
30
+ import { beside, type DeicticOptions, merge, prepare, writeClient } from './tools/integration.ts';
26
31
  import { JSX } from './tools/locate.ts';
27
32
 
28
33
  export interface DeicticNextOptions extends DeicticOptions {
@@ -45,6 +50,10 @@ const GLOBS = ['*.tsx', '*.jsx', '*.js'];
45
50
 
46
51
  // Next loads its config more than once in a process: one endpoints server per project is enough.
47
52
  const serving = new Map<string, Promise<number>>();
53
+ // Each project's plugins as its config last merged them, for its endpoints to load at their first request.
54
+ const loaded = new Map<string, ServerPlugin[]>();
55
+ /** On a config a `withDeictic` returned: the options of every one it went through. */
56
+ const GIVEN = Symbol.for('deictic.given');
48
57
 
49
58
  /**
50
59
  * Wraps the Next config: `export default withDeictic({ ... }, { plugins: [tailwind()] })`. Takes the
@@ -55,18 +64,25 @@ export function withDeictic<C extends object>(
55
64
  options: DeicticNextOptions = {},
56
65
  ): (phase: string, context: { defaultConfig: C }) => Promise<C> {
57
66
  // Now, so a wrong set of plugins stops the dev server as it starts, rather than the page.
58
- const { plugins, shortcut } = prepare(options);
67
+ prepare(options);
59
68
  return async (phase, context) => {
60
69
  const resolved = typeof next === 'function' ? await next(phase, context) : next;
61
70
  if (phase !== DEV) return resolved;
62
- const root = resolve(options.root ?? process.cwd());
71
+ const before = (resolved as { [GIVEN]?: DeicticNextOptions[] })[GIVEN];
72
+ const given = [...(before ?? []), options];
73
+ const merged = given.length === 1 ? options : merge(given);
74
+ const { plugins, shortcut } = prepare(merged);
75
+ const root = resolve(merged.root ?? process.cwd());
63
76
  const base = `${(resolved as { basePath?: string }).basePath ?? ''}/`;
64
77
  const client = writeClient(root, plugins, base, shortcut);
78
+ loaded.set(root, plugins);
79
+ // Wrapped already: the rules and the rewrite are there, and only the client and the plugins change.
80
+ if (before !== undefined) return { ...resolved, [GIVEN]: given };
65
81
  const rules: [string, Rule][] = GLOBS.flatMap((glob) => [
66
82
  [glob, { condition: { all: ['browser', { not: 'foreign' }] }, loaders: [{ loader: loaderPath, options: { root, client } }] }],
67
83
  [glob, { condition: { all: [{ not: 'browser' }, { not: 'foreign' }] }, loaders: [{ loader: loaderPath, options: { root } }] }],
68
84
  ]);
69
- return withRewrite(withWebpack(withRules(resolved, rules), root, client), await serve(root, plugins, base));
85
+ return { ...withRewrite(withWebpack(withRules(resolved, rules), root, client), await serve(root, base)), [GIVEN]: given };
70
86
  };
71
87
  }
72
88
 
@@ -102,20 +118,23 @@ function withRewrite<C extends object>(resolved: C, port: number): C {
102
118
  }
103
119
 
104
120
  /** Serves the endpoints on a free local port, for as long as the process lives. */
105
- function serve(root: string, plugins: ServerPlugin[], base: string): Promise<number> {
121
+ function serve(root: string, base: string): Promise<number> {
106
122
  const running = serving.get(root);
107
123
  if (running !== undefined) return running;
108
- const handle = endpoints({
109
- root,
110
- plugins,
111
- // Rewritten from under the base, but served at the root of their own server.
112
- base: '/',
113
- open: (path, { line, column }) =>
114
- redirect(`${base}__nextjs_launch-editor?${new URLSearchParams({ file: path, line1: String(line), column1: String(column) })}`),
115
- });
116
- const middleware = nodeMiddleware(handle);
124
+ let middleware: ReturnType<typeof nodeMiddleware> | undefined;
125
+ const made = () =>
126
+ (middleware ??= nodeMiddleware(
127
+ endpoints({
128
+ root,
129
+ plugins: loaded.get(root) ?? [],
130
+ // Rewritten from under the base, but served at the root of their own server.
131
+ base: '/',
132
+ open: (path, { line, column }) =>
133
+ redirect(`${base}__nextjs_launch-editor?${new URLSearchParams({ file: path, line1: String(line), column1: String(column) })}`),
134
+ }),
135
+ ));
117
136
  const server = createServer((req, res) =>
118
- middleware(req, res, () => {
137
+ made()(req, res, () => {
119
138
  res.statusCode = 404;
120
139
  res.end();
121
140
  }),
@@ -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;