@abubakarsiddiik/substrate 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/README.md +171 -2
- package/dist/affordances.d.ts +56 -0
- package/dist/affordances.d.ts.map +1 -0
- package/dist/affordances.js +201 -0
- package/dist/affordances.js.map +1 -0
- package/dist/chrome.d.ts +9 -0
- package/dist/chrome.d.ts.map +1 -0
- package/dist/chrome.js +24 -0
- package/dist/chrome.js.map +1 -0
- package/dist/engine.d.ts +132 -0
- package/dist/engine.d.ts.map +1 -0
- package/dist/engine.js +11 -0
- package/dist/engine.js.map +1 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +9 -0
- package/dist/index.js.map +1 -0
- package/dist/playwright-engine.d.ts +112 -0
- package/dist/playwright-engine.d.ts.map +1 -0
- package/dist/playwright-engine.js +825 -0
- package/dist/playwright-engine.js.map +1 -0
- package/dist/policy.d.ts +62 -0
- package/dist/policy.d.ts.map +1 -0
- package/dist/policy.js +182 -0
- package/dist/policy.js.map +1 -0
- package/dist/reaper.d.ts +22 -0
- package/dist/reaper.d.ts.map +1 -0
- package/dist/reaper.js +53 -0
- package/dist/reaper.js.map +1 -0
- package/dist/refs.d.ts +71 -0
- package/dist/refs.d.ts.map +1 -0
- package/dist/refs.js +160 -0
- package/dist/refs.js.map +1 -0
- package/dist/substrate.d.ts +164 -0
- package/dist/substrate.d.ts.map +1 -0
- package/dist/substrate.js +400 -0
- package/dist/substrate.js.map +1 -0
- package/package.json +37 -3
|
@@ -0,0 +1,825 @@
|
|
|
1
|
+
import { mkdtemp } from "node:fs/promises";
|
|
2
|
+
import { tmpdir } from "node:os";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { chromium } from "playwright-core";
|
|
5
|
+
import { EngineError, } from "./engine.js";
|
|
6
|
+
/** A body larger than this is not worth carrying into a trace. */
|
|
7
|
+
const MAX_BODY_CHARS = 256 * 1024;
|
|
8
|
+
export class PlaywrightEngine {
|
|
9
|
+
browser;
|
|
10
|
+
page;
|
|
11
|
+
cdp;
|
|
12
|
+
timeoutMs;
|
|
13
|
+
doc = 0;
|
|
14
|
+
v = 0;
|
|
15
|
+
network = new Map();
|
|
16
|
+
networkOrder = [];
|
|
17
|
+
networkSeqOf = new Map();
|
|
18
|
+
networkSeq = 0;
|
|
19
|
+
requestCaptures = new Map();
|
|
20
|
+
responseCaptures = new Map();
|
|
21
|
+
downloadStarted = false;
|
|
22
|
+
downloadPromise;
|
|
23
|
+
lastDownload;
|
|
24
|
+
downloadWaiters = [];
|
|
25
|
+
constructor(browser, page, cdp, timeoutMs) {
|
|
26
|
+
this.browser = browser;
|
|
27
|
+
this.page = page;
|
|
28
|
+
this.cdp = cdp;
|
|
29
|
+
this.timeoutMs = timeoutMs;
|
|
30
|
+
}
|
|
31
|
+
static async launch(options) {
|
|
32
|
+
const args = [...(options.launchArgs ?? [])];
|
|
33
|
+
if (options.instanceId !== undefined) {
|
|
34
|
+
args.push(`--portolan-instance=${options.instanceId}`);
|
|
35
|
+
}
|
|
36
|
+
const browser = await chromium.launch({
|
|
37
|
+
executablePath: options.executablePath,
|
|
38
|
+
headless: options.headless ?? true,
|
|
39
|
+
args,
|
|
40
|
+
});
|
|
41
|
+
const context = await browser.newContext({ acceptDownloads: true });
|
|
42
|
+
const page = await context.newPage();
|
|
43
|
+
const cdp = await context.newCDPSession(page);
|
|
44
|
+
const downloadDir = await mkdtemp(join(tmpdir(), "portolan-download-"));
|
|
45
|
+
const engine = new PlaywrightEngine(browser, page, cdp, options.timeoutMs ?? 30_000);
|
|
46
|
+
page.on("framenavigated", (frame) => {
|
|
47
|
+
if (frame === page.mainFrame())
|
|
48
|
+
engine.doc += 1;
|
|
49
|
+
});
|
|
50
|
+
page.on("download", (download) => {
|
|
51
|
+
engine.downloadStarted = true;
|
|
52
|
+
engine.downloadPromise = (async () => {
|
|
53
|
+
const filename = download.suggestedFilename();
|
|
54
|
+
const safe = filename.replace(/[^a-zA-Z0-9._-]/g, "_");
|
|
55
|
+
const target = join(downloadDir, `${Date.now()}-${safe}`);
|
|
56
|
+
await download.saveAs(target);
|
|
57
|
+
const info = { path: target, filename };
|
|
58
|
+
engine.lastDownload = info;
|
|
59
|
+
for (const resolve of engine.downloadWaiters.splice(0))
|
|
60
|
+
resolve(info);
|
|
61
|
+
return info;
|
|
62
|
+
})();
|
|
63
|
+
});
|
|
64
|
+
void cdp.send("Network.enable").catch(() => { });
|
|
65
|
+
cdp.on("Network.requestWillBeSent", (event) => {
|
|
66
|
+
engine.recordRequest(event);
|
|
67
|
+
});
|
|
68
|
+
cdp.on("Network.responseReceived", (event) => {
|
|
69
|
+
engine.recordResponse(event);
|
|
70
|
+
});
|
|
71
|
+
cdp.on("Network.loadingFinished", (event) => {
|
|
72
|
+
engine.captureBody(event);
|
|
73
|
+
});
|
|
74
|
+
return engine;
|
|
75
|
+
}
|
|
76
|
+
async navigate(url) {
|
|
77
|
+
try {
|
|
78
|
+
const response = await this.page.goto(url, {
|
|
79
|
+
waitUntil: "domcontentloaded",
|
|
80
|
+
timeout: this.timeoutMs,
|
|
81
|
+
});
|
|
82
|
+
return {
|
|
83
|
+
url: this.page.url(),
|
|
84
|
+
title: await this.page.title(),
|
|
85
|
+
status: response?.status() ?? null,
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
catch (error) {
|
|
89
|
+
throw new EngineError("navigation_failed", `could not navigate to ${url}`, {
|
|
90
|
+
cause: error,
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
async snapshot() {
|
|
95
|
+
const [ax, dom] = await Promise.all([
|
|
96
|
+
this.cdp.send("Accessibility.getFullAXTree"),
|
|
97
|
+
this.cdp.send("DOMSnapshot.captureSnapshot", {
|
|
98
|
+
computedStyles: ["display", "visibility", "opacity"],
|
|
99
|
+
includeDOMRects: true,
|
|
100
|
+
}),
|
|
101
|
+
]);
|
|
102
|
+
const index = indexSnapshot(dom);
|
|
103
|
+
return {
|
|
104
|
+
doc: this.doc,
|
|
105
|
+
v: this.v,
|
|
106
|
+
url: this.page.url(),
|
|
107
|
+
title: await this.page.title(),
|
|
108
|
+
nodes: ax.nodes.map((node) => toSemanticNode(node, index.layout, index.attributes)),
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
async dispatch(action) {
|
|
112
|
+
const beforeUrl = this.page.url();
|
|
113
|
+
const beforeDoc = this.doc;
|
|
114
|
+
const networkMark = this.networkSeq;
|
|
115
|
+
this.downloadStarted = false;
|
|
116
|
+
this.downloadPromise = undefined;
|
|
117
|
+
this.lastDownload = undefined;
|
|
118
|
+
switch (action.do) {
|
|
119
|
+
case "click":
|
|
120
|
+
await this.settleAction(() => this.click(action.backendNodeId));
|
|
121
|
+
break;
|
|
122
|
+
case "fill":
|
|
123
|
+
await this.fill(action.backendNodeId, action.value);
|
|
124
|
+
break;
|
|
125
|
+
case "select":
|
|
126
|
+
await this.select(action.backendNodeId, action.value);
|
|
127
|
+
break;
|
|
128
|
+
case "check":
|
|
129
|
+
await this.settleAction(() => this.setChecked(action.backendNodeId, true));
|
|
130
|
+
break;
|
|
131
|
+
case "uncheck":
|
|
132
|
+
await this.settleAction(() => this.setChecked(action.backendNodeId, false));
|
|
133
|
+
break;
|
|
134
|
+
case "press":
|
|
135
|
+
if (action.backendNodeId !== undefined) {
|
|
136
|
+
await this.focus(action.backendNodeId);
|
|
137
|
+
}
|
|
138
|
+
await this.settleAction(() => this.page.keyboard.press(action.key));
|
|
139
|
+
break;
|
|
140
|
+
}
|
|
141
|
+
await this.finishNetwork(networkMark);
|
|
142
|
+
this.v += 1;
|
|
143
|
+
const effects = this.effectsSince(networkMark, action, beforeUrl, beforeDoc);
|
|
144
|
+
// A site often fetches a PDF and then clicks a blob link, so the download
|
|
145
|
+
// starts after the action returns. Wait when the action fetched something
|
|
146
|
+
// that looks like a file, not on every click.
|
|
147
|
+
const downloadLike = effects.some((effect) => effect.kind === "network" &&
|
|
148
|
+
(effect.mime_type?.includes("pdf") === true ||
|
|
149
|
+
effect.mime_type?.includes("octet-stream") === true ||
|
|
150
|
+
/\/pdf(\?|$)/.test(effect.url)));
|
|
151
|
+
const download = this.downloadStarted || downloadLike ? await this.waitForDownload(3_000) : undefined;
|
|
152
|
+
return {
|
|
153
|
+
ok: true,
|
|
154
|
+
doc: this.doc,
|
|
155
|
+
v: this.v,
|
|
156
|
+
url: this.page.url(),
|
|
157
|
+
title: await this.page.title(),
|
|
158
|
+
effects,
|
|
159
|
+
...(download !== undefined ? { download } : {}),
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
async evaluate(expression) {
|
|
163
|
+
try {
|
|
164
|
+
return (await this.page.evaluate(expression));
|
|
165
|
+
}
|
|
166
|
+
catch (error) {
|
|
167
|
+
throw new EngineError("evaluate_failed", "page evaluation failed", {
|
|
168
|
+
cause: error,
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
async screenshot() {
|
|
173
|
+
return this.page.screenshot({ type: "png" });
|
|
174
|
+
}
|
|
175
|
+
async close() {
|
|
176
|
+
try {
|
|
177
|
+
await this.browser.close();
|
|
178
|
+
}
|
|
179
|
+
catch {
|
|
180
|
+
// Closing an already-closed browser is a no-op.
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
async resolveObject(backendNodeId) {
|
|
184
|
+
let resolved;
|
|
185
|
+
try {
|
|
186
|
+
resolved = (await this.cdp.send("DOM.resolveNode", {
|
|
187
|
+
backendNodeId,
|
|
188
|
+
}));
|
|
189
|
+
}
|
|
190
|
+
catch (error) {
|
|
191
|
+
throw new EngineError("not_found", `no DOM node with backend id ${backendNodeId}`, {
|
|
192
|
+
cause: error,
|
|
193
|
+
});
|
|
194
|
+
}
|
|
195
|
+
const objectId = resolved.object.objectId;
|
|
196
|
+
if (objectId === undefined) {
|
|
197
|
+
throw new EngineError("not_found", `no DOM node with backend id ${backendNodeId}`);
|
|
198
|
+
}
|
|
199
|
+
return objectId;
|
|
200
|
+
}
|
|
201
|
+
async callOn(objectId, functionDeclaration, args) {
|
|
202
|
+
const response = (await this.cdp.send("Runtime.callFunctionOn", {
|
|
203
|
+
objectId,
|
|
204
|
+
functionDeclaration,
|
|
205
|
+
arguments: args,
|
|
206
|
+
returnByValue: true,
|
|
207
|
+
}));
|
|
208
|
+
if (response.exceptionDetails !== undefined) {
|
|
209
|
+
throw new EngineError("evaluate_failed", response.exceptionDetails.text ?? "callFunctionOn failed");
|
|
210
|
+
}
|
|
211
|
+
return response.result.value;
|
|
212
|
+
}
|
|
213
|
+
effectsSince(mark, action, beforeUrl, beforeDoc) {
|
|
214
|
+
const effects = [];
|
|
215
|
+
if (this.doc !== beforeDoc || this.page.url() !== beforeUrl) {
|
|
216
|
+
effects.push({
|
|
217
|
+
kind: "navigation",
|
|
218
|
+
from: beforeUrl,
|
|
219
|
+
to: this.page.url(),
|
|
220
|
+
doc: this.doc,
|
|
221
|
+
});
|
|
222
|
+
}
|
|
223
|
+
for (const requestId of this.networkOrder) {
|
|
224
|
+
const seq = this.networkSeqOf.get(requestId);
|
|
225
|
+
if (seq === undefined || seq < mark)
|
|
226
|
+
continue;
|
|
227
|
+
const effect = this.network.get(requestId);
|
|
228
|
+
if (effect !== undefined)
|
|
229
|
+
effects.push(effect);
|
|
230
|
+
}
|
|
231
|
+
if (action.do === "fill" || action.do === "select") {
|
|
232
|
+
effects.push({
|
|
233
|
+
kind: "value",
|
|
234
|
+
backendNodeId: action.backendNodeId,
|
|
235
|
+
value: action.value,
|
|
236
|
+
});
|
|
237
|
+
}
|
|
238
|
+
return effects;
|
|
239
|
+
}
|
|
240
|
+
recordRequest(event) {
|
|
241
|
+
const effect = {
|
|
242
|
+
kind: "network",
|
|
243
|
+
method: event.request.method,
|
|
244
|
+
url: event.request.url,
|
|
245
|
+
};
|
|
246
|
+
if (event.type !== undefined)
|
|
247
|
+
effect.resource_type = event.type;
|
|
248
|
+
if (event.request.postData !== undefined) {
|
|
249
|
+
const body = parseJsonBody(event.request.postData);
|
|
250
|
+
if (body !== undefined)
|
|
251
|
+
effect.request_body = body;
|
|
252
|
+
}
|
|
253
|
+
else if (event.request.hasPostData === true) {
|
|
254
|
+
this.captureRequestBody(event.requestId, effect);
|
|
255
|
+
}
|
|
256
|
+
this.network.set(event.requestId, effect);
|
|
257
|
+
this.networkOrder.push(event.requestId);
|
|
258
|
+
this.networkSeqOf.set(event.requestId, this.networkSeq);
|
|
259
|
+
this.networkSeq += 1;
|
|
260
|
+
if (this.networkOrder.length > 500) {
|
|
261
|
+
const oldest = this.networkOrder.shift();
|
|
262
|
+
if (oldest !== undefined) {
|
|
263
|
+
this.network.delete(oldest);
|
|
264
|
+
this.networkSeqOf.delete(oldest);
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
recordResponse(event) {
|
|
269
|
+
const effect = this.network.get(event.requestId);
|
|
270
|
+
if (effect === undefined)
|
|
271
|
+
return;
|
|
272
|
+
effect.status = event.response.status;
|
|
273
|
+
if (event.response.mimeType !== undefined)
|
|
274
|
+
effect.mime_type = event.response.mimeType;
|
|
275
|
+
}
|
|
276
|
+
/**
|
|
277
|
+
* CDP only inlines a small request body in `requestWillBeSent`; a larger one
|
|
278
|
+
* has to be asked for by id. This is the body a lifted write needs to replay.
|
|
279
|
+
*/
|
|
280
|
+
captureRequestBody(requestId, effect) {
|
|
281
|
+
const capture = (async () => {
|
|
282
|
+
try {
|
|
283
|
+
const result = (await this.cdp.send("Network.getRequestPostData", {
|
|
284
|
+
requestId,
|
|
285
|
+
}));
|
|
286
|
+
const body = parseJsonBody(result.postData);
|
|
287
|
+
if (body !== undefined)
|
|
288
|
+
effect.request_body = body;
|
|
289
|
+
}
|
|
290
|
+
catch {
|
|
291
|
+
// The body was already evicted; the effect is still attributed.
|
|
292
|
+
}
|
|
293
|
+
})();
|
|
294
|
+
this.requestCaptures.set(requestId, capture);
|
|
295
|
+
void capture.finally(() => {
|
|
296
|
+
this.requestCaptures.delete(requestId);
|
|
297
|
+
});
|
|
298
|
+
}
|
|
299
|
+
/**
|
|
300
|
+
* Fetch a JSON response body while CDP still holds it.
|
|
301
|
+
*
|
|
302
|
+
* `loadingFinished` is the last moment the body is guaranteed to be
|
|
303
|
+
* available, so the capture starts there and the action awaits it before
|
|
304
|
+
* returning effects.
|
|
305
|
+
*/
|
|
306
|
+
captureBody(event) {
|
|
307
|
+
const effect = this.network.get(event.requestId);
|
|
308
|
+
if (effect === undefined || !isJsonMime(effect.mime_type))
|
|
309
|
+
return;
|
|
310
|
+
const capture = (async () => {
|
|
311
|
+
try {
|
|
312
|
+
const result = (await this.cdp.send("Network.getResponseBody", {
|
|
313
|
+
requestId: event.requestId,
|
|
314
|
+
}));
|
|
315
|
+
const text = result.base64Encoded
|
|
316
|
+
? Buffer.from(result.body, "base64").toString("utf8")
|
|
317
|
+
: result.body;
|
|
318
|
+
const body = parseJsonBody(text);
|
|
319
|
+
if (body !== undefined)
|
|
320
|
+
effect.response_body = body;
|
|
321
|
+
}
|
|
322
|
+
catch {
|
|
323
|
+
// Redirects and evicted bodies have no readable body; status remains.
|
|
324
|
+
}
|
|
325
|
+
})();
|
|
326
|
+
this.responseCaptures.set(event.requestId, capture);
|
|
327
|
+
void capture.finally(() => {
|
|
328
|
+
this.responseCaptures.delete(event.requestId);
|
|
329
|
+
});
|
|
330
|
+
}
|
|
331
|
+
/** Wait for the body captures that belong to the action starting at `mark`. */
|
|
332
|
+
async finishNetwork(mark) {
|
|
333
|
+
const pending = [];
|
|
334
|
+
for (const requestId of this.networkOrder) {
|
|
335
|
+
const seq = this.networkSeqOf.get(requestId);
|
|
336
|
+
if (seq === undefined || seq < mark)
|
|
337
|
+
continue;
|
|
338
|
+
const request = this.requestCaptures.get(requestId);
|
|
339
|
+
if (request !== undefined)
|
|
340
|
+
pending.push(request);
|
|
341
|
+
const response = this.responseCaptures.get(requestId);
|
|
342
|
+
if (response !== undefined)
|
|
343
|
+
pending.push(response);
|
|
344
|
+
}
|
|
345
|
+
await Promise.all(pending);
|
|
346
|
+
}
|
|
347
|
+
/** Focus a node before a key press. */
|
|
348
|
+
async focus(backendNodeId) {
|
|
349
|
+
const objectId = await this.resolveObject(backendNodeId);
|
|
350
|
+
await this.assertEnabled(objectId, backendNodeId);
|
|
351
|
+
try {
|
|
352
|
+
await this.callOn(objectId, `function () {
|
|
353
|
+
if (typeof this.scrollIntoView === "function") {
|
|
354
|
+
this.scrollIntoView({ block: "center", inline: "center" });
|
|
355
|
+
}
|
|
356
|
+
if (typeof this.focus === "function") {
|
|
357
|
+
this.focus();
|
|
358
|
+
}
|
|
359
|
+
}`, []);
|
|
360
|
+
}
|
|
361
|
+
catch {
|
|
362
|
+
// A node without focus support still receives the key press.
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
/**
|
|
366
|
+
* A disabled control is not clickable.
|
|
367
|
+
*
|
|
368
|
+
* Tailwind's `disabled:pointer-events-none` makes the hit-test land on the
|
|
369
|
+
* element behind the button, so without this check a disabled button is
|
|
370
|
+
* reported as "covered" by an opaque node id. The caller needs to know the
|
|
371
|
+
* control is disabled, not that something covers it.
|
|
372
|
+
*/
|
|
373
|
+
async assertEnabled(objectId, backendNodeId) {
|
|
374
|
+
const disabled = await this.callOn(objectId, `function () {
|
|
375
|
+
if ("disabled" in this && this.disabled === true) return true;
|
|
376
|
+
return this.getAttribute?.("aria-disabled") === "true";
|
|
377
|
+
}`, []);
|
|
378
|
+
if (disabled) {
|
|
379
|
+
throw new EngineError("disabled", `node ${backendNodeId} is disabled`);
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
async click(backendNodeId) {
|
|
383
|
+
const objectId = await this.resolveObject(backendNodeId);
|
|
384
|
+
try {
|
|
385
|
+
// Centre the node, not just bring it into view: a button at the bottom
|
|
386
|
+
// edge has its centre outside the viewport, and the hit-test then lands
|
|
387
|
+
// on whatever is at the clamped point.
|
|
388
|
+
await this.callOn(objectId, `function () {
|
|
389
|
+
if (typeof this.scrollIntoView === "function") {
|
|
390
|
+
this.scrollIntoView({ block: "center", inline: "center" });
|
|
391
|
+
}
|
|
392
|
+
}`, []);
|
|
393
|
+
}
|
|
394
|
+
catch {
|
|
395
|
+
// A node without a layout box reports a zero rect below.
|
|
396
|
+
}
|
|
397
|
+
const rect = await this.callOn(objectId, `function () {
|
|
398
|
+
const r = this.getBoundingClientRect();
|
|
399
|
+
return { x: r.x, y: r.y, width: r.width, height: r.height };
|
|
400
|
+
}`, []);
|
|
401
|
+
if (rect.width === 0 || rect.height === 0) {
|
|
402
|
+
throw new EngineError("not_interactive", `node ${backendNodeId} has no layout box`, {
|
|
403
|
+
details: { reason: "no_layout_box" },
|
|
404
|
+
});
|
|
405
|
+
}
|
|
406
|
+
await this.assertEnabled(objectId, backendNodeId);
|
|
407
|
+
const viewport = await this.evaluate("({ width: window.innerWidth, height: window.innerHeight, scrollX: window.scrollX, scrollY: window.scrollY })");
|
|
408
|
+
// A button at the bottom edge cannot be centred when the page is already
|
|
409
|
+
// scrolled to the end. Click the centre of the visible part instead.
|
|
410
|
+
const left = Math.max(0, rect.x);
|
|
411
|
+
const top = Math.max(0, rect.y);
|
|
412
|
+
const right = Math.min(viewport.width, rect.x + rect.width);
|
|
413
|
+
const bottom = Math.min(viewport.height, rect.y + rect.height);
|
|
414
|
+
if (right <= left || bottom <= top) {
|
|
415
|
+
throw new EngineError("not_interactive", `node ${backendNodeId} is outside the viewport`, {
|
|
416
|
+
details: { reason: "outside_viewport" },
|
|
417
|
+
});
|
|
418
|
+
}
|
|
419
|
+
const x = Math.round((left + right) / 2);
|
|
420
|
+
const y = Math.round((top + bottom) / 2);
|
|
421
|
+
let hit;
|
|
422
|
+
try {
|
|
423
|
+
// DOM.getNodeForLocation takes document coordinates; the mouse takes
|
|
424
|
+
// viewport coordinates. Without the scroll offset a scrolled page
|
|
425
|
+
// reports the node above the target as the blocker.
|
|
426
|
+
hit = (await this.cdp.send("DOM.getNodeForLocation", {
|
|
427
|
+
x: x + viewport.scrollX,
|
|
428
|
+
y: y + viewport.scrollY,
|
|
429
|
+
includeUserAgentShadowDOM: false,
|
|
430
|
+
}));
|
|
431
|
+
}
|
|
432
|
+
catch (error) {
|
|
433
|
+
throw new EngineError("not_interactive", `hit-test failed at ${x},${y}: ${error instanceof Error ? error.message : String(error)}`, { cause: error, details: { x, y, reason: "hit_test_failed" } });
|
|
434
|
+
}
|
|
435
|
+
const blocker = hit.backendNodeId;
|
|
436
|
+
if (blocker !== undefined && blocker !== backendNodeId) {
|
|
437
|
+
const related = (await this.contains(backendNodeId, blocker)) ||
|
|
438
|
+
(await this.ancestorsOf(backendNodeId)).has(blocker);
|
|
439
|
+
if (!related) {
|
|
440
|
+
const info = await this.describeBackend(blocker);
|
|
441
|
+
throw new EngineError("not_interactive", `node ${backendNodeId} is covered by ${blocker}`, {
|
|
442
|
+
details: {
|
|
443
|
+
blockerBackendNodeId: blocker,
|
|
444
|
+
...(info.tag !== undefined ? { blockerTag: info.tag } : {}),
|
|
445
|
+
...(info.domId !== undefined ? { blockerDomId: info.domId } : {}),
|
|
446
|
+
...(info.className !== undefined ? { blockerClass: info.className } : {}),
|
|
447
|
+
...(info.text !== undefined ? { blockerText: info.text } : {}),
|
|
448
|
+
},
|
|
449
|
+
});
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
await this.page.mouse.click(x, y);
|
|
453
|
+
}
|
|
454
|
+
/**
|
|
455
|
+
* Run an action that may navigate, and wait for the new document.
|
|
456
|
+
*
|
|
457
|
+
* The navigation waiter is installed *before* the action: a click can start
|
|
458
|
+
* and commit a navigation before a listener installed afterwards runs, and
|
|
459
|
+
* then the caller snapshots the old page. A non-navigating click (a modal,
|
|
460
|
+
* a menu) resolves after a short cap instead of the full timeout. We do not
|
|
461
|
+
* wait for networkidle: Playwright defines it as 500ms of quiet, which adds
|
|
462
|
+
* half a second to every click. `dispatch` awaits the requests it captured,
|
|
463
|
+
* and an op that needs a later state declares `await_state`.
|
|
464
|
+
*/
|
|
465
|
+
async settleAction(action) {
|
|
466
|
+
const navigated = new Promise((resolve) => {
|
|
467
|
+
const onNavigated = (frame) => {
|
|
468
|
+
if (frame === this.page.mainFrame()) {
|
|
469
|
+
this.page.off("framenavigated", onNavigated);
|
|
470
|
+
resolve();
|
|
471
|
+
}
|
|
472
|
+
};
|
|
473
|
+
// Install the listener before the action: a click can commit a
|
|
474
|
+
// navigation before a listener installed afterwards runs.
|
|
475
|
+
this.page.on("framenavigated", onNavigated);
|
|
476
|
+
setTimeout(() => {
|
|
477
|
+
this.page.off("framenavigated", onNavigated);
|
|
478
|
+
resolve();
|
|
479
|
+
}, 500);
|
|
480
|
+
});
|
|
481
|
+
await action();
|
|
482
|
+
await navigated;
|
|
483
|
+
await this.page.waitForLoadState("domcontentloaded", { timeout: 5_000 }).catch(() => { });
|
|
484
|
+
}
|
|
485
|
+
/** DOM facts about a node, for a blocker that has no semantic ref. */
|
|
486
|
+
async describeBackend(backendNodeId) {
|
|
487
|
+
try {
|
|
488
|
+
const resolved = (await this.cdp.send("DOM.resolveNode", {
|
|
489
|
+
backendNodeId,
|
|
490
|
+
}));
|
|
491
|
+
const objectId = resolved.object.objectId;
|
|
492
|
+
if (objectId === undefined)
|
|
493
|
+
return {};
|
|
494
|
+
return await this.callOn(objectId, `function () {
|
|
495
|
+
const text = String(this.textContent ?? "").trim().replace(/\\s+/g, " ").slice(0, 80);
|
|
496
|
+
return {
|
|
497
|
+
tag: this.tagName,
|
|
498
|
+
domId: this.id || undefined,
|
|
499
|
+
className: typeof this.className === "string" ? this.className.slice(0, 80) : undefined,
|
|
500
|
+
text: text || undefined,
|
|
501
|
+
};
|
|
502
|
+
}`, []);
|
|
503
|
+
}
|
|
504
|
+
catch {
|
|
505
|
+
return {};
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
async contains(target, candidate) {
|
|
509
|
+
const described = (await this.cdp.send("DOM.describeNode", {
|
|
510
|
+
backendNodeId: target,
|
|
511
|
+
depth: -1,
|
|
512
|
+
}));
|
|
513
|
+
return collectBackendIds(described.node).has(candidate);
|
|
514
|
+
}
|
|
515
|
+
async ancestorsOf(backendNodeId) {
|
|
516
|
+
const ids = new Set([backendNodeId]);
|
|
517
|
+
let current = backendNodeId;
|
|
518
|
+
for (let depth = 0; depth < 8; depth += 1) {
|
|
519
|
+
const described = (await this.cdp.send("DOM.describeNode", {
|
|
520
|
+
backendNodeId: current,
|
|
521
|
+
depth: 0,
|
|
522
|
+
}));
|
|
523
|
+
const parentId = described.node.parentId;
|
|
524
|
+
if (parentId === undefined)
|
|
525
|
+
break;
|
|
526
|
+
const parent = (await this.cdp.send("DOM.describeNode", {
|
|
527
|
+
nodeId: parentId,
|
|
528
|
+
depth: 0,
|
|
529
|
+
}));
|
|
530
|
+
const parentBackend = parent.node.backendNodeId;
|
|
531
|
+
if (parentBackend === undefined)
|
|
532
|
+
break;
|
|
533
|
+
ids.add(parentBackend);
|
|
534
|
+
current = parentBackend;
|
|
535
|
+
}
|
|
536
|
+
return ids;
|
|
537
|
+
}
|
|
538
|
+
/**
|
|
539
|
+
* Set files on a file input.
|
|
540
|
+
*
|
|
541
|
+
* A styled "Choose file" control is usually a button or label, with the
|
|
542
|
+
* real `<input type="file">` hidden nearby. Setting files on the button does
|
|
543
|
+
* nothing, so fall back to the first file input on the page.
|
|
544
|
+
*/
|
|
545
|
+
async setFiles(backendNodeId, files) {
|
|
546
|
+
const objectId = await this.resolveObject(backendNodeId);
|
|
547
|
+
const isFile = await this.callOn(objectId, `function () {
|
|
548
|
+
return this instanceof HTMLInputElement && this.type === "file";
|
|
549
|
+
}`, []);
|
|
550
|
+
if (isFile) {
|
|
551
|
+
await this.cdp.send("DOM.setFileInputFiles", { files, backendNodeId });
|
|
552
|
+
return;
|
|
553
|
+
}
|
|
554
|
+
const document = (await this.cdp.send("DOM.getDocument", { depth: 0 }));
|
|
555
|
+
const found = (await this.cdp.send("DOM.querySelector", {
|
|
556
|
+
nodeId: document.root.nodeId,
|
|
557
|
+
selector: 'input[type="file"]',
|
|
558
|
+
}));
|
|
559
|
+
if (found.nodeId === undefined || found.nodeId === 0) {
|
|
560
|
+
throw new EngineError("file_input_not_found", "no file input on the page");
|
|
561
|
+
}
|
|
562
|
+
const described = (await this.cdp.send("DOM.describeNode", {
|
|
563
|
+
nodeId: found.nodeId,
|
|
564
|
+
depth: 0,
|
|
565
|
+
}));
|
|
566
|
+
const target = described.node?.backendNodeId;
|
|
567
|
+
if (target === undefined) {
|
|
568
|
+
throw new EngineError("file_input_not_found", "no file input on the page");
|
|
569
|
+
}
|
|
570
|
+
await this.cdp.send("DOM.setFileInputFiles", { files, backendNodeId: target });
|
|
571
|
+
}
|
|
572
|
+
/** Wait for a download that starts after the action returns. */
|
|
573
|
+
async waitForDownload(ms) {
|
|
574
|
+
if (this.lastDownload !== undefined) {
|
|
575
|
+
const info = this.lastDownload;
|
|
576
|
+
this.lastDownload = undefined;
|
|
577
|
+
return info;
|
|
578
|
+
}
|
|
579
|
+
if (this.downloadPromise !== undefined) {
|
|
580
|
+
return Promise.race([
|
|
581
|
+
this.downloadPromise,
|
|
582
|
+
new Promise((resolve) => setTimeout(() => resolve(undefined), ms)),
|
|
583
|
+
]);
|
|
584
|
+
}
|
|
585
|
+
return new Promise((resolve) => {
|
|
586
|
+
const waiter = (info) => {
|
|
587
|
+
clearTimeout(timer);
|
|
588
|
+
this.downloadWaiters = this.downloadWaiters.filter((candidate) => candidate !== waiter);
|
|
589
|
+
resolve(info);
|
|
590
|
+
};
|
|
591
|
+
const timer = setTimeout(() => {
|
|
592
|
+
this.downloadWaiters = this.downloadWaiters.filter((candidate) => candidate !== waiter);
|
|
593
|
+
resolve(undefined);
|
|
594
|
+
}, ms);
|
|
595
|
+
this.downloadWaiters.push(waiter);
|
|
596
|
+
});
|
|
597
|
+
}
|
|
598
|
+
/** The current value of a form control, for a ref read. */
|
|
599
|
+
async readValue(backendNodeId) {
|
|
600
|
+
const objectId = await this.resolveObject(backendNodeId);
|
|
601
|
+
return this.callOn(objectId, `function () {
|
|
602
|
+
if (
|
|
603
|
+
this instanceof HTMLInputElement ||
|
|
604
|
+
this instanceof HTMLTextAreaElement ||
|
|
605
|
+
this instanceof HTMLSelectElement
|
|
606
|
+
) {
|
|
607
|
+
return this.value;
|
|
608
|
+
}
|
|
609
|
+
if (this.getAttribute?.("role") === "combobox") {
|
|
610
|
+
return (this.textContent ?? "").trim();
|
|
611
|
+
}
|
|
612
|
+
const aria = this.getAttribute?.("aria-valuetext") ?? this.getAttribute?.("aria-valuenow");
|
|
613
|
+
return aria === null || aria === undefined ? undefined : String(aria);
|
|
614
|
+
}`, []);
|
|
615
|
+
}
|
|
616
|
+
async fill(backendNodeId, value) {
|
|
617
|
+
const objectId = await this.resolveObject(backendNodeId);
|
|
618
|
+
const isFile = await this.callOn(objectId, `function () {
|
|
619
|
+
return this instanceof HTMLInputElement && this.type === "file";
|
|
620
|
+
}`, []);
|
|
621
|
+
if (isFile) {
|
|
622
|
+
await this.cdp.send("DOM.setFileInputFiles", {
|
|
623
|
+
files: [value],
|
|
624
|
+
backendNodeId,
|
|
625
|
+
});
|
|
626
|
+
return;
|
|
627
|
+
}
|
|
628
|
+
await this.callOn(objectId, `function () {
|
|
629
|
+
if ("value" in this) {
|
|
630
|
+
this.value = "";
|
|
631
|
+
}
|
|
632
|
+
}`, []);
|
|
633
|
+
await this.cdp.send("DOM.focus", { backendNodeId }).catch(() => {
|
|
634
|
+
throw new EngineError("not_interactive", `node ${backendNodeId} is not focusable`, {
|
|
635
|
+
details: { reason: "not_focusable" },
|
|
636
|
+
});
|
|
637
|
+
});
|
|
638
|
+
await this.page.keyboard.insertText(value).catch(() => {
|
|
639
|
+
throw new EngineError("not_interactive", `node ${backendNodeId} did not accept text`, {
|
|
640
|
+
details: { reason: "not_focusable" },
|
|
641
|
+
});
|
|
642
|
+
});
|
|
643
|
+
}
|
|
644
|
+
async select(backendNodeId, value) {
|
|
645
|
+
const objectId = await this.resolveObject(backendNodeId);
|
|
646
|
+
const native = await this.callOn(objectId, `function () { return this instanceof HTMLSelectElement; }`, []);
|
|
647
|
+
if (!native) {
|
|
648
|
+
await this.selectCustom(backendNodeId, value);
|
|
649
|
+
return;
|
|
650
|
+
}
|
|
651
|
+
await this.callOn(objectId, `function (value) {
|
|
652
|
+
if (!(this instanceof HTMLSelectElement)) {
|
|
653
|
+
throw new Error("target is not a select");
|
|
654
|
+
}
|
|
655
|
+
this.value = value;
|
|
656
|
+
if (this.value !== value) {
|
|
657
|
+
throw new Error("no option with value " + value);
|
|
658
|
+
}
|
|
659
|
+
this.dispatchEvent(new Event("input", { bubbles: true }));
|
|
660
|
+
this.dispatchEvent(new Event("change", { bubbles: true }));
|
|
661
|
+
}`, [{ value }]);
|
|
662
|
+
}
|
|
663
|
+
/**
|
|
664
|
+
* Choose an option in a custom combobox.
|
|
665
|
+
*
|
|
666
|
+
* React component libraries (Radix, shadcn, Headless UI) render a button
|
|
667
|
+
* with `role="combobox"` and a portal listbox, not a native `<select>`.
|
|
668
|
+
* Setting `.value` does nothing there. Open the control, find the option by
|
|
669
|
+
* its visible text, and click its centre.
|
|
670
|
+
*/
|
|
671
|
+
async selectCustom(backendNodeId, value) {
|
|
672
|
+
await this.click(backendNodeId);
|
|
673
|
+
await this.page.waitForTimeout(200);
|
|
674
|
+
const found = await this.evaluate(`(() => {
|
|
675
|
+
const wanted = ${JSON.stringify(value)}.toLowerCase();
|
|
676
|
+
const options = Array.from(document.querySelectorAll('[role="option"]'));
|
|
677
|
+
const names = options.map((node) => (node.textContent ?? "").trim());
|
|
678
|
+
const exact = options.find(
|
|
679
|
+
(node) => (node.textContent ?? "").trim().toLowerCase() === wanted,
|
|
680
|
+
);
|
|
681
|
+
const match =
|
|
682
|
+
exact ??
|
|
683
|
+
options.find((node) => (node.textContent ?? "").trim().toLowerCase().includes(wanted));
|
|
684
|
+
if (!match) return { options: names };
|
|
685
|
+
match.scrollIntoView({ block: "center", inline: "center" });
|
|
686
|
+
const rect = match.getBoundingClientRect();
|
|
687
|
+
return { point: { x: rect.x + rect.width / 2, y: rect.y + rect.height / 2 }, options: names };
|
|
688
|
+
})()`);
|
|
689
|
+
if (found.point === undefined) {
|
|
690
|
+
await this.page.keyboard.press("Escape").catch(() => { });
|
|
691
|
+
throw new EngineError("option_not_found", `no option "${value}"`, {
|
|
692
|
+
details: { options: found.options },
|
|
693
|
+
});
|
|
694
|
+
}
|
|
695
|
+
await this.page.mouse.click(found.point.x, found.point.y);
|
|
696
|
+
await this.page.waitForTimeout(150);
|
|
697
|
+
}
|
|
698
|
+
async setChecked(backendNodeId, checked) {
|
|
699
|
+
const objectId = await this.resolveObject(backendNodeId);
|
|
700
|
+
await this.callOn(objectId, `function (checked) {
|
|
701
|
+
if (!(this instanceof HTMLInputElement)) {
|
|
702
|
+
throw new Error("target is not an input");
|
|
703
|
+
}
|
|
704
|
+
this.checked = checked;
|
|
705
|
+
this.dispatchEvent(new Event("input", { bubbles: true }));
|
|
706
|
+
this.dispatchEvent(new Event("change", { bubbles: true }));
|
|
707
|
+
}`, [{ value: checked }]);
|
|
708
|
+
}
|
|
709
|
+
}
|
|
710
|
+
function parseJsonBody(text) {
|
|
711
|
+
if (text.length === 0 || text.length > MAX_BODY_CHARS)
|
|
712
|
+
return undefined;
|
|
713
|
+
try {
|
|
714
|
+
return JSON.parse(text);
|
|
715
|
+
}
|
|
716
|
+
catch {
|
|
717
|
+
return undefined;
|
|
718
|
+
}
|
|
719
|
+
}
|
|
720
|
+
function isJsonMime(mime) {
|
|
721
|
+
return mime?.includes("json") === true;
|
|
722
|
+
}
|
|
723
|
+
function indexSnapshot(snapshot) {
|
|
724
|
+
const layout = new Map();
|
|
725
|
+
const attributes = new Map();
|
|
726
|
+
for (const document of snapshot.documents) {
|
|
727
|
+
const nodes = document.nodes;
|
|
728
|
+
const boxes = document.layout;
|
|
729
|
+
// Attributes exist for hidden nodes too, including closed-select options.
|
|
730
|
+
nodes.backendNodeId.forEach((backendNodeId, index) => {
|
|
731
|
+
const parsed = attributesFor(nodes.attributes?.[index], snapshot.strings);
|
|
732
|
+
if (Object.keys(parsed).length > 0)
|
|
733
|
+
attributes.set(backendNodeId, parsed);
|
|
734
|
+
});
|
|
735
|
+
boxes.nodeIndex.forEach((nodeIndex, position) => {
|
|
736
|
+
const backendNodeId = nodes.backendNodeId[nodeIndex];
|
|
737
|
+
const bounds = boxes.bounds[position];
|
|
738
|
+
if (backendNodeId === undefined || bounds === undefined)
|
|
739
|
+
return;
|
|
740
|
+
const styles = boxes.styles?.[position];
|
|
741
|
+
layout.set(backendNodeId, {
|
|
742
|
+
bounds: {
|
|
743
|
+
x: bounds[0] ?? 0,
|
|
744
|
+
y: bounds[1] ?? 0,
|
|
745
|
+
width: bounds[2] ?? 0,
|
|
746
|
+
height: bounds[3] ?? 0,
|
|
747
|
+
},
|
|
748
|
+
display: styleValue(snapshot.strings, styles?.[0]),
|
|
749
|
+
visibility: styleValue(snapshot.strings, styles?.[1]),
|
|
750
|
+
opacity: styleValue(snapshot.strings, styles?.[2], "1"),
|
|
751
|
+
});
|
|
752
|
+
});
|
|
753
|
+
}
|
|
754
|
+
return { layout, attributes };
|
|
755
|
+
}
|
|
756
|
+
function styleValue(strings, index, fallback = "") {
|
|
757
|
+
if (index === undefined)
|
|
758
|
+
return fallback;
|
|
759
|
+
return strings[index] ?? fallback;
|
|
760
|
+
}
|
|
761
|
+
function attributesFor(indices, strings) {
|
|
762
|
+
const attributes = {};
|
|
763
|
+
if (indices === undefined)
|
|
764
|
+
return attributes;
|
|
765
|
+
for (let index = 0; index + 1 < indices.length; index += 2) {
|
|
766
|
+
const nameIndex = indices[index];
|
|
767
|
+
const valueIndex = indices[index + 1];
|
|
768
|
+
if (nameIndex === undefined || valueIndex === undefined)
|
|
769
|
+
continue;
|
|
770
|
+
const name = strings[nameIndex];
|
|
771
|
+
const value = strings[valueIndex];
|
|
772
|
+
if (name !== undefined && value !== undefined)
|
|
773
|
+
attributes[name] = value;
|
|
774
|
+
}
|
|
775
|
+
return attributes;
|
|
776
|
+
}
|
|
777
|
+
function toSemanticNode(node, layout, attributes) {
|
|
778
|
+
const properties = {};
|
|
779
|
+
for (const property of node.properties ?? []) {
|
|
780
|
+
const value = property.value?.value;
|
|
781
|
+
if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
|
|
782
|
+
properties[property.name] = value;
|
|
783
|
+
}
|
|
784
|
+
}
|
|
785
|
+
const result = {
|
|
786
|
+
nodeId: node.nodeId,
|
|
787
|
+
role: typeof node.role?.value === "string" ? node.role.value : "none",
|
|
788
|
+
name: typeof node.name?.value === "string" ? node.name.value : String(node.name?.value ?? ""),
|
|
789
|
+
ignored: node.ignored,
|
|
790
|
+
visible: false,
|
|
791
|
+
properties,
|
|
792
|
+
childIds: node.childIds ?? [],
|
|
793
|
+
};
|
|
794
|
+
if (node.backendDOMNodeId === undefined)
|
|
795
|
+
return result;
|
|
796
|
+
result.backendNodeId = node.backendDOMNodeId;
|
|
797
|
+
const attrs = attributes.get(node.backendDOMNodeId);
|
|
798
|
+
if (attrs !== undefined) {
|
|
799
|
+
result.attributes = attrs;
|
|
800
|
+
if (attrs["data-testid"] !== undefined)
|
|
801
|
+
result.test_id = attrs["data-testid"];
|
|
802
|
+
}
|
|
803
|
+
const info = layout.get(node.backendDOMNodeId);
|
|
804
|
+
if (info === undefined)
|
|
805
|
+
return result;
|
|
806
|
+
result.bounds = info.bounds;
|
|
807
|
+
result.visible =
|
|
808
|
+
!node.ignored &&
|
|
809
|
+
info.bounds.width > 0 &&
|
|
810
|
+
info.bounds.height > 0 &&
|
|
811
|
+
info.display !== "none" &&
|
|
812
|
+
info.visibility !== "hidden" &&
|
|
813
|
+
info.visibility !== "collapse" &&
|
|
814
|
+
Number(info.opacity) > 0;
|
|
815
|
+
return result;
|
|
816
|
+
}
|
|
817
|
+
function collectBackendIds(node, into = new Set()) {
|
|
818
|
+
if (node.backendNodeId !== undefined)
|
|
819
|
+
into.add(node.backendNodeId);
|
|
820
|
+
for (const child of node.children ?? []) {
|
|
821
|
+
collectBackendIds(child, into);
|
|
822
|
+
}
|
|
823
|
+
return into;
|
|
824
|
+
}
|
|
825
|
+
//# sourceMappingURL=playwright-engine.js.map
|