cuetake 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/probe.js CHANGED
@@ -1,80 +1,304 @@
1
1
  import { shortcutKeys } from './shortcuts.js';
2
+ import { contentOf } from './frames.js';
2
3
 
3
4
  /**
4
- * In-page Timeline probe. It records input exactly as the page receives it, so
5
- * director actions and raw Playwright input are captured alike. All positions
6
- * are CSS pixels; times are epoch milliseconds until collectTimeline rebases them.
7
- * Input inside cross-origin iframes never reaches this document and is not seen.
5
+ * The Timeline probe. It records input exactly as the page receives it, so director actions and raw
6
+ * Playwright input are captured alike, in every frame of the page: cross-origin and nested iframes,
7
+ * and frames that load after Capture starts. Each frame sends its records to Node as they happen, so a
8
+ * frame removed during the Take (a checkout that closes once paid) keeps what it saw.
9
+ *
10
+ * A frame sees only its own coordinates, and a cross-origin frame cannot ask where it sits. Its parent
11
+ * can: each document measures the iframes Node links to it, once per animation frame, and sends where
12
+ * their content starts and how much they are scaled whenever that changes. Node maps a frame's
13
+ * coordinates up through its parents to top-level CSS pixels, so scrolling, fixed and sticky
14
+ * positioning, translation and scaling are all followed. A rotated, skewed or 3D-transformed iframe is
15
+ * placed as if it were only scaled, and noted. Each document also measures the elements a mask follows
16
+ * (`watch`), once per animation frame, and sends their boxes whenever they change.
17
+ * Times are epoch milliseconds until collectTimeline rebases them. `contentOf` is frames.js's, passed
18
+ * in because the probe runs as page source.
8
19
  */
