@howaboua/pi-browser 0.0.3 → 0.0.4
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 +11 -0
- package/README.md +4 -0
- package/dist/index.js +2 -2
- package/dist/remote-worker.js +978 -136
- package/dist/src/browser/bounds.d.ts +1 -1
- package/dist/src/browser/bounds.js +6 -3
- package/dist/src/browser/help.js +8 -3
- 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 +32 -0
- 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/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 +4 -0
- package/dist/src/cdp/snapshot.js +67 -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 +7 -2
- package/src/browser/help.ts +8 -3
- 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 +34 -0
- package/src/browser-tool.ts +2 -1
- package/src/cdp/actions/click.ts +1 -1
- 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 +4 -0
- package/src/cdp/snapshot.ts +86 -17
- package/src/cdp/tabs.ts +292 -0
- package/src/cdp/types.ts +2 -0
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import type { CdpConnection, ElementRefs } from "../types.js";
|
|
2
|
+
import { type ElementPoint } from "./element.js";
|
|
3
|
+
export declare function clickBackendNode(cdp: CdpConnection, sessionId: string, backendNodeId: number, signal?: AbortSignal): Promise<ElementPoint>;
|
|
2
4
|
export declare function clickSelector(cdp: CdpConnection, sessionId: string, selector: string, signal?: AbortSignal): Promise<string>;
|
|
3
5
|
export declare function clickRef(cdp: CdpConnection, sessionId: string, elementRefs: ElementRefs, id: number | string, signal?: AbortSignal): Promise<string>;
|
|
4
6
|
export declare function clickCoordinates(cdp: CdpConnection, sessionId: string, x: number, y: number, signal?: AbortSignal): Promise<string>;
|
|
@@ -26,7 +26,7 @@ async function pressAndRelease(cdp, sessionId, point, signal) {
|
|
|
26
26
|
}
|
|
27
27
|
}
|
|
28
28
|
}
|
|
29
|
-
async function clickBackendNode(cdp, sessionId, backendNodeId, signal) {
|
|
29
|
+
export async function clickBackendNode(cdp, sessionId, backendNodeId, signal) {
|
|
30
30
|
const initial = await backendCenter(cdp, sessionId, backendNodeId, true, signal);
|
|
31
31
|
await dispatchMouse(cdp, sessionId, "mouseMoved", initial, signal);
|
|
32
32
|
const point = await backendCenter(cdp, sessionId, backendNodeId, false, signal);
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { CdpConnection, ElementRefs } from "../types.js";
|
|
2
|
+
export declare function fillElement(cdp: CdpConnection, sessionId: string, elementRefs: ElementRefs, target: {
|
|
3
|
+
id: number;
|
|
4
|
+
selector?: never;
|
|
5
|
+
} | {
|
|
6
|
+
selector: string;
|
|
7
|
+
id?: never;
|
|
8
|
+
}, value: string | boolean, signal?: AbortSignal): Promise<string>;
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
import { asRecord } from "../types.js";
|
|
2
|
+
import { clickBackendNode } from "./click.js";
|
|
3
|
+
import { backendCenter, requireElementRef, withBackendObject, } from "./element.js";
|
|
4
|
+
import { pressKey } from "./key.js";
|
|
5
|
+
import { selectorBackendNode } from "./selector.js";
|
|
6
|
+
// Runs in the element's realm. Native setters bypass framework value trackers;
|
|
7
|
+
// input/change events notify controlled form components of the replacement.
|
|
8
|
+
function prepareFill(value) {
|
|
9
|
+
if (!this.isConnected)
|
|
10
|
+
throw new Error("Element detached; run open again");
|
|
11
|
+
if (this.matches(":disabled") ||
|
|
12
|
+
this.getAttribute("aria-disabled") === "true" ||
|
|
13
|
+
this.closest("[inert]")) {
|
|
14
|
+
throw new Error("Element is disabled or inert");
|
|
15
|
+
}
|
|
16
|
+
const input = this instanceof HTMLInputElement;
|
|
17
|
+
const textarea = this instanceof HTMLTextAreaElement;
|
|
18
|
+
const select = this instanceof HTMLSelectElement;
|
|
19
|
+
if ((input || textarea) && this.readOnly)
|
|
20
|
+
throw new Error("Element is read-only");
|
|
21
|
+
const toggle = input && (this.type === "checkbox" || this.type === "radio");
|
|
22
|
+
if (toggle) {
|
|
23
|
+
if (typeof value !== "boolean")
|
|
24
|
+
throw new Error("Checkbox/radio requires a boolean value");
|
|
25
|
+
if (this.type === "radio" && !value && this.checked) {
|
|
26
|
+
throw new Error("Select another radio option with value true instead of unchecking this one");
|
|
27
|
+
}
|
|
28
|
+
const indeterminate = this.type === "checkbox" && this.indeterminate;
|
|
29
|
+
if (indeterminate && this.checked === value) {
|
|
30
|
+
const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "checked")?.set;
|
|
31
|
+
if (!setter)
|
|
32
|
+
throw new Error("Checkbox has no native checked setter");
|
|
33
|
+
// A click clears indeterminate and toggles checked. Start from the
|
|
34
|
+
// opposite state so that single click lands on the requested value.
|
|
35
|
+
setter.call(this, !value);
|
|
36
|
+
}
|
|
37
|
+
return {
|
|
38
|
+
kind: "checked",
|
|
39
|
+
expected: value,
|
|
40
|
+
needsClick: this.checked !== value || indeterminate,
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
if (typeof value !== "string")
|
|
44
|
+
throw new Error("Text fields and selects require a string value");
|
|
45
|
+
if (input &&
|
|
46
|
+
![
|
|
47
|
+
"text",
|
|
48
|
+
"search",
|
|
49
|
+
"email",
|
|
50
|
+
"url",
|
|
51
|
+
"tel",
|
|
52
|
+
"password",
|
|
53
|
+
"number",
|
|
54
|
+
"date",
|
|
55
|
+
"time",
|
|
56
|
+
"datetime-local",
|
|
57
|
+
"month",
|
|
58
|
+
"week",
|
|
59
|
+
].includes(this.type)) {
|
|
60
|
+
throw new Error(`Input type ${this.type} does not support fill`);
|
|
61
|
+
}
|
|
62
|
+
if (!input && !textarea && !select && !this.isContentEditable) {
|
|
63
|
+
throw new Error("Element is not an editable form control");
|
|
64
|
+
}
|
|
65
|
+
let replacement = value;
|
|
66
|
+
if (select) {
|
|
67
|
+
if (this.multiple)
|
|
68
|
+
throw new Error("fill requires a single-select control");
|
|
69
|
+
const options = Array.from(this.options);
|
|
70
|
+
const byValue = options.filter((option) => option.value === value);
|
|
71
|
+
const matches = byValue.length
|
|
72
|
+
? byValue
|
|
73
|
+
: options.filter((option) => option.label.trim() === value);
|
|
74
|
+
const option = matches[0];
|
|
75
|
+
if (matches.length !== 1 || !option)
|
|
76
|
+
throw new Error("Option value/label must match exactly one option");
|
|
77
|
+
if (option.matches(":disabled"))
|
|
78
|
+
throw new Error("Option is disabled");
|
|
79
|
+
replacement = option.value;
|
|
80
|
+
}
|
|
81
|
+
this.focus({ preventScroll: true });
|
|
82
|
+
const root = this.getRootNode();
|
|
83
|
+
if (!this.isConnected || root.activeElement !== this) {
|
|
84
|
+
throw new Error("Could not focus element; fill was not sent");
|
|
85
|
+
}
|
|
86
|
+
if (!input && !textarea && !select) {
|
|
87
|
+
const selection = this.ownerDocument.getSelection();
|
|
88
|
+
if (!selection)
|
|
89
|
+
throw new Error("Could not select editable text");
|
|
90
|
+
const range = this.ownerDocument.createRange();
|
|
91
|
+
range.selectNodeContents(this);
|
|
92
|
+
selection.removeAllRanges();
|
|
93
|
+
selection.addRange(range);
|
|
94
|
+
return { kind: "contenteditable", expected: value };
|
|
95
|
+
}
|
|
96
|
+
const prototype = input
|
|
97
|
+
? HTMLInputElement.prototype
|
|
98
|
+
: textarea
|
|
99
|
+
? HTMLTextAreaElement.prototype
|
|
100
|
+
: HTMLSelectElement.prototype;
|
|
101
|
+
const setter = Object.getOwnPropertyDescriptor(prototype, "value")?.set;
|
|
102
|
+
if (!setter)
|
|
103
|
+
throw new Error("Form control has no native value setter");
|
|
104
|
+
if (input || textarea) {
|
|
105
|
+
const probe = this.cloneNode(false);
|
|
106
|
+
setter.call(probe, replacement);
|
|
107
|
+
if (probe.value !== replacement)
|
|
108
|
+
throw new Error("Value is not accepted by this control; fill was not sent");
|
|
109
|
+
}
|
|
110
|
+
setter.call(this, replacement);
|
|
111
|
+
this.dispatchEvent(new Event("input", { bubbles: true, composed: true }));
|
|
112
|
+
this.dispatchEvent(new Event("change", { bubbles: true }));
|
|
113
|
+
return { kind: "value", expected: replacement };
|
|
114
|
+
}
|
|
115
|
+
async function callElement(cdp, sessionId, objectId, declaration, value, signal) {
|
|
116
|
+
const response = asRecord(await cdp.send("Runtime.callFunctionOn", {
|
|
117
|
+
objectId,
|
|
118
|
+
functionDeclaration: declaration,
|
|
119
|
+
arguments: [{ value }],
|
|
120
|
+
returnByValue: true,
|
|
121
|
+
}, sessionId, signal));
|
|
122
|
+
if (response["exceptionDetails"]) {
|
|
123
|
+
const details = asRecord(response["exceptionDetails"]);
|
|
124
|
+
const exception = details["exception"]
|
|
125
|
+
? asRecord(details["exception"])
|
|
126
|
+
: {};
|
|
127
|
+
throw new Error(typeof exception["description"] === "string"
|
|
128
|
+
? exception["description"]
|
|
129
|
+
: "Fill failed; run open to inspect the control before retrying");
|
|
130
|
+
}
|
|
131
|
+
return asRecord(asRecord(response["result"])["value"], "fill result");
|
|
132
|
+
}
|
|
133
|
+
export async function fillElement(cdp, sessionId, elementRefs, target, value, signal) {
|
|
134
|
+
const backendNodeId = target.id !== undefined
|
|
135
|
+
? requireElementRef(elementRefs, target.id).backendNodeId
|
|
136
|
+
: await selectorBackendNode(cdp, sessionId, target.selector, signal);
|
|
137
|
+
await backendCenter(cdp, sessionId, backendNodeId, true, signal);
|
|
138
|
+
return withBackendObject(cdp, sessionId, backendNodeId, async (objectId) => {
|
|
139
|
+
const prepared = await callElement(cdp, sessionId, objectId, prepareFill.toString(), value, signal);
|
|
140
|
+
if (prepared["kind"] === "checked" && prepared["needsClick"] === true) {
|
|
141
|
+
await clickBackendNode(cdp, sessionId, backendNodeId, signal);
|
|
142
|
+
}
|
|
143
|
+
else if (prepared["kind"] === "contenteditable") {
|
|
144
|
+
const focused = await callElement(cdp, sessionId, objectId, `function() {
|
|
145
|
+
const selection = this.ownerDocument.getSelection();
|
|
146
|
+
return { ok: this.isConnected && this.getRootNode().activeElement === this &&
|
|
147
|
+
selection && this.contains(selection.anchorNode) && this.contains(selection.focusNode) };
|
|
148
|
+
}`, null, signal);
|
|
149
|
+
if (focused["ok"] !== true)
|
|
150
|
+
throw new Error("Focus or selection changed; fill was not sent");
|
|
151
|
+
if (value === "")
|
|
152
|
+
await pressKey(cdp, sessionId, "Backspace", signal);
|
|
153
|
+
else
|
|
154
|
+
await cdp.send("Input.insertText", { text: value }, sessionId, signal);
|
|
155
|
+
}
|
|
156
|
+
const verified = await callElement(cdp, sessionId, objectId, `function(expected) {
|
|
157
|
+
if (!this.isConnected) return { ok: false };
|
|
158
|
+
const toggle = this instanceof HTMLInputElement && (this.type === 'checkbox' || this.type === 'radio');
|
|
159
|
+
// Editable DOM has no value property. Native editing introduces NBSPs
|
|
160
|
+
// and block/BR nodes, so compare equivalent rendered text, not markup.
|
|
161
|
+
if (this.isContentEditable) {
|
|
162
|
+
const normalize = text => text.replace(/\\s+/g, ' ').trim();
|
|
163
|
+
return { ok: normalize(this.innerText) === normalize(expected) };
|
|
164
|
+
}
|
|
165
|
+
const actual = toggle ? this.checked : this.value;
|
|
166
|
+
return { ok: actual === expected && (!toggle || !this.indeterminate) };
|
|
167
|
+
}`, prepared["expected"], signal);
|
|
168
|
+
if (verified["ok"] !== true) {
|
|
169
|
+
throw new Error("Fill did not retain the requested value; run open to inspect the control before retrying");
|
|
170
|
+
}
|
|
171
|
+
return target.id === undefined
|
|
172
|
+
? "Filled selected element"
|
|
173
|
+
: `Filled element ${target.id}`;
|
|
174
|
+
}, signal);
|
|
175
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { CdpConnection } from "../types.js";
|
|
2
|
+
declare const MODIFIERS: {
|
|
3
|
+
readonly Alt: 1;
|
|
4
|
+
readonly Control: 2;
|
|
5
|
+
readonly Meta: 4;
|
|
6
|
+
readonly Shift: 8;
|
|
7
|
+
};
|
|
8
|
+
type Modifier = keyof typeof MODIFIERS;
|
|
9
|
+
interface Key {
|
|
10
|
+
key: string;
|
|
11
|
+
code: string;
|
|
12
|
+
windowsVirtualKeyCode: number;
|
|
13
|
+
text?: string;
|
|
14
|
+
}
|
|
15
|
+
export declare function parseKeyChord(chord: string): {
|
|
16
|
+
modifiers: Modifier[];
|
|
17
|
+
key: Key;
|
|
18
|
+
};
|
|
19
|
+
export declare function pressKey(cdp: CdpConnection, sessionId: string, chord: string, signal?: AbortSignal): Promise<string>;
|
|
20
|
+
export {};
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
const MODIFIERS = { Alt: 1, Control: 2, Meta: 4, Shift: 8 };
|
|
2
|
+
const ALIASES = {
|
|
3
|
+
Ctrl: "Control",
|
|
4
|
+
Cmd: "Meta",
|
|
5
|
+
Option: "Alt",
|
|
6
|
+
};
|
|
7
|
+
const NAMED_KEYS = {
|
|
8
|
+
Backspace: 8,
|
|
9
|
+
Tab: 9,
|
|
10
|
+
Enter: 13,
|
|
11
|
+
Escape: 27,
|
|
12
|
+
Space: 32,
|
|
13
|
+
PageUp: 33,
|
|
14
|
+
PageDown: 34,
|
|
15
|
+
End: 35,
|
|
16
|
+
Home: 36,
|
|
17
|
+
ArrowLeft: 37,
|
|
18
|
+
ArrowUp: 38,
|
|
19
|
+
ArrowRight: 39,
|
|
20
|
+
ArrowDown: 40,
|
|
21
|
+
Insert: 45,
|
|
22
|
+
Delete: 46,
|
|
23
|
+
};
|
|
24
|
+
const PUNCTUATION = {
|
|
25
|
+
"`~": { code: "Backquote", keyCode: 192 },
|
|
26
|
+
"-_": { code: "Minus", keyCode: 189 },
|
|
27
|
+
"=+": { code: "Equal", keyCode: 187 },
|
|
28
|
+
"[{": { code: "BracketLeft", keyCode: 219 },
|
|
29
|
+
"]}": { code: "BracketRight", keyCode: 221 },
|
|
30
|
+
"\\|": { code: "Backslash", keyCode: 220 },
|
|
31
|
+
";:": { code: "Semicolon", keyCode: 186 },
|
|
32
|
+
"'\"": { code: "Quote", keyCode: 222 },
|
|
33
|
+
",<": { code: "Comma", keyCode: 188 },
|
|
34
|
+
".>": { code: "Period", keyCode: 190 },
|
|
35
|
+
"/?": { code: "Slash", keyCode: 191 },
|
|
36
|
+
};
|
|
37
|
+
function keyDefinition(name, shift) {
|
|
38
|
+
const namedCode = Object.hasOwn(NAMED_KEYS, name)
|
|
39
|
+
? NAMED_KEYS[name]
|
|
40
|
+
: undefined;
|
|
41
|
+
if (namedCode !== undefined) {
|
|
42
|
+
return {
|
|
43
|
+
key: name === "Space" ? " " : name,
|
|
44
|
+
code: name,
|
|
45
|
+
windowsVirtualKeyCode: namedCode,
|
|
46
|
+
...(name === "Enter"
|
|
47
|
+
? { text: "\r" }
|
|
48
|
+
: name === "Space"
|
|
49
|
+
? { text: " " }
|
|
50
|
+
: {}),
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
if (/^F(?:[1-9]|1[0-2])$/.test(name)) {
|
|
54
|
+
return {
|
|
55
|
+
key: name,
|
|
56
|
+
code: name,
|
|
57
|
+
windowsVirtualKeyCode: 111 + Number(name.slice(1)),
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
const key = name === "Plus" ? "+" : name;
|
|
61
|
+
if ([...key].length !== 1) {
|
|
62
|
+
throw new Error(`Unknown key ${name}; use a character, Enter, Tab, Escape, arrows, or a chord such as Control+a`);
|
|
63
|
+
}
|
|
64
|
+
if (/^[a-z]$/i.test(key)) {
|
|
65
|
+
const text = shift ? key.toUpperCase() : key;
|
|
66
|
+
return {
|
|
67
|
+
key: text,
|
|
68
|
+
code: `Key${key.toUpperCase()}`,
|
|
69
|
+
windowsVirtualKeyCode: key.toUpperCase().charCodeAt(0),
|
|
70
|
+
text,
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
const digit = "0123456789".indexOf(key);
|
|
74
|
+
const shiftedDigit = ")!@#$%^&*(".indexOf(key);
|
|
75
|
+
if (digit >= 0 || shiftedDigit >= 0) {
|
|
76
|
+
const number = digit >= 0 ? digit : shiftedDigit;
|
|
77
|
+
const text = shift && digit >= 0 ? ")!@#$%^&*(".charAt(number) : key;
|
|
78
|
+
return {
|
|
79
|
+
key: text,
|
|
80
|
+
code: `Digit${number}`,
|
|
81
|
+
windowsVirtualKeyCode: 48 + number,
|
|
82
|
+
text,
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
for (const [characters, definition] of Object.entries(PUNCTUATION)) {
|
|
86
|
+
if (!characters.includes(key))
|
|
87
|
+
continue;
|
|
88
|
+
const text = shift ? characters.charAt(1) : key;
|
|
89
|
+
return {
|
|
90
|
+
key: text,
|
|
91
|
+
code: definition.code,
|
|
92
|
+
windowsVirtualKeyCode: definition.keyCode,
|
|
93
|
+
text,
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
return { key, code: "", windowsVirtualKeyCode: 0, text: key };
|
|
97
|
+
}
|
|
98
|
+
export function parseKeyChord(chord) {
|
|
99
|
+
const parts = chord === "+" ? ["Plus"] : chord.split("+").map((part) => part.trim());
|
|
100
|
+
const name = parts.pop();
|
|
101
|
+
if (!name)
|
|
102
|
+
throw new Error("Missing key; use Plus for + in a chord");
|
|
103
|
+
const modifiers = [];
|
|
104
|
+
for (const part of parts) {
|
|
105
|
+
const modifier = ALIASES[part] ?? part;
|
|
106
|
+
if (!Object.hasOwn(MODIFIERS, modifier))
|
|
107
|
+
throw new Error(`Unknown modifier ${part}; use Control, Alt, Shift, or Meta`);
|
|
108
|
+
const valid = modifier;
|
|
109
|
+
if (modifiers.includes(valid))
|
|
110
|
+
throw new Error(`Repeated modifier ${part}`);
|
|
111
|
+
modifiers.push(valid);
|
|
112
|
+
}
|
|
113
|
+
return { modifiers, key: keyDefinition(name, modifiers.includes("Shift")) };
|
|
114
|
+
}
|
|
115
|
+
export async function pressKey(cdp, sessionId, chord, signal) {
|
|
116
|
+
const { modifiers, key } = parseKeyChord(chord);
|
|
117
|
+
const held = [];
|
|
118
|
+
let mask = 0;
|
|
119
|
+
let failure;
|
|
120
|
+
try {
|
|
121
|
+
for (const modifier of modifiers) {
|
|
122
|
+
signal?.throwIfAborted();
|
|
123
|
+
const bit = MODIFIERS[modifier];
|
|
124
|
+
const keyCode = { Alt: 18, Control: 17, Meta: 91, Shift: 16 }[modifier];
|
|
125
|
+
const modifierKey = {
|
|
126
|
+
key: modifier,
|
|
127
|
+
code: `${modifier}Left`,
|
|
128
|
+
windowsVirtualKeyCode: keyCode,
|
|
129
|
+
};
|
|
130
|
+
mask |= bit;
|
|
131
|
+
held.push({ key: modifierKey, bit });
|
|
132
|
+
await cdp.send("Input.dispatchKeyEvent", { ...modifierKey, type: "rawKeyDown", modifiers: mask }, sessionId, signal);
|
|
133
|
+
}
|
|
134
|
+
signal?.throwIfAborted();
|
|
135
|
+
held.push({ key, bit: 0 });
|
|
136
|
+
const { text, ...identity } = key;
|
|
137
|
+
const insertsText = text !== undefined && (mask & ~MODIFIERS.Shift) === 0;
|
|
138
|
+
await cdp.send("Input.dispatchKeyEvent", {
|
|
139
|
+
...identity,
|
|
140
|
+
type: insertsText ? "keyDown" : "rawKeyDown",
|
|
141
|
+
modifiers: mask,
|
|
142
|
+
...(insertsText ? { text } : {}),
|
|
143
|
+
}, sessionId, signal);
|
|
144
|
+
}
|
|
145
|
+
catch (error) {
|
|
146
|
+
failure = error;
|
|
147
|
+
}
|
|
148
|
+
finally {
|
|
149
|
+
for (const heldKey of held.reverse()) {
|
|
150
|
+
mask &= ~heldKey.bit;
|
|
151
|
+
const { text: _text, ...identity } = heldKey.key;
|
|
152
|
+
try {
|
|
153
|
+
await cdp.send("Input.dispatchKeyEvent", { ...identity, type: "keyUp", modifiers: mask }, sessionId);
|
|
154
|
+
}
|
|
155
|
+
catch (error) {
|
|
156
|
+
failure = failure
|
|
157
|
+
? new AggregateError([failure, error], "Key press failed; key release also failed")
|
|
158
|
+
: error;
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
if (failure)
|
|
163
|
+
throw failure;
|
|
164
|
+
signal?.throwIfAborted();
|
|
165
|
+
return `Pressed ${chord}`;
|
|
166
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { CdpConnection } from "../types.js";
|
|
2
|
+
export type WaitCondition = {
|
|
3
|
+
selector: string;
|
|
4
|
+
} | {
|
|
5
|
+
text: string;
|
|
6
|
+
} | {
|
|
7
|
+
url_includes: string;
|
|
8
|
+
};
|
|
9
|
+
export declare function waitForCondition(cdp: CdpConnection, sessionId: string, condition: WaitCondition, timeoutMs: number, signal?: AbortSignal): Promise<string>;
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import { sleep } from "../discovery.js";
|
|
2
|
+
import { evaluate } from "../evaluate.js";
|
|
3
|
+
import { errorMessage } from "../types.js";
|
|
4
|
+
const POLL_INTERVAL_MS = 100;
|
|
5
|
+
const SUMMARY_LENGTH = 120;
|
|
6
|
+
const NAVIGATION_CONTEXT_ERRORS = [
|
|
7
|
+
/(?:^|: )Execution context was destroyed\b/i,
|
|
8
|
+
/(?:^|: )Cannot find context with specified id\b/i,
|
|
9
|
+
/(?:^|: )Cannot find (?:default )?execution context\b/i,
|
|
10
|
+
/(?:^|: )No execution context with given id\b/i,
|
|
11
|
+
];
|
|
12
|
+
function conditionDetails(condition) {
|
|
13
|
+
if ("selector" in condition) {
|
|
14
|
+
return {
|
|
15
|
+
expression: `document.querySelector(${JSON.stringify(condition.selector)}) !== null`,
|
|
16
|
+
label: `selector ${summary(condition.selector)}`,
|
|
17
|
+
matched: `Matched selector ${summary(condition.selector)}`,
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
if ("text" in condition) {
|
|
21
|
+
return {
|
|
22
|
+
expression: `document.body?.innerText.includes(${JSON.stringify(condition.text)}) ?? false`,
|
|
23
|
+
label: `text ${summary(condition.text)}`,
|
|
24
|
+
matched: `Matched text ${summary(condition.text)}`,
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
return {
|
|
28
|
+
expression: `location.href.includes(${JSON.stringify(condition.url_includes)})`,
|
|
29
|
+
label: `URL containing ${summary(condition.url_includes)}`,
|
|
30
|
+
matched: `Matched URL containing ${summary(condition.url_includes)}`,
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
function summary(value) {
|
|
34
|
+
const normalized = value.replace(/\s+/g, " ").trim();
|
|
35
|
+
const bounded = normalized.length > SUMMARY_LENGTH
|
|
36
|
+
? `${normalized.slice(0, SUMMARY_LENGTH - 3)}...`
|
|
37
|
+
: normalized;
|
|
38
|
+
return JSON.stringify(bounded);
|
|
39
|
+
}
|
|
40
|
+
function isNavigationContextError(error) {
|
|
41
|
+
const message = errorMessage(error);
|
|
42
|
+
return NAVIGATION_CONTEXT_ERRORS.some((pattern) => pattern.test(message));
|
|
43
|
+
}
|
|
44
|
+
export async function waitForCondition(cdp, sessionId, condition, timeoutMs, signal) {
|
|
45
|
+
const details = conditionDetails(condition);
|
|
46
|
+
const timeoutError = new Error(`Timed out after ${timeoutMs}ms waiting for ${details.label}`);
|
|
47
|
+
const deadline = Date.now() + timeoutMs;
|
|
48
|
+
const controller = new AbortController();
|
|
49
|
+
let timedOut = false;
|
|
50
|
+
const abort = () => {
|
|
51
|
+
controller.abort(signal?.reason ?? new Error("Wait aborted"));
|
|
52
|
+
};
|
|
53
|
+
if (signal?.aborted) {
|
|
54
|
+
abort();
|
|
55
|
+
}
|
|
56
|
+
else {
|
|
57
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
58
|
+
}
|
|
59
|
+
const timer = setTimeout(() => {
|
|
60
|
+
timedOut = true;
|
|
61
|
+
controller.abort(timeoutError);
|
|
62
|
+
}, timeoutMs);
|
|
63
|
+
try {
|
|
64
|
+
while (Date.now() < deadline) {
|
|
65
|
+
try {
|
|
66
|
+
const matched = await evaluate(cdp, sessionId, details.expression, controller.signal);
|
|
67
|
+
if (matched === true)
|
|
68
|
+
return details.matched;
|
|
69
|
+
if (matched !== false) {
|
|
70
|
+
throw new Error("Wait condition returned a non-boolean result");
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
catch (error) {
|
|
74
|
+
if (controller.signal.aborted)
|
|
75
|
+
throw controller.signal.reason;
|
|
76
|
+
if (!isNavigationContextError(error))
|
|
77
|
+
throw error;
|
|
78
|
+
}
|
|
79
|
+
const remaining = deadline - Date.now();
|
|
80
|
+
if (remaining <= 0)
|
|
81
|
+
break;
|
|
82
|
+
await sleep(Math.min(POLL_INTERVAL_MS, remaining), controller.signal);
|
|
83
|
+
}
|
|
84
|
+
throw timeoutError;
|
|
85
|
+
}
|
|
86
|
+
catch (error) {
|
|
87
|
+
if (timedOut)
|
|
88
|
+
throw timeoutError;
|
|
89
|
+
throw error;
|
|
90
|
+
}
|
|
91
|
+
finally {
|
|
92
|
+
clearTimeout(timer);
|
|
93
|
+
signal?.removeEventListener("abort", abort);
|
|
94
|
+
}
|
|
95
|
+
}
|
package/dist/src/cdp/pages.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
1
|
import type { CdpConnection, PageInfo } from "./types.js";
|
|
2
|
-
export declare function
|
|
2
|
+
export declare function getPageTargets(cdp: CdpConnection, signal?: AbortSignal): Promise<PageInfo[]>;
|
|
3
|
+
export declare function getDisplayedPages(targets: PageInfo[]): PageInfo[];
|
|
3
4
|
export declare function waitForOpenedTarget(cdp: CdpConnection, targetId: string, requestedUrl: string, timeout?: number, signal?: AbortSignal): Promise<PageInfo>;
|
package/dist/src/cdp/pages.js
CHANGED
|
@@ -7,17 +7,21 @@ function pageInfo(value) {
|
|
|
7
7
|
title: typeof record["title"] === "string" ? record["title"] : "",
|
|
8
8
|
url: asString(record["url"], "target URL"),
|
|
9
9
|
...(typeof record["type"] === "string" ? { type: record["type"] } : {}),
|
|
10
|
+
...(typeof record["openerId"] === "string"
|
|
11
|
+
? { openerId: record["openerId"] }
|
|
12
|
+
: {}),
|
|
10
13
|
};
|
|
11
14
|
}
|
|
12
|
-
export async function
|
|
15
|
+
export async function getPageTargets(cdp, signal) {
|
|
13
16
|
const response = asRecord(await cdp.send("Target.getTargets", {}, undefined, signal), "Target.getTargets response");
|
|
14
17
|
const targetInfos = response["targetInfos"];
|
|
15
18
|
if (!Array.isArray(targetInfos)) {
|
|
16
19
|
throw new Error("Target.getTargets response has no targetInfos");
|
|
17
20
|
}
|
|
18
|
-
return targetInfos
|
|
19
|
-
|
|
20
|
-
|
|
21
|
+
return targetInfos.map(pageInfo).filter((target) => target.type === "page");
|
|
22
|
+
}
|
|
23
|
+
export function getDisplayedPages(targets) {
|
|
24
|
+
return targets.filter((target) => !target.url.startsWith("chrome://"));
|
|
21
25
|
}
|
|
22
26
|
export async function waitForOpenedTarget(cdp, targetId, requestedUrl, timeout = 5_000, signal) {
|
|
23
27
|
if (requestedUrl === "about:blank") {
|
|
@@ -7,17 +7,23 @@ export interface ActiveTab {
|
|
|
7
7
|
refId: string;
|
|
8
8
|
}
|
|
9
9
|
export declare class BrowserCdpSession {
|
|
10
|
+
private closing;
|
|
10
11
|
private root;
|
|
11
12
|
private rootPending;
|
|
13
|
+
private readonly ownerId;
|
|
14
|
+
private readonly ownershipDirectory;
|
|
12
15
|
private readonly tabs;
|
|
13
16
|
private readonly tabPromises;
|
|
17
|
+
constructor(ownerId: string, ownershipDirectory: string);
|
|
14
18
|
pages(signal?: AbortSignal): Promise<PageInfo[]>;
|
|
15
19
|
open(url: string, signal?: AbortSignal): Promise<{
|
|
16
20
|
refId: string;
|
|
17
21
|
}>;
|
|
22
|
+
show(refId: string, signal?: AbortSignal): Promise<string>;
|
|
23
|
+
closeTab(refId: string, signal?: AbortSignal): Promise<string>;
|
|
18
24
|
withTab<T>(refId: string, signal: AbortSignal | undefined, action: (tab: ActiveTab) => Promise<T>): Promise<T>;
|
|
19
25
|
stop(refId?: string): Promise<void>;
|
|
20
|
-
close(): void
|
|
26
|
+
close(): Promise<void>;
|
|
21
27
|
private rootConnection;
|
|
22
28
|
private connectTab;
|
|
23
29
|
private stopPendingTab;
|