cuetake 0.0.0-stage → 0.2.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/LICENSE +22 -0
- package/README.md +80 -2
- package/examples/basic.mjs +47 -0
- package/package.json +41 -4
- package/src/auth.js +48 -0
- package/src/camera.js +86 -0
- package/src/cli.js +62 -0
- package/src/cursor.js +57 -0
- package/src/director.js +54 -0
- package/src/edit.js +81 -0
- package/src/environment.js +36 -0
- package/src/look.js +107 -0
- package/src/pipeline.js +159 -0
- package/src/probe.js +57 -0
- package/src/recorder.js +64 -0
- package/src/render-page.js +454 -0
- package/src/render.js +92 -0
- package/src/stage.js +114 -0
- package/src/tab-capture.js +88 -0
package/src/look.js
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import fs from 'node:fs/promises';
|
|
2
|
+
import { homedir } from 'node:os';
|
|
3
|
+
import { basename, dirname, join, resolve } from 'node:path';
|
|
4
|
+
import { z } from 'zod';
|
|
5
|
+
import { editFields, editSchema, frameFields, outputFields } from './edit.js';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* A Look is the part of an Edit that does not depend on one Take: everything except camera targets,
|
|
9
|
+
* the address bar's url and the frame rate. Every field is optional; a Look sets only what it names.
|
|
10
|
+
*/
|
|
11
|
+
export const lookSchema = z.object({
|
|
12
|
+
cursor: editFields.cursor.removeDefault().partial().strict(),
|
|
13
|
+
clickEffect: editFields.clickEffect.removeDefault().partial().strict(),
|
|
14
|
+
output: outputFields.partial().strict(),
|
|
15
|
+
frame: z.union([z.literal(false), frameFields.omit({ url: true }).partial().strict()]),
|
|
16
|
+
camera: editFields.camera.removeDefault().partial().strict(),
|
|
17
|
+
}).partial().strict();
|
|
18
|
+
|
|
19
|
+
const isObject = value => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
20
|
+
/** `over` wins field by field: nested objects merge, anything else (including `frame: false`) replaces. */
|
|
21
|
+
export function mergeLook(base, over) {
|
|
22
|
+
const merged = { ...base };
|
|
23
|
+
for (const [key, value] of Object.entries(over ?? {})) merged[key] = isObject(value) && isObject(base?.[key]) ? mergeLook(base[key], value) : value;
|
|
24
|
+
return merged;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** The Look an Edit carries. */
|
|
28
|
+
export function lookFromEdit({ cursor, clickEffect, output: { fps, ...output }, frame, camera: { targets, ...camera } }) {
|
|
29
|
+
const { url, ...styling } = frame || {};
|
|
30
|
+
return lookSchema.parse({ cursor, clickEffect, output, frame: frame && styling, camera });
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** The Edit with a Look adopted. Camera targets and the frame rate stay; the address bar keeps its url, else shows `host`. */
|
|
34
|
+
export function applyLook(edit, look, host) {
|
|
35
|
+
const next = mergeLook(edit, look);
|
|
36
|
+
if (next.frame) next.frame = { url: edit.frame?.url ?? host, ...next.frame };
|
|
37
|
+
return editSchema.parse(next);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** One line for listings, such as "browser · ocean · 16:9 · 2160p". */
|
|
41
|
+
export function summarize(look) {
|
|
42
|
+
const { frame, output = {} } = look;
|
|
43
|
+
const parts = frame === false ? ['no frame', output.size] : [frame?.window, frame?.background, output.aspect, output.size];
|
|
44
|
+
return parts.filter(Boolean).join(' · ') || Object.keys(look).join(', ') || 'empty';
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Local Looks live in the directory CueTake runs in; global ones serve every directory. */
|
|
48
|
+
const scopes = (cwd = process.cwd()) => ({
|
|
49
|
+
local: join(cwd, '.cuetake', 'looks'),
|
|
50
|
+
global: process.env.CUETAKE_LOOK_DIR || join(homedir(), '.local/share/cuetake/looks'),
|
|
51
|
+
});
|
|
52
|
+
function lookPath(name, scope, cwd) {
|
|
53
|
+
if (!/^[a-z0-9][a-z0-9-]{0,63}$/.test(name)) throw new Error('Use a short lowercase Look name, such as brand');
|
|
54
|
+
return join(scopes(cwd)[scope], `${name}.json`);
|
|
55
|
+
}
|
|
56
|
+
function parseLook(data, path) {
|
|
57
|
+
const result = lookSchema.safeParse(data);
|
|
58
|
+
if (!result.success) throw new Error(`${path} is not a valid Look: ${result.error.issues.map(issue => `${issue.path.join('.') || 'look'} ${issue.message}`).join('; ')}`);
|
|
59
|
+
return result.data;
|
|
60
|
+
}
|
|
61
|
+
const readIfPresent = path => fs.readFile(path, 'utf8').catch(error => { if (error.code === 'ENOENT') return null; throw error; });
|
|
62
|
+
|
|
63
|
+
/** A Look by name, local before global, or from a JSON file labeled by its `name` or file name. */
|
|
64
|
+
export async function loadLook(ref, cwd = process.cwd()) {
|
|
65
|
+
if (ref.endsWith('.json')) {
|
|
66
|
+
const path = resolve(cwd, ref);
|
|
67
|
+
const { name = basename(ref, '.json'), ...look } = JSON.parse(await fs.readFile(path, 'utf8'));
|
|
68
|
+
return { name: String(name), look: parseLook(look, path) };
|
|
69
|
+
}
|
|
70
|
+
for (const scope of ['local', 'global']) {
|
|
71
|
+
const path = lookPath(ref, scope, cwd), text = await readIfPresent(path);
|
|
72
|
+
if (text !== null) return { name: ref, scope, look: parseLook(JSON.parse(text), path) };
|
|
73
|
+
}
|
|
74
|
+
const { local, global } = scopes(cwd);
|
|
75
|
+
throw new Error(`No Look named '${ref}' in ${local} or ${global}`);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Every saved Look; a global Look hidden by a local one with the same name is marked shadowed. */
|
|
79
|
+
export async function listLooks(cwd = process.cwd()) {
|
|
80
|
+
const found = [];
|
|
81
|
+
for (const [scope, dir] of Object.entries(scopes(cwd))) {
|
|
82
|
+
const files = await fs.readdir(dir).catch(error => { if (error.code === 'ENOENT') return []; throw error; });
|
|
83
|
+
for (const file of files.filter(f => f.endsWith('.json')).sort()) {
|
|
84
|
+
const name = basename(file, '.json'), path = join(dir, file);
|
|
85
|
+
const summary = await fs.readFile(path, 'utf8').then(text => summarize(parseLook(JSON.parse(text), path)), error => `invalid: ${error.message}`);
|
|
86
|
+
found.push({ name, scope, shadowed: scope === 'global' && found.some(l => l.scope === 'local' && l.name === name), summary, path });
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
return found;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Saves a Look locally unless `global`; an existing Look with the name is kept unless `replace`. */
|
|
93
|
+
export async function saveLook(name, look, { global = false, replace = false, cwd } = {}) {
|
|
94
|
+
const scope = global ? 'global' : 'local', path = lookPath(name, scope, cwd);
|
|
95
|
+
await fs.mkdir(dirname(path), { recursive: true });
|
|
96
|
+
await fs.writeFile(path, JSON.stringify(lookSchema.parse(look), null, 2) + '\n', { flag: replace ? 'w' : 'wx' }).catch(error => {
|
|
97
|
+
if (error.code === 'EEXIST') throw new Error(`A ${scope} Look named '${name}' already exists at ${path}; pass --replace to overwrite it`);
|
|
98
|
+
throw error;
|
|
99
|
+
});
|
|
100
|
+
return { name, scope, path, summary: summarize(look) };
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export async function removeLook(name, { global = false, cwd } = {}) {
|
|
104
|
+
const scope = global ? 'global' : 'local', path = lookPath(name, scope, cwd);
|
|
105
|
+
await fs.rm(path).catch(error => { if (error.code === 'ENOENT') throw new Error(`No ${scope} Look named '${name}' at ${path}`); throw error; });
|
|
106
|
+
return { name, scope, removed: path };
|
|
107
|
+
}
|
package/src/pipeline.js
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
import fs from 'node:fs/promises';
|
|
2
|
+
import { join, resolve } from 'node:path';
|
|
3
|
+
import { pathToFileURL } from 'node:url';
|
|
4
|
+
import { doctor } from './environment.js';
|
|
5
|
+
import { z } from 'zod';
|
|
6
|
+
import { startRecording, getRecordingPage, beginCapture, stopRecording, cleanup } from './recorder.js';
|
|
7
|
+
import { renderFinal, inspectFinal, composePreview } from './render.js';
|
|
8
|
+
import { outputSize } from './stage.js';
|
|
9
|
+
import { resolveAuthProfile } from './auth.js';
|
|
10
|
+
import { createDirector } from './director.js';
|
|
11
|
+
import { collectTimeline } from './probe.js';
|
|
12
|
+
import { editFields, editSchema, createEdit, evenSize } from './edit.js';
|
|
13
|
+
import { loadLook, mergeLook, applyLook, lookFromEdit, saveLook, summarize } from './look.js';
|
|
14
|
+
import pkg from '../package.json' with { type: 'json' };
|
|
15
|
+
|
|
16
|
+
const SCHEMA_VERSION = 2;
|
|
17
|
+
/** Scenario config: capture settings plus the defaults that seed each Take's Edit. */
|
|
18
|
+
export const scenarioSchema = z.object({
|
|
19
|
+
name: z.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/),
|
|
20
|
+
url: z.string().url().refine(s => /^https?:/.test(s), 'Capture requires HTTP(S)'),
|
|
21
|
+
viewport: z.object({ width: evenSize, height: evenSize }).default({ width: 1440, height: 900 }),
|
|
22
|
+
capture: z.object({ fps: z.union([z.literal(30), z.literal(60)]).default(60), resolutionScale: z.union([z.literal(1), z.literal(2)]).default(2) }).default({}),
|
|
23
|
+
...editFields,
|
|
24
|
+
});
|
|
25
|
+
const writeJson = (path, data) => fs.writeFile(path, JSON.stringify(data, null, 2) + '\n');
|
|
26
|
+
const readJson = async path => JSON.parse(await fs.readFile(path, 'utf8'));
|
|
27
|
+
|
|
28
|
+
/** New take directories are exclusive: reruns never overwrite a previous take. */
|
|
29
|
+
export async function recordScenario(scenarioPath, outputDir, options = {}) {
|
|
30
|
+
const scenario = await import(pathToFileURL(resolve(scenarioPath)).href);
|
|
31
|
+
// A Look sits under the Scenario: every field the config names wins over it.
|
|
32
|
+
const look = options.look ? await loadLook(options.look) : null;
|
|
33
|
+
const config = scenarioSchema.parse(look ? mergeLook(look.look, scenario.config) : scenario.config);
|
|
34
|
+
if (typeof scenario.run !== 'function') throw new Error('Scenario must export run(director)');
|
|
35
|
+
const authState = options.authProfile ? await resolveAuthProfile(options.authProfile) : undefined;
|
|
36
|
+
const ready = await doctor();
|
|
37
|
+
if (!ready.ok) throw new Error(JSON.stringify(ready));
|
|
38
|
+
const dir = resolve(outputDir || join('recordings', config.name, new Date().toISOString().replace(/[:.]/g, '-')));
|
|
39
|
+
await fs.mkdir(resolve(dir, '..'), { recursive: true });
|
|
40
|
+
await fs.mkdir(dir); // EEXIST is intentional, including for empty existing folders.
|
|
41
|
+
let project = { schemaVersion: SCHEMA_VERSION, tool: 'CueTake', version: pkg.version, createdAt: new Date().toISOString(), status: 'recording', authenticated: Boolean(authState), ...(look && { look: look.name }), config };
|
|
42
|
+
await writeJson(join(dir, 'project.json'), project);
|
|
43
|
+
await fs.copyFile(resolve(scenarioPath), join(dir, 'scenario.mjs'));
|
|
44
|
+
try {
|
|
45
|
+
const session = await startRecording(config.url, {
|
|
46
|
+
...config.viewport, ...config.capture, outputDir: dir, deferCapture: true, storageState: authState, headed: options.headed,
|
|
47
|
+
});
|
|
48
|
+
const page = getRecordingPage(session.sessionId);
|
|
49
|
+
if (scenario.prepare) await scenario.prepare(page);
|
|
50
|
+
await page.evaluate(() => document.fonts.ready);
|
|
51
|
+
const capture = await beginCapture(session.sessionId);
|
|
52
|
+
const startedAtMs = Date.parse(capture.startedAt);
|
|
53
|
+
const focus = [], wide = [];
|
|
54
|
+
const director = createDirector(page, startedAtMs, config.capture.fps, focus, wide);
|
|
55
|
+
const evidence = await scenario.run(director);
|
|
56
|
+
await page.screenshot({ path: join(dir, 'poster.png') });
|
|
57
|
+
const observed = await collectTimeline(page, startedAtMs);
|
|
58
|
+
const stopped = await stopRecording(session.sessionId);
|
|
59
|
+
await fs.rename(stopped.webmPath, join(dir, 'source.webm'));
|
|
60
|
+
await fs.rename(stopped.webmPath.replace(/\.webm$/, '-capture.json'), join(dir, 'capture.json'));
|
|
61
|
+
const timeline = {
|
|
62
|
+
schemaVersion: SCHEMA_VERSION, viewport: config.viewport, scale: config.capture.resolutionScale, duration: stopped.durationSeconds,
|
|
63
|
+
pointer: observed.pointer, events: [...observed.events, ...focus.map(f => ({ type: 'focus', ...f }))].sort((a, b) => a.t - b.t),
|
|
64
|
+
};
|
|
65
|
+
await writeJson(join(dir, 'timeline.json'), timeline);
|
|
66
|
+
await writeJson(join(dir, 'edit.json'), createEdit(config, timeline, focus, wide));
|
|
67
|
+
project = { ...project, status: 'captured', duration: stopped.durationSeconds, evidence: evidence ?? null };
|
|
68
|
+
await writeJson(join(dir, 'project.json'), project);
|
|
69
|
+
} catch (error) {
|
|
70
|
+
await writeJson(join(dir, 'project.json'), { ...project, status: 'failed', error: error.message });
|
|
71
|
+
throw error;
|
|
72
|
+
} finally { await cleanup(); }
|
|
73
|
+
await renderTake(dir);
|
|
74
|
+
const verification = await verifyTake(dir);
|
|
75
|
+
return { directory: dir, final: join(dir, 'final.mp4'), verification };
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Reads a Take's project.json, Timeline and Edit, refusing Takes from an older schema. */
|
|
79
|
+
async function loadTake(dir) {
|
|
80
|
+
const project = await readJson(join(dir, 'project.json'));
|
|
81
|
+
if (project.schemaVersion !== SCHEMA_VERSION) throw new Error(`${dir} was recorded by an older CueTake (schema ${project.schemaVersion ?? 1}); record it again`);
|
|
82
|
+
return { project, config: scenarioSchema.parse(project.config), timeline: await readJson(join(dir, 'timeline.json')), edit: editSchema.parse(await readJson(join(dir, 'edit.json'))) };
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Writes preview.png: the Take's current Edit beside each Look (names or JSON files), composed at 1080p,
|
|
87
|
+
* whose proportions match every output size. Without `at` it shows the last moment with the camera wide.
|
|
88
|
+
*/
|
|
89
|
+
export async function previewTake(directory, refs = [], { at } = {}) {
|
|
90
|
+
const dir = resolve(directory);
|
|
91
|
+
const { config, timeline, edit } = await loadTake(dir);
|
|
92
|
+
if (refs.length > 5) throw new Error('Compare at most five Looks with the current Edit');
|
|
93
|
+
if (at !== undefined && !(at >= 0 && at <= timeline.duration)) throw new Error(`--at must be between 0 and ${timeline.duration} seconds`);
|
|
94
|
+
const host = new URL(config.url).host;
|
|
95
|
+
const looks = await Promise.all(refs.map(ref => loadLook(ref)));
|
|
96
|
+
const tiles = [{ name: 'current', edit }, ...looks.map(({ name, look }) => ({ name, edit: applyLook(edit, look, host) }))];
|
|
97
|
+
const png = await composePreview({ sourcePath: join(dir, 'source.webm'), timeline, at, tiles: tiles.map(({ name, edit }) => ({ name, edit: { ...edit, output: { ...edit.output, size: '1080p' } } })) });
|
|
98
|
+
const preview = join(dir, 'preview.png');
|
|
99
|
+
await fs.writeFile(preview, png);
|
|
100
|
+
return { preview, at: at ?? 'end, camera wide', tiles: tiles.map(({ name, edit }) => ({ name, summary: summarize(lookFromEdit(edit)) })) };
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** Adopts a Look into the Take's edit.json; the Final changes only after the next Render. */
|
|
104
|
+
export async function applyLookToTake(ref, directory) {
|
|
105
|
+
const dir = resolve(directory);
|
|
106
|
+
const { config, edit } = await loadTake(dir);
|
|
107
|
+
const { name, look } = await loadLook(ref);
|
|
108
|
+
const next = applyLook(edit, look, new URL(config.url).host);
|
|
109
|
+
await writeJson(join(dir, 'edit.json'), next);
|
|
110
|
+
return { look: name, edit: join(dir, 'edit.json'), summary: summarize(lookFromEdit(next)), next: `cuetake render ${dir}` };
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** Saves the Take's styling as a Look, locally unless `global`. */
|
|
114
|
+
export async function saveLookFromTake(name, directory, options) {
|
|
115
|
+
const { edit } = await loadTake(resolve(directory));
|
|
116
|
+
return saveLook(name, lookFromEdit(edit), options);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export async function renderTake(directory) {
|
|
120
|
+
const dir = resolve(directory);
|
|
121
|
+
const { project, config, timeline, edit } = await loadTake(dir);
|
|
122
|
+
// Render to a temporary output; preserve the last complete final if encoding fails.
|
|
123
|
+
const temporary = join(dir, 'final.pending.mp4');
|
|
124
|
+
try {
|
|
125
|
+
const render = await renderFinal({ sourcePath: join(dir, 'source.webm'), finalPath: temporary, timeline, edit });
|
|
126
|
+
await fs.rename(temporary, join(dir, 'final.mp4'));
|
|
127
|
+
await writeJson(join(dir, 'render.json'), render);
|
|
128
|
+
await fs.rm(join(dir, 'verification.json'), { force: true });
|
|
129
|
+
await writeJson(join(dir, 'project.json'), { ...project, status: 'rendered' });
|
|
130
|
+
} catch (error) { await fs.rm(temporary, { force: true }); throw error; }
|
|
131
|
+
return join(dir, 'final.mp4');
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
export function summarizeFrames(frames, duration) {
|
|
135
|
+
const intervals = frames.slice(1).map((f, i) => f.timeMs - frames[i].timeMs);
|
|
136
|
+
const sorted = intervals.toSorted((a, b) => a - b);
|
|
137
|
+
const seconds = Array.from({ length: Math.ceil(duration) }, (_, second) => ({ second, callbacks: frames.filter(f => f.timeMs >= second * 1000 && f.timeMs < (second + 1) * 1000).length }));
|
|
138
|
+
return { callbacks: frames.length, medianIntervalMs: sorted[Math.floor(sorted.length / 2)] ?? null, maxIntervalMs: sorted.at(-1) ?? null, perSecond: seconds, note: 'Source capture is variable frame rate. Static sections reduce cadence; callback counts are observations, not a guarantee of unique encoded frames. Final output uses constant frame rate without motion interpolation.' };
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
export async function verifyTake(directory) {
|
|
142
|
+
const dir = resolve(directory);
|
|
143
|
+
const { project, config, timeline, edit } = await loadTake(dir);
|
|
144
|
+
const media = await inspectFinal(join(dir, 'final.mp4'));
|
|
145
|
+
const { fps } = edit.output;
|
|
146
|
+
const expected = { ...outputSize(edit, timeline.viewport), fps, frames: Math.round(project.duration * fps) };
|
|
147
|
+
const problems = [
|
|
148
|
+
media.width !== expected.width || media.height !== expected.height ? `size ${media.width}×${media.height}, expected ${expected.width}×${expected.height}` : null,
|
|
149
|
+
Math.abs(media.fps - expected.fps) > 0.01 ? `${media.fps} fps, expected ${expected.fps}` : null,
|
|
150
|
+
media.packets !== expected.frames ? `${media.packets} frames, expected ${expected.frames}` : null,
|
|
151
|
+
media.decodedFrames !== media.packets ? `only ${media.decodedFrames} of ${media.packets} frames decoded` : null,
|
|
152
|
+
].filter(Boolean);
|
|
153
|
+
if (problems.length) throw new Error(`Final failed verification: ${problems.join('; ')}`);
|
|
154
|
+
const capture = await readJson(join(dir, 'capture.json'));
|
|
155
|
+
const verification = { passed: true, checkedAt: new Date().toISOString(), media, source: { settings: capture.settings, ...summarizeFrames(capture.frames, capture.duration) }, fullDecode: 'passed' };
|
|
156
|
+
await writeJson(join(dir, 'verification.json'), verification);
|
|
157
|
+
await writeJson(join(dir, 'project.json'), { ...project, status: 'verified' });
|
|
158
|
+
return verification;
|
|
159
|
+
}
|
package/src/probe.js
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* In-page Timeline probe. It records input exactly as the page receives it, so
|
|
3
|
+
* director actions and raw Playwright input are captured alike. All positions
|
|
4
|
+
* are CSS pixels; times are epoch milliseconds until collectTimeline rebases them.
|
|
5
|
+
* Input inside cross-origin iframes never reaches this document and is not seen.
|
|
6
|
+
*/
|
|
7
|
+
export async function installProbe(page) {
|
|
8
|
+
await page.evaluate(() => {
|
|
9
|
+
window.__cuetakeProbe?.dispose();
|
|
10
|
+
const abort = new AbortController();
|
|
11
|
+
const on = (type, fn) => document.addEventListener(type, fn, { capture: true, passive: true, signal: abort.signal });
|
|
12
|
+
const at = event => performance.timeOrigin + event.timeStamp;
|
|
13
|
+
const interactive = 'a,button,input,textarea,select,label,summary,[role],[tabindex],[contenteditable]';
|
|
14
|
+
const box = element => {
|
|
15
|
+
const target = element?.closest?.(interactive) || element;
|
|
16
|
+
const r = target?.getBoundingClientRect?.();
|
|
17
|
+
return r ? { x: r.x, y: r.y, width: r.width, height: r.height } : null;
|
|
18
|
+
};
|
|
19
|
+
const state = { pointer: [], downs: [], ups: [], keys: [] };
|
|
20
|
+
on('pointermove', e => state.pointer.push([at(e), e.clientX, e.clientY]));
|
|
21
|
+
on('pointerdown', e => {
|
|
22
|
+
state.pointer.push([at(e), e.clientX, e.clientY]);
|
|
23
|
+
if (e.button === 0) state.downs.push({ ms: at(e), x: e.clientX, y: e.clientY, box: box(e.target) });
|
|
24
|
+
});
|
|
25
|
+
on('pointerup', e => { if (e.button === 0) state.ups.push({ ms: at(e), x: e.clientX, y: e.clientY }); });
|
|
26
|
+
on('keydown', e => state.keys.push({ ms: at(e), box: box(document.activeElement) }));
|
|
27
|
+
// The tab capture never shows the OS pointer; Render draws the cursor instead.
|
|
28
|
+
const css = document.createElement('style');
|
|
29
|
+
css.textContent = '* { cursor:none !important; }';
|
|
30
|
+
document.documentElement.append(css);
|
|
31
|
+
window.__cuetakeProbe = { state, dispose() { abort.abort(); css.remove(); } };
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const CLICK_SLOP = 6; // CSS px a press may travel and still count as a click
|
|
36
|
+
|
|
37
|
+
/** Rebases probe records to seconds since capture start and derives clicks, drags and typing. */
|
|
38
|
+
export async function collectTimeline(page, startedAtMs) {
|
|
39
|
+
const raw = await page.evaluate(() => window.__cuetakeProbe.state);
|
|
40
|
+
const t = ms => Math.round(ms - startedAtMs) / 1000;
|
|
41
|
+
const pointer = raw.pointer.filter(([ms]) => ms >= startedAtMs).map(([ms, x, y]) => [t(ms), x, y]);
|
|
42
|
+
const events = [];
|
|
43
|
+
for (const down of raw.downs.filter(d => d.ms >= startedAtMs)) {
|
|
44
|
+
const up = raw.ups.find(u => u.ms >= down.ms);
|
|
45
|
+
const moved = up && Math.hypot(up.x - down.x, up.y - down.y) > CLICK_SLOP;
|
|
46
|
+
events.push(moved
|
|
47
|
+
? { type: 'drag', t: t(down.ms), end: t(up.ms), from: { x: down.x, y: down.y }, to: { x: up.x, y: up.y } }
|
|
48
|
+
: { type: 'click', t: t(down.ms), x: down.x, y: down.y, box: down.box });
|
|
49
|
+
}
|
|
50
|
+
// Consecutive keys into the same field within a second form one typing burst.
|
|
51
|
+
for (const key of raw.keys.filter(k => k.ms >= startedAtMs)) {
|
|
52
|
+
const last = events.at(-1);
|
|
53
|
+
if (last?.type === 'type' && t(key.ms) - last.end <= 1 && JSON.stringify(last.box) === JSON.stringify(key.box)) last.end = t(key.ms);
|
|
54
|
+
else events.push({ type: 'type', t: t(key.ms), end: t(key.ms), box: key.box });
|
|
55
|
+
}
|
|
56
|
+
return { pointer, events: events.sort((a, b) => a.t - b.t) };
|
|
57
|
+
}
|
package/src/recorder.js
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { chromium } from 'playwright';
|
|
2
|
+
import { randomUUID } from 'node:crypto';
|
|
3
|
+
import { mkdir } from 'node:fs/promises';
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
import { startTabCapture, stopTabCapture } from './tab-capture.js';
|
|
6
|
+
import { installProbe } from './probe.js';
|
|
7
|
+
|
|
8
|
+
let browser = null;
|
|
9
|
+
const sessions = new Map();
|
|
10
|
+
|
|
11
|
+
export async function startRecording(url, options = {}) {
|
|
12
|
+
const width = options.width || 1440, height = options.height || 900;
|
|
13
|
+
const resolutionScale = options.resolutionScale || 2;
|
|
14
|
+
// Headless by default. Chromium's new headless mode (channel 'chromium') supports tab capture,
|
|
15
|
+
// but only captures at device scale when the scale is also forced on the browser.
|
|
16
|
+
browser ||= await chromium.launch({
|
|
17
|
+
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
|
+
});
|
|
20
|
+
const outputDir = options.outputDir || './recordings';
|
|
21
|
+
await mkdir(outputDir, { recursive: true });
|
|
22
|
+
const context = await browser.newContext({ viewport: { width, height }, deviceScaleFactor: resolutionScale, ...(options.storageState ? { storageState: options.storageState } : {}) });
|
|
23
|
+
const sessionId = randomUUID().slice(0, 8);
|
|
24
|
+
try {
|
|
25
|
+
const page = await context.newPage();
|
|
26
|
+
await page.goto(url, { waitUntil: 'load', timeout: 30_000 });
|
|
27
|
+
sessions.set(sessionId, { context, page, width, height, resolutionScale, options, outputDir });
|
|
28
|
+
if (!options.deferCapture) await beginCapture(sessionId);
|
|
29
|
+
return { sessionId, url };
|
|
30
|
+
} catch (error) { sessions.delete(sessionId); await context.close(); throw error; }
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function getRecordingPage(sessionId) {
|
|
34
|
+
const session = sessions.get(sessionId);
|
|
35
|
+
if (!session) throw new Error(`Unknown session ${sessionId}`);
|
|
36
|
+
return session.page;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export async function beginCapture(sessionId) {
|
|
40
|
+
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
|
+
}
|
|
48
|
+
|
|
49
|
+
export async function stopRecording(sessionId) {
|
|
50
|
+
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);
|
|
54
|
+
await session.context.close();
|
|
55
|
+
sessions.delete(sessionId);
|
|
56
|
+
return { webmPath, durationSeconds: stats.duration };
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export async function cleanup() {
|
|
60
|
+
for (const session of sessions.values()) await session.context.close().catch(() => {});
|
|
61
|
+
sessions.clear();
|
|
62
|
+
await browser?.close().catch(() => {});
|
|
63
|
+
browser = null;
|
|
64
|
+
}
|