@open-take/runtime 0.1.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 +21 -0
- package/dist/cdp-capture-0qW8oOct.js +3 -0
- package/dist/cdp-capture-CWFbnK9C.js +1078 -0
- package/dist/cdp-capture-CWFbnK9C.js.map +1 -0
- package/dist/index.d.ts +345 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +986 -0
- package/dist/index.js.map +1 -0
- package/editor-dist/assets/geist-mono-cyrillic-400-normal-C51Di1Mf.woff2 +0 -0
- package/editor-dist/assets/geist-mono-cyrillic-400-normal-CPJFfJgk.woff +0 -0
- package/editor-dist/assets/geist-mono-cyrillic-500-normal-D2cXvDHF.woff2 +0 -0
- package/editor-dist/assets/geist-mono-cyrillic-500-normal-DfuvdVgn.woff +0 -0
- package/editor-dist/assets/geist-mono-latin-400-normal-B2yvC1Cq.woff +0 -0
- package/editor-dist/assets/geist-mono-latin-400-normal-DTRLJnHl.woff2 +0 -0
- package/editor-dist/assets/geist-mono-latin-500-normal-D-GG86Jb.woff +0 -0
- package/editor-dist/assets/geist-mono-latin-500-normal-YINYabwD.woff2 +0 -0
- package/editor-dist/assets/geist-mono-latin-ext-400-normal-CfzLURNc.woff +0 -0
- package/editor-dist/assets/geist-mono-latin-ext-400-normal-DI-rJ0UV.woff2 +0 -0
- package/editor-dist/assets/geist-mono-latin-ext-500-normal-Buglb9-a.woff2 +0 -0
- package/editor-dist/assets/geist-mono-latin-ext-500-normal-CrWEgvU_.woff +0 -0
- package/editor-dist/assets/geist-mono-symbols2-400-normal-DjbiTEEA.woff +0 -0
- package/editor-dist/assets/geist-mono-symbols2-500-normal-CmnCPGa0.woff +0 -0
- package/editor-dist/assets/geist-mono-vietnamese-400-normal-CZEPLOgu.woff +0 -0
- package/editor-dist/assets/geist-mono-vietnamese-500-normal-Dx9-epDo.woff +0 -0
- package/editor-dist/assets/index-W0-YQO1h.js +49 -0
- package/editor-dist/assets/index-vf4XvOcQ.css +1 -0
- package/editor-dist/assets/instrument-sans-latin-ext-wght-normal-B5bTHO_g.woff2 +0 -0
- package/editor-dist/assets/instrument-sans-latin-wght-normal-BbzFLZTg.woff2 +0 -0
- package/editor-dist/index.html +15 -0
- package/editor-dist/sample/capture.json +113 -0
- package/editor-dist/sample/capture.mp4 +0 -0
- package/editor-dist/sample/composition.json +233 -0
- package/package.json +55 -0
|
@@ -0,0 +1,1078 @@
|
|
|
1
|
+
import { homedir, tmpdir } from "node:os";
|
|
2
|
+
import { dirname, join, resolve } from "node:path";
|
|
3
|
+
import { resolveFfmpeg, resolveFfprobe } from "@open-take/compositor";
|
|
4
|
+
import { spawn } from "node:child_process";
|
|
5
|
+
import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
|
|
6
|
+
import { createRequire } from "node:module";
|
|
7
|
+
|
|
8
|
+
//#region src/cdp.ts
|
|
9
|
+
const sleep$2 = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
10
|
+
const require = createRequire(import.meta.url);
|
|
11
|
+
const CHROME_CACHE = join(homedir(), ".open-take", "browsers");
|
|
12
|
+
const BUILDID_FILE = join(homedir(), ".open-take", "chrome-build.json");
|
|
13
|
+
function resolveChrome(explicit) {
|
|
14
|
+
const candidates = [];
|
|
15
|
+
if (explicit) candidates.push(explicit);
|
|
16
|
+
if (process.env.OPEN_TAKE_CHROME) candidates.push(process.env.OPEN_TAKE_CHROME);
|
|
17
|
+
if (existsSync(BUILDID_FILE)) try {
|
|
18
|
+
const exe = computeChromePathSync(JSON.parse(readFileSync(BUILDID_FILE, "utf8")).buildId);
|
|
19
|
+
if (exe) candidates.push(exe);
|
|
20
|
+
} catch {}
|
|
21
|
+
const abBrowsers = join(homedir(), ".agent-browser", "browsers");
|
|
22
|
+
if (existsSync(abBrowsers)) for (const d of readdirSync(abBrowsers).filter((n) => n.startsWith("chrome-")).sort().reverse()) candidates.push(join(abBrowsers, d, "Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing"), join(abBrowsers, d, "chrome-linux64", "chrome"), join(abBrowsers, d, "chrome"));
|
|
23
|
+
return candidates.find((c) => c && existsSync(c)) ?? null;
|
|
24
|
+
}
|
|
25
|
+
function computeChromePathSync(buildId) {
|
|
26
|
+
try {
|
|
27
|
+
const { computeExecutablePath, Browser } = require("@puppeteer/browsers");
|
|
28
|
+
return computeExecutablePath({
|
|
29
|
+
browser: Browser.CHROME,
|
|
30
|
+
buildId,
|
|
31
|
+
cacheDir: CHROME_CACHE
|
|
32
|
+
});
|
|
33
|
+
} catch {
|
|
34
|
+
return null;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
async function ensureChrome(explicit) {
|
|
38
|
+
const found = resolveChrome(explicit);
|
|
39
|
+
if (found) return found;
|
|
40
|
+
try {
|
|
41
|
+
const { install, resolveBuildId, detectBrowserPlatform, computeExecutablePath, Browser } = await import("@puppeteer/browsers");
|
|
42
|
+
const platform = detectBrowserPlatform();
|
|
43
|
+
if (!platform) throw new Error("unsupported platform");
|
|
44
|
+
const buildId = await resolveBuildId(Browser.CHROME, platform, "stable");
|
|
45
|
+
const exe = computeExecutablePath({
|
|
46
|
+
browser: Browser.CHROME,
|
|
47
|
+
buildId,
|
|
48
|
+
cacheDir: CHROME_CACHE
|
|
49
|
+
});
|
|
50
|
+
if (!existsSync(exe)) {
|
|
51
|
+
mkdirSync(CHROME_CACHE, { recursive: true });
|
|
52
|
+
process.stderr.write(`open-take: downloading Chrome for Testing (${buildId}, one-time) → ${CHROME_CACHE}\n`);
|
|
53
|
+
let lastPct = -1;
|
|
54
|
+
await install({
|
|
55
|
+
browser: Browser.CHROME,
|
|
56
|
+
buildId,
|
|
57
|
+
cacheDir: CHROME_CACHE,
|
|
58
|
+
downloadProgressCallback: (downloaded, total) => {
|
|
59
|
+
if (!total) return;
|
|
60
|
+
const pct = Math.floor(downloaded / total * 100);
|
|
61
|
+
if (pct >= lastPct + 10 || pct === 100) {
|
|
62
|
+
lastPct = pct;
|
|
63
|
+
process.stderr.write(`open-take: …Chrome download ${pct}%\n`);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
});
|
|
67
|
+
process.stderr.write("open-take: Chrome ready.\n");
|
|
68
|
+
}
|
|
69
|
+
mkdirSync(dirname(BUILDID_FILE), { recursive: true });
|
|
70
|
+
writeFileSync(BUILDID_FILE, JSON.stringify({ buildId }));
|
|
71
|
+
return exe;
|
|
72
|
+
} catch (e) {
|
|
73
|
+
throw new Error(`open-take: no Chrome found and auto-download failed (${e.message}). Install Chrome/Chromium, or set OPEN_TAKE_CHROME to a Chrome binary.`);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
var CDP = class CDP {
|
|
77
|
+
ws;
|
|
78
|
+
id = 0;
|
|
79
|
+
pending = new Map();
|
|
80
|
+
handlers = new Map();
|
|
81
|
+
constructor(ws) {
|
|
82
|
+
this.ws = ws;
|
|
83
|
+
ws.addEventListener("message", (ev) => {
|
|
84
|
+
const msg = JSON.parse(ev.data);
|
|
85
|
+
if (msg.id != null && this.pending.has(msg.id)) {
|
|
86
|
+
const { resolve: resolve$1, reject } = this.pending.get(msg.id);
|
|
87
|
+
this.pending.delete(msg.id);
|
|
88
|
+
msg.error ? reject(new Error(JSON.stringify(msg.error))) : resolve$1(msg.result);
|
|
89
|
+
} else if (msg.method) this.handlers.get(msg.method)?.(msg.params);
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
static connect(wsUrl) {
|
|
93
|
+
return new Promise((resolve$1, reject) => {
|
|
94
|
+
const ws = new WebSocket(wsUrl);
|
|
95
|
+
ws.addEventListener("open", () => resolve$1(new CDP(ws)));
|
|
96
|
+
ws.addEventListener("error", () => reject(new Error(`CDP connect failed: ${wsUrl}`)));
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
send(method, params = {}) {
|
|
100
|
+
const id = ++this.id;
|
|
101
|
+
return new Promise((resolve$1, reject) => {
|
|
102
|
+
this.pending.set(id, {
|
|
103
|
+
resolve: resolve$1,
|
|
104
|
+
reject
|
|
105
|
+
});
|
|
106
|
+
this.ws.send(JSON.stringify({
|
|
107
|
+
id,
|
|
108
|
+
method,
|
|
109
|
+
params
|
|
110
|
+
}));
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
on(method, fn) {
|
|
114
|
+
this.handlers.set(method, fn);
|
|
115
|
+
}
|
|
116
|
+
close() {
|
|
117
|
+
try {
|
|
118
|
+
this.ws.close();
|
|
119
|
+
} catch {}
|
|
120
|
+
}
|
|
121
|
+
};
|
|
122
|
+
/** Launch headless Chrome, return a CDP session bound to its page target. */
|
|
123
|
+
async function launchBrowser(opts) {
|
|
124
|
+
const chrome = await ensureChrome(opts.chromePath);
|
|
125
|
+
const userDir = mkdtempSync(join(tmpdir(), "open-take-cdp-"));
|
|
126
|
+
const proc = spawn(chrome, [
|
|
127
|
+
"--remote-debugging-port=0",
|
|
128
|
+
`--user-data-dir=${userDir}`,
|
|
129
|
+
`--window-size=${opts.width},${opts.height}`,
|
|
130
|
+
"--headless=new",
|
|
131
|
+
"--no-sandbox",
|
|
132
|
+
"--password-store=basic",
|
|
133
|
+
"--use-mock-keychain",
|
|
134
|
+
"--no-first-run",
|
|
135
|
+
"--no-default-browser-check",
|
|
136
|
+
"--hide-scrollbars",
|
|
137
|
+
"--disable-extensions",
|
|
138
|
+
"--disable-background-networking",
|
|
139
|
+
"--disable-features=Translate,AcceptCHFrame,MediaRouter,OptimizationHints",
|
|
140
|
+
"--mute-audio",
|
|
141
|
+
"about:blank"
|
|
142
|
+
], { stdio: [
|
|
143
|
+
"ignore",
|
|
144
|
+
"ignore",
|
|
145
|
+
"pipe"
|
|
146
|
+
] });
|
|
147
|
+
let stderr = "";
|
|
148
|
+
proc.stderr?.on("data", (d) => stderr += d);
|
|
149
|
+
const close = async () => {
|
|
150
|
+
const exited = new Promise((res) => {
|
|
151
|
+
if (proc.exitCode != null) return res();
|
|
152
|
+
proc.once("exit", () => res());
|
|
153
|
+
setTimeout(res, 2e3);
|
|
154
|
+
});
|
|
155
|
+
try {
|
|
156
|
+
proc.kill("SIGKILL");
|
|
157
|
+
} catch {}
|
|
158
|
+
await exited;
|
|
159
|
+
rmSync(userDir, {
|
|
160
|
+
recursive: true,
|
|
161
|
+
force: true,
|
|
162
|
+
maxRetries: 5,
|
|
163
|
+
retryDelay: 100
|
|
164
|
+
});
|
|
165
|
+
};
|
|
166
|
+
try {
|
|
167
|
+
const port = await readDevtoolsPort(userDir, proc);
|
|
168
|
+
const target = await pageTargetWs(port);
|
|
169
|
+
const cdp = await CDP.connect(target.wsUrl);
|
|
170
|
+
return {
|
|
171
|
+
cdp,
|
|
172
|
+
targetId: target.id,
|
|
173
|
+
close
|
|
174
|
+
};
|
|
175
|
+
} catch (e) {
|
|
176
|
+
await close();
|
|
177
|
+
throw new Error(`open-take(hi-fps): browser launch failed: ${e.message}\n${stderr.slice(-600)}`);
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
async function readDevtoolsPort(userDir, proc) {
|
|
181
|
+
const file = join(userDir, "DevToolsActivePort");
|
|
182
|
+
for (let i = 0; i < 100; i++) {
|
|
183
|
+
if (proc.exitCode != null) throw new Error(`chrome exited early (${proc.exitCode})`);
|
|
184
|
+
if (existsSync(file)) {
|
|
185
|
+
const line = readFileSync(file, "utf8").split("\n")[0]?.trim();
|
|
186
|
+
const port = Number(line);
|
|
187
|
+
if (Number.isFinite(port) && port > 0) return port;
|
|
188
|
+
}
|
|
189
|
+
await sleep$2(50);
|
|
190
|
+
}
|
|
191
|
+
throw new Error("timed out waiting for DevToolsActivePort");
|
|
192
|
+
}
|
|
193
|
+
async function pageTargetWs(port) {
|
|
194
|
+
for (let i = 0; i < 60; i++) {
|
|
195
|
+
try {
|
|
196
|
+
const list = await (await fetch(`http://localhost:${port}/json`)).json();
|
|
197
|
+
const page = list.find((t) => t.type === "page");
|
|
198
|
+
if (page?.webSocketDebuggerUrl) return {
|
|
199
|
+
wsUrl: page.webSocketDebuggerUrl,
|
|
200
|
+
id: page.id
|
|
201
|
+
};
|
|
202
|
+
} catch {}
|
|
203
|
+
await sleep$2(100);
|
|
204
|
+
}
|
|
205
|
+
throw new Error("no page target appeared");
|
|
206
|
+
}
|
|
207
|
+
async function fitViewport(cdp, targetId, vw, vh) {
|
|
208
|
+
const readInner = async () => {
|
|
209
|
+
const r = await cdp.send("Runtime.evaluate", {
|
|
210
|
+
expression: "JSON.stringify([window.innerWidth, window.innerHeight])",
|
|
211
|
+
returnByValue: true
|
|
212
|
+
});
|
|
213
|
+
const v = JSON.parse(r.result?.value ?? "[0,0]");
|
|
214
|
+
return [Number(v[0]), Number(v[1])];
|
|
215
|
+
};
|
|
216
|
+
let win = null;
|
|
217
|
+
try {
|
|
218
|
+
win = await cdp.send("Browser.getWindowForTarget", { targetId });
|
|
219
|
+
} catch {
|
|
220
|
+
return readInner();
|
|
221
|
+
}
|
|
222
|
+
if (!win?.windowId) return readInner();
|
|
223
|
+
let { width, height } = win.bounds;
|
|
224
|
+
let inner = await readInner();
|
|
225
|
+
for (let i = 0; i < 4; i++) {
|
|
226
|
+
const dw = vw - inner[0];
|
|
227
|
+
const dh = vh - inner[1];
|
|
228
|
+
if (Math.abs(dw) <= 1 && Math.abs(dh) <= 1) break;
|
|
229
|
+
width += dw;
|
|
230
|
+
height += dh;
|
|
231
|
+
await cdp.send("Browser.setWindowBounds", {
|
|
232
|
+
windowId: win.windowId,
|
|
233
|
+
bounds: {
|
|
234
|
+
width,
|
|
235
|
+
height
|
|
236
|
+
}
|
|
237
|
+
});
|
|
238
|
+
await sleep$2(120);
|
|
239
|
+
inner = await readInner();
|
|
240
|
+
}
|
|
241
|
+
return inner;
|
|
242
|
+
}
|
|
243
|
+
var Screencast = class {
|
|
244
|
+
cdp;
|
|
245
|
+
dir;
|
|
246
|
+
t0 = 0;
|
|
247
|
+
n = 0;
|
|
248
|
+
frames = [];
|
|
249
|
+
constructor(cdp, dir) {
|
|
250
|
+
this.cdp = cdp;
|
|
251
|
+
this.dir = dir;
|
|
252
|
+
}
|
|
253
|
+
/** Begin capture. `t0` (Date.now) anchors every frame + event onto one clock. */
|
|
254
|
+
async start(t0, opts) {
|
|
255
|
+
this.t0 = t0;
|
|
256
|
+
this.cdp.on("Page.screencastFrame", (p) => {
|
|
257
|
+
const off = Date.now() - this.t0;
|
|
258
|
+
const file = join(this.dir, `f-${String(this.n++).padStart(5, "0")}.jpg`);
|
|
259
|
+
writeFileSync(file, Buffer.from(p.data, "base64"));
|
|
260
|
+
this.frames.push({
|
|
261
|
+
file,
|
|
262
|
+
offMs: off
|
|
263
|
+
});
|
|
264
|
+
this.cdp.send("Page.screencastFrameAck", { sessionId: p.sessionId }).catch(() => {});
|
|
265
|
+
});
|
|
266
|
+
await this.cdp.send("Page.startScreencast", {
|
|
267
|
+
format: "jpeg",
|
|
268
|
+
quality: opts.quality ?? 90,
|
|
269
|
+
maxWidth: opts.maxWidth,
|
|
270
|
+
maxHeight: opts.maxHeight,
|
|
271
|
+
everyNthFrame: 1
|
|
272
|
+
});
|
|
273
|
+
}
|
|
274
|
+
async stop() {
|
|
275
|
+
await this.cdp.send("Page.stopScreencast").catch(() => {});
|
|
276
|
+
}
|
|
277
|
+
};
|
|
278
|
+
async function encodeFrames(frames, endMs, outPath, fps, ffmpegBin) {
|
|
279
|
+
if (frames.length === 0) throw new Error("open-take(hi-fps): no frames captured");
|
|
280
|
+
const bin = ffmpegBin ?? await resolveFfmpeg();
|
|
281
|
+
const dir = frames[0].file.slice(0, frames[0].file.lastIndexOf("/"));
|
|
282
|
+
const listPath = join(dir, "frames.concat");
|
|
283
|
+
const lines = [];
|
|
284
|
+
const bounds = [
|
|
285
|
+
0,
|
|
286
|
+
...frames.slice(1).map((f) => f.offMs),
|
|
287
|
+
Math.max(endMs, frames[frames.length - 1].offMs + 33)
|
|
288
|
+
];
|
|
289
|
+
for (let i = 0; i < frames.length; i++) {
|
|
290
|
+
const dur = Math.max(.001, (bounds[i + 1] - bounds[i]) / 1e3);
|
|
291
|
+
lines.push(`file '${frames[i].file}'`, `duration ${dur.toFixed(4)}`);
|
|
292
|
+
}
|
|
293
|
+
lines.push(`file '${frames[frames.length - 1].file}'`);
|
|
294
|
+
writeFileSync(listPath, lines.join("\n"));
|
|
295
|
+
const isWebm = /\.webm$/i.test(outPath);
|
|
296
|
+
const codec = isWebm ? [
|
|
297
|
+
"-c:v",
|
|
298
|
+
"libvpx-vp9",
|
|
299
|
+
"-b:v",
|
|
300
|
+
"0",
|
|
301
|
+
"-crf",
|
|
302
|
+
"28",
|
|
303
|
+
"-deadline",
|
|
304
|
+
"good",
|
|
305
|
+
"-cpu-used",
|
|
306
|
+
"4"
|
|
307
|
+
] : [
|
|
308
|
+
"-c:v",
|
|
309
|
+
"libx264",
|
|
310
|
+
"-preset",
|
|
311
|
+
"veryfast",
|
|
312
|
+
"-crf",
|
|
313
|
+
"18"
|
|
314
|
+
];
|
|
315
|
+
const colorConvert = isWebm ? "" : ":in_range=full:in_color_matrix=bt470bg:out_range=tv:out_color_matrix=bt709";
|
|
316
|
+
const colorLabel = isWebm ? "" : ",setparams=range=tv:colorspace=bt709:color_primaries=bt709:color_trc=bt709";
|
|
317
|
+
return new Promise((resolve$1, reject) => {
|
|
318
|
+
const args = [
|
|
319
|
+
"-y",
|
|
320
|
+
"-loglevel",
|
|
321
|
+
"error",
|
|
322
|
+
"-f",
|
|
323
|
+
"concat",
|
|
324
|
+
"-safe",
|
|
325
|
+
"0",
|
|
326
|
+
"-i",
|
|
327
|
+
listPath,
|
|
328
|
+
"-vsync",
|
|
329
|
+
"cfr",
|
|
330
|
+
"-r",
|
|
331
|
+
String(fps),
|
|
332
|
+
"-vf",
|
|
333
|
+
`scale=trunc(iw/2)*2:trunc(ih/2)*2${colorConvert},format=yuv420p${colorLabel}`,
|
|
334
|
+
...codec,
|
|
335
|
+
outPath
|
|
336
|
+
];
|
|
337
|
+
const c = spawn(bin, args, { stdio: [
|
|
338
|
+
"ignore",
|
|
339
|
+
"ignore",
|
|
340
|
+
"pipe"
|
|
341
|
+
] });
|
|
342
|
+
let err = "";
|
|
343
|
+
c.stderr.on("data", (d) => err += d);
|
|
344
|
+
c.on("error", reject);
|
|
345
|
+
c.on("close", (code) => code === 0 ? resolve$1() : reject(new Error(`ffmpeg encode exited ${code}: ${err.slice(-800)}`)));
|
|
346
|
+
});
|
|
347
|
+
}
|
|
348
|
+
/** A throwaway temp dir for the screencast's per-frame JPEGs. */
|
|
349
|
+
const makeFrameDir = () => mkdtempSync(join(tmpdir(), "open-take-frames-"));
|
|
350
|
+
|
|
351
|
+
//#endregion
|
|
352
|
+
//#region src/capture.ts
|
|
353
|
+
const sleep$1 = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
354
|
+
function findBox(o) {
|
|
355
|
+
if (!o || typeof o !== "object") return null;
|
|
356
|
+
const r = o;
|
|
357
|
+
if (typeof r.x === "number" && typeof r.y === "number" && (typeof r.width === "number" || typeof r.w === "number")) return {
|
|
358
|
+
x: r.x,
|
|
359
|
+
y: r.y,
|
|
360
|
+
w: r.width ?? r.w,
|
|
361
|
+
h: r.height ?? r.h
|
|
362
|
+
};
|
|
363
|
+
for (const k of Object.keys(r)) {
|
|
364
|
+
const hit = findBox(r[k]);
|
|
365
|
+
if (hit) return hit;
|
|
366
|
+
}
|
|
367
|
+
return null;
|
|
368
|
+
}
|
|
369
|
+
function deepParse(s) {
|
|
370
|
+
let cur = s;
|
|
371
|
+
for (let i = 0; i < 5 && typeof cur === "string"; i++) try {
|
|
372
|
+
cur = JSON.parse(cur);
|
|
373
|
+
} catch {
|
|
374
|
+
break;
|
|
375
|
+
}
|
|
376
|
+
return cur;
|
|
377
|
+
}
|
|
378
|
+
function evalValue(raw) {
|
|
379
|
+
let top;
|
|
380
|
+
try {
|
|
381
|
+
top = JSON.parse(raw);
|
|
382
|
+
} catch {
|
|
383
|
+
return deepParse(raw);
|
|
384
|
+
}
|
|
385
|
+
if (top && typeof top === "object") {
|
|
386
|
+
const o = top;
|
|
387
|
+
const data = o.data;
|
|
388
|
+
if (data && "result" in data) return deepParse(data.result);
|
|
389
|
+
for (const k of [
|
|
390
|
+
"result",
|
|
391
|
+
"output",
|
|
392
|
+
"stdout",
|
|
393
|
+
"value"
|
|
394
|
+
]) if (k in o) return deepParse(o[k]);
|
|
395
|
+
}
|
|
396
|
+
return deepParse(top);
|
|
397
|
+
}
|
|
398
|
+
function clickByTextJs(text) {
|
|
399
|
+
const t = JSON.stringify(text);
|
|
400
|
+
return `(function(){var t=${t};var els=Array.prototype.slice.call(document.querySelectorAll('button,a,[role=button],[role=link],[role=menuitem],input[type=submit],input[type=button]'));function name(e){return (e.getAttribute('aria-label')||e.textContent||'').replace(/\\s+/g,' ').trim();}var m=els.filter(function(e){return name(e)===t;})[0]||els.filter(function(e){return name(e).indexOf(t)!==-1;})[0];if(!m)return 'NOTFOUND';var r=m.getBoundingClientRect();if(r.top<0||r.bottom>window.innerHeight){m.scrollIntoView({block:'center'});r=m.getBoundingClientRect();}var b={x:Math.round(r.x),y:Math.round(r.y),w:Math.round(r.width),h:Math.round(r.height)};m.click();return JSON.stringify(b);})()`;
|
|
401
|
+
}
|
|
402
|
+
function clickBySelectorJs(selector) {
|
|
403
|
+
const s = JSON.stringify(selector);
|
|
404
|
+
return `(function(){var m=document.querySelector(${s});if(!m)return 'NOTFOUND';var r=m.getBoundingClientRect();if(r.top<0||r.bottom>window.innerHeight){m.scrollIntoView({block:'center'});r=m.getBoundingClientRect();}var b={x:Math.round(r.x),y:Math.round(r.y),w:Math.round(r.width),h:Math.round(r.height)};m.click();return JSON.stringify(b);})()`;
|
|
405
|
+
}
|
|
406
|
+
function focusFieldByTextJs(text) {
|
|
407
|
+
const t = JSON.stringify(text);
|
|
408
|
+
return `(function(){var t=${t};var els=Array.prototype.slice.call(document.querySelectorAll('input,textarea,[contenteditable],[contenteditable=true],[role=textbox],[role=searchbox]'));function name(e){return (e.getAttribute('aria-label')||e.getAttribute('placeholder')||e.textContent||'').replace(/\\s+/g,' ').trim();}var m=els.filter(function(e){return name(e)===t;})[0]||els.filter(function(e){return name(e).indexOf(t)!==-1;})[0];if(!m)return 'NOTFOUND';var r=m.getBoundingClientRect();if(r.top<0||r.bottom>window.innerHeight){m.scrollIntoView({block:'center'});r=m.getBoundingClientRect();}var b={x:Math.round(r.x),y:Math.round(r.y),w:Math.round(r.width),h:Math.round(r.height)};m.focus();m.click();m.focus();return JSON.stringify(b);})()`;
|
|
409
|
+
}
|
|
410
|
+
function focusSelectorJs(selector) {
|
|
411
|
+
const s = JSON.stringify(selector);
|
|
412
|
+
return `(function(){var m=document.querySelector(${s});if(!m)return 'NOTFOUND';var r=m.getBoundingClientRect();if(r.top<0||r.bottom>window.innerHeight){m.scrollIntoView({block:'center'});r=m.getBoundingClientRect();}var b={x:Math.round(r.x),y:Math.round(r.y),w:Math.round(r.width),h:Math.round(r.height)};m.focus();m.click();m.focus();return JSON.stringify(b);})()`;
|
|
413
|
+
}
|
|
414
|
+
function boxSelectorJs(selector) {
|
|
415
|
+
const s = JSON.stringify(selector);
|
|
416
|
+
return `(function(){var m=document.querySelector(${s});if(!m)return 'NOTFOUND';var r=m.getBoundingClientRect();if(r.top<0||r.bottom>window.innerHeight){m.scrollIntoView({block:'center'});r=m.getBoundingClientRect();}return JSON.stringify({x:Math.round(r.x),y:Math.round(r.y),w:Math.round(r.width),h:Math.round(r.height)});})()`;
|
|
417
|
+
}
|
|
418
|
+
function boxByTextJs(text) {
|
|
419
|
+
const t = JSON.stringify(text);
|
|
420
|
+
return `(function(){var t=${t};var els=Array.prototype.slice.call(document.querySelectorAll('button,a,[role=button],[role=link],[role=menuitem],[aria-label],[title],img[alt],li,[draggable=true]'));function name(e){return (e.getAttribute('aria-label')||e.getAttribute('title')||e.getAttribute('alt')||e.textContent||'').replace(/\\s+/g,' ').trim();}var m=els.filter(function(e){return name(e)===t;})[0]||els.filter(function(e){return name(e).indexOf(t)!==-1;})[0];if(!m)return 'NOTFOUND';var r=m.getBoundingClientRect();if(r.top<0||r.bottom>window.innerHeight){m.scrollIntoView({block:'center'});r=m.getBoundingClientRect();}return JSON.stringify({x:Math.round(r.x),y:Math.round(r.y),w:Math.round(r.width),h:Math.round(r.height)});})()`;
|
|
421
|
+
}
|
|
422
|
+
function scrollDeltaSelectorJs(selector) {
|
|
423
|
+
const s = JSON.stringify(selector);
|
|
424
|
+
return `(function(){var m=document.querySelector(${s});if(!m)return 'NOTFOUND';var r=m.getBoundingClientRect();return JSON.stringify({dy:Math.round(r.top+r.height/2-window.innerHeight/2)});})()`;
|
|
425
|
+
}
|
|
426
|
+
function scrollDeltaByTextJs(text) {
|
|
427
|
+
const t = JSON.stringify(text);
|
|
428
|
+
return `(function(){var t=${t};var els=Array.prototype.slice.call(document.querySelectorAll('button,a,[role=button],[role=link],[role=heading],[aria-label],[title],h1,h2,h3,li,section,p'));function name(e){return (e.getAttribute('aria-label')||e.getAttribute('title')||e.textContent||'').replace(/\\s+/g,' ').trim();}var m=els.filter(function(e){return name(e)===t;})[0]||els.filter(function(e){return name(e).indexOf(t)!==-1;})[0];if(!m)return 'NOTFOUND';var r=m.getBoundingClientRect();return JSON.stringify({dy:Math.round(r.top+r.height/2-window.innerHeight/2)});})()`;
|
|
429
|
+
}
|
|
430
|
+
function sampleAlong(pts, u) {
|
|
431
|
+
if (pts.length === 1) return pts[0];
|
|
432
|
+
const seg = [];
|
|
433
|
+
let total = 0;
|
|
434
|
+
for (let i = 0; i < pts.length - 1; i++) {
|
|
435
|
+
const d = Math.hypot(pts[i + 1].x - pts[i].x, pts[i + 1].y - pts[i].y);
|
|
436
|
+
seg.push(d);
|
|
437
|
+
total += d;
|
|
438
|
+
}
|
|
439
|
+
if (total === 0) return pts[0];
|
|
440
|
+
let target = u * total;
|
|
441
|
+
for (let i = 0; i < seg.length; i++) {
|
|
442
|
+
if (target <= seg[i] || i === seg.length - 1) {
|
|
443
|
+
const f = seg[i] > 0 ? target / seg[i] : 0;
|
|
444
|
+
return {
|
|
445
|
+
x: pts[i].x + (pts[i + 1].x - pts[i].x) * f,
|
|
446
|
+
y: pts[i].y + (pts[i + 1].y - pts[i].y) * f
|
|
447
|
+
};
|
|
448
|
+
}
|
|
449
|
+
target -= seg[i];
|
|
450
|
+
}
|
|
451
|
+
return pts[pts.length - 1];
|
|
452
|
+
}
|
|
453
|
+
async function ffprobe(path) {
|
|
454
|
+
const bin = await resolveFfprobe().catch(() => null);
|
|
455
|
+
if (!bin) return {};
|
|
456
|
+
return new Promise((res) => {
|
|
457
|
+
const c = spawn(bin, [
|
|
458
|
+
"-v",
|
|
459
|
+
"error",
|
|
460
|
+
"-select_streams",
|
|
461
|
+
"v:0",
|
|
462
|
+
"-show_entries",
|
|
463
|
+
"stream=width,height,r_frame_rate,duration",
|
|
464
|
+
"-show_entries",
|
|
465
|
+
"format=duration",
|
|
466
|
+
"-of",
|
|
467
|
+
"json",
|
|
468
|
+
path
|
|
469
|
+
], { stdio: [
|
|
470
|
+
"ignore",
|
|
471
|
+
"pipe",
|
|
472
|
+
"ignore"
|
|
473
|
+
] });
|
|
474
|
+
let out = "";
|
|
475
|
+
c.stdout.on("data", (d) => out += d);
|
|
476
|
+
c.on("close", () => {
|
|
477
|
+
try {
|
|
478
|
+
const j = JSON.parse(out);
|
|
479
|
+
const s = j.streams?.[0] ?? {};
|
|
480
|
+
res({
|
|
481
|
+
width: s.width,
|
|
482
|
+
height: s.height,
|
|
483
|
+
fps: s.r_frame_rate,
|
|
484
|
+
durationS: Number(s.duration ?? j.format?.duration ?? 0)
|
|
485
|
+
});
|
|
486
|
+
} catch {
|
|
487
|
+
res({});
|
|
488
|
+
}
|
|
489
|
+
});
|
|
490
|
+
});
|
|
491
|
+
}
|
|
492
|
+
/** Drive `plan` against the live app over CDP, return the ground-truth log. */
|
|
493
|
+
async function captureTake(plan, opts) {
|
|
494
|
+
const { captureTakeCDP: captureTakeCDP$1 } = await import("./cdp-capture-0qW8oOct.js");
|
|
495
|
+
return captureTakeCDP$1(plan, {
|
|
496
|
+
...opts,
|
|
497
|
+
fps: opts.fps ?? 60
|
|
498
|
+
});
|
|
499
|
+
}
|
|
500
|
+
function listInteractiveJs() {
|
|
501
|
+
return "(function(){function nm(e){return (e.getAttribute('aria-label')||e.textContent||'').replace(/\\s+/g,' ').trim();}var sel='button,a,[role=button],[role=link],[role=menuitem],[role=tab],[role=switch],[role=checkbox],input,select,textarea';var els=Array.prototype.slice.call(document.querySelectorAll(sel));var vw=window.innerWidth,vh=window.innerHeight;var out=[];var seen={};for(var i=0;i<els.length;i++){var e=els[i];var n=nm(e);var ph=e.getAttribute('placeholder');var r=e.getBoundingClientRect();if(r.width<6||r.height<6)continue;if(!n&&!ph)continue;var label=n||('['+(ph||e.tagName.toLowerCase())+']');var key=label+'@'+Math.round(r.x)+','+Math.round(r.y);if(seen[key])continue;seen[key]=1;var iv=r.top<vh&&r.bottom>0&&r.left<vw&&r.right>0;out.push({name:label,tag:e.tagName.toLowerCase(),role:e.getAttribute('role')||null,href:e.getAttribute('href')||null,inView:iv,x:Math.round(r.x),y:Math.round(r.y),w:Math.round(r.width),h:Math.round(r.height)});}out.sort(function(a,b){return (b.inView?1:0)-(a.inView?1:0);});return JSON.stringify(out.slice(0,60));})()";
|
|
502
|
+
}
|
|
503
|
+
/** Open `url`, return its interactive elements (accessible name + bbox) —
|
|
504
|
+
* what an agent uses to choose a demo flow. Pure CDP, same as capture, so
|
|
505
|
+
* the reported coordinate space matches what capture will drive against. */
|
|
506
|
+
async function inspectPage(url, opts = {}) {
|
|
507
|
+
const vw = opts.viewport?.width ?? 1920;
|
|
508
|
+
const vh = opts.viewport?.height ?? 1080;
|
|
509
|
+
const browser = await launchBrowser({
|
|
510
|
+
width: vw,
|
|
511
|
+
height: vh,
|
|
512
|
+
chromePath: opts.chromePath
|
|
513
|
+
});
|
|
514
|
+
try {
|
|
515
|
+
const { cdp } = browser;
|
|
516
|
+
await cdp.send("Page.enable");
|
|
517
|
+
await cdp.send("Runtime.enable");
|
|
518
|
+
const inner = await fitViewport(cdp, browser.targetId, vw, vh);
|
|
519
|
+
await cdp.send("Page.navigate", { url });
|
|
520
|
+
await sleep$1(opts.warmupMs ?? 1500);
|
|
521
|
+
const evalRaw = async (expr) => {
|
|
522
|
+
const r = await cdp.send("Runtime.evaluate", {
|
|
523
|
+
expression: expr,
|
|
524
|
+
returnByValue: true
|
|
525
|
+
});
|
|
526
|
+
return String(r.result?.value ?? "");
|
|
527
|
+
};
|
|
528
|
+
let elements = [];
|
|
529
|
+
try {
|
|
530
|
+
const v = evalValue(await evalRaw(listInteractiveJs()));
|
|
531
|
+
if (Array.isArray(v)) elements = v;
|
|
532
|
+
} catch {}
|
|
533
|
+
return {
|
|
534
|
+
url,
|
|
535
|
+
viewport: {
|
|
536
|
+
w: inner[0],
|
|
537
|
+
h: inner[1]
|
|
538
|
+
},
|
|
539
|
+
elements
|
|
540
|
+
};
|
|
541
|
+
} finally {
|
|
542
|
+
await browser.close();
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
//#endregion
|
|
547
|
+
//#region src/cdp-capture.ts
|
|
548
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
549
|
+
const smoother = (u) => {
|
|
550
|
+
u = Math.max(0, Math.min(1, u));
|
|
551
|
+
return u * u * u * (u * (u * 6 - 15) + 10);
|
|
552
|
+
};
|
|
553
|
+
async function evalBox(cdp, js) {
|
|
554
|
+
const r = await cdp.send("Runtime.evaluate", {
|
|
555
|
+
expression: js,
|
|
556
|
+
returnByValue: true,
|
|
557
|
+
awaitPromise: true
|
|
558
|
+
});
|
|
559
|
+
const v = r.result?.value;
|
|
560
|
+
if (v == null || v === "NOTFOUND") return null;
|
|
561
|
+
return findBox(evalValue(typeof v === "string" ? v : JSON.stringify(v)));
|
|
562
|
+
}
|
|
563
|
+
async function evalAny(cdp, js) {
|
|
564
|
+
const r = await cdp.send("Runtime.evaluate", {
|
|
565
|
+
expression: js,
|
|
566
|
+
returnByValue: true,
|
|
567
|
+
awaitPromise: true
|
|
568
|
+
});
|
|
569
|
+
const v = r.result?.value;
|
|
570
|
+
if (v == null || v === "NOTFOUND") return null;
|
|
571
|
+
return evalValue(typeof v === "string" ? v : JSON.stringify(v));
|
|
572
|
+
}
|
|
573
|
+
const center = (b) => ({
|
|
574
|
+
x: Math.round(b.x + b.w / 2),
|
|
575
|
+
y: Math.round(b.y + b.h / 2)
|
|
576
|
+
});
|
|
577
|
+
const mouse = (cdp, type, x, y, buttons = 0) => cdp.send("Input.dispatchMouseEvent", {
|
|
578
|
+
type,
|
|
579
|
+
x: Math.round(x),
|
|
580
|
+
y: Math.round(y),
|
|
581
|
+
button: type === "mouseMoved" ? "none" : "left",
|
|
582
|
+
buttons,
|
|
583
|
+
...type === "mouseMoved" ? {} : { clickCount: 1 }
|
|
584
|
+
});
|
|
585
|
+
const MOD = {
|
|
586
|
+
alt: 1,
|
|
587
|
+
option: 1,
|
|
588
|
+
ctrl: 2,
|
|
589
|
+
control: 2,
|
|
590
|
+
meta: 4,
|
|
591
|
+
cmd: 4,
|
|
592
|
+
command: 4,
|
|
593
|
+
super: 4,
|
|
594
|
+
win: 4,
|
|
595
|
+
shift: 8
|
|
596
|
+
};
|
|
597
|
+
const NAMED = {
|
|
598
|
+
enter: {
|
|
599
|
+
key: "Enter",
|
|
600
|
+
code: "Enter",
|
|
601
|
+
vk: 13,
|
|
602
|
+
text: "\r"
|
|
603
|
+
},
|
|
604
|
+
return: {
|
|
605
|
+
key: "Enter",
|
|
606
|
+
code: "Enter",
|
|
607
|
+
vk: 13,
|
|
608
|
+
text: "\r"
|
|
609
|
+
},
|
|
610
|
+
tab: {
|
|
611
|
+
key: "Tab",
|
|
612
|
+
code: "Tab",
|
|
613
|
+
vk: 9
|
|
614
|
+
},
|
|
615
|
+
escape: {
|
|
616
|
+
key: "Escape",
|
|
617
|
+
code: "Escape",
|
|
618
|
+
vk: 27
|
|
619
|
+
},
|
|
620
|
+
esc: {
|
|
621
|
+
key: "Escape",
|
|
622
|
+
code: "Escape",
|
|
623
|
+
vk: 27
|
|
624
|
+
},
|
|
625
|
+
backspace: {
|
|
626
|
+
key: "Backspace",
|
|
627
|
+
code: "Backspace",
|
|
628
|
+
vk: 8
|
|
629
|
+
},
|
|
630
|
+
delete: {
|
|
631
|
+
key: "Delete",
|
|
632
|
+
code: "Delete",
|
|
633
|
+
vk: 46
|
|
634
|
+
},
|
|
635
|
+
space: {
|
|
636
|
+
key: " ",
|
|
637
|
+
code: "Space",
|
|
638
|
+
vk: 32,
|
|
639
|
+
text: " "
|
|
640
|
+
},
|
|
641
|
+
arrowup: {
|
|
642
|
+
key: "ArrowUp",
|
|
643
|
+
code: "ArrowUp",
|
|
644
|
+
vk: 38
|
|
645
|
+
},
|
|
646
|
+
arrowdown: {
|
|
647
|
+
key: "ArrowDown",
|
|
648
|
+
code: "ArrowDown",
|
|
649
|
+
vk: 40
|
|
650
|
+
},
|
|
651
|
+
arrowleft: {
|
|
652
|
+
key: "ArrowLeft",
|
|
653
|
+
code: "ArrowLeft",
|
|
654
|
+
vk: 37
|
|
655
|
+
},
|
|
656
|
+
arrowright: {
|
|
657
|
+
key: "ArrowRight",
|
|
658
|
+
code: "ArrowRight",
|
|
659
|
+
vk: 39
|
|
660
|
+
},
|
|
661
|
+
up: {
|
|
662
|
+
key: "ArrowUp",
|
|
663
|
+
code: "ArrowUp",
|
|
664
|
+
vk: 38
|
|
665
|
+
},
|
|
666
|
+
down: {
|
|
667
|
+
key: "ArrowDown",
|
|
668
|
+
code: "ArrowDown",
|
|
669
|
+
vk: 40
|
|
670
|
+
},
|
|
671
|
+
left: {
|
|
672
|
+
key: "ArrowLeft",
|
|
673
|
+
code: "ArrowLeft",
|
|
674
|
+
vk: 37
|
|
675
|
+
},
|
|
676
|
+
right: {
|
|
677
|
+
key: "ArrowRight",
|
|
678
|
+
code: "ArrowRight",
|
|
679
|
+
vk: 39
|
|
680
|
+
},
|
|
681
|
+
home: {
|
|
682
|
+
key: "Home",
|
|
683
|
+
code: "Home",
|
|
684
|
+
vk: 36
|
|
685
|
+
},
|
|
686
|
+
end: {
|
|
687
|
+
key: "End",
|
|
688
|
+
code: "End",
|
|
689
|
+
vk: 35
|
|
690
|
+
},
|
|
691
|
+
pageup: {
|
|
692
|
+
key: "PageUp",
|
|
693
|
+
code: "PageUp",
|
|
694
|
+
vk: 33
|
|
695
|
+
},
|
|
696
|
+
pagedown: {
|
|
697
|
+
key: "PageDown",
|
|
698
|
+
code: "PageDown",
|
|
699
|
+
vk: 34
|
|
700
|
+
}
|
|
701
|
+
};
|
|
702
|
+
const MOD_KEY = {
|
|
703
|
+
1: {
|
|
704
|
+
key: "Alt",
|
|
705
|
+
code: "AltLeft",
|
|
706
|
+
vk: 18
|
|
707
|
+
},
|
|
708
|
+
2: {
|
|
709
|
+
key: "Control",
|
|
710
|
+
code: "ControlLeft",
|
|
711
|
+
vk: 17
|
|
712
|
+
},
|
|
713
|
+
4: {
|
|
714
|
+
key: "Meta",
|
|
715
|
+
code: "MetaLeft",
|
|
716
|
+
vk: 91
|
|
717
|
+
},
|
|
718
|
+
8: {
|
|
719
|
+
key: "Shift",
|
|
720
|
+
code: "ShiftLeft",
|
|
721
|
+
vk: 16
|
|
722
|
+
}
|
|
723
|
+
};
|
|
724
|
+
function parseChord(keys) {
|
|
725
|
+
const tokens = keys.split("+").map((t) => t.trim()).filter(Boolean);
|
|
726
|
+
const main = tokens.pop() ?? "";
|
|
727
|
+
let mods = 0;
|
|
728
|
+
for (const t of tokens) mods |= MOD[t.toLowerCase()] ?? 0;
|
|
729
|
+
const named = NAMED[main.toLowerCase()];
|
|
730
|
+
let info;
|
|
731
|
+
if (named) info = named;
|
|
732
|
+
else {
|
|
733
|
+
const ch = main;
|
|
734
|
+
const code = /^[a-z]$/i.test(ch) ? `Key${ch.toUpperCase()}` : /^[0-9]$/.test(ch) ? `Digit${ch}` : "";
|
|
735
|
+
info = {
|
|
736
|
+
key: ch,
|
|
737
|
+
code,
|
|
738
|
+
vk: ch.toUpperCase().charCodeAt(0) || 0
|
|
739
|
+
};
|
|
740
|
+
if (!(mods & 7)) info.text = ch;
|
|
741
|
+
}
|
|
742
|
+
return {
|
|
743
|
+
mods,
|
|
744
|
+
info
|
|
745
|
+
};
|
|
746
|
+
}
|
|
747
|
+
async function dispatchKey(cdp, type, info, mods) {
|
|
748
|
+
await cdp.send("Input.dispatchKeyEvent", {
|
|
749
|
+
type: info.text && type === "keyDown" ? "keyDown" : type,
|
|
750
|
+
modifiers: mods,
|
|
751
|
+
key: info.key,
|
|
752
|
+
code: info.code,
|
|
753
|
+
windowsVirtualKeyCode: info.vk,
|
|
754
|
+
nativeVirtualKeyCode: info.vk,
|
|
755
|
+
...info.text ? { text: info.text } : {}
|
|
756
|
+
});
|
|
757
|
+
}
|
|
758
|
+
async function pressChord(cdp, keys) {
|
|
759
|
+
const { mods, info } = parseChord(keys);
|
|
760
|
+
const active = [
|
|
761
|
+
1,
|
|
762
|
+
2,
|
|
763
|
+
4,
|
|
764
|
+
8
|
|
765
|
+
].filter((m) => mods & m);
|
|
766
|
+
for (const m of active) await dispatchKey(cdp, "keyDown", MOD_KEY[m], mods);
|
|
767
|
+
await dispatchKey(cdp, "keyDown", info, mods);
|
|
768
|
+
await sleep(40);
|
|
769
|
+
await dispatchKey(cdp, "keyUp", info, mods);
|
|
770
|
+
for (const m of active.reverse()) await dispatchKey(cdp, "keyUp", MOD_KEY[m], 0);
|
|
771
|
+
}
|
|
772
|
+
/** High-fps twin of captureTake. Drives + records via CDP. */
|
|
773
|
+
async function captureTakeCDP(plan, opts) {
|
|
774
|
+
const vw = plan.viewport?.width ?? 1920;
|
|
775
|
+
const vh = plan.viewport?.height ?? 1080;
|
|
776
|
+
const fps = Math.min(60, Math.max(24, Math.round(opts.fps ?? 60)));
|
|
777
|
+
const out = resolve(opts.videoPath);
|
|
778
|
+
let browser = null;
|
|
779
|
+
const frameDir = makeFrameDir();
|
|
780
|
+
try {
|
|
781
|
+
browser = await launchBrowser({
|
|
782
|
+
width: vw,
|
|
783
|
+
height: vh,
|
|
784
|
+
chromePath: opts.chromePath
|
|
785
|
+
});
|
|
786
|
+
const { cdp } = browser;
|
|
787
|
+
await cdp.send("Page.enable");
|
|
788
|
+
await cdp.send("Runtime.enable");
|
|
789
|
+
const inner = await fitViewport(cdp, browser.targetId, vw, vh);
|
|
790
|
+
await navigate(cdp, plan.url);
|
|
791
|
+
const screencast = new Screencast(cdp, frameDir);
|
|
792
|
+
const t0 = Date.now();
|
|
793
|
+
await screencast.start(t0, {
|
|
794
|
+
maxWidth: inner[0],
|
|
795
|
+
maxHeight: inner[1],
|
|
796
|
+
quality: 92
|
|
797
|
+
});
|
|
798
|
+
let pumping = true;
|
|
799
|
+
let pumpPaused = false;
|
|
800
|
+
const pump = (async () => {
|
|
801
|
+
while (pumping) {
|
|
802
|
+
if (!pumpPaused) await Promise.race([cdp.send("Page.captureScreenshot", {
|
|
803
|
+
format: "jpeg",
|
|
804
|
+
quality: 1
|
|
805
|
+
}).catch(() => {}), sleep(150)]);
|
|
806
|
+
await sleep(45);
|
|
807
|
+
}
|
|
808
|
+
})();
|
|
809
|
+
await sleep(opts.warmupMs ?? 900);
|
|
810
|
+
const resolvePoint = async (spec) => {
|
|
811
|
+
if (spec.point) return {
|
|
812
|
+
x: Math.round(spec.point.x),
|
|
813
|
+
y: Math.round(spec.point.y)
|
|
814
|
+
};
|
|
815
|
+
if (spec.selector) {
|
|
816
|
+
const b = await evalBox(cdp, boxSelectorJs(spec.selector));
|
|
817
|
+
return b ? center(b) : null;
|
|
818
|
+
}
|
|
819
|
+
if (spec.text) {
|
|
820
|
+
const b = await evalBox(cdp, boxByTextJs(spec.text));
|
|
821
|
+
return b ? center(b) : null;
|
|
822
|
+
}
|
|
823
|
+
return null;
|
|
824
|
+
};
|
|
825
|
+
const events = [];
|
|
826
|
+
for (const step of plan.steps) {
|
|
827
|
+
if (step.action === "wait") {
|
|
828
|
+
await sleep(step.ms);
|
|
829
|
+
continue;
|
|
830
|
+
}
|
|
831
|
+
if (step.action === "type") {
|
|
832
|
+
const label$1 = step.text ?? step.selector;
|
|
833
|
+
const tMs$1 = Date.now() - t0;
|
|
834
|
+
const box$1 = step.text ? await evalBox(cdp, focusFieldByTextJs(step.text)) : step.selector ? await evalBox(cdp, focusSelectorJs(step.selector)) : null;
|
|
835
|
+
if (!box$1) {
|
|
836
|
+
console.error(`captureTakeCDP: type target not found, skipped: ${JSON.stringify(label$1)}`);
|
|
837
|
+
await sleep(step.settleMs ?? 600);
|
|
838
|
+
continue;
|
|
839
|
+
}
|
|
840
|
+
const chars = [...step.value];
|
|
841
|
+
const perChar = Math.min(60, Math.max(28, Math.round(1100 / Math.max(1, chars.length))));
|
|
842
|
+
const tType = Date.now();
|
|
843
|
+
for (const ch of chars) {
|
|
844
|
+
await cdp.send("Input.insertText", { text: ch });
|
|
845
|
+
await sleep(perChar);
|
|
846
|
+
}
|
|
847
|
+
events.push({
|
|
848
|
+
kind: "type",
|
|
849
|
+
...center(box$1),
|
|
850
|
+
box: box$1,
|
|
851
|
+
tMs: tMs$1,
|
|
852
|
+
sel: label$1,
|
|
853
|
+
note: step.note,
|
|
854
|
+
text: step.value,
|
|
855
|
+
durationMs: Date.now() - tType,
|
|
856
|
+
...step.zoom ? { zoom: step.zoom } : {}
|
|
857
|
+
});
|
|
858
|
+
await sleep(step.settleMs ?? 900);
|
|
859
|
+
continue;
|
|
860
|
+
}
|
|
861
|
+
if (step.action === "drag") {
|
|
862
|
+
const pathPts = (step.path ?? []).map((p) => ({
|
|
863
|
+
x: Math.round(p.x),
|
|
864
|
+
y: Math.round(p.y)
|
|
865
|
+
}));
|
|
866
|
+
const from = await resolvePoint({
|
|
867
|
+
point: step.from,
|
|
868
|
+
selector: step.selector,
|
|
869
|
+
text: step.text
|
|
870
|
+
}) ?? pathPts[0] ?? null;
|
|
871
|
+
const to = await resolvePoint({
|
|
872
|
+
point: step.to,
|
|
873
|
+
selector: step.toSelector,
|
|
874
|
+
text: step.toText
|
|
875
|
+
}) ?? pathPts[pathPts.length - 1] ?? null;
|
|
876
|
+
const label$1 = step.note ?? step.text ?? step.selector;
|
|
877
|
+
if (!from || !to) {
|
|
878
|
+
console.error(`captureTakeCDP: drag endpoint not found, skipped: ${JSON.stringify(label$1)}`);
|
|
879
|
+
await sleep(step.settleMs ?? 600);
|
|
880
|
+
continue;
|
|
881
|
+
}
|
|
882
|
+
const path = pathPts.length ? pathPts : [from, to];
|
|
883
|
+
const target = step.durationMs ?? 1200;
|
|
884
|
+
const dragEase = opts.dragEasing ?? "smooth";
|
|
885
|
+
const easeParam = dragEase === "smooth" ? smoother : (u) => u;
|
|
886
|
+
const n = Math.max(12, Math.round(target / 16));
|
|
887
|
+
const tMs$1 = Date.now() - t0;
|
|
888
|
+
pumpPaused = true;
|
|
889
|
+
await sleep(160);
|
|
890
|
+
const tDrag = Date.now();
|
|
891
|
+
mouse(cdp, "mouseMoved", path[0].x, path[0].y, 0).catch(() => {});
|
|
892
|
+
mouse(cdp, "mousePressed", path[0].x, path[0].y, 1).catch(() => {});
|
|
893
|
+
for (let k = 1; k <= n; k++) {
|
|
894
|
+
const p = sampleAlong(path, easeParam(k / n));
|
|
895
|
+
mouse(cdp, "mouseMoved", p.x, p.y, 1).catch(() => {});
|
|
896
|
+
const due = tDrag + target * k / n;
|
|
897
|
+
const slack = due - Date.now();
|
|
898
|
+
if (slack > 0) await sleep(slack);
|
|
899
|
+
}
|
|
900
|
+
const last = path[path.length - 1];
|
|
901
|
+
mouse(cdp, "mouseReleased", last.x, last.y, 0).catch(() => {});
|
|
902
|
+
const drawnMs = Date.now() - tDrag;
|
|
903
|
+
await sleep(120);
|
|
904
|
+
pumpPaused = false;
|
|
905
|
+
events.push({
|
|
906
|
+
kind: "drag",
|
|
907
|
+
x: from.x,
|
|
908
|
+
y: from.y,
|
|
909
|
+
to,
|
|
910
|
+
path,
|
|
911
|
+
tMs: tMs$1,
|
|
912
|
+
sel: label$1,
|
|
913
|
+
note: step.note,
|
|
914
|
+
durationMs: drawnMs,
|
|
915
|
+
ease: dragEase,
|
|
916
|
+
...step.zoom ? { zoom: step.zoom } : {}
|
|
917
|
+
});
|
|
918
|
+
await sleep(step.settleMs ?? 1100);
|
|
919
|
+
continue;
|
|
920
|
+
}
|
|
921
|
+
if (step.action === "scroll") {
|
|
922
|
+
const tMs$1 = Date.now() - t0;
|
|
923
|
+
let dy;
|
|
924
|
+
if (step.toSelector || step.toText) {
|
|
925
|
+
const r = await evalAny(cdp, step.toSelector ? scrollDeltaSelectorJs(step.toSelector) : scrollDeltaByTextJs(step.toText));
|
|
926
|
+
if (r && typeof r.dy === "number") dy = r.dy;
|
|
927
|
+
else {
|
|
928
|
+
console.error(`captureTakeCDP: scroll target not found, skipped: ${JSON.stringify(step.toText ?? step.toSelector)}`);
|
|
929
|
+
await sleep(step.settleMs ?? 600);
|
|
930
|
+
continue;
|
|
931
|
+
}
|
|
932
|
+
} else dy = step.dy ?? Math.round(vh * .8);
|
|
933
|
+
const targetMs = step.durationMs ?? 1e3;
|
|
934
|
+
const cx = Math.round(inner[0] / 2), cy = Math.round(inner[1] / 2);
|
|
935
|
+
const start = Number(await evalAny(cdp, "window.scrollY")) || 0;
|
|
936
|
+
const n = Math.max(12, Math.round(targetMs / 16));
|
|
937
|
+
const tScroll = Date.now();
|
|
938
|
+
for (let k = 1; k <= n; k++) {
|
|
939
|
+
const u = k / n;
|
|
940
|
+
const want = Math.round(dy * (u * u * u * (u * (u * 6 - 15) + 10)));
|
|
941
|
+
await cdp.send("Runtime.evaluate", { expression: `window.scrollTo(0, ${start + want})` });
|
|
942
|
+
const due = tScroll + targetMs * k / n;
|
|
943
|
+
const slack = due - Date.now();
|
|
944
|
+
if (slack > 0) await sleep(slack);
|
|
945
|
+
}
|
|
946
|
+
events.push({
|
|
947
|
+
kind: "scroll",
|
|
948
|
+
x: cx,
|
|
949
|
+
y: cy,
|
|
950
|
+
tMs: tMs$1,
|
|
951
|
+
dy,
|
|
952
|
+
durationMs: Date.now() - tScroll,
|
|
953
|
+
note: step.note
|
|
954
|
+
});
|
|
955
|
+
await sleep(step.settleMs ?? 800);
|
|
956
|
+
continue;
|
|
957
|
+
}
|
|
958
|
+
if (step.action === "hover") {
|
|
959
|
+
const label$1 = step.text ?? step.selector;
|
|
960
|
+
const tMs$1 = Date.now() - t0;
|
|
961
|
+
const box$1 = step.text ? await evalBox(cdp, boxByTextJs(step.text)) : step.selector ? await evalBox(cdp, boxSelectorJs(step.selector)) : null;
|
|
962
|
+
if (!box$1) {
|
|
963
|
+
console.error(`captureTakeCDP: hover target not found, skipped: ${JSON.stringify(label$1)}`);
|
|
964
|
+
await sleep(step.settleMs ?? 600);
|
|
965
|
+
continue;
|
|
966
|
+
}
|
|
967
|
+
const c = center(box$1);
|
|
968
|
+
const dwell = step.durationMs ?? 1200;
|
|
969
|
+
await mouse(cdp, "mouseMoved", c.x, c.y, 0);
|
|
970
|
+
events.push({
|
|
971
|
+
kind: "hover",
|
|
972
|
+
...c,
|
|
973
|
+
box: box$1,
|
|
974
|
+
tMs: tMs$1,
|
|
975
|
+
sel: label$1,
|
|
976
|
+
note: step.note,
|
|
977
|
+
durationMs: dwell,
|
|
978
|
+
...step.zoom ? { zoom: step.zoom } : {}
|
|
979
|
+
});
|
|
980
|
+
await sleep(dwell);
|
|
981
|
+
await sleep(step.settleMs ?? 300);
|
|
982
|
+
continue;
|
|
983
|
+
}
|
|
984
|
+
if (step.action === "press") {
|
|
985
|
+
const tMs$1 = Date.now() - t0;
|
|
986
|
+
const tPress = Date.now();
|
|
987
|
+
try {
|
|
988
|
+
await pressChord(cdp, step.keys);
|
|
989
|
+
} catch (e) {
|
|
990
|
+
console.error(`captureTakeCDP: press failed for ${JSON.stringify(step.keys)}: ${e.message}`);
|
|
991
|
+
}
|
|
992
|
+
const dwell = step.durationMs ?? 1e3;
|
|
993
|
+
let box$1 = null;
|
|
994
|
+
if (step.selector || step.text) {
|
|
995
|
+
await sleep(250);
|
|
996
|
+
box$1 = step.text ? await evalBox(cdp, boxByTextJs(step.text)) : await evalBox(cdp, boxSelectorJs(step.selector));
|
|
997
|
+
}
|
|
998
|
+
const anchor = box$1 ? center(box$1) : {
|
|
999
|
+
x: Math.round(inner[0] / 2),
|
|
1000
|
+
y: Math.round(inner[1] / 2)
|
|
1001
|
+
};
|
|
1002
|
+
events.push({
|
|
1003
|
+
kind: "press",
|
|
1004
|
+
...anchor,
|
|
1005
|
+
...box$1 ? { box: box$1 } : {},
|
|
1006
|
+
tMs: tMs$1,
|
|
1007
|
+
keys: step.keys,
|
|
1008
|
+
sel: step.text ?? step.selector,
|
|
1009
|
+
note: step.note,
|
|
1010
|
+
durationMs: dwell,
|
|
1011
|
+
...step.zoom ? { zoom: step.zoom } : {}
|
|
1012
|
+
});
|
|
1013
|
+
await sleep(dwell);
|
|
1014
|
+
await sleep(step.settleMs ?? 400);
|
|
1015
|
+
continue;
|
|
1016
|
+
}
|
|
1017
|
+
const label = step.text ?? step.selector;
|
|
1018
|
+
const tMs = Date.now() - t0;
|
|
1019
|
+
const box = step.text ? await evalBox(cdp, clickByTextJs(step.text)) : step.selector ? await evalBox(cdp, clickBySelectorJs(step.selector)) : null;
|
|
1020
|
+
if (box) events.push({
|
|
1021
|
+
kind: "click",
|
|
1022
|
+
...center(box),
|
|
1023
|
+
box,
|
|
1024
|
+
tMs,
|
|
1025
|
+
sel: label,
|
|
1026
|
+
note: step.note,
|
|
1027
|
+
...step.zoom ? { zoom: step.zoom } : {}
|
|
1028
|
+
});
|
|
1029
|
+
else console.error(`captureTakeCDP: target not found, skipped: ${JSON.stringify(label)}`);
|
|
1030
|
+
await sleep(step.settleMs ?? 1300);
|
|
1031
|
+
}
|
|
1032
|
+
const tEndMs = Date.now() - t0;
|
|
1033
|
+
await sleep(400);
|
|
1034
|
+
pumping = false;
|
|
1035
|
+
await pump;
|
|
1036
|
+
await screencast.stop();
|
|
1037
|
+
await encodeFrames(screencast.frames, tEndMs + 400, out, fps);
|
|
1038
|
+
const probe = await ffprobe(out);
|
|
1039
|
+
return {
|
|
1040
|
+
video: {
|
|
1041
|
+
width: probe.width ?? inner[0],
|
|
1042
|
+
height: probe.height ?? inner[1],
|
|
1043
|
+
fps: probe.fps,
|
|
1044
|
+
durationS: probe.durationS
|
|
1045
|
+
},
|
|
1046
|
+
viewport: {
|
|
1047
|
+
w: inner[0],
|
|
1048
|
+
h: inner[1]
|
|
1049
|
+
},
|
|
1050
|
+
start: plan.startCursor ?? {
|
|
1051
|
+
x: Math.round(inner[0] * .25),
|
|
1052
|
+
y: Math.round(inner[1] * .9)
|
|
1053
|
+
},
|
|
1054
|
+
events,
|
|
1055
|
+
tEndMs
|
|
1056
|
+
};
|
|
1057
|
+
} finally {
|
|
1058
|
+
await browser?.close();
|
|
1059
|
+
rmSync(frameDir, {
|
|
1060
|
+
recursive: true,
|
|
1061
|
+
force: true,
|
|
1062
|
+
maxRetries: 5,
|
|
1063
|
+
retryDelay: 100
|
|
1064
|
+
});
|
|
1065
|
+
}
|
|
1066
|
+
}
|
|
1067
|
+
async function navigate(cdp, url) {
|
|
1068
|
+
const loaded = new Promise((res) => {
|
|
1069
|
+
cdp.on("Page.loadEventFired", () => res());
|
|
1070
|
+
setTimeout(res, 8e3);
|
|
1071
|
+
});
|
|
1072
|
+
await cdp.send("Page.navigate", { url });
|
|
1073
|
+
await loaded;
|
|
1074
|
+
}
|
|
1075
|
+
|
|
1076
|
+
//#endregion
|
|
1077
|
+
export { captureTake, captureTakeCDP, ensureChrome, inspectPage, resolveChrome };
|
|
1078
|
+
//# sourceMappingURL=cdp-capture-CWFbnK9C.js.map
|