9
- export async function installProbe(page) {
10
- await page.evaluate(() => {
11
- window.__cuetakeProbe?.dispose();
12
- const abort = new AbortController();
13
- const on = (type, fn) => document.addEventListener(type, fn, { capture: true, passive: true, signal: abort.signal });
14
- const at = event => performance.timeOrigin + event.timeStamp;
15
- const interactive = 'a,button,input,textarea,select,label,summary,[role],[tabindex],[contenteditable]';
16
- const box = element => {
17
- const target = element?.closest?.(interactive) || element;
18
- const r = target?.getBoundingClientRect?.();
19
- return r ? { x: r.x, y: r.y, width: r.width, height: r.height } : null;
20
- };
21
- const state = { pointer: [], downs: [], ups: [], keys: [], shapes: [] };
22
- const BUTTONS = { 0: 'left', 2: 'right' };
23
- // The tab capture never shows the pointer, so the page keeps its cursor and Render draws the shape it
24
- // asks for, as the browser would show it: `auto` is text over editable fields and selectable text,
25
- // otherwise default; an image cursor gives way to its fallback keyword.
26
- const deepest = (x, y) => {
27
- let element = document.elementFromPoint(x, y);
28
- for (let inner; element?.shadowRoot && (inner = element.shadowRoot.elementFromPoint(x, y)) && inner !== element;) element = inner;
29
- return element;
30
- };
31
- const editable = element => element.isContentEditable
32
- || element.matches('textarea:not(:disabled), input:not(:disabled):not([type=button],[type=submit],[type=reset],[type=checkbox],[type=radio],[type=range],[type=color],[type=file],[type=image])');
33
- const overText = (element, x, y) => {
34
- const caret = document.caretPositionFromPoint?.(x, y), node = caret?.offsetNode;
35
- const parent = node?.nodeType === Node.TEXT_NODE && node.data.trim() && element.contains(node) && node.parentElement;
36
- if (!parent || parent.closest('button, select') || getComputedStyle(parent).userSelect === 'none') return false;
37
- const range = document.createRange();
38
- range.selectNodeContents(node);
39
- return [...range.getClientRects()].some(r => x >= r.left && x <= r.right && y >= r.top && y <= r.bottom);
40
- };
41
- const shapeAt = (x, y) => {
42
- const element = deepest(x, y);
43
- if (!element) return 'default';
44
- const keyword = getComputedStyle(element).cursor.match(/([a-z-]+)\s*$/)?.[1] ?? 'auto';
45
- return keyword !== 'auto' ? keyword : editable(element) || overText(element, x, y) ? 'text' : 'default';
46
- };
47
- // Read after the page's own handlers have run, since they often set the cursor themselves.
48
- let point = null, due = null;
49
- const sampleShape = ms => {
50
- if (!point || due !== null) return;
51
- due = ms;
52
- setTimeout(() => {
53
- try {
54
- const shape = shapeAt(point.x, point.y);
55
- if (shape !== state.shapes.at(-1)?.[1]) state.shapes.push([due, shape]);
56
- } finally { due = null; }
57
- });
58
- };
59
- const moved = e => { point = { x: e.clientX, y: e.clientY }; sampleShape(at(e)); };
60
- on('pointermove', e => { state.pointer.push([at(e), e.clientX, e.clientY]); moved(e); });
61
- on('pointerdown', e => {
62
- state.pointer.push([at(e), e.clientX, e.clientY]); moved(e);
63
- if (BUTTONS[e.button]) state.downs.push({ ms: at(e), button: BUTTONS[e.button], x: e.clientX, y: e.clientY, box: box(e.target) });
64
- });
65
- on('pointerup', e => { moved(e); if (BUTTONS[e.button]) state.ups.push({ ms: at(e), button: BUTTONS[e.button], x: e.clientX, y: e.clientY }); });
66
- // Each key with what Node needs to tell typing from a Shortcut (shortcuts.js); only Shortcuts reach the Timeline.
67
- const focused = () => { let element = document.activeElement; while (element?.shadowRoot?.activeElement) element = element.shadowRoot.activeElement; return element; };
68
- on('keydown', e => {
69
- const element = focused();
70
- const { key, code, ctrlKey, altKey, shiftKey, metaKey, repeat } = e;
71
- state.keys.push({ ms: at(e), box: box(element), key, code, ctrlKey, altKey, shiftKey, metaKey, repeat, field: Boolean(element && editable(element)) });
72
- sampleShape(at(e));
20
+ function probe(contentOf) {
21
+ window.__cuetakeProbe?.dispose();
22
+ const abort = new AbortController();
23
+ const send = record => { try { window.__cuetakeRecord?.(record)?.catch?.(() => {}); } catch {} };
24
+ const on = (type, fn) => document.addEventListener(type, fn, { capture: true, passive: true, signal: abort.signal });
25
+ const at = event => performance.timeOrigin + event.timeStamp;
26
+ const interactive = 'a,button,input,textarea,select,label,summary,[role],[tabindex],[contenteditable]';
27
+ const box = element => {
28
+ const target = element?.closest?.(interactive) || element;
29
+ const r = target?.getBoundingClientRect?.();
30
+ return r ? { x: r.x, y: r.y, width: r.width, height: r.height } : null;
31
+ };
32
+ const BUTTONS = { 0: 'left', 2: 'right' };
33
+ const where = e => ({ x: e.clientX, y: e.clientY });
34
+ // The tab capture never shows the pointer, so the page keeps its cursor and Render draws the shape it
35
+ // asks for, as the browser would show it: `auto` is text over editable fields and selectable text,
36
+ // otherwise default; an image cursor gives way to its fallback keyword.
37
+ const deepest = (x, y) => {
38
+ let element = document.elementFromPoint(x, y);
39
+ for (let inner; element?.shadowRoot && (inner = element.shadowRoot.elementFromPoint(x, y)) && inner !== element;) element = inner;
40
+ return element;
41
+ };
42
+ const editable = element => element.isContentEditable
43
+ || element.matches('textarea:not(:disabled), input:not(:disabled):not([type=button],[type=submit],[type=reset],[type=checkbox],[type=radio],[type=range],[type=color],[type=file],[type=image])');
44
+ const overText = (element, x, y) => {
45
+ const caret = document.caretPositionFromPoint?.(x, y), node = caret?.offsetNode;
46
+ const parent = node?.nodeType === Node.TEXT_NODE && node.data.trim() && element.contains(node) && node.parentElement;
47
+ if (!parent || parent.closest('button, select') || getComputedStyle(parent).userSelect === 'none') return false;
48
+ const range = document.createRange();
49
+ range.selectNodeContents(node);
50
+ return [...range.getClientRects()].some(r => x >= r.left && x <= r.right && y >= r.top && y <= r.bottom);
51
+ };
52
+ const shapeAt = (x, y) => {
53
+ const element = deepest(x, y);
54
+ if (!element) return 'default';
55
+ const keyword = getComputedStyle(element).cursor.match(/([a-z-]+)\s*$/)?.[1] ?? 'auto';
56
+ return keyword !== 'auto' ? keyword : editable(element) || overText(element, x, y) ? 'text' : 'default';
57
+ };
58
+ // Read after the page's own handlers have run, since they often set the cursor themselves. A move
59
+ // carries the shape it found, since the pointer may have left this frame and come back to the same
60
+ // one; other samples are sent only when the shape changed.
61
+ let point = null, due = null, last = null;
62
+ const later = fn => setTimeout(() => { try { fn(); } catch {} });
63
+ const sampleShape = ms => {
64
+ if (!point || due !== null) return;
65
+ due = ms;
66
+ later(() => {
67
+ try {
68
+ const shape = shapeAt(point.x, point.y);
69
+ if (shape !== last) { last = shape; send({ kind: 'shape', ms: due, shape }); }
70
+ } finally { due = null; }
73
71
  });
74
- on('keyup', e => sampleShape(at(e)));
75
- on('scroll', e => sampleShape(at(e)));
76
- window.__cuetakeProbe = { state, dispose() { abort.abort(); } };
72
+ };
73
+ on('pointermove', e => {
74
+ point = { x: e.clientX, y: e.clientY };
75
+ const record = { kind: 'move', ms: at(e), ...where(e) };
76
+ later(() => { record.shape = last = shapeAt(record.x, record.y); });
77
+ later(() => send(record));
78
+ });
79
+ // Presses and releases are sent at once: a frame may be removed right after the click it took.
80
+ on('pointerdown', e => {
81
+ point = { x: e.clientX, y: e.clientY };
82
+ send(BUTTONS[e.button] ? { kind: 'down', ms: at(e), button: BUTTONS[e.button], ...where(e), box: box(e.target) } : { kind: 'move', ms: at(e), ...where(e) });
83
+ sampleShape(at(e));
77
84
  });
85
+ on('pointerup', e => {
86
+ point = { x: e.clientX, y: e.clientY };
87
+ if (BUTTONS[e.button]) send({ kind: 'up', ms: at(e), button: BUTTONS[e.button], ...where(e) });
88
+ sampleShape(at(e));
89
+ });
90
+ // Each key with what Node needs to tell typing from a Shortcut (shortcuts.js); only Shortcuts reach the Timeline.
91
+ const focused = () => { let element = document.activeElement; while (element?.shadowRoot?.activeElement) element = element.shadowRoot.activeElement; return element; };
92
+ on('keydown', e => {
93
+ const element = focused();
94
+ const { key, code, ctrlKey, altKey, shiftKey, metaKey, repeat } = e;
95
+ send({ kind: 'key', ms: at(e), box: box(element), key, code, ctrlKey, altKey, shiftKey, metaKey, repeat, field: Boolean(element && editable(element)) });
96
+ sampleShape(at(e));
97
+ });
98
+ on('keyup', e => sampleShape(at(e)));
99
+ on('scroll', e => sampleShape(at(e)));
100
+ // Child iframes Node has linked to this document, measured each animation frame and sent on change.
101
+ const ids = new WeakMap(), tracked = new Map();
102
+ let nextId = 0, looping = false;
103
+ const turned = element => {
104
+ for (let node = element; node; node = node.parentElement ?? node.getRootNode().host) {
105
+ const style = getComputedStyle(node);
106
+ if (style.rotate !== 'none') return true;
107
+ if (style.transform === 'none') continue;
108
+ const m = new DOMMatrixReadOnly(style.transform);
109
+ if (!m.is2D || m.b || m.c) return true;
110
+ }
111
+ return false;
112
+ };
113
+ const sampleFrames = () => {
114
+ const rects = [];
115
+ for (const [element, entry] of tracked) {
116
+ if (!element.isConnected) { tracked.delete(element); continue; }
117
+ const rect = contentOf(element), key = [rect.x, rect.y, rect.sx, rect.sy].map(v => v.toFixed(2)).join();
118
+ if (key === entry.key) continue;
119
+ entry.key = key;
120
+ rects.push({ id: entry.id, ...rect, turned: turned(element) });
121
+ }
122
+ if (rects.length) send({ kind: 'frames', ms: performance.timeOrigin + performance.now(), rects });
123
+ };
124
+ // The elements each mask follows (by Node's `watch` id), measured each animation frame and sent on
125
+ // change. An element removed from the page keeps its last box until Node watches what replaced it.
126
+ const watches = new Map();
127
+ const sampleBoxes = () => {
128
+ for (const [id, entry] of watches) {
129
+ const boxes = [];
130
+ for (const element of entry.elements) {
131
+ if (!element.isConnected) { if (entry.last.has(element)) boxes.push(entry.last.get(element)); continue; }
132
+ if (!element.getClientRects().length) { entry.last.delete(element); continue; }
133
+ const r = element.getBoundingClientRect(), box = { x: r.x, y: r.y, width: r.width, height: r.height };
134
+ entry.last.set(element, box); boxes.push(box);
135
+ }
136
+ const key = boxes.map(b => [b.x, b.y, b.width, b.height].map(v => v.toFixed(2)).join()).join(';');
137
+ if (key === entry.key) continue;
138
+ entry.key = key;
139
+ send({ kind: 'box', ms: performance.timeOrigin + performance.now(), watch: id, boxes });
140
+ }
141
+ };
142
+ const loop = () => {
143
+ if (abort.signal.aborted || (!tracked.size && !watches.size)) { looping = false; return; }
144
+ try { sampleFrames(); sampleBoxes(); } finally { requestAnimationFrame(loop); }
145
+ };
146
+ const run = () => { if (!looping) { looping = true; requestAnimationFrame(loop); } };
147
+ const track = element => {
148
+ if (!(element instanceof Element)) return null;
149
+ let id = ids.get(element);
150
+ if (id === undefined) ids.set(element, id = nextId++);
151
+ if (!tracked.has(element)) tracked.set(element, { id, key: null });
152
+ sampleFrames();
153
+ run();
154
+ return id;
155
+ };
156
+ /** Follows the elements a mask's locator matches now, replacing those it matched before. */
157
+ const watch = (id, elements) => {
158
+ const entry = watches.get(id) ?? { elements: [], last: new Map(), key: null };
159
+ entry.elements = elements;
160
+ for (const element of entry.last.keys()) if (!elements.includes(element)) entry.last.delete(element);
161
+ watches.set(id, entry);
162
+ sampleBoxes();
163
+ run();
164
+ return true;
165
+ };
166
+ window.__cuetakeProbe = { track, watch, dispose() { abort.abort(); } };
167
+ // Announced at once, so Node links this frame before any input reaches it.
168
+ send({ kind: 'hello' });
169
+ }
170
+
171
+ const collectors = new WeakMap(), script = `(${probe})(${contentOf})`;
172
+
173
+ /**
174
+ * Installs the probe in every frame of the page, now and in frames that load later, and starts
175
+ * collecting what it sends. Calling it again on the same page starts the collection over.
176
+ */
177
+ export async function installProbe(page) {
178
+ let collector = collectors.get(page);
179
+ if (!collector) {
180
+ collector = { pending: new Set() };
181
+ collectors.set(page, collector);
182
+ await page.exposeBinding('__cuetakeRecord', ({ frame }, record) => {
183
+ if (!record || typeof record !== 'object') return;
184
+ collector.records.push({ ...record, frame: collector.idOf(frame) });
185
+ collector.link(frame);
186
+ });
187
+ await page.addInitScript(script);
188
+ }
189
+ const ids = new WeakMap(), linked = new WeakSet(), records = [];
190
+ let count = 0;
191
+ const idOf = frame => { let id = ids.get(frame); if (id === undefined) ids.set(frame, id = count++); return id; };
192
+ // A subframe is linked to its iframe element when its probe starts, so its parent starts measuring it;
193
+ // a record that finds it unlinked tries again.
194
+ const link = frame => {
195
+ const parent = frame.parentFrame();
196
+ if (!parent || linked.has(frame)) return;
197
+ linked.add(frame);
198
+ const linking = (async () => {
199
+ const element = await frame.frameElement();
200
+ const id = await element.evaluate(e => window.__cuetakeProbe?.track(e) ?? null);
201
+ // The parent's probe may not be running yet; the frame's next record tries again.
202
+ if (id === null) { linked.delete(frame); return; }
203
+ records.push({ kind: 'link', frame: idOf(frame), parent: idOf(parent), element: id });
204
+ link(parent);
205
+ })().catch(() => linked.delete(frame));
206
+ collector.pending.add(linking);
207
+ linking.finally(() => collector.pending.delete(linking));
208
+ };
209
+ records.push({ kind: 'top', frame: idOf(page.mainFrame()) });
210
+ Object.assign(collector, { idOf, link, records });
211
+ // Parents first (frames() lists them in tree order), so each child finds its parent's probe to link to.
212
+ for (const frame of page.frames()) await frame.evaluate(script).catch(() => {});
213
+ }
214
+
215
+ /** The entry of `list`, sorted by `ms`, last at or before `ms`, or its first. */
216
+ function latest(list, ms) {
217
+ let low = 0, high = list.length - 1, found = 0;
218
+ while (low <= high) { const mid = (low + high) >> 1; if (list[mid].ms <= ms) { found = mid; low = mid + 1; } else high = mid - 1; }
219
+ return list[found];
220
+ }
221
+
222
+ /**
223
+ * Places the probe's records from every frame in top-level CSS pixels. A subframe's point goes up
224
+ * through each iframe holding it, by where that iframe's content started and how it was scaled at the
225
+ * moment (the parent's last measure before it, or its first). Each frame's cursor shape counts only
226
+ * while the pointer is over it. A masked element's boxes (`box` records, by `watch` id) are placed
227
+ * the same way, again whenever an iframe holding it moves. Returns the records as the top frame alone would have made them, plus
228
+ * the times of presses and keys inside a rotated, skewed or 3D-transformed iframe (`turned`) and in a
229
+ * frame that could not be placed (`unplaced`).
230
+ */
231
+ export function placeRecords(records) {
232
+ const top = new Set(), links = new Map(), measures = new Map();
233
+ for (const r of records) {
234
+ if (r.kind === 'top') top.add(r.frame);
235
+ if (r.kind === 'link') links.set(r.frame, r);
236
+ if (r.kind === 'frames') for (const rect of r.rects) {
237
+ const key = `${r.frame}:${rect.id}`;
238
+ if (!measures.has(key)) measures.set(key, []);
239
+ measures.get(key).push({ ms: r.ms, ...rect });
240
+ }
241
+ }
242
+ for (const list of measures.values()) list.sort((a, b) => a.ms - b.ms);
243
+ // The map from a frame's coordinates to the top level at `ms`: an offset and a scale.
244
+ const toTop = (frame, ms) => {
245
+ let map = { x: 0, y: 0, sx: 1, sy: 1, turned: false };
246
+ for (let f = frame, depth = 0; !top.has(f); depth++) {
247
+ const link = links.get(f), list = link && measures.get(`${link.parent}:${link.element}`);
248
+ if (!list?.length || depth > 32) return null;
249
+ const m = latest(list, ms);
250
+ map = { x: m.x + map.x * m.sx, y: m.y + map.y * m.sy, sx: map.sx * m.sx, sy: map.sy * m.sy, turned: map.turned || m.turned };
251
+ f = link.parent;
252
+ }
253
+ return map;
254
+ };
255
+ // When each frame's place in the top level can change: each measure of an iframe holding it.
256
+ const movesOf = frame => {
257
+ const times = [];
258
+ for (let f = frame, depth = 0; !top.has(f) && depth <= 32; depth++) {
259
+ const link = links.get(f);
260
+ if (!link) break;
261
+ times.push(...(measures.get(`${link.parent}:${link.element}`) ?? []).map(m => m.ms));
262
+ f = link.parent;
263
+ }
264
+ return times;
265
+ };
266
+ const placed = { pointer: [], downs: [], ups: [], keys: [], shapes: [], boxes: [] }, turned = [], unplaced = [];
267
+ // A masked element's boxes are placed when they change and whenever an iframe holding them moves.
268
+ const watched = new Map();
269
+ for (const r of records) if (r.kind === 'box' && typeof r.ms === 'number') { if (!watched.has(r.watch)) watched.set(r.watch, []); watched.get(r.watch).push(r); }
270
+ for (const [watch, list] of watched) {
271
+ list.sort((a, b) => a.ms - b.ms);
272
+ const times = [...new Set([...list.map(r => r.ms), ...list.flatMap(r => movesOf(r.frame))])].filter(ms => ms >= list[0].ms).sort((a, b) => a - b);
273
+ let last = null;
274
+ for (const ms of times) {
275
+ const r = latest(list, ms), map = toTop(r.frame, ms);
276
+ if (!map) continue;
277
+ const boxes = r.boxes.map(b => [map.x + b.x * map.sx, map.y + b.y * map.sy, b.width * map.sx, b.height * map.sy]), key = JSON.stringify(boxes);
278
+ if (key !== last) placed.boxes.push({ ms, watch, boxes });
279
+ last = key;
280
+ }
281
+ }
282
+ placed.boxes.sort((a, b) => a.ms - b.ms);
283
+ let over = null;
284
+ for (const r of records.filter(r => typeof r.ms === 'number' && r.kind !== 'frames' && r.kind !== 'box').toSorted((a, b) => a.ms - b.ms)) {
285
+ if (r.kind === 'move') over = r.frame;
286
+ if (r.shape) {
287
+ if (r.frame === over && r.shape !== placed.shapes.at(-1)?.[1]) placed.shapes.push([r.ms, r.shape]);
288
+ if (r.kind === 'shape') continue;
289
+ }
290
+ const map = toTop(r.frame, r.ms), pressed = r.kind === 'down' || r.kind === 'key';
291
+ if (!map) { if (pressed) unplaced.push(r.ms); continue; }
292
+ if (map.turned && pressed) turned.push(r.ms);
293
+ const box = b => b && { x: map.x + b.x * map.sx, y: map.y + b.y * map.sy, width: b.width * map.sx, height: b.height * map.sy };
294
+ if (r.kind === 'key') { const { kind, frame, ms, box: own, ...key } = r; placed.keys.push({ ms, box: box(own), ...key }); continue; }
295
+ const x = map.x + r.x * map.sx, y = map.y + r.y * map.sy;
296
+ over = r.frame;
297
+ if (r.kind === 'move' || r.kind === 'down') placed.pointer.push([r.ms, x, y]);
298
+ if (r.kind === 'down') placed.downs.push({ ms: r.ms, button: r.button, x, y, box: box(r.box) });
299
+ if (r.kind === 'up') placed.ups.push({ ms: r.ms, button: r.button, x, y });
300
+ }
301
+ return { ...placed, turned, unplaced };
78
302
  }
79
303
 
80
304
  const CLICK_SLOP = 6; // CSS px a press may travel and still count as a click
@@ -83,9 +307,17 @@ const CLICK_SLOP = 6; // CSS px a press may travel and still count as a click
83
307
  * Rebases probe records to seconds since capture start and derives clicks and drags (from press to
84
308
  * release; a right click is marked `button: 'right'`), typing, Shortcuts with their keys, and the
85
309
  * cursor shapes: each change as [t, keyword], starting with the one shown when Capture began.
310
+ * `turned` lists when a press or key landed in a rotated, skewed or 3D-transformed iframe, placed as
311
+ * if it were only scaled, and `unplaced` when one landed in a frame that could not be placed at all.
312
+ * `watched` lists the boxes of each element a mask follows, by its `watch` id.
86
313
  */
87
314
  export async function collectTimeline(page, startedAtMs) {
88
- const raw = await page.evaluate(() => window.__cuetakeProbe.state);
315
+ const collector = collectors.get(page);
316
+ if (!collector) throw new Error('The Timeline probe was never installed on this page');
317
+ // Records a frame sent before this call arrive before its answer to an evaluate.
318
+ await Promise.all(page.frames().map(frame => frame.evaluate(() => 0).catch(() => {})));
319
+ while (collector.pending.size) await Promise.all(collector.pending);
320
+ const raw = placeRecords(collector.records);
89
321
  const t = ms => Math.round(ms - startedAtMs) / 1000;
90
322
  const pointer = raw.pointer.filter(([ms]) => ms >= startedAtMs).map(([ms, x, y]) => [t(ms), x, y]);
91
323
  const events = [];
@@ -111,5 +343,15 @@ export async function collectTimeline(page, startedAtMs) {
111
343
  }
112
344
  const before = raw.shapes.filter(([ms]) => ms < startedAtMs).at(-1);
113
345
  const shapes = [...(before ? [[0, before[1]]] : []), ...raw.shapes.filter(([ms]) => ms >= startedAtMs).map(([ms, shape]) => [t(ms), shape])];
114
- return { pointer, shapes, events: events.sort((a, b) => a.t - b.t) };
346
+ const times = list => [...new Set(list.filter(ms => ms >= startedAtMs).map(t))];
347
+ // Each masked element's boxes as [t, ...[x, y, width, height]], held back to the start of Capture.
348
+ const watched = new Map(), round = v => Math.round(v * 100) / 100;
349
+ for (const { ms, watch, boxes } of raw.boxes) {
350
+ if (!watched.has(watch)) watched.set(watch, []);
351
+ watched.get(watch).push([Math.max(0, t(ms)), ...boxes.map(box => box.map(round))]);
352
+ }
353
+ return {
354
+ pointer, shapes, events: events.sort((a, b) => a.t - b.t), turned: times(raw.turned), unplaced: times(raw.unplaced),
355
+ watched: [...watched].map(([id, boxes]) => ({ id, boxes })),
356
+ };
115
357
  }
package/src/recorder.js CHANGED
@@ -2,7 +2,8 @@ import { chromium } from 'playwright';
2
2
  import { randomUUID } from 'node:crypto';
3
3
  import { mkdir } from 'node:fs/promises';
4
4
  import { join } from 'node:path';
5
- import { startTabCapture, stopTabCapture } from './tab-capture.js';
5
+ import { openRecorder, startTabCapture, stopTabCapture, watchNavigations, captureArgs } from './tab-capture.js';
6
+ import { followTabs } from './follow-tabs.js';
6
7
  import { installProbe } from './probe.js';
7
8
 
8
9
  let browser = null;
@@ -15,7 +16,7 @@ export async function startRecording(url, options = {}) {
15
16
  // but only captures at device scale when the scale is also forced on the browser.
16
17
  browser ||= await chromium.launch({
17
18
  headless: !options.headed, channel: 'chromium',
18
- args: ['--auto-accept-this-tab-capture', '--disable-backgrounding-occluded-windows', '--disable-renderer-backgrounding', ...(options.headed ? [] : [`--force-device-scale-factor=${resolutionScale}`])],
19
+ args: [...captureArgs, '--disable-backgrounding-occluded-windows', '--disable-renderer-backgrounding', ...(options.headed ? [] : [`--force-device-scale-factor=${resolutionScale}`])],
19
20
  });
20
21
  const outputDir = options.outputDir || './recordings';
21
22
  await mkdir(outputDir, { recursive: true });
@@ -36,24 +37,56 @@ export function getRecordingPage(sessionId) {
36
37
  return session.page;
37
38
  }
38
39
 
40
+ /**
41
+ * Starts the Timeline probe and the recorder on the page, and follows each Tab the demo opens from it
42
+ * (follow-tabs.js), recording each the same way. Returns when the first Tab records, with its capture
43
+ * and `tabs`, the Tabs followed.
44
+ */
39
45
  export async function beginCapture(sessionId) {
40
46
  const session = sessions.get(sessionId);
41
- if (!session || session.capture) throw new Error('Session is missing or already recording');
42
- // Preparation may navigate through login; install the probe only at the final document.
43
- await installProbe(session.page);
44
- const capture = await startTabCapture(session.page, { width: session.width * session.resolutionScale, height: session.height * session.resolutionScale, fps: session.options.fps || 60, bitrate: 40_000_000 });
45
- session.capture = capture;
46
- return capture;
47
+ if (!session || session.tabs) throw new Error('Session is missing or already recording');
48
+ // Preparation may navigate through login, before the probe and the recorder start; both then follow
49
+ // the page through any navigation or reload until Capture stops.
50
+ const recorder = await openRecorder(session.page), scale = session.resolutionScale;
51
+ session.tabs = followTabs(session.page, {
52
+ watch: tab => watchNavigations(tab.page),
53
+ async start(tab) {
54
+ await installProbe(tab.page);
55
+ const { width, height } = tab.viewport;
56
+ tab.capture = await startTabCapture(tab.page, recorder, { width: width * scale, height: height * scale, fps: session.options.fps || 60, bitrate: 40_000_000 });
57
+ },
58
+ });
59
+ await session.tabs.ready(session.page);
60
+ return { ...session.tabs.list()[0].capture, tabs: session.tabs };
47
61
  }
48
62
 
63
+ /**
64
+ * Stops recording every Tab and closes the session. Each recorded Tab's Source is written to
65
+ * `recording-<session>-<tab>.webm` beside its stats; times are seconds since the first Tab began
66
+ * recording, except in each Tab's stats, which count from its own start. `fronts` lists when each Tab
67
+ * came in front.
68
+ */
49
69
  export async function stopRecording(sessionId) {
50
70
  const session = sessions.get(sessionId);
51
- if (!session?.capture) throw new Error('Session has not started recording');
52
- const webmPath = join(session.outputDir, `recording-${sessionId}.webm`);
53
- const stats = await stopTabCapture(session.page, webmPath);
71
+ if (!session?.tabs) throw new Error('Session has not started recording');
72
+ // A Tab the demo opened just before the end may still be starting.
73
+ await session.tabs.started();
74
+ const tabs = session.tabs.list().filter(tab => tab.recorded);
75
+ const startedAtMs = Date.parse(tabs[0].capture.startedAt), t = ms => ms === null ? null : Math.round(Math.max(0, ms - startedAtMs)) / 1000;
76
+ const stopped = await Promise.all(tabs.map(async tab => {
77
+ const webmPath = join(session.outputDir, `recording-${sessionId}-${tab.id}.webm`);
78
+ const stats = await stopTabCapture(tab.page, webmPath), start = t(Date.parse(tab.capture.startedAt));
79
+ // The stats count from the Tab's own start; its navigations join the Timeline from the start of Capture.
80
+ const at = s => Math.max(0, Math.round((s + start) * 1000) / 1000);
81
+ const navigations = stats.navigations.filter(load => load.end + start >= 0).map(({ t, end, commit, ...load }) => ({ t: at(t), end: at(end), ...(commit !== undefined && { commit: at(commit) }), ...load }));
82
+ return { id: tab.id, opener: tab.opener, opened: t(tab.openedMs), closed: t(tab.closedMs), viewport: tab.viewport, url: tab.id === 0 ? tab.capture.url : tab.url, start, webmPath, stats, navigations };
83
+ }));
84
+ const recorded = new Set(tabs.map(tab => tab.id));
54
85
  await session.context.close();
55
86
  sessions.delete(sessionId);
56
- return { webmPath, durationSeconds: stats.duration };
87
+ // The Take lasts until the last Tab stops, even when the first one closed before.
88
+ const durationSeconds = Math.max(...stopped.map(tab => Math.round((tab.start + tab.stats.duration) * 1000) / 1000));
89
+ return { durationSeconds, tabs: stopped, fronts: session.tabs.fronts.filter(front => recorded.has(front.tab)).map(front => ({ t: t(front.ms), tab: front.tab })) };
57
90
  }
58
91
 
59
92
  export async function cleanup() {