@open-take/runtime 0.5.3 → 0.6.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/dist/cdp-capture-DfJeA-uY.js +4697 -0
- package/dist/cdp-capture-DfJeA-uY.js.map +1 -0
- package/dist/cdp-capture-ryEVA9lz.js +3 -0
- package/dist/index.d.ts +965 -84
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3503 -232
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
- package/dist/cdp-capture-MBg9nQy3.js +0 -2370
- package/dist/cdp-capture-MBg9nQy3.js.map +0 -1
- package/dist/cdp-capture-gux1GPRE.js +0 -3
|
@@ -1,2370 +0,0 @@
|
|
|
1
|
-
import { readFile } from "node:fs/promises";
|
|
2
|
-
import { homedir, tmpdir } from "node:os";
|
|
3
|
-
import { basename, dirname, join, resolve } from "node:path";
|
|
4
|
-
import { resolveFfmpeg, resolveFfprobe } from "@open-take/compositor";
|
|
5
|
-
import { spawn } from "node:child_process";
|
|
6
|
-
import { once } from "node:events";
|
|
7
|
-
import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, readlinkSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
8
|
-
import { createRequire } from "node:module";
|
|
9
|
-
|
|
10
|
-
//#region src/mjpeg-matroska.ts
|
|
11
|
-
const ID = {
|
|
12
|
-
EBML: 440786851,
|
|
13
|
-
EBMLVersion: 17030,
|
|
14
|
-
EBMLReadVersion: 17143,
|
|
15
|
-
EBMLMaxIDLength: 17138,
|
|
16
|
-
EBMLMaxSizeLength: 17139,
|
|
17
|
-
DocType: 17026,
|
|
18
|
-
DocTypeVersion: 17031,
|
|
19
|
-
DocTypeReadVersion: 17029,
|
|
20
|
-
Segment: 408125543,
|
|
21
|
-
Info: 357149030,
|
|
22
|
-
TimecodeScale: 2807729,
|
|
23
|
-
Duration: 17545,
|
|
24
|
-
MuxingApp: 19840,
|
|
25
|
-
WritingApp: 22337,
|
|
26
|
-
Tracks: 374648427,
|
|
27
|
-
TrackEntry: 174,
|
|
28
|
-
TrackNumber: 215,
|
|
29
|
-
TrackUID: 29637,
|
|
30
|
-
TrackType: 131,
|
|
31
|
-
FlagLacing: 156,
|
|
32
|
-
CodecID: 134,
|
|
33
|
-
Video: 224,
|
|
34
|
-
PixelWidth: 176,
|
|
35
|
-
PixelHeight: 186,
|
|
36
|
-
Cluster: 524531317,
|
|
37
|
-
Timecode: 231,
|
|
38
|
-
SimpleBlock: 163
|
|
39
|
-
};
|
|
40
|
-
/** Element IDs are written with their length marker bits included, so the
|
|
41
|
-
* constant's own big-endian bytes are the encoding. */
|
|
42
|
-
function idBytes(id) {
|
|
43
|
-
const bytes = [];
|
|
44
|
-
for (let v = id; v > 0; v = Math.floor(v / 256)) bytes.unshift(v % 256);
|
|
45
|
-
return Buffer.from(bytes);
|
|
46
|
-
}
|
|
47
|
-
/** EBML variable-size integer: a width-w encoding carries 7w bits and the
|
|
48
|
-
* all-ones pattern of each width is reserved for "size unknown". */
|
|
49
|
-
function sizeBytes(n) {
|
|
50
|
-
for (let width = 1; width <= 8; width++) {
|
|
51
|
-
if (n > 2 ** (7 * width) - 2) continue;
|
|
52
|
-
const out = Buffer.alloc(width);
|
|
53
|
-
let v = BigInt(n) | 1n << BigInt(7 * width);
|
|
54
|
-
for (let i = width - 1; i >= 0; i--) {
|
|
55
|
-
out[i] = Number(v & 0xffn);
|
|
56
|
-
v >>= 8n;
|
|
57
|
-
}
|
|
58
|
-
return out;
|
|
59
|
-
}
|
|
60
|
-
throw new Error(`matroska: element of ${n} bytes exceeds the EBML size range`);
|
|
61
|
-
}
|
|
62
|
-
const UNKNOWN_SIZE = Buffer.from([
|
|
63
|
-
1,
|
|
64
|
-
255,
|
|
65
|
-
255,
|
|
66
|
-
255,
|
|
67
|
-
255,
|
|
68
|
-
255,
|
|
69
|
-
255,
|
|
70
|
-
255
|
|
71
|
-
]);
|
|
72
|
-
const element = (id, payload) => Buffer.concat([
|
|
73
|
-
idBytes(id),
|
|
74
|
-
sizeBytes(payload.length),
|
|
75
|
-
payload
|
|
76
|
-
]);
|
|
77
|
-
function uint(id, n) {
|
|
78
|
-
if (!Number.isInteger(n) || n < 0) throw new Error(`matroska: ${n} is not an unsigned integer`);
|
|
79
|
-
const bytes = [];
|
|
80
|
-
let v = BigInt(n);
|
|
81
|
-
do {
|
|
82
|
-
bytes.unshift(Number(v & 0xffn));
|
|
83
|
-
v >>= 8n;
|
|
84
|
-
} while (v > 0n);
|
|
85
|
-
return element(id, Buffer.from(bytes));
|
|
86
|
-
}
|
|
87
|
-
const utf8 = (id, s) => element(id, Buffer.from(s, "utf8"));
|
|
88
|
-
function float64(id, x) {
|
|
89
|
-
const b = Buffer.alloc(8);
|
|
90
|
-
b.writeDoubleBE(x);
|
|
91
|
-
return element(id, b);
|
|
92
|
-
}
|
|
93
|
-
/** Pixel size from a JPEG's frame header (any SOF marker: baseline,
|
|
94
|
-
* progressive, lossless…), read past APPn/COM/DQT segments by their lengths. */
|
|
95
|
-
function jpegDimensions(jpeg) {
|
|
96
|
-
if (jpeg.length < 4 || jpeg[0] !== 255 || jpeg[1] !== 216) throw new Error("jpegDimensions: not a JPEG (no SOI marker)");
|
|
97
|
-
let i = 2;
|
|
98
|
-
while (i + 4 <= jpeg.length) {
|
|
99
|
-
if (jpeg[i] !== 255) {
|
|
100
|
-
i++;
|
|
101
|
-
continue;
|
|
102
|
-
}
|
|
103
|
-
const marker = jpeg[i + 1];
|
|
104
|
-
if (marker === 255) {
|
|
105
|
-
i++;
|
|
106
|
-
continue;
|
|
107
|
-
}
|
|
108
|
-
if (marker === 216 || marker === 1 || marker >= 208 && marker <= 215) {
|
|
109
|
-
i += 2;
|
|
110
|
-
continue;
|
|
111
|
-
}
|
|
112
|
-
const isSof = marker >= 192 && marker <= 207 && marker !== 196 && marker !== 200 && marker !== 204;
|
|
113
|
-
if (isSof) {
|
|
114
|
-
if (i + 9 > jpeg.length) break;
|
|
115
|
-
return {
|
|
116
|
-
height: jpeg.readUInt16BE(i + 5),
|
|
117
|
-
width: jpeg.readUInt16BE(i + 7)
|
|
118
|
-
};
|
|
119
|
-
}
|
|
120
|
-
if (marker === 218 || marker === 217) break;
|
|
121
|
-
i += 2 + jpeg.readUInt16BE(i + 2);
|
|
122
|
-
}
|
|
123
|
-
throw new Error("jpegDimensions: no SOF marker before scan data");
|
|
124
|
-
}
|
|
125
|
-
/** Everything before the first cluster. `durationMs` is advisory (players and
|
|
126
|
-
* ffprobe report it); the frames themselves carry the timing. */
|
|
127
|
-
function matroskaHead(width, height, durationMs) {
|
|
128
|
-
const header = element(ID.EBML, Buffer.concat([
|
|
129
|
-
uint(ID.EBMLVersion, 1),
|
|
130
|
-
uint(ID.EBMLReadVersion, 1),
|
|
131
|
-
uint(ID.EBMLMaxIDLength, 4),
|
|
132
|
-
uint(ID.EBMLMaxSizeLength, 8),
|
|
133
|
-
utf8(ID.DocType, "matroska"),
|
|
134
|
-
uint(ID.DocTypeVersion, 4),
|
|
135
|
-
uint(ID.DocTypeReadVersion, 2)
|
|
136
|
-
]));
|
|
137
|
-
const info = element(ID.Info, Buffer.concat([
|
|
138
|
-
uint(ID.TimecodeScale, 1e6),
|
|
139
|
-
float64(ID.Duration, durationMs),
|
|
140
|
-
utf8(ID.MuxingApp, "open-take"),
|
|
141
|
-
utf8(ID.WritingApp, "open-take")
|
|
142
|
-
]));
|
|
143
|
-
const tracks = element(ID.Tracks, element(ID.TrackEntry, Buffer.concat([
|
|
144
|
-
uint(ID.TrackNumber, 1),
|
|
145
|
-
uint(ID.TrackUID, 1),
|
|
146
|
-
uint(ID.TrackType, 1),
|
|
147
|
-
uint(ID.FlagLacing, 0),
|
|
148
|
-
utf8(ID.CodecID, "V_MJPEG"),
|
|
149
|
-
element(ID.Video, Buffer.concat([uint(ID.PixelWidth, width), uint(ID.PixelHeight, height)]))
|
|
150
|
-
])));
|
|
151
|
-
return Buffer.concat([
|
|
152
|
-
header,
|
|
153
|
-
idBytes(ID.Segment),
|
|
154
|
-
UNKNOWN_SIZE,
|
|
155
|
-
info,
|
|
156
|
-
tracks
|
|
157
|
-
]);
|
|
158
|
-
}
|
|
159
|
-
/** One frame: a cluster stamped with its absolute time holding a single
|
|
160
|
-
* keyframe SimpleBlock (track 1, relative timecode 0) around the raw JPEG. */
|
|
161
|
-
function matroskaCluster(tMs, jpeg) {
|
|
162
|
-
const block = element(ID.SimpleBlock, Buffer.concat([Buffer.from([
|
|
163
|
-
129,
|
|
164
|
-
0,
|
|
165
|
-
0,
|
|
166
|
-
128
|
|
167
|
-
]), jpeg]));
|
|
168
|
-
return element(ID.Cluster, Buffer.concat([uint(ID.Timecode, tMs), block]));
|
|
169
|
-
}
|
|
170
|
-
/** The whole stream, chunk by chunk, so a minute of Retina frames never sits
|
|
171
|
-
* in memory or on disk twice. Frames must be in non-decreasing tMs order;
|
|
172
|
-
* a file repeated back to back is read once.
|
|
173
|
-
*
|
|
174
|
-
* The track's pixel size comes from the first frame whose header parses.
|
|
175
|
-
* ffmpeg takes the size from each JPEG anyway, so one truncated frame (a
|
|
176
|
-
* write cut short) must not fail the whole encode here when the decoder
|
|
177
|
-
* would have skipped it; only a stream with no readable header at all is an
|
|
178
|
-
* error. */
|
|
179
|
-
async function* mjpegMatroska(frames) {
|
|
180
|
-
if (frames.length === 0) throw new Error("mjpegMatroska: no frames");
|
|
181
|
-
const jpegs = new Map();
|
|
182
|
-
let size;
|
|
183
|
-
for (const { file: file$1 } of frames) {
|
|
184
|
-
if (jpegs.has(file$1)) continue;
|
|
185
|
-
const jpeg$1 = await readFile(file$1);
|
|
186
|
-
jpegs.set(file$1, jpeg$1);
|
|
187
|
-
try {
|
|
188
|
-
size = jpegDimensions(jpeg$1);
|
|
189
|
-
break;
|
|
190
|
-
} catch {}
|
|
191
|
-
}
|
|
192
|
-
if (!size) throw new Error("mjpegMatroska: no frame has a readable JPEG header");
|
|
193
|
-
yield matroskaHead(size.width, size.height, frames[frames.length - 1].tMs);
|
|
194
|
-
let file = "";
|
|
195
|
-
let jpeg = Buffer.alloc(0);
|
|
196
|
-
for (const frame of frames) {
|
|
197
|
-
if (frame.file !== file) {
|
|
198
|
-
file = frame.file;
|
|
199
|
-
jpeg = jpegs.get(file) ?? await readFile(file);
|
|
200
|
-
jpegs.delete(file);
|
|
201
|
-
}
|
|
202
|
-
yield matroskaCluster(frame.tMs, jpeg);
|
|
203
|
-
}
|
|
204
|
-
}
|
|
205
|
-
|
|
206
|
-
//#endregion
|
|
207
|
-
//#region src/cdp.ts
|
|
208
|
-
const sleep$3 = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
209
|
-
const require = createRequire(import.meta.url);
|
|
210
|
-
const CHROME_CACHE = join(homedir(), ".open-take", "browsers");
|
|
211
|
-
const BUILDID_FILE = join(homedir(), ".open-take", "chrome-build.json");
|
|
212
|
-
function resolveChrome(explicit) {
|
|
213
|
-
const candidates = [];
|
|
214
|
-
if (explicit) candidates.push(explicit);
|
|
215
|
-
if (process.env.OPEN_TAKE_CHROME) candidates.push(process.env.OPEN_TAKE_CHROME);
|
|
216
|
-
if (existsSync(BUILDID_FILE)) try {
|
|
217
|
-
const exe = computeChromePathSync(JSON.parse(readFileSync(BUILDID_FILE, "utf8")).buildId);
|
|
218
|
-
if (exe) candidates.push(exe);
|
|
219
|
-
} catch {}
|
|
220
|
-
const abBrowsers = join(homedir(), ".agent-browser", "browsers");
|
|
221
|
-
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"));
|
|
222
|
-
return candidates.find((c) => c && existsSync(c)) ?? null;
|
|
223
|
-
}
|
|
224
|
-
function computeChromePathSync(buildId) {
|
|
225
|
-
try {
|
|
226
|
-
const { computeExecutablePath, Browser } = require("@puppeteer/browsers");
|
|
227
|
-
return computeExecutablePath({
|
|
228
|
-
browser: Browser.CHROME,
|
|
229
|
-
buildId,
|
|
230
|
-
cacheDir: CHROME_CACHE
|
|
231
|
-
});
|
|
232
|
-
} catch {
|
|
233
|
-
return null;
|
|
234
|
-
}
|
|
235
|
-
}
|
|
236
|
-
async function ensureChrome(explicit) {
|
|
237
|
-
const found = resolveChrome(explicit);
|
|
238
|
-
if (found) return found;
|
|
239
|
-
try {
|
|
240
|
-
const { install, resolveBuildId, detectBrowserPlatform, computeExecutablePath, Browser } = await import("@puppeteer/browsers");
|
|
241
|
-
const platform = detectBrowserPlatform();
|
|
242
|
-
if (!platform) throw new Error("unsupported platform");
|
|
243
|
-
const buildId = await resolveBuildId(Browser.CHROME, platform, "stable");
|
|
244
|
-
const exe = computeExecutablePath({
|
|
245
|
-
browser: Browser.CHROME,
|
|
246
|
-
buildId,
|
|
247
|
-
cacheDir: CHROME_CACHE
|
|
248
|
-
});
|
|
249
|
-
if (!existsSync(exe)) {
|
|
250
|
-
mkdirSync(CHROME_CACHE, { recursive: true });
|
|
251
|
-
process.stderr.write(`open-take: downloading Chrome for Testing (${buildId}, one-time) → ${CHROME_CACHE}\n`);
|
|
252
|
-
let lastPct = -1;
|
|
253
|
-
await install({
|
|
254
|
-
browser: Browser.CHROME,
|
|
255
|
-
buildId,
|
|
256
|
-
cacheDir: CHROME_CACHE,
|
|
257
|
-
downloadProgressCallback: (downloaded, total) => {
|
|
258
|
-
if (!total) return;
|
|
259
|
-
const pct = Math.floor(downloaded / total * 100);
|
|
260
|
-
if (pct >= lastPct + 10 || pct === 100) {
|
|
261
|
-
lastPct = pct;
|
|
262
|
-
process.stderr.write(`open-take: …Chrome download ${pct}%\n`);
|
|
263
|
-
}
|
|
264
|
-
}
|
|
265
|
-
});
|
|
266
|
-
process.stderr.write("open-take: Chrome ready.\n");
|
|
267
|
-
}
|
|
268
|
-
mkdirSync(dirname(BUILDID_FILE), { recursive: true });
|
|
269
|
-
writeFileSync(BUILDID_FILE, JSON.stringify({ buildId }));
|
|
270
|
-
return exe;
|
|
271
|
-
} catch (e) {
|
|
272
|
-
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.`);
|
|
273
|
-
}
|
|
274
|
-
}
|
|
275
|
-
var CDP = class CDP {
|
|
276
|
-
ws;
|
|
277
|
-
id = 0;
|
|
278
|
-
pending = new Map();
|
|
279
|
-
handlers = new Map();
|
|
280
|
-
constructor(ws) {
|
|
281
|
-
this.ws = ws;
|
|
282
|
-
ws.addEventListener("message", (ev) => {
|
|
283
|
-
const msg = JSON.parse(ev.data);
|
|
284
|
-
if (msg.id != null && this.pending.has(msg.id)) {
|
|
285
|
-
const { resolve: resolve$1, reject } = this.pending.get(msg.id);
|
|
286
|
-
this.pending.delete(msg.id);
|
|
287
|
-
msg.error ? reject(new Error(JSON.stringify(msg.error))) : resolve$1(msg.result);
|
|
288
|
-
} else if (msg.method) this.handlers.get(msg.method)?.(msg.params);
|
|
289
|
-
});
|
|
290
|
-
}
|
|
291
|
-
static connect(wsUrl) {
|
|
292
|
-
return new Promise((resolve$1, reject) => {
|
|
293
|
-
const ws = new WebSocket(wsUrl);
|
|
294
|
-
ws.addEventListener("open", () => resolve$1(new CDP(ws)));
|
|
295
|
-
ws.addEventListener("error", () => reject(new Error(`CDP connect failed: ${wsUrl}`)));
|
|
296
|
-
});
|
|
297
|
-
}
|
|
298
|
-
send(method, params = {}) {
|
|
299
|
-
const id = ++this.id;
|
|
300
|
-
return new Promise((resolve$1, reject) => {
|
|
301
|
-
this.pending.set(id, {
|
|
302
|
-
resolve: (value) => resolve$1(value),
|
|
303
|
-
reject
|
|
304
|
-
});
|
|
305
|
-
this.ws.send(JSON.stringify({
|
|
306
|
-
id,
|
|
307
|
-
method,
|
|
308
|
-
params
|
|
309
|
-
}));
|
|
310
|
-
});
|
|
311
|
-
}
|
|
312
|
-
on(method, fn) {
|
|
313
|
-
this.handlers.set(method, (params) => fn(params));
|
|
314
|
-
}
|
|
315
|
-
close() {
|
|
316
|
-
try {
|
|
317
|
-
this.ws.close();
|
|
318
|
-
} catch {}
|
|
319
|
-
}
|
|
320
|
-
};
|
|
321
|
-
/** Launch headless Chrome, return a CDP session bound to its page target. */
|
|
322
|
-
async function launchBrowser(opts) {
|
|
323
|
-
const chrome = await ensureChrome(opts.chromePath);
|
|
324
|
-
const ephemeral = !opts.userDataDir;
|
|
325
|
-
if (opts.userDataDir) mkdirSync(opts.userDataDir, { recursive: true });
|
|
326
|
-
const userDir = opts.userDataDir ?? mkdtempSync(join(tmpdir(), "open-take-cdp-"));
|
|
327
|
-
if (!ephemeral) rmSync(join(userDir, "DevToolsActivePort"), { force: true });
|
|
328
|
-
if (!ephemeral) {
|
|
329
|
-
const holder = singletonHolderPid(userDir);
|
|
330
|
-
if (holder != null && pidAlive(holder)) throw new Error(`profile in use: a Chrome (pid ${holder}) is already running on ${userDir} — quit it first (e.g. the \`open-take auth\` window)`);
|
|
331
|
-
for (const f of [
|
|
332
|
-
"SingletonLock",
|
|
333
|
-
"SingletonCookie",
|
|
334
|
-
"SingletonSocket"
|
|
335
|
-
]) rmSync(join(userDir, f), { force: true });
|
|
336
|
-
}
|
|
337
|
-
const dsf = opts.deviceScaleFactor ?? 1;
|
|
338
|
-
const proc = spawn(chrome, [
|
|
339
|
-
"--remote-debugging-port=0",
|
|
340
|
-
`--user-data-dir=${userDir}`,
|
|
341
|
-
`--window-size=${opts.width},${opts.height}`,
|
|
342
|
-
...dsf !== 1 ? [`--force-device-scale-factor=${dsf}`] : [],
|
|
343
|
-
...opts.headless === false ? [] : ["--headless=new"],
|
|
344
|
-
"--no-sandbox",
|
|
345
|
-
"--password-store=basic",
|
|
346
|
-
"--use-mock-keychain",
|
|
347
|
-
"--no-first-run",
|
|
348
|
-
"--no-default-browser-check",
|
|
349
|
-
"--hide-scrollbars",
|
|
350
|
-
"--disable-extensions",
|
|
351
|
-
"--disable-background-networking",
|
|
352
|
-
"--disable-features=Translate,AcceptCHFrame,MediaRouter,OptimizationHints",
|
|
353
|
-
"--mute-audio",
|
|
354
|
-
"about:blank"
|
|
355
|
-
], { stdio: [
|
|
356
|
-
"ignore",
|
|
357
|
-
"ignore",
|
|
358
|
-
"pipe"
|
|
359
|
-
] });
|
|
360
|
-
let stderr = "";
|
|
361
|
-
proc.stderr?.on("data", (d) => {
|
|
362
|
-
stderr += d;
|
|
363
|
-
});
|
|
364
|
-
const close = async () => {
|
|
365
|
-
const exitWithin = (ms) => new Promise((res) => {
|
|
366
|
-
if (proc.exitCode != null) return res(true);
|
|
367
|
-
const tm = setTimeout(() => res(false), ms);
|
|
368
|
-
proc.once("exit", () => {
|
|
369
|
-
clearTimeout(tm);
|
|
370
|
-
res(true);
|
|
371
|
-
});
|
|
372
|
-
});
|
|
373
|
-
try {
|
|
374
|
-
if (!ephemeral) {
|
|
375
|
-
proc.kill("SIGTERM");
|
|
376
|
-
if (!await exitWithin(4e3)) proc.kill("SIGKILL");
|
|
377
|
-
} else proc.kill("SIGKILL");
|
|
378
|
-
} catch {}
|
|
379
|
-
await exitWithin(2e3);
|
|
380
|
-
if (ephemeral) rmSync(userDir, {
|
|
381
|
-
recursive: true,
|
|
382
|
-
force: true,
|
|
383
|
-
maxRetries: 5,
|
|
384
|
-
retryDelay: 100
|
|
385
|
-
});
|
|
386
|
-
};
|
|
387
|
-
try {
|
|
388
|
-
const port = await readDevtoolsPort(userDir, proc);
|
|
389
|
-
const target = await pageTargetWs(port);
|
|
390
|
-
const cdp = await CDP.connect(target.wsUrl);
|
|
391
|
-
return {
|
|
392
|
-
cdp,
|
|
393
|
-
targetId: target.id,
|
|
394
|
-
close
|
|
395
|
-
};
|
|
396
|
-
} catch (e) {
|
|
397
|
-
await close();
|
|
398
|
-
throw new Error(`open-take(hi-fps): browser launch failed: ${e.message}\n${stderr.slice(-600)}`);
|
|
399
|
-
}
|
|
400
|
-
}
|
|
401
|
-
function singletonHolderPid(userDir) {
|
|
402
|
-
try {
|
|
403
|
-
const target = readlinkSync(join(userDir, "SingletonLock"));
|
|
404
|
-
const pid = Number(target.split("-").pop());
|
|
405
|
-
return Number.isFinite(pid) && pid > 0 ? pid : null;
|
|
406
|
-
} catch {
|
|
407
|
-
return null;
|
|
408
|
-
}
|
|
409
|
-
}
|
|
410
|
-
function pidAlive(pid) {
|
|
411
|
-
try {
|
|
412
|
-
process.kill(pid, 0);
|
|
413
|
-
return true;
|
|
414
|
-
} catch {
|
|
415
|
-
return false;
|
|
416
|
-
}
|
|
417
|
-
}
|
|
418
|
-
const DEVTOOLS_PORT_WAIT_MS = 3e4;
|
|
419
|
-
async function readDevtoolsPort(userDir, proc) {
|
|
420
|
-
const file = join(userDir, "DevToolsActivePort");
|
|
421
|
-
for (let i = 0; i < DEVTOOLS_PORT_WAIT_MS / 50; i++) {
|
|
422
|
-
if (proc.exitCode != null) throw new Error(`chrome exited early (${proc.exitCode})`);
|
|
423
|
-
if (existsSync(file)) {
|
|
424
|
-
const line = readFileSync(file, "utf8").split("\n")[0]?.trim();
|
|
425
|
-
const port = Number(line);
|
|
426
|
-
if (Number.isFinite(port) && port > 0) return port;
|
|
427
|
-
}
|
|
428
|
-
await sleep$3(50);
|
|
429
|
-
}
|
|
430
|
-
throw new Error(`timed out waiting for DevToolsActivePort (${DEVTOOLS_PORT_WAIT_MS / 1e3}s)`);
|
|
431
|
-
}
|
|
432
|
-
async function pageTargetWs(port) {
|
|
433
|
-
for (let i = 0; i < 60; i++) {
|
|
434
|
-
try {
|
|
435
|
-
const list = await (await fetch(`http://localhost:${port}/json`)).json();
|
|
436
|
-
const page = list.find((t) => t.type === "page");
|
|
437
|
-
if (page?.webSocketDebuggerUrl) return {
|
|
438
|
-
wsUrl: page.webSocketDebuggerUrl,
|
|
439
|
-
id: page.id
|
|
440
|
-
};
|
|
441
|
-
} catch {}
|
|
442
|
-
await sleep$3(100);
|
|
443
|
-
}
|
|
444
|
-
throw new Error("no page target appeared");
|
|
445
|
-
}
|
|
446
|
-
async function fitViewport(cdp, targetId, vw, vh) {
|
|
447
|
-
const readInner = async () => {
|
|
448
|
-
const r = await cdp.send("Runtime.evaluate", {
|
|
449
|
-
expression: "JSON.stringify([window.innerWidth, window.innerHeight])",
|
|
450
|
-
returnByValue: true
|
|
451
|
-
});
|
|
452
|
-
const v = JSON.parse(r.result?.value ?? "[0,0]");
|
|
453
|
-
return [Number(v[0]), Number(v[1])];
|
|
454
|
-
};
|
|
455
|
-
let win = null;
|
|
456
|
-
try {
|
|
457
|
-
win = await cdp.send("Browser.getWindowForTarget", { targetId });
|
|
458
|
-
} catch {
|
|
459
|
-
return readInner();
|
|
460
|
-
}
|
|
461
|
-
if (!win?.windowId) return readInner();
|
|
462
|
-
let { width, height } = win.bounds;
|
|
463
|
-
let inner = await readInner();
|
|
464
|
-
for (let i = 0; i < 4; i++) {
|
|
465
|
-
const dw = vw - inner[0];
|
|
466
|
-
const dh = vh - inner[1];
|
|
467
|
-
if (Math.abs(dw) <= 1 && Math.abs(dh) <= 1) break;
|
|
468
|
-
width += dw;
|
|
469
|
-
height += dh;
|
|
470
|
-
await cdp.send("Browser.setWindowBounds", {
|
|
471
|
-
windowId: win.windowId,
|
|
472
|
-
bounds: {
|
|
473
|
-
width,
|
|
474
|
-
height
|
|
475
|
-
}
|
|
476
|
-
});
|
|
477
|
-
await sleep$3(120);
|
|
478
|
-
inner = await readInner();
|
|
479
|
-
}
|
|
480
|
-
return inner;
|
|
481
|
-
}
|
|
482
|
-
function captureCadence(frames) {
|
|
483
|
-
const ordered = [...frames].sort((a, b) => a.offMs - b.offMs);
|
|
484
|
-
const intervals = ordered.slice(1).map((frame, i) => frame.offMs - ordered[i].offMs).sort((a, b) => a - b);
|
|
485
|
-
const rounded = (n) => Math.round(n * 1e3) / 1e3;
|
|
486
|
-
const sources = new Set(frames.map((frame) => frame.timestampSource ?? "arrival"));
|
|
487
|
-
return {
|
|
488
|
-
frameCount: frames.length,
|
|
489
|
-
timestampSource: sources.size > 1 ? "mixed" : sources.has("frame-swap") ? "frame-swap" : "arrival",
|
|
490
|
-
frameOffsetsMs: ordered.map((frame) => rounded(frame.offMs)),
|
|
491
|
-
arrivalOffsetsMs: ordered.map((frame) => rounded(frame.arrivalMs ?? frame.offMs)),
|
|
492
|
-
medianIntervalMs: rounded(intervals[Math.floor(intervals.length / 2)] ?? 0),
|
|
493
|
-
p95IntervalMs: rounded(intervals[Math.max(0, Math.ceil(intervals.length * .95) - 1)] ?? 0),
|
|
494
|
-
maxIntervalMs: rounded(intervals.at(-1) ?? 0),
|
|
495
|
-
maxArrivalDelayMs: rounded(frames.reduce((max, frame) => Math.max(max, (frame.arrivalMs ?? frame.offMs) - frame.offMs), 0)),
|
|
496
|
-
outOfOrderFrames: frames.filter((frame, i) => i > 0 && frame.offMs < frames[i - 1].offMs).length,
|
|
497
|
-
note: "Delivered-frame timing, not unique image content or a smoothness score. Static pages may send no frames; inspect image changes within active action windows. Encoded fps is separate."
|
|
498
|
-
};
|
|
499
|
-
}
|
|
500
|
-
var Screencast = class {
|
|
501
|
-
cdp;
|
|
502
|
-
dir;
|
|
503
|
-
t0 = 0;
|
|
504
|
-
n = 0;
|
|
505
|
-
lastArrivalAt = 0;
|
|
506
|
-
frames = [];
|
|
507
|
-
get idleForMs() {
|
|
508
|
-
return Date.now() - this.lastArrivalAt;
|
|
509
|
-
}
|
|
510
|
-
constructor(cdp, dir) {
|
|
511
|
-
this.cdp = cdp;
|
|
512
|
-
this.dir = dir;
|
|
513
|
-
}
|
|
514
|
-
/** Begin capture. `t0` (Date.now) anchors every frame + event onto one clock. */
|
|
515
|
-
async start(t0, opts) {
|
|
516
|
-
this.t0 = t0;
|
|
517
|
-
this.lastArrivalAt = t0;
|
|
518
|
-
this.cdp.on("Page.screencastFrame", (p) => {
|
|
519
|
-
const arrived = Date.now();
|
|
520
|
-
this.lastArrivalAt = arrived;
|
|
521
|
-
const swap = p.metadata?.timestamp;
|
|
522
|
-
const hasSwap = typeof swap === "number" && Number.isFinite(swap);
|
|
523
|
-
const off = Math.max(0, hasSwap ? swap * 1e3 - this.t0 : arrived - this.t0);
|
|
524
|
-
const file = join(this.dir, `f-${String(this.n++).padStart(5, "0")}.jpg`);
|
|
525
|
-
this.cdp.send("Page.screencastFrameAck", { sessionId: p.sessionId }).catch(() => {});
|
|
526
|
-
writeFileSync(file, Buffer.from(p.data, "base64"));
|
|
527
|
-
this.frames.push({
|
|
528
|
-
file,
|
|
529
|
-
offMs: off,
|
|
530
|
-
arrivalMs: arrived - this.t0,
|
|
531
|
-
timestampSource: hasSwap ? "frame-swap" : "arrival"
|
|
532
|
-
});
|
|
533
|
-
});
|
|
534
|
-
await this.cdp.send("Page.startScreencast", {
|
|
535
|
-
format: "jpeg",
|
|
536
|
-
quality: opts.quality ?? 90,
|
|
537
|
-
maxWidth: opts.maxWidth,
|
|
538
|
-
maxHeight: opts.maxHeight,
|
|
539
|
-
everyNthFrame: 1
|
|
540
|
-
});
|
|
541
|
-
}
|
|
542
|
-
async stop() {
|
|
543
|
-
await this.cdp.send("Page.stopScreencast").catch(() => {});
|
|
544
|
-
}
|
|
545
|
-
};
|
|
546
|
-
/** Refresh idle surfaces without interrupting pages already producing frames.
|
|
547
|
-
* Never queue another expensive screenshot behind a slow/in-flight request. */
|
|
548
|
-
async function pumpIdleRaster(cdp, screencast, active, paused) {
|
|
549
|
-
let pending = false;
|
|
550
|
-
while (active()) {
|
|
551
|
-
if (!paused() && !pending && screencast.idleForMs >= 200) {
|
|
552
|
-
pending = true;
|
|
553
|
-
cdp.send("Page.captureScreenshot", {
|
|
554
|
-
format: "jpeg",
|
|
555
|
-
quality: 1
|
|
556
|
-
}).catch(() => {}).finally(() => {
|
|
557
|
-
pending = false;
|
|
558
|
-
});
|
|
559
|
-
}
|
|
560
|
-
await sleep$3(45);
|
|
561
|
-
}
|
|
562
|
-
}
|
|
563
|
-
/** Where each frame sits on the video's clock, in whole milliseconds. The
|
|
564
|
-
* first frame is pulled back to 0 so the video timeline starts where event
|
|
565
|
-
* timestamps do; later frames keep their observed offset, nudged forward by
|
|
566
|
-
* 1 ms when two swaps round onto the same millisecond so no frame vanishes
|
|
567
|
-
* under its neighbour. The last frame is repeated at the end time (at least
|
|
568
|
-
* one frame period after it was shown) to give it a duration. */
|
|
569
|
-
function frameTimeline(frames, endMs, fps) {
|
|
570
|
-
const ordered = [...frames].sort((a, b) => a.offMs - b.offMs);
|
|
571
|
-
const timeline = [];
|
|
572
|
-
let tMs = 0;
|
|
573
|
-
for (let i = 0; i < ordered.length; i++) {
|
|
574
|
-
if (i > 0) tMs = Math.max(tMs + 1, Math.round(ordered[i].offMs));
|
|
575
|
-
timeline.push({
|
|
576
|
-
file: ordered[i].file,
|
|
577
|
-
tMs
|
|
578
|
-
});
|
|
579
|
-
}
|
|
580
|
-
const last = ordered[ordered.length - 1];
|
|
581
|
-
timeline.push({
|
|
582
|
-
file: last.file,
|
|
583
|
-
tMs: Math.max(tMs + 1, Math.round(endMs), Math.round(last.offMs + 1e3 / fps))
|
|
584
|
-
});
|
|
585
|
-
return timeline;
|
|
586
|
-
}
|
|
587
|
-
async function encodeFrames(frames, endMs, outPath, fps, ffmpegBin) {
|
|
588
|
-
if (frames.length === 0) throw new Error("open-take(hi-fps): no frames captured");
|
|
589
|
-
const timeline = frameTimeline(frames, endMs, fps);
|
|
590
|
-
const bin = ffmpegBin ?? await resolveFfmpeg();
|
|
591
|
-
const isWebm = /\.webm$/i.test(outPath);
|
|
592
|
-
const codec = isWebm ? [
|
|
593
|
-
"-c:v",
|
|
594
|
-
"libvpx-vp9",
|
|
595
|
-
"-b:v",
|
|
596
|
-
"0",
|
|
597
|
-
"-crf",
|
|
598
|
-
"28",
|
|
599
|
-
"-deadline",
|
|
600
|
-
"good",
|
|
601
|
-
"-cpu-used",
|
|
602
|
-
"4"
|
|
603
|
-
] : [
|
|
604
|
-
"-c:v",
|
|
605
|
-
"libx264",
|
|
606
|
-
"-preset",
|
|
607
|
-
"veryfast",
|
|
608
|
-
"-crf",
|
|
609
|
-
"18"
|
|
610
|
-
];
|
|
611
|
-
const colorConvert = isWebm ? "" : ":in_range=full:in_color_matrix=bt601:out_range=tv:out_color_matrix=bt709";
|
|
612
|
-
const colorLabel = isWebm ? "" : ",setparams=range=tv:colorspace=bt709:color_primaries=bt709:color_trc=bt709";
|
|
613
|
-
return new Promise((resolve$1, reject) => {
|
|
614
|
-
const args = [
|
|
615
|
-
"-y",
|
|
616
|
-
"-loglevel",
|
|
617
|
-
"error",
|
|
618
|
-
"-f",
|
|
619
|
-
"matroska",
|
|
620
|
-
"-i",
|
|
621
|
-
"pipe:0",
|
|
622
|
-
"-fps_mode",
|
|
623
|
-
"cfr",
|
|
624
|
-
"-r",
|
|
625
|
-
String(fps),
|
|
626
|
-
"-vf",
|
|
627
|
-
`scale=trunc(iw/2)*2:trunc(ih/2)*2${colorConvert},format=yuv420p${colorLabel}`,
|
|
628
|
-
...codec,
|
|
629
|
-
outPath
|
|
630
|
-
];
|
|
631
|
-
const c = spawn(bin, args, { stdio: [
|
|
632
|
-
"pipe",
|
|
633
|
-
"ignore",
|
|
634
|
-
"pipe"
|
|
635
|
-
] });
|
|
636
|
-
let err = "";
|
|
637
|
-
let feedErr;
|
|
638
|
-
c.stderr.on("data", (d) => {
|
|
639
|
-
err += d;
|
|
640
|
-
});
|
|
641
|
-
c.on("error", reject);
|
|
642
|
-
c.on("close", (code) => {
|
|
643
|
-
if (code !== 0 && code !== null) reject(new Error(`ffmpeg encode exited ${code}: ${err.slice(-800)}`));
|
|
644
|
-
else if (feedErr) reject(feedErr);
|
|
645
|
-
else if (code === 0) resolve$1();
|
|
646
|
-
else reject(new Error(`ffmpeg encode killed: ${err.slice(-800)}`));
|
|
647
|
-
});
|
|
648
|
-
c.stdin.on("error", () => {});
|
|
649
|
-
feedStdin(c.stdin, mjpegMatroska(timeline)).then(() => c.stdin.end(), (e) => {
|
|
650
|
-
feedErr = e;
|
|
651
|
-
c.kill("SIGKILL");
|
|
652
|
-
});
|
|
653
|
-
});
|
|
654
|
-
}
|
|
655
|
-
/** Write chunks respecting backpressure. The pipe dying underneath us (ffmpeg
|
|
656
|
-
* exited) simply ends the feed — the process exit explains itself; only the
|
|
657
|
-
* source throwing (a frame that cannot be read) rejects. */
|
|
658
|
-
async function feedStdin(stdin, chunks) {
|
|
659
|
-
for await (const chunk of chunks) {
|
|
660
|
-
if (stdin.destroyed || stdin.writableEnded) return;
|
|
661
|
-
try {
|
|
662
|
-
if (!stdin.write(chunk)) await once(stdin, "drain");
|
|
663
|
-
} catch {
|
|
664
|
-
return;
|
|
665
|
-
}
|
|
666
|
-
}
|
|
667
|
-
}
|
|
668
|
-
/** A throwaway temp dir for the screencast's per-frame JPEGs. */
|
|
669
|
-
const makeFrameDir = () => mkdtempSync(join(tmpdir(), "open-take-frames-"));
|
|
670
|
-
/** Poll `ready` every few milliseconds until it is true or `timeoutMs` has passed.
|
|
671
|
-
* Resolves true when the condition was met, false on timeout. Used to pace work
|
|
672
|
-
* by something the page did (a painted frame) instead of by a blind timer. */
|
|
673
|
-
async function waitUntil(ready, timeoutMs, stepMs = 4) {
|
|
674
|
-
const deadline = Date.now() + timeoutMs;
|
|
675
|
-
while (!ready()) {
|
|
676
|
-
if (Date.now() >= deadline) return false;
|
|
677
|
-
await new Promise((r) => setTimeout(r, stepMs));
|
|
678
|
-
}
|
|
679
|
-
return true;
|
|
680
|
-
}
|
|
681
|
-
|
|
682
|
-
//#endregion
|
|
683
|
-
//#region src/capture.ts
|
|
684
|
-
const sleep$2 = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
685
|
-
function findBox(o) {
|
|
686
|
-
if (!o || typeof o !== "object") return null;
|
|
687
|
-
const r = o;
|
|
688
|
-
if (typeof r.x === "number" && typeof r.y === "number" && (typeof r.width === "number" || typeof r.w === "number")) return {
|
|
689
|
-
x: r.x,
|
|
690
|
-
y: r.y,
|
|
691
|
-
w: r.width ?? r.w,
|
|
692
|
-
h: r.height ?? r.h
|
|
693
|
-
};
|
|
694
|
-
for (const k of Object.keys(r)) {
|
|
695
|
-
const hit = findBox(r[k]);
|
|
696
|
-
if (hit) return hit;
|
|
697
|
-
}
|
|
698
|
-
return null;
|
|
699
|
-
}
|
|
700
|
-
function deepParse(s) {
|
|
701
|
-
let cur = s;
|
|
702
|
-
for (let i = 0; i < 5 && typeof cur === "string"; i++) try {
|
|
703
|
-
cur = JSON.parse(cur);
|
|
704
|
-
} catch {
|
|
705
|
-
break;
|
|
706
|
-
}
|
|
707
|
-
return cur;
|
|
708
|
-
}
|
|
709
|
-
function evalValue(raw) {
|
|
710
|
-
let top;
|
|
711
|
-
try {
|
|
712
|
-
top = JSON.parse(raw);
|
|
713
|
-
} catch {
|
|
714
|
-
return deepParse(raw);
|
|
715
|
-
}
|
|
716
|
-
if (top && typeof top === "object") {
|
|
717
|
-
const o = top;
|
|
718
|
-
const data = o.data;
|
|
719
|
-
if (data && "result" in data) return deepParse(data.result);
|
|
720
|
-
for (const k of [
|
|
721
|
-
"result",
|
|
722
|
-
"output",
|
|
723
|
-
"stdout",
|
|
724
|
-
"value"
|
|
725
|
-
]) if (k in o) return deepParse(o[k]);
|
|
726
|
-
}
|
|
727
|
-
return deepParse(top);
|
|
728
|
-
}
|
|
729
|
-
const NAME_JS = "function names(e){var raw=[e.getAttribute('aria-label'),e.textContent,e.getAttribute('title'),e.getAttribute('alt'),e.getAttribute('placeholder')];var out=[];for(var i=0;i<raw.length;i++){var s=(raw[i]||'').replace(/\\s+/g,' ').trim();if(s&&out.indexOf(s)===-1)out.push(s);}return out;}function dispName(e){var a=[e.getAttribute('aria-label'),e.textContent,e.getAttribute('title'),e.getAttribute('alt')];for(var i=0;i<a.length;i++){var s=(a[i]||'').replace(/\\s+/g,' ').trim();if(s)return s;}return '';}function pick(els,t){var i,n,j;for(i=0;i<els.length;i++){if(names(els[i]).indexOf(t)!==-1)return els[i];}for(i=0;i<els.length;i++){n=names(els[i]);for(j=0;j<n.length;j++){if(n[j].indexOf(t)!==-1)return els[i];}}return null;}";
|
|
730
|
-
const HITTABLE_JS = "function hittable(m,r){var cx=Math.round(r.x+r.width/2),cy=Math.round(r.y+r.height/2);if(!(r.width>0&&r.height>0&&document.elementFromPoint))return null;var hit=document.elementFromPoint(cx,cy);var ok=!!hit&&(hit===m||(m.contains&&m.contains(hit)));if(!ok&&document.elementsFromPoint){var top=document.elementsFromPoint(cx,cy)[0];ok=!!top&&(top===m||(m.contains&&m.contains(top)));}return ok?{cx:cx,cy:cy}:null;}";
|
|
731
|
-
const CLICK_TAIL_JS = `if(m.tagName==='SELECT')return 'SELECTINERT';` + HITTABLE_JS + "var r=m.getBoundingClientRect();if(r.top<0||r.bottom>window.innerHeight){m.scrollIntoView({block:'center',behavior:'instant'});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)};var p=hittable(m,r);if(p){b.cx=p.cx;b.cy=p.cy;return JSON.stringify(b);}m.click();return JSON.stringify(b);";
|
|
732
|
-
const CLICK_CANDIDATES = "button,a,[role=button],[role=link],[role=menuitem],input[type=submit],input[type=button]";
|
|
733
|
-
const FIELD_CANDIDATES = "input,textarea,[contenteditable],[contenteditable=true],[role=textbox],[role=searchbox]";
|
|
734
|
-
const BOX_CANDIDATES = "button,a,[role=button],[role=link],[role=menuitem],[aria-label],[title],img[alt],li,[draggable=true]";
|
|
735
|
-
const SCROLL_CANDIDATES = "button,a,[role=button],[role=link],[role=heading],[aria-label],[title],h1,h2,h3,li,section,p";
|
|
736
|
-
function clickByTextJs(text) {
|
|
737
|
-
const t = JSON.stringify(text);
|
|
738
|
-
return `(function(){var t=${t};var els=Array.prototype.slice.call(document.querySelectorAll('${CLICK_CANDIDATES}'));` + NAME_JS + "var m=pick(els,t);if(!m)return 'NOTFOUND';" + CLICK_TAIL_JS + `})()`;
|
|
739
|
-
}
|
|
740
|
-
function clickBySelectorJs(selector) {
|
|
741
|
-
const s = JSON.stringify(selector);
|
|
742
|
-
return `(function(){var m=document.querySelector(${s});if(!m)return 'NOTFOUND';` + CLICK_TAIL_JS + `})()`;
|
|
743
|
-
}
|
|
744
|
-
const FOCUS_STATE_JS = "function deepActive(){var a=document.activeElement;while(a&&a.shadowRoot&&a.shadowRoot.activeElement){a=a.shadowRoot.activeElement;}return a;}function editable(a){if(!a)return false;if(a.isContentEditable)return true;return typeof a.value==='string'&&!a.readOnly&&!a.disabled;}function withinTarget(a){var n=a;while(n){if(n===m||(m.contains&&m.contains(n)))return true;var rn=n.getRootNode?n.getRootNode():null;n=n.parentElement||((rn&&rn.host)?rn.host:null);}return false;}var ae=deepActive();var ok=!!ae&&(ae!==document.body||m===document.body)&&editable(ae)&&(withinTarget(ae)||(ae.isContentEditable&&ae.contains&&ae.contains(m)));";
|
|
745
|
-
const FOCUS_TAIL_JS = HITTABLE_JS + "var r=m.getBoundingClientRect();if(r.top<0||r.bottom>window.innerHeight){m.scrollIntoView({block:'center',behavior:'instant'});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();" + FOCUS_STATE_JS + "b.f=ok?1:0;if(!ok){b.hit=hittable(m,m.getBoundingClientRect())?1:0;}return JSON.stringify(b);";
|
|
746
|
-
function focusFieldByTextJs(text) {
|
|
747
|
-
const t = JSON.stringify(text);
|
|
748
|
-
return `(function(){var t=${t};var els=Array.prototype.slice.call(document.querySelectorAll('${FIELD_CANDIDATES}'));` + NAME_JS + "var m=pick(els,t);if(!m)return 'NOTFOUND';" + FOCUS_TAIL_JS + `})()`;
|
|
749
|
-
}
|
|
750
|
-
function focusSelectorJs(selector) {
|
|
751
|
-
const s = JSON.stringify(selector);
|
|
752
|
-
return `(function(){var m=document.querySelector(${s});if(!m)return 'NOTFOUND';` + FOCUS_TAIL_JS + `})()`;
|
|
753
|
-
}
|
|
754
|
-
function verifyFocusJs(target) {
|
|
755
|
-
if (!target.text && !target.selector) return `'0'`;
|
|
756
|
-
const resolve$1 = target.text ? `var els=Array.prototype.slice.call(document.querySelectorAll('${FIELD_CANDIDATES}'));` + NAME_JS + `var m=pick(els,${JSON.stringify(target.text)});` : `var m=document.querySelector(${JSON.stringify(target.selector ?? "")});`;
|
|
757
|
-
return `(function(){${resolve$1}if(!m)return '0';` + FOCUS_STATE_JS + "if(ok)return '1';return (!!ae&&ae!==document.body&&editable(ae))?'1':'0';})()";
|
|
758
|
-
}
|
|
759
|
-
function selectAllInFocusedJs() {
|
|
760
|
-
return "(function(){var el=document.activeElement;if(!el)return 'NOFOCUS';if(typeof el.select==='function'&&typeof el.value==='string'){el.select();return 'SEL';}if(el.isContentEditable){var r=document.createRange();r.selectNodeContents(el);var s=window.getSelection();s.removeAllRanges();s.addRange(r);return 'SEL';}return 'NOSEL';})()";
|
|
761
|
-
}
|
|
762
|
-
function boxSelectorJs(selector) {
|
|
763
|
-
const s = JSON.stringify(selector);
|
|
764
|
-
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)});})()`;
|
|
765
|
-
}
|
|
766
|
-
function boxByTextJs(text) {
|
|
767
|
-
const t = JSON.stringify(text);
|
|
768
|
-
return `(function(){var t=${t};var els=Array.prototype.slice.call(document.querySelectorAll('${BOX_CANDIDATES}'));` + NAME_JS + "var m=pick(els,t);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)});})()";
|
|
769
|
-
}
|
|
770
|
-
const CLOSEST_ANCHOR_JS = "var a=m.closest('a[href]')||m.querySelector('a[href]');if(!a||!a.href)return 'NOTFOUND';return a.href;";
|
|
771
|
-
function hrefSelectorJs(selector) {
|
|
772
|
-
const s = JSON.stringify(selector);
|
|
773
|
-
return `(function(){var m=document.querySelector(${s});if(!m)return 'NOTFOUND';${CLOSEST_ANCHOR_JS}})()`;
|
|
774
|
-
}
|
|
775
|
-
function hrefByTextJs(text) {
|
|
776
|
-
const t = JSON.stringify(text);
|
|
777
|
-
return `(function(){var t=${t};var els=Array.prototype.slice.call(document.querySelectorAll('a,button,[role=link],[role=button],[aria-label],[title]'));` + NAME_JS + `var m=pick(els,t);if(!m)return 'NOTFOUND';${CLOSEST_ANCHOR_JS}})()`;
|
|
778
|
-
}
|
|
779
|
-
function scrollDeltaSelectorJs(selector) {
|
|
780
|
-
const s = JSON.stringify(selector);
|
|
781
|
-
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)});})()`;
|
|
782
|
-
}
|
|
783
|
-
function scrollDeltaByTextJs(text) {
|
|
784
|
-
const t = JSON.stringify(text);
|
|
785
|
-
return `(function(){var t=${t};var els=Array.prototype.slice.call(document.querySelectorAll('${SCROLL_CANDIDATES}'));` + NAME_JS + "var m=pick(els,t);if(!m)return 'NOTFOUND';var r=m.getBoundingClientRect();return JSON.stringify({dy:Math.round(r.top+r.height/2-window.innerHeight/2)});})()";
|
|
786
|
-
}
|
|
787
|
-
function sampleAlong(pts, u) {
|
|
788
|
-
if (pts.length === 1) return pts[0];
|
|
789
|
-
const seg = [];
|
|
790
|
-
let total = 0;
|
|
791
|
-
for (let i = 0; i < pts.length - 1; i++) {
|
|
792
|
-
const d = Math.hypot(pts[i + 1].x - pts[i].x, pts[i + 1].y - pts[i].y);
|
|
793
|
-
seg.push(d);
|
|
794
|
-
total += d;
|
|
795
|
-
}
|
|
796
|
-
if (total === 0) return pts[0];
|
|
797
|
-
let target = u * total;
|
|
798
|
-
for (let i = 0; i < seg.length; i++) {
|
|
799
|
-
if (target <= seg[i] || i === seg.length - 1) {
|
|
800
|
-
const f = seg[i] > 0 ? target / seg[i] : 0;
|
|
801
|
-
return {
|
|
802
|
-
x: pts[i].x + (pts[i + 1].x - pts[i].x) * f,
|
|
803
|
-
y: pts[i].y + (pts[i + 1].y - pts[i].y) * f
|
|
804
|
-
};
|
|
805
|
-
}
|
|
806
|
-
target -= seg[i];
|
|
807
|
-
}
|
|
808
|
-
return pts[pts.length - 1];
|
|
809
|
-
}
|
|
810
|
-
async function ffprobe(path) {
|
|
811
|
-
const bin = await resolveFfprobe().catch(() => null);
|
|
812
|
-
if (!bin) return {};
|
|
813
|
-
return new Promise((res) => {
|
|
814
|
-
const c = spawn(bin, [
|
|
815
|
-
"-v",
|
|
816
|
-
"error",
|
|
817
|
-
"-select_streams",
|
|
818
|
-
"v:0",
|
|
819
|
-
"-show_entries",
|
|
820
|
-
"stream=width,height,r_frame_rate,duration",
|
|
821
|
-
"-show_entries",
|
|
822
|
-
"format=duration",
|
|
823
|
-
"-of",
|
|
824
|
-
"json",
|
|
825
|
-
path
|
|
826
|
-
], { stdio: [
|
|
827
|
-
"ignore",
|
|
828
|
-
"pipe",
|
|
829
|
-
"ignore"
|
|
830
|
-
] });
|
|
831
|
-
let out = "";
|
|
832
|
-
c.stdout.on("data", (d) => {
|
|
833
|
-
out += d;
|
|
834
|
-
});
|
|
835
|
-
c.on("close", () => {
|
|
836
|
-
try {
|
|
837
|
-
const j = JSON.parse(out);
|
|
838
|
-
const s = j.streams?.[0] ?? {};
|
|
839
|
-
res({
|
|
840
|
-
width: s.width,
|
|
841
|
-
height: s.height,
|
|
842
|
-
fps: s.r_frame_rate,
|
|
843
|
-
durationS: Number(s.duration ?? j.format?.duration ?? 0)
|
|
844
|
-
});
|
|
845
|
-
} catch {
|
|
846
|
-
res({});
|
|
847
|
-
}
|
|
848
|
-
});
|
|
849
|
-
});
|
|
850
|
-
}
|
|
851
|
-
/** Drive `plan` against the live app over CDP, return the ground-truth log. */
|
|
852
|
-
async function captureTake(plan, opts) {
|
|
853
|
-
const { captureTakeCDP: captureTakeCDP$1 } = await import("./cdp-capture-gux1GPRE.js");
|
|
854
|
-
return captureTakeCDP$1(plan, {
|
|
855
|
-
...opts,
|
|
856
|
-
fps: opts.fps ?? 60
|
|
857
|
-
});
|
|
858
|
-
}
|
|
859
|
-
function listInteractiveJs() {
|
|
860
|
-
return `(function(){` + NAME_JS + "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=dispName(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));})()";
|
|
861
|
-
}
|
|
862
|
-
/** Open `url`, return its interactive elements (accessible name + bbox) —
|
|
863
|
-
* what an agent uses to choose a demo flow. Pure CDP, same as capture, so
|
|
864
|
-
* the reported coordinate space matches what capture will drive against. */
|
|
865
|
-
async function inspectPage(url, opts = {}) {
|
|
866
|
-
const vw = opts.viewport?.width ?? 1920;
|
|
867
|
-
const vh = opts.viewport?.height ?? 1080;
|
|
868
|
-
const browser = await launchBrowser({
|
|
869
|
-
width: vw,
|
|
870
|
-
height: vh,
|
|
871
|
-
chromePath: opts.chromePath,
|
|
872
|
-
...opts.userDataDir ? { userDataDir: opts.userDataDir } : {},
|
|
873
|
-
...opts.headless === false ? { headless: false } : {}
|
|
874
|
-
});
|
|
875
|
-
try {
|
|
876
|
-
const { cdp } = browser;
|
|
877
|
-
await cdp.send("Page.enable");
|
|
878
|
-
await cdp.send("Runtime.enable");
|
|
879
|
-
const inner = await fitViewport(cdp, browser.targetId, vw, vh);
|
|
880
|
-
const nav = await cdp.send("Page.navigate", { url });
|
|
881
|
-
if (nav.errorText) throw new Error(`inspectPage: ${url} did not answer (${nav.errorText}) — is the app running?`);
|
|
882
|
-
await sleep$2(opts.warmupMs ?? 1500);
|
|
883
|
-
const evalRaw = async (expr) => {
|
|
884
|
-
const r = await cdp.send("Runtime.evaluate", {
|
|
885
|
-
expression: expr,
|
|
886
|
-
returnByValue: true
|
|
887
|
-
});
|
|
888
|
-
return String(r.result?.value ?? "");
|
|
889
|
-
};
|
|
890
|
-
let elements = [];
|
|
891
|
-
try {
|
|
892
|
-
const v = evalValue(await evalRaw(listInteractiveJs()));
|
|
893
|
-
if (Array.isArray(v)) elements = v;
|
|
894
|
-
} catch {}
|
|
895
|
-
const title = await evalRaw("document.title").catch(() => "");
|
|
896
|
-
const finalUrl = await evalRaw("location.href").catch(() => "") || url;
|
|
897
|
-
return {
|
|
898
|
-
url,
|
|
899
|
-
finalUrl,
|
|
900
|
-
title,
|
|
901
|
-
viewport: {
|
|
902
|
-
w: inner[0],
|
|
903
|
-
h: inner[1]
|
|
904
|
-
},
|
|
905
|
-
elements
|
|
906
|
-
};
|
|
907
|
-
} finally {
|
|
908
|
-
await browser.close();
|
|
909
|
-
}
|
|
910
|
-
}
|
|
911
|
-
function selectOptionJs(target, value) {
|
|
912
|
-
const sel = JSON.stringify(target.selector ?? "");
|
|
913
|
-
const name = JSON.stringify(target.text ?? "");
|
|
914
|
-
const v = JSON.stringify(value);
|
|
915
|
-
return `(function(){var s=${sel},n=${name},want=${v};var m=null;if(s){m=document.querySelector(s);}else if(n){var els=Array.prototype.slice.call(document.querySelectorAll('select'));m=els.find(function(e){var a=(e.getAttribute('aria-label')||'').trim();if(a===n)return true;var id=e.id;if(id){var l=document.querySelector('label[for="'+id+'"]');if(l&&(l.textContent||'').trim().indexOf(n)>=0)return true;}var p=e.closest('label');if(p&&(p.textContent||'').trim().indexOf(n)>=0)return true;return false;})||null;}if(!m)return 'NOTFOUND';if(m.tagName!=='SELECT')return 'NOTASELECT';var opts=Array.prototype.slice.call(m.options);var norm=function(x){return (x||'').replace(/\\s+/g,'').trim();};var o=opts.find(function(x){return x.value===want;})||opts.find(function(x){return norm(x.textContent)===norm(want);})||opts.find(function(x){return norm(x.textContent).indexOf(norm(want))>=0;});if(!o)return 'NOOPTION';var r=m.getBoundingClientRect();if(r.top<0||r.bottom>window.innerHeight){m.scrollIntoView({block:'center'});r=m.getBoundingClientRect();}m.focus();m.value=o.value;m.dispatchEvent(new Event('input',{bubbles:true}));m.dispatchEvent(new Event('change',{bubbles:true}));var b={x:Math.round(r.x),y:Math.round(r.y),w:Math.round(r.width),h:Math.round(r.height)};return JSON.stringify(b);})()`;
|
|
916
|
-
}
|
|
917
|
-
|
|
918
|
-
//#endregion
|
|
919
|
-
//#region src/nav.ts
|
|
920
|
-
/**
|
|
921
|
-
* Resolve a navigate step to one absolute URL, or null when it cannot be.
|
|
922
|
-
*
|
|
923
|
-
* Precedence is `href` > `url` > `current`: a destination READ FROM THE PAGE
|
|
924
|
-
* beats one written in the plan, because it is the one that reflects what the
|
|
925
|
-
* app just did. `current` last means `{ query }` on its own is "reload this
|
|
926
|
-
* same page with these params" rather than an error.
|
|
927
|
-
*/
|
|
928
|
-
function resolveNavigateUrl(t) {
|
|
929
|
-
const base = safeUrl(t.current);
|
|
930
|
-
const raw = t.href || t.url || t.current;
|
|
931
|
-
if (!raw) return null;
|
|
932
|
-
const dest = safeUrl(raw, base);
|
|
933
|
-
if (!dest) return null;
|
|
934
|
-
for (const [k, v] of Object.entries(t.query ?? {})) dest.searchParams.set(k, v);
|
|
935
|
-
return dest.toString();
|
|
936
|
-
}
|
|
937
|
-
function safeUrl(raw, base) {
|
|
938
|
-
try {
|
|
939
|
-
return new URL(raw, base);
|
|
940
|
-
} catch {
|
|
941
|
-
return void 0;
|
|
942
|
-
}
|
|
943
|
-
}
|
|
944
|
-
|
|
945
|
-
//#endregion
|
|
946
|
-
//#region src/precheck.ts
|
|
947
|
-
/** Thrown by the capture when error-severity findings refuse the shoot.
|
|
948
|
-
* Carries the FULL structured findings (warns included) so the CLI can emit
|
|
949
|
-
* the machine-readable defects block and exit 2 like every other gate
|
|
950
|
-
* verdict — the message is only the human rendering of the same facts, and
|
|
951
|
-
* flattening the findings into it is how the measured values used to get
|
|
952
|
-
* lost on the way to the repair loop. */
|
|
953
|
-
var PrecheckRefusal = class extends Error {
|
|
954
|
-
issues;
|
|
955
|
-
constructor(message, issues) {
|
|
956
|
-
super(message);
|
|
957
|
-
this.name = "PrecheckRefusal";
|
|
958
|
-
this.issues = issues;
|
|
959
|
-
}
|
|
960
|
-
};
|
|
961
|
-
const FIELD_ORDER = {
|
|
962
|
-
click: ["text", "selector"],
|
|
963
|
-
type: ["text", "selector"],
|
|
964
|
-
look: ["text", "selector"],
|
|
965
|
-
hover: ["text", "selector"],
|
|
966
|
-
press: ["text", "selector"],
|
|
967
|
-
select: ["selector", "text"],
|
|
968
|
-
scroll: ["toSelector", "toText"],
|
|
969
|
-
drag: ["selector", "text"]
|
|
970
|
-
};
|
|
971
|
-
const DRAG_TO_ORDER = ["toSelector", "toText"];
|
|
972
|
-
const MUTATING = new Set([
|
|
973
|
-
"click",
|
|
974
|
-
"type",
|
|
975
|
-
"press",
|
|
976
|
-
"select",
|
|
977
|
-
"drag",
|
|
978
|
-
"dropFiles",
|
|
979
|
-
"navigate",
|
|
980
|
-
"hover",
|
|
981
|
-
"scroll"
|
|
982
|
-
]);
|
|
983
|
-
/** Every named target in the plan, in step order, tagged cold/late. */
|
|
984
|
-
function planTargets(steps) {
|
|
985
|
-
const out = [];
|
|
986
|
-
let cold = true;
|
|
987
|
-
for (let i = 0; i < steps.length; i++) {
|
|
988
|
-
const s = steps[i];
|
|
989
|
-
const action = String(s.action ?? "");
|
|
990
|
-
const has = (f) => typeof s[f] === "string" && s[f];
|
|
991
|
-
/** the first field of this group the step actually carries */
|
|
992
|
-
const winner = (order$1) => order$1.find(has);
|
|
993
|
-
const order = FIELD_ORDER[action];
|
|
994
|
-
const dragTo = action === "drag" && s.to ? null : winner(DRAG_TO_ORDER);
|
|
995
|
-
const primary = action === "drag" && s.from ? null : winner(order ?? []);
|
|
996
|
-
const isUsed = (field) => !order || field === primary || field === dragTo;
|
|
997
|
-
const add = (field, kind, revealOnly) => {
|
|
998
|
-
const v = s[field];
|
|
999
|
-
if (typeof v === "string" && v) out.push({
|
|
1000
|
-
step: i,
|
|
1001
|
-
action,
|
|
1002
|
-
field,
|
|
1003
|
-
kind,
|
|
1004
|
-
value: v,
|
|
1005
|
-
cold: cold && !revealOnly,
|
|
1006
|
-
used: isUsed(field),
|
|
1007
|
-
...revealOnly ? { revealOnly } : {}
|
|
1008
|
-
});
|
|
1009
|
-
};
|
|
1010
|
-
switch (action) {
|
|
1011
|
-
case "click":
|
|
1012
|
-
case "hover":
|
|
1013
|
-
case "look":
|
|
1014
|
-
case "type":
|
|
1015
|
-
case "select":
|
|
1016
|
-
add("selector", "selector");
|
|
1017
|
-
add("text", "text");
|
|
1018
|
-
break;
|
|
1019
|
-
case "press":
|
|
1020
|
-
add("selector", "selector", true);
|
|
1021
|
-
add("text", "text", true);
|
|
1022
|
-
break;
|
|
1023
|
-
case "scroll":
|
|
1024
|
-
add("toSelector", "selector");
|
|
1025
|
-
add("toText", "text");
|
|
1026
|
-
break;
|
|
1027
|
-
case "drag": {
|
|
1028
|
-
const hasPath = Array.isArray(s.path) && s.path.length > 0;
|
|
1029
|
-
if (!hasPath) {
|
|
1030
|
-
add("selector", "selector");
|
|
1031
|
-
add("text", "text");
|
|
1032
|
-
add("toSelector", "selector");
|
|
1033
|
-
add("toText", "text");
|
|
1034
|
-
}
|
|
1035
|
-
break;
|
|
1036
|
-
}
|
|
1037
|
-
case "navigate": {
|
|
1038
|
-
const hf = s.hrefFrom;
|
|
1039
|
-
const hfField = hf?.selector ? "selector" : hf?.text ? "text" : null;
|
|
1040
|
-
for (const [sub, kind] of [["selector", "selector"], ["text", "text"]]) {
|
|
1041
|
-
const v = hf?.[sub];
|
|
1042
|
-
if (typeof v === "string" && v) out.push({
|
|
1043
|
-
step: i,
|
|
1044
|
-
action,
|
|
1045
|
-
field: `hrefFrom.${sub}`,
|
|
1046
|
-
kind,
|
|
1047
|
-
value: v,
|
|
1048
|
-
cold,
|
|
1049
|
-
used: sub === hfField
|
|
1050
|
-
});
|
|
1051
|
-
}
|
|
1052
|
-
break;
|
|
1053
|
-
}
|
|
1054
|
-
default: break;
|
|
1055
|
-
}
|
|
1056
|
-
if (MUTATING.has(action)) cold = false;
|
|
1057
|
-
}
|
|
1058
|
-
return out;
|
|
1059
|
-
}
|
|
1060
|
-
/** The candidate set the ENGINE's by-text locator queries for this action —
|
|
1061
|
-
* imported from capture.ts so the probe and the real resolver cannot drift. */
|
|
1062
|
-
function textCandidates(action) {
|
|
1063
|
-
switch (action) {
|
|
1064
|
-
case "type": return FIELD_CANDIDATES;
|
|
1065
|
-
case "click": return CLICK_CANDIDATES;
|
|
1066
|
-
case "scroll": return SCROLL_CANDIDATES;
|
|
1067
|
-
case "navigate": return "a,button,[role=link],[role=button],[aria-label],[title]";
|
|
1068
|
-
default: return BOX_CANDIDATES;
|
|
1069
|
-
}
|
|
1070
|
-
}
|
|
1071
|
-
/** One page eval: resolve a target and DESCRIBE the outcome (no side effects). */
|
|
1072
|
-
function probeJs(kind, value, action) {
|
|
1073
|
-
const v = JSON.stringify(value);
|
|
1074
|
-
const desc = "function desc(m){if(!m)return null;var r=m.getBoundingClientRect();return {tag:m.tagName,w:Math.round(r.width),h:Math.round(r.height),x:Math.round(r.x),y:Math.round(r.y),inMain:!!m.closest('main')};}";
|
|
1075
|
-
if (kind === "selector") return `(function(){${desc}var all;try{all=Array.prototype.slice.call(document.querySelectorAll(${v}));}catch(e){return JSON.stringify({err:String(e.message||e)});}return JSON.stringify({count:all.length,first:desc(all[0]||null)});})()`;
|
|
1076
|
-
if (action === "select") return `(function(){${desc}var n=${v};var els=Array.prototype.slice.call(document.querySelectorAll('select'));var hits=els.filter(function(e){var a=(e.getAttribute('aria-label')||'').trim();if(a===n)return true;var id=e.id;if(id){var l=document.querySelector('label[for="'+id+'"]');if(l&&(l.textContent||'').trim().indexOf(n)>=0)return true;}var p=e.closest('label');if(p&&(p.textContent||'').trim().indexOf(n)>=0)return true;return false;});return JSON.stringify({count:hits.length?1:0,exact:hits.length,first:desc(hits[0]||null)});})()`;
|
|
1077
|
-
const set = textCandidates(action);
|
|
1078
|
-
return `(function(){${desc}${NAME_JS}var els=Array.prototype.slice.call(document.querySelectorAll('${set}'));var m=pick(els,${v});var exact=0;for(var i=0;i<els.length;i++){if(names(els[i]).indexOf(${v})!==-1)exact++;}var how=m?(names(m).indexOf(${v})!==-1?'exact':'substring'):'none';var share=how==='exact'?1:0,pn=null;if(m&&how==='substring'){var mn=names(m);for(var k=0;k<mn.length;k++){if(mn[k].indexOf(${v})!==-1&&(pn===null||mn[k].length<pn.length))pn=mn[k];}if(pn)share=${v}.length/pn.length;}function nm(e){var n=names(e),k;for(k=0;k<n.length;k++){if(n[k]===${v})return 'exact';}if(${v}.length>6){for(k=0;k<n.length;k++){if(n[k].length>6&&(n[k].indexOf(${v})!==-1||${v}.indexOf(n[k])!==-1))return 'contains';}}return null;}var inM=[],same=false,am=document.querySelectorAll('main *'),vwA=window.innerWidth*window.innerHeight;for(var i=0;i<am.length;i++){var e=am[i],mk=nm(e);if(!mk)continue;if(m&&e===m){if(mk==='exact')same=true;continue;}if(m&&(m.contains(e)||e.contains(m))){same=true;continue;}var d=desc(e);if(d.w<3||d.h<3)continue;if(mk==='contains'&&d.w*d.h>vwA*0.25)continue;d.match=mk;inM.push(d);}inM.sort(function(a,b){if(a.match!==b.match)return a.match==='exact'?-1:1;return a.w*a.h-b.w*b.h;});return JSON.stringify({count:m?1:0,exact:exact,first:desc(m),how:how,pickNameShare:Math.round(share*100)/100,pickName:pn?pn.slice(0,60):null,pickIsNamed:same,mainMatches:inM.slice(0,4)});})()`;
|
|
1079
|
-
}
|
|
1080
|
-
/** C3.5 parse-intent mismatch: the pick and the same-named in-main element
|
|
1081
|
-
* disagree by more than a step's worth of geometry. Validated against the 36
|
|
1082
|
-
* plans of the X5 corpus (23 poisoned targets). A pick that covers most of
|
|
1083
|
-
* its own label (share >= 0.5) is the named control, abbreviated — for that
|
|
1084
|
-
* shape only an EXACT in-main duplicate is evidence of anything; body copy
|
|
1085
|
-
* merely mentioning the phrase is how landing pages talk about their own
|
|
1086
|
-
* buttons. */
|
|
1087
|
-
const FAR_PX = 150;
|
|
1088
|
-
const ABBREVIATION_SHARE = .5;
|
|
1089
|
-
function parseIntentMismatch(p) {
|
|
1090
|
-
const pick = p.first;
|
|
1091
|
-
if (!pick || typeof pick.x !== "number" || typeof pick.y !== "number") return null;
|
|
1092
|
-
if (p.pickIsNamed) return null;
|
|
1093
|
-
let matches = (p.mainMatches ?? []).filter((m) => typeof m.x === "number" && typeof m.y === "number");
|
|
1094
|
-
if ((p.pickNameShare ?? 0) >= ABBREVIATION_SHARE) matches = matches.filter((m) => m.match === "exact");
|
|
1095
|
-
if (!matches.length) return null;
|
|
1096
|
-
const cx = pick.x + pick.w / 2;
|
|
1097
|
-
const cy = pick.y + pick.h / 2;
|
|
1098
|
-
for (const m of matches) if (Math.abs(m.x + m.w / 2 - cx) <= 5 && Math.abs(m.y + m.h / 2 - cy) <= 5) return null;
|
|
1099
|
-
const intended = matches[0];
|
|
1100
|
-
const far = Math.abs(intended.x + intended.w / 2 - cx) > FAR_PX || Math.abs(intended.y + intended.h / 2 - cy) > FAR_PX;
|
|
1101
|
-
return !pick.inMain || far ? {
|
|
1102
|
-
pick,
|
|
1103
|
-
intended
|
|
1104
|
-
} : null;
|
|
1105
|
-
}
|
|
1106
|
-
/** Resolve every plan target through `evalJson` (a Runtime.evaluate wrapper)
|
|
1107
|
-
* and grade the outcomes. Cold-prefix misses get ONE retry after `retryMs` —
|
|
1108
|
-
* a hydration-slow page may mount its controls a beat after load. */
|
|
1109
|
-
async function precheckPlan(steps, evalJson, opts) {
|
|
1110
|
-
const sleep$4 = opts?.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
|
|
1111
|
-
const targets = planTargets(steps).filter((t) => t.used);
|
|
1112
|
-
const probes = new Map();
|
|
1113
|
-
const probe = async (t) => await evalJson(probeJs(t.kind, t.value, t.action)) ?? {};
|
|
1114
|
-
for (const t of targets) probes.set(t, await probe(t));
|
|
1115
|
-
const misses = targets.filter((t) => !probes.get(t)?.err && !probes.get(t)?.count);
|
|
1116
|
-
if (misses.length) {
|
|
1117
|
-
await sleep$4(opts?.retryMs ?? 1500);
|
|
1118
|
-
for (const t of misses) probes.set(t, await probe(t));
|
|
1119
|
-
}
|
|
1120
|
-
const issues = [];
|
|
1121
|
-
const lateMisses = [];
|
|
1122
|
-
for (const t of targets) {
|
|
1123
|
-
const p = probes.get(t) ?? {};
|
|
1124
|
-
const path = `steps[${t.step}].${t.field}`;
|
|
1125
|
-
const name = `${t.action} ${JSON.stringify(t.value)}`;
|
|
1126
|
-
if (p.err) {
|
|
1127
|
-
issues.push({
|
|
1128
|
-
severity: "error",
|
|
1129
|
-
path,
|
|
1130
|
-
message: `${name}: invalid selector — the page rejected it (${p.err})`,
|
|
1131
|
-
fix: "fix the selector syntax; the capture would skip every use of it"
|
|
1132
|
-
});
|
|
1133
|
-
continue;
|
|
1134
|
-
}
|
|
1135
|
-
if (!p.count) {
|
|
1136
|
-
if (t.revealOnly) continue;
|
|
1137
|
-
if (t.cold) issues.push({
|
|
1138
|
-
severity: "error",
|
|
1139
|
-
path,
|
|
1140
|
-
message: `${name}: target not found in the page as loaded — this step runs before anything has changed the page, so it is CERTAIN to be skipped. Refusing in seconds what would fail after the full capture.`,
|
|
1141
|
-
fix: "point it at an element that exists at load (`open-take inspect <url>` lists them), or move it after the step that reveals it"
|
|
1142
|
-
});
|
|
1143
|
-
else lateMisses.push(t);
|
|
1144
|
-
continue;
|
|
1145
|
-
}
|
|
1146
|
-
if (t.kind === "text" && !t.revealOnly) {
|
|
1147
|
-
const mm = parseIntentMismatch(p);
|
|
1148
|
-
if (mm) {
|
|
1149
|
-
const certain = t.cold && p.how === "substring" && !mm.pick.inMain && (p.pickNameShare ?? 0) < ABBREVIATION_SHARE;
|
|
1150
|
-
issues.push({
|
|
1151
|
-
severity: certain ? "error" : "warn",
|
|
1152
|
-
path,
|
|
1153
|
-
message: `${name}: resolves to the WRONG element. The by-text lookup for ${t.action} searches only its candidate set and ${p.how === "substring" ? "substring-" : ""}matched a ${mm.pick.w}x${mm.pick.h} ${mm.pick.tag.toLowerCase()} at (${mm.pick.x},${mm.pick.y})${mm.pick.inMain ? "" : " OUTSIDE <main>"}${p.pickName ? ` (its actual name: ${JSON.stringify(p.pickName)})` : ""}, while the element named ${JSON.stringify(t.value.slice(0, 40))} is a ${mm.intended.tag.toLowerCase()} at (${mm.intended.x},${mm.intended.y}) inside <main>. The step would land on the impostor.`,
|
|
1154
|
-
fix: `target the in-main ${mm.intended.tag.toLowerCase()} with a CSS selector scoped to \`main\` (\`open-take inspect <url>\` lists one), or name a real control instead`
|
|
1155
|
-
});
|
|
1156
|
-
continue;
|
|
1157
|
-
}
|
|
1158
|
-
}
|
|
1159
|
-
if (t.kind === "selector" && (p.count ?? 0) > 1) {
|
|
1160
|
-
const z = p.first && (p.first.w === 0 || p.first.h === 0) ? " — and the first match is ZERO-SIZE" : "";
|
|
1161
|
-
issues.push({
|
|
1162
|
-
severity: "warn",
|
|
1163
|
-
path,
|
|
1164
|
-
message: `${name}: matches ${p.count} nodes; the engine takes the FIRST in document order${z}. A sidebar thumbnail or an off-screen clone outranking the real element is exactly how a whole take dies.`,
|
|
1165
|
-
fix: "qualify the selector until it matches once (e.g. scope it to `main`)"
|
|
1166
|
-
});
|
|
1167
|
-
continue;
|
|
1168
|
-
}
|
|
1169
|
-
if (t.kind === "text" && (p.exact ?? 0) > 1) {
|
|
1170
|
-
issues.push({
|
|
1171
|
-
severity: "warn",
|
|
1172
|
-
path,
|
|
1173
|
-
message: `${name}: ${p.exact} elements carry this exact accessible name; the engine takes the first in document order`,
|
|
1174
|
-
fix: "use a more specific name, or a CSS selector scoped to the intended region"
|
|
1175
|
-
});
|
|
1176
|
-
continue;
|
|
1177
|
-
}
|
|
1178
|
-
if (p.first && (p.first.w === 0 || p.first.h === 0)) issues.push({
|
|
1179
|
-
severity: "warn",
|
|
1180
|
-
path,
|
|
1181
|
-
message: `${name}: resolves to a zero-size element — the cursor has nowhere real to land`
|
|
1182
|
-
});
|
|
1183
|
-
}
|
|
1184
|
-
if (lateMisses.length) issues.push({
|
|
1185
|
-
severity: "warn",
|
|
1186
|
-
path: "steps",
|
|
1187
|
-
message: `${lateMisses.length} target${lateMisses.length === 1 ? " is" : "s are"} not in the initial DOM (${lateMisses.map((t) => `steps[${t.step}] ${JSON.stringify(t.value)}`).join(", ")}) — fine if earlier steps reveal them; any that never appears is SKIPPED at capture time (and the run exits non-zero)`
|
|
1188
|
-
});
|
|
1189
|
-
return issues;
|
|
1190
|
-
}
|
|
1191
|
-
|
|
1192
|
-
//#endregion
|
|
1193
|
-
//#region src/settle.ts
|
|
1194
|
-
const sleep$1 = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
1195
|
-
/** Extra time a hold may spend waiting for a busy page, per beat. Generous
|
|
1196
|
-
* enough for a slow round-trip, short enough that a page which NEVER goes
|
|
1197
|
-
* quiet (a live clock, a polling dashboard) costs a bounded, reported amount
|
|
1198
|
-
* rather than stretching the take without explanation. */
|
|
1199
|
-
const DEFAULT_SETTLE_BUDGET_MS = 1200;
|
|
1200
|
-
/** The page must have been still this long to count as settled — one paint
|
|
1201
|
-
* plus slack, so a mutation and the layout it triggers aren't read as two
|
|
1202
|
-
* separate quiet periods. */
|
|
1203
|
-
const QUIET_MS = 120;
|
|
1204
|
-
const POLL_MS = 60;
|
|
1205
|
-
/** A pending setTimeout longer than this is the page's own heartbeat (a poll
|
|
1206
|
-
* loop, a session timer), not this beat finishing. Counting it would make the
|
|
1207
|
-
* page look permanently busy. */
|
|
1208
|
-
const TIMER_MAX_MS = 2e3;
|
|
1209
|
-
/** Grace on a timer's own deadline before it stops counting as pending. Errs
|
|
1210
|
-
* SHORT on purpose: expiring early costs the old behaviour (a beat that may
|
|
1211
|
-
* be captured a touch soon), expiring late costs dead air in the cut on
|
|
1212
|
-
* every remaining beat — a much worse trade. */
|
|
1213
|
-
const TIMER_SLACK_MS = 250;
|
|
1214
|
-
/** A <canvas>/<video> covering this much of the frame makes the probe
|
|
1215
|
-
* effectively blind for that beat: the element never changes size, position
|
|
1216
|
-
* or attributes no matter what is painted inside it, so "the page is done"
|
|
1217
|
-
* is unanswerable. Set low on purpose — a needless note costs a line of
|
|
1218
|
-
* output, a missed one costs an author trusting a quiet run that proved
|
|
1219
|
-
* nothing. */
|
|
1220
|
-
const PAINT_BLIND_FRAC = .2;
|
|
1221
|
-
/** Installed once per document; keeps `t` at the last moment anything moved. */
|
|
1222
|
-
const PROBE_INSTALL_JS = `(() => {
|
|
1223
|
-
if (window.__openTakeActivity) return;
|
|
1224
|
-
const TIMER_MAX = ${TIMER_MAX_MS}, TIMER_SLACK = ${TIMER_SLACK_MS};
|
|
1225
|
-
const A = { t: 0, net: 0, timers: 0 };
|
|
1226
|
-
const touch = () => { A.t = performance.now(); };
|
|
1227
|
-
touch();
|
|
1228
|
-
try {
|
|
1229
|
-
new MutationObserver(touch).observe(document, {
|
|
1230
|
-
subtree: true, childList: true, attributes: true, characterData: true,
|
|
1231
|
-
});
|
|
1232
|
-
} catch (e) {}
|
|
1233
|
-
try {
|
|
1234
|
-
const of = window.fetch;
|
|
1235
|
-
if (typeof of === "function")
|
|
1236
|
-
window.fetch = function () {
|
|
1237
|
-
A.net++; touch();
|
|
1238
|
-
let p;
|
|
1239
|
-
try { p = of.apply(window, arguments); } catch (e) { A.net--; throw e; }
|
|
1240
|
-
return Promise.resolve(p).then(
|
|
1241
|
-
(r) => { A.net--; touch(); return r; },
|
|
1242
|
-
(e) => { A.net--; touch(); throw e; },
|
|
1243
|
-
);
|
|
1244
|
-
};
|
|
1245
|
-
} catch (e) {}
|
|
1246
|
-
try {
|
|
1247
|
-
const os = XMLHttpRequest.prototype.send;
|
|
1248
|
-
if (typeof os === "function")
|
|
1249
|
-
XMLHttpRequest.prototype.send = function () {
|
|
1250
|
-
A.net++; touch();
|
|
1251
|
-
// send() throws on API misuse (send before open, send after abort) and
|
|
1252
|
-
// then NO request exists, so loadend never fires — without this the
|
|
1253
|
-
// increment is permanent and the page reads busy for the rest of the
|
|
1254
|
-
// take. Same guard the fetch branch above already has.
|
|
1255
|
-
try { this.addEventListener("loadend", () => { A.net--; touch(); }); } catch (e) {}
|
|
1256
|
-
try { return os.apply(this, arguments); } catch (e) { A.net--; touch(); throw e; }
|
|
1257
|
-
};
|
|
1258
|
-
} catch (e) {}
|
|
1259
|
-
try {
|
|
1260
|
-
const st = window.setTimeout, ct = window.clearTimeout, ci = window.clearInterval;
|
|
1261
|
-
// id -> the moment it must have fired by. Counting by DEADLINE rather than
|
|
1262
|
-
// by cancellation bookkeeping is what makes this safe: a timer we never see
|
|
1263
|
-
// cancelled (clearInterval on a setTimeout id, an id coerced through a
|
|
1264
|
-
// dataset attribute, any API we did not wrap) simply expires and stops
|
|
1265
|
-
// counting. Chasing every cancellation path would leave one uncounted, and
|
|
1266
|
-
// ONE stuck entry means every remaining beat of the take waits the whole
|
|
1267
|
-
// budget for nothing.
|
|
1268
|
-
const live = new Map();
|
|
1269
|
-
const forget = function (id) { live.delete(Number(id)); };
|
|
1270
|
-
A.pending = function () {
|
|
1271
|
-
const now = performance.now();
|
|
1272
|
-
live.forEach(function (due, id) { if (due <= now) live.delete(id); });
|
|
1273
|
-
A.timers = live.size;
|
|
1274
|
-
return live.size;
|
|
1275
|
-
};
|
|
1276
|
-
window.setTimeout = function (fn, delay) {
|
|
1277
|
-
const d = Number(delay) || 0;
|
|
1278
|
-
// a string body keeps the original semantics (wrapping would stop the
|
|
1279
|
-
// code ever running), and a long delay is a heartbeat, not this beat
|
|
1280
|
-
if (typeof fn !== "function" || d > TIMER_MAX) return st.apply(window, arguments);
|
|
1281
|
-
const rest = Array.prototype.slice.call(arguments, 2);
|
|
1282
|
-
let id;
|
|
1283
|
-
const wrapped = function () {
|
|
1284
|
-
forget(id); touch();
|
|
1285
|
-
return fn.apply(this, arguments);
|
|
1286
|
-
};
|
|
1287
|
-
id = st.apply(window, [wrapped, d].concat(rest));
|
|
1288
|
-
live.set(Number(id), performance.now() + d + TIMER_SLACK);
|
|
1289
|
-
touch();
|
|
1290
|
-
return id;
|
|
1291
|
-
};
|
|
1292
|
-
// Both cancellers, and both coerce their argument the way the platform
|
|
1293
|
-
// does — clearInterval legally cancels a setTimeout (one timer map), and
|
|
1294
|
-
// clearTimeout(String(id)) is what you get back out of a dataset.
|
|
1295
|
-
window.clearTimeout = function (id) { forget(id); return ct.apply(window, arguments); };
|
|
1296
|
-
window.clearInterval = function (id) { forget(id); return ci.apply(window, arguments); };
|
|
1297
|
-
} catch (e) {}
|
|
1298
|
-
window.__openTakeActivity = A;
|
|
1299
|
-
})()`;
|
|
1300
|
-
/** Reads the probe. Returns a JSON string so one Runtime.evaluate round-trip
|
|
1301
|
-
* carries the whole answer (returnByValue on a plain object also works, but
|
|
1302
|
-
* the rest of this package already speaks the JSON-string convention). */
|
|
1303
|
-
const PROBE_READ_JS = `(() => {
|
|
1304
|
-
const A = window.__openTakeActivity;
|
|
1305
|
-
if (!A) return JSON.stringify({ ok: false });
|
|
1306
|
-
let anims = 0;
|
|
1307
|
-
try {
|
|
1308
|
-
for (const a of document.getAnimations()) {
|
|
1309
|
-
if (a.playState !== "running") continue;
|
|
1310
|
-
let it = 1;
|
|
1311
|
-
try { it = a.effect.getTiming().iterations; } catch (e) {}
|
|
1312
|
-
if (it === Infinity) continue; // ambient — never settles, never counted
|
|
1313
|
-
anims++;
|
|
1314
|
-
}
|
|
1315
|
-
} catch (e) {}
|
|
1316
|
-
// The largest <canvas>/<video> as a fraction of the viewport, clipped to it
|
|
1317
|
-
// (an offscreen or scrolled-away surface is not what the viewer is watching).
|
|
1318
|
-
let paint = 0;
|
|
1319
|
-
try {
|
|
1320
|
-
const area = innerWidth * innerHeight;
|
|
1321
|
-
if (area > 0)
|
|
1322
|
-
for (const el of document.querySelectorAll("canvas,video")) {
|
|
1323
|
-
const r = el.getBoundingClientRect();
|
|
1324
|
-
const w = Math.max(0, Math.min(r.right, innerWidth) - Math.max(r.left, 0));
|
|
1325
|
-
const h = Math.max(0, Math.min(r.bottom, innerHeight) - Math.max(r.top, 0));
|
|
1326
|
-
if (w * h > paint * area) paint = (w * h) / area;
|
|
1327
|
-
}
|
|
1328
|
-
} catch (e) {}
|
|
1329
|
-
const timers = typeof A.pending === "function" ? A.pending() : (A.timers | 0);
|
|
1330
|
-
const busy = A.net > 0 || timers > 0 || anims > 0 || document.readyState !== "complete";
|
|
1331
|
-
return JSON.stringify({
|
|
1332
|
-
ok: true,
|
|
1333
|
-
quietMs: busy ? 0 : Math.max(0, performance.now() - A.t),
|
|
1334
|
-
net: A.net,
|
|
1335
|
-
timers,
|
|
1336
|
-
anims,
|
|
1337
|
-
paint,
|
|
1338
|
-
});
|
|
1339
|
-
})()`;
|
|
1340
|
-
/** Install the activity probe for the current document AND every future one
|
|
1341
|
-
* (a plan may navigate mid-take). Never throws — a capture must not fail
|
|
1342
|
-
* because a diagnostic could not be attached. */
|
|
1343
|
-
async function installActivityProbe(cdp) {
|
|
1344
|
-
await cdp.send("Page.addScriptToEvaluateOnNewDocument", { source: PROBE_INSTALL_JS }).catch(() => {});
|
|
1345
|
-
await cdp.send("Runtime.evaluate", { expression: PROBE_INSTALL_JS }).catch(() => {});
|
|
1346
|
-
}
|
|
1347
|
-
async function readProbe(cdp) {
|
|
1348
|
-
try {
|
|
1349
|
-
const r = await cdp.send("Runtime.evaluate", {
|
|
1350
|
-
expression: PROBE_READ_JS,
|
|
1351
|
-
returnByValue: true
|
|
1352
|
-
});
|
|
1353
|
-
const v = r.result?.value;
|
|
1354
|
-
if (typeof v !== "string") return null;
|
|
1355
|
-
const p = JSON.parse(v);
|
|
1356
|
-
if (!p.ok) return null;
|
|
1357
|
-
return {
|
|
1358
|
-
quietMs: p.quietMs ?? 0,
|
|
1359
|
-
net: p.net ?? 0,
|
|
1360
|
-
timers: p.timers ?? 0,
|
|
1361
|
-
anims: p.anims ?? 0,
|
|
1362
|
-
paint: p.paint ?? 0
|
|
1363
|
-
};
|
|
1364
|
-
} catch {
|
|
1365
|
-
return null;
|
|
1366
|
-
}
|
|
1367
|
-
}
|
|
1368
|
-
/**
|
|
1369
|
-
* Hold for `heldMs` (the editorial beat — always run in full), then keep
|
|
1370
|
-
* waiting while the page is still working, up to `budgetMs`.
|
|
1371
|
-
*
|
|
1372
|
-
* `budgetMs <= 0` reduces this to the old fixed sleep exactly — the escape
|
|
1373
|
-
* hatch for a page that never goes quiet (`CaptureOpts.settleBudgetMs: 0`),
|
|
1374
|
-
* and what the unit tests use to pin the legacy timing.
|
|
1375
|
-
*/
|
|
1376
|
-
async function settle(cdp, heldMs, opts = {}) {
|
|
1377
|
-
const budget = opts.budgetMs ?? DEFAULT_SETTLE_BUDGET_MS;
|
|
1378
|
-
await sleep$1(Math.max(0, heldMs));
|
|
1379
|
-
if (!(budget > 0)) return {
|
|
1380
|
-
heldMs,
|
|
1381
|
-
waitedMs: 0,
|
|
1382
|
-
reason: "budget",
|
|
1383
|
-
paintFrac: 0
|
|
1384
|
-
};
|
|
1385
|
-
const t0 = Date.now();
|
|
1386
|
-
let paintFrac = 0;
|
|
1387
|
-
for (;;) {
|
|
1388
|
-
const p = await readProbe(cdp);
|
|
1389
|
-
const waitedMs = Date.now() - t0;
|
|
1390
|
-
if (!p) return {
|
|
1391
|
-
heldMs,
|
|
1392
|
-
waitedMs,
|
|
1393
|
-
reason: "unavailable",
|
|
1394
|
-
paintFrac
|
|
1395
|
-
};
|
|
1396
|
-
paintFrac = Math.max(paintFrac, p.paint);
|
|
1397
|
-
if (p.quietMs >= QUIET_MS) return {
|
|
1398
|
-
heldMs,
|
|
1399
|
-
waitedMs,
|
|
1400
|
-
reason: "idle",
|
|
1401
|
-
paintFrac
|
|
1402
|
-
};
|
|
1403
|
-
if (waitedMs >= budget) return {
|
|
1404
|
-
heldMs,
|
|
1405
|
-
waitedMs,
|
|
1406
|
-
reason: "budget",
|
|
1407
|
-
paintFrac
|
|
1408
|
-
};
|
|
1409
|
-
await sleep$1(POLL_MS);
|
|
1410
|
-
}
|
|
1411
|
-
}
|
|
1412
|
-
/** How many beats in a row may spend the WHOLE budget without the page ever
|
|
1413
|
-
* settling before the waiting is written off. */
|
|
1414
|
-
const SETTLE_GIVE_UP_STREAK = 2;
|
|
1415
|
-
/**
|
|
1416
|
-
* Budget policy across one take. Some pages never go quiet — a one-second
|
|
1417
|
-
* clock, a poll loop, a streaming widget — and no DOM signal can tell that
|
|
1418
|
-
* apart from real work. So do not try: once a run of beats has each spent the
|
|
1419
|
-
* entire budget with no result, the waiting is provably not helping, and
|
|
1420
|
-
* paying it on every remaining beat would add more dead air than the whole
|
|
1421
|
-
* demo is long. Give up once, loudly, and let the author set settleMs by eye.
|
|
1422
|
-
*/
|
|
1423
|
-
function makeBudgetGovernor(budgetMs, giveUpStreak = SETTLE_GIVE_UP_STREAK) {
|
|
1424
|
-
let budget = budgetMs;
|
|
1425
|
-
let streak = 0;
|
|
1426
|
-
return {
|
|
1427
|
-
get budgetMs() {
|
|
1428
|
-
return budget;
|
|
1429
|
-
},
|
|
1430
|
-
get gaveUp() {
|
|
1431
|
-
return budget <= 0 && budgetMs > 0;
|
|
1432
|
-
},
|
|
1433
|
-
record(reason) {
|
|
1434
|
-
if (reason === "idle") {
|
|
1435
|
-
streak = 0;
|
|
1436
|
-
return false;
|
|
1437
|
-
}
|
|
1438
|
-
if (reason !== "budget" || budget <= 0) return false;
|
|
1439
|
-
if (++streak < giveUpStreak) return false;
|
|
1440
|
-
budget = 0;
|
|
1441
|
-
return true;
|
|
1442
|
-
}
|
|
1443
|
-
};
|
|
1444
|
-
}
|
|
1445
|
-
|
|
1446
|
-
//#endregion
|
|
1447
|
-
//#region src/cdp-capture.ts
|
|
1448
|
-
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
1449
|
-
/** Report a settle wait only past this — a couple of polls is the probe
|
|
1450
|
-
* confirming quiet, not the page being slow, and a log full of 60ms notes
|
|
1451
|
-
* would bury the beat that actually needed a second. */
|
|
1452
|
-
const SETTLE_NOTE_MS = 150;
|
|
1453
|
-
const smoother = (u) => {
|
|
1454
|
-
const clamped = Math.max(0, Math.min(1, u));
|
|
1455
|
-
return clamped * clamped * clamped * (clamped * (clamped * 6 - 15) + 10);
|
|
1456
|
-
};
|
|
1457
|
-
async function evalBox(cdp, js) {
|
|
1458
|
-
const r = await cdp.send("Runtime.evaluate", {
|
|
1459
|
-
expression: js,
|
|
1460
|
-
returnByValue: true,
|
|
1461
|
-
awaitPromise: true
|
|
1462
|
-
});
|
|
1463
|
-
const v = r.result?.value;
|
|
1464
|
-
if (v == null || v === "NOTFOUND") return null;
|
|
1465
|
-
return findBox(evalValue(typeof v === "string" ? v : JSON.stringify(v)));
|
|
1466
|
-
}
|
|
1467
|
-
async function evalAny(cdp, js) {
|
|
1468
|
-
const r = await cdp.send("Runtime.evaluate", {
|
|
1469
|
-
expression: js,
|
|
1470
|
-
returnByValue: true,
|
|
1471
|
-
awaitPromise: true
|
|
1472
|
-
});
|
|
1473
|
-
const v = r.result?.value;
|
|
1474
|
-
if (v == null || v === "NOTFOUND") return null;
|
|
1475
|
-
return evalValue(typeof v === "string" ? v : JSON.stringify(v));
|
|
1476
|
-
}
|
|
1477
|
-
async function evalString(cdp, js) {
|
|
1478
|
-
const r = await cdp.send("Runtime.evaluate", {
|
|
1479
|
-
expression: js,
|
|
1480
|
-
returnByValue: true,
|
|
1481
|
-
awaitPromise: true
|
|
1482
|
-
});
|
|
1483
|
-
const v = r.result?.value;
|
|
1484
|
-
return typeof v === "string" && v !== "NOTFOUND" && v !== "" ? v : null;
|
|
1485
|
-
}
|
|
1486
|
-
async function awaitFonts(cdp) {
|
|
1487
|
-
await Promise.race([cdp.send("Runtime.evaluate", {
|
|
1488
|
-
expression: "document.fonts.ready.then(() => true)",
|
|
1489
|
-
awaitPromise: true,
|
|
1490
|
-
returnByValue: true
|
|
1491
|
-
}).catch(() => {}), sleep(3e3)]);
|
|
1492
|
-
}
|
|
1493
|
-
const center = (b) => ({
|
|
1494
|
-
x: Math.round(b.x + b.w / 2),
|
|
1495
|
-
y: Math.round(b.y + b.h / 2)
|
|
1496
|
-
});
|
|
1497
|
-
const mouse = (cdp, type, x, y, buttons = 0) => cdp.send("Input.dispatchMouseEvent", {
|
|
1498
|
-
type,
|
|
1499
|
-
x: Math.round(x),
|
|
1500
|
-
y: Math.round(y),
|
|
1501
|
-
button: type === "mouseMoved" ? "none" : "left",
|
|
1502
|
-
buttons,
|
|
1503
|
-
...type === "mouseMoved" ? {} : { clickCount: 1 }
|
|
1504
|
-
});
|
|
1505
|
-
const MOD = {
|
|
1506
|
-
alt: 1,
|
|
1507
|
-
option: 1,
|
|
1508
|
-
ctrl: 2,
|
|
1509
|
-
control: 2,
|
|
1510
|
-
meta: 4,
|
|
1511
|
-
cmd: 4,
|
|
1512
|
-
command: 4,
|
|
1513
|
-
super: 4,
|
|
1514
|
-
win: 4,
|
|
1515
|
-
shift: 8
|
|
1516
|
-
};
|
|
1517
|
-
const NAMED = {
|
|
1518
|
-
enter: {
|
|
1519
|
-
key: "Enter",
|
|
1520
|
-
code: "Enter",
|
|
1521
|
-
vk: 13,
|
|
1522
|
-
text: "\r"
|
|
1523
|
-
},
|
|
1524
|
-
return: {
|
|
1525
|
-
key: "Enter",
|
|
1526
|
-
code: "Enter",
|
|
1527
|
-
vk: 13,
|
|
1528
|
-
text: "\r"
|
|
1529
|
-
},
|
|
1530
|
-
tab: {
|
|
1531
|
-
key: "Tab",
|
|
1532
|
-
code: "Tab",
|
|
1533
|
-
vk: 9
|
|
1534
|
-
},
|
|
1535
|
-
escape: {
|
|
1536
|
-
key: "Escape",
|
|
1537
|
-
code: "Escape",
|
|
1538
|
-
vk: 27
|
|
1539
|
-
},
|
|
1540
|
-
esc: {
|
|
1541
|
-
key: "Escape",
|
|
1542
|
-
code: "Escape",
|
|
1543
|
-
vk: 27
|
|
1544
|
-
},
|
|
1545
|
-
backspace: {
|
|
1546
|
-
key: "Backspace",
|
|
1547
|
-
code: "Backspace",
|
|
1548
|
-
vk: 8
|
|
1549
|
-
},
|
|
1550
|
-
delete: {
|
|
1551
|
-
key: "Delete",
|
|
1552
|
-
code: "Delete",
|
|
1553
|
-
vk: 46
|
|
1554
|
-
},
|
|
1555
|
-
space: {
|
|
1556
|
-
key: " ",
|
|
1557
|
-
code: "Space",
|
|
1558
|
-
vk: 32,
|
|
1559
|
-
text: " "
|
|
1560
|
-
},
|
|
1561
|
-
arrowup: {
|
|
1562
|
-
key: "ArrowUp",
|
|
1563
|
-
code: "ArrowUp",
|
|
1564
|
-
vk: 38
|
|
1565
|
-
},
|
|
1566
|
-
arrowdown: {
|
|
1567
|
-
key: "ArrowDown",
|
|
1568
|
-
code: "ArrowDown",
|
|
1569
|
-
vk: 40
|
|
1570
|
-
},
|
|
1571
|
-
arrowleft: {
|
|
1572
|
-
key: "ArrowLeft",
|
|
1573
|
-
code: "ArrowLeft",
|
|
1574
|
-
vk: 37
|
|
1575
|
-
},
|
|
1576
|
-
arrowright: {
|
|
1577
|
-
key: "ArrowRight",
|
|
1578
|
-
code: "ArrowRight",
|
|
1579
|
-
vk: 39
|
|
1580
|
-
},
|
|
1581
|
-
up: {
|
|
1582
|
-
key: "ArrowUp",
|
|
1583
|
-
code: "ArrowUp",
|
|
1584
|
-
vk: 38
|
|
1585
|
-
},
|
|
1586
|
-
down: {
|
|
1587
|
-
key: "ArrowDown",
|
|
1588
|
-
code: "ArrowDown",
|
|
1589
|
-
vk: 40
|
|
1590
|
-
},
|
|
1591
|
-
left: {
|
|
1592
|
-
key: "ArrowLeft",
|
|
1593
|
-
code: "ArrowLeft",
|
|
1594
|
-
vk: 37
|
|
1595
|
-
},
|
|
1596
|
-
right: {
|
|
1597
|
-
key: "ArrowRight",
|
|
1598
|
-
code: "ArrowRight",
|
|
1599
|
-
vk: 39
|
|
1600
|
-
},
|
|
1601
|
-
home: {
|
|
1602
|
-
key: "Home",
|
|
1603
|
-
code: "Home",
|
|
1604
|
-
vk: 36
|
|
1605
|
-
},
|
|
1606
|
-
end: {
|
|
1607
|
-
key: "End",
|
|
1608
|
-
code: "End",
|
|
1609
|
-
vk: 35
|
|
1610
|
-
},
|
|
1611
|
-
pageup: {
|
|
1612
|
-
key: "PageUp",
|
|
1613
|
-
code: "PageUp",
|
|
1614
|
-
vk: 33
|
|
1615
|
-
},
|
|
1616
|
-
pagedown: {
|
|
1617
|
-
key: "PageDown",
|
|
1618
|
-
code: "PageDown",
|
|
1619
|
-
vk: 34
|
|
1620
|
-
}
|
|
1621
|
-
};
|
|
1622
|
-
const MOD_KEY = {
|
|
1623
|
-
1: {
|
|
1624
|
-
key: "Alt",
|
|
1625
|
-
code: "AltLeft",
|
|
1626
|
-
vk: 18
|
|
1627
|
-
},
|
|
1628
|
-
2: {
|
|
1629
|
-
key: "Control",
|
|
1630
|
-
code: "ControlLeft",
|
|
1631
|
-
vk: 17
|
|
1632
|
-
},
|
|
1633
|
-
4: {
|
|
1634
|
-
key: "Meta",
|
|
1635
|
-
code: "MetaLeft",
|
|
1636
|
-
vk: 91
|
|
1637
|
-
},
|
|
1638
|
-
8: {
|
|
1639
|
-
key: "Shift",
|
|
1640
|
-
code: "ShiftLeft",
|
|
1641
|
-
vk: 16
|
|
1642
|
-
}
|
|
1643
|
-
};
|
|
1644
|
-
function parseChord(keys) {
|
|
1645
|
-
const tokens = keys.split("+").map((t) => t.trim()).filter(Boolean);
|
|
1646
|
-
const main = tokens.pop() ?? "";
|
|
1647
|
-
let mods = 0;
|
|
1648
|
-
for (const t of tokens) mods |= MOD[t.toLowerCase()] ?? 0;
|
|
1649
|
-
const named = NAMED[main.toLowerCase()];
|
|
1650
|
-
let info;
|
|
1651
|
-
if (named) info = named;
|
|
1652
|
-
else {
|
|
1653
|
-
const ch = main;
|
|
1654
|
-
const code = /^[a-z]$/i.test(ch) ? `Key${ch.toUpperCase()}` : /^[0-9]$/.test(ch) ? `Digit${ch}` : "";
|
|
1655
|
-
info = {
|
|
1656
|
-
key: ch,
|
|
1657
|
-
code,
|
|
1658
|
-
vk: ch.toUpperCase().charCodeAt(0) || 0
|
|
1659
|
-
};
|
|
1660
|
-
if (!(mods & 7)) info.text = ch;
|
|
1661
|
-
}
|
|
1662
|
-
return {
|
|
1663
|
-
mods,
|
|
1664
|
-
info
|
|
1665
|
-
};
|
|
1666
|
-
}
|
|
1667
|
-
async function dispatchKey(cdp, type, info, mods) {
|
|
1668
|
-
await cdp.send("Input.dispatchKeyEvent", {
|
|
1669
|
-
type: info.text && type === "keyDown" ? "keyDown" : type,
|
|
1670
|
-
modifiers: mods,
|
|
1671
|
-
key: info.key,
|
|
1672
|
-
code: info.code,
|
|
1673
|
-
windowsVirtualKeyCode: info.vk,
|
|
1674
|
-
nativeVirtualKeyCode: info.vk,
|
|
1675
|
-
...info.text ? { text: info.text } : {}
|
|
1676
|
-
});
|
|
1677
|
-
}
|
|
1678
|
-
async function pressChord(cdp, keys) {
|
|
1679
|
-
const { mods, info } = parseChord(keys);
|
|
1680
|
-
const active = [
|
|
1681
|
-
1,
|
|
1682
|
-
2,
|
|
1683
|
-
4,
|
|
1684
|
-
8
|
|
1685
|
-
].filter((m) => mods & m);
|
|
1686
|
-
for (const m of active) await dispatchKey(cdp, "keyDown", MOD_KEY[m], mods);
|
|
1687
|
-
await dispatchKey(cdp, "keyDown", info, mods);
|
|
1688
|
-
await sleep(40);
|
|
1689
|
-
await dispatchKey(cdp, "keyUp", info, mods);
|
|
1690
|
-
for (const m of active.reverse()) await dispatchKey(cdp, "keyUp", MOD_KEY[m], 0);
|
|
1691
|
-
}
|
|
1692
|
-
/** High-fps twin of captureTake. Drives + records via CDP. */
|
|
1693
|
-
async function captureTakeCDP(plan, opts) {
|
|
1694
|
-
const vw = plan.viewport?.width ?? 1920;
|
|
1695
|
-
const vh = plan.viewport?.height ?? 1080;
|
|
1696
|
-
const fps = Math.min(60, Math.max(24, Math.round(opts.fps ?? 60)));
|
|
1697
|
-
const scale = Math.max(1, opts.captureScale ?? 2);
|
|
1698
|
-
const out = resolve(opts.videoPath);
|
|
1699
|
-
let browser = null;
|
|
1700
|
-
const frameDir = makeFrameDir();
|
|
1701
|
-
try {
|
|
1702
|
-
browser = await launchBrowser({
|
|
1703
|
-
width: vw,
|
|
1704
|
-
height: vh,
|
|
1705
|
-
chromePath: opts.chromePath,
|
|
1706
|
-
deviceScaleFactor: scale,
|
|
1707
|
-
...opts.userDataDir ? { userDataDir: opts.userDataDir } : {},
|
|
1708
|
-
...opts.headless === false ? { headless: false } : {}
|
|
1709
|
-
});
|
|
1710
|
-
const { cdp } = browser;
|
|
1711
|
-
await cdp.send("Page.enable");
|
|
1712
|
-
await cdp.send("Runtime.enable");
|
|
1713
|
-
let inner = await fitViewport(cdp, browser.targetId, vw, vh);
|
|
1714
|
-
await installActivityProbe(cdp);
|
|
1715
|
-
if (!originAllowed(plan.url)) throw new Error(`captureTakeCDP: plan.url ${plan.url} is outside OPEN_TAKE_ALLOWED_ORIGINS — an unattended run only films the app it was pointed at`);
|
|
1716
|
-
const navError = await navigate(cdp, plan.url);
|
|
1717
|
-
if (navError) throw new Error(`captureTakeCDP: ${plan.url} did not answer (${navError}) — is the app running? Start it (or fix the URL) and re-make; nothing was recorded.`);
|
|
1718
|
-
await installActivityProbe(cdp);
|
|
1719
|
-
await awaitFonts(cdp);
|
|
1720
|
-
inner = await fitViewport(cdp, browser.targetId, vw, vh);
|
|
1721
|
-
const precheck = await precheckPlan(plan.steps, (js) => evalAny(cdp, js));
|
|
1722
|
-
const precheckErrors = precheck.filter((p) => p.severity === "error");
|
|
1723
|
-
if (precheckErrors.length) throw new PrecheckRefusal(`captureTakeCDP: ${precheckErrors.length} plan target(s) failed the pre-capture check — nothing was recorded:\n` + precheckErrors.map((p) => ` ${p.path}: ${p.message}${p.fix ? `\n fix: ${p.fix}` : ""}`).join("\n"), precheck);
|
|
1724
|
-
for (const p of precheck) console.error(`captureTakeCDP precheck [${p.severity}] ${p.path}: ${p.message}`);
|
|
1725
|
-
const screencast = new Screencast(cdp, frameDir);
|
|
1726
|
-
const t0 = Date.now();
|
|
1727
|
-
await screencast.start(t0, {
|
|
1728
|
-
maxWidth: inner[0] * scale,
|
|
1729
|
-
maxHeight: inner[1] * scale,
|
|
1730
|
-
quality: 92
|
|
1731
|
-
});
|
|
1732
|
-
let pumping = true;
|
|
1733
|
-
let pumpPaused = false;
|
|
1734
|
-
const pump = opts.rasterRefresh === "off" ? Promise.resolve() : pumpIdleRaster(cdp, screencast, () => pumping, () => pumpPaused);
|
|
1735
|
-
await sleep(opts.warmupMs ?? 900);
|
|
1736
|
-
const resolvePoint = async (spec) => {
|
|
1737
|
-
if (spec.point) return {
|
|
1738
|
-
x: Math.round(spec.point.x),
|
|
1739
|
-
y: Math.round(spec.point.y)
|
|
1740
|
-
};
|
|
1741
|
-
if (spec.selector) {
|
|
1742
|
-
const b = await evalBox(cdp, boxSelectorJs(spec.selector));
|
|
1743
|
-
return b ? center(b) : null;
|
|
1744
|
-
}
|
|
1745
|
-
if (spec.text) {
|
|
1746
|
-
const b = await evalBox(cdp, boxByTextJs(spec.text));
|
|
1747
|
-
return b ? center(b) : null;
|
|
1748
|
-
}
|
|
1749
|
-
return null;
|
|
1750
|
-
};
|
|
1751
|
-
const events = [];
|
|
1752
|
-
const skipped = [];
|
|
1753
|
-
const settleWaits = [];
|
|
1754
|
-
const governor = makeBudgetGovernor(opts.settleBudgetMs ?? DEFAULT_SETTLE_BUDGET_MS);
|
|
1755
|
-
let paintedFrac = 0;
|
|
1756
|
-
let paintNoted = false;
|
|
1757
|
-
for (let stepIdx = 0; stepIdx < plan.steps.length; stepIdx++) {
|
|
1758
|
-
const step = plan.steps[stepIdx];
|
|
1759
|
-
const skip = (action, target, reason) => {
|
|
1760
|
-
skipped.push({
|
|
1761
|
-
step: stepIdx,
|
|
1762
|
-
action,
|
|
1763
|
-
...target ? { target } : {},
|
|
1764
|
-
reason
|
|
1765
|
-
});
|
|
1766
|
-
console.error(`captureTakeCDP: ${action} ${reason}, skipped: ${JSON.stringify(target)}`);
|
|
1767
|
-
};
|
|
1768
|
-
const hold = async (defaultMs) => {
|
|
1769
|
-
const heldMs = ("settleMs" in step ? step.settleMs : void 0) ?? defaultMs;
|
|
1770
|
-
const r = await settle(cdp, heldMs, { budgetMs: governor.budgetMs });
|
|
1771
|
-
paintedFrac = Math.max(paintedFrac, r.paintFrac);
|
|
1772
|
-
if (paintedFrac >= PAINT_BLIND_FRAC && !paintNoted) {
|
|
1773
|
-
paintNoted = true;
|
|
1774
|
-
console.error(`captureTakeCDP: a <canvas>/<video> covers ~${Math.round(paintedFrac * 100)}% of the frame — the settle probe reads page STRUCTURE and cannot see what is painted inside one, so on beats whose payoff is drawn there, settleMs is doing the whole job. Set those by eye and check \`frames\`.`);
|
|
1775
|
-
}
|
|
1776
|
-
if (governor.record(r.reason)) console.error("captureTakeCDP: this page never goes quiet (consecutive beats spent the whole settle budget) — settle waiting is OFF for the rest of the take; set each beat's settleMs explicitly instead");
|
|
1777
|
-
if (r.waitedMs < SETTLE_NOTE_MS) return;
|
|
1778
|
-
const waitedMs = Math.round(r.waitedMs);
|
|
1779
|
-
settleWaits.push({
|
|
1780
|
-
step: stepIdx,
|
|
1781
|
-
action: step.action,
|
|
1782
|
-
heldMs,
|
|
1783
|
-
waitedMs,
|
|
1784
|
-
reason: r.reason
|
|
1785
|
-
});
|
|
1786
|
-
console.error(`captureTakeCDP: step ${stepIdx} (${step.action}) held ${heldMs}ms, then waited ${waitedMs}ms more for the page to settle (${r.reason})`);
|
|
1787
|
-
};
|
|
1788
|
-
if (step.action === "wait") {
|
|
1789
|
-
await sleep(step.ms);
|
|
1790
|
-
continue;
|
|
1791
|
-
}
|
|
1792
|
-
if (step.action === "navigate") {
|
|
1793
|
-
const spec = step.hrefFrom;
|
|
1794
|
-
let href = null;
|
|
1795
|
-
if (spec) {
|
|
1796
|
-
const target = spec.text ?? spec.selector;
|
|
1797
|
-
if (!target) {
|
|
1798
|
-
skip("navigate", void 0, "hrefFrom has neither `selector` nor `text`");
|
|
1799
|
-
continue;
|
|
1800
|
-
}
|
|
1801
|
-
href = spec.selector ? await evalString(cdp, hrefSelectorJs(spec.selector)) : await evalString(cdp, hrefByTextJs(spec.text));
|
|
1802
|
-
if (!href) {
|
|
1803
|
-
skip("navigate", target, "no link with an href found");
|
|
1804
|
-
continue;
|
|
1805
|
-
}
|
|
1806
|
-
}
|
|
1807
|
-
const current = await evalString(cdp, "location.href") ?? plan.url;
|
|
1808
|
-
const dest = resolveNavigateUrl({
|
|
1809
|
-
current,
|
|
1810
|
-
url: step.url,
|
|
1811
|
-
href,
|
|
1812
|
-
query: step.query
|
|
1813
|
-
});
|
|
1814
|
-
if (!dest) {
|
|
1815
|
-
skip("navigate", step.url ?? href ?? current, "destination is not a resolvable URL");
|
|
1816
|
-
continue;
|
|
1817
|
-
}
|
|
1818
|
-
if (!originAllowed(dest)) {
|
|
1819
|
-
skip("navigate", dest, "destination is outside OPEN_TAKE_ALLOWED_ORIGINS");
|
|
1820
|
-
continue;
|
|
1821
|
-
}
|
|
1822
|
-
const midNavError = await navigate(cdp, dest);
|
|
1823
|
-
if (midNavError) {
|
|
1824
|
-
skip("navigate", dest, `destination did not answer (${midNavError})`);
|
|
1825
|
-
await navigate(cdp, current);
|
|
1826
|
-
await hold(1200);
|
|
1827
|
-
continue;
|
|
1828
|
-
}
|
|
1829
|
-
await awaitFonts(cdp);
|
|
1830
|
-
await hold(1200);
|
|
1831
|
-
continue;
|
|
1832
|
-
}
|
|
1833
|
-
if (step.action === "type") {
|
|
1834
|
-
const label$1 = step.text ?? step.selector;
|
|
1835
|
-
let tMs$1 = Date.now() - t0;
|
|
1836
|
-
const focusRaw = step.text ? await evalAny(cdp, focusFieldByTextJs(step.text)) : step.selector ? await evalAny(cdp, focusSelectorJs(step.selector)) : null;
|
|
1837
|
-
const box$1 = focusRaw ? findBox(focusRaw) : null;
|
|
1838
|
-
if (!box$1) {
|
|
1839
|
-
skip("type", label$1, "target not found");
|
|
1840
|
-
await hold(600);
|
|
1841
|
-
continue;
|
|
1842
|
-
}
|
|
1843
|
-
let focused = focusRaw.f === 1;
|
|
1844
|
-
if (!focused && focusRaw.hit !== 1) {
|
|
1845
|
-
skip("type", label$1, "focus never reached the target — its centre is covered, so no click could arm it");
|
|
1846
|
-
await hold(600);
|
|
1847
|
-
continue;
|
|
1848
|
-
}
|
|
1849
|
-
if (!focused) {
|
|
1850
|
-
const pt$1 = center(box$1);
|
|
1851
|
-
pumpPaused = true;
|
|
1852
|
-
await sleep(160);
|
|
1853
|
-
tMs$1 = Date.now() - t0;
|
|
1854
|
-
mouse(cdp, "mouseMoved", pt$1.x, pt$1.y, 0).catch(() => {});
|
|
1855
|
-
mouse(cdp, "mousePressed", pt$1.x, pt$1.y, 1).catch(() => {});
|
|
1856
|
-
await sleep(60);
|
|
1857
|
-
mouse(cdp, "mouseReleased", pt$1.x, pt$1.y, 0).catch(() => {});
|
|
1858
|
-
await sleep(120);
|
|
1859
|
-
pumpPaused = false;
|
|
1860
|
-
for (let poll = 0; poll < 3 && !focused; poll++) {
|
|
1861
|
-
await sleep(250);
|
|
1862
|
-
focused = await evalString(cdp, verifyFocusJs({
|
|
1863
|
-
text: step.text,
|
|
1864
|
-
selector: step.selector
|
|
1865
|
-
})) === "1";
|
|
1866
|
-
}
|
|
1867
|
-
}
|
|
1868
|
-
if (!focused) {
|
|
1869
|
-
skip("type", label$1, "focus never reached the target — typing would go nowhere");
|
|
1870
|
-
await hold(600);
|
|
1871
|
-
continue;
|
|
1872
|
-
}
|
|
1873
|
-
if (process.env.OPEN_TAKE_CI && await evalString(cdp, credentialFieldProbeJs()) === "secret") {
|
|
1874
|
-
skip("type", label$1, "refusing to type into a credential field (OPEN_TAKE_CI)");
|
|
1875
|
-
await hold(600);
|
|
1876
|
-
continue;
|
|
1877
|
-
}
|
|
1878
|
-
if (step.clear) await evalAny(cdp, selectAllInFocusedJs());
|
|
1879
|
-
const chars = [...step.value];
|
|
1880
|
-
const cjk = chars.filter((c) => /[\u2E80-\u9FFF\uAC00-\uD7AF\uF900-\uFAFF\uFF66-\uFF9F]/.test(c)).length;
|
|
1881
|
-
const auto = Math.min(90, Math.max(28, Math.round(1100 / Math.max(1, chars.length)))) * (cjk * 2 > chars.length ? 1.4 : 1);
|
|
1882
|
-
if (step.perCharMs === 0) await cdp.send("Input.insertText", { text: step.value });
|
|
1883
|
-
else {
|
|
1884
|
-
const perChar = Math.round(step.perCharMs ?? auto);
|
|
1885
|
-
for (const ch of chars) {
|
|
1886
|
-
const painted = screencast.frames.length, sentAt = Date.now();
|
|
1887
|
-
await cdp.send("Input.insertText", { text: ch });
|
|
1888
|
-
await waitUntil(() => screencast.frames.length > painted, Math.max(perChar, 250));
|
|
1889
|
-
const rest = perChar - (Date.now() - sentAt);
|
|
1890
|
-
if (rest > 0) await sleep(rest);
|
|
1891
|
-
}
|
|
1892
|
-
}
|
|
1893
|
-
events.push({
|
|
1894
|
-
kind: "type",
|
|
1895
|
-
...center(box$1),
|
|
1896
|
-
box: box$1,
|
|
1897
|
-
tMs: tMs$1,
|
|
1898
|
-
sel: label$1,
|
|
1899
|
-
note: step.note,
|
|
1900
|
-
...step.caption ? { caption: step.caption } : {},
|
|
1901
|
-
text: step.value,
|
|
1902
|
-
durationMs: Date.now() - t0 - tMs$1,
|
|
1903
|
-
...step.zoom ? { zoom: step.zoom } : {}
|
|
1904
|
-
});
|
|
1905
|
-
await hold(900);
|
|
1906
|
-
continue;
|
|
1907
|
-
}
|
|
1908
|
-
if (step.action === "drag") {
|
|
1909
|
-
const pathPts = (step.path ?? []).map((p) => ({
|
|
1910
|
-
x: Math.round(p.x),
|
|
1911
|
-
y: Math.round(p.y)
|
|
1912
|
-
}));
|
|
1913
|
-
const from = await resolvePoint({
|
|
1914
|
-
point: step.from,
|
|
1915
|
-
selector: step.selector,
|
|
1916
|
-
text: step.text
|
|
1917
|
-
}) ?? pathPts[0] ?? null;
|
|
1918
|
-
const to = await resolvePoint({
|
|
1919
|
-
point: step.to,
|
|
1920
|
-
selector: step.toSelector,
|
|
1921
|
-
text: step.toText
|
|
1922
|
-
}) ?? pathPts[pathPts.length - 1] ?? null;
|
|
1923
|
-
const label$1 = step.note ?? step.text ?? step.selector;
|
|
1924
|
-
if (!from || !to) {
|
|
1925
|
-
skip("drag", label$1, "endpoint not found");
|
|
1926
|
-
await hold(600);
|
|
1927
|
-
continue;
|
|
1928
|
-
}
|
|
1929
|
-
const path = pathPts.length ? pathPts : [from, to];
|
|
1930
|
-
const target = step.durationMs ?? 1200;
|
|
1931
|
-
const dragEase = opts.dragEasing ?? "smooth";
|
|
1932
|
-
const easeParam = dragEase === "smooth" ? smoother : (u) => u;
|
|
1933
|
-
const n = Math.max(12, Math.round(target / 16));
|
|
1934
|
-
const tMs$1 = Date.now() - t0;
|
|
1935
|
-
pumpPaused = true;
|
|
1936
|
-
await sleep(160);
|
|
1937
|
-
const tDrag = Date.now();
|
|
1938
|
-
mouse(cdp, "mouseMoved", path[0].x, path[0].y, 0).catch(() => {});
|
|
1939
|
-
mouse(cdp, "mousePressed", path[0].x, path[0].y, 1).catch(() => {});
|
|
1940
|
-
for (let k = 1; k <= n; k++) {
|
|
1941
|
-
const p = sampleAlong(path, easeParam(k / n));
|
|
1942
|
-
mouse(cdp, "mouseMoved", p.x, p.y, 1).catch(() => {});
|
|
1943
|
-
const due = tDrag + target * k / n;
|
|
1944
|
-
const slack = due - Date.now();
|
|
1945
|
-
if (slack > 0) await sleep(slack);
|
|
1946
|
-
}
|
|
1947
|
-
const last = path[path.length - 1];
|
|
1948
|
-
mouse(cdp, "mouseReleased", last.x, last.y, 0).catch(() => {});
|
|
1949
|
-
const drawnMs = Date.now() - tDrag;
|
|
1950
|
-
await sleep(120);
|
|
1951
|
-
pumpPaused = false;
|
|
1952
|
-
events.push({
|
|
1953
|
-
kind: "drag",
|
|
1954
|
-
x: from.x,
|
|
1955
|
-
y: from.y,
|
|
1956
|
-
to,
|
|
1957
|
-
path,
|
|
1958
|
-
tMs: tMs$1,
|
|
1959
|
-
sel: label$1,
|
|
1960
|
-
note: step.note,
|
|
1961
|
-
...step.caption ? { caption: step.caption } : {},
|
|
1962
|
-
durationMs: drawnMs,
|
|
1963
|
-
ease: dragEase,
|
|
1964
|
-
...step.zoom ? { zoom: step.zoom } : {}
|
|
1965
|
-
});
|
|
1966
|
-
await hold(1100);
|
|
1967
|
-
continue;
|
|
1968
|
-
}
|
|
1969
|
-
if (step.action === "dropFiles") {
|
|
1970
|
-
const label$1 = step.note ?? step.paths.map((p) => basename(p)).join(", ");
|
|
1971
|
-
if (!step.paths.length) {
|
|
1972
|
-
skip("dropFiles", label$1, "no files given (empty paths)");
|
|
1973
|
-
await hold(600);
|
|
1974
|
-
continue;
|
|
1975
|
-
}
|
|
1976
|
-
const absPaths = step.paths.map((p) => resolve(p));
|
|
1977
|
-
const missing = absPaths.filter((p) => !existsSync(p));
|
|
1978
|
-
if (missing.length) {
|
|
1979
|
-
skip("dropFiles", label$1, `file not found: ${missing.join(", ")}`);
|
|
1980
|
-
await hold(600);
|
|
1981
|
-
continue;
|
|
1982
|
-
}
|
|
1983
|
-
const files = absPaths.map((p) => {
|
|
1984
|
-
const st = statSync(p);
|
|
1985
|
-
return {
|
|
1986
|
-
name: basename(p),
|
|
1987
|
-
size: st.size
|
|
1988
|
-
};
|
|
1989
|
-
});
|
|
1990
|
-
let to;
|
|
1991
|
-
if (step.to || step.toSelector || step.toText) {
|
|
1992
|
-
const found = await resolvePoint({
|
|
1993
|
-
point: step.to,
|
|
1994
|
-
selector: step.toSelector,
|
|
1995
|
-
text: step.toText
|
|
1996
|
-
});
|
|
1997
|
-
if (!found) {
|
|
1998
|
-
skip("dropFiles", label$1, "drop target not found");
|
|
1999
|
-
await hold(600);
|
|
2000
|
-
continue;
|
|
2001
|
-
}
|
|
2002
|
-
to = found;
|
|
2003
|
-
} else to = {
|
|
2004
|
-
x: Math.round(inner[0] / 2),
|
|
2005
|
-
y: Math.round(inner[1] / 2)
|
|
2006
|
-
};
|
|
2007
|
-
const from = step.from ? {
|
|
2008
|
-
x: Math.round(step.from.x),
|
|
2009
|
-
y: Math.round(step.from.y)
|
|
2010
|
-
} : {
|
|
2011
|
-
x: inner[0] - 28,
|
|
2012
|
-
y: Math.round(inner[1] * .18)
|
|
2013
|
-
};
|
|
2014
|
-
const pathPts = (step.path ?? []).map((p) => ({
|
|
2015
|
-
x: Math.round(p.x),
|
|
2016
|
-
y: Math.round(p.y)
|
|
2017
|
-
}));
|
|
2018
|
-
const path = pathPts.length ? pathPts : [from, to];
|
|
2019
|
-
const target = step.durationMs ?? 1400;
|
|
2020
|
-
const dragEase = opts.dragEasing ?? "smooth";
|
|
2021
|
-
const easeParam = dragEase === "smooth" ? smoother : (u) => u;
|
|
2022
|
-
const data = {
|
|
2023
|
-
items: [],
|
|
2024
|
-
files: absPaths,
|
|
2025
|
-
dragOperationsMask: 1
|
|
2026
|
-
};
|
|
2027
|
-
const dragEvt = (type, p) => cdp.send("Input.dispatchDragEvent", {
|
|
2028
|
-
type,
|
|
2029
|
-
x: Math.round(p.x),
|
|
2030
|
-
y: Math.round(p.y),
|
|
2031
|
-
data
|
|
2032
|
-
});
|
|
2033
|
-
const n = Math.max(12, Math.round(target / 16));
|
|
2034
|
-
const tMs$1 = Date.now() - t0;
|
|
2035
|
-
pumpPaused = true;
|
|
2036
|
-
await sleep(160);
|
|
2037
|
-
const tCarry = Date.now();
|
|
2038
|
-
const last = path[path.length - 1];
|
|
2039
|
-
let carriedMs;
|
|
2040
|
-
try {
|
|
2041
|
-
await dragEvt("dragEnter", path[0]);
|
|
2042
|
-
for (let k = 1; k <= n; k++) {
|
|
2043
|
-
const p = sampleAlong(path, easeParam(k / n));
|
|
2044
|
-
dragEvt("dragOver", p).catch(() => {});
|
|
2045
|
-
const due = tCarry + target * k / n;
|
|
2046
|
-
const slack = due - Date.now();
|
|
2047
|
-
if (slack > 0) await sleep(slack);
|
|
2048
|
-
}
|
|
2049
|
-
await dragEvt("dragOver", last).catch(() => {});
|
|
2050
|
-
await dragEvt("drop", last);
|
|
2051
|
-
carriedMs = Date.now() - tCarry;
|
|
2052
|
-
} catch (e) {
|
|
2053
|
-
pumpPaused = false;
|
|
2054
|
-
skip("dropFiles", label$1, `drag dispatch failed: ${e.message}`);
|
|
2055
|
-
await hold(600);
|
|
2056
|
-
continue;
|
|
2057
|
-
}
|
|
2058
|
-
await sleep(120);
|
|
2059
|
-
pumpPaused = false;
|
|
2060
|
-
events.push({
|
|
2061
|
-
kind: "dropFiles",
|
|
2062
|
-
x: path[0].x,
|
|
2063
|
-
y: path[0].y,
|
|
2064
|
-
to: last,
|
|
2065
|
-
path,
|
|
2066
|
-
tMs: tMs$1,
|
|
2067
|
-
sel: label$1,
|
|
2068
|
-
note: step.note,
|
|
2069
|
-
...step.caption ? { caption: step.caption } : {},
|
|
2070
|
-
durationMs: carriedMs,
|
|
2071
|
-
ease: dragEase,
|
|
2072
|
-
files,
|
|
2073
|
-
...step.zoom ? { zoom: step.zoom } : {}
|
|
2074
|
-
});
|
|
2075
|
-
await hold(1600);
|
|
2076
|
-
continue;
|
|
2077
|
-
}
|
|
2078
|
-
if (step.action === "scroll") {
|
|
2079
|
-
const tMs$1 = Date.now() - t0;
|
|
2080
|
-
let dy;
|
|
2081
|
-
if (step.toSelector || step.toText) {
|
|
2082
|
-
const r = await evalAny(cdp, step.toSelector ? scrollDeltaSelectorJs(step.toSelector) : scrollDeltaByTextJs(step.toText));
|
|
2083
|
-
if (r && typeof r.dy === "number") dy = r.dy;
|
|
2084
|
-
else {
|
|
2085
|
-
skip("scroll", step.toText ?? step.toSelector, "target not found");
|
|
2086
|
-
await hold(600);
|
|
2087
|
-
continue;
|
|
2088
|
-
}
|
|
2089
|
-
} else dy = step.dy ?? Math.round(vh * .8);
|
|
2090
|
-
const targetMs = step.durationMs ?? 1e3;
|
|
2091
|
-
const cx = Math.round(inner[0] / 2), cy = Math.round(inner[1] / 2);
|
|
2092
|
-
const start = Number(await evalAny(cdp, "window.scrollY")) || 0;
|
|
2093
|
-
const n = Math.max(12, Math.round(targetMs / 16));
|
|
2094
|
-
const tScroll = Date.now();
|
|
2095
|
-
for (let k = 1; k <= n; k++) {
|
|
2096
|
-
const u = k / n;
|
|
2097
|
-
const want = Math.round(dy * (u * u * u * (u * (u * 6 - 15) + 10)));
|
|
2098
|
-
await cdp.send("Runtime.evaluate", { expression: `window.scrollTo(0, ${start + want})` });
|
|
2099
|
-
const due = tScroll + targetMs * k / n;
|
|
2100
|
-
const slack = due - Date.now();
|
|
2101
|
-
if (slack > 0) await sleep(slack);
|
|
2102
|
-
}
|
|
2103
|
-
events.push({
|
|
2104
|
-
kind: "scroll",
|
|
2105
|
-
x: cx,
|
|
2106
|
-
y: cy,
|
|
2107
|
-
tMs: tMs$1,
|
|
2108
|
-
dy,
|
|
2109
|
-
durationMs: Date.now() - tScroll,
|
|
2110
|
-
note: step.note,
|
|
2111
|
-
...step.caption ? { caption: step.caption } : {}
|
|
2112
|
-
});
|
|
2113
|
-
await hold(800);
|
|
2114
|
-
continue;
|
|
2115
|
-
}
|
|
2116
|
-
if (step.action === "hover") {
|
|
2117
|
-
const label$1 = step.text ?? step.selector;
|
|
2118
|
-
const tMs$1 = Date.now() - t0;
|
|
2119
|
-
const box$1 = step.text ? await evalBox(cdp, boxByTextJs(step.text)) : step.selector ? await evalBox(cdp, boxSelectorJs(step.selector)) : null;
|
|
2120
|
-
if (!box$1) {
|
|
2121
|
-
skip("hover", label$1, "target not found");
|
|
2122
|
-
await hold(600);
|
|
2123
|
-
continue;
|
|
2124
|
-
}
|
|
2125
|
-
const c = center(box$1);
|
|
2126
|
-
const dwell = step.durationMs ?? 1200;
|
|
2127
|
-
await mouse(cdp, "mouseMoved", c.x, c.y, 0);
|
|
2128
|
-
events.push({
|
|
2129
|
-
kind: "hover",
|
|
2130
|
-
...c,
|
|
2131
|
-
box: box$1,
|
|
2132
|
-
tMs: tMs$1,
|
|
2133
|
-
sel: label$1,
|
|
2134
|
-
note: step.note,
|
|
2135
|
-
...step.caption ? { caption: step.caption } : {},
|
|
2136
|
-
durationMs: dwell,
|
|
2137
|
-
...step.zoom ? { zoom: step.zoom } : {}
|
|
2138
|
-
});
|
|
2139
|
-
await sleep(dwell);
|
|
2140
|
-
await hold(900);
|
|
2141
|
-
continue;
|
|
2142
|
-
}
|
|
2143
|
-
if (step.action === "select") {
|
|
2144
|
-
const label$1 = step.text ?? step.selector;
|
|
2145
|
-
const tMs$1 = Date.now() - t0;
|
|
2146
|
-
const r = await cdp.send("Runtime.evaluate", {
|
|
2147
|
-
expression: selectOptionJs({
|
|
2148
|
-
selector: step.selector,
|
|
2149
|
-
text: step.text
|
|
2150
|
-
}, step.value),
|
|
2151
|
-
returnByValue: true,
|
|
2152
|
-
awaitPromise: true
|
|
2153
|
-
});
|
|
2154
|
-
const raw = r.result?.value;
|
|
2155
|
-
const str = typeof raw === "string" ? raw : raw == null ? "NOTFOUND" : JSON.stringify(raw);
|
|
2156
|
-
if (str === "NOTFOUND" || str === "NOTASELECT" || str === "NOOPTION") {
|
|
2157
|
-
skip("select", label$1, str === "NOTASELECT" ? "target is not a <select> (use click for custom dropdowns)" : str === "NOOPTION" ? `no option matching ${JSON.stringify(step.value)}` : "target not found");
|
|
2158
|
-
await hold(600);
|
|
2159
|
-
continue;
|
|
2160
|
-
}
|
|
2161
|
-
const box$1 = findBox(evalValue(str));
|
|
2162
|
-
if (!box$1) {
|
|
2163
|
-
skip("select", label$1, "target not found");
|
|
2164
|
-
await hold(600);
|
|
2165
|
-
continue;
|
|
2166
|
-
}
|
|
2167
|
-
events.push({
|
|
2168
|
-
kind: "click",
|
|
2169
|
-
...center(box$1),
|
|
2170
|
-
box: box$1,
|
|
2171
|
-
tMs: tMs$1,
|
|
2172
|
-
sel: label$1,
|
|
2173
|
-
note: step.note,
|
|
2174
|
-
...step.caption ? { caption: step.caption } : {},
|
|
2175
|
-
...step.zoom ? { zoom: step.zoom } : {}
|
|
2176
|
-
});
|
|
2177
|
-
await hold(1300);
|
|
2178
|
-
continue;
|
|
2179
|
-
}
|
|
2180
|
-
if (step.action === "look") {
|
|
2181
|
-
const label$1 = step.text ?? step.selector;
|
|
2182
|
-
const tMs$1 = Date.now() - t0;
|
|
2183
|
-
const box$1 = step.text ? await evalBox(cdp, boxByTextJs(step.text)) : step.selector ? await evalBox(cdp, boxSelectorJs(step.selector)) : null;
|
|
2184
|
-
if (!box$1) {
|
|
2185
|
-
skip("look", label$1, step.text || step.selector ? "target not found" : "no target given");
|
|
2186
|
-
await hold(600);
|
|
2187
|
-
continue;
|
|
2188
|
-
}
|
|
2189
|
-
const dwell = step.durationMs ?? 1800;
|
|
2190
|
-
events.push({
|
|
2191
|
-
kind: "look",
|
|
2192
|
-
...center(box$1),
|
|
2193
|
-
box: box$1,
|
|
2194
|
-
tMs: tMs$1,
|
|
2195
|
-
sel: label$1,
|
|
2196
|
-
note: step.note,
|
|
2197
|
-
...step.caption ? { caption: step.caption } : {},
|
|
2198
|
-
durationMs: dwell,
|
|
2199
|
-
zoom: step.zoom ?? "always"
|
|
2200
|
-
});
|
|
2201
|
-
await sleep(dwell);
|
|
2202
|
-
await hold(900);
|
|
2203
|
-
continue;
|
|
2204
|
-
}
|
|
2205
|
-
if (step.action === "press") {
|
|
2206
|
-
const tMs$1 = Date.now() - t0;
|
|
2207
|
-
try {
|
|
2208
|
-
await pressChord(cdp, step.keys);
|
|
2209
|
-
} catch (e) {
|
|
2210
|
-
console.error(`captureTakeCDP: press failed for ${JSON.stringify(step.keys)}: ${e.message}`);
|
|
2211
|
-
}
|
|
2212
|
-
const dwell = step.durationMs ?? 1e3;
|
|
2213
|
-
let box$1 = null;
|
|
2214
|
-
if (step.selector || step.text) {
|
|
2215
|
-
await sleep(250);
|
|
2216
|
-
box$1 = step.text ? await evalBox(cdp, boxByTextJs(step.text)) : await evalBox(cdp, boxSelectorJs(step.selector));
|
|
2217
|
-
}
|
|
2218
|
-
const anchor = box$1 ? center(box$1) : {
|
|
2219
|
-
x: Math.round(inner[0] / 2),
|
|
2220
|
-
y: Math.round(inner[1] / 2)
|
|
2221
|
-
};
|
|
2222
|
-
events.push({
|
|
2223
|
-
kind: "press",
|
|
2224
|
-
...anchor,
|
|
2225
|
-
...box$1 ? { box: box$1 } : {},
|
|
2226
|
-
tMs: tMs$1,
|
|
2227
|
-
keys: step.keys,
|
|
2228
|
-
sel: step.text ?? step.selector,
|
|
2229
|
-
note: step.note,
|
|
2230
|
-
...step.caption ? { caption: step.caption } : {},
|
|
2231
|
-
durationMs: dwell,
|
|
2232
|
-
...step.zoom ? { zoom: step.zoom } : {}
|
|
2233
|
-
});
|
|
2234
|
-
await sleep(dwell);
|
|
2235
|
-
await hold(900);
|
|
2236
|
-
continue;
|
|
2237
|
-
}
|
|
2238
|
-
const label = step.text ?? step.selector;
|
|
2239
|
-
let tMs = Date.now() - t0;
|
|
2240
|
-
const clickRaw = step.text ? await evalString(cdp, clickByTextJs(step.text)) : step.selector ? await evalString(cdp, clickBySelectorJs(step.selector)) : null;
|
|
2241
|
-
if (clickRaw === "SELECTINERT") {
|
|
2242
|
-
skip("click", label, "clicking a native <select> does nothing headless (inert, no popup) — use the `select` action");
|
|
2243
|
-
await hold(600);
|
|
2244
|
-
continue;
|
|
2245
|
-
}
|
|
2246
|
-
const parsed = clickRaw ? evalValue(clickRaw) : null;
|
|
2247
|
-
const box = parsed ? findBox(parsed) : null;
|
|
2248
|
-
const pt = parsed && typeof parsed.cx === "number" && typeof parsed.cy === "number" ? {
|
|
2249
|
-
x: parsed.cx,
|
|
2250
|
-
y: parsed.cy
|
|
2251
|
-
} : null;
|
|
2252
|
-
if (box && pt) {
|
|
2253
|
-
pumpPaused = true;
|
|
2254
|
-
await sleep(160);
|
|
2255
|
-
tMs = Date.now() - t0;
|
|
2256
|
-
mouse(cdp, "mouseMoved", pt.x, pt.y, 0).catch(() => {});
|
|
2257
|
-
mouse(cdp, "mousePressed", pt.x, pt.y, 1).catch(() => {});
|
|
2258
|
-
await sleep(60);
|
|
2259
|
-
mouse(cdp, "mouseReleased", pt.x, pt.y, 0).catch(() => {});
|
|
2260
|
-
await sleep(120);
|
|
2261
|
-
pumpPaused = false;
|
|
2262
|
-
}
|
|
2263
|
-
if (box) events.push({
|
|
2264
|
-
kind: "click",
|
|
2265
|
-
...pt ?? center(box),
|
|
2266
|
-
box,
|
|
2267
|
-
tMs,
|
|
2268
|
-
sel: label,
|
|
2269
|
-
note: step.note,
|
|
2270
|
-
...step.caption ? { caption: step.caption } : {},
|
|
2271
|
-
...step.zoom ? { zoom: step.zoom } : {}
|
|
2272
|
-
});
|
|
2273
|
-
else skip("click", label, "target not found");
|
|
2274
|
-
await hold(1300);
|
|
2275
|
-
}
|
|
2276
|
-
const tEndMs = Date.now() - t0;
|
|
2277
|
-
await sleep(400);
|
|
2278
|
-
pumping = false;
|
|
2279
|
-
await pump;
|
|
2280
|
-
await screencast.stop();
|
|
2281
|
-
await encodeFrames(screencast.frames, tEndMs + 400, out, fps);
|
|
2282
|
-
const probe = await ffprobe(out);
|
|
2283
|
-
if (probe.width && probe.height) {
|
|
2284
|
-
const videoAspect = probe.width / probe.height;
|
|
2285
|
-
const viewAspect = inner[0] / inner[1];
|
|
2286
|
-
if (Math.abs(videoAspect / viewAspect - 1) > .01) process.stderr.write(`⚠ the browser window resized MID-capture: viewport ${inner[0]}×${inner[1]} but the recording is ${probe.width}×${probe.height} — cursor/zoom coordinates in this take are skewed. Re-run; in a cloud/Xvfb environment give the screen a fixed size at least the requested viewport.\n`);
|
|
2287
|
-
}
|
|
2288
|
-
return {
|
|
2289
|
-
video: {
|
|
2290
|
-
width: probe.width ?? inner[0],
|
|
2291
|
-
height: probe.height ?? inner[1],
|
|
2292
|
-
fps: probe.fps,
|
|
2293
|
-
durationS: probe.durationS
|
|
2294
|
-
},
|
|
2295
|
-
viewport: {
|
|
2296
|
-
w: inner[0],
|
|
2297
|
-
h: inner[1]
|
|
2298
|
-
},
|
|
2299
|
-
start: plan.startCursor ?? {
|
|
2300
|
-
x: Math.round(inner[0] * .25),
|
|
2301
|
-
y: Math.round(inner[1] * .9)
|
|
2302
|
-
},
|
|
2303
|
-
events,
|
|
2304
|
-
tEndMs,
|
|
2305
|
-
captureCadence: {
|
|
2306
|
-
...captureCadence(screencast.frames),
|
|
2307
|
-
rasterRefresh: opts.rasterRefresh ?? "idle"
|
|
2308
|
-
},
|
|
2309
|
-
...skipped.length ? { skipped } : {},
|
|
2310
|
-
...precheck.length ? { precheck } : {},
|
|
2311
|
-
...settleWaits.length ? { settleWaits } : {},
|
|
2312
|
-
...paintedFrac >= PAINT_BLIND_FRAC ? { paintedFrac: Math.round(paintedFrac * 100) / 100 } : {}
|
|
2313
|
-
};
|
|
2314
|
-
} finally {
|
|
2315
|
-
await browser?.close();
|
|
2316
|
-
rmSync(frameDir, {
|
|
2317
|
-
recursive: true,
|
|
2318
|
-
force: true,
|
|
2319
|
-
maxRetries: 5,
|
|
2320
|
-
retryDelay: 100
|
|
2321
|
-
});
|
|
2322
|
-
}
|
|
2323
|
-
}
|
|
2324
|
-
/** CI containment. A plan is agent-written, and the agent reads the very page
|
|
2325
|
-
* it films — a hostile string ON that page can talk its way into a plan step.
|
|
2326
|
-
* When OPEN_TAKE_ALLOWED_ORIGINS is set (comma-separated origins; `open-take
|
|
2327
|
-
* ci` sets it to the app's own origin), any navigation outside the list is a
|
|
2328
|
-
* skipped step, never a request. Unset (the interactive default), everything
|
|
2329
|
-
* is allowed — a human is watching. */
|
|
2330
|
-
function originAllowed(url) {
|
|
2331
|
-
const raw = process.env.OPEN_TAKE_ALLOWED_ORIGINS;
|
|
2332
|
-
if (!raw) return true;
|
|
2333
|
-
try {
|
|
2334
|
-
const origin = new URL(url).origin;
|
|
2335
|
-
return raw.split(",").some((entry) => entry.trim() === origin);
|
|
2336
|
-
} catch {
|
|
2337
|
-
return false;
|
|
2338
|
-
}
|
|
2339
|
-
}
|
|
2340
|
-
/** Runs in-page AFTER focus landed on the type target: names the field
|
|
2341
|
-
* "secret" when it is a password input or smells like a credential field.
|
|
2342
|
-
* Only consulted under OPEN_TAKE_CI — locally the human sees what is typed. */
|
|
2343
|
-
function credentialFieldProbeJs() {
|
|
2344
|
-
return `(() => {
|
|
2345
|
-
const el = document.activeElement;
|
|
2346
|
-
if (!el) return "ok";
|
|
2347
|
-
const type = (el.getAttribute("type") || "").toLowerCase();
|
|
2348
|
-
const smell = [el.getAttribute("name"), el.getAttribute("id"), el.getAttribute("autocomplete"), el.getAttribute("placeholder")]
|
|
2349
|
-
.filter(Boolean).join(" ").toLowerCase();
|
|
2350
|
-
return type === "password" || /passw|secret|api[-_]?key|access[-_]?token/.test(smell) ? "secret" : "ok";
|
|
2351
|
-
})()`;
|
|
2352
|
-
}
|
|
2353
|
-
/** Returns Chrome's `errorText` (e.g. "net::ERR_CONNECTION_REFUSED") when the
|
|
2354
|
-
* navigation never reached a server — the tab is then showing Chrome's own
|
|
2355
|
-
* error page, which fires load events like any document and would otherwise
|
|
2356
|
-
* get filmed as if it were the app. HTTP error PAGES (404/500) carry no
|
|
2357
|
-
* errorText: the app answered, and what it said is what an honest take shows. */
|
|
2358
|
-
async function navigate(cdp, url) {
|
|
2359
|
-
const loaded = new Promise((res) => {
|
|
2360
|
-
cdp.on("Page.loadEventFired", () => res());
|
|
2361
|
-
setTimeout(res, 8e3);
|
|
2362
|
-
});
|
|
2363
|
-
const nav = await cdp.send("Page.navigate", { url });
|
|
2364
|
-
await loaded;
|
|
2365
|
-
return nav.errorText || void 0;
|
|
2366
|
-
}
|
|
2367
|
-
|
|
2368
|
-
//#endregion
|
|
2369
|
-
export { PrecheckRefusal, captureTake, captureTakeCDP, ensureChrome, inspectPage, planTargets, precheckPlan, resolveChrome, resolveNavigateUrl };
|
|
2370
|
-
//# sourceMappingURL=cdp-capture-MBg9nQy3.js.map
|