@pyrokine/mcp-chrome 3.0.0 → 3.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/README.md +721 -303
- package/README_zh.md +750 -292
- package/dist/cdp/client.d.ts +7 -3
- package/dist/cdp/client.d.ts.map +1 -1
- package/dist/cdp/client.js +252 -63
- package/dist/cdp/client.js.map +1 -1
- package/dist/cdp/launcher.d.ts +1 -1
- package/dist/cdp/launcher.d.ts.map +1 -1
- package/dist/cdp/launcher.js +33 -12
- package/dist/cdp/launcher.js.map +1 -1
- package/dist/core/auto-wait.d.ts.map +1 -1
- package/dist/core/auto-wait.js +88 -52
- package/dist/core/auto-wait.js.map +1 -1
- package/dist/core/browser-driver.d.ts +76 -18
- package/dist/core/browser-driver.d.ts.map +1 -1
- package/dist/core/browser-driver.js.map +1 -1
- package/dist/core/browser-event-schema.d.ts +287 -0
- package/dist/core/browser-event-schema.d.ts.map +1 -0
- package/dist/core/browser-event-schema.js +104 -0
- package/dist/core/browser-event-schema.js.map +1 -0
- package/dist/core/browser-events.d.ts +99 -0
- package/dist/core/browser-events.d.ts.map +1 -0
- package/dist/core/browser-events.js +1312 -0
- package/dist/core/browser-events.js.map +1 -0
- package/dist/core/challenge-page.d.ts +39 -0
- package/dist/core/challenge-page.d.ts.map +1 -0
- package/dist/core/challenge-page.js +226 -0
- package/dist/core/challenge-page.js.map +1 -0
- package/dist/core/dom-helpers.d.ts +28 -0
- package/dist/core/dom-helpers.d.ts.map +1 -0
- package/dist/core/dom-helpers.js +311 -0
- package/dist/core/dom-helpers.js.map +1 -0
- package/dist/core/errors.d.ts +10 -4
- package/dist/core/errors.d.ts.map +1 -1
- package/dist/core/errors.js +63 -13
- package/dist/core/errors.js.map +1 -1
- package/dist/core/file-upload.d.ts +22 -0
- package/dist/core/file-upload.d.ts.map +1 -0
- package/dist/core/file-upload.js +194 -0
- package/dist/core/file-upload.js.map +1 -0
- package/dist/core/locator.d.ts +17 -2
- package/dist/core/locator.d.ts.map +1 -1
- package/dist/core/locator.js +156 -212
- package/dist/core/locator.js.map +1 -1
- package/dist/core/os-mouse.d.ts +11 -0
- package/dist/core/os-mouse.d.ts.map +1 -1
- package/dist/core/os-mouse.js +102 -29
- package/dist/core/os-mouse.js.map +1 -1
- package/dist/core/retry.d.ts.map +1 -1
- package/dist/core/retry.js +4 -1
- package/dist/core/retry.js.map +1 -1
- package/dist/core/session.d.ts +65 -14
- package/dist/core/session.d.ts.map +1 -1
- package/dist/core/session.js +1089 -273
- package/dist/core/session.js.map +1 -1
- package/dist/core/types.d.ts +5 -1
- package/dist/core/types.d.ts.map +1 -1
- package/dist/core/types.js +16 -1
- package/dist/core/types.js.map +1 -1
- package/dist/core/unified-session.d.ts +50 -41
- package/dist/core/unified-session.d.ts.map +1 -1
- package/dist/core/unified-session.js +938 -285
- package/dist/core/unified-session.js.map +1 -1
- package/dist/core/utils.d.ts +5 -4
- package/dist/core/utils.d.ts.map +1 -1
- package/dist/core/utils.js +73 -18
- package/dist/core/utils.js.map +1 -1
- package/dist/extension/bridge.d.ts +50 -19
- package/dist/extension/bridge.d.ts.map +1 -1
- package/dist/extension/bridge.js +289 -57
- package/dist/extension/bridge.js.map +1 -1
- package/dist/extension/http-server.d.ts +7 -2
- package/dist/extension/http-server.d.ts.map +1 -1
- package/dist/extension/http-server.js +219 -48
- package/dist/extension/http-server.js.map +1 -1
- package/dist/index.js +14 -1
- package/dist/index.js.map +1 -1
- package/dist/tools/browse.d.ts.map +1 -1
- package/dist/tools/browse.js +66 -32
- package/dist/tools/browse.js.map +1 -1
- package/dist/tools/browser-event-output.d.ts +7 -0
- package/dist/tools/browser-event-output.d.ts.map +1 -0
- package/dist/tools/browser-event-output.js +19 -0
- package/dist/tools/browser-event-output.js.map +1 -0
- package/dist/tools/challenge.d.ts +17 -5
- package/dist/tools/challenge.d.ts.map +1 -1
- package/dist/tools/challenge.js +113 -195
- package/dist/tools/challenge.js.map +1 -1
- package/dist/tools/cookies.d.ts.map +1 -1
- package/dist/tools/cookies.js +33 -8
- package/dist/tools/cookies.js.map +1 -1
- package/dist/tools/diagnostics.d.ts.map +1 -1
- package/dist/tools/diagnostics.js +14 -0
- package/dist/tools/diagnostics.js.map +1 -1
- package/dist/tools/evaluate.d.ts +6 -5
- package/dist/tools/evaluate.d.ts.map +1 -1
- package/dist/tools/evaluate.js +102 -52
- package/dist/tools/evaluate.js.map +1 -1
- package/dist/tools/extract.d.ts.map +1 -1
- package/dist/tools/extract.js +178 -124
- package/dist/tools/extract.js.map +1 -1
- package/dist/tools/input.d.ts.map +1 -1
- package/dist/tools/input.js +623 -271
- package/dist/tools/input.js.map +1 -1
- package/dist/tools/logs.d.ts.map +1 -1
- package/dist/tools/logs.js +50 -11
- package/dist/tools/logs.js.map +1 -1
- package/dist/tools/manage.d.ts.map +1 -1
- package/dist/tools/manage.js +127 -46
- package/dist/tools/manage.js.map +1 -1
- package/dist/tools/network-sanitizer.d.ts +1 -0
- package/dist/tools/network-sanitizer.d.ts.map +1 -1
- package/dist/tools/network-sanitizer.js +30 -1
- package/dist/tools/network-sanitizer.js.map +1 -1
- package/dist/tools/page-context.d.ts +4 -3
- package/dist/tools/page-context.d.ts.map +1 -1
- package/dist/tools/page-context.js +56 -14
- package/dist/tools/page-context.js.map +1 -1
- package/dist/tools/post-condition.d.ts +1 -1
- package/dist/tools/post-condition.d.ts.map +1 -1
- package/dist/tools/post-condition.js +153 -47
- package/dist/tools/post-condition.js.map +1 -1
- package/dist/tools/schema.d.ts +7 -4
- package/dist/tools/schema.d.ts.map +1 -1
- package/dist/tools/schema.js +32 -122
- package/dist/tools/schema.js.map +1 -1
- package/dist/tools/target-diagnostics.d.ts +10 -2
- package/dist/tools/target-diagnostics.d.ts.map +1 -1
- package/dist/tools/target-diagnostics.js +74 -21
- package/dist/tools/target-diagnostics.js.map +1 -1
- package/dist/tools/wait.d.ts.map +1 -1
- package/dist/tools/wait.js +108 -42
- package/dist/tools/wait.js.map +1 -1
- package/extension/dist/assets/{content.ts-C4imZ6A9.js → content.ts-BAMOcF3R.js} +1 -1
- package/extension/dist/assets/{content.ts-loader-CnJuCGhl.js → content.ts-loader-4F9a1EWZ.js} +1 -1
- package/extension/dist/assets/index.ts-B79g2ikq.js +19820 -0
- package/extension/dist/assets/{page-scripts-CMIY1zhd.js → page-scripts-CSxn58h1.js} +300 -410
- package/extension/dist/assets/{popup.html-CgtWL6Py.js → popup.html-DwwHo00N.js} +8 -6
- package/extension/dist/manifest.json +4 -4
- package/extension/dist/service-worker-loader.js +1 -1
- package/extension/dist/src/popup/popup.html +3 -3
- package/package.json +15 -7
- package/scripts/start-chrome.ps1 +9 -1
- package/extension/dist/assets/index.ts-GeHNZBml.js +0 -8972
|
@@ -0,0 +1,1312 @@
|
|
|
1
|
+
import { sanitizeUrl } from '../tools/network-sanitizer.js';
|
|
2
|
+
import { getErrorSource } from './errors.js';
|
|
3
|
+
const MAX_ENTRIES = 500;
|
|
4
|
+
const MAX_PENDING = 64;
|
|
5
|
+
const MAX_METADATA = 16 * 1024 * 1024;
|
|
6
|
+
const MAX_BYTES = 48 * 1024 * 1024;
|
|
7
|
+
const MAX_BODY = 16 * 1024 * 1024;
|
|
8
|
+
const MAX_MESSAGE = 64 * 1024;
|
|
9
|
+
const TTL = 5 * 60_000;
|
|
10
|
+
const PAUSE_TTL = 30_000;
|
|
11
|
+
export function eventRefTarget(ref) {
|
|
12
|
+
const parts = ref.split(':');
|
|
13
|
+
if (parts.length !== 7 || parts[0] !== 'be') {
|
|
14
|
+
throw new Error('Invalid browser event ref');
|
|
15
|
+
}
|
|
16
|
+
return { backend: parts[1], targetId: decodeURIComponent(parts[2]) };
|
|
17
|
+
}
|
|
18
|
+
function matches(value, pattern = '*') {
|
|
19
|
+
if (!pattern.includes('*') && !pattern.includes('?')) {
|
|
20
|
+
return value.includes(pattern);
|
|
21
|
+
}
|
|
22
|
+
let position = 0;
|
|
23
|
+
let index = 0;
|
|
24
|
+
let star = -1;
|
|
25
|
+
let restart = 0;
|
|
26
|
+
while (position < value.length) {
|
|
27
|
+
if (pattern[index] === '?' || pattern[index] === value[position]) {
|
|
28
|
+
++position;
|
|
29
|
+
++index;
|
|
30
|
+
}
|
|
31
|
+
else if (pattern[index] === '*') {
|
|
32
|
+
star = index++;
|
|
33
|
+
restart = position;
|
|
34
|
+
}
|
|
35
|
+
else if (star >= 0) {
|
|
36
|
+
index = star + 1;
|
|
37
|
+
position = ++restart;
|
|
38
|
+
}
|
|
39
|
+
else {
|
|
40
|
+
return false;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
while (pattern[index] === '*') {
|
|
44
|
+
++index;
|
|
45
|
+
}
|
|
46
|
+
return index === pattern.length;
|
|
47
|
+
}
|
|
48
|
+
function bytes(payload) {
|
|
49
|
+
if (payload.encoding === 'utf8') {
|
|
50
|
+
return new TextEncoder().encode(payload.data).length;
|
|
51
|
+
}
|
|
52
|
+
if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(payload.data)) {
|
|
53
|
+
throw new Error('Invalid base64 payload');
|
|
54
|
+
}
|
|
55
|
+
return (payload.data.length / 4) * 3 - (payload.data.endsWith('==') ? 2 : payload.data.endsWith('=') ? 1 : 0);
|
|
56
|
+
}
|
|
57
|
+
function base64(payload) {
|
|
58
|
+
if (bytes(payload) >= MAX_BODY) {
|
|
59
|
+
throw new Error('Payload exceeds the 16 MiB event body budget');
|
|
60
|
+
}
|
|
61
|
+
if (payload.encoding === 'base64') {
|
|
62
|
+
return payload.data;
|
|
63
|
+
}
|
|
64
|
+
const data = new TextEncoder().encode(payload.data);
|
|
65
|
+
let binary = '';
|
|
66
|
+
for (let i = 0; i < data.length; i += 8192) {
|
|
67
|
+
binary += String.fromCharCode(...data.subarray(i, i + 8192));
|
|
68
|
+
}
|
|
69
|
+
return btoa(binary);
|
|
70
|
+
}
|
|
71
|
+
function bounded(value, depth = 0) {
|
|
72
|
+
if (typeof value === 'string') {
|
|
73
|
+
return value.slice(0, MAX_MESSAGE);
|
|
74
|
+
}
|
|
75
|
+
if (!value || typeof value !== 'object') {
|
|
76
|
+
return value;
|
|
77
|
+
}
|
|
78
|
+
if (depth >= 8) {
|
|
79
|
+
return '[metadata depth limit]';
|
|
80
|
+
}
|
|
81
|
+
if (Array.isArray(value)) {
|
|
82
|
+
return value.slice(0, 1000).map((v) => bounded(v, depth + 1));
|
|
83
|
+
}
|
|
84
|
+
const result = Object.fromEntries(Object.entries(value)
|
|
85
|
+
.slice(0, 1000)
|
|
86
|
+
.map(([key, v]) => [
|
|
87
|
+
key,
|
|
88
|
+
/^(?:postData|postDataEntries)$/.test(key)
|
|
89
|
+
? '[read original requestBody by ref]'
|
|
90
|
+
: bounded(v, depth + 1),
|
|
91
|
+
]));
|
|
92
|
+
if (depth === 0 && new TextEncoder().encode(JSON.stringify(result)).length > 128 * 1024) {
|
|
93
|
+
const retained = Object.fromEntries(Object.entries(result).filter(([key, v]) => typeof v !== 'object' && !['data', 'message', 'defaultPrompt'].includes(key)));
|
|
94
|
+
return {
|
|
95
|
+
...retained,
|
|
96
|
+
metadataTruncated: true,
|
|
97
|
+
...(result.request
|
|
98
|
+
? {
|
|
99
|
+
request: {
|
|
100
|
+
url: result.request.url,
|
|
101
|
+
method: result.request.method,
|
|
102
|
+
},
|
|
103
|
+
}
|
|
104
|
+
: {}),
|
|
105
|
+
...(result.response
|
|
106
|
+
? {
|
|
107
|
+
response: {
|
|
108
|
+
status: result.response.status,
|
|
109
|
+
payloadData: result.response.payloadData,
|
|
110
|
+
opcode: result.response.opcode,
|
|
111
|
+
},
|
|
112
|
+
}
|
|
113
|
+
: {}),
|
|
114
|
+
...(typeof result.data === 'string' && !result.response ? { data: result.data } : {}),
|
|
115
|
+
...(typeof result.message === 'string' ? { message: result.message.slice(0, 16 * 1024) } : {}),
|
|
116
|
+
...(typeof result.defaultPrompt === 'string'
|
|
117
|
+
? { defaultPrompt: result.defaultPrompt.slice(0, 16 * 1024) }
|
|
118
|
+
: {}),
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
return result;
|
|
122
|
+
}
|
|
123
|
+
function redact(value, key = '') {
|
|
124
|
+
if (/^(?:authorization|proxy-authorization|cookie|set-cookie|cookieLine|password|username)$/i.test(key)) {
|
|
125
|
+
return '[REDACTED]';
|
|
126
|
+
}
|
|
127
|
+
if (Array.isArray(value)) {
|
|
128
|
+
return value.map((v) => redact(v));
|
|
129
|
+
}
|
|
130
|
+
if (value && typeof value === 'object' && 'name' in value && 'value' in value) {
|
|
131
|
+
return { ...value, value: redact(value.value, String(value.name)) };
|
|
132
|
+
}
|
|
133
|
+
if (value && typeof value === 'object') {
|
|
134
|
+
return Object.fromEntries(Object.entries(value)
|
|
135
|
+
.filter(([k]) => k !== 'timer' && k !== 'bodyRead')
|
|
136
|
+
.map(([k, v]) => [k, redact(v, k)]));
|
|
137
|
+
}
|
|
138
|
+
if (typeof value === 'string' && /^(?:request|response)?headersText$/i.test(key)) {
|
|
139
|
+
return value
|
|
140
|
+
.replace(/^(?<method>[A-Z]+)\s+(?<url>\S+)\s+(?<protocol>HTTP\/[^\r\n]+)/, (_line, method, url, protocol) => `${method} ${redact(url, 'url')} ${protocol}`)
|
|
141
|
+
.replace(/^(?<h>authorization|proxy-authorization|cookie|set-cookie):[^\r\n]*(?:\r?\n[ \t]+[^\r\n]*)*/gim, '$<h>: [REDACTED]')
|
|
142
|
+
.replace(/^(?<header>(?:location|content-location|referer|referrer|origin):[ \t]*)(?<url>[^\r\n]*)/gim, (_line, header, url) => `${header}${redact(url, 'url')}`);
|
|
143
|
+
}
|
|
144
|
+
if (typeof value === 'string' &&
|
|
145
|
+
/^(?:url|documentURL|origin|location|content-location|referer|referrer)$/i.test(key)) {
|
|
146
|
+
const sanitized = sanitizeUrl(value).url;
|
|
147
|
+
return sanitized.replace(/^(?<scheme>(?:https?|wss?):\/\/)[^/@]+@/i, '$<scheme>[REDACTED]@');
|
|
148
|
+
}
|
|
149
|
+
return value;
|
|
150
|
+
}
|
|
151
|
+
/** Native event state is shared by CDP and chrome.debugger; it never re-fetches a URL. */
|
|
152
|
+
export class BrowserEventController {
|
|
153
|
+
identity;
|
|
154
|
+
send;
|
|
155
|
+
sequence = 0;
|
|
156
|
+
entries = new Map();
|
|
157
|
+
requests = new Map();
|
|
158
|
+
extras = new Map();
|
|
159
|
+
pauses = new Map();
|
|
160
|
+
bodies = new Map();
|
|
161
|
+
bodyBytes = 0;
|
|
162
|
+
dropped = 0;
|
|
163
|
+
evicted = 0;
|
|
164
|
+
dialogWatching = true;
|
|
165
|
+
rawAuthentication = false;
|
|
166
|
+
dialog;
|
|
167
|
+
dialogWaiters = new Set();
|
|
168
|
+
routes = new Map();
|
|
169
|
+
credentials;
|
|
170
|
+
challenged = new Set();
|
|
171
|
+
capture = new Set();
|
|
172
|
+
downloading = false;
|
|
173
|
+
downloadPattern = '*';
|
|
174
|
+
fetchEnabled = false;
|
|
175
|
+
fetchConfig = Promise.resolve();
|
|
176
|
+
active = true;
|
|
177
|
+
documentRevision = 0;
|
|
178
|
+
downloadBodies = new Map();
|
|
179
|
+
downloadWaiters = new Set();
|
|
180
|
+
cleanupFailures = [];
|
|
181
|
+
constructor(identity, send) {
|
|
182
|
+
this.identity = identity;
|
|
183
|
+
this.send = send;
|
|
184
|
+
}
|
|
185
|
+
handle(method, raw, sessionId) {
|
|
186
|
+
if (!this.active) {
|
|
187
|
+
return;
|
|
188
|
+
}
|
|
189
|
+
const p = raw;
|
|
190
|
+
if (method === 'Page.javascriptDialogOpening') {
|
|
191
|
+
if (!this.dialogWatching) {
|
|
192
|
+
return;
|
|
193
|
+
}
|
|
194
|
+
this.dialog = this.make('dialog', { ...p, sessionId, state: 'pending' });
|
|
195
|
+
const error = this.dialogError();
|
|
196
|
+
for (const reject of this.dialogWaiters) {
|
|
197
|
+
reject(error);
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
else if (method === 'Page.javascriptDialogClosed' && this.dialog) {
|
|
201
|
+
Object.assign(this.dialog, { state: 'closed', result: p.result, userInput: p.userInput });
|
|
202
|
+
this.dialog = undefined;
|
|
203
|
+
}
|
|
204
|
+
else if (method === 'Page.frameNavigated' &&
|
|
205
|
+
!p.frame?.parentId &&
|
|
206
|
+
sessionId === this.identity.nativeSessionId) {
|
|
207
|
+
this.documentRevision++;
|
|
208
|
+
void this.abortPending('navigation');
|
|
209
|
+
this.challenged.clear();
|
|
210
|
+
if (this.dialog) {
|
|
211
|
+
this.dialog.state = 'invalidated';
|
|
212
|
+
this.dialog = undefined;
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
else if (method === 'Page.frameNavigated') {
|
|
216
|
+
for (const pause of this.pauses.values()) {
|
|
217
|
+
if ((p.frame?.id && pause.frameId === p.frame.id) ||
|
|
218
|
+
(sessionId !== this.identity.nativeSessionId && pause.sessionId === sessionId)) {
|
|
219
|
+
void this.abortOne(pause, 'frame navigation');
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
else if (method === 'Network.requestWillBeSent') {
|
|
224
|
+
const key = this.key(p.requestId, sessionId);
|
|
225
|
+
const hops = this.requests.get(key) ?? [];
|
|
226
|
+
if (p.redirectResponse && hops.length) {
|
|
227
|
+
Object.assign(hops.at(-1), {
|
|
228
|
+
response: bounded(p.redirectResponse),
|
|
229
|
+
state: 'redirected',
|
|
230
|
+
extraExpected: p.redirectHasExtraInfo === true,
|
|
231
|
+
});
|
|
232
|
+
}
|
|
233
|
+
const entry = this.make('request', {
|
|
234
|
+
requestId: p.requestId,
|
|
235
|
+
hop: hops.length,
|
|
236
|
+
url: p.request.url,
|
|
237
|
+
request: p.request,
|
|
238
|
+
frameId: p.frameId,
|
|
239
|
+
loaderId: p.loaderId,
|
|
240
|
+
type: p.type,
|
|
241
|
+
sessionId,
|
|
242
|
+
state: 'pending',
|
|
243
|
+
protocolTimestamp: p.timestamp,
|
|
244
|
+
});
|
|
245
|
+
hops.push(entry);
|
|
246
|
+
this.requests.set(key, hops);
|
|
247
|
+
this.bindExtras(key);
|
|
248
|
+
}
|
|
249
|
+
else if (method === 'Network.requestWillBeSentExtraInfo' || method === 'Network.responseReceivedExtraInfo') {
|
|
250
|
+
const key = this.key(p.requestId, sessionId);
|
|
251
|
+
const extras = this.extras.get(key) ?? { request: [], response: [] };
|
|
252
|
+
const queue = method.endsWith('requestWillBeSentExtraInfo') ? extras.request : extras.response;
|
|
253
|
+
const queued = [...this.extras.values()].reduce((count, value) => count + value.request.length + value.response.length, 0);
|
|
254
|
+
if (queued < MAX_ENTRIES) {
|
|
255
|
+
queue.push(bounded(p));
|
|
256
|
+
}
|
|
257
|
+
else {
|
|
258
|
+
this.dropped++;
|
|
259
|
+
}
|
|
260
|
+
this.extras.set(key, extras);
|
|
261
|
+
this.bindExtras(key);
|
|
262
|
+
}
|
|
263
|
+
else if (method === 'Network.responseReceived') {
|
|
264
|
+
const request = this.latest(p.requestId, sessionId);
|
|
265
|
+
if (request) {
|
|
266
|
+
Object.assign(request, {
|
|
267
|
+
response: bounded(p.response),
|
|
268
|
+
extraExpected: p.hasExtraInfo === true,
|
|
269
|
+
...(JSON.stringify(p.response) !== JSON.stringify(bounded(p.response))
|
|
270
|
+
? { metadataTruncated: true }
|
|
271
|
+
: {}),
|
|
272
|
+
});
|
|
273
|
+
this.bindExtras(this.key(p.requestId, sessionId));
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
else if (method === 'Network.loadingFinished' || method === 'Network.loadingFailed') {
|
|
277
|
+
const request = this.latest(p.requestId, sessionId);
|
|
278
|
+
if (request) {
|
|
279
|
+
Object.assign(request, {
|
|
280
|
+
state: method.endsWith('loadingFinished') ? 'finished' : 'failed',
|
|
281
|
+
errorText: p.errorText,
|
|
282
|
+
encodedDataLength: p.encodedDataLength,
|
|
283
|
+
});
|
|
284
|
+
if (this.capture.has('body') && request.state === 'finished') {
|
|
285
|
+
void this.readBody(request, 'responseBody').catch((e) => {
|
|
286
|
+
request.bodyError = this.failure(e);
|
|
287
|
+
});
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
else if (this.capture.has('stream') && /^Network\.(?:webSocket|eventSource)/.test(method)) {
|
|
292
|
+
const data = p.response?.payloadData ?? p.data;
|
|
293
|
+
const dataText = typeof data === 'string' ? data : undefined;
|
|
294
|
+
const encoded = dataText === undefined ? undefined : new TextEncoder().encode(dataText);
|
|
295
|
+
const truncated = (encoded?.length ?? 0) > MAX_MESSAGE;
|
|
296
|
+
const message = truncated ? new TextDecoder().decode(encoded.subarray(0, MAX_MESSAGE)) : dataText;
|
|
297
|
+
this.make('stream', {
|
|
298
|
+
...p,
|
|
299
|
+
response: p.response ? { ...p.response, payloadData: message } : undefined,
|
|
300
|
+
data: message,
|
|
301
|
+
truncated,
|
|
302
|
+
originalBytes: encoded?.length,
|
|
303
|
+
protocolTimestamp: p.timestamp,
|
|
304
|
+
nativeMethod: method,
|
|
305
|
+
direction: method.includes('Sent')
|
|
306
|
+
? 'sent'
|
|
307
|
+
: method.includes('Received') || method.includes('MessageReceived')
|
|
308
|
+
? 'received'
|
|
309
|
+
: 'lifecycle',
|
|
310
|
+
sessionId,
|
|
311
|
+
requestRef: this.latest(p.requestId, sessionId)?.ref,
|
|
312
|
+
sequence: this.sequence + 1,
|
|
313
|
+
});
|
|
314
|
+
}
|
|
315
|
+
else if (method === 'Fetch.requestPaused') {
|
|
316
|
+
void this.onPaused(p, sessionId).catch((e) => {
|
|
317
|
+
this.recordCleanupFailure(e, method, p.requestId, sessionId);
|
|
318
|
+
});
|
|
319
|
+
}
|
|
320
|
+
else if (method === 'Fetch.authRequired') {
|
|
321
|
+
void this.onAuth(p, sessionId).catch((e) => {
|
|
322
|
+
this.recordCleanupFailure(e, method, p.requestId, sessionId);
|
|
323
|
+
});
|
|
324
|
+
}
|
|
325
|
+
else if (method === 'Page.downloadWillBegin' || method === 'Browser.downloadWillBegin') {
|
|
326
|
+
if (!this.downloading || !matches(p.url, this.downloadPattern)) {
|
|
327
|
+
return;
|
|
328
|
+
}
|
|
329
|
+
const existing = [...this.entries.values()].find((e) => e.kind === 'download' && e.guid === p.guid);
|
|
330
|
+
if (existing) {
|
|
331
|
+
return;
|
|
332
|
+
}
|
|
333
|
+
const candidates = p.frameId ? (this.downloadBodies.get(p.frameId) ?? []) : [];
|
|
334
|
+
const captured = candidates.length === 1 && candidates[0].url === p.url ? candidates[0] : undefined;
|
|
335
|
+
const entry = this.make('download', {
|
|
336
|
+
...p,
|
|
337
|
+
sessionId,
|
|
338
|
+
state: 'inProgress',
|
|
339
|
+
artifact: captured ? 'available' : 'unavailable',
|
|
340
|
+
bodyRef: captured?.ref,
|
|
341
|
+
artifactReason: captured
|
|
342
|
+
? undefined
|
|
343
|
+
: candidates.length > 1
|
|
344
|
+
? 'Multiple original response candidates in this frame; native GUID cannot be assigned safely'
|
|
345
|
+
: 'Original response unavailable (blob, Save As, browser security, or uncaptured response)',
|
|
346
|
+
});
|
|
347
|
+
if (p.frameId && (captured || candidates.length > 1)) {
|
|
348
|
+
this.downloadBodies.delete(p.frameId);
|
|
349
|
+
}
|
|
350
|
+
void entry;
|
|
351
|
+
this.notifyDownloads();
|
|
352
|
+
}
|
|
353
|
+
else if (method === 'Page.downloadProgress' || method === 'Browser.downloadProgress') {
|
|
354
|
+
const entry = [...this.entries.values()].find((e) => e.kind === 'download' && e.guid === p.guid);
|
|
355
|
+
if (entry) {
|
|
356
|
+
Object.assign(entry, { ...p });
|
|
357
|
+
this.notifyDownloads();
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
assertNativeReady() {
|
|
362
|
+
if (this.dialog && ['pending', 'resolving', 'unknown'].includes(String(this.dialog.state))) {
|
|
363
|
+
throw this.dialogError(false);
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
async race(operation) {
|
|
367
|
+
this.dialogWatching = true;
|
|
368
|
+
if (this.dialog?.state === 'pending') {
|
|
369
|
+
void operation.catch(() => { });
|
|
370
|
+
throw this.dialogError();
|
|
371
|
+
}
|
|
372
|
+
let rejectDialog = () => { };
|
|
373
|
+
const dialog = new Promise((_, reject) => {
|
|
374
|
+
rejectDialog = reject;
|
|
375
|
+
this.dialogWaiters.add(reject);
|
|
376
|
+
});
|
|
377
|
+
try {
|
|
378
|
+
return await Promise.race([operation, dialog]);
|
|
379
|
+
}
|
|
380
|
+
finally {
|
|
381
|
+
this.dialogWaiters.delete(rejectDialog);
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
async command(action, command, signal) {
|
|
385
|
+
signal?.throwIfAborted();
|
|
386
|
+
if (!this.active) {
|
|
387
|
+
throw new Error('Browser event session is closed');
|
|
388
|
+
}
|
|
389
|
+
if (action === 'read') {
|
|
390
|
+
return this.read(command);
|
|
391
|
+
}
|
|
392
|
+
const op = command.op;
|
|
393
|
+
if (action === 'dialog') {
|
|
394
|
+
if (op === 'watch') {
|
|
395
|
+
this.dialogWatching = true;
|
|
396
|
+
await this.send('Page.enable');
|
|
397
|
+
return this.status();
|
|
398
|
+
}
|
|
399
|
+
if (op === 'stop') {
|
|
400
|
+
this.dialogWatching = false;
|
|
401
|
+
return { ...this.status(), stopped: true, pending: this.dialog?.ref ?? null };
|
|
402
|
+
}
|
|
403
|
+
const entry = this.require(command.ref, 'dialog');
|
|
404
|
+
if (entry !== this.dialog || !['pending', 'resolving'].includes(String(entry.state))) {
|
|
405
|
+
throw new Error('Dialog is no longer pending');
|
|
406
|
+
}
|
|
407
|
+
if (entry.state === 'resolving') {
|
|
408
|
+
throw new Error('Dialog handling already dispatched; outcome pending');
|
|
409
|
+
}
|
|
410
|
+
entry.state = 'resolving';
|
|
411
|
+
try {
|
|
412
|
+
await this.send('Page.handleJavaScriptDialog', { accept: op === 'accept', ...(command.text !== undefined ? { promptText: command.text } : {}) }, entry.sessionId);
|
|
413
|
+
if (entry.state === 'resolving') {
|
|
414
|
+
entry.state = 'handled';
|
|
415
|
+
}
|
|
416
|
+
if (this.dialog === entry) {
|
|
417
|
+
this.dialog = undefined;
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
catch (e) {
|
|
421
|
+
if (entry.state === 'resolving') {
|
|
422
|
+
entry.state = 'unknown';
|
|
423
|
+
}
|
|
424
|
+
throw e;
|
|
425
|
+
}
|
|
426
|
+
return { ...this.status(), dialog: redact(entry) };
|
|
427
|
+
}
|
|
428
|
+
if (action === 'networkCapture') {
|
|
429
|
+
if (op === 'start') {
|
|
430
|
+
this.capture = new Set(command.include ?? []);
|
|
431
|
+
await this.send('Network.enable', {
|
|
432
|
+
maxTotalBufferSize: MAX_BYTES,
|
|
433
|
+
maxResourceBufferSize: MAX_BODY,
|
|
434
|
+
maxPostDataSize: MAX_BODY,
|
|
435
|
+
});
|
|
436
|
+
}
|
|
437
|
+
else {
|
|
438
|
+
this.capture.clear();
|
|
439
|
+
}
|
|
440
|
+
return this.status();
|
|
441
|
+
}
|
|
442
|
+
if (action === 'route') {
|
|
443
|
+
if (op === 'add') {
|
|
444
|
+
if (this.routes.size >= 100) {
|
|
445
|
+
throw new Error('Route limit reached (100); remove unused rules');
|
|
446
|
+
}
|
|
447
|
+
const rule = this.make('route', { urlPattern: command.urlPattern, stage: command.stage ?? 'Request' });
|
|
448
|
+
this.routes.set(rule.ref, {
|
|
449
|
+
urlPattern: String(command.urlPattern),
|
|
450
|
+
stage: String(command.stage ?? 'Request'),
|
|
451
|
+
});
|
|
452
|
+
try {
|
|
453
|
+
await this.configureFetch();
|
|
454
|
+
}
|
|
455
|
+
catch (e) {
|
|
456
|
+
this.routes.delete(rule.ref);
|
|
457
|
+
throw e;
|
|
458
|
+
}
|
|
459
|
+
return { ...this.status(), rule: redact(rule) };
|
|
460
|
+
}
|
|
461
|
+
if (op === 'remove') {
|
|
462
|
+
this.require(command.ref, 'route');
|
|
463
|
+
this.routes.delete(command.ref);
|
|
464
|
+
await Promise.all([...this.pauses.values()]
|
|
465
|
+
.filter((pause) => pause.ruleRef === command.ref)
|
|
466
|
+
.map((pause) => this.abortOne(pause, 'route removed')));
|
|
467
|
+
await this.configureFetch();
|
|
468
|
+
return this.status();
|
|
469
|
+
}
|
|
470
|
+
return this.resolvePause(command);
|
|
471
|
+
}
|
|
472
|
+
if (action === 'httpAuth') {
|
|
473
|
+
if (op === 'set') {
|
|
474
|
+
const scope = command.scope;
|
|
475
|
+
const origin = new URL(scope.origin).origin;
|
|
476
|
+
if (origin !== scope.origin) {
|
|
477
|
+
throw new Error('Authentication scope must be an exact origin without path or credentials');
|
|
478
|
+
}
|
|
479
|
+
this.credentials = {
|
|
480
|
+
...scope,
|
|
481
|
+
origin,
|
|
482
|
+
username: String(command.username),
|
|
483
|
+
password: String(command.password),
|
|
484
|
+
};
|
|
485
|
+
}
|
|
486
|
+
else {
|
|
487
|
+
this.credentials = undefined;
|
|
488
|
+
await this.abortPending('authentication cleared', 'auth');
|
|
489
|
+
}
|
|
490
|
+
await this.configureFetch();
|
|
491
|
+
return this.status();
|
|
492
|
+
}
|
|
493
|
+
if (action === 'download') {
|
|
494
|
+
if (op === 'watch') {
|
|
495
|
+
this.downloading = true;
|
|
496
|
+
this.downloadPattern = String(command.urlPattern ?? '*');
|
|
497
|
+
await this.send('Page.enable');
|
|
498
|
+
await this.configureFetch();
|
|
499
|
+
return this.status();
|
|
500
|
+
}
|
|
501
|
+
if (op === 'stop') {
|
|
502
|
+
this.downloading = false;
|
|
503
|
+
await this.abortPending('download observation stopped', 'download-capture');
|
|
504
|
+
await this.configureFetch();
|
|
505
|
+
return this.status();
|
|
506
|
+
}
|
|
507
|
+
const entry = this.require(command.ref, 'download');
|
|
508
|
+
if (op === 'wait') {
|
|
509
|
+
return this.waitDownload(entry, Number(command.timeout ?? 30_000), signal);
|
|
510
|
+
}
|
|
511
|
+
if (entry.state !== 'completed') {
|
|
512
|
+
throw new Error(`Download state is ${entry.state}; original file is not complete`);
|
|
513
|
+
}
|
|
514
|
+
const body = typeof entry.bodyRef === 'string' ? this.bodies.get(entry.bodyRef) : undefined;
|
|
515
|
+
if (!body) {
|
|
516
|
+
throw new Error(String(entry.artifactReason ?? 'Original download bytes expired or were evicted'));
|
|
517
|
+
}
|
|
518
|
+
return { ...this.status(), download: redact(entry), payload: body, bytes: bytes(body) };
|
|
519
|
+
}
|
|
520
|
+
throw new Error('Unsupported browser event action');
|
|
521
|
+
}
|
|
522
|
+
async abortPending(reason, kind) {
|
|
523
|
+
await Promise.all([...this.pauses.values()].filter((p) => !kind || p.kind === kind).map((p) => this.abortOne(p, reason)));
|
|
524
|
+
}
|
|
525
|
+
async suspend(reason) {
|
|
526
|
+
this.credentials = undefined;
|
|
527
|
+
this.rawAuthentication = false;
|
|
528
|
+
this.dialogWatching = false;
|
|
529
|
+
this.capture.clear();
|
|
530
|
+
this.downloading = false;
|
|
531
|
+
await this.abortPending(reason);
|
|
532
|
+
const unresolved = [...this.pauses.values()];
|
|
533
|
+
if (unresolved.length) {
|
|
534
|
+
return {
|
|
535
|
+
...this.status(),
|
|
536
|
+
suspended: false,
|
|
537
|
+
reason,
|
|
538
|
+
unresolved: unresolved.map((p) => ({ ref: p.ref, state: p.state, cleanupError: p.cleanupError })),
|
|
539
|
+
};
|
|
540
|
+
}
|
|
541
|
+
this.routes.clear();
|
|
542
|
+
await this.configureFetch();
|
|
543
|
+
return { ...this.status(), suspended: true, reason };
|
|
544
|
+
}
|
|
545
|
+
async dispose(reason) {
|
|
546
|
+
const result = await this.suspend(reason);
|
|
547
|
+
if (result.suspended === false) {
|
|
548
|
+
throw Object.assign(new Error('Browser event cleanup outcome unknown'), { context: result });
|
|
549
|
+
}
|
|
550
|
+
this.active = false;
|
|
551
|
+
this.entries.clear();
|
|
552
|
+
this.bodies.clear();
|
|
553
|
+
this.requests.clear();
|
|
554
|
+
this.extras.clear();
|
|
555
|
+
this.challenged.clear();
|
|
556
|
+
this.downloadBodies.clear();
|
|
557
|
+
this.cleanupFailures = [];
|
|
558
|
+
this.bodyBytes = 0;
|
|
559
|
+
for (const reject of this.dialogWaiters) {
|
|
560
|
+
reject(new Error(reason));
|
|
561
|
+
}
|
|
562
|
+
this.dialogWaiters.clear();
|
|
563
|
+
this.notifyDownloads();
|
|
564
|
+
return result;
|
|
565
|
+
}
|
|
566
|
+
async rawFetch(method, params = {}) {
|
|
567
|
+
if (method === 'Fetch.enable') {
|
|
568
|
+
const patterns = params.patterns;
|
|
569
|
+
for (const [key, rule] of this.routes) {
|
|
570
|
+
if (rule.raw) {
|
|
571
|
+
this.routes.delete(key);
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
if ((patterns?.length ?? 1) + this.routes.size > 100) {
|
|
575
|
+
throw new Error('Route limit reached (100)');
|
|
576
|
+
}
|
|
577
|
+
const rule = this.make('route', { raw: true });
|
|
578
|
+
for (const [index, p] of (patterns ?? [{}]).entries()) {
|
|
579
|
+
this.routes.set(`${rule.ref}/${index}`, {
|
|
580
|
+
urlPattern: p.urlPattern ?? '*',
|
|
581
|
+
stage: p.requestStage ?? 'Request',
|
|
582
|
+
raw: true,
|
|
583
|
+
});
|
|
584
|
+
}
|
|
585
|
+
this.rawAuthentication = params.handleAuthRequests === true;
|
|
586
|
+
this.fetchEnabled = true;
|
|
587
|
+
const combined = [...this.routes.values()].map((rule) => ({
|
|
588
|
+
urlPattern: rule.urlPattern,
|
|
589
|
+
requestStage: rule.stage,
|
|
590
|
+
}));
|
|
591
|
+
if (this.downloading) {
|
|
592
|
+
combined.push({ urlPattern: this.downloadPattern, requestStage: 'Response' });
|
|
593
|
+
}
|
|
594
|
+
if (this.credentials) {
|
|
595
|
+
combined.push({ urlPattern: '*', requestStage: 'Request' });
|
|
596
|
+
}
|
|
597
|
+
return this.send(method, {
|
|
598
|
+
...params,
|
|
599
|
+
patterns: combined,
|
|
600
|
+
handleAuthRequests: !!this.credentials || this.rawAuthentication,
|
|
601
|
+
});
|
|
602
|
+
}
|
|
603
|
+
if (method === 'Fetch.disable') {
|
|
604
|
+
await this.abortPending('raw Fetch.disable');
|
|
605
|
+
if (this.pauses.size) {
|
|
606
|
+
throw new Error('Fetch cleanup incomplete; debugger remains attached');
|
|
607
|
+
}
|
|
608
|
+
this.routes.clear();
|
|
609
|
+
this.credentials = undefined;
|
|
610
|
+
this.rawAuthentication = false;
|
|
611
|
+
this.downloading = false;
|
|
612
|
+
this.fetchEnabled = false;
|
|
613
|
+
return this.send(method, params);
|
|
614
|
+
}
|
|
615
|
+
const candidates = [...this.pauses.values()].filter((p) => p.requestId === params.requestId);
|
|
616
|
+
if (candidates.length > 1) {
|
|
617
|
+
throw new Error('Ambiguous native Fetch requestId across sessions; use its observed ref through route');
|
|
618
|
+
}
|
|
619
|
+
const entry = candidates[0];
|
|
620
|
+
if (!entry) {
|
|
621
|
+
throw new Error('Fetch request is not pending under this page/session owner');
|
|
622
|
+
}
|
|
623
|
+
if (method === 'Fetch.getResponseBody') {
|
|
624
|
+
return this.send(method, params, entry.sessionId);
|
|
625
|
+
}
|
|
626
|
+
if (![
|
|
627
|
+
'Fetch.continueRequest',
|
|
628
|
+
'Fetch.continueResponse',
|
|
629
|
+
'Fetch.fulfillRequest',
|
|
630
|
+
'Fetch.failRequest',
|
|
631
|
+
'Fetch.continueWithAuth',
|
|
632
|
+
].includes(method)) {
|
|
633
|
+
throw new Error('Unsupported Fetch command; stream consumption is not supported');
|
|
634
|
+
}
|
|
635
|
+
if (entry.state !== 'pending') {
|
|
636
|
+
throw new Error('Fetch operation already dispatched');
|
|
637
|
+
}
|
|
638
|
+
entry.state = 'resolving';
|
|
639
|
+
clearTimeout(entry.timer);
|
|
640
|
+
try {
|
|
641
|
+
const result = await this.send(method, params, entry.sessionId);
|
|
642
|
+
entry.state = 'resolved';
|
|
643
|
+
return result;
|
|
644
|
+
}
|
|
645
|
+
catch (e) {
|
|
646
|
+
this.nativeFailure(entry, e);
|
|
647
|
+
throw e;
|
|
648
|
+
}
|
|
649
|
+
finally {
|
|
650
|
+
if (entry.state === 'resolved') {
|
|
651
|
+
this.pauses.delete(entry.ref);
|
|
652
|
+
}
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
make(kind, fields = {}) {
|
|
656
|
+
this.sweep();
|
|
657
|
+
const ref = [
|
|
658
|
+
'be',
|
|
659
|
+
this.identity.backend,
|
|
660
|
+
encodeURIComponent(this.identity.targetId),
|
|
661
|
+
this.identity.generation,
|
|
662
|
+
kind,
|
|
663
|
+
++this.sequence,
|
|
664
|
+
crypto.randomUUID(),
|
|
665
|
+
].join(':');
|
|
666
|
+
const boundedFields = bounded(fields);
|
|
667
|
+
const entry = {
|
|
668
|
+
...boundedFields,
|
|
669
|
+
...(JSON.stringify(fields) !== JSON.stringify(boundedFields) ? { metadataTruncated: true } : {}),
|
|
670
|
+
ref,
|
|
671
|
+
kind,
|
|
672
|
+
timestamp: Date.now(),
|
|
673
|
+
targetId: this.identity.targetId,
|
|
674
|
+
documentRevision: this.documentRevision,
|
|
675
|
+
};
|
|
676
|
+
this.entries.set(ref, entry);
|
|
677
|
+
while (this.entries.size > MAX_ENTRIES ||
|
|
678
|
+
new TextEncoder().encode(JSON.stringify([...this.entries.values()], (key, value) => key === 'timer' || key === 'bodyRead' ? undefined : value)).length > MAX_METADATA) {
|
|
679
|
+
const oldest = [...this.entries.values()].find((e) => !this.pauses.has(e.ref) &&
|
|
680
|
+
e !== this.dialog &&
|
|
681
|
+
![...this.routes.keys()].some((key) => key === e.ref || key.startsWith(e.ref + '/')));
|
|
682
|
+
if (!oldest) {
|
|
683
|
+
this.dropped++;
|
|
684
|
+
break;
|
|
685
|
+
}
|
|
686
|
+
this.remove(oldest.ref);
|
|
687
|
+
}
|
|
688
|
+
return entry;
|
|
689
|
+
}
|
|
690
|
+
remove(ref) {
|
|
691
|
+
this.entries.delete(ref);
|
|
692
|
+
for (const key of [ref, `${ref}/request`]) {
|
|
693
|
+
const body = this.bodies.get(key);
|
|
694
|
+
if (body) {
|
|
695
|
+
this.bodyBytes -= bytes(body);
|
|
696
|
+
this.bodies.delete(key);
|
|
697
|
+
}
|
|
698
|
+
}
|
|
699
|
+
this.evicted++;
|
|
700
|
+
}
|
|
701
|
+
sweep() {
|
|
702
|
+
for (const e of this.entries.values()) {
|
|
703
|
+
if (Date.now() - e.timestamp > TTL &&
|
|
704
|
+
!this.pauses.has(e.ref) &&
|
|
705
|
+
e !== this.dialog &&
|
|
706
|
+
![...this.routes.keys()].some((key) => key === e.ref || key.startsWith(e.ref + '/'))) {
|
|
707
|
+
this.remove(e.ref);
|
|
708
|
+
}
|
|
709
|
+
}
|
|
710
|
+
for (const [key, hops] of this.requests) {
|
|
711
|
+
if (!hops.some((h) => this.entries.has(h.ref))) {
|
|
712
|
+
this.requests.delete(key);
|
|
713
|
+
this.extras.delete(key);
|
|
714
|
+
}
|
|
715
|
+
}
|
|
716
|
+
while (this.extras.size > MAX_ENTRIES) {
|
|
717
|
+
this.extras.delete(this.extras.keys().next().value);
|
|
718
|
+
this.dropped++;
|
|
719
|
+
}
|
|
720
|
+
}
|
|
721
|
+
require(ref, kind) {
|
|
722
|
+
this.sweep();
|
|
723
|
+
const entry = ref && this.entries.get(ref);
|
|
724
|
+
if (!this.active || !entry || (kind && entry.kind !== kind)) {
|
|
725
|
+
throw new Error('Browser event ref expired, evicted, or belongs to another owner/page/session');
|
|
726
|
+
}
|
|
727
|
+
return entry;
|
|
728
|
+
}
|
|
729
|
+
saveBody(ref, payload) {
|
|
730
|
+
const length = bytes(payload);
|
|
731
|
+
if (length >= MAX_BODY) {
|
|
732
|
+
throw new Error('Original body exceeds the 16 MiB event body budget');
|
|
733
|
+
}
|
|
734
|
+
while (this.bodyBytes + length > MAX_BYTES && this.bodies.size) {
|
|
735
|
+
const oldest = this.bodies.keys().next().value;
|
|
736
|
+
this.bodyBytes -= bytes(this.bodies.get(oldest));
|
|
737
|
+
this.bodies.delete(oldest);
|
|
738
|
+
this.evicted++;
|
|
739
|
+
}
|
|
740
|
+
const previous = this.bodies.get(ref);
|
|
741
|
+
if (previous) {
|
|
742
|
+
this.bodyBytes -= bytes(previous);
|
|
743
|
+
}
|
|
744
|
+
this.bodies.set(ref, payload);
|
|
745
|
+
this.bodyBytes += length;
|
|
746
|
+
}
|
|
747
|
+
key(requestId, sessionId) {
|
|
748
|
+
return `${sessionId ?? ''}\0${requestId}`;
|
|
749
|
+
}
|
|
750
|
+
latest(requestId, sessionId) {
|
|
751
|
+
if (requestId === undefined) {
|
|
752
|
+
return undefined;
|
|
753
|
+
}
|
|
754
|
+
return this.requests.get(this.key(requestId, sessionId))?.at(-1);
|
|
755
|
+
}
|
|
756
|
+
nativeFailure(entry, error) {
|
|
757
|
+
const context = error
|
|
758
|
+
?.context;
|
|
759
|
+
const message = this.failure(error);
|
|
760
|
+
let code = context?.nativeCode;
|
|
761
|
+
let nativeMessage;
|
|
762
|
+
if (code !== undefined && context?.method?.startsWith('Fetch.') && message.startsWith(`${context.method}: `)) {
|
|
763
|
+
nativeMessage = message.slice(context.method.length + 2);
|
|
764
|
+
}
|
|
765
|
+
if (code === undefined) {
|
|
766
|
+
try {
|
|
767
|
+
const native = JSON.parse(message);
|
|
768
|
+
code = native?.code;
|
|
769
|
+
nativeMessage = native?.message;
|
|
770
|
+
}
|
|
771
|
+
catch {
|
|
772
|
+
/* Native errors can also use plain text. */
|
|
773
|
+
}
|
|
774
|
+
}
|
|
775
|
+
const fromPage = getErrorSource(error) === 'page';
|
|
776
|
+
clearTimeout(entry.timer);
|
|
777
|
+
entry.error = message;
|
|
778
|
+
if (!fromPage && code === -32602 && nativeMessage === 'Invalid InterceptionId.') {
|
|
779
|
+
entry.state = 'expired';
|
|
780
|
+
entry.reason = 'Native interception no longer exists';
|
|
781
|
+
this.pauses.delete(entry.ref);
|
|
782
|
+
return;
|
|
783
|
+
}
|
|
784
|
+
const refused = !fromPage && (context?.actionExecuted === false || [-32601, -32602].includes(code ?? 0));
|
|
785
|
+
entry.state = refused ? 'pending' : 'unknown';
|
|
786
|
+
const remaining = entry.timestamp + PAUSE_TTL - Date.now();
|
|
787
|
+
if (refused && remaining > 0) {
|
|
788
|
+
entry.timer = setTimeout(() => {
|
|
789
|
+
void this.abortOne(entry, 'pause timeout after native refusal');
|
|
790
|
+
}, remaining);
|
|
791
|
+
}
|
|
792
|
+
}
|
|
793
|
+
failure(error) {
|
|
794
|
+
return error instanceof Error ? error.message : String(error);
|
|
795
|
+
}
|
|
796
|
+
recordCleanupFailure(error, phase, requestId, sessionId, ref) {
|
|
797
|
+
const pause = ref
|
|
798
|
+
? undefined
|
|
799
|
+
: [...this.pauses.values()].find((entry) => entry.requestId === requestId && entry.sessionId === sessionId);
|
|
800
|
+
this.cleanupFailures.push({
|
|
801
|
+
timestamp: Date.now(),
|
|
802
|
+
phase,
|
|
803
|
+
error: this.failure(error),
|
|
804
|
+
targetId: this.identity.targetId,
|
|
805
|
+
owner: this.identity.owner,
|
|
806
|
+
sessionGeneration: this.identity.generation,
|
|
807
|
+
nativeSessionId: sessionId ?? this.identity.nativeSessionId,
|
|
808
|
+
requestId,
|
|
809
|
+
ref: ref ?? pause?.ref,
|
|
810
|
+
});
|
|
811
|
+
this.cleanupFailures = this.cleanupFailures.slice(-20);
|
|
812
|
+
}
|
|
813
|
+
bindExtras(key) {
|
|
814
|
+
const hops = this.requests.get(key);
|
|
815
|
+
const extras = this.extras.get(key);
|
|
816
|
+
if (!hops || !extras) {
|
|
817
|
+
return;
|
|
818
|
+
}
|
|
819
|
+
for (const hop of hops) {
|
|
820
|
+
if (hop.extraExpected === undefined) {
|
|
821
|
+
break;
|
|
822
|
+
}
|
|
823
|
+
if (hop.extraExpected && !hop.requestExtraInfo && extras.request.length) {
|
|
824
|
+
hop.requestExtraInfo = extras.request.shift();
|
|
825
|
+
}
|
|
826
|
+
if (hop.extraExpected && !hop.responseExtraInfo) {
|
|
827
|
+
if (!extras.response.length) {
|
|
828
|
+
break;
|
|
829
|
+
}
|
|
830
|
+
hop.responseExtraInfo = extras.response.shift();
|
|
831
|
+
}
|
|
832
|
+
}
|
|
833
|
+
}
|
|
834
|
+
dialogError(actionExecuted = 'unknown') {
|
|
835
|
+
const message = 'Native operation is blocked by a JavaScript dialog; handle the observed ref before checking its result';
|
|
836
|
+
const context = {
|
|
837
|
+
ref: this.dialog?.ref,
|
|
838
|
+
targetId: this.identity.targetId,
|
|
839
|
+
actionExecuted,
|
|
840
|
+
actionStatus: actionExecuted === false ? 'not_started' : 'unknown',
|
|
841
|
+
retryable: false,
|
|
842
|
+
};
|
|
843
|
+
return Object.assign(new Error(message), {
|
|
844
|
+
code: 'DIALOG_OPEN',
|
|
845
|
+
context,
|
|
846
|
+
toJSON: () => ({ error: { code: 'DIALOG_OPEN', message, context } }),
|
|
847
|
+
});
|
|
848
|
+
}
|
|
849
|
+
status() {
|
|
850
|
+
return {
|
|
851
|
+
targetId: this.identity.targetId,
|
|
852
|
+
sessionGeneration: this.identity.generation,
|
|
853
|
+
capture: [...this.capture],
|
|
854
|
+
fetchEnabled: this.fetchEnabled,
|
|
855
|
+
routes: this.routes.size,
|
|
856
|
+
authConfigured: !!this.credentials,
|
|
857
|
+
dialogWatching: this.dialogWatching,
|
|
858
|
+
downloadWatching: this.downloading,
|
|
859
|
+
limits: {
|
|
860
|
+
entries: MAX_ENTRIES,
|
|
861
|
+
pending: MAX_PENDING,
|
|
862
|
+
metadataBytes: MAX_METADATA,
|
|
863
|
+
bodyBytes: MAX_BODY,
|
|
864
|
+
cachedBodyBytes: MAX_BYTES,
|
|
865
|
+
messageBytes: MAX_MESSAGE,
|
|
866
|
+
ttlMs: TTL,
|
|
867
|
+
pauseTtlMs: PAUSE_TTL,
|
|
868
|
+
},
|
|
869
|
+
dropped: this.dropped,
|
|
870
|
+
evicted: this.evicted,
|
|
871
|
+
cleanupFailures: this.cleanupFailures.map((failure) => failure.error),
|
|
872
|
+
cleanupFailureDetails: this.cleanupFailures.map((failure) => ({ ...failure })),
|
|
873
|
+
downloadCaptureFailures: [...this.entries.values()]
|
|
874
|
+
.filter((e) => e.kind === 'download-capture' && typeof e.error === 'string')
|
|
875
|
+
.map((e) => ({
|
|
876
|
+
ref: e.ref,
|
|
877
|
+
state: e.state,
|
|
878
|
+
nativeState: 'not-observed',
|
|
879
|
+
error: e.error ?? e.reason,
|
|
880
|
+
cleanupError: e.cleanupError,
|
|
881
|
+
})),
|
|
882
|
+
};
|
|
883
|
+
}
|
|
884
|
+
async configureFetch() {
|
|
885
|
+
this.fetchConfig = this.fetchConfig
|
|
886
|
+
.catch(() => { })
|
|
887
|
+
.then(async () => {
|
|
888
|
+
// A body read owns its pause until getResponseBody completes, including stop/cleanup.
|
|
889
|
+
await Promise.all([...this.pauses.values()].map((p) => p.bodyRead));
|
|
890
|
+
if ([...this.pauses.values()].some((p) => p.state === 'unknown')) {
|
|
891
|
+
throw new Error('Fetch cleanup outcome is unknown; configuration and debugger attachment are preserved');
|
|
892
|
+
}
|
|
893
|
+
const patterns = [...this.routes.values()].map((r) => ({
|
|
894
|
+
urlPattern: r.urlPattern,
|
|
895
|
+
requestStage: r.stage,
|
|
896
|
+
}));
|
|
897
|
+
if (this.downloading) {
|
|
898
|
+
patterns.push({ urlPattern: this.downloadPattern, requestStage: 'Response' });
|
|
899
|
+
}
|
|
900
|
+
if (this.credentials || (this.rawAuthentication && patterns.length === 0)) {
|
|
901
|
+
patterns.push({ urlPattern: '*', requestStage: 'Request' });
|
|
902
|
+
}
|
|
903
|
+
if (patterns.length || this.credentials || this.rawAuthentication) {
|
|
904
|
+
await this.send('Fetch.enable', {
|
|
905
|
+
patterns,
|
|
906
|
+
handleAuthRequests: !!this.credentials || this.rawAuthentication,
|
|
907
|
+
});
|
|
908
|
+
this.fetchEnabled = true;
|
|
909
|
+
}
|
|
910
|
+
else if (this.fetchEnabled) {
|
|
911
|
+
if (this.pauses.size) {
|
|
912
|
+
throw new Error('Fetch cleanup is incomplete; pending requests and debugger attachment are preserved');
|
|
913
|
+
}
|
|
914
|
+
await this.send('Fetch.disable');
|
|
915
|
+
this.fetchEnabled = false;
|
|
916
|
+
}
|
|
917
|
+
});
|
|
918
|
+
await this.fetchConfig;
|
|
919
|
+
}
|
|
920
|
+
async onPaused(p, sessionId) {
|
|
921
|
+
const stage = p.responseStatusCode !== undefined || p.responseErrorReason !== undefined ? 'Response' : 'Request';
|
|
922
|
+
const rule = [...this.routes.entries()].find(([, r]) => r.stage === stage && matches(p.request.url, r.urlPattern));
|
|
923
|
+
const native = { requestId: p.requestId };
|
|
924
|
+
if (!rule && !(this.downloading && stage === 'Response' && matches(p.request.url, this.downloadPattern))) {
|
|
925
|
+
await this.send(stage === 'Response' ? 'Fetch.continueResponse' : 'Fetch.continueRequest', native, sessionId);
|
|
926
|
+
return;
|
|
927
|
+
}
|
|
928
|
+
if (this.pauses.size >= MAX_PENDING) {
|
|
929
|
+
this.dropped++;
|
|
930
|
+
await this.send('Fetch.failRequest', { ...native, errorReason: 'Aborted' }, sessionId);
|
|
931
|
+
return;
|
|
932
|
+
}
|
|
933
|
+
const headers = p.responseHeaders;
|
|
934
|
+
const attachment = headers?.some((h) => h.name.toLowerCase() === 'content-disposition' && /^attachment(?:;|$)/i.test(h.value));
|
|
935
|
+
if (!rule && !attachment) {
|
|
936
|
+
await this.send('Fetch.continueResponse', native, sessionId);
|
|
937
|
+
return;
|
|
938
|
+
}
|
|
939
|
+
const entry = this.make(rule ? 'paused' : 'download-capture', {
|
|
940
|
+
...p,
|
|
941
|
+
sessionId,
|
|
942
|
+
state: 'pending',
|
|
943
|
+
stage,
|
|
944
|
+
ruleRef: rule?.[0],
|
|
945
|
+
networkRef: this.latest(p.networkId, sessionId)?.ref,
|
|
946
|
+
});
|
|
947
|
+
this.pauses.set(entry.ref, entry);
|
|
948
|
+
entry.timer = setTimeout(() => {
|
|
949
|
+
void this.abortOne(entry, 'pause timeout');
|
|
950
|
+
}, PAUSE_TTL);
|
|
951
|
+
if (!rule) {
|
|
952
|
+
entry.bodyRead = (async () => {
|
|
953
|
+
try {
|
|
954
|
+
const contentLength = Number(headers?.find((h) => h.name.toLowerCase() === 'content-length')?.value ?? 0);
|
|
955
|
+
if (contentLength >= MAX_BODY) {
|
|
956
|
+
// 配额拒绝与原生读取失败共用下方中止路径
|
|
957
|
+
// noinspection ExceptionCaughtLocallyJS
|
|
958
|
+
throw new Error('Download exceeds the original body budget');
|
|
959
|
+
}
|
|
960
|
+
const body = (await this.send('Fetch.getResponseBody', native, sessionId));
|
|
961
|
+
this.saveBody(entry.ref, { encoding: body.base64Encoded ? 'base64' : 'utf8', data: body.body });
|
|
962
|
+
if (p.frameId) {
|
|
963
|
+
const candidates = this.downloadBodies.get(p.frameId) ?? [];
|
|
964
|
+
candidates.push({ ref: entry.ref, frameId: p.frameId, url: p.request.url });
|
|
965
|
+
this.downloadBodies.set(p.frameId, candidates.slice(-MAX_ENTRIES));
|
|
966
|
+
}
|
|
967
|
+
if (entry.abortReason) {
|
|
968
|
+
await this.send('Fetch.failRequest', { ...native, errorReason: 'Aborted' }, sessionId);
|
|
969
|
+
entry.state = 'aborted';
|
|
970
|
+
entry.reason = entry.abortReason;
|
|
971
|
+
}
|
|
972
|
+
else {
|
|
973
|
+
await this.send('Fetch.continueResponse', native, sessionId);
|
|
974
|
+
entry.state = 'resolved';
|
|
975
|
+
}
|
|
976
|
+
}
|
|
977
|
+
catch (e) {
|
|
978
|
+
this.nativeFailure(entry, e);
|
|
979
|
+
if (entry.state === 'expired') {
|
|
980
|
+
return;
|
|
981
|
+
}
|
|
982
|
+
await this.send('Fetch.failRequest', { ...native, errorReason: 'Aborted' }, sessionId).then(() => {
|
|
983
|
+
entry.state = 'aborted';
|
|
984
|
+
}, (cleanup) => {
|
|
985
|
+
this.nativeFailure(entry, cleanup);
|
|
986
|
+
entry.error = this.failure(e);
|
|
987
|
+
entry.cleanupError = this.failure(cleanup);
|
|
988
|
+
if (entry.state !== 'expired') {
|
|
989
|
+
this.recordCleanupFailure(cleanup, 'downloadCapture:abort', entry.requestId, entry.sessionId, entry.ref);
|
|
990
|
+
}
|
|
991
|
+
});
|
|
992
|
+
}
|
|
993
|
+
finally {
|
|
994
|
+
if (entry.state !== 'pending') {
|
|
995
|
+
clearTimeout(entry.timer);
|
|
996
|
+
}
|
|
997
|
+
if (['resolved', 'aborted', 'expired'].includes(entry.state)) {
|
|
998
|
+
this.pauses.delete(entry.ref);
|
|
999
|
+
}
|
|
1000
|
+
}
|
|
1001
|
+
})();
|
|
1002
|
+
await entry.bodyRead;
|
|
1003
|
+
}
|
|
1004
|
+
}
|
|
1005
|
+
async onAuth(p, sessionId) {
|
|
1006
|
+
const challenge = p.authChallenge;
|
|
1007
|
+
if (this.pauses.size >= MAX_PENDING) {
|
|
1008
|
+
this.dropped++;
|
|
1009
|
+
await this.send('Fetch.continueWithAuth', { requestId: p.requestId, authChallengeResponse: { response: 'CancelAuth' } }, sessionId);
|
|
1010
|
+
return;
|
|
1011
|
+
}
|
|
1012
|
+
const key = `${this.key(p.requestId, sessionId)}\0${challenge.source}\0${challenge.origin}\0${challenge.realm}`;
|
|
1013
|
+
const c = this.credentials;
|
|
1014
|
+
if (this.rawAuthentication && !c) {
|
|
1015
|
+
const entry = this.make('auth', {
|
|
1016
|
+
requestId: p.requestId,
|
|
1017
|
+
challenge,
|
|
1018
|
+
sessionId,
|
|
1019
|
+
state: 'pending',
|
|
1020
|
+
response: 'awaiting-explicit-native-control',
|
|
1021
|
+
url: p.request?.url,
|
|
1022
|
+
});
|
|
1023
|
+
this.pauses.set(entry.ref, entry);
|
|
1024
|
+
entry.timer = setTimeout(() => {
|
|
1025
|
+
void this.abortOne(entry, 'authentication timeout');
|
|
1026
|
+
}, PAUSE_TTL);
|
|
1027
|
+
return;
|
|
1028
|
+
}
|
|
1029
|
+
const permitted = c &&
|
|
1030
|
+
c.source === challenge.source &&
|
|
1031
|
+
c.origin === challenge.origin &&
|
|
1032
|
+
(c.realm === undefined || c.realm === challenge.realm) &&
|
|
1033
|
+
!this.challenged.has(key);
|
|
1034
|
+
this.challenged.add(key);
|
|
1035
|
+
if (this.challenged.size > MAX_ENTRIES) {
|
|
1036
|
+
this.challenged.delete(this.challenged.values().next().value);
|
|
1037
|
+
}
|
|
1038
|
+
const entry = this.make('auth', {
|
|
1039
|
+
requestId: p.requestId,
|
|
1040
|
+
challenge,
|
|
1041
|
+
sessionId,
|
|
1042
|
+
state: 'resolving',
|
|
1043
|
+
response: permitted ? 'ProvideCredentials' : 'CancelAuth',
|
|
1044
|
+
url: p.request?.url,
|
|
1045
|
+
});
|
|
1046
|
+
this.pauses.set(entry.ref, entry);
|
|
1047
|
+
try {
|
|
1048
|
+
await this.send('Fetch.continueWithAuth', {
|
|
1049
|
+
requestId: p.requestId,
|
|
1050
|
+
authChallengeResponse: permitted
|
|
1051
|
+
? { response: 'ProvideCredentials', username: c.username, password: c.password }
|
|
1052
|
+
: { response: 'CancelAuth' },
|
|
1053
|
+
}, sessionId);
|
|
1054
|
+
entry.state = 'resolved';
|
|
1055
|
+
}
|
|
1056
|
+
catch (e) {
|
|
1057
|
+
this.nativeFailure(entry, e);
|
|
1058
|
+
}
|
|
1059
|
+
finally {
|
|
1060
|
+
if (entry.state === 'resolved') {
|
|
1061
|
+
this.pauses.delete(entry.ref);
|
|
1062
|
+
}
|
|
1063
|
+
}
|
|
1064
|
+
}
|
|
1065
|
+
async resolvePause(command) {
|
|
1066
|
+
const entry = this.require(command.ref, 'paused');
|
|
1067
|
+
if (entry.state !== 'pending') {
|
|
1068
|
+
return { ...this.status(), paused: redact(entry), alreadyProcessed: true };
|
|
1069
|
+
}
|
|
1070
|
+
let method = 'Fetch.continueRequest';
|
|
1071
|
+
const params = { requestId: entry.requestId };
|
|
1072
|
+
if (command.op === 'fail') {
|
|
1073
|
+
method = 'Fetch.failRequest';
|
|
1074
|
+
params.errorReason = command.errorReason ?? 'Aborted';
|
|
1075
|
+
}
|
|
1076
|
+
else if (command.op === 'fulfill') {
|
|
1077
|
+
method = 'Fetch.fulfillRequest';
|
|
1078
|
+
const response = command.response;
|
|
1079
|
+
Object.assign(params, {
|
|
1080
|
+
responseCode: response.status,
|
|
1081
|
+
responsePhrase: response.statusText,
|
|
1082
|
+
responseHeaders: response.headers,
|
|
1083
|
+
body: response.body ? base64(response.body) : '',
|
|
1084
|
+
});
|
|
1085
|
+
}
|
|
1086
|
+
else {
|
|
1087
|
+
const request = command.request;
|
|
1088
|
+
if (entry.stage === 'Response') {
|
|
1089
|
+
if (request) {
|
|
1090
|
+
throw new Error('Response-stage continue does not accept request overrides');
|
|
1091
|
+
}
|
|
1092
|
+
method = 'Fetch.continueResponse';
|
|
1093
|
+
}
|
|
1094
|
+
else if (request) {
|
|
1095
|
+
Object.assign(params, {
|
|
1096
|
+
url: request.url,
|
|
1097
|
+
method: request.method,
|
|
1098
|
+
headers: request.headers,
|
|
1099
|
+
postData: request.body ? base64(request.body) : undefined,
|
|
1100
|
+
});
|
|
1101
|
+
}
|
|
1102
|
+
}
|
|
1103
|
+
entry.state = 'resolving';
|
|
1104
|
+
clearTimeout(entry.timer);
|
|
1105
|
+
try {
|
|
1106
|
+
await this.send(method, params, entry.sessionId);
|
|
1107
|
+
entry.state = 'resolved';
|
|
1108
|
+
}
|
|
1109
|
+
catch (e) {
|
|
1110
|
+
this.nativeFailure(entry, e);
|
|
1111
|
+
throw e;
|
|
1112
|
+
}
|
|
1113
|
+
finally {
|
|
1114
|
+
if (entry.state === 'resolved') {
|
|
1115
|
+
this.pauses.delete(entry.ref);
|
|
1116
|
+
}
|
|
1117
|
+
}
|
|
1118
|
+
return { ...this.status(), paused: redact(entry) };
|
|
1119
|
+
}
|
|
1120
|
+
async abortOne(entry, reason) {
|
|
1121
|
+
entry.abortReason = reason;
|
|
1122
|
+
await entry.bodyRead;
|
|
1123
|
+
if (entry.state !== 'pending') {
|
|
1124
|
+
return;
|
|
1125
|
+
}
|
|
1126
|
+
clearTimeout(entry.timer);
|
|
1127
|
+
entry.state = 'resolving';
|
|
1128
|
+
try {
|
|
1129
|
+
await this.send(entry.kind === 'auth' ? 'Fetch.continueWithAuth' : 'Fetch.failRequest', {
|
|
1130
|
+
requestId: entry.requestId,
|
|
1131
|
+
...(entry.kind === 'auth'
|
|
1132
|
+
? { authChallengeResponse: { response: 'CancelAuth' } }
|
|
1133
|
+
: { errorReason: 'Aborted' }),
|
|
1134
|
+
}, entry.sessionId);
|
|
1135
|
+
entry.state = 'aborted';
|
|
1136
|
+
entry.reason = reason;
|
|
1137
|
+
}
|
|
1138
|
+
catch (e) {
|
|
1139
|
+
this.nativeFailure(entry, e);
|
|
1140
|
+
if (entry.state !== 'expired') {
|
|
1141
|
+
entry.cleanupError = this.failure(e);
|
|
1142
|
+
this.recordCleanupFailure(e, `abortPending:${reason}`, entry.requestId, entry.sessionId, entry.ref);
|
|
1143
|
+
}
|
|
1144
|
+
}
|
|
1145
|
+
finally {
|
|
1146
|
+
if (entry.state === 'aborted') {
|
|
1147
|
+
this.pauses.delete(entry.ref);
|
|
1148
|
+
}
|
|
1149
|
+
}
|
|
1150
|
+
}
|
|
1151
|
+
async readBody(request, view) {
|
|
1152
|
+
const bodyKey = view === 'requestBody' ? `${request.ref}/request` : request.ref;
|
|
1153
|
+
const cached = this.bodies.get(bodyKey);
|
|
1154
|
+
if (cached) {
|
|
1155
|
+
return cached;
|
|
1156
|
+
}
|
|
1157
|
+
if (this.latest(request.requestId, request.sessionId) !== request) {
|
|
1158
|
+
throw new Error('Redirect-hop body is unavailable from the native protocol');
|
|
1159
|
+
}
|
|
1160
|
+
if (view === 'responseBody' && request.state !== 'finished') {
|
|
1161
|
+
throw new Error(`Original response body unavailable while request is ${request.state}`);
|
|
1162
|
+
}
|
|
1163
|
+
const result = (await this.send(view === 'requestBody' ? 'Network.getRequestPostData' : 'Network.getResponseBody', { requestId: request.requestId }, request.sessionId));
|
|
1164
|
+
const data = view === 'requestBody' ? result.postData : result.body;
|
|
1165
|
+
if (typeof data !== 'string') {
|
|
1166
|
+
throw new Error('Native protocol did not provide the original body (multipart file parts are not provided)');
|
|
1167
|
+
}
|
|
1168
|
+
const payload = { encoding: result.base64Encoded ? 'base64' : 'utf8', data };
|
|
1169
|
+
this.saveBody(bodyKey, payload);
|
|
1170
|
+
return payload;
|
|
1171
|
+
}
|
|
1172
|
+
async read(options) {
|
|
1173
|
+
this.sweep();
|
|
1174
|
+
const view = options.view ?? 'summary';
|
|
1175
|
+
const selected = options.ref ? this.require(options.ref) : undefined;
|
|
1176
|
+
if (view === 'requestBody' || view === 'responseBody') {
|
|
1177
|
+
const entry = this.require(options.ref, 'request');
|
|
1178
|
+
const payload = await this.readBody(entry, view);
|
|
1179
|
+
if (options.clear) {
|
|
1180
|
+
this.remove(entry.ref);
|
|
1181
|
+
}
|
|
1182
|
+
return {
|
|
1183
|
+
...this.status(),
|
|
1184
|
+
ref: entry.ref,
|
|
1185
|
+
payload,
|
|
1186
|
+
bytes: bytes(payload),
|
|
1187
|
+
bodySource: 'native-protocol-entity',
|
|
1188
|
+
limitations: view === 'requestBody' ? ['Multipart file parts are omitted by the native protocol'] : [],
|
|
1189
|
+
};
|
|
1190
|
+
}
|
|
1191
|
+
const kind = options.type === 'network'
|
|
1192
|
+
? view === 'stream'
|
|
1193
|
+
? 'stream'
|
|
1194
|
+
: view === 'paused'
|
|
1195
|
+
? 'paused'
|
|
1196
|
+
: view === 'auth'
|
|
1197
|
+
? 'auth'
|
|
1198
|
+
: 'request'
|
|
1199
|
+
: options.type;
|
|
1200
|
+
if (selected && selected.kind !== kind) {
|
|
1201
|
+
throw new Error('Browser event ref kind does not match the requested view');
|
|
1202
|
+
}
|
|
1203
|
+
const entries = [...this.entries.values()].filter((e) => e.kind === kind &&
|
|
1204
|
+
(!selected || e.ref === selected.ref) &&
|
|
1205
|
+
(!options.urlPattern ||
|
|
1206
|
+
matches(String(e.url ?? e.request?.url ?? ''), options.urlPattern)));
|
|
1207
|
+
const logs = entries.slice(-(options.limit ?? 100)).map((e) => {
|
|
1208
|
+
if (kind === 'request' && view === 'summary') {
|
|
1209
|
+
return redact({
|
|
1210
|
+
ref: e.ref,
|
|
1211
|
+
requestId: e.requestId,
|
|
1212
|
+
hop: e.hop,
|
|
1213
|
+
url: e.url,
|
|
1214
|
+
method: e.request.method,
|
|
1215
|
+
status: e.response?.status,
|
|
1216
|
+
type: e.type,
|
|
1217
|
+
state: e.state,
|
|
1218
|
+
timestamp: e.timestamp,
|
|
1219
|
+
});
|
|
1220
|
+
}
|
|
1221
|
+
return redact({
|
|
1222
|
+
...e,
|
|
1223
|
+
...(kind === 'request'
|
|
1224
|
+
? {
|
|
1225
|
+
headersSource: {
|
|
1226
|
+
base: 'requestWillBeSent/responseReceived',
|
|
1227
|
+
actual: 'ExtraInfo',
|
|
1228
|
+
complete: e.extraExpected === false || (!!e.responseExtraInfo && !!e.requestExtraInfo),
|
|
1229
|
+
},
|
|
1230
|
+
}
|
|
1231
|
+
: {}),
|
|
1232
|
+
...(kind === 'download'
|
|
1233
|
+
? {
|
|
1234
|
+
artifact: typeof e.bodyRef === 'string' && this.bodies.has(e.bodyRef) ? 'available' : 'unavailable',
|
|
1235
|
+
}
|
|
1236
|
+
: {}),
|
|
1237
|
+
});
|
|
1238
|
+
});
|
|
1239
|
+
if (options.clear) {
|
|
1240
|
+
for (const e of entries) {
|
|
1241
|
+
if (!this.pauses.has(e.ref) && e !== this.dialog) {
|
|
1242
|
+
this.remove(e.ref);
|
|
1243
|
+
}
|
|
1244
|
+
}
|
|
1245
|
+
}
|
|
1246
|
+
return { ...this.status(), logs, count: logs.length, totalBuffered: entries.length, view };
|
|
1247
|
+
}
|
|
1248
|
+
notifyDownloads() {
|
|
1249
|
+
for (const notify of this.downloadWaiters) {
|
|
1250
|
+
notify();
|
|
1251
|
+
}
|
|
1252
|
+
}
|
|
1253
|
+
async waitDownload(entry, timeout, signal) {
|
|
1254
|
+
await new Promise((resolve, reject) => {
|
|
1255
|
+
const check = () => {
|
|
1256
|
+
if (!this.active) {
|
|
1257
|
+
cleanup();
|
|
1258
|
+
reject(new Error('Download session closed'));
|
|
1259
|
+
return;
|
|
1260
|
+
}
|
|
1261
|
+
if (entry.state !== 'inProgress') {
|
|
1262
|
+
cleanup();
|
|
1263
|
+
resolve();
|
|
1264
|
+
}
|
|
1265
|
+
};
|
|
1266
|
+
const abort = () => {
|
|
1267
|
+
cleanup();
|
|
1268
|
+
reject(signal?.reason ?? new Error('Download wait cancelled'));
|
|
1269
|
+
};
|
|
1270
|
+
const timer = setTimeout(() => {
|
|
1271
|
+
cleanup();
|
|
1272
|
+
reject(new Error('Download is still in progress at timeout'));
|
|
1273
|
+
}, timeout);
|
|
1274
|
+
const cleanup = () => {
|
|
1275
|
+
clearTimeout(timer);
|
|
1276
|
+
this.downloadWaiters.delete(check);
|
|
1277
|
+
signal?.removeEventListener('abort', abort);
|
|
1278
|
+
};
|
|
1279
|
+
this.downloadWaiters.add(check);
|
|
1280
|
+
signal?.addEventListener('abort', abort, { once: true });
|
|
1281
|
+
check();
|
|
1282
|
+
if (signal?.aborted) {
|
|
1283
|
+
abort();
|
|
1284
|
+
}
|
|
1285
|
+
});
|
|
1286
|
+
return { ...this.status(), download: redact(entry) };
|
|
1287
|
+
}
|
|
1288
|
+
}
|
|
1289
|
+
export const BROWSER_EVENT_METHODS = [
|
|
1290
|
+
'Page.javascriptDialogOpening',
|
|
1291
|
+
'Page.javascriptDialogClosed',
|
|
1292
|
+
'Page.frameNavigated',
|
|
1293
|
+
'Page.downloadWillBegin',
|
|
1294
|
+
'Page.downloadProgress',
|
|
1295
|
+
'Network.requestWillBeSent',
|
|
1296
|
+
'Network.requestWillBeSentExtraInfo',
|
|
1297
|
+
'Network.responseReceived',
|
|
1298
|
+
'Network.responseReceivedExtraInfo',
|
|
1299
|
+
'Network.loadingFinished',
|
|
1300
|
+
'Network.loadingFailed',
|
|
1301
|
+
'Network.webSocketCreated',
|
|
1302
|
+
'Network.webSocketWillSendHandshakeRequest',
|
|
1303
|
+
'Network.webSocketHandshakeResponseReceived',
|
|
1304
|
+
'Network.webSocketFrameSent',
|
|
1305
|
+
'Network.webSocketFrameReceived',
|
|
1306
|
+
'Network.webSocketFrameError',
|
|
1307
|
+
'Network.webSocketClosed',
|
|
1308
|
+
'Network.eventSourceMessageReceived',
|
|
1309
|
+
'Fetch.requestPaused',
|
|
1310
|
+
'Fetch.authRequired',
|
|
1311
|
+
];
|
|
1312
|
+
//# sourceMappingURL=browser-events.js.map
|