@howaboua/pi-browser 0.0.3 → 0.0.5
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/CHANGELOG.md +18 -0
- package/README.md +4 -0
- package/dist/index.js +2 -2
- package/dist/remote-worker.js +1026 -176
- package/dist/src/browser/bounds.d.ts +1 -1
- package/dist/src/browser/bounds.js +13 -4
- package/dist/src/browser/help.js +11 -6
- package/dist/src/browser/operation-executor.js +15 -1
- package/dist/src/browser/operation.d.ts +25 -2
- package/dist/src/browser/operation.js +5 -0
- package/dist/src/browser/parse-operation.js +61 -2
- package/dist/src/browser/remote.d.ts +1 -1
- package/dist/src/browser/remote.js +2 -2
- package/dist/src/browser/runtime.d.ts +8 -3
- package/dist/src/browser/runtime.js +91 -25
- package/dist/src/browser/worker-server.js +12 -6
- package/dist/src/browser-parameters.d.ts +10 -0
- package/dist/src/browser-parameters.js +34 -5
- package/dist/src/browser-tool.d.ts +10 -0
- package/dist/src/browser-tool.js +2 -1
- package/dist/src/cdp/actions/click.d.ts +2 -0
- package/dist/src/cdp/actions/click.js +1 -1
- package/dist/src/cdp/actions/element.js +4 -0
- package/dist/src/cdp/actions/fill.d.ts +8 -0
- package/dist/src/cdp/actions/fill.js +175 -0
- package/dist/src/cdp/actions/key.d.ts +20 -0
- package/dist/src/cdp/actions/key.js +166 -0
- package/dist/src/cdp/actions/wait.d.ts +9 -0
- package/dist/src/cdp/actions/wait.js +95 -0
- package/dist/src/cdp/pages.d.ts +2 -1
- package/dist/src/cdp/pages.js +8 -4
- package/dist/src/cdp/session.d.ts +7 -1
- package/dist/src/cdp/session.js +79 -27
- package/dist/src/cdp/snapshot-contract.d.ts +6 -0
- package/dist/src/cdp/snapshot.js +72 -11
- package/dist/src/cdp/tabs.d.ts +32 -0
- package/dist/src/cdp/tabs.js +226 -0
- package/dist/src/cdp/types.d.ts +2 -0
- package/index.ts +2 -2
- package/package.json +5 -5
- package/src/browser/bounds.ts +14 -3
- package/src/browser/help.ts +12 -6
- package/src/browser/operation-executor.ts +34 -0
- package/src/browser/operation.ts +19 -1
- package/src/browser/parse-operation.ts +63 -2
- package/src/browser/remote.ts +2 -1
- package/src/browser/runtime.ts +115 -26
- package/src/browser/worker-server.ts +24 -7
- package/src/browser-parameters.ts +131 -96
- package/src/browser-tool.ts +2 -1
- package/src/cdp/actions/click.ts +1 -1
- package/src/cdp/actions/element.ts +4 -0
- package/src/cdp/actions/fill.ts +246 -0
- package/src/cdp/actions/key.ts +202 -0
- package/src/cdp/actions/wait.ts +117 -0
- package/src/cdp/pages.ts +9 -6
- package/src/cdp/session.ts +98 -46
- package/src/cdp/snapshot-contract.ts +6 -0
- package/src/cdp/snapshot.ts +92 -17
- package/src/cdp/tabs.ts +292 -0
- package/src/cdp/types.ts +2 -0
package/dist/remote-worker.js
CHANGED
|
@@ -2,28 +2,190 @@
|
|
|
2
2
|
// @howaboua/pi-browser managed worker
|
|
3
3
|
|
|
4
4
|
// remote-worker.ts
|
|
5
|
-
import { createHash } from "node:crypto";
|
|
5
|
+
import { createHash as createHash2 } from "node:crypto";
|
|
6
6
|
import { readFileSync as readFileSync3, realpathSync } from "node:fs";
|
|
7
7
|
import { resolve as resolve2 } from "node:path";
|
|
8
8
|
import { fileURLToPath as fileURLToPath2 } from "node:url";
|
|
9
9
|
|
|
10
10
|
// src/browser/worker-server.ts
|
|
11
11
|
import { spawn as spawn3 } from "node:child_process";
|
|
12
|
-
import { chmod, lstat, mkdir as
|
|
12
|
+
import { chmod, lstat as lstat2, mkdir as mkdir4, rm as rm4 } from "node:fs/promises";
|
|
13
13
|
import { createConnection, createServer } from "node:net";
|
|
14
14
|
import { tmpdir as tmpdir2 } from "node:os";
|
|
15
|
-
import { dirname as dirname2, join as
|
|
15
|
+
import { dirname as dirname2, join as join6 } from "node:path";
|
|
16
16
|
import { StringDecoder as StringDecoder3 } from "node:string_decoder";
|
|
17
17
|
|
|
18
|
+
// src/cdp/actions/key.ts
|
|
19
|
+
var MODIFIERS = { Alt: 1, Control: 2, Meta: 4, Shift: 8 };
|
|
20
|
+
var ALIASES = {
|
|
21
|
+
Ctrl: "Control",
|
|
22
|
+
Cmd: "Meta",
|
|
23
|
+
Option: "Alt"
|
|
24
|
+
};
|
|
25
|
+
var NAMED_KEYS = {
|
|
26
|
+
Backspace: 8,
|
|
27
|
+
Tab: 9,
|
|
28
|
+
Enter: 13,
|
|
29
|
+
Escape: 27,
|
|
30
|
+
Space: 32,
|
|
31
|
+
PageUp: 33,
|
|
32
|
+
PageDown: 34,
|
|
33
|
+
End: 35,
|
|
34
|
+
Home: 36,
|
|
35
|
+
ArrowLeft: 37,
|
|
36
|
+
ArrowUp: 38,
|
|
37
|
+
ArrowRight: 39,
|
|
38
|
+
ArrowDown: 40,
|
|
39
|
+
Insert: 45,
|
|
40
|
+
Delete: 46
|
|
41
|
+
};
|
|
42
|
+
var PUNCTUATION = {
|
|
43
|
+
"`~": { code: "Backquote", keyCode: 192 },
|
|
44
|
+
"-_": { code: "Minus", keyCode: 189 },
|
|
45
|
+
"=+": { code: "Equal", keyCode: 187 },
|
|
46
|
+
"[{": { code: "BracketLeft", keyCode: 219 },
|
|
47
|
+
"]}": { code: "BracketRight", keyCode: 221 },
|
|
48
|
+
"\\|": { code: "Backslash", keyCode: 220 },
|
|
49
|
+
";:": { code: "Semicolon", keyCode: 186 },
|
|
50
|
+
"'\"": { code: "Quote", keyCode: 222 },
|
|
51
|
+
",<": { code: "Comma", keyCode: 188 },
|
|
52
|
+
".>": { code: "Period", keyCode: 190 },
|
|
53
|
+
"/?": { code: "Slash", keyCode: 191 }
|
|
54
|
+
};
|
|
55
|
+
function keyDefinition(name, shift) {
|
|
56
|
+
const namedCode = Object.hasOwn(NAMED_KEYS, name) ? NAMED_KEYS[name] : undefined;
|
|
57
|
+
if (namedCode !== undefined) {
|
|
58
|
+
return {
|
|
59
|
+
key: name === "Space" ? " " : name,
|
|
60
|
+
code: name,
|
|
61
|
+
windowsVirtualKeyCode: namedCode,
|
|
62
|
+
...name === "Enter" ? { text: "\r" } : name === "Space" ? { text: " " } : {}
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
if (/^F(?:[1-9]|1[0-2])$/.test(name)) {
|
|
66
|
+
return {
|
|
67
|
+
key: name,
|
|
68
|
+
code: name,
|
|
69
|
+
windowsVirtualKeyCode: 111 + Number(name.slice(1))
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
const key = name === "Plus" ? "+" : name;
|
|
73
|
+
if ([...key].length !== 1) {
|
|
74
|
+
throw new Error(`Unknown key ${name}; use a character, Enter, Tab, Escape, arrows, or a chord such as Control+a`);
|
|
75
|
+
}
|
|
76
|
+
if (/^[a-z]$/i.test(key)) {
|
|
77
|
+
const text = shift ? key.toUpperCase() : key;
|
|
78
|
+
return {
|
|
79
|
+
key: text,
|
|
80
|
+
code: `Key${key.toUpperCase()}`,
|
|
81
|
+
windowsVirtualKeyCode: key.toUpperCase().charCodeAt(0),
|
|
82
|
+
text
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
const digit = "0123456789".indexOf(key);
|
|
86
|
+
const shiftedDigit = ")!@#$%^&*(".indexOf(key);
|
|
87
|
+
if (digit >= 0 || shiftedDigit >= 0) {
|
|
88
|
+
const number = digit >= 0 ? digit : shiftedDigit;
|
|
89
|
+
const text = shift && digit >= 0 ? ")!@#$%^&*(".charAt(number) : key;
|
|
90
|
+
return {
|
|
91
|
+
key: text,
|
|
92
|
+
code: `Digit${number}`,
|
|
93
|
+
windowsVirtualKeyCode: 48 + number,
|
|
94
|
+
text
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
for (const [characters, definition] of Object.entries(PUNCTUATION)) {
|
|
98
|
+
if (!characters.includes(key))
|
|
99
|
+
continue;
|
|
100
|
+
const text = shift ? characters.charAt(1) : key;
|
|
101
|
+
return {
|
|
102
|
+
key: text,
|
|
103
|
+
code: definition.code,
|
|
104
|
+
windowsVirtualKeyCode: definition.keyCode,
|
|
105
|
+
text
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
return { key, code: "", windowsVirtualKeyCode: 0, text: key };
|
|
109
|
+
}
|
|
110
|
+
function parseKeyChord(chord) {
|
|
111
|
+
const parts = chord === "+" ? ["Plus"] : chord.split("+").map((part) => part.trim());
|
|
112
|
+
const name = parts.pop();
|
|
113
|
+
if (!name)
|
|
114
|
+
throw new Error("Missing key; use Plus for + in a chord");
|
|
115
|
+
const modifiers = [];
|
|
116
|
+
for (const part of parts) {
|
|
117
|
+
const modifier = ALIASES[part] ?? part;
|
|
118
|
+
if (!Object.hasOwn(MODIFIERS, modifier))
|
|
119
|
+
throw new Error(`Unknown modifier ${part}; use Control, Alt, Shift, or Meta`);
|
|
120
|
+
const valid = modifier;
|
|
121
|
+
if (modifiers.includes(valid))
|
|
122
|
+
throw new Error(`Repeated modifier ${part}`);
|
|
123
|
+
modifiers.push(valid);
|
|
124
|
+
}
|
|
125
|
+
return { modifiers, key: keyDefinition(name, modifiers.includes("Shift")) };
|
|
126
|
+
}
|
|
127
|
+
async function pressKey(cdp, sessionId, chord, signal) {
|
|
128
|
+
const { modifiers, key } = parseKeyChord(chord);
|
|
129
|
+
const held = [];
|
|
130
|
+
let mask = 0;
|
|
131
|
+
let failure;
|
|
132
|
+
try {
|
|
133
|
+
for (const modifier of modifiers) {
|
|
134
|
+
signal?.throwIfAborted();
|
|
135
|
+
const bit = MODIFIERS[modifier];
|
|
136
|
+
const keyCode = { Alt: 18, Control: 17, Meta: 91, Shift: 16 }[modifier];
|
|
137
|
+
const modifierKey = {
|
|
138
|
+
key: modifier,
|
|
139
|
+
code: `${modifier}Left`,
|
|
140
|
+
windowsVirtualKeyCode: keyCode
|
|
141
|
+
};
|
|
142
|
+
mask |= bit;
|
|
143
|
+
held.push({ key: modifierKey, bit });
|
|
144
|
+
await cdp.send("Input.dispatchKeyEvent", { ...modifierKey, type: "rawKeyDown", modifiers: mask }, sessionId, signal);
|
|
145
|
+
}
|
|
146
|
+
signal?.throwIfAborted();
|
|
147
|
+
held.push({ key, bit: 0 });
|
|
148
|
+
const { text, ...identity } = key;
|
|
149
|
+
const insertsText = text !== undefined && (mask & ~MODIFIERS.Shift) === 0;
|
|
150
|
+
await cdp.send("Input.dispatchKeyEvent", {
|
|
151
|
+
...identity,
|
|
152
|
+
type: insertsText ? "keyDown" : "rawKeyDown",
|
|
153
|
+
modifiers: mask,
|
|
154
|
+
...insertsText ? { text } : {}
|
|
155
|
+
}, sessionId, signal);
|
|
156
|
+
} catch (error) {
|
|
157
|
+
failure = error;
|
|
158
|
+
} finally {
|
|
159
|
+
for (const heldKey of held.reverse()) {
|
|
160
|
+
mask &= ~heldKey.bit;
|
|
161
|
+
const { text: _text, ...identity } = heldKey.key;
|
|
162
|
+
try {
|
|
163
|
+
await cdp.send("Input.dispatchKeyEvent", { ...identity, type: "keyUp", modifiers: mask }, sessionId);
|
|
164
|
+
} catch (error) {
|
|
165
|
+
failure = failure ? new AggregateError([failure, error], "Key press failed; key release also failed") : error;
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
if (failure)
|
|
170
|
+
throw failure;
|
|
171
|
+
signal?.throwIfAborted();
|
|
172
|
+
return `Pressed ${chord}`;
|
|
173
|
+
}
|
|
174
|
+
|
|
18
175
|
// src/browser/operation.ts
|
|
19
176
|
var BROWSER_ACTIONS = [
|
|
20
177
|
"help",
|
|
21
178
|
"start",
|
|
22
179
|
"tabs",
|
|
23
180
|
"open",
|
|
181
|
+
"show",
|
|
182
|
+
"close",
|
|
24
183
|
"find",
|
|
25
184
|
"click",
|
|
26
185
|
"type",
|
|
186
|
+
"fill",
|
|
187
|
+
"press",
|
|
188
|
+
"wait",
|
|
27
189
|
"screenshot",
|
|
28
190
|
"html",
|
|
29
191
|
"navigate",
|
|
@@ -42,11 +204,16 @@ var fields = (...names) => new Set(["action", ...names]);
|
|
|
42
204
|
var ACTION_FIELDS = {
|
|
43
205
|
help: fields(),
|
|
44
206
|
start: fields(),
|
|
45
|
-
tabs: fields("query", "offset"),
|
|
207
|
+
tabs: fields("query", "offset", "owned_only"),
|
|
46
208
|
open: fields("ref_id", "url", "lineno", "response_length"),
|
|
209
|
+
show: fields("ref_id"),
|
|
210
|
+
close: fields("ref_id"),
|
|
47
211
|
find: fields("ref_id", "pattern", "lineno", "response_length"),
|
|
48
212
|
click: fields("ref_id", "id", "selector", "x", "y"),
|
|
49
213
|
type: fields("ref_id", "id", "text"),
|
|
214
|
+
fill: fields("ref_id", "id", "selector", "value"),
|
|
215
|
+
press: fields("ref_id", "key"),
|
|
216
|
+
wait: fields("ref_id", "selector", "text", "url_includes", "timeout_ms"),
|
|
50
217
|
screenshot: fields("ref_id", "id", "selector"),
|
|
51
218
|
html: fields("ref_id", "id", "selector"),
|
|
52
219
|
navigate: fields("ref_id", "url"),
|
|
@@ -133,25 +300,29 @@ function parseActionRequest(value) {
|
|
|
133
300
|
return { action };
|
|
134
301
|
if (action === "tabs") {
|
|
135
302
|
const query = optionalString(value["query"], "query");
|
|
303
|
+
const ownedOnly = value["owned_only"];
|
|
304
|
+
if (ownedOnly !== undefined && typeof ownedOnly !== "boolean")
|
|
305
|
+
throw new Error("owned_only must be a boolean");
|
|
136
306
|
return {
|
|
137
307
|
action,
|
|
138
308
|
...query ? { query } : {},
|
|
139
|
-
offset: offset(value["offset"])
|
|
309
|
+
offset: offset(value["offset"]),
|
|
310
|
+
...ownedOnly === undefined ? {} : { owned_only: ownedOnly }
|
|
140
311
|
};
|
|
141
312
|
}
|
|
142
313
|
if (action === "open") {
|
|
143
|
-
const
|
|
314
|
+
const refId = optionalString(value["ref_id"], "ref_id");
|
|
144
315
|
const url = optionalString(value["url"], "url");
|
|
145
|
-
if (Boolean(
|
|
316
|
+
if (Boolean(refId) === Boolean(url)) {
|
|
146
317
|
throw new Error("open requires exactly one of ref_id or url");
|
|
147
318
|
}
|
|
148
319
|
if (url)
|
|
149
320
|
return { action, url };
|
|
150
|
-
if (!
|
|
321
|
+
if (!refId)
|
|
151
322
|
throw new Error("open requires ref_id or url");
|
|
152
323
|
return {
|
|
153
324
|
action,
|
|
154
|
-
ref_id:
|
|
325
|
+
ref_id: refId,
|
|
155
326
|
lineno: line(value["lineno"]),
|
|
156
327
|
response_length: responseLength(value["response_length"])
|
|
157
328
|
};
|
|
@@ -176,11 +347,11 @@ function parseActionRequest(value) {
|
|
|
176
347
|
return { action, handle: resultHandle(value["handle"]) };
|
|
177
348
|
}
|
|
178
349
|
if (action === "stop") {
|
|
179
|
-
const
|
|
180
|
-
return { action, ...
|
|
350
|
+
const refId = optionalString(value["ref_id"], "ref_id");
|
|
351
|
+
return { action, ...refId ? { ref_id: refId } : {} };
|
|
181
352
|
}
|
|
182
353
|
const refId = requiredRef(value["ref_id"], action);
|
|
183
|
-
if (action === "network")
|
|
354
|
+
if (action === "network" || action === "show" || action === "close")
|
|
184
355
|
return { action, ref_id: refId };
|
|
185
356
|
if (action === "navigate") {
|
|
186
357
|
return {
|
|
@@ -248,6 +419,53 @@ function parseActionRequest(value) {
|
|
|
248
419
|
...selector ? { selector } : {}
|
|
249
420
|
};
|
|
250
421
|
}
|
|
422
|
+
if (action === "fill") {
|
|
423
|
+
const id = elementId(value["id"]);
|
|
424
|
+
const selector = optionalString(value["selector"], "selector");
|
|
425
|
+
if (Number(id !== undefined) + Number(selector !== undefined) !== 1) {
|
|
426
|
+
throw new Error("fill requires exactly one of id or selector");
|
|
427
|
+
}
|
|
428
|
+
const fillValue = value["value"];
|
|
429
|
+
if (typeof fillValue !== "string" && typeof fillValue !== "boolean") {
|
|
430
|
+
throw new Error("value must be text or a boolean for checkbox/radio");
|
|
431
|
+
}
|
|
432
|
+
if (id !== undefined)
|
|
433
|
+
return { action, ref_id: refId, id, value: fillValue };
|
|
434
|
+
if (selector)
|
|
435
|
+
return { action, ref_id: refId, selector, value: fillValue };
|
|
436
|
+
throw new Error("fill requires id or selector");
|
|
437
|
+
}
|
|
438
|
+
if (action === "press") {
|
|
439
|
+
const key = requiredString(value["key"], "key");
|
|
440
|
+
parseKeyChord(key);
|
|
441
|
+
return { action, ref_id: refId, key };
|
|
442
|
+
}
|
|
443
|
+
if (action === "wait") {
|
|
444
|
+
const conditions = ["selector", "text", "url_includes"];
|
|
445
|
+
const provided = conditions.filter((field) => value[field] !== undefined);
|
|
446
|
+
const field = provided[0];
|
|
447
|
+
if (provided.length !== 1 || !field) {
|
|
448
|
+
throw new Error("wait requires exactly one of selector, text, or url_includes");
|
|
449
|
+
}
|
|
450
|
+
const match = value[field];
|
|
451
|
+
if (typeof match !== "string" || !match.trim()) {
|
|
452
|
+
throw new Error(`${field} must be a non-empty string`);
|
|
453
|
+
}
|
|
454
|
+
const timeout = value["timeout_ms"] ?? 1e4;
|
|
455
|
+
if (!Number.isInteger(timeout) || Number(timeout) < 1 || Number(timeout) > 60000) {
|
|
456
|
+
throw new Error("timeout_ms must be an integer from 1 to 60000");
|
|
457
|
+
}
|
|
458
|
+
const base = {
|
|
459
|
+
action,
|
|
460
|
+
ref_id: refId,
|
|
461
|
+
timeout_ms: Number(timeout)
|
|
462
|
+
};
|
|
463
|
+
if (field === "selector")
|
|
464
|
+
return { ...base, selector: match };
|
|
465
|
+
if (field === "text")
|
|
466
|
+
return { ...base, text: match };
|
|
467
|
+
return { ...base, url_includes: match };
|
|
468
|
+
}
|
|
251
469
|
if (action === "load_all") {
|
|
252
470
|
const interval = value["interval_ms"] ?? 1500;
|
|
253
471
|
if (!Number.isInteger(interval) || Number(interval) < 0 || Number(interval) > 60000) {
|
|
@@ -401,6 +619,30 @@ function loadBrowserRoutes(path, currentHostname = hostname()) {
|
|
|
401
619
|
return routesFromConfig(readBrowserRouteConfig(path), currentHostname);
|
|
402
620
|
}
|
|
403
621
|
|
|
622
|
+
// src/browser/runtime.ts
|
|
623
|
+
import { randomUUID } from "node:crypto";
|
|
624
|
+
import { join as join5 } from "node:path";
|
|
625
|
+
|
|
626
|
+
// src/cdp/serial.ts
|
|
627
|
+
function waitForTurn(promise, signal) {
|
|
628
|
+
if (!signal)
|
|
629
|
+
return promise;
|
|
630
|
+
if (signal.aborted) {
|
|
631
|
+
return Promise.reject(signal.reason ?? new Error("Operation aborted"));
|
|
632
|
+
}
|
|
633
|
+
return new Promise((resolveValue, reject) => {
|
|
634
|
+
const abort = () => reject(signal.reason ?? new Error("Operation aborted"));
|
|
635
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
636
|
+
promise.then((value) => {
|
|
637
|
+
signal.removeEventListener("abort", abort);
|
|
638
|
+
resolveValue(value);
|
|
639
|
+
}, (error) => {
|
|
640
|
+
signal.removeEventListener("abort", abort);
|
|
641
|
+
reject(error);
|
|
642
|
+
});
|
|
643
|
+
});
|
|
644
|
+
}
|
|
645
|
+
|
|
404
646
|
// src/cdp/discovery.ts
|
|
405
647
|
import { existsSync, readFileSync as readFileSync2 } from "node:fs";
|
|
406
648
|
import http from "node:http";
|
|
@@ -814,6 +1056,11 @@ class CdpClient {
|
|
|
814
1056
|
}
|
|
815
1057
|
}
|
|
816
1058
|
|
|
1059
|
+
// src/cdp/tabs.ts
|
|
1060
|
+
import { createHash } from "node:crypto";
|
|
1061
|
+
import { lstat, mkdir, readdir, rm, utimes, writeFile } from "node:fs/promises";
|
|
1062
|
+
import { join as join2 } from "node:path";
|
|
1063
|
+
|
|
817
1064
|
// src/cdp/pages.ts
|
|
818
1065
|
function pageInfo(value) {
|
|
819
1066
|
const record = asRecord(value, "CDP target");
|
|
@@ -821,16 +1068,20 @@ function pageInfo(value) {
|
|
|
821
1068
|
targetId: asString(record["targetId"], "targetId"),
|
|
822
1069
|
title: typeof record["title"] === "string" ? record["title"] : "",
|
|
823
1070
|
url: asString(record["url"], "target URL"),
|
|
824
|
-
...typeof record["type"] === "string" ? { type: record["type"] } : {}
|
|
1071
|
+
...typeof record["type"] === "string" ? { type: record["type"] } : {},
|
|
1072
|
+
...typeof record["openerId"] === "string" ? { openerId: record["openerId"] } : {}
|
|
825
1073
|
};
|
|
826
1074
|
}
|
|
827
|
-
async function
|
|
1075
|
+
async function getPageTargets(cdp, signal) {
|
|
828
1076
|
const response = asRecord(await cdp.send("Target.getTargets", {}, undefined, signal), "Target.getTargets response");
|
|
829
1077
|
const targetInfos = response["targetInfos"];
|
|
830
1078
|
if (!Array.isArray(targetInfos)) {
|
|
831
1079
|
throw new Error("Target.getTargets response has no targetInfos");
|
|
832
1080
|
}
|
|
833
|
-
return targetInfos.map(pageInfo).filter((target) => target.type === "page"
|
|
1081
|
+
return targetInfos.map(pageInfo).filter((target) => target.type === "page");
|
|
1082
|
+
}
|
|
1083
|
+
function getDisplayedPages(targets) {
|
|
1084
|
+
return targets.filter((target) => !target.url.startsWith("chrome://"));
|
|
834
1085
|
}
|
|
835
1086
|
async function waitForOpenedTarget(cdp, targetId, requestedUrl, timeout = 5000, signal) {
|
|
836
1087
|
if (requestedUrl === "about:blank") {
|
|
@@ -852,26 +1103,6 @@ async function waitForOpenedTarget(cdp, targetId, requestedUrl, timeout = 5000,
|
|
|
852
1103
|
throw new Error(`New tab did not begin navigating to ${requestedUrl}`);
|
|
853
1104
|
}
|
|
854
1105
|
|
|
855
|
-
// src/cdp/serial.ts
|
|
856
|
-
function waitForTurn(promise, signal) {
|
|
857
|
-
if (!signal)
|
|
858
|
-
return promise;
|
|
859
|
-
if (signal.aborted) {
|
|
860
|
-
return Promise.reject(signal.reason ?? new Error("Operation aborted"));
|
|
861
|
-
}
|
|
862
|
-
return new Promise((resolveValue, reject) => {
|
|
863
|
-
const abort = () => reject(signal.reason ?? new Error("Operation aborted"));
|
|
864
|
-
signal.addEventListener("abort", abort, { once: true });
|
|
865
|
-
promise.then((value) => {
|
|
866
|
-
signal.removeEventListener("abort", abort);
|
|
867
|
-
resolveValue(value);
|
|
868
|
-
}, (error) => {
|
|
869
|
-
signal.removeEventListener("abort", abort);
|
|
870
|
-
reject(error);
|
|
871
|
-
});
|
|
872
|
-
});
|
|
873
|
-
}
|
|
874
|
-
|
|
875
1106
|
// src/cdp/url.ts
|
|
876
1107
|
function assertHttpUrl(value) {
|
|
877
1108
|
let parsed;
|
|
@@ -885,6 +1116,203 @@ function assertHttpUrl(value) {
|
|
|
885
1116
|
}
|
|
886
1117
|
}
|
|
887
1118
|
|
|
1119
|
+
// src/cdp/tabs.ts
|
|
1120
|
+
var TARGET_ID = /^[A-Za-z0-9_-]{1,128}$/;
|
|
1121
|
+
var SCOPE_ID = /^[a-f0-9]{64}$/;
|
|
1122
|
+
var SCOPE_TTL_MS = 30 * 24 * 60 * 60 * 1000;
|
|
1123
|
+
var SCOPE_PRUNE_LIMIT = 32;
|
|
1124
|
+
function missing(error) {
|
|
1125
|
+
return error instanceof Error && "code" in error && error.code === "ENOENT";
|
|
1126
|
+
}
|
|
1127
|
+
async function pruneOwnershipScopes(directory, currentScope, now = Date.now()) {
|
|
1128
|
+
let entries;
|
|
1129
|
+
try {
|
|
1130
|
+
entries = await readdir(directory, { withFileTypes: true });
|
|
1131
|
+
} catch (error) {
|
|
1132
|
+
if (missing(error))
|
|
1133
|
+
return;
|
|
1134
|
+
throw error;
|
|
1135
|
+
}
|
|
1136
|
+
const stale = [];
|
|
1137
|
+
for (const entry of entries) {
|
|
1138
|
+
if (entry.name === currentScope || !SCOPE_ID.test(entry.name) || !entry.isDirectory())
|
|
1139
|
+
continue;
|
|
1140
|
+
const path = join2(directory, entry.name);
|
|
1141
|
+
try {
|
|
1142
|
+
const info = await lstat(path);
|
|
1143
|
+
if (info.isDirectory() && !info.isSymbolicLink() && now - info.mtimeMs > SCOPE_TTL_MS) {
|
|
1144
|
+
stale.push({ path, mtimeMs: info.mtimeMs });
|
|
1145
|
+
}
|
|
1146
|
+
} catch (error) {
|
|
1147
|
+
if (!missing(error))
|
|
1148
|
+
throw error;
|
|
1149
|
+
}
|
|
1150
|
+
}
|
|
1151
|
+
stale.sort((left, right) => left.mtimeMs - right.mtimeMs);
|
|
1152
|
+
await Promise.all(stale.slice(0, SCOPE_PRUNE_LIMIT).map((scope) => rm(scope.path, { force: true, recursive: true })));
|
|
1153
|
+
}
|
|
1154
|
+
|
|
1155
|
+
class BrowserTabs {
|
|
1156
|
+
cdp;
|
|
1157
|
+
directory;
|
|
1158
|
+
ownershipDirectory;
|
|
1159
|
+
scope;
|
|
1160
|
+
tail = Promise.resolve();
|
|
1161
|
+
closed = false;
|
|
1162
|
+
prepared = false;
|
|
1163
|
+
constructor(cdp, ownerId, directory, browserUrl) {
|
|
1164
|
+
this.cdp = cdp;
|
|
1165
|
+
this.ownershipDirectory = directory;
|
|
1166
|
+
this.scope = createHash("sha256").update(`${browserUrl}\x00${ownerId}`).digest("hex");
|
|
1167
|
+
this.directory = join2(directory, this.scope);
|
|
1168
|
+
}
|
|
1169
|
+
list(signal) {
|
|
1170
|
+
return this.enqueue(() => this.listNow(signal), signal);
|
|
1171
|
+
}
|
|
1172
|
+
async shutdown() {
|
|
1173
|
+
this.closed = true;
|
|
1174
|
+
await this.tail;
|
|
1175
|
+
}
|
|
1176
|
+
enqueue(action, signal) {
|
|
1177
|
+
const pending = this.tail.then(async () => {
|
|
1178
|
+
signal?.throwIfAborted();
|
|
1179
|
+
if (this.closed)
|
|
1180
|
+
throw new Error("Browser session closed");
|
|
1181
|
+
if (!this.prepared) {
|
|
1182
|
+
await this.touchDirectory();
|
|
1183
|
+
await pruneOwnershipScopes(this.ownershipDirectory, this.scope);
|
|
1184
|
+
this.prepared = true;
|
|
1185
|
+
}
|
|
1186
|
+
return action();
|
|
1187
|
+
});
|
|
1188
|
+
this.tail = pending.then(() => {
|
|
1189
|
+
return;
|
|
1190
|
+
}, () => {
|
|
1191
|
+
return;
|
|
1192
|
+
});
|
|
1193
|
+
return waitForTurn(pending, signal);
|
|
1194
|
+
}
|
|
1195
|
+
async listNow(signal) {
|
|
1196
|
+
const owned = await this.readOwned();
|
|
1197
|
+
const targets = await getPageTargets(this.cdp, signal);
|
|
1198
|
+
const pages = getDisplayedPages(targets);
|
|
1199
|
+
const known = new Set(owned);
|
|
1200
|
+
let changed = true;
|
|
1201
|
+
while (changed) {
|
|
1202
|
+
changed = false;
|
|
1203
|
+
for (const page of pages) {
|
|
1204
|
+
if (!page.openerId || !known.has(page.openerId) || known.has(page.targetId))
|
|
1205
|
+
continue;
|
|
1206
|
+
await this.remember(page.targetId);
|
|
1207
|
+
known.add(page.targetId);
|
|
1208
|
+
changed = true;
|
|
1209
|
+
}
|
|
1210
|
+
}
|
|
1211
|
+
const live = new Set(targets.map((page) => page.targetId));
|
|
1212
|
+
await Promise.all(owned.filter((id) => !live.has(id)).map((id) => this.forget(id)));
|
|
1213
|
+
return pages.map((page) => ({ ...page, owned: known.has(page.targetId) }));
|
|
1214
|
+
}
|
|
1215
|
+
async resolve(refId, signal) {
|
|
1216
|
+
const pages = await this.list(signal);
|
|
1217
|
+
const ids = pages.map((page) => page.targetId);
|
|
1218
|
+
const targetId = resolvePrefix(refId, ids, "target", "Run tabs.");
|
|
1219
|
+
const page = pages.find((candidate) => candidate.targetId === targetId);
|
|
1220
|
+
if (!page)
|
|
1221
|
+
throw new Error("Tab disappeared; run tabs again");
|
|
1222
|
+
return { page, refId: targetId.slice(0, getDisplayPrefixLength(ids)) };
|
|
1223
|
+
}
|
|
1224
|
+
async open(url, signal) {
|
|
1225
|
+
assertHttpUrl(url);
|
|
1226
|
+
const targetId = await this.enqueue(async () => {
|
|
1227
|
+
let response;
|
|
1228
|
+
try {
|
|
1229
|
+
response = asRecord(await this.cdp.send("Target.createTarget", { url, background: true }), "Target.createTarget response");
|
|
1230
|
+
} catch (error) {
|
|
1231
|
+
throw new Error(`Chrome did not confirm tab creation; a shared tab may exist. Run tabs before retrying: ${errorMessage(error)}`);
|
|
1232
|
+
}
|
|
1233
|
+
if (typeof response["targetId"] !== "string")
|
|
1234
|
+
throw new Error("Chrome did not return a new tab target; run tabs before retrying");
|
|
1235
|
+
const created = response["targetId"];
|
|
1236
|
+
try {
|
|
1237
|
+
await this.remember(created);
|
|
1238
|
+
} catch (error) {
|
|
1239
|
+
throw new Error(`Opened tab ${created} but could not save ownership; it remains shared: ${errorMessage(error)}`);
|
|
1240
|
+
}
|
|
1241
|
+
return created;
|
|
1242
|
+
}, signal);
|
|
1243
|
+
await waitForOpenedTarget(this.cdp, targetId, url, 5000, signal);
|
|
1244
|
+
const { refId } = await this.resolve(targetId, signal);
|
|
1245
|
+
return { refId };
|
|
1246
|
+
}
|
|
1247
|
+
async show(refId, signal) {
|
|
1248
|
+
const resolved = await this.resolve(refId, signal);
|
|
1249
|
+
await this.cdp.send("Target.activateTarget", { targetId: resolved.page.targetId }, undefined, signal);
|
|
1250
|
+
return resolved.refId;
|
|
1251
|
+
}
|
|
1252
|
+
async close(refId, signal) {
|
|
1253
|
+
const resolved = await this.resolve(refId, signal);
|
|
1254
|
+
const targetId = resolved.page.targetId;
|
|
1255
|
+
const response = asRecord(await this.cdp.send("Target.closeTarget", { targetId }, undefined, signal), "Target.closeTarget response");
|
|
1256
|
+
if (response["success"] !== true)
|
|
1257
|
+
throw new Error("Chrome did not close the tab; run tabs to inspect it");
|
|
1258
|
+
await this.forget(targetId);
|
|
1259
|
+
return { targetId, refId: resolved.refId };
|
|
1260
|
+
}
|
|
1261
|
+
targetPath(targetId) {
|
|
1262
|
+
if (!TARGET_ID.test(targetId))
|
|
1263
|
+
throw new Error("Chrome returned an invalid target id");
|
|
1264
|
+
return join2(this.directory, targetId);
|
|
1265
|
+
}
|
|
1266
|
+
async readOwned() {
|
|
1267
|
+
if (!await this.touchDirectory())
|
|
1268
|
+
return [];
|
|
1269
|
+
try {
|
|
1270
|
+
const files = await readdir(this.directory, { withFileTypes: true });
|
|
1271
|
+
for (const file of files) {
|
|
1272
|
+
if (!file.isFile() || !TARGET_ID.test(file.name))
|
|
1273
|
+
throw new Error("Invalid browser ownership record; refusing to infer tab ownership");
|
|
1274
|
+
}
|
|
1275
|
+
return files.map((file) => file.name);
|
|
1276
|
+
} catch (error) {
|
|
1277
|
+
if (missing(error))
|
|
1278
|
+
return [];
|
|
1279
|
+
throw error;
|
|
1280
|
+
}
|
|
1281
|
+
}
|
|
1282
|
+
async touchDirectory() {
|
|
1283
|
+
try {
|
|
1284
|
+
const info = await lstat(this.directory);
|
|
1285
|
+
if (!info.isDirectory() || info.isSymbolicLink())
|
|
1286
|
+
throw new Error("Invalid browser ownership directory");
|
|
1287
|
+
const now = new Date;
|
|
1288
|
+
await utimes(this.directory, now, now);
|
|
1289
|
+
return true;
|
|
1290
|
+
} catch (error) {
|
|
1291
|
+
if (missing(error))
|
|
1292
|
+
return false;
|
|
1293
|
+
throw error;
|
|
1294
|
+
}
|
|
1295
|
+
}
|
|
1296
|
+
async remember(targetId) {
|
|
1297
|
+
const path = this.targetPath(targetId);
|
|
1298
|
+
await mkdir(this.directory, { recursive: true, mode: 448 });
|
|
1299
|
+
const info = await lstat(this.directory);
|
|
1300
|
+
if (!info.isDirectory() || info.isSymbolicLink())
|
|
1301
|
+
throw new Error("Invalid browser ownership directory");
|
|
1302
|
+
try {
|
|
1303
|
+
await writeFile(path, "", { flag: "wx", mode: 384 });
|
|
1304
|
+
} catch (error) {
|
|
1305
|
+
if (!(error instanceof Error && ("code" in error) && error.code === "EEXIST"))
|
|
1306
|
+
throw error;
|
|
1307
|
+
if (!(await lstat(path)).isFile())
|
|
1308
|
+
throw new Error("Invalid browser ownership record");
|
|
1309
|
+
}
|
|
1310
|
+
}
|
|
1311
|
+
async forget(targetId) {
|
|
1312
|
+
await rm(this.targetPath(targetId), { force: true });
|
|
1313
|
+
}
|
|
1314
|
+
}
|
|
1315
|
+
|
|
888
1316
|
// src/cdp/session.ts
|
|
889
1317
|
var TAB_IDLE_MS = 20 * 60 * 1000;
|
|
890
1318
|
|
|
@@ -896,6 +1324,7 @@ class TabBridge {
|
|
|
896
1324
|
tail = Promise.resolve();
|
|
897
1325
|
idleTimer;
|
|
898
1326
|
closed = false;
|
|
1327
|
+
backgroundRendering = false;
|
|
899
1328
|
onClose;
|
|
900
1329
|
constructor(targetId, cdp, sessionId, onClose) {
|
|
901
1330
|
this.targetId = targetId;
|
|
@@ -953,6 +1382,13 @@ class TabBridge {
|
|
|
953
1382
|
release();
|
|
954
1383
|
}
|
|
955
1384
|
}
|
|
1385
|
+
async setBackgroundRendering(enabled, signal) {
|
|
1386
|
+
if (this.backgroundRendering === enabled)
|
|
1387
|
+
return;
|
|
1388
|
+
this.backgroundRendering = undefined;
|
|
1389
|
+
await this.cdp.send("Emulation.setFocusEmulationEnabled", { enabled }, this.sessionId, signal);
|
|
1390
|
+
this.backgroundRendering = enabled;
|
|
1391
|
+
}
|
|
956
1392
|
close(detach = true) {
|
|
957
1393
|
if (this.closed)
|
|
958
1394
|
return;
|
|
@@ -978,29 +1414,36 @@ class TabBridge {
|
|
|
978
1414
|
}
|
|
979
1415
|
|
|
980
1416
|
class BrowserCdpSession {
|
|
1417
|
+
closing;
|
|
981
1418
|
root;
|
|
982
1419
|
rootPending;
|
|
1420
|
+
ownerId;
|
|
1421
|
+
ownershipDirectory;
|
|
983
1422
|
tabs = new Map;
|
|
984
1423
|
tabPromises = new Map;
|
|
1424
|
+
constructor(ownerId, ownershipDirectory) {
|
|
1425
|
+
this.ownerId = ownerId;
|
|
1426
|
+
this.ownershipDirectory = ownershipDirectory;
|
|
1427
|
+
}
|
|
985
1428
|
async pages(signal) {
|
|
986
|
-
return
|
|
1429
|
+
return (await this.rootConnection(signal)).tabs.list(signal);
|
|
987
1430
|
}
|
|
988
1431
|
async open(url, signal) {
|
|
989
|
-
|
|
1432
|
+
return (await this.rootConnection(signal)).tabs.open(url, signal);
|
|
1433
|
+
}
|
|
1434
|
+
async show(refId, signal) {
|
|
1435
|
+
return (await this.rootConnection(signal)).tabs.show(refId, signal);
|
|
1436
|
+
}
|
|
1437
|
+
async closeTab(refId, signal) {
|
|
990
1438
|
const root = await this.rootConnection(signal);
|
|
991
|
-
const
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
const
|
|
996
|
-
const
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
}
|
|
1000
|
-
const prefixLength = getDisplayPrefixLength(pages.map((candidate) => candidate.targetId));
|
|
1001
|
-
return {
|
|
1002
|
-
refId: page.targetId.slice(0, prefixLength)
|
|
1003
|
-
};
|
|
1439
|
+
const resolved = await root.tabs.resolve(refId, signal);
|
|
1440
|
+
const targetId = resolved.page.targetId;
|
|
1441
|
+
this.stopPendingTab(targetId, "Tab is closing");
|
|
1442
|
+
const bridge = this.tabs.get(targetId);
|
|
1443
|
+
const close = () => root.tabs.close(targetId, signal);
|
|
1444
|
+
const closed = bridge ? await bridge.run(resolved.refId, signal, close) : await close();
|
|
1445
|
+
bridge?.close(false);
|
|
1446
|
+
return closed.refId;
|
|
1004
1447
|
}
|
|
1005
1448
|
async withTab(refId, signal, action) {
|
|
1006
1449
|
const pages = await this.pages(signal);
|
|
@@ -1036,12 +1479,17 @@ class BrowserCdpSession {
|
|
|
1036
1479
|
}
|
|
1037
1480
|
}
|
|
1038
1481
|
const prefixLength = getDisplayPrefixLength(pages.map((page) => page.targetId));
|
|
1039
|
-
|
|
1482
|
+
const owned = pages.some((page) => page.targetId === targetId && page.owned === true);
|
|
1483
|
+
const current = bridge;
|
|
1484
|
+
return current.run(targetId.slice(0, prefixLength), signal, async (tab) => {
|
|
1485
|
+
await current.setBackgroundRendering(owned, signal);
|
|
1486
|
+
return action(tab);
|
|
1487
|
+
});
|
|
1040
1488
|
}
|
|
1041
1489
|
async stop(refId) {
|
|
1042
1490
|
if (!refId) {
|
|
1043
|
-
for (const
|
|
1044
|
-
this.stopPendingTab(
|
|
1491
|
+
for (const targetId of this.tabPromises.keys()) {
|
|
1492
|
+
this.stopPendingTab(targetId, "All tab bridges were stopped");
|
|
1045
1493
|
}
|
|
1046
1494
|
for (const bridge of this.tabs.values())
|
|
1047
1495
|
bridge.close();
|
|
@@ -1055,6 +1503,8 @@ class BrowserCdpSession {
|
|
|
1055
1503
|
this.tabs.delete(targetId);
|
|
1056
1504
|
}
|
|
1057
1505
|
close() {
|
|
1506
|
+
if (this.closing)
|
|
1507
|
+
return this.closing;
|
|
1058
1508
|
for (const targetId of this.tabPromises.keys()) {
|
|
1059
1509
|
this.stopPendingTab(targetId, "Browser session closed");
|
|
1060
1510
|
}
|
|
@@ -1063,16 +1513,28 @@ class BrowserCdpSession {
|
|
|
1063
1513
|
this.tabs.clear();
|
|
1064
1514
|
const rootPending = this.rootPending;
|
|
1065
1515
|
this.rootPending = undefined;
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1516
|
+
rootPending?.controller.abort(new Error("Browser session closed"));
|
|
1517
|
+
const root = this.root;
|
|
1518
|
+
this.root = undefined;
|
|
1519
|
+
this.closing = (async () => {
|
|
1520
|
+
const connected = await rootPending?.promise.catch(() => {
|
|
1069
1521
|
return;
|
|
1070
1522
|
});
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1523
|
+
for (const connection of new Set([root, connected])) {
|
|
1524
|
+
if (!connection)
|
|
1525
|
+
continue;
|
|
1526
|
+
try {
|
|
1527
|
+
await connection.tabs.shutdown();
|
|
1528
|
+
} finally {
|
|
1529
|
+
connection.cdp.close();
|
|
1530
|
+
}
|
|
1531
|
+
}
|
|
1532
|
+
})();
|
|
1533
|
+
return this.closing;
|
|
1074
1534
|
}
|
|
1075
1535
|
async rootConnection(signal) {
|
|
1536
|
+
if (this.closing)
|
|
1537
|
+
throw new Error("Browser session closed");
|
|
1076
1538
|
if (this.root)
|
|
1077
1539
|
return this.root;
|
|
1078
1540
|
let pending = this.rootPending;
|
|
@@ -1117,50 +1579,63 @@ class BrowserCdpSession {
|
|
|
1117
1579
|
}
|
|
1118
1580
|
async connectRoot(signal) {
|
|
1119
1581
|
const client = new CdpClient;
|
|
1120
|
-
|
|
1121
|
-
|
|
1582
|
+
const url = await getWebSocketUrl();
|
|
1583
|
+
try {
|
|
1584
|
+
await client.connect(url, signal);
|
|
1585
|
+
signal.throwIfAborted();
|
|
1586
|
+
if (this.closing)
|
|
1587
|
+
throw new Error("Browser session closed");
|
|
1588
|
+
} catch (error) {
|
|
1589
|
+
client.close();
|
|
1590
|
+
throw error;
|
|
1591
|
+
}
|
|
1592
|
+
const connection = {
|
|
1593
|
+
cdp: client,
|
|
1594
|
+
tabs: new BrowserTabs(client, this.ownerId, this.ownershipDirectory, url)
|
|
1595
|
+
};
|
|
1596
|
+
this.root = connection;
|
|
1122
1597
|
client.onClose(() => {
|
|
1123
|
-
if (this.root !==
|
|
1598
|
+
if (this.root !== connection)
|
|
1124
1599
|
return;
|
|
1125
1600
|
this.root = undefined;
|
|
1126
1601
|
});
|
|
1127
|
-
return
|
|
1602
|
+
return connection;
|
|
1128
1603
|
}
|
|
1129
1604
|
}
|
|
1130
1605
|
|
|
1131
1606
|
// src/browser/artifacts.ts
|
|
1132
1607
|
import {
|
|
1133
|
-
mkdir,
|
|
1134
|
-
readdir,
|
|
1608
|
+
mkdir as mkdir2,
|
|
1609
|
+
readdir as readdir2,
|
|
1135
1610
|
readFile,
|
|
1136
|
-
rm,
|
|
1611
|
+
rm as rm2,
|
|
1137
1612
|
stat,
|
|
1138
|
-
writeFile
|
|
1613
|
+
writeFile as writeFile2
|
|
1139
1614
|
} from "node:fs/promises";
|
|
1140
1615
|
import { tmpdir } from "node:os";
|
|
1141
|
-
import { join as
|
|
1616
|
+
import { join as join3 } from "node:path";
|
|
1142
1617
|
var RESULT_TTL_MS = 60 * 60 * 1000;
|
|
1143
1618
|
var SCREENSHOT_TTL_MS = 24 * 60 * 60 * 1000;
|
|
1144
1619
|
var TEXT_BUDGET_BYTES = 32000;
|
|
1145
1620
|
function artifactDirectory() {
|
|
1146
|
-
return process.env["XDG_RUNTIME_DIR"] ?
|
|
1621
|
+
return process.env["XDG_RUNTIME_DIR"] ? join3(process.env["XDG_RUNTIME_DIR"], "browser-tool") : join3(tmpdir(), `browser-tool-${process.getuid?.() ?? "user"}`);
|
|
1147
1622
|
}
|
|
1148
1623
|
function resultPath(handle) {
|
|
1149
|
-
return
|
|
1624
|
+
return join3(artifactDirectory(), `result-${handle}.txt`);
|
|
1150
1625
|
}
|
|
1151
1626
|
async function screenshotPath(request) {
|
|
1152
|
-
await
|
|
1627
|
+
await mkdir2(artifactDirectory(), {
|
|
1153
1628
|
recursive: true,
|
|
1154
1629
|
mode: 448
|
|
1155
1630
|
});
|
|
1156
1631
|
const suffix = request.id !== undefined ? `-element-${request.id}` : request.selector ? "-element" : "";
|
|
1157
1632
|
const safeRef = request.ref_id.slice(0, 12).replace(/[^A-Za-z0-9_-]/g, "_");
|
|
1158
|
-
return
|
|
1633
|
+
return join3(artifactDirectory(), `browser-${safeRef}${suffix}-${crypto.randomUUID()}.png`);
|
|
1159
1634
|
}
|
|
1160
1635
|
async function pruneArtifacts(now = Date.now()) {
|
|
1161
1636
|
let names;
|
|
1162
1637
|
try {
|
|
1163
|
-
names = await
|
|
1638
|
+
names = await readdir2(artifactDirectory());
|
|
1164
1639
|
} catch (error) {
|
|
1165
1640
|
if (error && typeof error === "object" && "code" in error && error.code === "ENOENT") {
|
|
1166
1641
|
return 0;
|
|
@@ -1169,11 +1644,11 @@ async function pruneArtifacts(now = Date.now()) {
|
|
|
1169
1644
|
}
|
|
1170
1645
|
let removed = 0;
|
|
1171
1646
|
for (const name of names.filter((candidate) => /^(?:result-[a-f0-9-]{36}\.txt|browser-.*\.png)$/.test(candidate))) {
|
|
1172
|
-
const path =
|
|
1647
|
+
const path = join3(artifactDirectory(), name);
|
|
1173
1648
|
try {
|
|
1174
1649
|
const maxAge = name.startsWith("result-") ? RESULT_TTL_MS : SCREENSHOT_TTL_MS;
|
|
1175
1650
|
if (now - (await stat(path)).mtimeMs > maxAge) {
|
|
1176
|
-
await
|
|
1651
|
+
await rm2(path, { force: true });
|
|
1177
1652
|
removed++;
|
|
1178
1653
|
}
|
|
1179
1654
|
} catch (error) {
|
|
@@ -1184,25 +1659,25 @@ async function pruneArtifacts(now = Date.now()) {
|
|
|
1184
1659
|
}
|
|
1185
1660
|
return removed;
|
|
1186
1661
|
}
|
|
1187
|
-
function chunkForJson(value,
|
|
1662
|
+
function chunkForJson(value, offset = 0, budget = TEXT_BUDGET_BYTES) {
|
|
1188
1663
|
let bytes = 2;
|
|
1189
|
-
let end =
|
|
1190
|
-
for (const character of value.slice(
|
|
1664
|
+
let end = offset;
|
|
1665
|
+
for (const character of value.slice(offset)) {
|
|
1191
1666
|
const next = Buffer.byteLength(JSON.stringify(character)) - 2;
|
|
1192
1667
|
if (bytes + next > budget)
|
|
1193
1668
|
break;
|
|
1194
1669
|
bytes += next;
|
|
1195
1670
|
end += character.length;
|
|
1196
1671
|
}
|
|
1197
|
-
return { text: value.slice(
|
|
1672
|
+
return { text: value.slice(offset, end), end };
|
|
1198
1673
|
}
|
|
1199
1674
|
async function cacheResult(value) {
|
|
1200
1675
|
const handle = crypto.randomUUID();
|
|
1201
|
-
await
|
|
1676
|
+
await mkdir2(artifactDirectory(), {
|
|
1202
1677
|
recursive: true,
|
|
1203
1678
|
mode: 448
|
|
1204
1679
|
});
|
|
1205
|
-
await
|
|
1680
|
+
await writeFile2(resultPath(handle), value, { mode: 384 });
|
|
1206
1681
|
return handle;
|
|
1207
1682
|
}
|
|
1208
1683
|
async function limitedText(base, field, value) {
|
|
@@ -1235,7 +1710,7 @@ async function readCachedResult(request) {
|
|
|
1235
1710
|
const chunk = chunkForJson(value, request.offset);
|
|
1236
1711
|
const complete = chunk.end >= value.length;
|
|
1237
1712
|
if (complete) {
|
|
1238
|
-
await
|
|
1713
|
+
await rm2(resultPath(request.handle), { force: true });
|
|
1239
1714
|
}
|
|
1240
1715
|
return {
|
|
1241
1716
|
handle: request.handle,
|
|
@@ -1246,7 +1721,7 @@ async function readCachedResult(request) {
|
|
|
1246
1721
|
};
|
|
1247
1722
|
}
|
|
1248
1723
|
async function discardCachedResult(handle) {
|
|
1249
|
-
await
|
|
1724
|
+
await rm2(resultPath(handle), { force: true });
|
|
1250
1725
|
return { discarded: handle };
|
|
1251
1726
|
}
|
|
1252
1727
|
|
|
@@ -1254,19 +1729,24 @@ async function discardCachedResult(handle) {
|
|
|
1254
1729
|
function browserHelp(hosts = []) {
|
|
1255
1730
|
const routed = hosts.length > 0;
|
|
1256
1731
|
return {
|
|
1257
|
-
input: "Code
|
|
1732
|
+
input: "Request={action,...fields}; Code/Notebook: JSON.stringify(request), JSON.parse(result)",
|
|
1258
1733
|
...routed ? {
|
|
1259
1734
|
host: `${hosts.join("|")} optional; keep a user-named host on every call and its refs/handles`
|
|
1260
1735
|
} : {},
|
|
1261
1736
|
refs: "tabs -> open; keep ref_id/id/cursors with their result",
|
|
1262
1737
|
safety: "Ask before unfamiliar low-trust navigation or consequential action unless authorized; never close shared browser",
|
|
1263
|
-
batch: "
|
|
1738
|
+
batch: "Code/Notebook: {action_name:[{...fields}],...}; nonempty arrays; items omit action; host/response_length at request root; independent only",
|
|
1264
1739
|
actions: {
|
|
1265
|
-
tabs: "query? offset? -> ref_id title url",
|
|
1266
|
-
open: "ref_id lineno?
|
|
1267
|
-
|
|
1740
|
+
tabs: "query? offset? owned_only? -> ref_id title url owned",
|
|
1741
|
+
open: "ref_id lineno? | url; new tabs open in background",
|
|
1742
|
+
show: "ref_id; bring tab to foreground",
|
|
1743
|
+
close: "ref_id",
|
|
1744
|
+
find: "ref_id pattern lineno?",
|
|
1268
1745
|
click: "ref_id id|selector|x+y",
|
|
1269
1746
|
type: "ref_id text id?; id focuses",
|
|
1747
|
+
fill: "ref_id id|selector value; replace/clear text, select option value/label, boolean checks/unchecks",
|
|
1748
|
+
press: "ref_id key; focused element, e.g. Enter or Control+a",
|
|
1749
|
+
wait: "ref_id selector|text|url_includes timeout_ms?; DOM presence or substring, default 10000ms",
|
|
1270
1750
|
screenshot: "ref_id id?|selector? -> file",
|
|
1271
1751
|
navigate: "ref_id url",
|
|
1272
1752
|
html: "ref_id id?|selector?",
|
|
@@ -1275,7 +1755,7 @@ function browserHelp(hosts = []) {
|
|
|
1275
1755
|
load_all: "ref_id selector interval_ms?",
|
|
1276
1756
|
raw: "ref_id method params?",
|
|
1277
1757
|
start: "",
|
|
1278
|
-
stop: "ref_id
|
|
1758
|
+
stop: "ref_id?; detach without closing tabs",
|
|
1279
1759
|
read_result: "handle offset",
|
|
1280
1760
|
discard_result: "handle"
|
|
1281
1761
|
},
|
|
@@ -1349,6 +1829,10 @@ async function backendCenter(cdp, sessionId, backendNodeId, scroll = true, signa
|
|
|
1349
1829
|
const response = await withBackendObject(cdp, sessionId, backendNodeId, (objectId) => cdp.send("Runtime.callFunctionOn", {
|
|
1350
1830
|
objectId,
|
|
1351
1831
|
functionDeclaration: `function() {
|
|
1832
|
+
const view = this.ownerDocument.defaultView;
|
|
1833
|
+
if (view && (view.innerWidth <= 0 || view.innerHeight <= 0)) {
|
|
1834
|
+
return { ok: false, error: 'Browser viewport is ' + view.innerWidth + 'x' + view.innerHeight + '; restore or resize its window, then retry' };
|
|
1835
|
+
}
|
|
1352
1836
|
const rect = this.getBoundingClientRect();
|
|
1353
1837
|
const style = getComputedStyle(this);
|
|
1354
1838
|
const disabled = this.matches(':disabled') ||
|
|
@@ -1519,6 +2003,156 @@ async function clickCoordinates(cdp, sessionId, x, y, signal) {
|
|
|
1519
2003
|
return `Clicked at CSS (${x}, ${y})`;
|
|
1520
2004
|
}
|
|
1521
2005
|
|
|
2006
|
+
// src/cdp/actions/fill.ts
|
|
2007
|
+
function prepareFill(value) {
|
|
2008
|
+
if (!this.isConnected)
|
|
2009
|
+
throw new Error("Element detached; run open again");
|
|
2010
|
+
if (this.matches(":disabled") || this.getAttribute("aria-disabled") === "true" || this.closest("[inert]")) {
|
|
2011
|
+
throw new Error("Element is disabled or inert");
|
|
2012
|
+
}
|
|
2013
|
+
const input = this instanceof HTMLInputElement;
|
|
2014
|
+
const textarea = this instanceof HTMLTextAreaElement;
|
|
2015
|
+
const select = this instanceof HTMLSelectElement;
|
|
2016
|
+
if ((input || textarea) && this.readOnly)
|
|
2017
|
+
throw new Error("Element is read-only");
|
|
2018
|
+
const toggle = input && (this.type === "checkbox" || this.type === "radio");
|
|
2019
|
+
if (toggle) {
|
|
2020
|
+
if (typeof value !== "boolean")
|
|
2021
|
+
throw new Error("Checkbox/radio requires a boolean value");
|
|
2022
|
+
if (this.type === "radio" && !value && this.checked) {
|
|
2023
|
+
throw new Error("Select another radio option with value true instead of unchecking this one");
|
|
2024
|
+
}
|
|
2025
|
+
const indeterminate = this.type === "checkbox" && this.indeterminate;
|
|
2026
|
+
if (indeterminate && this.checked === value) {
|
|
2027
|
+
const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "checked")?.set;
|
|
2028
|
+
if (!setter)
|
|
2029
|
+
throw new Error("Checkbox has no native checked setter");
|
|
2030
|
+
setter.call(this, !value);
|
|
2031
|
+
}
|
|
2032
|
+
return {
|
|
2033
|
+
kind: "checked",
|
|
2034
|
+
expected: value,
|
|
2035
|
+
needsClick: this.checked !== value || indeterminate
|
|
2036
|
+
};
|
|
2037
|
+
}
|
|
2038
|
+
if (typeof value !== "string")
|
|
2039
|
+
throw new Error("Text fields and selects require a string value");
|
|
2040
|
+
if (input && ![
|
|
2041
|
+
"text",
|
|
2042
|
+
"search",
|
|
2043
|
+
"email",
|
|
2044
|
+
"url",
|
|
2045
|
+
"tel",
|
|
2046
|
+
"password",
|
|
2047
|
+
"number",
|
|
2048
|
+
"date",
|
|
2049
|
+
"time",
|
|
2050
|
+
"datetime-local",
|
|
2051
|
+
"month",
|
|
2052
|
+
"week"
|
|
2053
|
+
].includes(this.type)) {
|
|
2054
|
+
throw new Error(`Input type ${this.type} does not support fill`);
|
|
2055
|
+
}
|
|
2056
|
+
if (!input && !textarea && !select && !this.isContentEditable) {
|
|
2057
|
+
throw new Error("Element is not an editable form control");
|
|
2058
|
+
}
|
|
2059
|
+
let replacement = value;
|
|
2060
|
+
if (select) {
|
|
2061
|
+
if (this.multiple)
|
|
2062
|
+
throw new Error("fill requires a single-select control");
|
|
2063
|
+
const options = Array.from(this.options);
|
|
2064
|
+
const byValue = options.filter((option) => option.value === value);
|
|
2065
|
+
const matches = byValue.length ? byValue : options.filter((option) => option.label.trim() === value);
|
|
2066
|
+
const option = matches[0];
|
|
2067
|
+
if (matches.length !== 1 || !option)
|
|
2068
|
+
throw new Error("Option value/label must match exactly one option");
|
|
2069
|
+
if (option.matches(":disabled"))
|
|
2070
|
+
throw new Error("Option is disabled");
|
|
2071
|
+
replacement = option.value;
|
|
2072
|
+
}
|
|
2073
|
+
this.focus({ preventScroll: true });
|
|
2074
|
+
const root = this.getRootNode();
|
|
2075
|
+
if (!this.isConnected || root.activeElement !== this) {
|
|
2076
|
+
throw new Error("Could not focus element; fill was not sent");
|
|
2077
|
+
}
|
|
2078
|
+
if (!input && !textarea && !select) {
|
|
2079
|
+
const selection = this.ownerDocument.getSelection();
|
|
2080
|
+
if (!selection)
|
|
2081
|
+
throw new Error("Could not select editable text");
|
|
2082
|
+
const range = this.ownerDocument.createRange();
|
|
2083
|
+
range.selectNodeContents(this);
|
|
2084
|
+
selection.removeAllRanges();
|
|
2085
|
+
selection.addRange(range);
|
|
2086
|
+
return { kind: "contenteditable", expected: value };
|
|
2087
|
+
}
|
|
2088
|
+
const prototype = input ? HTMLInputElement.prototype : textarea ? HTMLTextAreaElement.prototype : HTMLSelectElement.prototype;
|
|
2089
|
+
const setter = Object.getOwnPropertyDescriptor(prototype, "value")?.set;
|
|
2090
|
+
if (!setter)
|
|
2091
|
+
throw new Error("Form control has no native value setter");
|
|
2092
|
+
if (input || textarea) {
|
|
2093
|
+
const probe = this.cloneNode(false);
|
|
2094
|
+
setter.call(probe, replacement);
|
|
2095
|
+
if (probe.value !== replacement)
|
|
2096
|
+
throw new Error("Value is not accepted by this control; fill was not sent");
|
|
2097
|
+
}
|
|
2098
|
+
setter.call(this, replacement);
|
|
2099
|
+
this.dispatchEvent(new Event("input", { bubbles: true, composed: true }));
|
|
2100
|
+
this.dispatchEvent(new Event("change", { bubbles: true }));
|
|
2101
|
+
return { kind: "value", expected: replacement };
|
|
2102
|
+
}
|
|
2103
|
+
async function callElement(cdp, sessionId, objectId, declaration, value, signal) {
|
|
2104
|
+
const response = asRecord(await cdp.send("Runtime.callFunctionOn", {
|
|
2105
|
+
objectId,
|
|
2106
|
+
functionDeclaration: declaration,
|
|
2107
|
+
arguments: [{ value }],
|
|
2108
|
+
returnByValue: true
|
|
2109
|
+
}, sessionId, signal));
|
|
2110
|
+
if (response["exceptionDetails"]) {
|
|
2111
|
+
const details = asRecord(response["exceptionDetails"]);
|
|
2112
|
+
const exception = details["exception"] ? asRecord(details["exception"]) : {};
|
|
2113
|
+
throw new Error(typeof exception["description"] === "string" ? exception["description"] : "Fill failed; run open to inspect the control before retrying");
|
|
2114
|
+
}
|
|
2115
|
+
return asRecord(asRecord(response["result"])["value"], "fill result");
|
|
2116
|
+
}
|
|
2117
|
+
async function fillElement(cdp, sessionId, elementRefs, target, value, signal) {
|
|
2118
|
+
const backendNodeId = target.id !== undefined ? requireElementRef(elementRefs, target.id).backendNodeId : await selectorBackendNode(cdp, sessionId, target.selector, signal);
|
|
2119
|
+
await backendCenter(cdp, sessionId, backendNodeId, true, signal);
|
|
2120
|
+
return withBackendObject(cdp, sessionId, backendNodeId, async (objectId) => {
|
|
2121
|
+
const prepared = await callElement(cdp, sessionId, objectId, prepareFill.toString(), value, signal);
|
|
2122
|
+
if (prepared["kind"] === "checked" && prepared["needsClick"] === true) {
|
|
2123
|
+
await clickBackendNode(cdp, sessionId, backendNodeId, signal);
|
|
2124
|
+
} else if (prepared["kind"] === "contenteditable") {
|
|
2125
|
+
const focused = await callElement(cdp, sessionId, objectId, `function() {
|
|
2126
|
+
const selection = this.ownerDocument.getSelection();
|
|
2127
|
+
return { ok: this.isConnected && this.getRootNode().activeElement === this &&
|
|
2128
|
+
selection && this.contains(selection.anchorNode) && this.contains(selection.focusNode) };
|
|
2129
|
+
}`, null, signal);
|
|
2130
|
+
if (focused["ok"] !== true)
|
|
2131
|
+
throw new Error("Focus or selection changed; fill was not sent");
|
|
2132
|
+
if (value === "")
|
|
2133
|
+
await pressKey(cdp, sessionId, "Backspace", signal);
|
|
2134
|
+
else
|
|
2135
|
+
await cdp.send("Input.insertText", { text: value }, sessionId, signal);
|
|
2136
|
+
}
|
|
2137
|
+
const verified = await callElement(cdp, sessionId, objectId, `function(expected) {
|
|
2138
|
+
if (!this.isConnected) return { ok: false };
|
|
2139
|
+
const toggle = this instanceof HTMLInputElement && (this.type === 'checkbox' || this.type === 'radio');
|
|
2140
|
+
// Editable DOM has no value property. Native editing introduces NBSPs
|
|
2141
|
+
// and block/BR nodes, so compare equivalent rendered text, not markup.
|
|
2142
|
+
if (this.isContentEditable) {
|
|
2143
|
+
const normalize = text => text.replace(/\\s+/g, ' ').trim();
|
|
2144
|
+
return { ok: normalize(this.innerText) === normalize(expected) };
|
|
2145
|
+
}
|
|
2146
|
+
const actual = toggle ? this.checked : this.value;
|
|
2147
|
+
return { ok: actual === expected && (!toggle || !this.indeterminate) };
|
|
2148
|
+
}`, prepared["expected"], signal);
|
|
2149
|
+
if (verified["ok"] !== true) {
|
|
2150
|
+
throw new Error("Fill did not retain the requested value; run open to inspect the control before retrying");
|
|
2151
|
+
}
|
|
2152
|
+
return target.id === undefined ? "Filled selected element" : `Filled element ${target.id}`;
|
|
2153
|
+
}, signal);
|
|
2154
|
+
}
|
|
2155
|
+
|
|
1522
2156
|
// src/cdp/evaluate.ts
|
|
1523
2157
|
async function evaluate(cdp, sessionId, expression, signal) {
|
|
1524
2158
|
await cdp.send("Runtime.enable", {}, sessionId, signal);
|
|
@@ -1879,6 +2513,94 @@ async function typeRef(cdp, sessionId, elementRefs, id, text, signal) {
|
|
|
1879
2513
|
}, signal);
|
|
1880
2514
|
}
|
|
1881
2515
|
|
|
2516
|
+
// src/cdp/actions/wait.ts
|
|
2517
|
+
var POLL_INTERVAL_MS = 100;
|
|
2518
|
+
var SUMMARY_LENGTH = 120;
|
|
2519
|
+
var NAVIGATION_CONTEXT_ERRORS = [
|
|
2520
|
+
/(?:^|: )Execution context was destroyed\b/i,
|
|
2521
|
+
/(?:^|: )Cannot find context with specified id\b/i,
|
|
2522
|
+
/(?:^|: )Cannot find (?:default )?execution context\b/i,
|
|
2523
|
+
/(?:^|: )No execution context with given id\b/i
|
|
2524
|
+
];
|
|
2525
|
+
function conditionDetails(condition) {
|
|
2526
|
+
if ("selector" in condition) {
|
|
2527
|
+
return {
|
|
2528
|
+
expression: `document.querySelector(${JSON.stringify(condition.selector)}) !== null`,
|
|
2529
|
+
label: `selector ${summary(condition.selector)}`,
|
|
2530
|
+
matched: `Matched selector ${summary(condition.selector)}`
|
|
2531
|
+
};
|
|
2532
|
+
}
|
|
2533
|
+
if ("text" in condition) {
|
|
2534
|
+
return {
|
|
2535
|
+
expression: `document.body?.innerText.includes(${JSON.stringify(condition.text)}) ?? false`,
|
|
2536
|
+
label: `text ${summary(condition.text)}`,
|
|
2537
|
+
matched: `Matched text ${summary(condition.text)}`
|
|
2538
|
+
};
|
|
2539
|
+
}
|
|
2540
|
+
return {
|
|
2541
|
+
expression: `location.href.includes(${JSON.stringify(condition.url_includes)})`,
|
|
2542
|
+
label: `URL containing ${summary(condition.url_includes)}`,
|
|
2543
|
+
matched: `Matched URL containing ${summary(condition.url_includes)}`
|
|
2544
|
+
};
|
|
2545
|
+
}
|
|
2546
|
+
function summary(value) {
|
|
2547
|
+
const normalized = value.replace(/\s+/g, " ").trim();
|
|
2548
|
+
const bounded = normalized.length > SUMMARY_LENGTH ? `${normalized.slice(0, SUMMARY_LENGTH - 3)}...` : normalized;
|
|
2549
|
+
return JSON.stringify(bounded);
|
|
2550
|
+
}
|
|
2551
|
+
function isNavigationContextError(error) {
|
|
2552
|
+
const message = errorMessage(error);
|
|
2553
|
+
return NAVIGATION_CONTEXT_ERRORS.some((pattern) => pattern.test(message));
|
|
2554
|
+
}
|
|
2555
|
+
async function waitForCondition(cdp, sessionId, condition, timeoutMs, signal) {
|
|
2556
|
+
const details = conditionDetails(condition);
|
|
2557
|
+
const timeoutError = new Error(`Timed out after ${timeoutMs}ms waiting for ${details.label}`);
|
|
2558
|
+
const deadline = Date.now() + timeoutMs;
|
|
2559
|
+
const controller = new AbortController;
|
|
2560
|
+
let timedOut = false;
|
|
2561
|
+
const abort = () => {
|
|
2562
|
+
controller.abort(signal?.reason ?? new Error("Wait aborted"));
|
|
2563
|
+
};
|
|
2564
|
+
if (signal?.aborted) {
|
|
2565
|
+
abort();
|
|
2566
|
+
} else {
|
|
2567
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
2568
|
+
}
|
|
2569
|
+
const timer = setTimeout(() => {
|
|
2570
|
+
timedOut = true;
|
|
2571
|
+
controller.abort(timeoutError);
|
|
2572
|
+
}, timeoutMs);
|
|
2573
|
+
try {
|
|
2574
|
+
while (Date.now() < deadline) {
|
|
2575
|
+
try {
|
|
2576
|
+
const matched = await evaluate(cdp, sessionId, details.expression, controller.signal);
|
|
2577
|
+
if (matched === true)
|
|
2578
|
+
return details.matched;
|
|
2579
|
+
if (matched !== false) {
|
|
2580
|
+
throw new Error("Wait condition returned a non-boolean result");
|
|
2581
|
+
}
|
|
2582
|
+
} catch (error) {
|
|
2583
|
+
if (controller.signal.aborted)
|
|
2584
|
+
throw controller.signal.reason;
|
|
2585
|
+
if (!isNavigationContextError(error))
|
|
2586
|
+
throw error;
|
|
2587
|
+
}
|
|
2588
|
+
const remaining = deadline - Date.now();
|
|
2589
|
+
if (remaining <= 0)
|
|
2590
|
+
break;
|
|
2591
|
+
await sleep(Math.min(POLL_INTERVAL_MS, remaining), controller.signal);
|
|
2592
|
+
}
|
|
2593
|
+
throw timeoutError;
|
|
2594
|
+
} catch (error) {
|
|
2595
|
+
if (timedOut)
|
|
2596
|
+
throw timeoutError;
|
|
2597
|
+
throw error;
|
|
2598
|
+
} finally {
|
|
2599
|
+
clearTimeout(timer);
|
|
2600
|
+
signal?.removeEventListener("abort", abort);
|
|
2601
|
+
}
|
|
2602
|
+
}
|
|
2603
|
+
|
|
1882
2604
|
// src/cdp/snapshot.ts
|
|
1883
2605
|
var INTERACTIVE_ROLES = new Set([
|
|
1884
2606
|
"button",
|
|
@@ -1900,6 +2622,16 @@ var INTERACTIVE_ROLES = new Set([
|
|
|
1900
2622
|
"treeitem"
|
|
1901
2623
|
]);
|
|
1902
2624
|
var NEXT_ELEMENT_IDS = new WeakMap;
|
|
2625
|
+
function axProperty(value) {
|
|
2626
|
+
const record = asRecord(value, "accessibility property");
|
|
2627
|
+
if (typeof record["name"] !== "string") {
|
|
2628
|
+
throw new Error("Accessibility property has no name");
|
|
2629
|
+
}
|
|
2630
|
+
return {
|
|
2631
|
+
name: record["name"],
|
|
2632
|
+
...record["value"] ? { value: asRecord(record["value"]) } : {}
|
|
2633
|
+
};
|
|
2634
|
+
}
|
|
1903
2635
|
function axNode(value) {
|
|
1904
2636
|
const record = asRecord(value, "accessibility node");
|
|
1905
2637
|
if (typeof record["nodeId"] !== "string") {
|
|
@@ -1915,7 +2647,8 @@ function axNode(value) {
|
|
|
1915
2647
|
...typeof record["ignored"] === "boolean" ? { ignored: record["ignored"] } : {},
|
|
1916
2648
|
...record["role"] ? { role: asRecord(record["role"]) } : {},
|
|
1917
2649
|
...record["name"] ? { name: asRecord(record["name"]) } : {},
|
|
1918
|
-
...record["value"] ? { value: asRecord(record["value"]) } : {}
|
|
2650
|
+
...record["value"] ? { value: asRecord(record["value"]) } : {},
|
|
2651
|
+
...Array.isArray(record["properties"]) ? { properties: record["properties"].map(axProperty) } : {}
|
|
1919
2652
|
};
|
|
1920
2653
|
}
|
|
1921
2654
|
function shouldShow(node) {
|
|
@@ -1924,6 +2657,8 @@ function shouldShow(node) {
|
|
|
1924
2657
|
const value = node.value?.value;
|
|
1925
2658
|
if (role === "InlineTextBox")
|
|
1926
2659
|
return false;
|
|
2660
|
+
if (INTERACTIVE_ROLES.has(role))
|
|
2661
|
+
return true;
|
|
1927
2662
|
return role !== "none" && role !== "generic" && !(name === "" && (value === "" || value == null));
|
|
1928
2663
|
}
|
|
1929
2664
|
function orderedChildren(node, nodesById, childrenByParent) {
|
|
@@ -1957,9 +2692,35 @@ function splitText(value, max = 700) {
|
|
|
1957
2692
|
}
|
|
1958
2693
|
return parts;
|
|
1959
2694
|
}
|
|
2695
|
+
function interactiveState(node) {
|
|
2696
|
+
const values = new Map((node.properties ?? []).map((property) => [
|
|
2697
|
+
property.name,
|
|
2698
|
+
property.value?.value
|
|
2699
|
+
]));
|
|
2700
|
+
const checkedValue = values.get("checked");
|
|
2701
|
+
const checked = checkedValue === "true" ? true : checkedValue === "false" ? false : typeof checkedValue === "boolean" || checkedValue === "mixed" ? checkedValue : undefined;
|
|
2702
|
+
const selected = values.get("selected");
|
|
2703
|
+
const expanded = values.get("expanded");
|
|
2704
|
+
const disabled = values.get("disabled");
|
|
2705
|
+
return {
|
|
2706
|
+
...checked === undefined ? {} : { checked },
|
|
2707
|
+
...typeof selected === "boolean" ? { selected } : {},
|
|
2708
|
+
...typeof expanded === "boolean" ? { expanded } : {},
|
|
2709
|
+
...typeof disabled === "boolean" ? { disabled } : {}
|
|
2710
|
+
};
|
|
2711
|
+
}
|
|
2712
|
+
function interactiveText(role, name, value, state) {
|
|
2713
|
+
const states = [
|
|
2714
|
+
state.checked === undefined ? undefined : `checked=${state.checked}`,
|
|
2715
|
+
state.selected === undefined ? undefined : `selected=${state.selected}`,
|
|
2716
|
+
state.expanded === undefined ? undefined : `expanded=${state.expanded}`,
|
|
2717
|
+
state.disabled === undefined ? undefined : `disabled=${state.disabled}`
|
|
2718
|
+
].filter((entry) => entry !== undefined);
|
|
2719
|
+
return `${role}${name ? ` ${name}` : ""}${value === "" || value == null ? "" : ` = ${JSON.stringify(value)}`}${states.length > 0 ? ` [${states.join(", ")}]` : ""}`;
|
|
2720
|
+
}
|
|
1960
2721
|
async function snapshotData(cdp, sessionId, elementRefs, options = {}) {
|
|
1961
2722
|
const lineno = positiveInteger(options.lineno ?? 1, "line cursor");
|
|
1962
|
-
const
|
|
2723
|
+
const responseLength = snapshotResponseLength(options.responseLength);
|
|
1963
2724
|
const response = asRecord(await cdp.send("Accessibility.getFullAXTree", {}, sessionId, options.signal), "Accessibility response");
|
|
1964
2725
|
if (!Array.isArray(response["nodes"])) {
|
|
1965
2726
|
throw new Error("Accessibility response has no nodes");
|
|
@@ -2016,17 +2777,27 @@ async function snapshotData(cdp, sessionId, elementRefs, options = {}) {
|
|
|
2016
2777
|
const value = node.value?.value;
|
|
2017
2778
|
let renderedName = parentName;
|
|
2018
2779
|
if (!node.ignored && shouldShow(node)) {
|
|
2019
|
-
if (INTERACTIVE_ROLES.has(role)
|
|
2020
|
-
const
|
|
2021
|
-
|
|
2022
|
-
|
|
2023
|
-
|
|
2024
|
-
|
|
2025
|
-
}
|
|
2026
|
-
|
|
2027
|
-
|
|
2028
|
-
|
|
2029
|
-
|
|
2780
|
+
if (INTERACTIVE_ROLES.has(role)) {
|
|
2781
|
+
const state = interactiveState(node);
|
|
2782
|
+
const text = interactiveText(role, name, value, state);
|
|
2783
|
+
if (!node.backendDOMNodeId) {
|
|
2784
|
+
addLine(text, undefined, "interactive");
|
|
2785
|
+
renderedName = name;
|
|
2786
|
+
} else {
|
|
2787
|
+
const href = role === "link" ? node.properties?.find((property) => property.name === "url")?.value?.value : undefined;
|
|
2788
|
+
const element = {
|
|
2789
|
+
id: nextElementId(),
|
|
2790
|
+
role,
|
|
2791
|
+
...name ? { name } : {},
|
|
2792
|
+
...typeof href === "string" && href ? { href } : {},
|
|
2793
|
+
...value === "" || value == null ? {} : { value },
|
|
2794
|
+
...state
|
|
2795
|
+
};
|
|
2796
|
+
elementRefs.set(element.id, node.backendDOMNodeId);
|
|
2797
|
+
elements.push(element);
|
|
2798
|
+
addLine(`[${element.id}] ${text}`, element, "interactive");
|
|
2799
|
+
renderedName = name;
|
|
2800
|
+
}
|
|
2030
2801
|
} else if (role === "StaticText") {
|
|
2031
2802
|
if (name && name !== parentName)
|
|
2032
2803
|
addStaticText(name);
|
|
@@ -2047,10 +2818,10 @@ async function snapshotData(cdp, sessionId, elementRefs, options = {}) {
|
|
|
2047
2818
|
visit(node);
|
|
2048
2819
|
const metadata = asRecord(await evaluate(cdp, sessionId, "({title: document.title, url: location.href})", options.signal), "page metadata");
|
|
2049
2820
|
const pattern = options.pattern?.toLowerCase();
|
|
2050
|
-
const matching = pattern ? lines.filter((
|
|
2821
|
+
const matching = pattern ? lines.filter((line) => line.text.toLowerCase().includes(pattern)) : lines;
|
|
2051
2822
|
const start = lineno - 1;
|
|
2052
|
-
const content = matching.slice(start, start + SNAPSHOT_LIMITS[
|
|
2053
|
-
const visibleIds = new Set(content.flatMap((
|
|
2823
|
+
const content = matching.slice(start, start + SNAPSHOT_LIMITS[responseLength]).map(({ kind: _kind, ...line }) => line);
|
|
2824
|
+
const visibleIds = new Set(content.flatMap((line) => line.element_id === undefined ? [] : [line.element_id]));
|
|
2054
2825
|
const hasMore = start + content.length < matching.length;
|
|
2055
2826
|
return {
|
|
2056
2827
|
...options.refId ? { ref_id: options.refId } : {},
|
|
@@ -2082,6 +2853,7 @@ function truncateUtf8(value, maxBytes) {
|
|
|
2082
2853
|
return new StringDecoder("utf8").write(bytes.subarray(0, maxBytes));
|
|
2083
2854
|
}
|
|
2084
2855
|
function boundedElement(element) {
|
|
2856
|
+
const { href, ...rest } = element;
|
|
2085
2857
|
let value = element.value;
|
|
2086
2858
|
if (typeof value === "string") {
|
|
2087
2859
|
value = truncateUtf8(value, SNAPSHOT_ELEMENT_VALUE_BYTES);
|
|
@@ -2092,43 +2864,45 @@ function boundedElement(element) {
|
|
|
2092
2864
|
}
|
|
2093
2865
|
}
|
|
2094
2866
|
return {
|
|
2095
|
-
...
|
|
2867
|
+
...rest,
|
|
2868
|
+
...href === undefined ? {} : Buffer.byteLength(href) > SNAPSHOT_URL_BYTES ? { href_omitted: true } : { href },
|
|
2096
2869
|
role: truncateUtf8(element.role, 128),
|
|
2097
2870
|
...element.name === undefined ? {} : { name: truncateUtf8(element.name, SNAPSHOT_ELEMENT_NAME_BYTES) },
|
|
2098
2871
|
...value === undefined ? {} : { value }
|
|
2099
2872
|
};
|
|
2100
2873
|
}
|
|
2101
|
-
function boundTabs(pages, query,
|
|
2874
|
+
function boundTabs(pages, query, offset, ownedOnly = false) {
|
|
2102
2875
|
const prefixLength = getDisplayPrefixLength(pages.map((page) => page.targetId));
|
|
2103
|
-
let filtered = pages;
|
|
2876
|
+
let filtered = ownedOnly ? pages.filter((page) => page.owned === true) : pages;
|
|
2104
2877
|
if (query) {
|
|
2105
2878
|
const normalized = query.toLowerCase();
|
|
2106
|
-
filtered =
|
|
2879
|
+
filtered = filtered.filter((page) => `${page.title}
|
|
2107
2880
|
${page.url}`.toLowerCase().includes(normalized));
|
|
2108
2881
|
}
|
|
2109
|
-
if (
|
|
2110
|
-
throw new Error(`offset ${
|
|
2882
|
+
if (offset > filtered.length) {
|
|
2883
|
+
throw new Error(`offset ${offset} exceeds tab count ${filtered.length}`);
|
|
2111
2884
|
}
|
|
2112
2885
|
const tabs = [];
|
|
2113
|
-
for (const page of filtered.slice(
|
|
2886
|
+
for (const page of filtered.slice(offset)) {
|
|
2114
2887
|
const compact = {
|
|
2115
2888
|
ref_id: page.targetId.slice(0, prefixLength),
|
|
2116
2889
|
title: page.title.slice(0, 500),
|
|
2117
|
-
url: page.url.slice(0, 8000)
|
|
2890
|
+
url: page.url.slice(0, 8000),
|
|
2891
|
+
owned: page.owned === true
|
|
2118
2892
|
};
|
|
2119
2893
|
if (byteLength({ tabs: [...tabs, compact] }) > OUTPUT_BUDGET_BYTES) {
|
|
2120
2894
|
break;
|
|
2121
2895
|
}
|
|
2122
2896
|
tabs.push(compact);
|
|
2123
2897
|
}
|
|
2124
|
-
const remaining = filtered.length -
|
|
2898
|
+
const remaining = filtered.length - offset - tabs.length;
|
|
2125
2899
|
return {
|
|
2126
|
-
offset
|
|
2900
|
+
offset,
|
|
2127
2901
|
tabs,
|
|
2128
2902
|
...remaining > 0 ? {
|
|
2129
2903
|
truncated: true,
|
|
2130
2904
|
omitted_tabs: remaining,
|
|
2131
|
-
next_offset:
|
|
2905
|
+
next_offset: offset + tabs.length
|
|
2132
2906
|
} : {}
|
|
2133
2907
|
};
|
|
2134
2908
|
}
|
|
@@ -2144,11 +2918,11 @@ function boundSnapshot(page) {
|
|
|
2144
2918
|
const content = [];
|
|
2145
2919
|
const includedElements = [];
|
|
2146
2920
|
const includedIds = new Set;
|
|
2147
|
-
for (const
|
|
2148
|
-
const nextContent = [...content,
|
|
2921
|
+
for (const line of page.content) {
|
|
2922
|
+
const nextContent = [...content, line];
|
|
2149
2923
|
const nextElements = [...includedElements];
|
|
2150
|
-
if (
|
|
2151
|
-
const element = elements.get(
|
|
2924
|
+
if (line.element_id !== undefined && !includedIds.has(line.element_id) && elements.has(line.element_id)) {
|
|
2925
|
+
const element = elements.get(line.element_id);
|
|
2152
2926
|
if (element)
|
|
2153
2927
|
nextElements.push(element);
|
|
2154
2928
|
}
|
|
@@ -2159,10 +2933,10 @@ function boundSnapshot(page) {
|
|
|
2159
2933
|
}) > OUTPUT_BUDGET_BYTES) {
|
|
2160
2934
|
break;
|
|
2161
2935
|
}
|
|
2162
|
-
content.push(
|
|
2163
|
-
if (
|
|
2164
|
-
includedIds.add(
|
|
2165
|
-
const element = elements.get(
|
|
2936
|
+
content.push(line);
|
|
2937
|
+
if (line.element_id !== undefined && !includedIds.has(line.element_id) && elements.has(line.element_id)) {
|
|
2938
|
+
includedIds.add(line.element_id);
|
|
2939
|
+
const element = elements.get(line.element_id);
|
|
2166
2940
|
if (element)
|
|
2167
2941
|
includedElements.push(element);
|
|
2168
2942
|
}
|
|
@@ -2350,13 +3124,14 @@ class BrowserOperationExecutor {
|
|
|
2350
3124
|
case "start":
|
|
2351
3125
|
return { result: await startBrowser(signal) };
|
|
2352
3126
|
case "tabs":
|
|
2353
|
-
return boundTabs(await this.cdp.pages(signal), operation.query, operation.offset);
|
|
3127
|
+
return boundTabs(await this.cdp.pages(signal), operation.query, operation.offset, operation.owned_only);
|
|
2354
3128
|
case "open":
|
|
2355
3129
|
if ("url" in operation) {
|
|
2356
3130
|
const opened = await this.cdp.open(operation.url, signal);
|
|
2357
3131
|
return {
|
|
2358
3132
|
ref_id: opened.refId,
|
|
2359
|
-
url: operation.url
|
|
3133
|
+
url: operation.url,
|
|
3134
|
+
owned: true
|
|
2360
3135
|
};
|
|
2361
3136
|
}
|
|
2362
3137
|
return this.cdp.withTab(operation.ref_id, signal, async (tab) => boundSnapshot(await snapshotData(tab.cdp, tab.sessionId, tab.elementRefs, {
|
|
@@ -2373,6 +3148,10 @@ class BrowserOperationExecutor {
|
|
|
2373
3148
|
responseLength: operation.response_length,
|
|
2374
3149
|
signal
|
|
2375
3150
|
})));
|
|
3151
|
+
case "show":
|
|
3152
|
+
return { shown: await this.cdp.show(operation.ref_id, signal) };
|
|
3153
|
+
case "close":
|
|
3154
|
+
return { closed: await this.cdp.closeTab(operation.ref_id, signal) };
|
|
2376
3155
|
case "read_result":
|
|
2377
3156
|
return readCachedResult(operation);
|
|
2378
3157
|
case "discard_result":
|
|
@@ -2411,18 +3190,24 @@ class BrowserOperationExecutor {
|
|
|
2411
3190
|
return this.tabResult(operation.ref_id, signal, (tab) => operation.id === undefined ? typeAtFocus(tab.cdp, tab.sessionId, operation.text, signal) : typeRef(tab.cdp, tab.sessionId, tab.elementRefs, operation.id, operation.text, signal));
|
|
2412
3191
|
case "load_all":
|
|
2413
3192
|
return this.tabResult(operation.ref_id, signal, (tab) => loadAll(tab.cdp, tab.sessionId, operation.selector, operation.interval_ms, signal));
|
|
3193
|
+
case "fill":
|
|
3194
|
+
return this.tabResult(operation.ref_id, signal, (tab) => fillElement(tab.cdp, tab.sessionId, tab.elementRefs, operation, operation.value, signal));
|
|
3195
|
+
case "press":
|
|
3196
|
+
return this.tabResult(operation.ref_id, signal, (tab) => pressKey(tab.cdp, tab.sessionId, operation.key, signal));
|
|
3197
|
+
case "wait":
|
|
3198
|
+
return this.tabResult(operation.ref_id, signal, (tab) => waitForCondition(tab.cdp, tab.sessionId, operation, operation.timeout_ms, signal));
|
|
2414
3199
|
}
|
|
2415
3200
|
}
|
|
2416
3201
|
async screenshot(operation, signal) {
|
|
2417
3202
|
const file = await screenshotPath(operation);
|
|
2418
3203
|
return this.cdp.withTab(operation.ref_id, signal, async (tab) => {
|
|
2419
|
-
const
|
|
3204
|
+
const capture = operation.id !== undefined ? await captureRef(tab.cdp, tab.sessionId, tab.elementRefs, operation.id, file, signal) : operation.selector ? await captureSelector(tab.cdp, tab.sessionId, operation.selector, file, signal) : await captureViewport(tab.cdp, tab.sessionId, file, signal);
|
|
2420
3205
|
return {
|
|
2421
3206
|
ref_id: tab.refId,
|
|
2422
3207
|
...operation.id === undefined ? {} : { id: operation.id },
|
|
2423
3208
|
...operation.selector ? { selector: operation.selector } : {},
|
|
2424
|
-
file:
|
|
2425
|
-
dpr:
|
|
3209
|
+
file: capture.file,
|
|
3210
|
+
dpr: capture.dpr,
|
|
2426
3211
|
coordinates: "CSS pixels; screenshot pixels / DPR"
|
|
2427
3212
|
};
|
|
2428
3213
|
});
|
|
@@ -2436,8 +3221,8 @@ class BrowserOperationExecutor {
|
|
|
2436
3221
|
}
|
|
2437
3222
|
|
|
2438
3223
|
// src/browser/remote.ts
|
|
2439
|
-
import { mkdir as
|
|
2440
|
-
import { basename as basename2, join as
|
|
3224
|
+
import { mkdir as mkdir3, rm as rm3 } from "node:fs/promises";
|
|
3225
|
+
import { basename as basename2, join as join4 } from "node:path";
|
|
2441
3226
|
|
|
2442
3227
|
// src/browser/remote-helper.ts
|
|
2443
3228
|
import { readFile as readFile2 } from "node:fs/promises";
|
|
@@ -2639,8 +3424,8 @@ async function copyRemoteArtifact(host, remoteFile, signal) {
|
|
|
2639
3424
|
if (!SAFE_REMOTE_FILE.test(remoteFile)) {
|
|
2640
3425
|
throw new Error(`remote browser returned an unsafe artifact path: ${remoteFile}`);
|
|
2641
3426
|
}
|
|
2642
|
-
await
|
|
2643
|
-
const localFile =
|
|
3427
|
+
await mkdir3(artifactDirectory(), { recursive: true, mode: 448 });
|
|
3428
|
+
const localFile = join4(artifactDirectory(), `${host}-${basename2(remoteFile)}`);
|
|
2644
3429
|
const copied = await runProgram("scp", ["-q", `${host}:${remoteFile}`, localFile], undefined, signal);
|
|
2645
3430
|
if (copied.code !== 0) {
|
|
2646
3431
|
throw new Error(copied.stderr || copied.stdout || "could not copy remote screenshot");
|
|
@@ -2652,7 +3437,7 @@ async function copyRemoteArtifact(host, remoteFile, signal) {
|
|
|
2652
3437
|
}
|
|
2653
3438
|
return localFile;
|
|
2654
3439
|
} catch (error) {
|
|
2655
|
-
await
|
|
3440
|
+
await rm3(localFile, { force: true });
|
|
2656
3441
|
throw error;
|
|
2657
3442
|
}
|
|
2658
3443
|
}
|
|
@@ -2667,12 +3452,12 @@ async function localizeScreenshots(host, operations, result, signal) {
|
|
|
2667
3452
|
item["file"] = await copyRemoteArtifact(host, item["file"], signal);
|
|
2668
3453
|
}
|
|
2669
3454
|
}
|
|
2670
|
-
async function executeRemoteBrowser(route, operations, signal) {
|
|
3455
|
+
async function executeRemoteBrowser(route, operations, ownerId, signal) {
|
|
2671
3456
|
if (!route.remote) {
|
|
2672
3457
|
throw new Error(`Browser host ${route.name} has no remote command`);
|
|
2673
3458
|
}
|
|
2674
3459
|
await ensureRemoteHelper(route.name, route.remote, signal);
|
|
2675
|
-
const executed = await runProgram("ssh", [route.name, remoteNodeCommand(route.remote)], JSON.stringify({ operations }), signal);
|
|
3460
|
+
const executed = await runProgram("ssh", [route.name, remoteNodeCommand(route.remote)], JSON.stringify({ owner_id: ownerId, operations }), signal);
|
|
2676
3461
|
if (executed.code !== 0) {
|
|
2677
3462
|
throw new Error(executed.stderr || executed.stdout || `remote browser exited with code ${executed.code}`);
|
|
2678
3463
|
}
|
|
@@ -2690,20 +3475,31 @@ async function executeRemoteBrowser(route, operations, signal) {
|
|
|
2690
3475
|
}
|
|
2691
3476
|
|
|
2692
3477
|
// src/browser/runtime.ts
|
|
3478
|
+
var LOCAL_SESSION_IDLE_MS = 20 * 60 * 1000;
|
|
3479
|
+
|
|
2693
3480
|
class BrowserRuntime {
|
|
2694
3481
|
hosts;
|
|
2695
|
-
|
|
2696
|
-
|
|
3482
|
+
defaultOwnerId = randomUUID();
|
|
3483
|
+
lifetime = new AbortController;
|
|
3484
|
+
closing;
|
|
3485
|
+
localSessions = new Map;
|
|
2697
3486
|
routes;
|
|
2698
3487
|
constructor(routes = loadBrowserRoutes()) {
|
|
2699
3488
|
this.routes = routes;
|
|
2700
3489
|
this.hosts = routes.names;
|
|
2701
3490
|
}
|
|
2702
3491
|
async execute(request, options = {}) {
|
|
3492
|
+
options = {
|
|
3493
|
+
...options,
|
|
3494
|
+
signal: options.signal ? AbortSignal.any([options.signal, this.lifetime.signal]) : this.lifetime.signal
|
|
3495
|
+
};
|
|
2703
3496
|
options.signal?.throwIfAborted();
|
|
3497
|
+
await waitForTurn(this.pruneLocalSessions(), options.signal);
|
|
2704
3498
|
await pruneArtifacts();
|
|
3499
|
+
options.signal?.throwIfAborted();
|
|
2705
3500
|
if ("help" in request)
|
|
2706
3501
|
return browserHelp(this.hosts);
|
|
3502
|
+
const ownerId = options.ownerId ?? this.defaultOwnerId;
|
|
2707
3503
|
if (request.host) {
|
|
2708
3504
|
const route = this.routes.resolve(request.host);
|
|
2709
3505
|
if (!route.local) {
|
|
@@ -2711,37 +3507,87 @@ class BrowserRuntime {
|
|
|
2711
3507
|
if (first) {
|
|
2712
3508
|
options.onOperation?.(first, 0, request.operations.length);
|
|
2713
3509
|
}
|
|
2714
|
-
const
|
|
2715
|
-
return { host: request.host, ...
|
|
3510
|
+
const result = await executeRemoteBrowser(route, request.operations, ownerId, options.signal);
|
|
3511
|
+
return { host: request.host, ...result };
|
|
2716
3512
|
}
|
|
2717
3513
|
}
|
|
2718
|
-
const result = await this.executeLocal(request.operations, options);
|
|
3514
|
+
const result = await this.executeLocal(request.operations, ownerId, options);
|
|
2719
3515
|
return request.host ? { host: request.host, ...result } : result;
|
|
2720
3516
|
}
|
|
2721
3517
|
close() {
|
|
2722
|
-
this.
|
|
3518
|
+
if (this.closing)
|
|
3519
|
+
return this.closing;
|
|
3520
|
+
this.lifetime.abort(new Error("Browser runtime closed"));
|
|
3521
|
+
const closing = [...this.localSessions.values()].map((session) => session.cdp.close());
|
|
3522
|
+
this.localSessions.clear();
|
|
3523
|
+
this.closing = Promise.all(closing).then(() => {
|
|
3524
|
+
return;
|
|
3525
|
+
});
|
|
3526
|
+
return this.closing;
|
|
2723
3527
|
}
|
|
2724
|
-
async executeLocal(operations, options) {
|
|
2725
|
-
|
|
2726
|
-
|
|
2727
|
-
|
|
2728
|
-
|
|
2729
|
-
options.onOperation?.(operation, index, operations.length);
|
|
2730
|
-
results.push(await this.operations.execute(operation, options.signal));
|
|
2731
|
-
} catch (error) {
|
|
2732
|
-
throw new Error(`batch failed at ${operation.action}[${index}] after ${results.length} completed operation(s): ${error instanceof Error ? error.message : String(error)}`);
|
|
2733
|
-
}
|
|
3528
|
+
async executeLocal(operations, ownerId, options) {
|
|
3529
|
+
let pendingClose = this.localSessions.get(ownerId)?.closing;
|
|
3530
|
+
while (pendingClose) {
|
|
3531
|
+
await waitForTurn(pendingClose, options.signal);
|
|
3532
|
+
pendingClose = this.localSessions.get(ownerId)?.closing;
|
|
2734
3533
|
}
|
|
2735
|
-
|
|
2736
|
-
|
|
2737
|
-
|
|
2738
|
-
|
|
2739
|
-
|
|
2740
|
-
|
|
2741
|
-
|
|
2742
|
-
|
|
2743
|
-
|
|
3534
|
+
options.signal?.throwIfAborted();
|
|
3535
|
+
const session = this.localSession(ownerId);
|
|
3536
|
+
session.activeCalls++;
|
|
3537
|
+
try {
|
|
3538
|
+
const results = [];
|
|
3539
|
+
for (const [index, operation] of operations.entries()) {
|
|
3540
|
+
try {
|
|
3541
|
+
options.signal?.throwIfAborted();
|
|
3542
|
+
options.onOperation?.(operation, index, operations.length);
|
|
3543
|
+
results.push(await session.operations.execute(operation, options.signal));
|
|
3544
|
+
} catch (error) {
|
|
3545
|
+
throw new Error(`batch failed at ${operation.action}[${index}] after ${results.length} completed operation(s): ${error instanceof Error ? error.message : String(error)}`);
|
|
3546
|
+
}
|
|
3547
|
+
}
|
|
3548
|
+
const first = results[0];
|
|
3549
|
+
if (results.length === 1 && first)
|
|
3550
|
+
return first;
|
|
3551
|
+
return {
|
|
3552
|
+
results: results.map((result, index) => ({
|
|
3553
|
+
operation: operations[index]?.action ?? "unknown",
|
|
3554
|
+
index,
|
|
3555
|
+
...result
|
|
3556
|
+
}))
|
|
3557
|
+
};
|
|
3558
|
+
} finally {
|
|
3559
|
+
session.activeCalls--;
|
|
3560
|
+
session.lastUsed = Date.now();
|
|
3561
|
+
}
|
|
3562
|
+
}
|
|
3563
|
+
localSession(ownerId) {
|
|
3564
|
+
let session = this.localSessions.get(ownerId);
|
|
3565
|
+
if (session)
|
|
3566
|
+
return session;
|
|
3567
|
+
const cdp = new BrowserCdpSession(ownerId, join5(artifactDirectory(), "tabs"));
|
|
3568
|
+
session = {
|
|
3569
|
+
activeCalls: 0,
|
|
3570
|
+
cdp,
|
|
3571
|
+
lastUsed: Date.now(),
|
|
3572
|
+
operations: new BrowserOperationExecutor(cdp)
|
|
2744
3573
|
};
|
|
3574
|
+
this.localSessions.set(ownerId, session);
|
|
3575
|
+
return session;
|
|
3576
|
+
}
|
|
3577
|
+
async pruneLocalSessions(now = Date.now()) {
|
|
3578
|
+
const closing = [];
|
|
3579
|
+
for (const [ownerId, session] of this.localSessions) {
|
|
3580
|
+
if (!session.closing && session.activeCalls === 0 && now - session.lastUsed >= LOCAL_SESSION_IDLE_MS) {
|
|
3581
|
+
session.closing = session.cdp.close().finally(() => {
|
|
3582
|
+
if (this.localSessions.get(ownerId) === session) {
|
|
3583
|
+
this.localSessions.delete(ownerId);
|
|
3584
|
+
}
|
|
3585
|
+
});
|
|
3586
|
+
}
|
|
3587
|
+
if (session.closing)
|
|
3588
|
+
closing.push(session.closing);
|
|
3589
|
+
}
|
|
3590
|
+
await Promise.all(closing);
|
|
2745
3591
|
}
|
|
2746
3592
|
}
|
|
2747
3593
|
|
|
@@ -2753,15 +3599,15 @@ var IS_WINDOWS2 = process.platform === "win32";
|
|
|
2753
3599
|
function workerSocketPath(workerId) {
|
|
2754
3600
|
if (IS_WINDOWS2)
|
|
2755
3601
|
return `\\\\.\\pipe\\pi-browser-worker-${workerId}`;
|
|
2756
|
-
const directory = process.env["XDG_RUNTIME_DIR"] ?
|
|
2757
|
-
return
|
|
3602
|
+
const directory = process.env["XDG_RUNTIME_DIR"] ? join6(process.env["XDG_RUNTIME_DIR"], "browser-tool") : join6(tmpdir2(), `browser-tool-${process.getuid?.() ?? "user"}`);
|
|
3603
|
+
return join6(directory, `worker-${workerId}.sock`);
|
|
2758
3604
|
}
|
|
2759
3605
|
async function ensureWorkerSocketDirectory(workerId) {
|
|
2760
3606
|
if (IS_WINDOWS2)
|
|
2761
3607
|
return;
|
|
2762
3608
|
const directory = dirname2(workerSocketPath(workerId));
|
|
2763
|
-
await
|
|
2764
|
-
const info = await
|
|
3609
|
+
await mkdir4(directory, { recursive: true, mode: 448 });
|
|
3610
|
+
const info = await lstat2(directory);
|
|
2765
3611
|
const uid = process.getuid?.();
|
|
2766
3612
|
if (info.isSymbolicLink() || !info.isDirectory()) {
|
|
2767
3613
|
throw new Error(`Browser worker socket directory is not a directory: ${directory}`);
|
|
@@ -2772,7 +3618,7 @@ async function ensureWorkerSocketDirectory(workerId) {
|
|
|
2772
3618
|
if ((info.mode & 63) !== 0)
|
|
2773
3619
|
await chmod(directory, 448);
|
|
2774
3620
|
}
|
|
2775
|
-
function
|
|
3621
|
+
function parseWorkerRequest(input) {
|
|
2776
3622
|
let value;
|
|
2777
3623
|
try {
|
|
2778
3624
|
value = JSON.parse(input);
|
|
@@ -2781,14 +3627,17 @@ function parseWorkerOperations(input) {
|
|
|
2781
3627
|
}
|
|
2782
3628
|
if (!isRecordValue(value))
|
|
2783
3629
|
throw new Error("worker input must be an object");
|
|
2784
|
-
const unknown = Object.keys(value).filter((key) => key !== "operations");
|
|
3630
|
+
const unknown = Object.keys(value).filter((key) => key !== "owner_id" && key !== "operations");
|
|
2785
3631
|
if (unknown.length > 0) {
|
|
2786
3632
|
throw new Error(`unknown worker field(s): ${unknown.join(", ")}`);
|
|
2787
3633
|
}
|
|
3634
|
+
if (typeof value["owner_id"] !== "string" || value["owner_id"].length === 0 || value["owner_id"].length > 256) {
|
|
3635
|
+
throw new Error("worker owner_id must be a non-empty string no longer than 256 characters");
|
|
3636
|
+
}
|
|
2788
3637
|
if (!Array.isArray(value["operations"]) || value["operations"].length === 0) {
|
|
2789
3638
|
throw new Error("worker operations must be a non-empty array");
|
|
2790
3639
|
}
|
|
2791
|
-
|
|
3640
|
+
const operations = value["operations"].map((operation, index) => {
|
|
2792
3641
|
if (!isRecordValue(operation)) {
|
|
2793
3642
|
throw new Error(`worker operations[${index}] must be an object`);
|
|
2794
3643
|
}
|
|
@@ -2798,6 +3647,7 @@ function parseWorkerOperations(input) {
|
|
|
2798
3647
|
}
|
|
2799
3648
|
return parsed;
|
|
2800
3649
|
});
|
|
3650
|
+
return { operations, ownerId: value["owner_id"] };
|
|
2801
3651
|
}
|
|
2802
3652
|
function readLine(socket) {
|
|
2803
3653
|
return new Promise((resolveValue, reject) => {
|
|
@@ -2841,10 +3691,10 @@ async function handleConnection(socket, runtime) {
|
|
|
2841
3691
|
socket.once("error", abort);
|
|
2842
3692
|
let response;
|
|
2843
3693
|
try {
|
|
2844
|
-
const
|
|
3694
|
+
const request = parseWorkerRequest(await readLine(socket));
|
|
2845
3695
|
response = {
|
|
2846
3696
|
ok: true,
|
|
2847
|
-
result: await runtime.execute({ operations }, { signal: controller.signal })
|
|
3697
|
+
result: await runtime.execute({ operations: request.operations }, { ownerId: request.ownerId, signal: controller.signal })
|
|
2848
3698
|
};
|
|
2849
3699
|
} catch (error) {
|
|
2850
3700
|
response = {
|
|
@@ -2892,9 +3742,9 @@ async function serveBrowserWorker(workerId) {
|
|
|
2892
3742
|
clearTimeout(idleTimer);
|
|
2893
3743
|
process.removeListener("SIGINT", close);
|
|
2894
3744
|
process.removeListener("SIGTERM", close);
|
|
2895
|
-
runtime.close();
|
|
3745
|
+
await runtime.close();
|
|
2896
3746
|
if (!IS_WINDOWS2 && ownsSocket)
|
|
2897
|
-
await
|
|
3747
|
+
await rm4(path, { force: true });
|
|
2898
3748
|
}
|
|
2899
3749
|
}
|
|
2900
3750
|
async function requestOnce(input, workerId, signal) {
|
|
@@ -2914,11 +3764,11 @@ async function requestOnce(input, workerId, signal) {
|
|
|
2914
3764
|
signal?.addEventListener("abort", abort, { once: true });
|
|
2915
3765
|
socket.once("connect", () => socket.write(`${input}
|
|
2916
3766
|
`));
|
|
2917
|
-
readLine(socket).then((
|
|
3767
|
+
readLine(socket).then((line) => {
|
|
2918
3768
|
signal?.removeEventListener("abort", abort);
|
|
2919
3769
|
socket.destroy();
|
|
2920
3770
|
try {
|
|
2921
|
-
const response = JSON.parse(
|
|
3771
|
+
const response = JSON.parse(line);
|
|
2922
3772
|
if (!isRecordValue(response) || typeof response["ok"] !== "boolean") {
|
|
2923
3773
|
throw new Error("Browser worker returned an invalid response");
|
|
2924
3774
|
}
|
|
@@ -2949,7 +3799,7 @@ async function requestBrowserWorker(input, entryPath, workerId, signal) {
|
|
|
2949
3799
|
throw error;
|
|
2950
3800
|
}
|
|
2951
3801
|
if (!IS_WINDOWS2)
|
|
2952
|
-
await
|
|
3802
|
+
await rm4(workerSocketPath(workerId), { force: true });
|
|
2953
3803
|
const child = spawn3(process.execPath, ["--preserve-symlinks-main", entryPath, "--daemon"], { detached: true, stdio: "ignore" });
|
|
2954
3804
|
child.unref();
|
|
2955
3805
|
const deadline = Date.now() + START_TIMEOUT_MS;
|
|
@@ -2982,7 +3832,7 @@ async function readStdin() {
|
|
|
2982
3832
|
}
|
|
2983
3833
|
async function main() {
|
|
2984
3834
|
const entryPath = fileURLToPath2(import.meta.url);
|
|
2985
|
-
const workerId =
|
|
3835
|
+
const workerId = createHash2("sha256").update(readFileSync3(entryPath)).digest("hex").slice(0, 12);
|
|
2986
3836
|
if (process.argv.includes("--daemon")) {
|
|
2987
3837
|
await serveBrowserWorker(workerId);
|
|
2988
3838
|
return;
|