@pyrokine/mcp-chrome 3.0.1 → 3.1.1

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