mcp-browser-dev-tools 0.2.2 → 0.4.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/README.md +30 -15
- package/package.json +9 -2
- package/src/action-changes.mjs +340 -0
- package/src/browser-adapter.mjs +48 -4
- package/src/cdp-client.mjs +1219 -44
- package/src/config.mjs +10 -0
- package/src/firefox-bidi-client.mjs +767 -47
- package/src/json-schema.mjs +14 -1
- package/src/mcp-server.mjs +59 -8
- package/src/network-control.mjs +156 -0
- package/src/page-context.mjs +306 -2
- package/src/page-script.mjs +1175 -13
- package/src/run-steps.mjs +75 -23
- package/src/run-tabs.mjs +11 -16
- package/src/screenshot-output.mjs +92 -1
- package/src/session-events.mjs +57 -0
- package/src/tool-schemas.mjs +88 -83
- package/src/tool-sets.mjs +73 -0
- package/src/tools/action-tools.mjs +217 -77
- package/src/tools/browser-tools.mjs +12 -19
- package/src/tools/inspection-tools.mjs +88 -54
- package/src/tools/more-tools.mjs +108 -0
- package/src/tools/performance-tools.mjs +183 -0
- package/src/tools/state-tools.mjs +62 -16
- package/src/upload-files.mjs +57 -0
- package/src/video-output.mjs +401 -0
package/src/cdp-client.mjs
CHANGED
|
@@ -1,6 +1,11 @@
|
|
|
1
|
+
import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
|
2
|
+
import { tmpdir } from "node:os";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
|
|
1
5
|
import {
|
|
2
6
|
exportHarLikeSummary,
|
|
3
7
|
filterConsoleMessages,
|
|
8
|
+
InFlightRequests,
|
|
4
9
|
summarizeNetworkRequests,
|
|
5
10
|
} from "./session-events.mjs";
|
|
6
11
|
import { DEFAULT_CDP_BASE_URL } from "./config.mjs";
|
|
@@ -13,6 +18,70 @@ import {
|
|
|
13
18
|
} from "./page-context.mjs";
|
|
14
19
|
import { buildCdpKeyEvents } from "./keyboard.mjs";
|
|
15
20
|
import { sendCheckedInput } from "./input-delivery.mjs";
|
|
21
|
+
import { imageSize, SCREENSHOT_FILE_MODE } from "./screenshot-output.mjs";
|
|
22
|
+
import {
|
|
23
|
+
applyNetworkOptions,
|
|
24
|
+
describeNetworkState,
|
|
25
|
+
inNetworkTurn,
|
|
26
|
+
mockHeaders,
|
|
27
|
+
takeMatchingRule,
|
|
28
|
+
} from "./network-control.mjs";
|
|
29
|
+
import {
|
|
30
|
+
FrameKeys,
|
|
31
|
+
probeScope,
|
|
32
|
+
restoreFrameSelector,
|
|
33
|
+
addFrameSnapshots,
|
|
34
|
+
frameElementSnapshot,
|
|
35
|
+
parseFrameRef,
|
|
36
|
+
shiftFramePoints,
|
|
37
|
+
unknownFrame,
|
|
38
|
+
takeFileTarget,
|
|
39
|
+
assertFileInput,
|
|
40
|
+
uploadResult,
|
|
41
|
+
describePointer,
|
|
42
|
+
dragEnd,
|
|
43
|
+
wheelScroll,
|
|
44
|
+
dragPath,
|
|
45
|
+
pointerFields,
|
|
46
|
+
takeNextRef,
|
|
47
|
+
} from "./page-context.mjs";
|
|
48
|
+
|
|
49
|
+
// How long a drag waits after its first move for the page to start an HTML5
|
|
50
|
+
// drag, and the longest a drag's interception stays open.
|
|
51
|
+
const DRAG_START_MS = 100;
|
|
52
|
+
// The categories DevTools' Performance panel records, so a trace opens there
|
|
53
|
+
// with its timeline, call stacks, and CPU profile.
|
|
54
|
+
const TRACE_CATEGORIES = [
|
|
55
|
+
"-*",
|
|
56
|
+
"devtools.timeline",
|
|
57
|
+
"disabled-by-default-devtools.timeline",
|
|
58
|
+
"disabled-by-default-devtools.timeline.frame",
|
|
59
|
+
"disabled-by-default-devtools.timeline.stack",
|
|
60
|
+
"v8.execute",
|
|
61
|
+
"disabled-by-default-v8.cpu_profiler",
|
|
62
|
+
"blink.console",
|
|
63
|
+
"blink.user_timing",
|
|
64
|
+
"latencyInfo",
|
|
65
|
+
"loading",
|
|
66
|
+
];
|
|
67
|
+
const TRACE_COMPLETE_MS = 60_000;
|
|
68
|
+
// A video capture stops by itself after maxDurationMs, 10 minutes unless
|
|
69
|
+
// asked, 30 at most, so a forgotten recording does not fill the disk. A
|
|
70
|
+
// stretch with no frame longer than VIDEO_GAP_WARN_S is reported, since a
|
|
71
|
+
// hidden or minimised tab sends none.
|
|
72
|
+
export const VIDEO_DEFAULT_DURATION_MS = 10 * 60_000;
|
|
73
|
+
export const VIDEO_MAX_DURATION_MS = 30 * 60_000;
|
|
74
|
+
const VIDEO_GAP_WARN_S = 5;
|
|
75
|
+
const ORPHANED_VIDEO_LIMIT = 8;
|
|
76
|
+
// How long a click may take to open a file chooser.
|
|
77
|
+
const FILE_CHOOSER_MS = 2000;
|
|
78
|
+
const DRAG_SESSION_MS = 30_000;
|
|
79
|
+
|
|
80
|
+
function sleep(ms) {
|
|
81
|
+
return new Promise((resolve) => {
|
|
82
|
+
setTimeout(resolve, ms);
|
|
83
|
+
});
|
|
84
|
+
}
|
|
16
85
|
|
|
17
86
|
function toErrorMessage(error) {
|
|
18
87
|
return error instanceof Error ? error.message : String(error);
|
|
@@ -377,6 +446,31 @@ function pageExceptionMessage(details) {
|
|
|
377
446
|
return details.text || "Page action failed";
|
|
378
447
|
}
|
|
379
448
|
|
|
449
|
+
// A stretch with no frame plays as one still frame. Longer than a few
|
|
450
|
+
// seconds, that is worth saying: the page did not repaint, or the tab was
|
|
451
|
+
// hidden or minimised, which stops Chrome's frames.
|
|
452
|
+
function videoGapWarnings(state) {
|
|
453
|
+
const seconds = (value) => Math.round((value - state.startedAt) * 10) / 10;
|
|
454
|
+
const gaps = [];
|
|
455
|
+
const times = state.frames.map((frame) => frame.timestamp);
|
|
456
|
+
times.push(state.stoppedAt ?? Date.now() / 1000);
|
|
457
|
+
for (let index = 1; index < times.length; index += 1) {
|
|
458
|
+
const gap = times[index] - times[index - 1];
|
|
459
|
+
if (gap > VIDEO_GAP_WARN_S) {
|
|
460
|
+
gaps.push({ gap, from: times[index - 1], to: times[index] });
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
if (gaps.length === 0) {
|
|
464
|
+
return [];
|
|
465
|
+
}
|
|
466
|
+
const longest = gaps.reduce((a, b) => (b.gap > a.gap ? b : a));
|
|
467
|
+
const others =
|
|
468
|
+
gaps.length > 1 ? ` and in ${gaps.length - 1} other stretch(es)` : "";
|
|
469
|
+
return [
|
|
470
|
+
`No frame arrived for ${Math.round(longest.gap * 10) / 10} s (from ${seconds(longest.from)} s to ${seconds(longest.to)} s into the recording)${others}: the page did not repaint, or the tab was hidden or minimised, so the video holds one frame there`,
|
|
471
|
+
];
|
|
472
|
+
}
|
|
473
|
+
|
|
380
474
|
export class CdpSession {
|
|
381
475
|
constructor(target, options = {}) {
|
|
382
476
|
this.id = crypto.randomUUID();
|
|
@@ -385,6 +479,7 @@ export class CdpSession {
|
|
|
385
479
|
this.eventBufferSize = options.eventBufferSize ?? 200;
|
|
386
480
|
this.onClosed = options.onClosed ?? null;
|
|
387
481
|
this.bufferedEvents = [];
|
|
482
|
+
this.inFlight = new InFlightRequests();
|
|
388
483
|
this.pending = new Map();
|
|
389
484
|
this.nextMessageId = 1;
|
|
390
485
|
this.connectedAt = new Date().toISOString();
|
|
@@ -394,6 +489,13 @@ export class CdpSession {
|
|
|
394
489
|
this.lastNavigationAt = null;
|
|
395
490
|
this.lastReloadAt = null;
|
|
396
491
|
this.viewportOverride = null;
|
|
492
|
+
this.video = null;
|
|
493
|
+
// Frames: child sessions of cross-site iframes (attached in flatten
|
|
494
|
+
// mode, by session id), the default execution context of each frame,
|
|
495
|
+
// keyed by session and frame id, and the frame keys refs use.
|
|
496
|
+
this.frameSessions = new Map();
|
|
497
|
+
this.frameContexts = new Map();
|
|
498
|
+
this.frameKeys = new FrameKeys();
|
|
397
499
|
}
|
|
398
500
|
|
|
399
501
|
markClosed() {
|
|
@@ -402,6 +504,7 @@ export class CdpSession {
|
|
|
402
504
|
}
|
|
403
505
|
|
|
404
506
|
this.closed = true;
|
|
507
|
+
void this.endVideoCapture(this.video, "closed");
|
|
405
508
|
this.rejectPending(new Error("CDP session closed"));
|
|
406
509
|
this.rejectEventWaiters(new Error("CDP session closed"));
|
|
407
510
|
this.onClosed?.(this);
|
|
@@ -467,6 +570,14 @@ export class CdpSession {
|
|
|
467
570
|
this.send("Log.enable"),
|
|
468
571
|
this.send("Network.enable"),
|
|
469
572
|
]);
|
|
573
|
+
// Chrome's performance counters count from here, so get_performance's
|
|
574
|
+
// layout, style, and script times cover the whole session.
|
|
575
|
+
await this.send("Performance.enable")
|
|
576
|
+
.then(() => {
|
|
577
|
+
this.performanceEnabled = true;
|
|
578
|
+
})
|
|
579
|
+
.catch(() => {});
|
|
580
|
+
await this.autoAttachFrames(null);
|
|
470
581
|
|
|
471
582
|
await this.installInputRecorder();
|
|
472
583
|
await this.seedBufferedState();
|
|
@@ -500,10 +611,255 @@ export class CdpSession {
|
|
|
500
611
|
return;
|
|
501
612
|
}
|
|
502
613
|
|
|
614
|
+
// Events of a cross-site iframe's session only keep the frame records,
|
|
615
|
+
// except a file chooser opened there, which an upload waits for.
|
|
616
|
+
if (message.sessionId) {
|
|
617
|
+
if (message.method === "Page.fileChooserOpened") {
|
|
618
|
+
this.resolveEventWaiters(message.method, {
|
|
619
|
+
...message.params,
|
|
620
|
+
sessionId: message.sessionId,
|
|
621
|
+
});
|
|
622
|
+
}
|
|
623
|
+
this.trackFrameEvent(
|
|
624
|
+
message.method,
|
|
625
|
+
message.params ?? {},
|
|
626
|
+
message.sessionId,
|
|
627
|
+
);
|
|
628
|
+
return;
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
this.trackFrameEvent(message.method, message.params ?? {}, null);
|
|
503
632
|
this.bufferEvent(message.method, message.params ?? {});
|
|
504
633
|
}
|
|
505
634
|
|
|
635
|
+
// Cross-site iframes run in their own targets; attaching to them in
|
|
636
|
+
// flatten mode gives a session on this connection for each, and doing
|
|
637
|
+
// the same in each such session reaches iframes nested in them.
|
|
638
|
+
async autoAttachFrames(sessionId) {
|
|
639
|
+
await this.send(
|
|
640
|
+
"Target.setAutoAttach",
|
|
641
|
+
{ autoAttach: true, waitForDebuggerOnStart: false, flatten: true },
|
|
642
|
+
sessionId,
|
|
643
|
+
).catch(() => {});
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
trackFrameEvent(method, params, sessionId) {
|
|
647
|
+
const scope = sessionId ?? "";
|
|
648
|
+
if (method === "Runtime.executionContextCreated") {
|
|
649
|
+
const { id, auxData } = params.context ?? {};
|
|
650
|
+
if (auxData?.isDefault && auxData.frameId) {
|
|
651
|
+
this.frameContexts.set(`${scope}:${auxData.frameId}`, id);
|
|
652
|
+
// A frame document that was already loaded gets the recorder late
|
|
653
|
+
// (a new one has it from its start, which this leaves alone).
|
|
654
|
+
this.send(
|
|
655
|
+
"Runtime.evaluate",
|
|
656
|
+
{
|
|
657
|
+
expression: buildInputRecorderExpression(false),
|
|
658
|
+
contextId: id,
|
|
659
|
+
awaitPromise: false,
|
|
660
|
+
returnByValue: true,
|
|
661
|
+
},
|
|
662
|
+
sessionId,
|
|
663
|
+
).catch(() => {});
|
|
664
|
+
}
|
|
665
|
+
} else if (method === "Runtime.executionContextDestroyed") {
|
|
666
|
+
for (const [key, id] of this.frameContexts) {
|
|
667
|
+
if (key.startsWith(`${scope}:`) && id === params.executionContextId) {
|
|
668
|
+
this.frameContexts.delete(key);
|
|
669
|
+
}
|
|
670
|
+
}
|
|
671
|
+
} else if (method === "Runtime.executionContextsCleared") {
|
|
672
|
+
for (const key of Array.from(this.frameContexts.keys())) {
|
|
673
|
+
if (key.startsWith(`${scope}:`)) {
|
|
674
|
+
this.frameContexts.delete(key);
|
|
675
|
+
}
|
|
676
|
+
}
|
|
677
|
+
} else if (
|
|
678
|
+
method === "Target.attachedToTarget" &&
|
|
679
|
+
params.targetInfo?.type === "iframe"
|
|
680
|
+
) {
|
|
681
|
+
const child = params.sessionId;
|
|
682
|
+
this.frameSessions.set(child, {
|
|
683
|
+
sessionId: child,
|
|
684
|
+
frameId: params.targetInfo.targetId,
|
|
685
|
+
parentSessionId: sessionId,
|
|
686
|
+
});
|
|
687
|
+
for (const enable of ["Runtime.enable", "DOM.enable", "Page.enable"]) {
|
|
688
|
+
this.send(enable, {}, child).catch(() => {});
|
|
689
|
+
}
|
|
690
|
+
void this.installInputRecorder(child);
|
|
691
|
+
void this.autoAttachFrames(child);
|
|
692
|
+
} else if (method === "Target.detachedFromTarget") {
|
|
693
|
+
this.frameSessions.delete(params.sessionId);
|
|
694
|
+
}
|
|
695
|
+
}
|
|
696
|
+
|
|
697
|
+
// The tab's iframes, outermost first: the top target's own frames, then
|
|
698
|
+
// each cross-site iframe's target and its own frames.
|
|
699
|
+
async listFrames() {
|
|
700
|
+
const frames = [];
|
|
701
|
+
const walk = (node, sessionId) => {
|
|
702
|
+
for (const child of node.childFrames ?? []) {
|
|
703
|
+
frames.push({
|
|
704
|
+
id: child.frame.id,
|
|
705
|
+
url: child.frame.url,
|
|
706
|
+
sessionId,
|
|
707
|
+
root: false,
|
|
708
|
+
});
|
|
709
|
+
walk(child, sessionId);
|
|
710
|
+
}
|
|
711
|
+
};
|
|
712
|
+
const top = await this.send("Page.getFrameTree");
|
|
713
|
+
walk(top.frameTree, null);
|
|
714
|
+
for (const child of this.frameSessions.values()) {
|
|
715
|
+
const tree = await this.send(
|
|
716
|
+
"Page.getFrameTree",
|
|
717
|
+
{},
|
|
718
|
+
child.sessionId,
|
|
719
|
+
).catch(() => null);
|
|
720
|
+
frames.push({
|
|
721
|
+
id: child.frameId,
|
|
722
|
+
url: tree?.frameTree.frame.url ?? "",
|
|
723
|
+
sessionId: child.sessionId,
|
|
724
|
+
root: true,
|
|
725
|
+
});
|
|
726
|
+
if (tree) {
|
|
727
|
+
walk(tree.frameTree, child.sessionId);
|
|
728
|
+
}
|
|
729
|
+
}
|
|
730
|
+
return frames;
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
// The frame's owner element, found in whichever session holds it, and
|
|
734
|
+
// the top-left of its content box in that session's viewport.
|
|
735
|
+
async frameOwner(frameId) {
|
|
736
|
+
for (const sessionId of [null, ...this.frameSessions.keys()]) {
|
|
737
|
+
try {
|
|
738
|
+
const { backendNodeId } = await this.send(
|
|
739
|
+
"DOM.getFrameOwner",
|
|
740
|
+
{ frameId },
|
|
741
|
+
sessionId,
|
|
742
|
+
);
|
|
743
|
+
const { model } = await this.send(
|
|
744
|
+
"DOM.getBoxModel",
|
|
745
|
+
{ backendNodeId },
|
|
746
|
+
sessionId,
|
|
747
|
+
);
|
|
748
|
+
return {
|
|
749
|
+
sessionId,
|
|
750
|
+
backendNodeId,
|
|
751
|
+
x: model.content[0],
|
|
752
|
+
y: model.content[1],
|
|
753
|
+
};
|
|
754
|
+
} catch {
|
|
755
|
+
// Not in this session.
|
|
756
|
+
}
|
|
757
|
+
}
|
|
758
|
+
return null;
|
|
759
|
+
}
|
|
760
|
+
|
|
761
|
+
// Where the frame's viewport starts in the top page's viewport, adding up
|
|
762
|
+
// the owners of the cross-site frames it is nested in; null when the
|
|
763
|
+
// frame has no box (hidden) or is gone. With scroll, each owner is
|
|
764
|
+
// scrolled into view first, outermost first.
|
|
765
|
+
async frameOffset(frameId, scroll = false) {
|
|
766
|
+
const owner = await this.frameOwner(frameId);
|
|
767
|
+
if (!owner) {
|
|
768
|
+
return null;
|
|
769
|
+
}
|
|
770
|
+
const parent = owner.sessionId
|
|
771
|
+
? this.frameSessions.get(owner.sessionId)
|
|
772
|
+
: null;
|
|
773
|
+
if (scroll) {
|
|
774
|
+
if (parent) {
|
|
775
|
+
await this.frameOffset(parent.frameId, true);
|
|
776
|
+
}
|
|
777
|
+
await this.send(
|
|
778
|
+
"DOM.scrollIntoViewIfNeeded",
|
|
779
|
+
{ backendNodeId: owner.backendNodeId },
|
|
780
|
+
owner.sessionId,
|
|
781
|
+
).catch(() => {});
|
|
782
|
+
return this.frameOffset(frameId, false);
|
|
783
|
+
}
|
|
784
|
+
const base = parent
|
|
785
|
+
? await this.frameOffset(parent.frameId)
|
|
786
|
+
: { x: 0, y: 0 };
|
|
787
|
+
return base ? { x: base.x + owner.x, y: base.y + owner.y } : null;
|
|
788
|
+
}
|
|
789
|
+
|
|
790
|
+
// Runs a page action in a frame: in its target's session for a cross-site
|
|
791
|
+
// frame's own document, else in the frame's default execution context.
|
|
792
|
+
async runInFrame(frameKey, payload, options = {}) {
|
|
793
|
+
const frame = this.frameKeys.get(frameKey);
|
|
794
|
+
if (!frame) {
|
|
795
|
+
return unknownFrame(frameKey, payload.selector);
|
|
796
|
+
}
|
|
797
|
+
// Change tracking needs no position, and works in a hidden frame.
|
|
798
|
+
const positioned = options.offset !== false;
|
|
799
|
+
// A drop target is read without scrolling, so the drag's source stays
|
|
800
|
+
// where it was measured.
|
|
801
|
+
const before = positioned
|
|
802
|
+
? await this.frameOffset(
|
|
803
|
+
frame.id,
|
|
804
|
+
options.scroll ?? payload.scrollIntoView !== false,
|
|
805
|
+
)
|
|
806
|
+
: { x: 0, y: 0 };
|
|
807
|
+
const contextId = frame.root
|
|
808
|
+
? undefined
|
|
809
|
+
: this.frameContexts.get(`${frame.sessionId ?? ""}:${frame.id}`);
|
|
810
|
+
if (!before || (!frame.root && contextId === undefined)) {
|
|
811
|
+
return unknownFrame(frameKey, payload.selector);
|
|
812
|
+
}
|
|
813
|
+
const response = await this.send(
|
|
814
|
+
"Runtime.evaluate",
|
|
815
|
+
{
|
|
816
|
+
expression: buildPageContextExpression(
|
|
817
|
+
{ browserFamily: cdpBrowserFamily(this.config), ...payload },
|
|
818
|
+
{ serialize: true },
|
|
819
|
+
),
|
|
820
|
+
awaitPromise: true,
|
|
821
|
+
returnByValue: true,
|
|
822
|
+
userGesture: options.userGesture ?? false,
|
|
823
|
+
...(contextId !== undefined ? { contextId } : {}),
|
|
824
|
+
},
|
|
825
|
+
frame.sessionId,
|
|
826
|
+
);
|
|
827
|
+
if (response.exceptionDetails) {
|
|
828
|
+
throw new Error(pageExceptionMessage(response.exceptionDetails));
|
|
829
|
+
}
|
|
830
|
+
const value = response.result?.value;
|
|
831
|
+
const result = typeof value === "string" ? JSON.parse(value) : value;
|
|
832
|
+
// The action may have scrolled the frame's ancestors, moving the frame.
|
|
833
|
+
const offset = positioned
|
|
834
|
+
? ((await this.frameOffset(frame.id)) ?? before)
|
|
835
|
+
: before;
|
|
836
|
+
return shiftFramePoints(result, offset);
|
|
837
|
+
}
|
|
838
|
+
|
|
839
|
+
// Where a frame ref's own document runs, for protocol calls that must
|
|
840
|
+
// reach it: the session and execution context.
|
|
841
|
+
frameScope(selector) {
|
|
842
|
+
const route = parseFrameRef(selector);
|
|
843
|
+
const frame = route ? this.frameKeys.get(route.frameKey) : null;
|
|
844
|
+
if (!frame) {
|
|
845
|
+
return { sessionId: null, contextId: undefined };
|
|
846
|
+
}
|
|
847
|
+
return {
|
|
848
|
+
sessionId: frame.sessionId,
|
|
849
|
+
contextId: frame.root
|
|
850
|
+
? undefined
|
|
851
|
+
: this.frameContexts.get(`${frame.sessionId ?? ""}:${frame.id}`),
|
|
852
|
+
};
|
|
853
|
+
}
|
|
854
|
+
|
|
506
855
|
bufferEvent(method, params) {
|
|
856
|
+
// Frames carry image data and arrive many times a second, so they are
|
|
857
|
+
// written to the recording, never buffered or logged.
|
|
858
|
+
if (method === "Page.screencastFrame") {
|
|
859
|
+
this.handleScreencastFrame(params);
|
|
860
|
+
return;
|
|
861
|
+
}
|
|
862
|
+
|
|
507
863
|
const capturedAt = new Date().toISOString();
|
|
508
864
|
if (
|
|
509
865
|
method === "Page.frameNavigated" &&
|
|
@@ -527,6 +883,10 @@ export class CdpSession {
|
|
|
527
883
|
this.autoDismissDialog(params);
|
|
528
884
|
}
|
|
529
885
|
|
|
886
|
+
if (method === "Fetch.requestPaused") {
|
|
887
|
+
void this.handleRequestPaused(params);
|
|
888
|
+
}
|
|
889
|
+
|
|
530
890
|
this.pushEvent({
|
|
531
891
|
method,
|
|
532
892
|
capturedAt,
|
|
@@ -535,12 +895,89 @@ export class CdpSession {
|
|
|
535
895
|
this.resolveEventWaiters(method, params);
|
|
536
896
|
}
|
|
537
897
|
|
|
898
|
+
// Fetch pauses only requests whose URL matches a rule's pattern, so other
|
|
899
|
+
// requests are not slowed by a round trip to the server.
|
|
900
|
+
// One call at a time per tab, so a reset cannot be undone by a call that
|
|
901
|
+
// started before it.
|
|
902
|
+
async setNetwork(options) {
|
|
903
|
+
return inNetworkTurn(this, () => this.applyNetwork(options));
|
|
904
|
+
}
|
|
905
|
+
|
|
906
|
+
async applyNetwork(options) {
|
|
907
|
+
const before = this.network;
|
|
908
|
+
const state = applyNetworkOptions(before, options);
|
|
909
|
+
// Requests paused once the new patterns apply see the new rules.
|
|
910
|
+
this.network = state;
|
|
911
|
+
if (state.rules.length > 0) {
|
|
912
|
+
await this.send("Fetch.enable", {
|
|
913
|
+
patterns: state.rules.map((rule) => ({
|
|
914
|
+
urlPattern: rule.url,
|
|
915
|
+
requestStage: "Request",
|
|
916
|
+
})),
|
|
917
|
+
});
|
|
918
|
+
} else if (before?.rules.length > 0) {
|
|
919
|
+
await this.send("Fetch.disable");
|
|
920
|
+
}
|
|
921
|
+
if (options.headers !== undefined || options.reset) {
|
|
922
|
+
await this.send("Network.setExtraHTTPHeaders", {
|
|
923
|
+
headers: state.headers,
|
|
924
|
+
});
|
|
925
|
+
}
|
|
926
|
+
const conditions = [
|
|
927
|
+
"offline",
|
|
928
|
+
"latencyMs",
|
|
929
|
+
"downloadKbps",
|
|
930
|
+
"uploadKbps",
|
|
931
|
+
"reset",
|
|
932
|
+
];
|
|
933
|
+
if (conditions.some((key) => options[key] !== undefined)) {
|
|
934
|
+
const throughput = (kbps) => (kbps ? (kbps * 1024) / 8 : -1);
|
|
935
|
+
await this.send("Network.emulateNetworkConditions", {
|
|
936
|
+
offline: state.offline,
|
|
937
|
+
latency: state.latencyMs ?? 0,
|
|
938
|
+
downloadThroughput: throughput(state.downloadKbps),
|
|
939
|
+
uploadThroughput: throughput(state.uploadKbps),
|
|
940
|
+
});
|
|
941
|
+
}
|
|
942
|
+
return {
|
|
943
|
+
browserFamily: cdpBrowserFamily(this.config),
|
|
944
|
+
...describeNetworkState(state),
|
|
945
|
+
};
|
|
946
|
+
}
|
|
947
|
+
|
|
948
|
+
async handleRequestPaused(params) {
|
|
949
|
+
const { requestId } = params;
|
|
950
|
+
const rule = takeMatchingRule(this.network, params.request?.url ?? "");
|
|
951
|
+
try {
|
|
952
|
+
if (!rule) {
|
|
953
|
+
await this.send("Fetch.continueRequest", { requestId });
|
|
954
|
+
} else if (rule.action === "block") {
|
|
955
|
+
await this.send("Fetch.failRequest", {
|
|
956
|
+
requestId,
|
|
957
|
+
errorReason: "BlockedByClient",
|
|
958
|
+
});
|
|
959
|
+
} else {
|
|
960
|
+
await this.send("Fetch.fulfillRequest", {
|
|
961
|
+
requestId,
|
|
962
|
+
responseCode: rule.status,
|
|
963
|
+
responseHeaders: mockHeaders(rule),
|
|
964
|
+
body: Buffer.from(rule.body).toString("base64"),
|
|
965
|
+
});
|
|
966
|
+
}
|
|
967
|
+
} catch {
|
|
968
|
+
// Release the request if it is still paused; it may also have gone
|
|
969
|
+
// away, for example because the page navigated.
|
|
970
|
+
await this.send("Fetch.continueRequest", { requestId }).catch(() => {});
|
|
971
|
+
}
|
|
972
|
+
}
|
|
973
|
+
|
|
538
974
|
autoDismissDialog(params) {
|
|
539
975
|
const accept = params.type !== "prompt";
|
|
540
976
|
this.send("Page.handleJavaScriptDialog", { accept }).catch(() => {});
|
|
541
977
|
}
|
|
542
978
|
|
|
543
979
|
pushEvent(event) {
|
|
980
|
+
this.inFlight.observe(event);
|
|
544
981
|
this.bufferedEvents.push(event);
|
|
545
982
|
if (this.bufferedEvents.length > this.eventBufferSize) {
|
|
546
983
|
this.bufferedEvents.shift();
|
|
@@ -614,13 +1051,18 @@ export class CdpSession {
|
|
|
614
1051
|
this.pending.clear();
|
|
615
1052
|
}
|
|
616
1053
|
|
|
617
|
-
send(method, params = {}) {
|
|
1054
|
+
send(method, params = {}, sessionId = null) {
|
|
618
1055
|
if (!this.websocket || this.websocket.readyState !== WebSocket.OPEN) {
|
|
619
1056
|
throw new Error(`CDP session ${this.id} is not connected`);
|
|
620
1057
|
}
|
|
621
1058
|
|
|
622
1059
|
const id = this.nextMessageId++;
|
|
623
|
-
const payload = JSON.stringify({
|
|
1060
|
+
const payload = JSON.stringify({
|
|
1061
|
+
id,
|
|
1062
|
+
method,
|
|
1063
|
+
params,
|
|
1064
|
+
...(sessionId ? { sessionId } : {}),
|
|
1065
|
+
});
|
|
624
1066
|
|
|
625
1067
|
return new Promise((resolve, reject) => {
|
|
626
1068
|
this.pending.set(id, { resolve, reject });
|
|
@@ -714,6 +1156,15 @@ export class CdpSession {
|
|
|
714
1156
|
}
|
|
715
1157
|
|
|
716
1158
|
async runPageAction(payload, options = {}) {
|
|
1159
|
+
const route = parseFrameRef(payload.selector);
|
|
1160
|
+
if (route) {
|
|
1161
|
+
const result = await this.runInFrame(
|
|
1162
|
+
route.frameKey,
|
|
1163
|
+
{ ...payload, selector: route.selector },
|
|
1164
|
+
options,
|
|
1165
|
+
);
|
|
1166
|
+
return restoreFrameSelector(result, route, payload.selector);
|
|
1167
|
+
}
|
|
717
1168
|
const result = await this.evaluateRuntime(
|
|
718
1169
|
buildPageContextExpression(
|
|
719
1170
|
{
|
|
@@ -881,8 +1332,71 @@ export class CdpSession {
|
|
|
881
1332
|
};
|
|
882
1333
|
}
|
|
883
1334
|
|
|
1335
|
+
// Refs number on from the last snapshot, across navigations, so an old
|
|
1336
|
+
// ref never names an element on a later page.
|
|
1337
|
+
async runSnapshotAction(payload) {
|
|
1338
|
+
const result = await this.runPageAction({
|
|
1339
|
+
...payload,
|
|
1340
|
+
refStart: this.refStart ?? 1,
|
|
1341
|
+
});
|
|
1342
|
+
return takeNextRef(this, result);
|
|
1343
|
+
}
|
|
1344
|
+
|
|
884
1345
|
async snapshotControls() {
|
|
885
|
-
return this.
|
|
1346
|
+
return this.runSnapshotAction({ action: "controls_snapshot" });
|
|
1347
|
+
}
|
|
1348
|
+
|
|
1349
|
+
// The top page's headings and controls, then each iframe's.
|
|
1350
|
+
async snapshotPage(options = {}) {
|
|
1351
|
+
const runInFrame = (key, payload, runOptions) =>
|
|
1352
|
+
this.runInFrame(key, payload, runOptions);
|
|
1353
|
+
const route = parseFrameRef(options.selector);
|
|
1354
|
+
if (route) {
|
|
1355
|
+
return frameElementSnapshot({
|
|
1356
|
+
route,
|
|
1357
|
+
frameKeys: this.frameKeys,
|
|
1358
|
+
runInFrame,
|
|
1359
|
+
options,
|
|
1360
|
+
});
|
|
1361
|
+
}
|
|
1362
|
+
const result = await this.runSnapshotAction({
|
|
1363
|
+
action: "snapshot",
|
|
1364
|
+
...options,
|
|
1365
|
+
});
|
|
1366
|
+
if (options.selector) {
|
|
1367
|
+
return result;
|
|
1368
|
+
}
|
|
1369
|
+
return addFrameSnapshots({
|
|
1370
|
+
result,
|
|
1371
|
+
frames: await this.listFrames().catch(() => []),
|
|
1372
|
+
frameKeys: this.frameKeys,
|
|
1373
|
+
runInFrame,
|
|
1374
|
+
options,
|
|
1375
|
+
});
|
|
1376
|
+
}
|
|
1377
|
+
|
|
1378
|
+
async trackChanges(phase, options = {}) {
|
|
1379
|
+
const { frameKey, ...rest } = options;
|
|
1380
|
+
if (!frameKey) {
|
|
1381
|
+
return this.runSnapshotAction({ action: `change_${phase}`, ...rest });
|
|
1382
|
+
}
|
|
1383
|
+
// In a frame, refs number on from the frame's own last snapshot. A frame
|
|
1384
|
+
// that is gone ends tracking as a lost baseline does.
|
|
1385
|
+
const entry = this.frameKeys.get(frameKey);
|
|
1386
|
+
const result = entry
|
|
1387
|
+
? await this.runInFrame(
|
|
1388
|
+
frameKey,
|
|
1389
|
+
{ action: `change_${phase}`, ...rest, refStart: entry.refStart ?? 1 },
|
|
1390
|
+
{ offset: false },
|
|
1391
|
+
)
|
|
1392
|
+
: null;
|
|
1393
|
+
if (!result || result.error?.startsWith("Unknown frame")) {
|
|
1394
|
+
if (phase === "baseline") {
|
|
1395
|
+
throw new Error(`Unknown frame ${frameKey}`);
|
|
1396
|
+
}
|
|
1397
|
+
return { document: "same", lost: true };
|
|
1398
|
+
}
|
|
1399
|
+
return takeNextRef(entry, result);
|
|
886
1400
|
}
|
|
887
1401
|
|
|
888
1402
|
async readText(options = {}) {
|
|
@@ -902,17 +1416,33 @@ export class CdpSession {
|
|
|
902
1416
|
action: "pointer_target",
|
|
903
1417
|
selector,
|
|
904
1418
|
...(options.inputProbe ? { inputProbe: options.inputProbe } : {}),
|
|
1419
|
+
...(options.scrollIntoView === false ? { scrollIntoView: false } : {}),
|
|
905
1420
|
});
|
|
906
1421
|
assertPointerTarget(target);
|
|
907
1422
|
return target;
|
|
908
1423
|
}
|
|
909
1424
|
|
|
910
|
-
|
|
1425
|
+
// A locator, scrolled into view unless scrollIntoView is false, or
|
|
1426
|
+
// viewport coordinates, which never scroll.
|
|
1427
|
+
async resolvePointer(target, options = {}) {
|
|
1428
|
+
if (typeof target === "string") {
|
|
1429
|
+
return this.resolvePointerTarget(target, options);
|
|
1430
|
+
}
|
|
1431
|
+
return this.runSnapshotAction({
|
|
1432
|
+
action: "point_target",
|
|
1433
|
+
x: target.x,
|
|
1434
|
+
y: target.y,
|
|
1435
|
+
...(options.inputProbe ? { inputProbe: options.inputProbe } : {}),
|
|
1436
|
+
});
|
|
1437
|
+
}
|
|
1438
|
+
|
|
1439
|
+
async readInputProbe(token, disarm, target = null) {
|
|
911
1440
|
try {
|
|
912
1441
|
const probe = await this.runPageAction({
|
|
913
1442
|
action: "input_probe",
|
|
914
1443
|
token,
|
|
915
1444
|
disarm,
|
|
1445
|
+
...probeScope(target),
|
|
916
1446
|
});
|
|
917
1447
|
return probe.armed ? probe : null;
|
|
918
1448
|
} catch {
|
|
@@ -920,11 +1450,20 @@ export class CdpSession {
|
|
|
920
1450
|
}
|
|
921
1451
|
}
|
|
922
1452
|
|
|
923
|
-
|
|
924
|
-
|
|
1453
|
+
// A double click is two presses, the second with clickCount 2, as the
|
|
1454
|
+
// browser reports them.
|
|
1455
|
+
async dispatchClick(point, options = {}) {
|
|
1456
|
+
const button = options.button ?? "left";
|
|
1457
|
+
const buttons = { left: 1, right: 2, middle: 4 }[button] ?? 1;
|
|
925
1458
|
await this.dispatchMouse("mouseMoved", point);
|
|
926
|
-
|
|
927
|
-
|
|
1459
|
+
for (let count = 1; count <= (options.clickCount ?? 1); count += 1) {
|
|
1460
|
+
const press = { button, clickCount: count };
|
|
1461
|
+
await this.dispatchMouse("mousePressed", point, { ...press, buttons });
|
|
1462
|
+
await this.dispatchMouse("mouseReleased", point, {
|
|
1463
|
+
...press,
|
|
1464
|
+
buttons: 0,
|
|
1465
|
+
});
|
|
1466
|
+
}
|
|
928
1467
|
}
|
|
929
1468
|
|
|
930
1469
|
async dispatchMouse(type, point, extra = {}) {
|
|
@@ -942,31 +1481,29 @@ export class CdpSession {
|
|
|
942
1481
|
}
|
|
943
1482
|
}
|
|
944
1483
|
|
|
945
|
-
async click(
|
|
1484
|
+
async click(target, options = {}) {
|
|
946
1485
|
const token = crypto.randomUUID();
|
|
947
|
-
const
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
1486
|
+
const resolved = await this.resolvePointer(target, { inputProbe: token });
|
|
1487
|
+
if (!resolved.found) {
|
|
1488
|
+
return resolved;
|
|
1489
|
+
}
|
|
1490
|
+
if (typeof target === "string") {
|
|
1491
|
+
assertEnabled(resolved);
|
|
952
1492
|
}
|
|
953
|
-
assertEnabled(target);
|
|
954
1493
|
|
|
955
1494
|
const delivery = await sendCheckedInput({
|
|
956
|
-
send: () => this.dispatchClick(
|
|
957
|
-
readProbe: (disarm) => this.readInputProbe(token, disarm),
|
|
1495
|
+
send: () => this.dispatchClick(resolved.point, options),
|
|
1496
|
+
readProbe: (disarm) => this.readInputProbe(token, disarm, target),
|
|
958
1497
|
recover: () => this.bringToFront(),
|
|
959
|
-
describe: `The click on
|
|
1498
|
+
describe: `The click on ${describePointer(target)}`,
|
|
960
1499
|
});
|
|
961
1500
|
|
|
962
1501
|
return {
|
|
963
1502
|
browserFamily: cdpBrowserFamily(this.config),
|
|
964
|
-
selector,
|
|
965
1503
|
found: true,
|
|
966
1504
|
clicked: true,
|
|
967
1505
|
...(delivery.resent ? { resent: true } : {}),
|
|
968
|
-
|
|
969
|
-
node: delivery.node ?? target.node,
|
|
1506
|
+
...pointerFields(target, resolved, delivery.node ?? resolved.node),
|
|
970
1507
|
};
|
|
971
1508
|
}
|
|
972
1509
|
|
|
@@ -976,24 +1513,132 @@ export class CdpSession {
|
|
|
976
1513
|
await this.send("Page.bringToFront").catch(() => {});
|
|
977
1514
|
}
|
|
978
1515
|
|
|
979
|
-
async hover(
|
|
980
|
-
const
|
|
1516
|
+
async hover(target) {
|
|
1517
|
+
const resolved = await this.resolvePointer(target);
|
|
1518
|
+
if (!resolved.found) {
|
|
1519
|
+
return resolved;
|
|
1520
|
+
}
|
|
1521
|
+
|
|
1522
|
+
await this.dispatchMouse("mouseMoved", resolved.point);
|
|
1523
|
+
|
|
1524
|
+
return {
|
|
1525
|
+
browserFamily: cdpBrowserFamily(this.config),
|
|
1526
|
+
found: true,
|
|
1527
|
+
hovered: true,
|
|
1528
|
+
...pointerFields(target, resolved),
|
|
1529
|
+
};
|
|
1530
|
+
}
|
|
1531
|
+
|
|
1532
|
+
// Presses at from, moves through dragPath, and releases at to. Chrome
|
|
1533
|
+
// does not run an HTML5 drag (draggable elements, dataTransfer) from CDP
|
|
1534
|
+
// mouse input, so drags are intercepted: when the page starts one, Chrome
|
|
1535
|
+
// hands over its data and the drag finishes with drag events instead.
|
|
1536
|
+
async drag(from, to, options = {}) {
|
|
1537
|
+
const token = crypto.randomUUID();
|
|
1538
|
+
const source = await this.resolvePointer(from, { inputProbe: token });
|
|
1539
|
+
if (!source.found) {
|
|
1540
|
+
await this.readInputProbe(token, true, from);
|
|
1541
|
+
return source;
|
|
1542
|
+
}
|
|
1543
|
+
// The drop point is read without scrolling, so the source stays put.
|
|
1544
|
+
const target = await this.resolvePointer(to, { scrollIntoView: false });
|
|
981
1545
|
if (!target.found) {
|
|
1546
|
+
await this.readInputProbe(token, true, from);
|
|
982
1547
|
return target;
|
|
983
1548
|
}
|
|
984
1549
|
|
|
985
|
-
await this.
|
|
1550
|
+
await this.send("Input.setInterceptDrags", { enabled: true });
|
|
1551
|
+
let dragData = null;
|
|
1552
|
+
const intercepted = this.createEventWaiter(
|
|
1553
|
+
"Input.dragIntercepted",
|
|
1554
|
+
() => true,
|
|
1555
|
+
DRAG_SESSION_MS,
|
|
1556
|
+
);
|
|
1557
|
+
intercepted.promise.then(
|
|
1558
|
+
(params) => {
|
|
1559
|
+
dragData = params.data;
|
|
1560
|
+
},
|
|
1561
|
+
() => {},
|
|
1562
|
+
);
|
|
1563
|
+
const held = { button: "left", buttons: 1 };
|
|
1564
|
+
const release = { button: "left", buttons: 0, clickCount: 1 };
|
|
1565
|
+
let delivery;
|
|
1566
|
+
let released = false;
|
|
1567
|
+
try {
|
|
1568
|
+
delivery = await sendCheckedInput({
|
|
1569
|
+
send: async () => {
|
|
1570
|
+
await this.dispatchMouse("mouseMoved", source.point);
|
|
1571
|
+
await this.dispatchMouse("mousePressed", source.point, {
|
|
1572
|
+
...held,
|
|
1573
|
+
clickCount: 1,
|
|
1574
|
+
});
|
|
1575
|
+
},
|
|
1576
|
+
readProbe: (disarm) => this.readInputProbe(token, disarm, from),
|
|
1577
|
+
recover: () => this.bringToFront(),
|
|
1578
|
+
describe: `The press to drag ${describePointer(from)}`,
|
|
1579
|
+
});
|
|
1580
|
+
|
|
1581
|
+
const path = dragPath(source.point, target.point, options.steps);
|
|
1582
|
+
let index = 0;
|
|
1583
|
+
for (; index < path.length && !dragData; index += 1) {
|
|
1584
|
+
await this.dispatchMouse("mouseMoved", path[index], held);
|
|
1585
|
+
if (index === 0) {
|
|
1586
|
+
// A page starts an HTML5 drag on the first move past a few pixels.
|
|
1587
|
+
await Promise.race([intercepted.promise, sleep(DRAG_START_MS)]).catch(
|
|
1588
|
+
() => {},
|
|
1589
|
+
);
|
|
1590
|
+
}
|
|
1591
|
+
}
|
|
1592
|
+
if (dragData) {
|
|
1593
|
+
const rest = path.slice(index);
|
|
1594
|
+
const enter = rest[0] ?? target.point;
|
|
1595
|
+
await this.dispatchDrag("dragEnter", enter, dragData);
|
|
1596
|
+
for (const point of rest) {
|
|
1597
|
+
await this.dispatchDrag("dragOver", point, dragData);
|
|
1598
|
+
}
|
|
1599
|
+
await this.dispatchDrag("drop", target.point, dragData);
|
|
1600
|
+
}
|
|
1601
|
+
await this.dispatchMouse("mouseReleased", target.point, release);
|
|
1602
|
+
released = true;
|
|
1603
|
+
} finally {
|
|
1604
|
+
// A drag that failed partway must not leave the button down for the
|
|
1605
|
+
// next action.
|
|
1606
|
+
if (!released) {
|
|
1607
|
+
if (dragData) {
|
|
1608
|
+
await this.dispatchDrag("dragCancel", target.point, dragData).catch(
|
|
1609
|
+
() => {},
|
|
1610
|
+
);
|
|
1611
|
+
}
|
|
1612
|
+
await this.dispatchMouse("mouseReleased", target.point, release).catch(
|
|
1613
|
+
() => {},
|
|
1614
|
+
);
|
|
1615
|
+
}
|
|
1616
|
+
intercepted.cancel();
|
|
1617
|
+
await this.send("Input.setInterceptDrags", { enabled: false }).catch(
|
|
1618
|
+
() => {},
|
|
1619
|
+
);
|
|
1620
|
+
}
|
|
986
1621
|
|
|
987
1622
|
return {
|
|
988
1623
|
browserFamily: cdpBrowserFamily(this.config),
|
|
989
|
-
selector,
|
|
990
1624
|
found: true,
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
1625
|
+
dragged: true,
|
|
1626
|
+
html5: Boolean(dragData),
|
|
1627
|
+
...(delivery.resent ? { resent: true } : {}),
|
|
1628
|
+
from: dragEnd(from, source),
|
|
1629
|
+
to: dragEnd(to, target),
|
|
994
1630
|
};
|
|
995
1631
|
}
|
|
996
1632
|
|
|
1633
|
+
async dispatchDrag(type, point, data) {
|
|
1634
|
+
await this.send("Input.dispatchDragEvent", {
|
|
1635
|
+
type,
|
|
1636
|
+
x: point.x,
|
|
1637
|
+
y: point.y,
|
|
1638
|
+
data,
|
|
1639
|
+
});
|
|
1640
|
+
}
|
|
1641
|
+
|
|
997
1642
|
async type(selector, text, options = {}) {
|
|
998
1643
|
const token = crypto.randomUUID();
|
|
999
1644
|
const prepared = await this.runPageAction(
|
|
@@ -1034,12 +1679,12 @@ export class CdpSession {
|
|
|
1034
1679
|
if (text || options.clear !== false) {
|
|
1035
1680
|
delivery = await sendCheckedInput({
|
|
1036
1681
|
send: sendText,
|
|
1037
|
-
readProbe: (disarm) => this.readInputProbe(token, disarm),
|
|
1682
|
+
readProbe: (disarm) => this.readInputProbe(token, disarm, selector),
|
|
1038
1683
|
recover: () => this.bringToFront(),
|
|
1039
1684
|
describe: `The text for "${selector}"`,
|
|
1040
1685
|
});
|
|
1041
1686
|
} else {
|
|
1042
|
-
await this.readInputProbe(token, true);
|
|
1687
|
+
await this.readInputProbe(token, true, selector);
|
|
1043
1688
|
}
|
|
1044
1689
|
|
|
1045
1690
|
let node = delivery.node;
|
|
@@ -1062,6 +1707,413 @@ export class CdpSession {
|
|
|
1062
1707
|
};
|
|
1063
1708
|
}
|
|
1064
1709
|
|
|
1710
|
+
// Sets files on a file input, or, for a button that opens a file chooser
|
|
1711
|
+
// from script, intercepts the chooser its click opens.
|
|
1712
|
+
async uploadFiles(selector, files) {
|
|
1713
|
+
const token = crypto.randomUUID();
|
|
1714
|
+
const target = await this.runPageAction({
|
|
1715
|
+
action: "file_input",
|
|
1716
|
+
selector,
|
|
1717
|
+
token,
|
|
1718
|
+
clear: files.length === 0,
|
|
1719
|
+
});
|
|
1720
|
+
if (!target.found) {
|
|
1721
|
+
return target;
|
|
1722
|
+
}
|
|
1723
|
+
const family = cdpBrowserFamily(this.config);
|
|
1724
|
+
if (target.cleared) {
|
|
1725
|
+
return uploadResult(family, selector, files);
|
|
1726
|
+
}
|
|
1727
|
+
if (target.fileInput) {
|
|
1728
|
+
// The input's handle and the files go to the session of the
|
|
1729
|
+
// document it is in, a frame's for a frame ref.
|
|
1730
|
+
const scope = this.frameScope(selector);
|
|
1731
|
+
const handle = await this.send(
|
|
1732
|
+
"Runtime.evaluate",
|
|
1733
|
+
{
|
|
1734
|
+
expression: takeFileTarget(token),
|
|
1735
|
+
returnByValue: false,
|
|
1736
|
+
...(scope.contextId !== undefined
|
|
1737
|
+
? { contextId: scope.contextId }
|
|
1738
|
+
: {}),
|
|
1739
|
+
},
|
|
1740
|
+
scope.sessionId,
|
|
1741
|
+
);
|
|
1742
|
+
const objectId = handle.result?.objectId;
|
|
1743
|
+
try {
|
|
1744
|
+
assertFileInput(target, files);
|
|
1745
|
+
await this.send(
|
|
1746
|
+
"DOM.setFileInputFiles",
|
|
1747
|
+
{ files, objectId },
|
|
1748
|
+
scope.sessionId,
|
|
1749
|
+
);
|
|
1750
|
+
} finally {
|
|
1751
|
+
this.send("Runtime.releaseObject", { objectId }, scope.sessionId).catch(
|
|
1752
|
+
() => {},
|
|
1753
|
+
);
|
|
1754
|
+
}
|
|
1755
|
+
return uploadResult(family, selector, files, {
|
|
1756
|
+
multiple: target.multiple,
|
|
1757
|
+
accept: target.accept,
|
|
1758
|
+
});
|
|
1759
|
+
}
|
|
1760
|
+
|
|
1761
|
+
// One chooser at a time per tab, so a chooser goes to the upload whose
|
|
1762
|
+
// click opened it.
|
|
1763
|
+
const previous = this.chooserTurn ?? Promise.resolve();
|
|
1764
|
+
let finished;
|
|
1765
|
+
this.chooserTurn = new Promise((resolve) => {
|
|
1766
|
+
finished = resolve;
|
|
1767
|
+
});
|
|
1768
|
+
await previous;
|
|
1769
|
+
try {
|
|
1770
|
+
return await this.uploadThroughChooser(selector, files, family);
|
|
1771
|
+
} finally {
|
|
1772
|
+
finished();
|
|
1773
|
+
}
|
|
1774
|
+
}
|
|
1775
|
+
|
|
1776
|
+
// The chooser opens in the session of the document whose script opens it,
|
|
1777
|
+
// the button's frame or the top page, so both intercept it.
|
|
1778
|
+
async uploadThroughChooser(selector, files, family) {
|
|
1779
|
+
const sessions = Array.from(
|
|
1780
|
+
new Set([null, this.frameScope(selector).sessionId]),
|
|
1781
|
+
);
|
|
1782
|
+
for (const sessionId of sessions) {
|
|
1783
|
+
await this.send(
|
|
1784
|
+
"Page.setInterceptFileChooserDialog",
|
|
1785
|
+
{ enabled: true },
|
|
1786
|
+
sessionId,
|
|
1787
|
+
).catch(() => {});
|
|
1788
|
+
}
|
|
1789
|
+
const chooser = this.createEventWaiter(
|
|
1790
|
+
"Page.fileChooserOpened",
|
|
1791
|
+
() => true,
|
|
1792
|
+
FILE_CHOOSER_MS,
|
|
1793
|
+
);
|
|
1794
|
+
try {
|
|
1795
|
+
await this.click(selector);
|
|
1796
|
+
let opened;
|
|
1797
|
+
try {
|
|
1798
|
+
opened = await chooser.promise;
|
|
1799
|
+
} catch {
|
|
1800
|
+
throw new Error(
|
|
1801
|
+
`"${selector}" is not a file input, and clicking it opened no file chooser; pass the <input type="file">, which may be hidden`,
|
|
1802
|
+
);
|
|
1803
|
+
}
|
|
1804
|
+
if (files.length > 1 && opened.mode !== "selectMultiple") {
|
|
1805
|
+
throw new Error(
|
|
1806
|
+
`The file chooser "${selector}" opened takes one file, not ${files.length}`,
|
|
1807
|
+
);
|
|
1808
|
+
}
|
|
1809
|
+
await this.send(
|
|
1810
|
+
"DOM.setFileInputFiles",
|
|
1811
|
+
{ files, backendNodeId: opened.backendNodeId },
|
|
1812
|
+
opened.sessionId ?? null,
|
|
1813
|
+
);
|
|
1814
|
+
} finally {
|
|
1815
|
+
chooser.cancel();
|
|
1816
|
+
for (const sessionId of sessions) {
|
|
1817
|
+
await this.send(
|
|
1818
|
+
"Page.setInterceptFileChooserDialog",
|
|
1819
|
+
{ enabled: false },
|
|
1820
|
+
sessionId,
|
|
1821
|
+
).catch(() => {});
|
|
1822
|
+
}
|
|
1823
|
+
}
|
|
1824
|
+
return uploadResult(family, selector, files, { chooser: true });
|
|
1825
|
+
}
|
|
1826
|
+
|
|
1827
|
+
// The page's report, with Chromium's own counters: heap, DOM nodes,
|
|
1828
|
+
// listeners, layouts and style recalculations, and script and task time.
|
|
1829
|
+
async getPerformance() {
|
|
1830
|
+
const report = await this.runPageAction({ action: "performance" });
|
|
1831
|
+
let metrics = null;
|
|
1832
|
+
try {
|
|
1833
|
+
if (!this.performanceEnabled) {
|
|
1834
|
+
await this.send("Performance.enable");
|
|
1835
|
+
this.performanceEnabled = true;
|
|
1836
|
+
}
|
|
1837
|
+
const values = Object.fromEntries(
|
|
1838
|
+
(await this.send("Performance.getMetrics")).metrics.map(
|
|
1839
|
+
({ name, value }) => [name, value],
|
|
1840
|
+
),
|
|
1841
|
+
);
|
|
1842
|
+
const ms = (seconds) =>
|
|
1843
|
+
seconds === undefined ? null : Math.round(seconds * 1000);
|
|
1844
|
+
metrics = {
|
|
1845
|
+
jsHeapUsedBytes: Math.round(values.JSHeapUsedSize ?? 0),
|
|
1846
|
+
jsHeapTotalBytes: Math.round(values.JSHeapTotalSize ?? 0),
|
|
1847
|
+
domNodes: values.Nodes ?? null,
|
|
1848
|
+
eventListeners: values.JSEventListeners ?? null,
|
|
1849
|
+
layouts: values.LayoutCount ?? null,
|
|
1850
|
+
styleRecalcs: values.RecalcStyleCount ?? null,
|
|
1851
|
+
layoutMs: ms(values.LayoutDuration),
|
|
1852
|
+
styleRecalcMs: ms(values.RecalcStyleDuration),
|
|
1853
|
+
scriptMs: ms(values.ScriptDuration),
|
|
1854
|
+
taskMs: ms(values.TaskDuration),
|
|
1855
|
+
};
|
|
1856
|
+
} catch {
|
|
1857
|
+
// The counters are extra; the page's report stands without them.
|
|
1858
|
+
}
|
|
1859
|
+
return { ...report, metrics };
|
|
1860
|
+
}
|
|
1861
|
+
|
|
1862
|
+
async startTrace(options = {}) {
|
|
1863
|
+
if (this.tracing) {
|
|
1864
|
+
throw new Error("A trace is already recording; stop it first");
|
|
1865
|
+
}
|
|
1866
|
+
await this.send("Tracing.start", {
|
|
1867
|
+
transferMode: "ReturnAsStream",
|
|
1868
|
+
traceConfig: {
|
|
1869
|
+
recordMode: "recordUntilFull",
|
|
1870
|
+
includedCategories: [
|
|
1871
|
+
...TRACE_CATEGORIES,
|
|
1872
|
+
...(options.screenshots
|
|
1873
|
+
? ["disabled-by-default-devtools.screenshot"]
|
|
1874
|
+
: []),
|
|
1875
|
+
],
|
|
1876
|
+
},
|
|
1877
|
+
});
|
|
1878
|
+
this.tracing = { startedAt: Date.now() };
|
|
1879
|
+
return { browserFamily: cdpBrowserFamily(this.config), recording: true };
|
|
1880
|
+
}
|
|
1881
|
+
|
|
1882
|
+
// Ends the trace and reads it from the stream Chrome hands back.
|
|
1883
|
+
async stopTrace() {
|
|
1884
|
+
if (!this.tracing) {
|
|
1885
|
+
throw new Error("No trace is recording; start one first");
|
|
1886
|
+
}
|
|
1887
|
+
const { startedAt } = this.tracing;
|
|
1888
|
+
const complete = this.createEventWaiter(
|
|
1889
|
+
"Tracing.tracingComplete",
|
|
1890
|
+
() => true,
|
|
1891
|
+
TRACE_COMPLETE_MS,
|
|
1892
|
+
);
|
|
1893
|
+
try {
|
|
1894
|
+
await this.send("Tracing.end");
|
|
1895
|
+
} catch (error) {
|
|
1896
|
+
// Chrome is still recording; a later stop can end it.
|
|
1897
|
+
complete.cancel();
|
|
1898
|
+
throw error;
|
|
1899
|
+
}
|
|
1900
|
+
this.tracing = null;
|
|
1901
|
+
const { stream } = await complete.promise;
|
|
1902
|
+
const chunks = [];
|
|
1903
|
+
try {
|
|
1904
|
+
while (true) {
|
|
1905
|
+
const chunk = await this.send("IO.read", {
|
|
1906
|
+
handle: stream,
|
|
1907
|
+
size: 1 << 20,
|
|
1908
|
+
});
|
|
1909
|
+
chunks.push(
|
|
1910
|
+
Buffer.from(chunk.data, chunk.base64Encoded ? "base64" : "utf8"),
|
|
1911
|
+
);
|
|
1912
|
+
if (chunk.eof) {
|
|
1913
|
+
break;
|
|
1914
|
+
}
|
|
1915
|
+
}
|
|
1916
|
+
} finally {
|
|
1917
|
+
await this.send("IO.close", { handle: stream }).catch(() => {});
|
|
1918
|
+
}
|
|
1919
|
+
return { data: Buffer.concat(chunks), durationMs: Date.now() - startedAt };
|
|
1920
|
+
}
|
|
1921
|
+
|
|
1922
|
+
// Records what the tab shows: Chrome streams a JPEG of each repaint, and
|
|
1923
|
+
// each is written to a private temp directory as it arrives, with its
|
|
1924
|
+
// time, for the stop action to encode. The first frame is a screenshot,
|
|
1925
|
+
// so a page that never repaints still has one. Frames are scaled by Chrome
|
|
1926
|
+
// to fit maxWidth and maxHeight, by default the viewport in device pixels.
|
|
1927
|
+
async startVideo(options = {}) {
|
|
1928
|
+
if (this.video) {
|
|
1929
|
+
throw new Error("A video is already recording; stop it first");
|
|
1930
|
+
}
|
|
1931
|
+
const fps = options.fps ?? 30;
|
|
1932
|
+
const quality = options.quality ?? 80;
|
|
1933
|
+
const maxDurationMs = Math.min(
|
|
1934
|
+
options.maxDurationMs ?? VIDEO_DEFAULT_DURATION_MS,
|
|
1935
|
+
VIDEO_MAX_DURATION_MS,
|
|
1936
|
+
);
|
|
1937
|
+
// Reserved before the first await, so a second start meanwhile fails
|
|
1938
|
+
// instead of making a second recording.
|
|
1939
|
+
const state = {
|
|
1940
|
+
starting: true,
|
|
1941
|
+
dir: null,
|
|
1942
|
+
fps,
|
|
1943
|
+
width: null,
|
|
1944
|
+
height: null,
|
|
1945
|
+
maxDurationMs,
|
|
1946
|
+
startedAt: Date.now() / 1000,
|
|
1947
|
+
stoppedAt: null,
|
|
1948
|
+
capturing: false,
|
|
1949
|
+
written: 0,
|
|
1950
|
+
frames: [],
|
|
1951
|
+
warnings: [],
|
|
1952
|
+
writeErrors: 0,
|
|
1953
|
+
queue: Promise.resolve(),
|
|
1954
|
+
timer: null,
|
|
1955
|
+
};
|
|
1956
|
+
this.video = state;
|
|
1957
|
+
try {
|
|
1958
|
+
const shot = await this.send("Page.captureScreenshot", {
|
|
1959
|
+
format: "jpeg",
|
|
1960
|
+
quality,
|
|
1961
|
+
});
|
|
1962
|
+
const first = Buffer.from(shot.data, "base64");
|
|
1963
|
+
const viewport = imageSize(first);
|
|
1964
|
+
if (!viewport) {
|
|
1965
|
+
throw new Error("Could not read the size of the first frame");
|
|
1966
|
+
}
|
|
1967
|
+
const scale = Math.min(
|
|
1968
|
+
1,
|
|
1969
|
+
(options.maxWidth ?? Infinity) / viewport.width,
|
|
1970
|
+
(options.maxHeight ?? Infinity) / viewport.height,
|
|
1971
|
+
);
|
|
1972
|
+
state.width = Math.max(1, Math.round(viewport.width * scale));
|
|
1973
|
+
state.height = Math.max(1, Math.round(viewport.height * scale));
|
|
1974
|
+
state.dir = await mkdtemp(
|
|
1975
|
+
path.join(tmpdir(), "mcp-browser-dev-tools-video-"),
|
|
1976
|
+
);
|
|
1977
|
+
state.capturing = true;
|
|
1978
|
+
this.writeVideoFrame(state, first, state.startedAt);
|
|
1979
|
+
await this.send("Page.startScreencast", {
|
|
1980
|
+
format: "jpeg",
|
|
1981
|
+
quality,
|
|
1982
|
+
maxWidth: state.width,
|
|
1983
|
+
maxHeight: state.height,
|
|
1984
|
+
everyNthFrame: 1,
|
|
1985
|
+
});
|
|
1986
|
+
} catch (error) {
|
|
1987
|
+
state.capturing = false;
|
|
1988
|
+
if (this.video === state) {
|
|
1989
|
+
this.video = null;
|
|
1990
|
+
}
|
|
1991
|
+
await state.queue;
|
|
1992
|
+
if (state.dir) {
|
|
1993
|
+
await rm(state.dir, { recursive: true, force: true });
|
|
1994
|
+
}
|
|
1995
|
+
throw error;
|
|
1996
|
+
}
|
|
1997
|
+
state.starting = false;
|
|
1998
|
+
state.timer = setTimeout(() => {
|
|
1999
|
+
void this.endVideoCapture(state, "maxDurationMs");
|
|
2000
|
+
}, maxDurationMs);
|
|
2001
|
+
state.timer.unref?.();
|
|
2002
|
+
return {
|
|
2003
|
+
browserFamily: cdpBrowserFamily(this.config),
|
|
2004
|
+
recording: true,
|
|
2005
|
+
dir: state.dir,
|
|
2006
|
+
startedAt: state.startedAt,
|
|
2007
|
+
width: state.width,
|
|
2008
|
+
height: state.height,
|
|
2009
|
+
fps,
|
|
2010
|
+
};
|
|
2011
|
+
}
|
|
2012
|
+
|
|
2013
|
+
// Every frame is acknowledged, or Chrome stops sending them: a recorded
|
|
2014
|
+
// frame once it is on disk, so a slow disk slows Chrome's frames rather
|
|
2015
|
+
// than filling memory with queued ones; any other frame at once.
|
|
2016
|
+
handleScreencastFrame(params) {
|
|
2017
|
+
const ack = () => {
|
|
2018
|
+
try {
|
|
2019
|
+
this.send("Page.screencastFrameAck", {
|
|
2020
|
+
sessionId: params.sessionId,
|
|
2021
|
+
}).catch(() => {});
|
|
2022
|
+
} catch {
|
|
2023
|
+
// Not connected any more; there is nothing to acknowledge to.
|
|
2024
|
+
}
|
|
2025
|
+
};
|
|
2026
|
+
const state = this.video;
|
|
2027
|
+
if (!state?.capturing) {
|
|
2028
|
+
ack();
|
|
2029
|
+
return;
|
|
2030
|
+
}
|
|
2031
|
+
this.writeVideoFrame(
|
|
2032
|
+
state,
|
|
2033
|
+
Buffer.from(params.data, "base64"),
|
|
2034
|
+
params.metadata?.timestamp ?? Date.now() / 1000,
|
|
2035
|
+
).then(ack, ack);
|
|
2036
|
+
}
|
|
2037
|
+
|
|
2038
|
+
// Writes are chained so frames keep their order and stop can wait for
|
|
2039
|
+
// the last one. A frame whose write fails is left out of the video.
|
|
2040
|
+
writeVideoFrame(state, data, timestamp) {
|
|
2041
|
+
const file = `${String(state.written).padStart(6, "0")}.jpg`;
|
|
2042
|
+
state.written += 1;
|
|
2043
|
+
state.queue = state.queue
|
|
2044
|
+
.then(async () => {
|
|
2045
|
+
await writeFile(path.join(state.dir, file), data, {
|
|
2046
|
+
flag: "wx",
|
|
2047
|
+
mode: SCREENSHOT_FILE_MODE,
|
|
2048
|
+
});
|
|
2049
|
+
state.frames.push({ file, timestamp });
|
|
2050
|
+
})
|
|
2051
|
+
.catch((error) => {
|
|
2052
|
+
state.writeErrors += 1;
|
|
2053
|
+
state.writeError = error.message;
|
|
2054
|
+
});
|
|
2055
|
+
return state.queue;
|
|
2056
|
+
}
|
|
2057
|
+
|
|
2058
|
+
// Stops taking frames (on stop, at maxDurationMs, or when the session
|
|
2059
|
+
// ends) but keeps them for stop to encode.
|
|
2060
|
+
async endVideoCapture(state, reason) {
|
|
2061
|
+
if (!state?.capturing) {
|
|
2062
|
+
return;
|
|
2063
|
+
}
|
|
2064
|
+
state.capturing = false;
|
|
2065
|
+
clearTimeout(state.timer);
|
|
2066
|
+
state.stoppedAt = Date.now() / 1000;
|
|
2067
|
+
if (reason === "maxDurationMs") {
|
|
2068
|
+
state.warnings.push(
|
|
2069
|
+
`Capture stopped at maxDurationMs (${state.maxDurationMs} ms); the frames up to then are kept, and stop encodes them`,
|
|
2070
|
+
);
|
|
2071
|
+
}
|
|
2072
|
+
if (!this.closed) {
|
|
2073
|
+
try {
|
|
2074
|
+
await this.send("Page.stopScreencast");
|
|
2075
|
+
} catch (error) {
|
|
2076
|
+
state.warnings.push(`Page.stopScreencast failed: ${error.message}`);
|
|
2077
|
+
}
|
|
2078
|
+
}
|
|
2079
|
+
}
|
|
2080
|
+
|
|
2081
|
+
// Ends the capture and hands over the frames, in order with their times,
|
|
2082
|
+
// for encoding. A closed session (the tab closed or was detached) still
|
|
2083
|
+
// hands over what it captured.
|
|
2084
|
+
async stopVideo() {
|
|
2085
|
+
const state = this.video;
|
|
2086
|
+
if (!state) {
|
|
2087
|
+
throw new Error("No video is recording; start one first");
|
|
2088
|
+
}
|
|
2089
|
+
if (state.starting) {
|
|
2090
|
+
throw new Error(
|
|
2091
|
+
"The video is still starting; stop it once start returns",
|
|
2092
|
+
);
|
|
2093
|
+
}
|
|
2094
|
+
// Taken at once, so a second stop while this one finishes has nothing
|
|
2095
|
+
// to stop and the frames are encoded once.
|
|
2096
|
+
this.video = null;
|
|
2097
|
+
await this.endVideoCapture(state, "stop");
|
|
2098
|
+
await state.queue;
|
|
2099
|
+
const warnings = [...state.warnings, ...videoGapWarnings(state)];
|
|
2100
|
+
if (state.writeErrors > 0) {
|
|
2101
|
+
warnings.push(
|
|
2102
|
+
`${state.writeErrors} frame(s) could not be written (${state.writeError})`,
|
|
2103
|
+
);
|
|
2104
|
+
}
|
|
2105
|
+
return {
|
|
2106
|
+
dir: state.dir,
|
|
2107
|
+
frames: state.frames,
|
|
2108
|
+
startedAt: state.startedAt,
|
|
2109
|
+
stoppedAt: state.stoppedAt,
|
|
2110
|
+
fps: state.fps,
|
|
2111
|
+
width: state.width,
|
|
2112
|
+
height: state.height,
|
|
2113
|
+
warnings,
|
|
2114
|
+
};
|
|
2115
|
+
}
|
|
2116
|
+
|
|
1065
2117
|
async select(selector, options = {}) {
|
|
1066
2118
|
return this.runPageAction(
|
|
1067
2119
|
{
|
|
@@ -1091,7 +2143,7 @@ export class CdpSession {
|
|
|
1091
2143
|
|
|
1092
2144
|
const delivery = await sendCheckedInput({
|
|
1093
2145
|
send: () => this.dispatchKeyEvents(events),
|
|
1094
|
-
readProbe: (disarm) => this.readInputProbe(token, disarm),
|
|
2146
|
+
readProbe: (disarm) => this.readInputProbe(token, disarm, selector),
|
|
1095
2147
|
recover: () => this.bringToFront(),
|
|
1096
2148
|
describe: `The key press "${key}"`,
|
|
1097
2149
|
});
|
|
@@ -1105,7 +2157,29 @@ export class CdpSession {
|
|
|
1105
2157
|
};
|
|
1106
2158
|
}
|
|
1107
2159
|
|
|
2160
|
+
// A selector alone scrolls its element into view and deltas alone scroll
|
|
2161
|
+
// the page. Coordinates, or a selector with deltas, send a real mouse
|
|
2162
|
+
// wheel there, which scrolls whatever is under the pointer, such as a list
|
|
2163
|
+
// inside the page.
|
|
1108
2164
|
async scroll(options = {}) {
|
|
2165
|
+
if (wheelScroll(options)) {
|
|
2166
|
+
const target = options.selector ?? { x: options.x, y: options.y };
|
|
2167
|
+
const resolved = await this.resolvePointer(target);
|
|
2168
|
+
if (!resolved.found) {
|
|
2169
|
+
return resolved;
|
|
2170
|
+
}
|
|
2171
|
+
await this.dispatchMouse("mouseWheel", resolved.point, {
|
|
2172
|
+
deltaX: options.deltaX ?? 0,
|
|
2173
|
+
deltaY: options.deltaY ?? 0,
|
|
2174
|
+
});
|
|
2175
|
+
return {
|
|
2176
|
+
browserFamily: cdpBrowserFamily(this.config),
|
|
2177
|
+
found: true,
|
|
2178
|
+
scrolled: true,
|
|
2179
|
+
wheel: { deltaX: options.deltaX ?? 0, deltaY: options.deltaY ?? 0 },
|
|
2180
|
+
...pointerFields(target, resolved),
|
|
2181
|
+
};
|
|
2182
|
+
}
|
|
1109
2183
|
return this.runPageAction(
|
|
1110
2184
|
{
|
|
1111
2185
|
action: "scroll",
|
|
@@ -1215,15 +2289,23 @@ export class CdpSession {
|
|
|
1215
2289
|
// Counts trusted input from the start of every later document, and from
|
|
1216
2290
|
// now on in the current one, so input actions can check that their input
|
|
1217
2291
|
// arrived. Without it they are reported as sent, unchecked.
|
|
1218
|
-
|
|
2292
|
+
// A cross-site iframe's target gets the recorder too, by its session.
|
|
2293
|
+
async installInputRecorder(sessionId = null) {
|
|
1219
2294
|
try {
|
|
1220
|
-
await this.send(
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
2295
|
+
await this.send(
|
|
2296
|
+
"Page.addScriptToEvaluateOnNewDocument",
|
|
2297
|
+
{ source: buildInputRecorderExpression(true) },
|
|
2298
|
+
sessionId,
|
|
2299
|
+
);
|
|
2300
|
+
await this.send(
|
|
2301
|
+
"Runtime.evaluate",
|
|
2302
|
+
{
|
|
2303
|
+
expression: buildInputRecorderExpression(false),
|
|
2304
|
+
awaitPromise: false,
|
|
2305
|
+
returnByValue: true,
|
|
2306
|
+
},
|
|
2307
|
+
sessionId,
|
|
2308
|
+
);
|
|
1227
2309
|
} catch {
|
|
1228
2310
|
// Ignore recorder failures so attach still succeeds.
|
|
1229
2311
|
}
|
|
@@ -1259,6 +2341,10 @@ export class CdpSession {
|
|
|
1259
2341
|
return this.bufferedEvents.slice(-safeLimit);
|
|
1260
2342
|
}
|
|
1261
2343
|
|
|
2344
|
+
pendingRequests() {
|
|
2345
|
+
return this.inFlight.list();
|
|
2346
|
+
}
|
|
2347
|
+
|
|
1262
2348
|
getSummary() {
|
|
1263
2349
|
return {
|
|
1264
2350
|
sessionId: this.id,
|
|
@@ -1280,6 +2366,7 @@ export class CdpSession {
|
|
|
1280
2366
|
return;
|
|
1281
2367
|
}
|
|
1282
2368
|
|
|
2369
|
+
await this.endVideoCapture(this.video, "detach");
|
|
1283
2370
|
this.websocket.close();
|
|
1284
2371
|
}
|
|
1285
2372
|
}
|
|
@@ -1288,6 +2375,9 @@ export class CdpSessionManager {
|
|
|
1288
2375
|
constructor(config) {
|
|
1289
2376
|
this.config = config;
|
|
1290
2377
|
this.sessions = new Map();
|
|
2378
|
+
// Sessions that ended while recording a video, kept by id so that stop
|
|
2379
|
+
// still encodes their frames, which are on disk.
|
|
2380
|
+
this.orphanedVideos = new Map();
|
|
1291
2381
|
this.resolvedBaseUrl = null;
|
|
1292
2382
|
this.lastAttemptedBaseUrl = null;
|
|
1293
2383
|
this.lastKnownBaseUrl = null;
|
|
@@ -1579,6 +2669,7 @@ export class CdpSessionManager {
|
|
|
1579
2669
|
eventBufferSize: this.config.eventBufferSize,
|
|
1580
2670
|
onClosed: (closedSession) => {
|
|
1581
2671
|
this.sessions.delete(closedSession.id);
|
|
2672
|
+
this.orphanVideo(closedSession);
|
|
1582
2673
|
},
|
|
1583
2674
|
});
|
|
1584
2675
|
await session.connect();
|
|
@@ -1599,12 +2690,44 @@ export class CdpSessionManager {
|
|
|
1599
2690
|
const session = this.getSession(sessionId);
|
|
1600
2691
|
await session.close();
|
|
1601
2692
|
this.sessions.delete(sessionId);
|
|
2693
|
+
const video = this.orphanVideo(session);
|
|
1602
2694
|
return {
|
|
1603
2695
|
detached: true,
|
|
1604
2696
|
sessionId,
|
|
2697
|
+
...(video ? { video } : {}),
|
|
1605
2698
|
};
|
|
1606
2699
|
}
|
|
1607
2700
|
|
|
2701
|
+
// A session that ends while recording keeps its frames: record_video
|
|
2702
|
+
// stop with the same sessionId encodes them, and the result of the
|
|
2703
|
+
// detach or close says where they are.
|
|
2704
|
+
// Up to ORPHANED_VIDEO_LIMIT such recordings are kept; past that, the
|
|
2705
|
+
// oldest one's frames are deleted, so ended sessions cannot fill the disk.
|
|
2706
|
+
orphanVideo(session) {
|
|
2707
|
+
if (!session.video?.dir) {
|
|
2708
|
+
return null;
|
|
2709
|
+
}
|
|
2710
|
+
this.orphanedVideos.set(session.id, session);
|
|
2711
|
+
for (const [id, oldest] of this.orphanedVideos) {
|
|
2712
|
+
if (this.orphanedVideos.size <= ORPHANED_VIDEO_LIMIT) {
|
|
2713
|
+
break;
|
|
2714
|
+
}
|
|
2715
|
+
this.orphanedVideos.delete(id);
|
|
2716
|
+
void this.discardOrphanedVideo(oldest);
|
|
2717
|
+
}
|
|
2718
|
+
return {
|
|
2719
|
+
framesDir: session.video.dir,
|
|
2720
|
+
note: `The recording's frames are kept; record_video stop with this sessionId encodes them (the frames of the ${ORPHANED_VIDEO_LIMIT} most recently ended recordings are kept)`,
|
|
2721
|
+
};
|
|
2722
|
+
}
|
|
2723
|
+
|
|
2724
|
+
async discardOrphanedVideo(session) {
|
|
2725
|
+
const state = session.video;
|
|
2726
|
+
session.video = null;
|
|
2727
|
+
await state.queue;
|
|
2728
|
+
await rm(state.dir, { recursive: true, force: true });
|
|
2729
|
+
}
|
|
2730
|
+
|
|
1608
2731
|
async closeTarget(targetId) {
|
|
1609
2732
|
const result = await this.sendBrowserCommand("Target.closeTarget", {
|
|
1610
2733
|
targetId,
|
|
@@ -1618,7 +2741,8 @@ export class CdpSessionManager {
|
|
|
1618
2741
|
.map((session) => {
|
|
1619
2742
|
session.markClosed?.();
|
|
1620
2743
|
this.sessions.delete(session.id);
|
|
1621
|
-
|
|
2744
|
+
const video = this.orphanVideo(session);
|
|
2745
|
+
return { sessionId: session.id, ...(video ? { video } : {}) };
|
|
1622
2746
|
});
|
|
1623
2747
|
|
|
1624
2748
|
return {
|
|
@@ -1659,12 +2783,51 @@ export class CdpSessionManager {
|
|
|
1659
2783
|
return this.getSession(sessionId).reload(options);
|
|
1660
2784
|
}
|
|
1661
2785
|
|
|
1662
|
-
async click(sessionId,
|
|
1663
|
-
return this.getSession(sessionId).click(
|
|
2786
|
+
async click(sessionId, target, options) {
|
|
2787
|
+
return this.getSession(sessionId).click(target, options);
|
|
1664
2788
|
}
|
|
1665
2789
|
|
|
1666
|
-
async hover(sessionId,
|
|
1667
|
-
return this.getSession(sessionId).hover(
|
|
2790
|
+
async hover(sessionId, target) {
|
|
2791
|
+
return this.getSession(sessionId).hover(target);
|
|
2792
|
+
}
|
|
2793
|
+
|
|
2794
|
+
async drag(sessionId, from, to, options) {
|
|
2795
|
+
return this.getSession(sessionId).drag(from, to, options);
|
|
2796
|
+
}
|
|
2797
|
+
|
|
2798
|
+
async uploadFiles(sessionId, selector, files) {
|
|
2799
|
+
return this.getSession(sessionId).uploadFiles(selector, files);
|
|
2800
|
+
}
|
|
2801
|
+
|
|
2802
|
+
async setNetwork(sessionId, options) {
|
|
2803
|
+
return this.getSession(sessionId).setNetwork(options);
|
|
2804
|
+
}
|
|
2805
|
+
|
|
2806
|
+
async getPerformance(sessionId) {
|
|
2807
|
+
return this.getSession(sessionId).getPerformance();
|
|
2808
|
+
}
|
|
2809
|
+
|
|
2810
|
+
async startTrace(sessionId, options) {
|
|
2811
|
+
return this.getSession(sessionId).startTrace(options);
|
|
2812
|
+
}
|
|
2813
|
+
|
|
2814
|
+
async stopTrace(sessionId) {
|
|
2815
|
+
return this.getSession(sessionId).stopTrace();
|
|
2816
|
+
}
|
|
2817
|
+
|
|
2818
|
+
async startVideo(sessionId, options) {
|
|
2819
|
+
return this.getSession(sessionId).startVideo(options);
|
|
2820
|
+
}
|
|
2821
|
+
|
|
2822
|
+
async stopVideo(sessionId) {
|
|
2823
|
+
const session =
|
|
2824
|
+
this.sessions.get(sessionId) ?? this.orphanedVideos.get(sessionId);
|
|
2825
|
+
if (!session) {
|
|
2826
|
+
throw new Error(`No active session found for ${sessionId}`);
|
|
2827
|
+
}
|
|
2828
|
+
const capture = await session.stopVideo();
|
|
2829
|
+
this.orphanedVideos.delete(sessionId);
|
|
2830
|
+
return capture;
|
|
1668
2831
|
}
|
|
1669
2832
|
|
|
1670
2833
|
async type(sessionId, selector, text, options) {
|
|
@@ -1731,10 +2894,22 @@ export class CdpSessionManager {
|
|
|
1731
2894
|
return this.getSession(sessionId).snapshotControls();
|
|
1732
2895
|
}
|
|
1733
2896
|
|
|
2897
|
+
async snapshotPage(sessionId, options) {
|
|
2898
|
+
return this.getSession(sessionId).snapshotPage(options);
|
|
2899
|
+
}
|
|
2900
|
+
|
|
2901
|
+
async trackChanges(sessionId, phase, options) {
|
|
2902
|
+
return this.getSession(sessionId).trackChanges(phase, options);
|
|
2903
|
+
}
|
|
2904
|
+
|
|
1734
2905
|
async inspectElement(sessionId, selector, options) {
|
|
1735
2906
|
return this.getSession(sessionId).inspectElement(selector, options);
|
|
1736
2907
|
}
|
|
1737
2908
|
|
|
2909
|
+
pendingRequests(sessionId) {
|
|
2910
|
+
return this.getSession(sessionId).pendingRequests();
|
|
2911
|
+
}
|
|
2912
|
+
|
|
1738
2913
|
getEvents(sessionId, limit) {
|
|
1739
2914
|
return this.getSession(sessionId).getEvents(limit);
|
|
1740
2915
|
}
|