browserpaw 0.0.0-stage → 5.0.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.
Files changed (45) hide show
  1. package/LICENSE +681 -0
  2. package/README.md +4 -2
  3. package/dist/v5/cli-files.cjs +147 -0
  4. package/dist/v5/cli.cjs +4028 -0
  5. package/dist/v5/extension/assets/popup-Djl4pI1R.css +359 -0
  6. package/dist/v5/extension/background.js +37712 -0
  7. package/dist/v5/extension/browserpaw-build.json +184 -0
  8. package/dist/v5/extension/chunks/popup-DjxqduQH.js +6542 -0
  9. package/dist/v5/extension/content-scripts/agent-cursor.js +1459 -0
  10. package/dist/v5/extension/icon/128.png +0 -0
  11. package/dist/v5/extension/icon/16.png +0 -0
  12. package/dist/v5/extension/icon/32.png +0 -0
  13. package/dist/v5/extension/icon/48.png +0 -0
  14. package/dist/v5/extension/icon/96.png +0 -0
  15. package/dist/v5/extension/images/cursor-chat.png +0 -0
  16. package/dist/v5/extension/inject-scripts/accessibility-tree-helper.js +1883 -0
  17. package/dist/v5/extension/inject-scripts/keyboard-helper.js +402 -0
  18. package/dist/v5/extension/inject-scripts/network-helper.js +213 -0
  19. package/dist/v5/extension/inject-scripts/screenshot-helper.js +408 -0
  20. package/dist/v5/extension/inpage-engine.js +9300 -0
  21. package/dist/v5/extension/manifest.json +1 -0
  22. package/dist/v5/extension/popup.html +14 -0
  23. package/dist/v5/host.cjs +19441 -0
  24. package/dist/v5/recipes/developer.mozilla.org.md +15 -0
  25. package/dist/v5/recipes/github-releases.json +177 -0
  26. package/dist/v5/recipes/mdn-search.json +174 -0
  27. package/dist/v5/recipes/npm-compare.json +456 -0
  28. package/dist/v5/recipes/x-search-thread.json +321 -0
  29. package/dist/v5/recipes/x-visible-thread.json +303 -0
  30. package/dist/v5/run_host.bat +7 -0
  31. package/dist/v5/run_host.sh +6 -0
  32. package/dist/v5/skill/browserpaw/SKILL.md +48 -0
  33. package/dist/v5/skill/browserpaw/assets/recipes/developer.mozilla.org.md +15 -0
  34. package/dist/v5/skill/browserpaw/assets/recipes/github-releases.json +177 -0
  35. package/dist/v5/skill/browserpaw/assets/recipes/mdn-search.json +174 -0
  36. package/dist/v5/skill/browserpaw/assets/recipes/npm-compare.json +456 -0
  37. package/dist/v5/skill/browserpaw/assets/recipes/x-search-thread.json +321 -0
  38. package/dist/v5/skill/browserpaw/assets/recipes/x-visible-thread.json +303 -0
  39. package/dist/v5/skill/browserpaw/references/TROUBLESHOOTING.md +7 -0
  40. package/dist/v5/skill/browserpaw/references/TROUBLESHOOTING.zh-CN.md +5 -0
  41. package/dist/v5/skill/browserpaw/references/browser-data.md +33 -0
  42. package/dist/v5/skill/browserpaw/references/commands.md +103 -0
  43. package/dist/v5/skill/browserpaw/references/debugging.md +32 -0
  44. package/dist/v5/skill/browserpaw/references/recipe-contract.md +46 -0
  45. package/package.json +67 -4
