deictic 0.2.0 → 0.3.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 +303 -0
  2. package/README.md +56 -127
  3. package/dist/client/index.d.ts.map +1 -1
  4. package/dist/client/index.js +117 -7
  5. package/dist/client/index.js.map +1 -1
  6. package/dist/index.js.map +1 -1
  7. package/dist/logs/client.d.ts +4 -0
  8. package/dist/logs/client.d.ts.map +1 -0
  9. package/dist/logs/client.js +16 -0
  10. package/dist/logs/client.js.map +1 -0
  11. package/dist/logs/index.d.ts +18 -0
  12. package/dist/logs/index.d.ts.map +1 -0
  13. package/dist/logs/index.js +21 -0
  14. package/dist/logs/index.js.map +1 -0
  15. package/dist/network/client.d.ts +4 -0
  16. package/dist/network/client.d.ts.map +1 -0
  17. package/dist/network/client.js +29 -0
  18. package/dist/network/client.js.map +1 -0
  19. package/dist/network/index.d.ts +2 -0
  20. package/dist/network/index.js +39 -0
  21. package/dist/network/index.js.map +1 -0
  22. package/dist/recommended/index.d.ts +13 -3
  23. package/dist/recommended/index.d.ts.map +1 -1
  24. package/dist/recommended/index.js +8 -1
  25. package/dist/recommended/index.js.map +1 -1
  26. package/dist/recordings/client.d.ts +1 -1
  27. package/dist/recordings/client.d.ts.map +1 -1
  28. package/dist/recordings/client.js +175 -46
  29. package/dist/recordings/client.js.map +1 -1
  30. package/dist/recordings/index.d.ts +2 -2
  31. package/dist/screenshots/client.d.ts +6 -0
  32. package/dist/screenshots/client.d.ts.map +1 -1
  33. package/dist/screenshots/client.js +34 -2
  34. package/dist/screenshots/client.js.map +1 -1
  35. package/dist/screenshots/dom.d.ts.map +1 -1
  36. package/dist/screenshots/dom.js +1 -28
  37. package/dist/screenshots/dom.js.map +1 -1
  38. package/dist/screenshots/index.js.map +1 -1
  39. package/dist/screenshots/rrweb.d.ts +1 -1
  40. package/dist/screenshots/rrweb.js +5 -1
  41. package/dist/screenshots/rrweb.js.map +1 -1
  42. package/dist/shared/index.d.ts +14 -2
  43. package/dist/shared/index.d.ts.map +1 -1
  44. package/dist/shared/index2.d.ts +2 -0
  45. package/dist/shared/index2.d.ts.map +1 -1
  46. package/dist/shared/index3.d.ts +29 -3
  47. package/dist/shared/index3.d.ts.map +1 -1
  48. package/dist/shared/index4.d.ts +52 -172
  49. package/dist/shared/index4.d.ts.map +1 -1
  50. package/dist/shared/index5.d.ts +208 -58
  51. package/dist/shared/index5.d.ts.map +1 -1
  52. package/dist/shared/index6.d.ts +70 -0
  53. package/dist/shared/index6.d.ts.map +1 -0
  54. package/dist/shared/marks.js +6 -1
  55. package/dist/shared/marks.js.map +1 -1
  56. package/dist/shared/mask.js +107 -0
  57. package/dist/shared/mask.js.map +1 -0
  58. package/dist/shared/playwright.js +19 -4
  59. package/dist/shared/playwright.js.map +1 -1
  60. package/dist/shared/recordings.js +219 -28
  61. package/dist/shared/recordings.js.map +1 -1
  62. package/dist/shared/tasks.js +145 -34
  63. package/dist/shared/tasks.js.map +1 -1
  64. package/dist/tailwind/client.d.ts +1 -1
  65. package/dist/tailwind/index.d.ts +1 -1
  66. package/dist/tasks/client.d.ts +1 -1
  67. package/dist/tasks/client.d.ts.map +1 -1
  68. package/dist/tasks/client.js +271 -56
  69. package/dist/tasks/client.js.map +1 -1
  70. package/dist/tasks/index.d.ts +2 -2
  71. package/dist/voice/client.d.ts.map +1 -1
  72. package/dist/voice/client.js +35 -14
  73. package/dist/voice/client.js.map +1 -1
  74. package/dist/voice/index.d.ts +6 -1
  75. package/dist/voice/index.d.ts.map +1 -1
  76. package/dist/voice/index.js +12 -2
  77. package/dist/voice/index.js.map +1 -1
  78. package/package.json +41 -2
  79. package/skills/deictic/SKILL.md +20 -14
  80. package/skills/deictic/references/install.md +18 -11
  81. package/skills/deictic/references/recordings.md +29 -0
  82. package/skills/deictic/references/tasks.md +49 -21
  83. package/skills/deictic/references/watch.md +38 -11
  84. package/skills/deictic/scripts/lib.mjs +69 -3
  85. package/skills/deictic/scripts/recording.mjs +84 -4
  86. package/skills/deictic/scripts/task.mjs +36 -7
  87. package/skills/deictic/scripts/vb.mjs +12 -0
  88. package/skills/deictic/scripts/watch.mjs +74 -10
  89. package/src/client/away.ts +105 -0
  90. package/src/client/index.ts +40 -9
  91. package/src/client/style.ts +1 -0
  92. package/src/index.ts +14 -2
  93. package/src/plugins/logs/client.ts +18 -0
  94. package/src/plugins/logs/index.ts +55 -0
  95. package/src/plugins/network/client.ts +30 -0
  96. package/src/plugins/network/index.ts +69 -0
  97. package/src/plugins/network/mask.ts +133 -0
  98. package/src/plugins/recommended/index.ts +14 -1
  99. package/src/plugins/recordings/client.ts +219 -40
  100. package/src/plugins/recordings/index.ts +108 -23
  101. package/src/plugins/recordings/marks.ts +6 -0
  102. package/src/plugins/recordings/replay.ts +127 -4
  103. package/src/plugins/screenshots/client.ts +35 -0
  104. package/src/plugins/screenshots/dom.ts +1 -32
  105. package/src/plugins/screenshots/index.ts +2 -0
  106. package/src/plugins/screenshots/playwright.ts +15 -4
  107. package/src/plugins/screenshots/rrweb.ts +2 -1
  108. package/src/plugins/tasks/client.ts +273 -41
  109. package/src/plugins/tasks/index.ts +155 -39
  110. package/src/plugins/tasks/watchers.ts +36 -0
  111. package/src/plugins/voice/client.ts +33 -11
  112. package/src/plugins/voice/index.ts +21 -4
