@wordbricks/playwright-mcp 0.1.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/README.md +624 -0
- package/cli-wrapper.js +47 -0
- package/cli.js +18 -0
- package/config.d.ts +119 -0
- package/index.d.ts +23 -0
- package/index.js +19 -0
- package/lib/browserContextFactory.js +289 -0
- package/lib/browserServerBackend.js +82 -0
- package/lib/config.js +246 -0
- package/lib/context.js +236 -0
- package/lib/extension/cdpRelay.js +346 -0
- package/lib/extension/extensionContextFactory.js +56 -0
- package/lib/frameworkPatterns.js +35 -0
- package/lib/hooks/core.js +144 -0
- package/lib/hooks/eventConsumer.js +39 -0
- package/lib/hooks/events.js +42 -0
- package/lib/hooks/formatToolCallEvent.js +16 -0
- package/lib/hooks/frameworkStateHook.js +182 -0
- package/lib/hooks/grouping.js +72 -0
- package/lib/hooks/jsonLdDetectionHook.js +175 -0
- package/lib/hooks/networkFilters.js +74 -0
- package/lib/hooks/networkSetup.js +56 -0
- package/lib/hooks/networkTrackingHook.js +55 -0
- package/lib/hooks/pageHeightHook.js +75 -0
- package/lib/hooks/registry.js +39 -0
- package/lib/hooks/requireTabHook.js +26 -0
- package/lib/hooks/schema.js +75 -0
- package/lib/hooks/waitHook.js +33 -0
- package/lib/index.js +39 -0
- package/lib/loop/loop.js +69 -0
- package/lib/loop/loopClaude.js +152 -0
- package/lib/loop/loopOpenAI.js +141 -0
- package/lib/loop/main.js +60 -0
- package/lib/loopTools/context.js +66 -0
- package/lib/loopTools/main.js +51 -0
- package/lib/loopTools/perform.js +32 -0
- package/lib/loopTools/snapshot.js +29 -0
- package/lib/loopTools/tool.js +18 -0
- package/lib/mcp/inProcessTransport.js +72 -0
- package/lib/mcp/proxyBackend.js +115 -0
- package/lib/mcp/server.js +86 -0
- package/lib/mcp/tool.js +29 -0
- package/lib/mcp/transport.js +181 -0
- package/lib/playwrightTransformer.js +497 -0
- package/lib/program.js +111 -0
- package/lib/response.js +186 -0
- package/lib/sessionLog.js +121 -0
- package/lib/tab.js +249 -0
- package/lib/tools/common.js +55 -0
- package/lib/tools/console.js +33 -0
- package/lib/tools/dialogs.js +47 -0
- package/lib/tools/evaluate.js +53 -0
- package/lib/tools/extractFrameworkState.js +214 -0
- package/lib/tools/files.js +44 -0
- package/lib/tools/getSnapshot.js +37 -0
- package/lib/tools/getVisibleHtml.js +52 -0
- package/lib/tools/install.js +53 -0
- package/lib/tools/keyboard.js +78 -0
- package/lib/tools/mouse.js +99 -0
- package/lib/tools/navigate.js +70 -0
- package/lib/tools/network.js +123 -0
- package/lib/tools/networkDetail.js +231 -0
- package/lib/tools/networkSearch/bodySearch.js +141 -0
- package/lib/tools/networkSearch/grouping.js +28 -0
- package/lib/tools/networkSearch/helpers.js +32 -0
- package/lib/tools/networkSearch/searchHtml.js +65 -0
- package/lib/tools/networkSearch/types.js +1 -0
- package/lib/tools/networkSearch/urlSearch.js +82 -0
- package/lib/tools/networkSearch.js +168 -0
- package/lib/tools/pdf.js +40 -0
- package/lib/tools/repl.js +402 -0
- package/lib/tools/screenshot.js +79 -0
- package/lib/tools/scroll.js +126 -0
- package/lib/tools/snapshot.js +139 -0
- package/lib/tools/tabs.js +87 -0
- package/lib/tools/tool.js +33 -0
- package/lib/tools/utils.js +74 -0
- package/lib/tools/wait.js +55 -0
- package/lib/tools.js +67 -0
- package/lib/utils/codegen.js +49 -0
- package/lib/utils/extensionPath.js +6 -0
- package/lib/utils/fileUtils.js +36 -0
- package/lib/utils/graphql.js +258 -0
- package/lib/utils/guid.js +22 -0
- package/lib/utils/httpServer.js +39 -0
- package/lib/utils/log.js +21 -0
- package/lib/utils/manualPromise.js +111 -0
- package/lib/utils/networkFormat.js +12 -0
- package/lib/utils/package.js +20 -0
- package/lib/utils/result.js +2 -0
- package/lib/utils/sanitizeHtml.js +98 -0
- package/lib/utils/truncate.js +103 -0
- package/lib/utils/withTimeout.js +7 -0
- package/package.json +100 -0
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copyright (c) Microsoft Corporation.
|
|
3
|
+
*
|
|
4
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
+
* you may not use this file except in compliance with the License.
|
|
6
|
+
* You may obtain a copy of the License at
|
|
7
|
+
*
|
|
8
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
+
*
|
|
10
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
11
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
+
* See the License for the specific language governing permissions and
|
|
14
|
+
* limitations under the License.
|
|
15
|
+
*/
|
|
16
|
+
import { z } from 'zod';
|
|
17
|
+
import { defineTool, defineTabTool } from './tool.js';
|
|
18
|
+
const navigate = defineTool({
|
|
19
|
+
capability: 'core',
|
|
20
|
+
schema: {
|
|
21
|
+
name: 'browser_navigate',
|
|
22
|
+
title: 'Navigate to a URL',
|
|
23
|
+
description: 'Navigate to a URL',
|
|
24
|
+
inputSchema: z.object({
|
|
25
|
+
url: z.string().describe('The URL to navigate to'),
|
|
26
|
+
}),
|
|
27
|
+
type: 'destructive',
|
|
28
|
+
},
|
|
29
|
+
handle: async (context, params, response) => {
|
|
30
|
+
const tab = await context.ensureTab();
|
|
31
|
+
await tab.navigate(params.url);
|
|
32
|
+
response.setIncludeSnapshot();
|
|
33
|
+
response.addCode(`await page.goto('${params.url}');`);
|
|
34
|
+
},
|
|
35
|
+
});
|
|
36
|
+
const goBack = defineTabTool({
|
|
37
|
+
capability: 'core',
|
|
38
|
+
schema: {
|
|
39
|
+
name: 'browser_navigate_back',
|
|
40
|
+
title: 'Go back',
|
|
41
|
+
description: 'Go back to the previous page',
|
|
42
|
+
inputSchema: z.object({}),
|
|
43
|
+
type: 'readOnly',
|
|
44
|
+
},
|
|
45
|
+
handle: async (tab, params, response) => {
|
|
46
|
+
await tab.page.goBack();
|
|
47
|
+
response.setIncludeSnapshot();
|
|
48
|
+
response.addCode(`await page.goBack();`);
|
|
49
|
+
},
|
|
50
|
+
});
|
|
51
|
+
const goForward = defineTabTool({
|
|
52
|
+
capability: 'core',
|
|
53
|
+
schema: {
|
|
54
|
+
name: 'browser_navigate_forward',
|
|
55
|
+
title: 'Go forward',
|
|
56
|
+
description: 'Go forward to the next page',
|
|
57
|
+
inputSchema: z.object({}),
|
|
58
|
+
type: 'readOnly',
|
|
59
|
+
},
|
|
60
|
+
handle: async (tab, params, response) => {
|
|
61
|
+
await tab.page.goForward();
|
|
62
|
+
response.setIncludeSnapshot();
|
|
63
|
+
response.addCode(`await page.goForward();`);
|
|
64
|
+
},
|
|
65
|
+
});
|
|
66
|
+
export default [
|
|
67
|
+
navigate,
|
|
68
|
+
goBack,
|
|
69
|
+
goForward,
|
|
70
|
+
];
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copyright (c) Microsoft Corporation.
|
|
3
|
+
*
|
|
4
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
+
* you may not use this file except in compliance with the License.
|
|
6
|
+
* You may obtain a copy of the License at
|
|
7
|
+
*
|
|
8
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
+
*
|
|
10
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
11
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
+
* See the License for the specific language governing permissions and
|
|
14
|
+
* limitations under the License.
|
|
15
|
+
*/
|
|
16
|
+
import { z } from 'zod';
|
|
17
|
+
import { defineTabTool } from './tool.js';
|
|
18
|
+
import { formatUrlWithTrimmedParams } from '../hooks/networkFilters.js';
|
|
19
|
+
// const requests = defineTool({
|
|
20
|
+
// capability: 'core',
|
|
21
|
+
// schema: {
|
|
22
|
+
// name: 'browser_network_requests',
|
|
23
|
+
// title: 'List network requests',
|
|
24
|
+
// description: 'Returns all network requests since loading the page',
|
|
25
|
+
// inputSchema: z.object({}),
|
|
26
|
+
// type: 'readOnly',
|
|
27
|
+
// },
|
|
28
|
+
// handle: async ctx => {
|
|
29
|
+
// const reqs = await pipe(
|
|
30
|
+
// ctx.currentTabOrDie().requests().entries(),
|
|
31
|
+
// filter(([request, response]) => ['document', 'xhr', 'fetch'].includes(request.resourceType())),
|
|
32
|
+
// // GET, POST
|
|
33
|
+
// filter(([request, response]) => ['GET', 'POST'].includes(request.method())),
|
|
34
|
+
// // 2xx
|
|
35
|
+
// filter(([request, response]) => response?.ok()),
|
|
36
|
+
// // 204 No Content
|
|
37
|
+
// reject(([request, response]) => response?.status() === 204),
|
|
38
|
+
// // body length > 0
|
|
39
|
+
// toAsync,
|
|
40
|
+
// filter(([request, response]) => response ? withTimeout(response.body(), 500).catch(() => []).then(body => body.length > 0) : Promise.resolve(false)),
|
|
41
|
+
// uniqBy(([request, response]) => JSON.stringify({
|
|
42
|
+
// url: request.url(),
|
|
43
|
+
// body: request.postData(),
|
|
44
|
+
// })),
|
|
45
|
+
// toArray,
|
|
46
|
+
// );
|
|
47
|
+
// const lines = await Promise.all(
|
|
48
|
+
// reqs.map(([request, response]) => renderRequest(request, response))
|
|
49
|
+
// );
|
|
50
|
+
// const log = lines.join('\n');
|
|
51
|
+
// return {
|
|
52
|
+
// code: [`// <internal code to list network requests>`],
|
|
53
|
+
// action: async () => {
|
|
54
|
+
// return {
|
|
55
|
+
// content: [{ type: 'text', text: log }]
|
|
56
|
+
// };
|
|
57
|
+
// },
|
|
58
|
+
// captureSnapshot: false,
|
|
59
|
+
// waitForNetwork: false,
|
|
60
|
+
// };
|
|
61
|
+
// },
|
|
62
|
+
// });
|
|
63
|
+
const requests = defineTabTool({
|
|
64
|
+
capability: 'core',
|
|
65
|
+
schema: {
|
|
66
|
+
name: 'browser_network_requests',
|
|
67
|
+
title: 'List network requests',
|
|
68
|
+
description: 'Returns all network requests since loading the page',
|
|
69
|
+
inputSchema: z.object({}),
|
|
70
|
+
type: 'readOnly',
|
|
71
|
+
},
|
|
72
|
+
handle: async (tab, params, response) => {
|
|
73
|
+
const requests = tab.requests();
|
|
74
|
+
for (const [req, res] of requests.entries())
|
|
75
|
+
response.addResult(await renderRequest(req, res));
|
|
76
|
+
},
|
|
77
|
+
});
|
|
78
|
+
export async function renderRequest(request, response) {
|
|
79
|
+
const result = [];
|
|
80
|
+
// Basic request information (trimmed URL params for token efficiency)
|
|
81
|
+
const trimmedUrl = formatUrlWithTrimmedParams(request.url());
|
|
82
|
+
result.push(`[${request.method().toUpperCase()}] ${trimmedUrl}`);
|
|
83
|
+
// Append response status if available with compact content-type
|
|
84
|
+
if (response) {
|
|
85
|
+
const ct = response.headers()?.['content-type'];
|
|
86
|
+
result.push(`=> [${response.status()}] ${response.statusText()}${ct ? ` ct=${ct}` : ''}`);
|
|
87
|
+
}
|
|
88
|
+
// Always include request headers (excluding HTTP/2 pseudo-headers and common headers)
|
|
89
|
+
// const allHeaders = await request.allHeaders();
|
|
90
|
+
// const headers = Object.fromEntries(
|
|
91
|
+
// Object.entries(allHeaders).filter(([key]) => {
|
|
92
|
+
// const lowerKey = key.toLowerCase();
|
|
93
|
+
// // Filter out HTTP/2 pseudo-headers
|
|
94
|
+
// if (lowerKey.startsWith(':'))
|
|
95
|
+
// return false;
|
|
96
|
+
// // Filter out specified headers
|
|
97
|
+
// if (lowerKey === 'accept-encoding' ||
|
|
98
|
+
// lowerKey.startsWith('sec-') ||
|
|
99
|
+
// lowerKey.startsWith('sentry-') ||
|
|
100
|
+
// lowerKey === 'baggage' ||
|
|
101
|
+
// lowerKey === 'ect' ||
|
|
102
|
+
// lowerKey === 'connection' ||
|
|
103
|
+
// lowerKey === 'accept-language' ||
|
|
104
|
+
// lowerKey === 'priority' ||
|
|
105
|
+
// lowerKey === 'user-agent' ||
|
|
106
|
+
// lowerKey === 'upgrade-insecure-requests' ||
|
|
107
|
+
// lowerKey === 'cache-control')
|
|
108
|
+
// return false;
|
|
109
|
+
// return true;
|
|
110
|
+
// })
|
|
111
|
+
// );
|
|
112
|
+
// result.push(`headers=${JSON.stringify(headers)}`);
|
|
113
|
+
// Include raw body when method is not GET
|
|
114
|
+
// if (request.method().toUpperCase() !== 'GET') {
|
|
115
|
+
// const body = request.postData();
|
|
116
|
+
// if (body)
|
|
117
|
+
// result.push(`body=${body}`);
|
|
118
|
+
// }
|
|
119
|
+
return result.join('\n');
|
|
120
|
+
}
|
|
121
|
+
export default [
|
|
122
|
+
requests,
|
|
123
|
+
];
|
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import ms from 'ms';
|
|
3
|
+
import * as cheerio from 'cheerio';
|
|
4
|
+
import { defineTabTool } from './tool.js';
|
|
5
|
+
import { removeNonEssentialLinks, removeMetaTags, removeHtmlComments, stripSvgAttributes, minifyHtml } from '../utils/sanitizeHtml.js';
|
|
6
|
+
import { formatTruncationLine } from '../utils/truncate.js';
|
|
7
|
+
import { withTimeout } from '../utils/withTimeout.js';
|
|
8
|
+
import { getNetworkEventEntry } from '../hooks/networkSetup.js';
|
|
9
|
+
import { parseGraphQLRequestFromHttp, summarizeGraphQL, extractGraphQLResponseInfo, minifyGraphQLQuery, minifyGraphQLRequestBody } from '../utils/graphql.js';
|
|
10
|
+
import { formatNetworkSummaryLine } from '../utils/networkFormat.js';
|
|
11
|
+
const TIMEOUT_MS = ms('5s');
|
|
12
|
+
const CHUNK_BYTES = 8 * 1024; // 8KB per page
|
|
13
|
+
const contextBodyMap = new WeakMap();
|
|
14
|
+
// Skip HTTP/2 pseudo-headers and their non-colon variants in displayed request headers
|
|
15
|
+
const SKIP_REQUEST_HEADER_KEYS = new Set([
|
|
16
|
+
':authority',
|
|
17
|
+
':method',
|
|
18
|
+
':path',
|
|
19
|
+
':scheme',
|
|
20
|
+
'authority',
|
|
21
|
+
'method',
|
|
22
|
+
'path',
|
|
23
|
+
'scheme',
|
|
24
|
+
]);
|
|
25
|
+
const getStateMap = (ctx) => {
|
|
26
|
+
let m = contextBodyMap.get(ctx);
|
|
27
|
+
if (!m) {
|
|
28
|
+
m = new Map();
|
|
29
|
+
contextBodyMap.set(ctx, m);
|
|
30
|
+
}
|
|
31
|
+
return m;
|
|
32
|
+
};
|
|
33
|
+
const networkDetailSchema = z.object({
|
|
34
|
+
id: z.number().describe('The network event id from events log'),
|
|
35
|
+
});
|
|
36
|
+
const normalizeHeaderKeys = (headers) => {
|
|
37
|
+
const out = {};
|
|
38
|
+
for (const [k, v] of Object.entries(headers))
|
|
39
|
+
out[k.toLowerCase()] = v;
|
|
40
|
+
return out;
|
|
41
|
+
};
|
|
42
|
+
const formatBytes = (n) => {
|
|
43
|
+
const units = ['B', 'KB', 'MB', 'GB'];
|
|
44
|
+
let i = 0;
|
|
45
|
+
let v = n;
|
|
46
|
+
while (v >= 1024 && i < units.length - 1) {
|
|
47
|
+
v /= 1024;
|
|
48
|
+
i++;
|
|
49
|
+
}
|
|
50
|
+
const digits = v < 10 && i > 0 ? 1 : 0;
|
|
51
|
+
return `${v.toFixed(digits)} ${units[i]}`;
|
|
52
|
+
};
|
|
53
|
+
const formatRequestDetail = async (ctx, { request, response, id, }) => {
|
|
54
|
+
const lines = [];
|
|
55
|
+
const reqHeaders = normalizeHeaderKeys(await request.allHeaders());
|
|
56
|
+
const requestBody = request.postData();
|
|
57
|
+
lines.push(formatNetworkSummaryLine({
|
|
58
|
+
method: request.method(),
|
|
59
|
+
url: request.url(),
|
|
60
|
+
status: response ? response.status() : 0,
|
|
61
|
+
statusText: response?.statusText(),
|
|
62
|
+
postData: requestBody,
|
|
63
|
+
headers: reqHeaders,
|
|
64
|
+
}, { trimParams: false }));
|
|
65
|
+
const timing = response ? response.request().timing() : null;
|
|
66
|
+
if (timing) {
|
|
67
|
+
const duration = Math.round(timing.responseEnd - timing.requestStart);
|
|
68
|
+
if (!Number.isNaN(duration))
|
|
69
|
+
lines.push(`Duration: ${duration}ms`);
|
|
70
|
+
}
|
|
71
|
+
lines.push(`Failure: ${request.failure()?.errorText || 'None'}`);
|
|
72
|
+
if (!response) {
|
|
73
|
+
lines.push(`\nRequest Headers:`);
|
|
74
|
+
const headerKeysNoResp = Object.keys(reqHeaders)
|
|
75
|
+
.filter(k => !SKIP_REQUEST_HEADER_KEYS.has(k))
|
|
76
|
+
.sort();
|
|
77
|
+
for (const key of headerKeysNoResp)
|
|
78
|
+
lines.push(`${key}: ${reqHeaders[key]}`);
|
|
79
|
+
lines.push(`\nNo response received yet`);
|
|
80
|
+
return lines.join('\n');
|
|
81
|
+
}
|
|
82
|
+
// Determine if this request is GraphQL (used for both request and response sections)
|
|
83
|
+
const gqlReq = parseGraphQLRequestFromHttp(request.method(), request.url(), reqHeaders, requestBody);
|
|
84
|
+
const map = getStateMap(ctx);
|
|
85
|
+
const existing = map.get(id);
|
|
86
|
+
let state;
|
|
87
|
+
if (!existing) {
|
|
88
|
+
state = { cursor: 0, headersShown: false, isGraphQLRequest: !!gqlReq };
|
|
89
|
+
map.set(id, state);
|
|
90
|
+
}
|
|
91
|
+
else {
|
|
92
|
+
state = existing;
|
|
93
|
+
state.isGraphQLRequest = !!gqlReq;
|
|
94
|
+
}
|
|
95
|
+
// Headers printed once (first call)
|
|
96
|
+
if (!state.headersShown) {
|
|
97
|
+
// Print full request headers on the first call (excluding authority/method/path/scheme)
|
|
98
|
+
lines.push(`\nRequest Headers:`);
|
|
99
|
+
const headerKeys = Object.keys(reqHeaders)
|
|
100
|
+
.filter(k => !SKIP_REQUEST_HEADER_KEYS.has(k))
|
|
101
|
+
.sort();
|
|
102
|
+
for (const key of headerKeys)
|
|
103
|
+
lines.push(`${key}: ${reqHeaders[key]}`);
|
|
104
|
+
const reqCt = reqHeaders['content-type'];
|
|
105
|
+
// GraphQL request summary (if applicable) and compact body handling
|
|
106
|
+
if (gqlReq) {
|
|
107
|
+
lines.push(`\nGraphQL Request: ${summarizeGraphQL(gqlReq)}`);
|
|
108
|
+
if (gqlReq.variables && typeof gqlReq.variables === 'object' && !Array.isArray(gqlReq.variables)) {
|
|
109
|
+
const varKeys = Object.keys(gqlReq.variables);
|
|
110
|
+
if (varKeys.length)
|
|
111
|
+
lines.push(`Variables: { ${varKeys.join(', ')} }`);
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
if (requestBody) {
|
|
115
|
+
if (gqlReq) {
|
|
116
|
+
lines.push(`\nRequest Body (GraphQL):`);
|
|
117
|
+
try {
|
|
118
|
+
if (reqCt && reqCt.includes('application/graphql')) {
|
|
119
|
+
lines.push(minifyGraphQLQuery(requestBody));
|
|
120
|
+
}
|
|
121
|
+
else {
|
|
122
|
+
const body = JSON.parse(requestBody);
|
|
123
|
+
const minimized = minifyGraphQLRequestBody(body);
|
|
124
|
+
lines.push(JSON.stringify(minimized, null, 2));
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
catch {
|
|
128
|
+
lines.push(requestBody);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
else {
|
|
132
|
+
lines.push(`\nRequest Body:`);
|
|
133
|
+
try {
|
|
134
|
+
lines.push(JSON.stringify(JSON.parse(requestBody), null, 2));
|
|
135
|
+
}
|
|
136
|
+
catch {
|
|
137
|
+
lines.push(requestBody);
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
const resHeaders = normalizeHeaderKeys(await response.allHeaders());
|
|
142
|
+
const resCt = resHeaders['content-type'];
|
|
143
|
+
const resCl = resHeaders['content-length'];
|
|
144
|
+
const headerParts = [];
|
|
145
|
+
if (resCt)
|
|
146
|
+
headerParts.push(`content-type=${resCt}`);
|
|
147
|
+
if (resCl)
|
|
148
|
+
headerParts.push(`content-length=${resCl}`);
|
|
149
|
+
if (headerParts.length)
|
|
150
|
+
lines.push(`\nResponse Headers: { ${headerParts.join(', ')} }`);
|
|
151
|
+
}
|
|
152
|
+
// Fetch the full body each time
|
|
153
|
+
let buf;
|
|
154
|
+
try {
|
|
155
|
+
buf = await withTimeout(response.body(), TIMEOUT_MS);
|
|
156
|
+
}
|
|
157
|
+
catch (e) {
|
|
158
|
+
const msg = e instanceof Error ? e.message : String(e);
|
|
159
|
+
lines.push(`\nFailed to read response body: ${msg}`);
|
|
160
|
+
return lines.join('\n');
|
|
161
|
+
}
|
|
162
|
+
// On first page, summarize GraphQL response if applicable
|
|
163
|
+
if (!state.headersShown && state.isGraphQLRequest) {
|
|
164
|
+
try {
|
|
165
|
+
const fullText = buf.toString('utf8');
|
|
166
|
+
const gqlInfo = extractGraphQLResponseInfo(fullText);
|
|
167
|
+
if (gqlInfo) {
|
|
168
|
+
lines.push(`\nGraphQL Response: ${gqlInfo.hasErrors ? `${gqlInfo.errorCount} error(s)` : 'ok'}`);
|
|
169
|
+
if (gqlInfo.topMessages.length)
|
|
170
|
+
lines.push(`Errors: ${gqlInfo.topMessages.join(' | ')}`);
|
|
171
|
+
if (gqlInfo.dataKeys.length)
|
|
172
|
+
lines.push(`Data keys: ${gqlInfo.dataKeys.join(', ')}`);
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
catch { }
|
|
176
|
+
}
|
|
177
|
+
// Reset if finished in a prior call
|
|
178
|
+
if (state.cursor >= buf.length) {
|
|
179
|
+
state.cursor = 0;
|
|
180
|
+
state.headersShown = false; // allow headers again after a full pass
|
|
181
|
+
}
|
|
182
|
+
let bodyText = buf.toString('utf8');
|
|
183
|
+
const resHeadersForBody = normalizeHeaderKeys(await response.allHeaders());
|
|
184
|
+
const resCtForBody = resHeadersForBody['content-type'] || '';
|
|
185
|
+
const isHtml = resCtForBody.includes('html');
|
|
186
|
+
if (isHtml) {
|
|
187
|
+
const $ = cheerio.load(bodyText, { xmlMode: false });
|
|
188
|
+
removeNonEssentialLinks($);
|
|
189
|
+
removeMetaTags($);
|
|
190
|
+
removeHtmlComments($);
|
|
191
|
+
stripSvgAttributes($);
|
|
192
|
+
bodyText = minifyHtml($.root().html() || '');
|
|
193
|
+
}
|
|
194
|
+
const totalLength = bodyText.length;
|
|
195
|
+
const start = state.cursor;
|
|
196
|
+
const end = Math.min(start + CHUNK_BYTES, totalLength);
|
|
197
|
+
const chunk = bodyText.slice(start, end);
|
|
198
|
+
const nextCursor = end;
|
|
199
|
+
const more = nextCursor < totalLength;
|
|
200
|
+
const percent = totalLength ? Math.round((nextCursor / totalLength) * 100) : 100;
|
|
201
|
+
lines.push(`\nBody Chunk (text): ${percent}%${more ? ' (more)' : ' (done)'}:`);
|
|
202
|
+
lines.push(chunk);
|
|
203
|
+
if (more)
|
|
204
|
+
lines.push(formatTruncationLine(nextCursor, buf.length, { formatter: formatBytes }));
|
|
205
|
+
state.cursor = nextCursor;
|
|
206
|
+
state.headersShown = true;
|
|
207
|
+
return lines.join('\n');
|
|
208
|
+
};
|
|
209
|
+
const networkDetail = defineTabTool({
|
|
210
|
+
capability: 'core',
|
|
211
|
+
schema: {
|
|
212
|
+
name: 'browser_network_detail',
|
|
213
|
+
title: 'Get network request detail',
|
|
214
|
+
description: 'Show detailed info for a specific network request by event id. Call repeatedly to page through the body.',
|
|
215
|
+
inputSchema: networkDetailSchema,
|
|
216
|
+
type: 'readOnly',
|
|
217
|
+
},
|
|
218
|
+
handle: async (tab, params, r) => {
|
|
219
|
+
const entry = getNetworkEventEntry(tab.context, params.id);
|
|
220
|
+
if (!entry) {
|
|
221
|
+
r.addResult(`Network request with ID ${params.id} not found`);
|
|
222
|
+
return;
|
|
223
|
+
}
|
|
224
|
+
r.addResult(await formatRequestDetail(tab.context, {
|
|
225
|
+
request: entry.request,
|
|
226
|
+
response: entry.response,
|
|
227
|
+
id: params.id,
|
|
228
|
+
}));
|
|
229
|
+
},
|
|
230
|
+
});
|
|
231
|
+
export default [networkDetail];
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
import { withTimeout } from '../../utils/withTimeout.js';
|
|
2
|
+
import { searchInHtml } from './searchHtml.js';
|
|
3
|
+
import { highlightMatch } from './helpers.js';
|
|
4
|
+
const CONTEXT_LENGTH_BODY = 400;
|
|
5
|
+
const CONTEXT_LENGTH_DEFAULT = 300;
|
|
6
|
+
const MAX_SEARCH_DEPTH = 20;
|
|
7
|
+
export const searchInObject = (obj, keyword, path, matches, depth = 0) => {
|
|
8
|
+
if (depth > MAX_SEARCH_DEPTH || !obj || typeof obj !== 'object')
|
|
9
|
+
return;
|
|
10
|
+
for (const key in obj) {
|
|
11
|
+
const newPath = path ? `${path}.${key}` : key;
|
|
12
|
+
const value = obj[key];
|
|
13
|
+
if (key.toLowerCase().includes(keyword)) {
|
|
14
|
+
const highlightedKey = highlightMatch(key, keyword, CONTEXT_LENGTH_DEFAULT);
|
|
15
|
+
const valueContext = typeof value === 'object' && value !== null
|
|
16
|
+
? truncateJsonPreview(value)
|
|
17
|
+
: truncateStringPreview(String(value));
|
|
18
|
+
matches.push({
|
|
19
|
+
path: newPath,
|
|
20
|
+
value: typeof value === 'object' && value !== null ? JSON.stringify(value) : String(value),
|
|
21
|
+
context: `${highlightedKey}: ${valueContext}`,
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
if (typeof value === 'string' && value.toLowerCase().includes(keyword)) {
|
|
25
|
+
matches.push({
|
|
26
|
+
path: newPath,
|
|
27
|
+
value: value,
|
|
28
|
+
context: `${key}: ${highlightMatch(value, keyword, CONTEXT_LENGTH_DEFAULT)}`,
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
else if (typeof value === 'number' && String(value).includes(keyword)) {
|
|
32
|
+
const valueStr = String(value);
|
|
33
|
+
matches.push({
|
|
34
|
+
path: newPath,
|
|
35
|
+
value: valueStr,
|
|
36
|
+
context: `${key}: ${highlightMatch(valueStr, keyword, CONTEXT_LENGTH_DEFAULT)}`,
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
if (typeof value === 'object' && value !== null)
|
|
40
|
+
searchInObject(value, keyword, newPath, matches, depth + 1);
|
|
41
|
+
}
|
|
42
|
+
};
|
|
43
|
+
const truncateStringPreview = (text) => text.length > CONTEXT_LENGTH_DEFAULT ? text.slice(0, CONTEXT_LENGTH_DEFAULT) + '...' : text;
|
|
44
|
+
const truncateJsonPreview = (obj) => {
|
|
45
|
+
try {
|
|
46
|
+
return JSON.stringify(obj).slice(0, CONTEXT_LENGTH_BODY) + '...';
|
|
47
|
+
}
|
|
48
|
+
catch {
|
|
49
|
+
return '[Object]';
|
|
50
|
+
}
|
|
51
|
+
};
|
|
52
|
+
export const searchInRequestBody = (request, keyword, matches) => {
|
|
53
|
+
const body = request.postData();
|
|
54
|
+
if (!body || !body.toLowerCase().includes(keyword))
|
|
55
|
+
return;
|
|
56
|
+
const requestContentType = request.headers()['content-type'] || '';
|
|
57
|
+
let handled = false;
|
|
58
|
+
if (requestContentType.includes('application/json') || body.trim().startsWith('{') || body.trim().startsWith('[')) {
|
|
59
|
+
try {
|
|
60
|
+
const parsed = JSON.parse(body);
|
|
61
|
+
searchInObject(parsed, keyword, 'request.body', matches);
|
|
62
|
+
handled = true;
|
|
63
|
+
}
|
|
64
|
+
catch { }
|
|
65
|
+
}
|
|
66
|
+
if (!handled && (requestContentType.includes('text/html') || body.trim().startsWith('<'))) {
|
|
67
|
+
searchInHtml(body, keyword, 'request.body', matches);
|
|
68
|
+
handled = true;
|
|
69
|
+
}
|
|
70
|
+
if (!handled && requestContentType.includes('application/x-www-form-urlencoded')) {
|
|
71
|
+
try {
|
|
72
|
+
const sp = new URLSearchParams(body);
|
|
73
|
+
for (const [k, v] of sp.entries()) {
|
|
74
|
+
const vStr = v || '';
|
|
75
|
+
if (!vStr.toLowerCase().includes(keyword))
|
|
76
|
+
continue;
|
|
77
|
+
const trimmed = vStr.trim();
|
|
78
|
+
let parsedOk = false;
|
|
79
|
+
if (trimmed.startsWith('{') || trimmed.startsWith('[')) {
|
|
80
|
+
try {
|
|
81
|
+
const parsed = JSON.parse(trimmed);
|
|
82
|
+
searchInObject(parsed, keyword, `request.body.form.${k}`, matches);
|
|
83
|
+
parsedOk = true;
|
|
84
|
+
}
|
|
85
|
+
catch { }
|
|
86
|
+
}
|
|
87
|
+
if (!parsedOk) {
|
|
88
|
+
matches.push({
|
|
89
|
+
path: `request.body.form.${k}`,
|
|
90
|
+
value: vStr,
|
|
91
|
+
context: `${k}=${highlightMatch(vStr, keyword, CONTEXT_LENGTH_DEFAULT)}`,
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
handled = true;
|
|
96
|
+
}
|
|
97
|
+
catch { }
|
|
98
|
+
}
|
|
99
|
+
if (!handled) {
|
|
100
|
+
matches.push({
|
|
101
|
+
path: 'request.body',
|
|
102
|
+
value: body,
|
|
103
|
+
context: highlightMatch(body, keyword, CONTEXT_LENGTH_BODY),
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
};
|
|
107
|
+
export const searchInResponseBody = async (response, keyword, matches) => {
|
|
108
|
+
const contentTypeHeader = response.headers()['content-type'] || '';
|
|
109
|
+
if (!(contentTypeHeader.startsWith('text/') || contentTypeHeader.includes('application/json') || contentTypeHeader.includes('application/xml')))
|
|
110
|
+
return;
|
|
111
|
+
try {
|
|
112
|
+
const responseBody = await withTimeout(response.text(), 2000);
|
|
113
|
+
if (!responseBody || !responseBody.toLowerCase().includes(keyword))
|
|
114
|
+
return;
|
|
115
|
+
let handled = false;
|
|
116
|
+
const trimmed = responseBody.trimStart();
|
|
117
|
+
const xssiPrefix = ")]}'";
|
|
118
|
+
const hasXssi = trimmed.startsWith(xssiPrefix);
|
|
119
|
+
const jsonCandidate = hasXssi ? trimmed.slice(xssiPrefix.length) : trimmed;
|
|
120
|
+
if (contentTypeHeader.includes('application/json') || jsonCandidate.startsWith('{') || jsonCandidate.startsWith('[')) {
|
|
121
|
+
try {
|
|
122
|
+
const parsed = JSON.parse(jsonCandidate);
|
|
123
|
+
searchInObject(parsed, keyword, 'response.body', matches);
|
|
124
|
+
handled = true;
|
|
125
|
+
}
|
|
126
|
+
catch { }
|
|
127
|
+
}
|
|
128
|
+
if (!handled && (contentTypeHeader.includes('text/html') || responseBody.trim().startsWith('<'))) {
|
|
129
|
+
searchInHtml(responseBody, keyword, 'response.body', matches);
|
|
130
|
+
handled = true;
|
|
131
|
+
}
|
|
132
|
+
if (!handled) {
|
|
133
|
+
matches.push({
|
|
134
|
+
path: 'response.body',
|
|
135
|
+
value: responseBody,
|
|
136
|
+
context: highlightMatch(responseBody, keyword, CONTEXT_LENGTH_BODY),
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
catch { }
|
|
141
|
+
};
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
export const normalizePath = (path) => {
|
|
2
|
+
if (path.includes(' > '))
|
|
3
|
+
return path.replace(/:nth-child\(\d+\)/g, ':nth-child(*)');
|
|
4
|
+
return path.replace(/\.(?:\d+)(?=\.|$)/g, '.*');
|
|
5
|
+
};
|
|
6
|
+
export const getDepth = (path) => {
|
|
7
|
+
const separators = path.match(/\.|>/g) || [];
|
|
8
|
+
return separators.length;
|
|
9
|
+
};
|
|
10
|
+
export const mergeGroupedMatches = (a, b) => {
|
|
11
|
+
const map = new Map();
|
|
12
|
+
for (const g of a)
|
|
13
|
+
map.set(g.normalized, { normalized: g.normalized, count: g.count, examples: g.examples.slice(0, 3) });
|
|
14
|
+
for (const g of b) {
|
|
15
|
+
const existing = map.get(g.normalized);
|
|
16
|
+
if (existing) {
|
|
17
|
+
existing.count += g.count;
|
|
18
|
+
for (const e of g.examples) {
|
|
19
|
+
if (existing.examples.length < 3 && !existing.examples.some(x => x.context === e.context))
|
|
20
|
+
existing.examples.push(e);
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
else {
|
|
24
|
+
map.set(g.normalized, { normalized: g.normalized, count: g.count, examples: g.examples.slice(0, 3) });
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
return Array.from(map.values());
|
|
28
|
+
};
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { truncateStringTo } from '../../utils/truncate.js';
|
|
2
|
+
export const parseKeywordParams = (keyword) => {
|
|
3
|
+
const out = [];
|
|
4
|
+
try {
|
|
5
|
+
const sp = new URLSearchParams(keyword);
|
|
6
|
+
sp.forEach((value, key) => {
|
|
7
|
+
if (key)
|
|
8
|
+
out.push({ name: key, value });
|
|
9
|
+
});
|
|
10
|
+
}
|
|
11
|
+
catch { }
|
|
12
|
+
return out;
|
|
13
|
+
};
|
|
14
|
+
export const highlightMatch = (text, keyword, maxLength = 50) => {
|
|
15
|
+
const lowerText = text.toLowerCase();
|
|
16
|
+
const index = lowerText.indexOf(keyword);
|
|
17
|
+
if (index === -1)
|
|
18
|
+
return truncateStringTo(text, maxLength).text;
|
|
19
|
+
const contextBefore = Math.floor((maxLength - keyword.length) / 2);
|
|
20
|
+
const contextAfter = maxLength - keyword.length - contextBefore;
|
|
21
|
+
const start = Math.max(0, index - contextBefore);
|
|
22
|
+
const end = Math.min(text.length, index + keyword.length + contextAfter);
|
|
23
|
+
let result = '';
|
|
24
|
+
if (start > 0)
|
|
25
|
+
result += '...';
|
|
26
|
+
result += text.substring(start, index);
|
|
27
|
+
result += text.substring(index, index + keyword.length);
|
|
28
|
+
result += text.substring(index + keyword.length, end);
|
|
29
|
+
if (end < text.length)
|
|
30
|
+
result += '...';
|
|
31
|
+
return result;
|
|
32
|
+
};
|