@@ -0,0 +1,402 @@
1
+ // keyboard-helper.js
2
+ // This script is injected into the page to handle keyboard event simulation
3
+
4
+ if (window.__KEYBOARD_HELPER_INITIALIZED__) {
5
+ // Already initialized, skip
6
+ } else {
7
+ window.__KEYBOARD_HELPER_INITIALIZED__ = true;
8
+
9
+ // A map for special keys to their KeyboardEvent properties
10
+ // Key names should be lowercase for matching
11
+ const SPECIAL_KEY_MAP = {
12
+ enter: { key: 'Enter', code: 'Enter', keyCode: 13 },
13
+ tab: { key: 'Tab', code: 'Tab', keyCode: 9 },
14
+ esc: { key: 'Escape', code: 'Escape', keyCode: 27 },
15
+ escape: { key: 'Escape', code: 'Escape', keyCode: 27 },
16
+ space: { key: ' ', code: 'Space', keyCode: 32 },
17
+ backspace: { key: 'Backspace', code: 'Backspace', keyCode: 8 },
18
+ delete: { key: 'Delete', code: 'Delete', keyCode: 46 },
19
+ del: { key: 'Delete', code: 'Delete', keyCode: 46 },
20
+ up: { key: 'ArrowUp', code: 'ArrowUp', keyCode: 38 },
21
+ arrowup: { key: 'ArrowUp', code: 'ArrowUp', keyCode: 38 },
22
+ down: { key: 'ArrowDown', code: 'ArrowDown', keyCode: 40 },
23
+ arrowdown: { key: 'ArrowDown', code: 'ArrowDown', keyCode: 40 },
24
+ left: { key: 'ArrowLeft', code: 'ArrowLeft', keyCode: 37 },
25
+ arrowleft: { key: 'ArrowLeft', code: 'ArrowLeft', keyCode: 37 },
26
+ right: { key: 'ArrowRight', code: 'ArrowRight', keyCode: 39 },
27
+ arrowright: { key: 'ArrowRight', code: 'ArrowRight', keyCode: 39 },
28
+ home: { key: 'Home', code: 'Home', keyCode: 36 },
29
+ end: { key: 'End', code: 'End', keyCode: 35 },
30
+ pageup: { key: 'PageUp', code: 'PageUp', keyCode: 33 },
31
+ pagedown: { key: 'PageDown', code: 'PageDown', keyCode: 34 },
32
+ insert: { key: 'Insert', code: 'Insert', keyCode: 45 },
33
+ '+': { key: '+', code: 'Equal', keyCode: 187 },
34
+ plus: { key: '+', code: 'Equal', keyCode: 187 },
35
+ ',': { key: ',', code: 'Comma', keyCode: 188 },
36
+ comma: { key: ',', code: 'Comma', keyCode: 188 },
37
+ // Function keys
38
+ ...Object.fromEntries(
39
+ Array.from({ length: 12 }, (_, i) => [
40
+ `f${i + 1}`,
41
+ { key: `F${i + 1}`, code: `F${i + 1}`, keyCode: 112 + i },
42
+ ]),
43
+ ),
44
+ };
45
+
46
+ const MODIFIER_KEYS = {
47
+ ctrl: 'ctrlKey',
48
+ control: 'ctrlKey',
49
+ alt: 'altKey',
50
+ shift: 'shiftKey',
51
+ meta: 'metaKey',
52
+ command: 'metaKey',
53
+ cmd: 'metaKey',
54
+ };
55
+
56
+ const SHIFTED_DIGITS = ')!@#$%^&*(';
57
+
58
+ /**
59
+ * Parses a key string (e.g., "Ctrl+Shift+A", "Enter") into a main key and modifiers.
60
+ * @param {string} keyString - String representation of a single key press (can include modifiers).
61
+ * @returns { {key: string, code: string, keyCode: number, charCode?: number, modifiers: {ctrlKey:boolean, altKey:boolean, shiftKey:boolean, metaKey:boolean}} | null }
62
+ * Returns null if the keyString is invalid or represents only modifiers.
63
+ */
64
+ function parseSingleKeyCombination(keyString) {
65
+ const rawTrimmed = keyString.trim();
66
+ const modifiers = {
67
+ ctrlKey: false,
68
+ altKey: false,
69
+ shiftKey: false,
70
+ metaKey: false,
71
+ };
72
+
73
+ if (rawTrimmed === '+') {
74
+ return { ...SPECIAL_KEY_MAP['+'], modifiers };
75
+ }
76
+ if (rawTrimmed === ',') {
77
+ return { ...SPECIAL_KEY_MAP[','], modifiers };
78
+ }
79
+
80
+ let mainKeyPart = null;
81
+ if (rawTrimmed.endsWith('++')) {
82
+ const modPrefix = rawTrimmed.slice(0, -2);
83
+ const modParts = modPrefix
84
+ .split('+')
85
+ .map((p) => p.trim().toLowerCase())
86
+ .filter(Boolean);
87
+ let allMods = true;
88
+ for (const m of modParts) {
89
+ if (MODIFIER_KEYS[m]) {
90
+ modifiers[MODIFIER_KEYS[m]] = true;
91
+ } else {
92
+ allMods = false;
93
+ break;
94
+ }
95
+ }
96
+ if (allMods && modParts.length > 0) {
97
+ mainKeyPart = '+';
98
+ }
99
+ }
100
+
101
+ let parts = [];
102
+ if (mainKeyPart === null) {
103
+ parts = rawTrimmed.split('+').map((part) => part.trim().toLowerCase());
104
+ for (const part of parts) {
105
+ if (MODIFIER_KEYS[part]) {
106
+ modifiers[MODIFIER_KEYS[part]] = true;
107
+ } else if (mainKeyPart === null) {
108
+ // First non-modifier is the main key
109
+ mainKeyPart = part;
110
+ } else {
111
+ // Invalid format: multiple main keys in a single combination (e.g., "Ctrl+A+B")
112
+ console.error(`Invalid key combination string: ${keyString}. Multiple main keys found.`);
113
+ return null;
114
+ }
115
+ }
116
+ }
117
+
118
+ if (!mainKeyPart) {
119
+ // This case could happen if the keyString is something like "Ctrl+" or just "Ctrl"
120
+ // If the intent was to press JUST 'Control', the input should be 'Control' not 'Control+'
121
+ // Let's check if mainKeyPart is actually a modifier name used as a main key
122
+ if (parts.length === 1 && MODIFIER_KEYS[parts[0]]) {
123
+ mainKeyPart = parts[0]; // e.g. user wants to press "Control" key itself
124
+ // For "Control" key itself, key: "Control", code: "ControlLeft" (or Right)
125
+ if (mainKeyPart === 'ctrl' || mainKeyPart === 'control')
126
+ return { key: 'Control', code: 'ControlLeft', keyCode: 17, modifiers };
127
+ if (mainKeyPart === 'alt') return { key: 'Alt', code: 'AltLeft', keyCode: 18, modifiers };
128
+ if (mainKeyPart === 'shift')
129
+ return { key: 'Shift', code: 'ShiftLeft', keyCode: 16, modifiers };
130
+ if (mainKeyPart === 'meta' || mainKeyPart === 'command' || mainKeyPart === 'cmd')
131
+ return { key: 'Meta', code: 'MetaLeft', keyCode: 91, modifiers };
132
+ } else {
133
+ console.error(`Invalid key combination string: ${keyString}. No main key specified.`);
134
+ return null;
135
+ }
136
+ }
137
+
138
+ const specialKey = SPECIAL_KEY_MAP[mainKeyPart];
139
+ if (specialKey) {
140
+ return { ...specialKey, modifiers };
141
+ }
142
+
143
+ // For single characters or other unmapped keys
144
+ if (mainKeyPart.length === 1) {
145
+ const isLetter = /^[a-z]$/i.test(mainKeyPart);
146
+ const isDigit = /^[0-9]$/.test(mainKeyPart);
147
+ const charCode = mainKeyPart.charCodeAt(0);
148
+ let keyChar = mainKeyPart;
149
+ if (modifiers.shiftKey) {
150
+ if (isLetter) keyChar = mainKeyPart.toUpperCase();
151
+ else if (isDigit) keyChar = SHIFTED_DIGITS[Number(mainKeyPart)];
152
+ else return null; // Shifted punctuation requires a physical layout.
153
+ }
154
+
155
+ return {
156
+ key: keyChar,
157
+ code: isLetter ? `Key${mainKeyPart.toUpperCase()}` : isDigit ? `Digit${mainKeyPart}` : '',
158
+ keyCode: charCode,
159
+ charCode: keyChar.charCodeAt(0),
160
+ modifiers,
161
+ };
162
+ }
163
+
164
+ console.error(`Unknown key: ${mainKeyPart} in string "${keyString}"`);
165
+ return null; // Or handle as an error
166
+ }
167
+
168
+ /**
169
+ * Simulates a single key press (keydown, (keypress), keyup) for a parsed key.
170
+ * @param { {key: string, code: string, keyCode: number, charCode?: number, modifiers: object} } parsedKeyInfo
171
+ * @param {Element} element - Target element.
172
+ * @returns {{success: boolean, error?: string}}
173
+ */
174
+ function dispatchKeyEvents(parsedKeyInfo, element) {
175
+ if (!parsedKeyInfo) return { success: false, error: 'Invalid key info provided for dispatch.' };
176
+
177
+ const { key, code, keyCode, charCode, modifiers } = parsedKeyInfo;
178
+
179
+ const eventOptions = {
180
+ key: key,
181
+ code: code,
182
+ bubbles: true,
183
+ cancelable: true,
184
+ composed: true, // Important for shadow DOM
185
+ view:
186
+ typeof window !== 'undefined' &&
187
+ window &&
188
+ typeof window.Window === 'function' &&
189
+ window instanceof window.Window
190
+ ? window
191
+ : undefined,
192
+ ...modifiers, // ctrlKey, altKey, shiftKey, metaKey
193
+ // keyCode/which are deprecated but often set for compatibility
194
+ keyCode: keyCode || (key.length === 1 ? key.charCodeAt(0) : 0),
195
+ which: keyCode || (key.length === 1 ? key.charCodeAt(0) : 0),
196
+ };
197
+
198
+ try {
199
+ const kdRes = element.dispatchEvent(new KeyboardEvent('keydown', eventOptions));
200
+
201
+ // keypress is deprecated, but simulate if it's a character key or Enter
202
+ // Only dispatch if keydown was not cancelled and it's a character producing key
203
+ if (kdRes && (key.length === 1 || key === 'Enter' || key === ' ')) {
204
+ const keypressOptions = { ...eventOptions };
205
+ if (charCode) keypressOptions.charCode = charCode;
206
+ element.dispatchEvent(new KeyboardEvent('keypress', keypressOptions));
207
+ }
208
+
209
+ element.dispatchEvent(new KeyboardEvent('keyup', eventOptions));
210
+ return { success: true };
211
+ } catch (error) {
212
+ console.error(`Error dispatching key events for "${key}":`, error);
213
+ return {
214
+ success: false,
215
+ error: `Error dispatching key events for "${key}": ${error.message}`,
216
+ };
217
+ }
218
+ }
219
+
220
+ /**
221
+ * Simulate keyboard events on an element or document
222
+ * @param {string} keysSequenceString - String representation of key(s) (e.g., "Enter", "Ctrl+C, A, B")
223
+ * @param {Element} targetElement - Element to dispatch events on (optional)
224
+ * @param {number} delay - Delay between key sequences in milliseconds (optional)
225
+ * @returns {Promise<Object>} - Result of the keyboard operation
226
+ */
227
+ function splitKeySequence(str) {
228
+ const trimmed = (str || '').trim();
229
+ if (!trimmed) return [];
230
+ if (trimmed === ',') return [','];
231
+
232
+ const results = [];
233
+ let current = '';
234
+
235
+ for (let i = 0; i < trimmed.length; i++) {
236
+ const char = trimmed[i];
237
+ if (char === ',') {
238
+ const trimmedCurrent = current.trim();
239
+ const lastNonSpace = trimmedCurrent.slice(-1);
240
+ if (lastNonSpace === '+' && !trimmedCurrent.endsWith('++')) {
241
+ current += char;
242
+ } else if (!trimmedCurrent) {
243
+ results.push(',');
244
+ current = '';
245
+ } else {
246
+ results.push(trimmedCurrent);
247
+ current = '';
248
+ }
249
+ } else {
250
+ current += char;
251
+ }
252
+ }
253
+
254
+ if (current.trim()) {
255
+ results.push(current.trim());
256
+ }
257
+
258
+ return results.filter(Boolean);
259
+ }
260
+
261
+ async function simulateKeyboard(keysSequenceString, targetElement = null, delay = 0) {
262
+ try {
263
+ let active = document.activeElement;
264
+ const seen = new Set();
265
+ while (
266
+ active &&
267
+ !seen.has(active) &&
268
+ !['INPUT', 'TEXTAREA', 'SELECT'].includes(active.tagName)
269
+ ) {
270
+ seen.add(active);
271
+ let root = active.shadowRoot;
272
+ try {
273
+ root = chrome.dom?.openOrClosedShadowRoot?.(active) || root;
274
+ } catch {}
275
+ const inner = root?.activeElement;
276
+ if (!inner || inner === active) break;
277
+ active = inner;
278
+ }
279
+ const element = targetElement || active || document.body;
280
+
281
+ if (element !== active && typeof element.focus === 'function') {
282
+ element.focus();
283
+ await new Promise((resolve) => setTimeout(resolve, 50)); // Small delay for focus
284
+ }
285
+
286
+ const keyCombinations = splitKeySequence(keysSequenceString);
287
+ const parsedCombinations = keyCombinations.map((comboString) => ({
288
+ comboString,
289
+ parsedKeyInfo: parseSingleKeyCombination(comboString),
290
+ }));
291
+ const invalidCombination = parsedCombinations.find((item) => !item.parsedKeyInfo);
292
+ const targetInfo = {
293
+ tagName: element.tagName,
294
+ id: element.id,
295
+ className: element.className,
296
+ type: element.type, // if applicable e.g. for input
297
+ };
298
+
299
+ if (invalidCombination) {
300
+ return {
301
+ success: false,
302
+ status: 'blocked',
303
+ retry: true,
304
+ dispatched: false,
305
+ error: `Invalid key string or combination: ${invalidCombination.comboString}`,
306
+ message: 'Keyboard sequence rejected before dispatch',
307
+ results: parsedCombinations.map(({ comboString, parsedKeyInfo }) => ({
308
+ keyCombination: comboString,
309
+ success: false,
310
+ dispatched: false,
311
+ error: parsedKeyInfo
312
+ ? `Not dispatched because sequence contains invalid key: ${invalidCombination.comboString}`
313
+ : `Invalid key string or combination: ${comboString}`,
314
+ })),
315
+ targetElement: targetInfo,
316
+ };
317
+ }
318
+
319
+ const operationResults = [];
320
+
321
+ for (let i = 0; i < parsedCombinations.length; i++) {
322
+ const { comboString, parsedKeyInfo } = parsedCombinations[i];
323
+ const dispatchResult = dispatchKeyEvents(parsedKeyInfo, element);
324
+ operationResults.push({
325
+ keyCombination: comboString,
326
+ ...dispatchResult,
327
+ });
328
+
329
+ if (dispatchResult.error) {
330
+ // Optionally, decide if sequence should stop on first error
331
+ // For now, we continue but log the error in results
332
+ console.warn(
333
+ `Failed to simulate key combination "${comboString}": ${dispatchResult.error}`,
334
+ );
335
+ }
336
+
337
+ if (delay > 0 && i < parsedCombinations.length - 1) {
338
+ await new Promise((resolve) => setTimeout(resolve, delay));
339
+ }
340
+ }
341
+
342
+ // Check if all individual operations were successful
343
+ const overallSuccess = operationResults.every((r) => r.success);
344
+
345
+ return {
346
+ success: overallSuccess,
347
+ dispatched: true,
348
+ message: overallSuccess
349
+ ? `Keyboard events simulated successfully: ${keysSequenceString}`
350
+ : `Some keyboard events failed for: ${keysSequenceString}`,
351
+ results: operationResults, // Detailed results for each key combination
352
+ targetElement: targetInfo,
353
+ };
354
+ } catch (error) {
355
+ console.error('Error in simulateKeyboard:', error);
356
+ return {
357
+ success: false,
358
+ error: `Error simulating keyboard events: ${error.message}`,
359
+ results: [],
360
+ };
361
+ }
362
+ }
363
+
364
+ // Listener for messages from the extension
365
+ chrome.runtime.onMessage.addListener((request, _sender, sendResponse) => {
366
+ if (request.action === 'simulateKeyboard') {
367
+ let targetEl = null;
368
+ if (request.selector) {
369
+ targetEl = document.querySelector(request.selector);
370
+ if (!targetEl) {
371
+ sendResponse({
372
+ success: false,
373
+ error: `Element with selector "${request.selector}" not found`,
374
+ results: [],
375
+ });
376
+ return true; // Keep channel open for async response
377
+ }
378
+ }
379
+
380
+ simulateKeyboard(request.keys, targetEl, request.delay)
381
+ .then(sendResponse)
382
+ .catch((error) => {
383
+ // This catch is for unexpected errors in simulateKeyboard promise chain itself
384
+ console.error('Unexpected error in simulateKeyboard promise chain:', error);
385
+ sendResponse({
386
+ success: false,
387
+ error: `Unexpected error during keyboard simulation: ${error.message}`,
388
+ results: [],
389
+ });
390
+ });
391
+ return true; // Indicates async response is expected
392
+ } else if (
393
+ request.action === 'chrome_keyboard_ping' ||
394
+ String(request.action || '').startsWith('mcp_ping_')
395
+ ) {
396
+ sendResponse({ status: 'pong', initialized: true }); // Respond that it's initialized
397
+ return false; // Synchronous response
398
+ }
399
+ // Not our message, or no async response needed
400
+ return false;
401
+ });
402
+ }
@@ -0,0 +1,213 @@
1
+ /**
2
+ * Network Capture Helper
3
+ *
4
+ * This script helps replay network requests with the original cookies and headers.
5
+ */
6
+
7
+ // Prevent duplicate initialization
8
+ if (window.__NETWORK_CAPTURE_HELPER_INITIALIZED__) {
9
+ // Already initialized, skip
10
+ } else {
11
+ window.__NETWORK_CAPTURE_HELPER_INITIALIZED__ = true;
12
+
13
+ /**
14
+ * Replay a network request
15
+ * @param {string} url - The URL to send the request to
16
+ * @param {string} method - The HTTP method to use
17
+ * @param {Object} headers - The headers to include in the request
18
+ * @param {any} body - The body of the request
19
+ * @param {number} timeout - Timeout in milliseconds (default: 30000)
20
+ * @returns {Promise<Object>} - The response data
21
+ */
22
+ async function replayNetworkRequest(
23
+ url,
24
+ method,
25
+ headers,
26
+ body,
27
+ timeout = 30000,
28
+ formDataDescriptor = null,
29
+ ) {
30
+ try {
31
+ // Create fetch options
32
+ const options = {
33
+ method: method,
34
+ headers: headers || {},
35
+ credentials: 'include', // Include cookies
36
+ mode: 'cors',
37
+ cache: 'no-cache',
38
+ };
39
+
40
+ // Helper: convert base64 to Blob
41
+ const base64ToBlob = (base64, contentType = 'application/octet-stream') => {
42
+ try {
43
+ const decodedString = atob(base64);
44
+ const len = decodedString.length;
45
+ const bytes = new Uint8Array(len);
46
+ for (let i = 0; i < len; i++) bytes[i] = decodedString.charCodeAt(i);
47
+ return new Blob([bytes], { type: contentType });
48
+ } catch (e) {
49
+ return new Blob([]);
50
+ }
51
+ };
52
+
53
+ // Build multipart/form-data if descriptor is provided
54
+ if (method !== 'GET' && method !== 'HEAD' && formDataDescriptor) {
55
+ const fd = new FormData();
56
+ try {
57
+ if (Array.isArray(formDataDescriptor)) {
58
+ for (const item of formDataDescriptor) {
59
+ if (!Array.isArray(item) || item.length < 2) continue;
60
+ const name = String(item[0] || 'file');
61
+ const spec = String(item[1] || '');
62
+ const filenameHint = item[2] ? String(item[2]) : undefined;
63
+ if (/^(https?:\/\/|url:)/i.test(spec)) {
64
+ const url = spec.replace(/^url:/i, '');
65
+ const resp = await fetch(url);
66
+ const blob = await resp.blob();
67
+ const fn =
68
+ filenameHint || url.split('?')[0].split('#')[0].split('/').pop() || 'file';
69
+ fd.append(name, blob, fn);
70
+ } else if (/^base64:/i.test(spec)) {
71
+ const b64 = spec.replace(/^base64:/i, '');
72
+ const blob = base64ToBlob(b64);
73
+ fd.append(name, blob, filenameHint || 'file');
74
+ } else {
75
+ // treat as string field
76
+ fd.append(name, spec);
77
+ }
78
+ }
79
+ } else if (typeof formDataDescriptor === 'object') {
80
+ const fds = formDataDescriptor;
81
+ const fields = fds.fields || {};
82
+ const files = Array.isArray(fds.files) ? fds.files : [];
83
+ for (const [k, v] of Object.entries(fields)) fd.append(String(k), String(v));
84
+ for (const file of files) {
85
+ const name = String(file.name || 'file');
86
+ if (file.fileUrl) {
87
+ const resp = await fetch(String(file.fileUrl));
88
+ const blob = await resp.blob();
89
+ const fn =
90
+ file.filename ||
91
+ String(file.fileUrl).split('?')[0].split('#')[0].split('/').pop() ||
92
+ 'file';
93
+ fd.append(name, blob, fn);
94
+ } else if (typeof file.base64Data === 'string') {
95
+ const blob = base64ToBlob(
96
+ String(file.base64Data),
97
+ String(file.contentType || 'application/octet-stream'),
98
+ );
99
+ fd.append(name, blob, file.filename || 'file');
100
+ }
101
+ }
102
+ }
103
+ } catch (e) {
104
+ console.warn('Failed to construct FormData:', e);
105
+ }
106
+ // Let browser set the correct multipart boundary
107
+ try {
108
+ if (options.headers) {
109
+ delete options.headers['content-type'];
110
+ delete options.headers['Content-Type'];
111
+ }
112
+ } catch {}
113
+ options.body = fd;
114
+ } else if (method !== 'GET' && method !== 'HEAD' && body !== undefined) {
115
+ // Fallback to raw body
116
+ options.body = body;
117
+ }
118
+
119
+ // Create a fetch request with timeout
120
+ const fetchWithTimeout = async (url, options, timeout) => {
121
+ const controller = new AbortController();
122
+ const signal = controller.signal;
123
+
124
+ // Set up abort timeout
125
+ const timeoutId = setTimeout(() => controller.abort(), timeout);
126
+
127
+ try {
128
+ const response = await fetch(url, { ...options, signal });
129
+ clearTimeout(timeoutId);
130
+ return response;
131
+ } catch (error) {
132
+ clearTimeout(timeoutId);
133
+ throw error;
134
+ }
135
+ };
136
+
137
+ // Send request with timeout controller
138
+ const response = await fetchWithTimeout(url, options, timeout);
139
+
140
+ // Process response
141
+ const responseData = {
142
+ status: response.status,
143
+ statusText: response.statusText,
144
+ headers: {},
145
+ };
146
+
147
+ // Get response headers
148
+ response.headers.forEach((value, key) => {
149
+ responseData.headers[key] = value;
150
+ });
151
+
152
+ // Try to get response body based on content type
153
+ const contentType = response.headers.get('content-type') || '';
154
+
155
+ try {
156
+ if (contentType.includes('application/json')) {
157
+ responseData.body = await response.json();
158
+ } else if (
159
+ contentType.includes('text/') ||
160
+ contentType.includes('application/xml') ||
161
+ contentType.includes('application/javascript')
162
+ ) {
163
+ responseData.body = await response.text();
164
+ } else {
165
+ // For binary data, just indicate it was received but not parsed
166
+ responseData.body = '[Binary data not displayed]';
167
+ }
168
+ } catch (error) {
169
+ responseData.body = `[Error parsing response body: ${error.message}]`;
170
+ }
171
+
172
+ return {
173
+ success: true,
174
+ response: responseData,
175
+ };
176
+ } catch (error) {
177
+ console.error('Error replaying request:', error);
178
+ return {
179
+ success: false,
180
+ error: `Error replaying request: ${error.message}`,
181
+ };
182
+ }
183
+ }
184
+
185
+ // Listen for messages from the extension
186
+ chrome.runtime.onMessage.addListener((request, _sender, sendResponse) => {
187
+ // Respond to ping message
188
+ if (
189
+ request.action === 'chrome_network_request_ping' ||
190
+ String(request.action || '').startsWith('mcp_ping_')
191
+ ) {
192
+ sendResponse({ status: 'pong' });
193
+ return false; // Synchronous response
194
+ } else if (request.action === 'sendPureNetworkRequest') {
195
+ replayNetworkRequest(
196
+ request.url,
197
+ request.method,
198
+ request.headers,
199
+ request.body,
200
+ request.timeout,
201
+ request.formData,
202
+ )
203
+ .then(sendResponse)
204
+ .catch((error) => {
205
+ sendResponse({
206
+ success: false,
207
+ error: `Unexpected error: ${error.message}`,
208
+ });
209
+ });
210
+ return true; // Indicates async response
211
+ }
212
+ });
213
+ }