@@ -6,11 +6,17 @@
6
6
  *
7
7
  * Recordings are kept under `.deictic/recordings`, the latest `keep`, as JSON: rrweb's
8
8
  * events, with the page, its viewport and how long it ran. `replay/<id>` plays one back in the browser.
9
+ *
10
+ * The page sends one as it goes (`begin`, then `part/<id>` each second or so, then `end/<id>` or `discard/<id>`),
11
+ * not whole at the end, so it outlasts the page: after a reload, or a link to another page of the site, the next
12
+ * page carries on with the same recording, which then holds each page in turn.
9
13
  */
10
- import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
14
+ import { appendFileSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
11
15
  import { createRequire } from 'node:module';
12
16
  import { dirname, join, resolve } from 'node:path';
13
17
 
18
+ import type { record } from 'rrweb';
19
+
14
20
  import { definePlugin } from '#src/index.ts';
15
21
  import type { Masking, ResolvedMasking } from '#src/plugins/screenshots/index.ts';
16
22
  import { keptIn } from '#src/tools/kept.ts';
@@ -40,11 +46,26 @@ export interface VoiceClip {
40
46
  export interface Recorder {
41
47
  /**
42
48
  * Records the page, with the toolbar, until Stop: answers the recording, kept by the dev server, or
43
- * nothing when it's discarded. Rejects while another is going, or when it couldn't be kept.
49
+ * nothing when it's discarded. Rejects while another is going, or when it couldn't be kept. A page load
50
+ * doesn't end it: the next page of the site carries on, and `going` there answers what this would have.
44
51
  */
45
52
  record(): Promise<Recording | undefined>;
46
53
  /** Whether one is going. */
47
54
  recording(): boolean;
55
+ /** The one going, as `record` answers it: also one a page before this started, carried on here. */
56
+ going(): Promise<Recording | undefined> | undefined;
57
+ }
58
+
59
+ /** A plugin of rrweb's own, as its `record` takes them: what puts more than the page in a recording. */
60
+ export type RecordPlugin = NonNullable<NonNullable<Parameters<typeof record>[0]>['plugins']>[number];
61
+
62
+ /**
63
+ * What a plugin that adds to recordings answers in the page, under its name (`logs` and `network` do): the
64
+ * recorder asks each it knows for its rrweb plugin as a recording starts, so nothing listens before, or after it stops.
65
+ */
66
+ export interface Recorded {
67
+ /** `sinceLoad`: the recording was going as this page loaded, so what the page did before now is its too. */
68
+ plugin(from: { sinceLoad: boolean }): Promise<RecordPlugin>;
48
69
  }
49
70
 
50
71
  /** The server's half, for other plugins' server halves. */
@@ -53,8 +74,12 @@ export interface Recordings {
53
74
  read(id: string): { data: Uint8Array<ArrayBuffer>; name: string; type: 'application/json' } | undefined;
54
75
  }
55
76
 
56
- /** What the page sends, and what's kept: rrweb's events and what they can't say. */
77
+ /** What a recording says as it begins: all of a `Kept` that's known then. */
78
+ export type Meta = Omit<Kept, 'events' | 'duration' | 'voice'>;
79
+
80
+ /** What's kept: rrweb's events and what they can't say. */
57
81
  export interface Kept {
82
+ /** The page it started on. One that went on to others has each in its events, as rrweb's own: a `Meta`, then a snapshot. */
58
83
  page: string;
59
84
  viewport: { width: number; height: number };
60
85
  /**
@@ -83,11 +108,18 @@ export interface RecordingsOptions extends Masking {
83
108
  keep?: number;
84
109
  /** Where they're kept, from the project's root: `.deictic/recordings` by default. */
85
110
  dir?: string;
111
+ /**
112
+ * What a `<canvas>` draws (a chart, a map, WebGL), which is no part of the page's markup: a picture of each
113
+ * canvas that changed, `fps` times a second, 2 by default. `false` for none, and a canvas replays blank.
114
+ */
115
+ canvas?: boolean | { fps?: number };
86
116
  }
87
117
 
88
118
  const ID = /^[a-z0-9]+-[a-z0-9]+$/;
89
119
  /** What one recording may weigh: minutes of a busy page are a few MB. */
90
120
  const MAX = 50 * 1024 * 1024;
121
+ /** How long a recording nobody ended keeps its parts, in milliseconds. */
122
+ const STALE = 24 * 60 * 60 * 1000;
91
123
 
92
124
  /** rrweb's player (`rrweb-player`), served to the replay page: its build for a script tag, and its styles. */
93
125
  const player = (file: string) => {
@@ -108,16 +140,45 @@ export function recordings(options: RecordingsOptions = {}) {
108
140
  if (!ID.test(id) || !existsSync(pathOf(id))) return undefined;
109
141
  return { data: new Uint8Array(readFileSync(pathOf(id))), name: `recording-${id}.json`, type: 'application/json' };
110
142
  };
111
- const keepRecording = (data: Uint8Array) => {
143
+ const partOf = (id: string) => join(dir, `${id}.part`);
144
+ /** The recording going on that a request names, as its last segment: its ID, or the answer that there's none. */
145
+ const going = (req: Request): string | Response => {
146
+ const id = new URL(req.url).pathname.split('/').at(-1) ?? '';
147
+ if (ID.test(id) && existsSync(partOf(id))) return id;
148
+ return Response.json({ problem: `no recording ${id} is going any more: record again` }, { status: 404 });
149
+ };
150
+ const json = async <T>(req: Request): Promise<T | undefined> => {
151
+ try {
152
+ return (await req.json()) as T;
153
+ } catch {
154
+ return undefined;
155
+ }
156
+ };
157
+ /** A recording begun: its ID, and the file its parts are added to, which starts with what `Kept` says besides the events. */
158
+ const begin = (meta: Meta) => {
112
159
  // Sorts by when it was made, which is what pruning keeps by: the count orders two in one millisecond.
113
160
  const id = `${Date.now().toString(36).padStart(9, '0')}${(taken++ % 1296).toString(36).padStart(2, '0')}-${crypto.randomUUID().slice(0, 8)}`;
114
161
  mkdirSync(dir, { recursive: true });
115
- writeFileSync(pathOf(id), data);
116
- const kept = readdirSync(dir)
162
+ // One nobody ended, as its tab was closed: gone a day on.
163
+ for (const f of readdirSync(dir)) if (f.endsWith('.part') && Date.now() - statSync(join(dir, f)).mtimeMs > STALE) rmSync(join(dir, f));
164
+
165
+ writeFileSync(partOf(id), `${JSON.stringify(meta)}\n`);
166
+ return id;
167
+ };
168
+ /** The parts as one recording, in their order whatever order they came in: a page's last may overtake the one before. */
169
+ const end = (id: string, last: Pick<Kept, 'duration' | 'voice'>): boolean => {
170
+ const [meta, ...lines] = readFileSync(partOf(id), 'utf8').trimEnd().split('\n');
171
+ const parts = lines.map((line) => JSON.parse(line) as { seq: number; events: unknown[] });
172
+ const events = parts.toSorted((a, b) => a.seq - b.seq).flatMap((part) => part.events);
173
+ rmSync(partOf(id));
174
+ if (events.length === 0) return false;
175
+ const kept: Kept = { ...(JSON.parse(meta!) as Meta), ...last, events };
176
+ writeFileSync(pathOf(id), JSON.stringify(kept));
177
+ const all = readdirSync(dir)
117
178
  .filter((f) => f.endsWith('.json'))
118
179
  .toSorted();
119
- for (const old of kept.slice(0, Math.max(0, kept.length - keep))) rmSync(join(dir, old));
120
- return id;
180
+ for (const old of all.slice(0, Math.max(0, all.length - keep))) rmSync(join(dir, old));
181
+ return true;
121
182
  };
122
183
  const file = (path: string, type: string) => {
123
184
  if (!existsSync(path)) return new Response('rrweb-player is missing: add it to your devDependencies', { status: 404 });
@@ -135,28 +196,52 @@ export function recordings(options: RecordingsOptions = {}) {
135
196
  maskTextSelector: options.maskTextSelector,
136
197
  maskAllInputs: options.maskAllInputs ?? false,
137
198
  } satisfies ResolvedMasking,
199
+ canvas: options.canvas === false ? false : { fps: (options.canvas === true ? undefined : options.canvas?.fps) ?? 2 },
138
200
  },
139
201
  setup: ({ root }) => {
140
202
  dir = options.dir === undefined ? keptIn(root, 'recordings') : resolve(root, options.dir);
141
203
  return { read };
142
204
  },
143
205
  routes: {
144
- // What the page recorded, as JSON.
145
- add: async (req) => {
146
- if (!(req.headers.get('content-type') ?? '').startsWith('application/json'))
147
- return Response.json({ problem: 'send the recording as application/json' }, { status: 415 });
148
- const body = new Uint8Array(await req.arrayBuffer());
149
- if (body.byteLength > MAX)
150
- return Response.json({ problem: `a recording may weigh ${MAX / 1024 / 1024} MB at most` }, { status: 413 });
151
- let kept: Partial<Kept>;
152
- try {
153
- kept = JSON.parse(new TextDecoder().decode(body)) as Partial<Kept>;
154
- } catch {
155
- return Response.json({ problem: "the recording isn't JSON" }, { status: 400 });
156
- }
157
- if (!Array.isArray(kept.events) || kept.events.length === 0)
206
+ // A recording starts: the page, its viewport and when. Its events come in parts, as they happen, so a page
207
+ // load in the middle loses none of them, and the next page carries on under the same ID.
208
+ begin: async (req) => {
209
+ const meta = await json<Partial<Meta>>(req);
210
+ if (meta?.viewport === undefined || typeof meta.page !== 'string' || typeof meta.startedAt !== 'number')
211
+ return Response.json({ problem: 'send the page, its viewport and when it started, as JSON' }, { status: 400 });
212
+ const { page, viewport, colorScheme, startedAt } = meta;
213
+ return Response.json({ id: begin({ page, viewport, ...(colorScheme === undefined ? {} : { colorScheme }), startedAt }) });
214
+ },
215
+ // `part/<id>?seq=<n>`: more of its events, a JSON array, and their place among the parts.
216
+ part: async (req) => {
217
+ const id = going(req);
218
+ if (typeof id !== 'string') return id;
219
+ const seq = Number(new URL(req.url).searchParams.get('seq') ?? 'none');
220
+ const events = await json<unknown>(req);
221
+ if (!Array.isArray(events) || !Number.isInteger(seq))
222
+ return Response.json({ problem: 'send the events as a JSON array, and `seq`, their place' }, { status: 400 });
223
+ const line = `${JSON.stringify({ seq, events })}\n`;
224
+ if (statSync(partOf(id)).size + line.length > MAX)
225
+ return Response.json({ problem: `a recording may weigh ${MAX / 1024 / 1024} MB at most: stop this one` }, { status: 413 });
226
+ appendFileSync(partOf(id), line);
227
+ return Response.json({ id });
228
+ },
229
+ // `end/<id>`: it's over, and kept: how long it ran, and the mic's clips.
230
+ end: async (req) => {
231
+ const id = going(req);
232
+ if (typeof id !== 'string') return id;
233
+ const last = await json<Partial<Kept>>(req);
234
+ if (typeof last?.duration !== 'number') return Response.json({ problem: 'send how long it ran, as JSON' }, { status: 400 });
235
+ if (!end(id, { duration: last.duration, ...(last.voice === undefined ? {} : { voice: last.voice }) }))
158
236
  return Response.json({ problem: 'the recording has no events: record for a moment longer' }, { status: 400 });
159
- return Response.json({ id: keepRecording(body) });
237
+ return Response.json({ id });
238
+ },
239
+ // `discard/<id>`: it's over, and not kept.
240
+ discard: (req) => {
241
+ const id = going(req);
242
+ if (typeof id !== 'string') return id;
243
+ rmSync(partOf(id));
244
+ return Response.json({ id });
160
245
  },
161
246
  // `recording/<id>`: the JSON, for the replay page.
162
247
  recording: (req) => {
@@ -4,6 +4,12 @@
4
4
  */
5
5
  export const MARKS = 'deictic.annotations';
6
6
 
7
+ /**
8
+ * The custom event for the page's address changing with no load, as a router does it (`href`, the new one): rrweb
9
+ * records what the route drew, not that the address changed. A page that loads has rrweb's own `Meta` instead.
10
+ */
11
+ export const PAGE = 'deictic.page';
12
+
7
13
  /**
8
14
  * The custom event a recording ends with: rrweb's timeline lasts as long as its events, so without it a
9
15
  * recording of a still page (a voice-over, say) would replay as a moment, and its voice never play.
@@ -10,6 +10,11 @@
10
10
  * which the replayer rebuilds. Each is a marker on the timeline.
11
11
  * - The voice clips play in step, at the player's speed. A recording with voice starts paused, as a browser
12
12
  * plays sound only after a click.
13
+ * - What the page logged and asked for (rrweb's console and network plugins' events, which its player doesn't
14
+ * show) is a list beside the replay, where the window has the room: the row the replay is at is lit, a click on
15
+ * one goes to its moment and shows the rest of it, and each error and failed request is a mark on the timeline.
16
+ * - A recorded canvas is replayed (`UNSAFE_replayCanvas`, which lets the replay's frame run rrweb's own script
17
+ * to draw it), for a recording that has one.
13
18
  *
14
19
  * `?t=<seconds>` opens it paused there, and `&bare` without the controls at the recorded size, 1:1, for a
15
20
  * screenshot; `?embed` is it filling a frame, with no header of its own (the lightbox's); `body[data-ready]` says
@@ -44,11 +49,35 @@ export const replayPage = ({ player = '..', source }: ReplaySources = {}) => `<!
44
49
  body { margin: 0; min-height: 100vh; display: flex; flex-direction: column; background: #18181b; color: #fafafa; font: 13px/1.4 system-ui, sans-serif; }
45
50
  header { display: flex; gap: 10px; align-items: center; padding: 10px 16px; border-bottom: 1px solid #3f3f46; }
46
51
  header a { color: #a1a1aa; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
47
- main { flex: 1; display: flex; justify-content: center; align-items: flex-start; padding: 16px; }
52
+ #stage { flex: 1; display: flex; min-height: 0; }
53
+ main { flex: 1; min-width: 0; display: flex; justify-content: center; align-items: flex-start; padding: 16px; }
48
54
  body.bare header { display: none; }
49
55
  body.bare main { padding: 0; }
50
56
  body.embed header { display: none; }
51
57
  body.embed main { padding: 0; }
58
+ /* What the page logged and asked for, beside the replay: the window's height, its list scrolling in it. */
59
+ #log { display: none; flex: none; width: 340px; flex-direction: column; border-left: 1px solid #3f3f46; background: #1f1f23; }
60
+ body.logged { height: 100vh; }
61
+ body.logged #log { display: flex; }
62
+ @media (max-width: 899px) { body.logged #log { display: none; } }
63
+ #log .filters { display: flex; gap: 6px; padding: 8px; border-bottom: 1px solid #3f3f46; }
64
+ #log .filters button { padding: 3px 8px; border: 1px solid #3f3f46; border-radius: 6px; background: none; color: #a1a1aa; font: inherit; font-size: 12px; cursor: pointer; }
65
+ #log .filters button[aria-pressed='true'] { color: #fafafa; background: #3f3f46; }
66
+ #log ol { flex: 1; min-height: 0; overflow: auto; margin: 0; padding: 0; list-style: none; font: 12px/1.45 ui-monospace, monospace; }
67
+ #log li { border-bottom: 1px solid #2e2e33; border-left: 2px solid transparent; }
68
+ #log li.ahead { opacity: 0.45; }
69
+ #log li.now { border-left-color: var(--accent); background: #27272a; }
70
+ #log li.warn .label { color: #fbbf24; }
71
+ #log li.bad .label, #log li.bad .text { color: #f87171; }
72
+ #log li > button { display: flex; gap: 8px; align-items: baseline; width: 100%; padding: 5px 8px; border: 0; background: none; color: inherit; font: inherit; text-align: left; cursor: pointer; }
73
+ #log li > button:hover { background: #2e2e33; }
74
+ #log time { flex: none; color: #71717a; }
75
+ #log .label { flex: none; min-width: 4ch; color: #a1a1aa; }
76
+ #log .text { min-width: 0; overflow: hidden; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow-wrap: anywhere; }
77
+ #log li.open .text { display: block; white-space: pre-wrap; }
78
+ #log pre { margin: 0; padding: 2px 8px 8px calc(8px + 6ch + 8px); color: #a1a1aa; font: inherit; white-space: pre-wrap; overflow-wrap: anywhere; }
79
+ #log.no-console li.console, #log.no-network li.network, #log.only-bad li:not(.bad) { display: none; }
80
+ #main .rr-player .rr-progress .bad-mark { position: absolute; top: -3px; width: 3px; height: 10px; margin-left: -1px; border-radius: 1px; background: #f87171; pointer-events: none; }
52
81
  body.embed #main .rr-player { box-shadow: none; border-radius: 0; }
53
82
  #marks { position: absolute; left: 0; top: 0; pointer-events: none; z-index: 3; }
54
83
  #marks svg { position: absolute; left: 0; top: 0; overflow: visible; }
@@ -77,7 +106,17 @@ export const replayPage = ({ player = '..', source }: ReplaySources = {}) => `<!
77
106
  <strong>Recording</strong>
78
107
  <a id="page" target="_blank" rel="noreferrer"></a>
79
108
  </header>
80
- <main id="main"></main>
109
+ <div id="stage">
110
+ <main id="main"></main>
111
+ <aside id="log" aria-label="Console and network">
112
+ <div class="filters">
113
+ <button type="button" data-hides="no-console" aria-pressed="true">Console</button>
114
+ <button type="button" data-hides="no-network" aria-pressed="true">Network</button>
115
+ <button type="button" data-shows="only-bad" aria-pressed="false" title="Errors, and requests that failed">Problems</button>
116
+ </div>
117
+ <ol></ol>
118
+ </aside>
119
+ </div>
81
120
  <script src="${player}/player.js"></script>${
82
121
  source === undefined
83
122
  ? ''
@@ -106,6 +145,46 @@ export const replayPage = ({ player = '..', source }: ReplaySources = {}) => `<!
106
145
  page.textContent = kept.page;
107
146
  page.href = kept.page;
108
147
 
148
+ // What the page logged and asked for, where the recording has it (rrweb's console and network plugins' events):
149
+ // a row each, in their order, beside the replay. Not in a bare one, which is the page alone.
150
+ const t0 = events[0].timestamp;
151
+ const clock = (ms) => { const s = Math.max(0, ms) / 1000; return Math.floor(s / 60) + ':' + (s % 60).toFixed(1).padStart(4, '0'); };
152
+ // An argument is kept as JSON: a string reads better without its quotes.
153
+ const plain = (arg) => { try { const v = JSON.parse(arg); return typeof v === 'string' ? v : arg; } catch { return arg; } };
154
+ const origin = (() => { try { return new URL(kept.page).origin; } catch { return ''; } })();
155
+ const fields = (title, held) => (held && Object.keys(held).length > 0 ? [title, ...Object.entries(held).map(([k, v]) => ' ' + k + ': ' + v)] : []);
156
+ const rows = [];
157
+ for (const e of events) {
158
+ if (e.type !== 6 || bare) continue;
159
+ const at = e.timestamp - t0;
160
+ if (e.data.plugin === 'rrweb/console@1') {
161
+ const { level, payload = [], trace = [] } = e.data.payload;
162
+ rows.push({ at, kind: 'console', label: level, bad: level === 'error' || level === 'assert', warn: level === 'warn', text: payload.map(plain).join(' '), more: trace.map((l) => 'at ' + l) });
163
+ }
164
+ if (e.data.plugin === 'rrweb/network@1') {
165
+ for (const r of e.data.payload.requests ?? []) {
166
+ // The page's own origin goes without saying.
167
+ let name = r.name;
168
+ try { const u = new URL(r.name); if (u.origin === origin) name = u.pathname + u.search + u.hash; } catch {}
169
+ const more = [
170
+ r.name,
171
+ [r.initiatorType, Number.isFinite(r.duration) ? Math.round(r.duration) + ' ms' : '', e.data.payload.isInitial ? 'as the page loaded' : ''].filter(Boolean).join(' · '),
172
+ ...fields('Request headers', r.requestHeaders),
173
+ ...(r.requestBody ? ['Request body', ' ' + r.requestBody] : []),
174
+ ...fields('Response headers', r.responseHeaders),
175
+ ...(r.responseBody ? ['Response body', ' ' + r.responseBody] : []),
176
+ ];
177
+ // No status is one the browser won't say (another origin's), not one that failed.
178
+ rows.push({ at, kind: 'network', label: r.status ? String(r.status) : '···', bad: r.status >= 400, text: (r.method ? r.method + ' ' : '') + name, more });
179
+ }
180
+ }
181
+ }
182
+ const logged = rows.length > 0;
183
+ const log = document.getElementById('log');
184
+ if (logged) document.body.classList.add('logged');
185
+ // The panel's room, where the window is wide enough to show it (as the stylesheet has it).
186
+ const side = () => (logged && innerWidth >= 900 ? 340 : 0);
187
+
109
188
  // A recording with the mic starts paused: a browser plays sound only after a click, which Play is.
110
189
  const clips = await Promise.all((kept.voice ?? []).map(async (c) => ({ ...c, audio: Object.assign(new Audio(await from.clip(c.id)), { preload: 'auto' }) })));
111
190
  const t = Number.parseFloat(params.get('t') ?? '');
@@ -113,8 +192,8 @@ export const replayPage = ({ player = '..', source }: ReplaySources = {}) => `<!
113
192
  const size = () => bare
114
193
  ? { width: kept.viewport.width, height: kept.viewport.height }
115
194
  : embed
116
- ? { width: innerWidth, height: innerHeight - 80 }
117
- : { width: Math.min(kept.viewport.width, innerWidth - 32), height: Math.min(kept.viewport.height, innerHeight - 90 - 80 - 16) };
195
+ ? { width: innerWidth - side(), height: innerHeight - 80 }
196
+ : { width: Math.min(kept.viewport.width, innerWidth - 32 - side()), height: Math.min(kept.viewport.height, innerHeight - 90 - 80 - 16) };
118
197
  const Player = rrwebPlayer.default ?? rrwebPlayer.Player ?? rrwebPlayer;
119
198
  const player = new Player({
120
199
  target: main,
@@ -127,6 +206,9 @@ export const replayPage = ({ player = '..', source }: ReplaySources = {}) => `<!
127
206
  tags: { ${JSON.stringify(MARKS)}: '#12b358' },
128
207
  inactiveColor: '#3f3f46',
129
208
  mouseTail: false,
209
+ // A recorded canvas is drawn by rrweb's own script in the replay's frame, which then must run scripts
210
+ // (the page's own were never recorded): only for a recording that has one.
211
+ ...(events.some((e) => e.type === 3 && e.data.source === 9) ? { UNSAFE_replayCanvas: true } : {}),
130
212
  },
131
213
  });
132
214
  addEventListener('resize', () => { player.$set(size()); player.triggerResize(); });
@@ -140,10 +222,51 @@ export const replayPage = ({ player = '..', source }: ReplaySources = {}) => `<!
140
222
 
141
223
  let playing = false;
142
224
  player.addEventListener('ui-update-player-state', (e) => { playing = e.payload === 'playing'; });
225
+
226
+ // The rows: a click goes to its moment, and shows the rest of it (where a line was logged from, a request's
227
+ // headers and bodies). All set as text: it's the recorded page's, not ours.
228
+ const list = log.querySelector('ol');
229
+ const bar = main.querySelector('.rr-progress');
230
+ for (const row of rows) {
231
+ const cell = (tag, name, text) => Object.assign(document.createElement(tag), { className: name, textContent: text });
232
+ const go = Object.assign(document.createElement('button'), { type: 'button' });
233
+ go.append(cell('time', '', clock(row.at)), cell('span', 'label', row.label), cell('span', 'text', row.text));
234
+ const more = Object.assign(cell('pre', '', row.more.join('\\n')), { hidden: true });
235
+ row.el = Object.assign(document.createElement('li'), { className: row.kind + (row.bad ? ' bad' : row.warn ? ' warn' : '') });
236
+ go.addEventListener('click', () => {
237
+ player.goto(Math.min(row.at, total), playing);
238
+ more.hidden = !more.hidden || row.more.length === 0;
239
+ row.el.classList.toggle('open', !more.hidden);
240
+ });
241
+ row.el.append(go, more);
242
+ list.append(row.el);
243
+ // An error, or a request that failed, is a mark on the timeline too.
244
+ if (row.bad && bar) bar.append(Object.assign(cell('i', 'bad-mark', ''), { title: row.text.slice(0, 200), style: 'left:' + (total > 0 ? (row.at / total) * 100 : 0) + '%' }));
245
+ }
246
+ for (const button of log.querySelectorAll('.filters button')) {
247
+ button.addEventListener('click', () => {
248
+ const on = button.getAttribute('aria-pressed') !== 'true';
249
+ button.setAttribute('aria-pressed', String(on));
250
+ if (button.dataset.hides) log.classList.toggle(button.dataset.hides, !on);
251
+ if (button.dataset.shows) log.classList.toggle(button.dataset.shows, on);
252
+ });
253
+ }
254
+ // The row the replay is at: the last whose moment has come, lit, the ones to come faint, kept in sight unless
255
+ // the list is being read.
256
+ let lit;
257
+ const light = (now) => {
258
+ let i = -1;
259
+ while (i + 1 < rows.length && rows[i + 1].at <= now) i++;
260
+ if (i === lit) return;
261
+ lit = i;
262
+ rows.forEach((row, k) => { row.el.classList.toggle('ahead', k > i); row.el.classList.toggle('now', k === i); });
263
+ if (i >= 0 && !log.matches(':hover')) rows[i].el.scrollIntoView({ block: 'nearest' });
264
+ };
143
265
  const follow = () => {
144
266
  const win = replayer.iframe.contentWindow;
145
267
  if (win) marks.style.transform = 'translate(' + -win.scrollX + 'px,' + -win.scrollY + 'px)';
146
268
  const now = Math.min(replayer.getCurrentTime(), total);
269
+ light(now);
147
270
  const speed = replayer.config.speed ?? 1;
148
271
  // Each clip plays while the replay is inside it, at its speed, kept within a few frames of the replay's time.
149
272
  for (const c of clips) {
@@ -33,6 +33,36 @@ export function boxOf(element: Element, area: NonNullable<CaptureOptions['area']
33
33
  return area === 'element' ? { x: 0, y: 0, width, height } : { x, y, width, height };
34
34
  }
35
35
 
36
+ const BLANK = '#d4d4d8';
37
+
38
+ const selector = (className: string, extra: string | undefined) => [`.${CSS.escape(className)}`, ...(extra ? [extra] : [])].join(', ');
39
+
40
+ /**
41
+ * Hides in a copy of the page's what rrweb would: blocked elements become a blank box their size (the copy keeps each
42
+ * element's size as its styles), masked text keeps its spaces but shows `*`, and so do passwords' values,
43
+ * or every field's.
44
+ */
45
+ export function mask(copy: Node, m: ResolvedMasking): void {
46
+ if (!(copy instanceof Element)) return;
47
+ const all = (sel: string) => [...(copy.matches(sel) ? [copy] : []), ...copy.querySelectorAll(sel)];
48
+ const stars = (text: string) => text.replace(/\S/g, '*');
49
+ for (const el of all(selector(m.blockClass, m.blockSelector))) {
50
+ el.replaceChildren();
51
+ if (el instanceof HTMLElement || el instanceof SVGElement) el.style.background = BLANK;
52
+ }
53
+ for (const el of all(selector(m.maskTextClass, m.maskTextSelector))) {
54
+ const walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT);
55
+ for (let text = walker.nextNode(); text !== null; text = walker.nextNode()) text.textContent = stars(text.textContent ?? '');
56
+ }
57
+ for (const field of all('input, textarea')) {
58
+ if (!(field instanceof HTMLInputElement || field instanceof HTMLTextAreaElement)) continue;
59
+ if (!m.maskAllInputs && !(field instanceof HTMLInputElement && field.type === 'password')) continue;
60
+ field.value = stars(field.value);
61
+ field.setAttribute('value', field.value);
62
+ if (field instanceof HTMLTextAreaElement) field.textContent = field.value;
63
+ }
64
+ }
65
+
36
66
  export function screenshotsClient(capture: PageCapture) {
37
67
  return defineClientPlugin<never, never, Capture>({
38
68
  name: 'screenshots',
@@ -58,6 +88,11 @@ export function screenshotsClient(capture: PageCapture) {
58
88
  return add(body, type, { box, size });
59
89
  },
60
90
  upload: (png, of) => add(png, 'image/png', of),
91
+ masked: (element) => {
92
+ const copy = element.cloneNode(true) as Element;
93
+ mask(copy, masking);
94
+ return copy;
95
+ },
61
96
  };
62
97
  },
63
98
  });
@@ -3,38 +3,7 @@
3
3
  * (imported on the first shot), so it needs no server, but text may lay out a little differently than
4
4
  * the page's. Masking changes only the copy that's drawn, never the page.
5
5
  */
6
- import { boxOf, notOurs, screenshotsClient } from './client.ts';
7
- import type { ResolvedMasking } from './index.ts';
8
-
9
- const BLANK = '#d4d4d8';
10
-
11
- const selector = (className: string, extra: string | undefined) => [`.${CSS.escape(className)}`, ...(extra ? [extra] : [])].join(', ');
12
-
13
- /**
14
- * Hides in the copy what rrweb would: blocked elements become a blank box their size (the copy keeps each
15
- * element's size as its styles), masked text keeps its spaces but shows `*`, and so do passwords' values,
16
- * or every field's.
17
- */
18
- function mask(copy: Node, m: ResolvedMasking): void {
19
- if (!(copy instanceof Element)) return;
20
- const all = (sel: string) => [...(copy.matches(sel) ? [copy] : []), ...copy.querySelectorAll(sel)];
21
- const stars = (text: string) => text.replace(/\S/g, '*');
22
- for (const el of all(selector(m.blockClass, m.blockSelector))) {
23
- el.replaceChildren();
24
- if (el instanceof HTMLElement || el instanceof SVGElement) el.style.background = BLANK;
25
- }
26
- for (const el of all(selector(m.maskTextClass, m.maskTextSelector))) {
27
- const walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT);
28
- for (let text = walker.nextNode(); text !== null; text = walker.nextNode()) text.textContent = stars(text.textContent ?? '');
29
- }
30
- for (const field of all('input, textarea')) {
31
- if (!(field instanceof HTMLInputElement || field instanceof HTMLTextAreaElement)) continue;
32
- if (!m.maskAllInputs && !(field instanceof HTMLInputElement && field.type === 'password')) continue;
33
- field.value = stars(field.value);
34
- field.setAttribute('value', field.value);
35
- if (field instanceof HTMLTextAreaElement) field.textContent = field.value;
36
- }
37
- }
6
+ import { boxOf, mask, notOurs, screenshotsClient } from './client.ts';
38
7
 
39
8
  /** Draws an SVG over the whole canvas, which is the area it was made for at the canvas's scale. */
40
9
  async function drawOver(canvas: HTMLCanvasElement, svg: string | undefined): Promise<HTMLCanvasElement> {
@@ -46,6 +46,8 @@ export interface Capture {
46
46
  capture(element: Element, options?: CaptureOptions): Promise<Shot>;
47
47
  /** Keeps a PNG made of a shot (the same one with marks drawn over it, say) as a shot of its own. */
48
48
  upload(png: Blob, of: Pick<Shot, 'box' | 'size'>): Promise<Shot>;
49
+ /** A copy of an element with what a shot hides hidden in it too: for a plugin that sends its HTML somewhere. */
50
+ masked(element: Element): Element;
49
51
  }
50
52
 
51
53
  /** The server's half, for other plugins' server halves. */
@@ -6,6 +6,11 @@
6
6
  * The snapshot is rebuilt into a sandboxed iframe filling a blank page on the page's own origin, which
7
7
  * Playwright answers itself, so nothing asks the dev server for it: rrweb has made the snapshot's URLs
8
8
  * whole, and its stylesheets' fonts and images load from the dev server as the page's did.
9
+ *
10
+ * The browser is as big as the page's window, scrollbars and all, and shows its own: a media query asks the
11
+ * window's width, and the page is laid out in what the scrollbar leaves. At the width without it, a window
12
+ * right on a breakpoint (1024 wide, 1009 to lay out in) would render as the narrower layout. The shot is then
13
+ * cut to the part the page is in.
9
14
  */
10
15
  import { createRequire } from 'node:module';
11
16
 
@@ -22,6 +27,8 @@ export interface Snapshot {
22
27
  snapshot: SnapshotNode;
23
28
  url: string;
24
29
  viewport: { width: number; height: number };
30
+ /** The window's size, scrollbars included, where it has any: what the page's media queries ask. */
31
+ window?: { width: number; height: number };
25
32
  scroll: { x: number; y: number };
26
33
  scale: number;
27
34
  /** The part of the viewport to keep, for a shot of an element alone. */
@@ -46,15 +53,18 @@ export function browserOf(options: BrowserOptions): Promise<Browser> {
46
53
  return launched;
47
54
  }
48
55
 
56
+ /** Playwright hides a headless browser's scrollbars, and with them the room they take in the page. */
57
+ const SCROLLBARS = { ignoreDefaultArgs: ['--hide-scrollbars'] };
58
+
49
59
  async function launch({ executablePath, channel }: BrowserOptions): Promise<Browser> {
50
60
  const { chromium } = await import('playwright-core').catch((e: unknown) => {
51
61
  throw new Error('the rrweb() renderer needs playwright-core: add it to your devDependencies', { cause: e });
52
62
  });
53
- if (executablePath !== undefined || channel !== undefined) return chromium.launch({ executablePath, channel });
63
+ if (executablePath !== undefined || channel !== undefined) return chromium.launch({ executablePath, channel, ...SCROLLBARS });
54
64
  const tried: string[] = [];
55
65
  for (const attempt of [{}, { channel: 'chrome' }, { channel: 'msedge' }]) {
56
66
  try {
57
- return await chromium.launch(attempt);
67
+ return await chromium.launch({ ...attempt, ...SCROLLBARS });
58
68
  } catch (e) {
59
69
  tried.push(
60
70
  `${'channel' in attempt ? attempt.channel : "Playwright's Chromium"}: ${(e instanceof Error ? e.message : String(e)).split('\n', 1)[0]}`,
@@ -74,7 +84,7 @@ export async function render(input: unknown, options: BrowserOptions): Promise<U
74
84
  if (typeof shot?.url !== 'string' || typeof shot.snapshot !== 'object' || typeof shot.viewport?.width !== 'number')
75
85
  throw new Error('screenshots: that is not a snapshot the rrweb() renderer took');
76
86
  const browser = await browserOf(options);
77
- const context = await browser.newContext({ viewport: shot.viewport, deviceScaleFactor: shot.scale });
87
+ const context = await browser.newContext({ viewport: shot.window ?? shot.viewport, deviceScaleFactor: shot.scale });
78
88
  try {
79
89
  const page = await context.newPage();
80
90
  const host = new URL('/__deictic/plugins/screenshots/host', shot.url).href;
@@ -102,7 +112,8 @@ export async function render(input: unknown, options: BrowserOptions): Promise<U
102
112
  marks.innerHTML = overlay;
103
113
  document.body.append(marks);
104
114
  }, shot);
105
- const clip = shot.clip === undefined ? undefined : clamp(shot.clip, shot.viewport);
115
+ // Without the scrollbars: a shot is what the page is drawn in, which is what an element's box is from.
116
+ const clip = clamp(shot.clip ?? { x: 0, y: 0, ...shot.viewport }, shot.viewport);
106
117
  return new Uint8Array(await page.screenshot({ type: 'png', ...(clip === undefined ? {} : { clip }) }));
107
118
  } finally {
108
119
  await context.close();
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * The `rrweb()` renderer's page half: a snapshot of the page's DOM with `rrweb-snapshot` (imported on the
3
3
  * first shot), masked as rrweb masks, without deictic's overlay, sent with what the server's browser needs
4
- * to show it as the page does: the viewport, where it's scrolled to, the pixel density, the page's URL.
4
+ * to show it as the page does: the viewport and the window around it, where it's scrolled to, the pixel density, the page's URL.
5
5
  */
6
6
 
7
7
  import { boxOf, screenshotsClient } from './client.ts';
@@ -35,6 +35,7 @@ export default screenshotsClient(async (element, { area, masking, overlay }) =>
35
35
  snapshot: withoutOurs(taken),
36
36
  url: location.href,
37
37
  viewport,
38
+ window: { width: innerWidth, height: innerHeight },
38
39
  ...(marks === undefined ? {} : { overlay: marks }),
39
40
  scroll: { x: scrollX, y: scrollY },
40
41
  scale: Math.min(devicePixelRatio, 2),