mcp-browser-dev-tools 0.0.1 → 0.0.2-beta.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +9 -1
- package/package.json +4 -1
- package/src/app.mjs +9 -1
- package/src/browser-adapter.mjs +30 -0
- package/src/cdp-client.mjs +159 -0
- package/src/cli.mjs +13 -3
- package/src/config.mjs +25 -0
- package/src/firefox-bidi-client.mjs +71 -0
- package/src/index.mjs +3 -0
- package/src/logger.mjs +53 -0
- package/src/mcp-server.mjs +156 -12
- package/src/tcp-relay.mjs +7 -1
- package/src/wait-for.mjs +201 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Rindo Hinase <rindo.hinase@gmail.com>
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -10,8 +10,10 @@ It is designed for a local trust boundary:
|
|
|
10
10
|
|
|
11
11
|
- A stdio MCP server for local desktop and terminal clients
|
|
12
12
|
- Browser discovery and attach/detach for Chrome, Edge, other Chromium-family browsers, and Firefox
|
|
13
|
+
- Tab lifecycle tools to create and close browser tabs through MCP
|
|
13
14
|
- Inspection tools for DOM lookup, richer element details, console messages, network requests, screenshots, tab listing, and buffered events
|
|
14
15
|
- Page interaction tools for navigation, reload, click, hover, type, select, key presses, scroll, and viewport overrides
|
|
16
|
+
- Wait conditions for selector visibility, URL changes, and document ready state
|
|
15
17
|
- Optional JavaScript evaluation behind an explicit environment flag
|
|
16
18
|
- Helper commands to check browser connectivity, launch a debug-enabled browser, and relay CDP traffic across a local machine boundary
|
|
17
19
|
|
|
@@ -286,6 +288,8 @@ mbdt relay --wsl
|
|
|
286
288
|
- `FIREFOX_BIDI_WS_URL` defaults to `ws://127.0.0.1:9222`; when pointed at the root Firefox remote debugging port, the broker connects to the `/session` websocket and creates a BiDi session there
|
|
287
289
|
- in `auto` mode, assign CDP and Firefox different ports so both browsers can run at once
|
|
288
290
|
- `MCP_BROWSER_EVENT_BUFFER_SIZE` sets the per-session buffered event limit
|
|
291
|
+
- `MCP_BROWSER_LOG_LEVEL` controls diagnostic logging to `stderr`: `error`, `warn`, `info`, or `debug`
|
|
292
|
+
- `MCP_BROWSER_DEBUG_STDIO=1` emits raw MCP stdio transport diagnostics to `stderr`
|
|
289
293
|
- `MCP_BROWSER_ENABLE_EVAL=1` enables `evaluate_js`
|
|
290
294
|
- `MCP_BROWSER_ALLOW_REMOTE_ENDPOINTS=1` allows non-loopback CDP or BiDi endpoints
|
|
291
295
|
- `MCP_BROWSER_ALLOW_REMOTE_CDP=1` is still accepted as a legacy alias
|
|
@@ -301,11 +305,14 @@ The `relay` command defaults to `127.0.0.1:9223 -> 127.0.0.1:9222`. Non-loopback
|
|
|
301
305
|
In `auto` mode it also includes per-browser adapter status under `browsers`
|
|
302
306
|
- `list_tabs`
|
|
303
307
|
In `auto` mode each `targetId` is namespaced as `chromium:<id>` or `firefox:<id>`
|
|
308
|
+
- `new_tab`
|
|
309
|
+
- `close_tab`
|
|
304
310
|
- `list_sessions`
|
|
305
311
|
In `auto` mode each `sessionId` is namespaced the same way
|
|
306
312
|
- `attach_tab`
|
|
307
313
|
- `detach_tab`
|
|
308
314
|
- `get_page_state`
|
|
315
|
+
- `wait_for`
|
|
309
316
|
- `navigate`
|
|
310
317
|
- `reload`
|
|
311
318
|
- `click`
|
|
@@ -355,7 +362,7 @@ Playwright is still the stronger choice for deterministic browser automation and
|
|
|
355
362
|
`mcp-browser-dev-tools` solves a different problem:
|
|
356
363
|
|
|
357
364
|
- it is MCP-native, so AI clients call a bounded tool surface instead of generating and executing Playwright scripts
|
|
358
|
-
- it
|
|
365
|
+
- it can inspect an already-open browser tab or create a fresh one, then inspect the current session state, cookies, login state, extensions, console, and network history
|
|
359
366
|
- it is designed for local AI debugging workflows, including loopback-only defaults, opt-in evaluation, and the Windows-to-WSL relay path
|
|
360
367
|
- it presents one MCP interface across Chromium CDP and Firefox BiDi instead of requiring the AI client to know browser protocol details
|
|
361
368
|
|
|
@@ -366,6 +373,7 @@ Use Playwright when you want reproducible automation. Use this project when you
|
|
|
366
373
|
- `attach_tab` now seeds network history from the Performance API so already-loaded pages still show useful requests
|
|
367
374
|
- console buffers include source URL, line and column where the browser reports them, plus stack frames when available
|
|
368
375
|
- `get_page_state` reports the current URL, title, viewport, and scroll position without enabling `evaluate_js`
|
|
376
|
+
- broker diagnostics write to `stderr` so `stdout` stays reserved for MCP protocol traffic
|
|
369
377
|
|
|
370
378
|
## Safety Defaults
|
|
371
379
|
|
package/package.json
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "mcp-browser-dev-tools",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.2-beta.0",
|
|
4
4
|
"description": "Local MCP server for Chromium DevTools Protocol and Firefox WebDriver BiDi",
|
|
5
5
|
"author": "Hinaser <rindo.hinase@gmail.com>",
|
|
6
|
+
"license": "MIT",
|
|
6
7
|
"type": "module",
|
|
7
8
|
"packageManager": "pnpm@10.29.3",
|
|
8
9
|
"homepage": "https://github.com/Hinaser/mcp-browser-dev-tools#readme",
|
|
@@ -30,12 +31,14 @@
|
|
|
30
31
|
"src/firefox-bidi-client.mjs",
|
|
31
32
|
"src/index.mjs",
|
|
32
33
|
"src/json-rpc-stdio.mjs",
|
|
34
|
+
"src/logger.mjs",
|
|
33
35
|
"src/mcp-server.mjs",
|
|
34
36
|
"src/page-context.mjs",
|
|
35
37
|
"src/package-info.mjs",
|
|
36
38
|
"src/session-events.mjs",
|
|
37
39
|
"src/server.mjs",
|
|
38
40
|
"src/tcp-relay.mjs",
|
|
41
|
+
"src/wait-for.mjs",
|
|
39
42
|
"README.md"
|
|
40
43
|
],
|
|
41
44
|
"bin": {
|
package/src/app.mjs
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { createBrowserAdapter } from "./browser-adapter.mjs";
|
|
2
2
|
import { loadConfig } from "./config.mjs";
|
|
3
|
+
import { createLogger } from "./logger.mjs";
|
|
3
4
|
import { McpBrowserDevToolsServer } from "./mcp-server.mjs";
|
|
4
5
|
import { PACKAGE_NAME } from "./package-info.mjs";
|
|
5
6
|
|
|
@@ -10,6 +11,11 @@ export function createBrowserDevToolsApp({
|
|
|
10
11
|
errorOutput = process.stderr,
|
|
11
12
|
} = {}) {
|
|
12
13
|
const config = loadConfig(env);
|
|
14
|
+
const logger = createLogger({
|
|
15
|
+
level: config.logLevel,
|
|
16
|
+
output: errorOutput,
|
|
17
|
+
name: PACKAGE_NAME,
|
|
18
|
+
});
|
|
13
19
|
const browserAdapter = createBrowserAdapter(config);
|
|
14
20
|
const server = new McpBrowserDevToolsServer({
|
|
15
21
|
config,
|
|
@@ -17,6 +23,7 @@ export function createBrowserDevToolsApp({
|
|
|
17
23
|
input,
|
|
18
24
|
output,
|
|
19
25
|
errorOutput,
|
|
26
|
+
logger,
|
|
20
27
|
});
|
|
21
28
|
|
|
22
29
|
let closing = false;
|
|
@@ -27,7 +34,7 @@ export function createBrowserDevToolsApp({
|
|
|
27
34
|
}
|
|
28
35
|
|
|
29
36
|
closing = true;
|
|
30
|
-
|
|
37
|
+
logger.info(`shutting down after ${signal}`);
|
|
31
38
|
await browserAdapter.closeAll();
|
|
32
39
|
}
|
|
33
40
|
|
|
@@ -47,6 +54,7 @@ export function createBrowserDevToolsApp({
|
|
|
47
54
|
|
|
48
55
|
return {
|
|
49
56
|
config,
|
|
57
|
+
logger,
|
|
50
58
|
browserAdapter,
|
|
51
59
|
server,
|
|
52
60
|
start,
|
package/src/browser-adapter.mjs
CHANGED
|
@@ -161,6 +161,32 @@ export class MultiBrowserAdapter {
|
|
|
161
161
|
);
|
|
162
162
|
}
|
|
163
163
|
|
|
164
|
+
async createTab(url, options = {}) {
|
|
165
|
+
const browserFamily = options.browserFamily;
|
|
166
|
+
if (!browserFamily) {
|
|
167
|
+
throw new Error(
|
|
168
|
+
"browserFamily is required when multiple browsers are configured",
|
|
169
|
+
);
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
const result = await this.getAdapter(browserFamily).createTab(url);
|
|
173
|
+
return {
|
|
174
|
+
...mapPrefixedFields(result, browserFamily),
|
|
175
|
+
browserFamily,
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
async closeTarget(targetId) {
|
|
180
|
+
const { browserFamily, localId } = resolvePrefixedId(targetId, "targetId");
|
|
181
|
+
return {
|
|
182
|
+
...mapPrefixedFields(
|
|
183
|
+
await this.getAdapter(browserFamily).closeTarget(localId),
|
|
184
|
+
browserFamily,
|
|
185
|
+
),
|
|
186
|
+
browserFamily,
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
|
|
164
190
|
async delegateSession(sessionId, methodName, args = []) {
|
|
165
191
|
const { browserFamily, localId } = resolvePrefixedId(
|
|
166
192
|
sessionId,
|
|
@@ -188,6 +214,10 @@ export class MultiBrowserAdapter {
|
|
|
188
214
|
return this.delegateSession(sessionId, "getPageState");
|
|
189
215
|
}
|
|
190
216
|
|
|
217
|
+
waitFor(sessionId, options) {
|
|
218
|
+
return this.delegateSession(sessionId, "waitFor", [options]);
|
|
219
|
+
}
|
|
220
|
+
|
|
191
221
|
navigate(sessionId, url, options) {
|
|
192
222
|
return this.delegateSession(sessionId, "navigate", [url, options]);
|
|
193
223
|
}
|
package/src/cdp-client.mjs
CHANGED
|
@@ -2,6 +2,7 @@ import {
|
|
|
2
2
|
filterConsoleMessages,
|
|
3
3
|
summarizeNetworkRequests,
|
|
4
4
|
} from "./session-events.mjs";
|
|
5
|
+
import { waitForPageCondition } from "./wait-for.mjs";
|
|
5
6
|
import { buildPageContextExpression } from "./page-context.mjs";
|
|
6
7
|
|
|
7
8
|
function toErrorMessage(error) {
|
|
@@ -19,6 +20,19 @@ function normalizeTarget(target) {
|
|
|
19
20
|
};
|
|
20
21
|
}
|
|
21
22
|
|
|
23
|
+
function inferTitle(url) {
|
|
24
|
+
if (!url) {
|
|
25
|
+
return "New Tab";
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
try {
|
|
29
|
+
const parsed = new URL(url);
|
|
30
|
+
return parsed.hostname || url;
|
|
31
|
+
} catch {
|
|
32
|
+
return url;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
22
36
|
function cdpBrowserFamily(config) {
|
|
23
37
|
return config.browserFamily === "edge" ? "edge" : "chromium";
|
|
24
38
|
}
|
|
@@ -891,6 +905,92 @@ export class CdpSessionManager {
|
|
|
891
905
|
return parseJson(response);
|
|
892
906
|
}
|
|
893
907
|
|
|
908
|
+
async sendBrowserCommand(method, params = {}) {
|
|
909
|
+
const info = await this.fetchJson("/json/version");
|
|
910
|
+
if (!info.webSocketDebuggerUrl) {
|
|
911
|
+
throw new Error("Browser endpoint does not expose a debugger websocket");
|
|
912
|
+
}
|
|
913
|
+
|
|
914
|
+
const websocket = new WebSocket(info.webSocketDebuggerUrl);
|
|
915
|
+
|
|
916
|
+
return new Promise((resolve, reject) => {
|
|
917
|
+
let settled = false;
|
|
918
|
+
|
|
919
|
+
const cleanup = () => {
|
|
920
|
+
websocket.removeEventListener("open", handleOpen);
|
|
921
|
+
websocket.removeEventListener("message", handleMessage);
|
|
922
|
+
websocket.removeEventListener("error", handleError);
|
|
923
|
+
websocket.removeEventListener("close", handleClose);
|
|
924
|
+
};
|
|
925
|
+
|
|
926
|
+
const finish = (callback) => {
|
|
927
|
+
if (settled) {
|
|
928
|
+
return;
|
|
929
|
+
}
|
|
930
|
+
|
|
931
|
+
settled = true;
|
|
932
|
+
cleanup();
|
|
933
|
+
callback();
|
|
934
|
+
|
|
935
|
+
if (websocket.readyState < WebSocket.CLOSING) {
|
|
936
|
+
websocket.close();
|
|
937
|
+
}
|
|
938
|
+
};
|
|
939
|
+
|
|
940
|
+
const handleOpen = () => {
|
|
941
|
+
try {
|
|
942
|
+
websocket.send(
|
|
943
|
+
JSON.stringify({
|
|
944
|
+
id: 1,
|
|
945
|
+
method,
|
|
946
|
+
params,
|
|
947
|
+
}),
|
|
948
|
+
);
|
|
949
|
+
} catch (error) {
|
|
950
|
+
finish(() => reject(error));
|
|
951
|
+
}
|
|
952
|
+
};
|
|
953
|
+
|
|
954
|
+
const handleMessage = async (event) => {
|
|
955
|
+
const raw = await readWebSocketData(event.data);
|
|
956
|
+
const message = JSON.parse(raw);
|
|
957
|
+
if (message.id !== 1) {
|
|
958
|
+
return;
|
|
959
|
+
}
|
|
960
|
+
|
|
961
|
+
if (message.error) {
|
|
962
|
+
finish(() =>
|
|
963
|
+
reject(
|
|
964
|
+
new Error(
|
|
965
|
+
`${message.error.message} (code ${message.error.code})`,
|
|
966
|
+
),
|
|
967
|
+
),
|
|
968
|
+
);
|
|
969
|
+
return;
|
|
970
|
+
}
|
|
971
|
+
|
|
972
|
+
finish(() => resolve(message.result ?? {}));
|
|
973
|
+
};
|
|
974
|
+
|
|
975
|
+
const handleError = () => {
|
|
976
|
+
finish(() =>
|
|
977
|
+
reject(
|
|
978
|
+
new Error(`Failed to connect to ${info.webSocketDebuggerUrl}`),
|
|
979
|
+
),
|
|
980
|
+
);
|
|
981
|
+
};
|
|
982
|
+
|
|
983
|
+
const handleClose = () => {
|
|
984
|
+
finish(() => reject(new Error("Browser debugger websocket closed")));
|
|
985
|
+
};
|
|
986
|
+
|
|
987
|
+
websocket.addEventListener("open", handleOpen, { once: true });
|
|
988
|
+
websocket.addEventListener("message", handleMessage);
|
|
989
|
+
websocket.addEventListener("error", handleError, { once: true });
|
|
990
|
+
websocket.addEventListener("close", handleClose, { once: true });
|
|
991
|
+
});
|
|
992
|
+
}
|
|
993
|
+
|
|
894
994
|
async getBrowserStatus() {
|
|
895
995
|
try {
|
|
896
996
|
const info = await this.fetchJson("/json/version");
|
|
@@ -925,6 +1025,33 @@ export class CdpSessionManager {
|
|
|
925
1025
|
);
|
|
926
1026
|
}
|
|
927
1027
|
|
|
1028
|
+
async createTab(url = "about:blank") {
|
|
1029
|
+
const targetUrl =
|
|
1030
|
+
typeof url === "string" && url.trim() ? url.trim() : "about:blank";
|
|
1031
|
+
const result = await this.sendBrowserCommand("Target.createTarget", {
|
|
1032
|
+
url: targetUrl,
|
|
1033
|
+
});
|
|
1034
|
+
const targetId = result.targetId;
|
|
1035
|
+
if (!targetId) {
|
|
1036
|
+
throw new Error("Browser did not return a target id for the new tab");
|
|
1037
|
+
}
|
|
1038
|
+
const target = (await this.listTargets()).find(
|
|
1039
|
+
(candidate) => candidate.targetId === targetId,
|
|
1040
|
+
);
|
|
1041
|
+
|
|
1042
|
+
return {
|
|
1043
|
+
browserFamily: cdpBrowserFamily(this.config),
|
|
1044
|
+
...(target ?? {
|
|
1045
|
+
targetId,
|
|
1046
|
+
type: "page",
|
|
1047
|
+
title: inferTitle(targetUrl),
|
|
1048
|
+
url: targetUrl,
|
|
1049
|
+
attached: false,
|
|
1050
|
+
webSocketDebuggerUrl: null,
|
|
1051
|
+
}),
|
|
1052
|
+
};
|
|
1053
|
+
}
|
|
1054
|
+
|
|
928
1055
|
async attachToTarget(targetId) {
|
|
929
1056
|
const targets = await this.listTargets();
|
|
930
1057
|
const target = targets.find((candidate) => candidate.targetId === targetId);
|
|
@@ -963,6 +1090,30 @@ export class CdpSessionManager {
|
|
|
963
1090
|
};
|
|
964
1091
|
}
|
|
965
1092
|
|
|
1093
|
+
async closeTarget(targetId) {
|
|
1094
|
+
const result = await this.sendBrowserCommand("Target.closeTarget", {
|
|
1095
|
+
targetId,
|
|
1096
|
+
});
|
|
1097
|
+
if (result.success === false) {
|
|
1098
|
+
throw new Error(`Failed to close target ${targetId}`);
|
|
1099
|
+
}
|
|
1100
|
+
|
|
1101
|
+
const detachedSessions = Array.from(this.sessions.values())
|
|
1102
|
+
.filter((session) => session.target.targetId === targetId)
|
|
1103
|
+
.map((session) => {
|
|
1104
|
+
session.markClosed?.();
|
|
1105
|
+
this.sessions.delete(session.id);
|
|
1106
|
+
return { sessionId: session.id };
|
|
1107
|
+
});
|
|
1108
|
+
|
|
1109
|
+
return {
|
|
1110
|
+
browserFamily: cdpBrowserFamily(this.config),
|
|
1111
|
+
closed: true,
|
|
1112
|
+
targetId,
|
|
1113
|
+
detachedSessions,
|
|
1114
|
+
};
|
|
1115
|
+
}
|
|
1116
|
+
|
|
966
1117
|
async evaluate(sessionId, expression, options) {
|
|
967
1118
|
return this.getSession(sessionId).evaluate(expression, options);
|
|
968
1119
|
}
|
|
@@ -975,6 +1126,14 @@ export class CdpSessionManager {
|
|
|
975
1126
|
return this.getSession(sessionId).getPageState();
|
|
976
1127
|
}
|
|
977
1128
|
|
|
1129
|
+
async waitFor(sessionId, options = {}) {
|
|
1130
|
+
return waitForPageCondition({
|
|
1131
|
+
getPageState: () => this.getPageState(sessionId),
|
|
1132
|
+
inspectElement: (selector) => this.inspectElement(sessionId, selector),
|
|
1133
|
+
options,
|
|
1134
|
+
});
|
|
1135
|
+
}
|
|
1136
|
+
|
|
978
1137
|
async navigate(sessionId, url, options) {
|
|
979
1138
|
return this.getSession(sessionId).navigate(url, options);
|
|
980
1139
|
}
|
package/src/cli.mjs
CHANGED
|
@@ -10,8 +10,9 @@ import {
|
|
|
10
10
|
buildBrowserLaunchArgs,
|
|
11
11
|
findBrowserExecutable,
|
|
12
12
|
} from "./browser-launcher.mjs";
|
|
13
|
-
import { isLoopbackHost, loadConfig } from "./config.mjs";
|
|
13
|
+
import { isLoopbackHost, loadConfig, loadLoggingConfig } from "./config.mjs";
|
|
14
14
|
import { collectDoctorReport, renderDoctorReport } from "./doctor.mjs";
|
|
15
|
+
import { createLogger } from "./logger.mjs";
|
|
15
16
|
import { PACKAGE_NAME, PACKAGE_VERSION } from "./package-info.mjs";
|
|
16
17
|
import { resolveRelayOptions, startTcpRelay } from "./tcp-relay.mjs";
|
|
17
18
|
|
|
@@ -325,11 +326,20 @@ async function runOpen(positional, options) {
|
|
|
325
326
|
}
|
|
326
327
|
|
|
327
328
|
async function runRelay(options) {
|
|
329
|
+
const logging = loadLoggingConfig(process.env);
|
|
330
|
+
const logger = createLogger({
|
|
331
|
+
level: logging.logLevel,
|
|
332
|
+
output: process.stderr,
|
|
333
|
+
name: PACKAGE_NAME,
|
|
334
|
+
});
|
|
328
335
|
const relayOptions = resolveRelayOptions(options);
|
|
329
|
-
const relay = await startTcpRelay(
|
|
336
|
+
const relay = await startTcpRelay({
|
|
337
|
+
...relayOptions,
|
|
338
|
+
logger,
|
|
339
|
+
});
|
|
330
340
|
|
|
331
341
|
const close = async (signal) => {
|
|
332
|
-
|
|
342
|
+
logger.info(`relay shutting down after ${signal}`);
|
|
333
343
|
await relay.close();
|
|
334
344
|
};
|
|
335
345
|
|
package/src/config.mjs
CHANGED
|
@@ -3,6 +3,7 @@ export const DEFAULT_FIREFOX_BIDI_WS_URL = "ws://127.0.0.1:9222";
|
|
|
3
3
|
export const DEFAULT_EVENT_BUFFER_SIZE = 200;
|
|
4
4
|
export const DEFAULT_PROTOCOL_VERSION = "2024-11-05";
|
|
5
5
|
export const DEFAULT_BROWSER_FAMILY = "chromium";
|
|
6
|
+
export const DEFAULT_LOG_LEVEL = "error";
|
|
6
7
|
export const CDP_BROWSER_FAMILIES = ["chromium", "edge"];
|
|
7
8
|
|
|
8
9
|
export function isLoopbackHost(value) {
|
|
@@ -59,11 +60,33 @@ export function parseBrowserFamily(value) {
|
|
|
59
60
|
return DEFAULT_BROWSER_FAMILY;
|
|
60
61
|
}
|
|
61
62
|
|
|
63
|
+
export function parseLogLevel(value) {
|
|
64
|
+
const normalized = value?.trim().toLowerCase();
|
|
65
|
+
if (
|
|
66
|
+
normalized === "error" ||
|
|
67
|
+
normalized === "warn" ||
|
|
68
|
+
normalized === "info" ||
|
|
69
|
+
normalized === "debug"
|
|
70
|
+
) {
|
|
71
|
+
return normalized;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
return DEFAULT_LOG_LEVEL;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export function loadLoggingConfig(env = process.env) {
|
|
78
|
+
return {
|
|
79
|
+
logLevel: parseLogLevel(env.MCP_BROWSER_LOG_LEVEL),
|
|
80
|
+
debugStdio: isTruthyFlag(env.MCP_BROWSER_DEBUG_STDIO),
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
|
|
62
84
|
export function loadConfig(env = process.env) {
|
|
63
85
|
const browserFamily = parseBrowserFamily(env.MCP_BROWSER_FAMILY);
|
|
64
86
|
const allowRemoteEndpoints = allowsRemoteEndpoints(env);
|
|
65
87
|
const cdpBaseUrl = normalizeBaseUrl(env.CDP_BASE_URL);
|
|
66
88
|
const firefoxBidiWsUrl = normalizeWebSocketUrl(env.FIREFOX_BIDI_WS_URL);
|
|
89
|
+
const logging = loadLoggingConfig(env);
|
|
67
90
|
const endpointsToValidate =
|
|
68
91
|
browserFamily === "firefox"
|
|
69
92
|
? [["FIREFOX_BIDI_WS_URL", firefoxBidiWsUrl]]
|
|
@@ -95,6 +118,8 @@ export function loadConfig(env = process.env) {
|
|
|
95
118
|
env.MCP_BROWSER_EVENT_BUFFER_SIZE,
|
|
96
119
|
DEFAULT_EVENT_BUFFER_SIZE,
|
|
97
120
|
),
|
|
121
|
+
logLevel: logging.logLevel,
|
|
122
|
+
debugStdio: logging.debugStdio,
|
|
98
123
|
protocolVersion:
|
|
99
124
|
env.MCP_PROTOCOL_VERSION?.trim() || DEFAULT_PROTOCOL_VERSION,
|
|
100
125
|
};
|
|
@@ -2,6 +2,7 @@ import {
|
|
|
2
2
|
filterConsoleMessages,
|
|
3
3
|
summarizeNetworkRequests,
|
|
4
4
|
} from "./session-events.mjs";
|
|
5
|
+
import { waitForPageCondition } from "./wait-for.mjs";
|
|
5
6
|
import { buildPageContextExpression } from "./page-context.mjs";
|
|
6
7
|
|
|
7
8
|
function toErrorMessage(error) {
|
|
@@ -620,6 +621,46 @@ export class FirefoxBidiSessionManager {
|
|
|
620
621
|
);
|
|
621
622
|
}
|
|
622
623
|
|
|
624
|
+
async createTab(url = "about:blank") {
|
|
625
|
+
await this.ensureConnected();
|
|
626
|
+
const targetUrl =
|
|
627
|
+
typeof url === "string" && url.trim() ? url.trim() : "about:blank";
|
|
628
|
+
const result = await this.send("browsingContext.create", {
|
|
629
|
+
type: "tab",
|
|
630
|
+
});
|
|
631
|
+
const targetId = result.context;
|
|
632
|
+
if (!targetId) {
|
|
633
|
+
throw new Error(
|
|
634
|
+
"Firefox did not return a browsing context id for the new tab",
|
|
635
|
+
);
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
if (targetUrl !== "about:blank") {
|
|
639
|
+
await this.send("browsingContext.navigate", {
|
|
640
|
+
context: targetId,
|
|
641
|
+
url: targetUrl,
|
|
642
|
+
wait: "complete",
|
|
643
|
+
});
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
const target = (await this.listTargets()).find(
|
|
647
|
+
(candidate) => candidate.targetId === targetId,
|
|
648
|
+
);
|
|
649
|
+
|
|
650
|
+
return {
|
|
651
|
+
browserFamily: "firefox",
|
|
652
|
+
...(target ?? {
|
|
653
|
+
targetId,
|
|
654
|
+
type: "page",
|
|
655
|
+
title: inferTitle(targetUrl),
|
|
656
|
+
url: targetUrl,
|
|
657
|
+
attached: false,
|
|
658
|
+
userContext: null,
|
|
659
|
+
clientWindow: null,
|
|
660
|
+
}),
|
|
661
|
+
};
|
|
662
|
+
}
|
|
663
|
+
|
|
623
664
|
getSession(sessionId) {
|
|
624
665
|
const session = this.sessions.get(sessionId);
|
|
625
666
|
if (!session) {
|
|
@@ -674,6 +715,28 @@ export class FirefoxBidiSessionManager {
|
|
|
674
715
|
};
|
|
675
716
|
}
|
|
676
717
|
|
|
718
|
+
async closeTarget(targetId) {
|
|
719
|
+
await this.ensureConnected();
|
|
720
|
+
await this.send("browsingContext.close", {
|
|
721
|
+
context: targetId,
|
|
722
|
+
});
|
|
723
|
+
|
|
724
|
+
const detachedSessions = Array.from(this.sessions.values())
|
|
725
|
+
.filter((session) => session.target.targetId === targetId)
|
|
726
|
+
.map((session) => {
|
|
727
|
+
session.closed = true;
|
|
728
|
+
this.sessions.delete(session.id);
|
|
729
|
+
return { sessionId: session.id };
|
|
730
|
+
});
|
|
731
|
+
|
|
732
|
+
return {
|
|
733
|
+
browserFamily: "firefox",
|
|
734
|
+
closed: true,
|
|
735
|
+
targetId,
|
|
736
|
+
detachedSessions,
|
|
737
|
+
};
|
|
738
|
+
}
|
|
739
|
+
|
|
677
740
|
async evaluate(sessionId, expression, options = {}) {
|
|
678
741
|
const session = this.getSession(sessionId);
|
|
679
742
|
const result = await this.evaluateInContext(session, expression, options);
|
|
@@ -784,6 +847,14 @@ export class FirefoxBidiSessionManager {
|
|
|
784
847
|
};
|
|
785
848
|
}
|
|
786
849
|
|
|
850
|
+
async waitFor(sessionId, options = {}) {
|
|
851
|
+
return waitForPageCondition({
|
|
852
|
+
getPageState: () => this.getPageState(sessionId),
|
|
853
|
+
inspectElement: (selector) => this.inspectElement(sessionId, selector),
|
|
854
|
+
options,
|
|
855
|
+
});
|
|
856
|
+
}
|
|
857
|
+
|
|
787
858
|
async navigate(sessionId, url, options = {}) {
|
|
788
859
|
const session = this.getSession(sessionId);
|
|
789
860
|
const waitUntil = normalizeWaitUntil(options.waitUntil);
|
package/src/index.mjs
CHANGED
|
@@ -14,14 +14,17 @@ export {
|
|
|
14
14
|
DEFAULT_CDP_BASE_URL,
|
|
15
15
|
DEFAULT_EVENT_BUFFER_SIZE,
|
|
16
16
|
DEFAULT_FIREFOX_BIDI_WS_URL,
|
|
17
|
+
DEFAULT_LOG_LEVEL,
|
|
17
18
|
DEFAULT_PROTOCOL_VERSION,
|
|
18
19
|
isLoopbackHost,
|
|
19
20
|
isLoopbackOrigin,
|
|
20
21
|
isTruthyFlag,
|
|
21
22
|
loadConfig,
|
|
23
|
+
loadLoggingConfig,
|
|
22
24
|
normalizeBaseUrl,
|
|
23
25
|
normalizeWebSocketUrl,
|
|
24
26
|
parseBrowserFamily,
|
|
27
|
+
parseLogLevel,
|
|
25
28
|
parsePositiveInteger,
|
|
26
29
|
} from "./config.mjs";
|
|
27
30
|
export { collectDoctorReport, renderDoctorReport } from "./doctor.mjs";
|
package/src/logger.mjs
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import process from "node:process";
|
|
2
|
+
|
|
3
|
+
import { PACKAGE_NAME } from "./package-info.mjs";
|
|
4
|
+
|
|
5
|
+
export const LOG_LEVELS = {
|
|
6
|
+
error: 0,
|
|
7
|
+
warn: 1,
|
|
8
|
+
info: 2,
|
|
9
|
+
debug: 3,
|
|
10
|
+
};
|
|
11
|
+
|
|
12
|
+
function normalizeMessage(message) {
|
|
13
|
+
if (message instanceof Error) {
|
|
14
|
+
return message.message;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
return String(message);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function createLogger({
|
|
21
|
+
level = "error",
|
|
22
|
+
output = process.stderr,
|
|
23
|
+
name = PACKAGE_NAME,
|
|
24
|
+
} = {}) {
|
|
25
|
+
const threshold = LOG_LEVELS[level] ?? LOG_LEVELS.error;
|
|
26
|
+
|
|
27
|
+
return {
|
|
28
|
+
level,
|
|
29
|
+
enabled(messageLevel) {
|
|
30
|
+
return (LOG_LEVELS[messageLevel] ?? -1) <= threshold;
|
|
31
|
+
},
|
|
32
|
+
log(messageLevel, message, options = {}) {
|
|
33
|
+
if (!options.force && !this.enabled(messageLevel)) {
|
|
34
|
+
return false;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
output.write(`[${name}] ${messageLevel}: ${normalizeMessage(message)}\n`);
|
|
38
|
+
return true;
|
|
39
|
+
},
|
|
40
|
+
error(message, options) {
|
|
41
|
+
return this.log("error", message, options);
|
|
42
|
+
},
|
|
43
|
+
warn(message, options) {
|
|
44
|
+
return this.log("warn", message, options);
|
|
45
|
+
},
|
|
46
|
+
info(message, options) {
|
|
47
|
+
return this.log("info", message, options);
|
|
48
|
+
},
|
|
49
|
+
debug(message, options) {
|
|
50
|
+
return this.log("debug", message, options);
|
|
51
|
+
},
|
|
52
|
+
};
|
|
53
|
+
}
|
package/src/mcp-server.mjs
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { encodeMessage, MessageBuffer } from "./json-rpc-stdio.mjs";
|
|
2
|
+
import { createLogger } from "./logger.mjs";
|
|
2
3
|
import { PACKAGE_NAME, PACKAGE_VERSION } from "./package-info.mjs";
|
|
3
4
|
|
|
4
5
|
const SERVER_NAME = PACKAGE_NAME;
|
|
5
6
|
const SERVER_VERSION = PACKAGE_VERSION;
|
|
6
|
-
const DEBUG_STDIO_ENABLED = process.env.MCP_BROWSER_DEBUG_STDIO === "1";
|
|
7
7
|
|
|
8
8
|
function formatChunkPreview(chunk, limit = 160) {
|
|
9
9
|
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
@@ -173,6 +173,68 @@ function waitUntilProperty() {
|
|
|
173
173
|
};
|
|
174
174
|
}
|
|
175
175
|
|
|
176
|
+
function waitForInputSchema() {
|
|
177
|
+
return {
|
|
178
|
+
type: "object",
|
|
179
|
+
properties: {
|
|
180
|
+
sessionId: {
|
|
181
|
+
type: "string",
|
|
182
|
+
},
|
|
183
|
+
selector: {
|
|
184
|
+
type: "string",
|
|
185
|
+
},
|
|
186
|
+
state: {
|
|
187
|
+
type: "string",
|
|
188
|
+
enum: ["present", "visible", "hidden"],
|
|
189
|
+
},
|
|
190
|
+
url: {
|
|
191
|
+
type: "string",
|
|
192
|
+
},
|
|
193
|
+
urlIncludes: {
|
|
194
|
+
type: "string",
|
|
195
|
+
},
|
|
196
|
+
readyState: {
|
|
197
|
+
type: "string",
|
|
198
|
+
enum: ["interactive", "complete"],
|
|
199
|
+
},
|
|
200
|
+
timeoutMs: {
|
|
201
|
+
type: "integer",
|
|
202
|
+
minimum: 1,
|
|
203
|
+
},
|
|
204
|
+
pollIntervalMs: {
|
|
205
|
+
type: "integer",
|
|
206
|
+
minimum: 1,
|
|
207
|
+
},
|
|
208
|
+
},
|
|
209
|
+
required: ["sessionId"],
|
|
210
|
+
additionalProperties: false,
|
|
211
|
+
};
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
function newTabInputSchema(browserFamily) {
|
|
215
|
+
const properties = {
|
|
216
|
+
url: {
|
|
217
|
+
type: "string",
|
|
218
|
+
},
|
|
219
|
+
};
|
|
220
|
+
const required = [];
|
|
221
|
+
|
|
222
|
+
if (browserFamily === "auto") {
|
|
223
|
+
properties.browserFamily = {
|
|
224
|
+
type: "string",
|
|
225
|
+
enum: ["chromium", "firefox"],
|
|
226
|
+
};
|
|
227
|
+
required.push("browserFamily");
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
return {
|
|
231
|
+
type: "object",
|
|
232
|
+
properties,
|
|
233
|
+
required,
|
|
234
|
+
additionalProperties: false,
|
|
235
|
+
};
|
|
236
|
+
}
|
|
237
|
+
|
|
176
238
|
export class McpBrowserDevToolsServer {
|
|
177
239
|
constructor({
|
|
178
240
|
config,
|
|
@@ -180,12 +242,18 @@ export class McpBrowserDevToolsServer {
|
|
|
180
242
|
input = process.stdin,
|
|
181
243
|
output = process.stdout,
|
|
182
244
|
errorOutput = process.stderr,
|
|
245
|
+
logger = createLogger({
|
|
246
|
+
level: config.logLevel,
|
|
247
|
+
output: errorOutput,
|
|
248
|
+
name: SERVER_NAME,
|
|
249
|
+
}),
|
|
183
250
|
}) {
|
|
184
251
|
this.config = config;
|
|
185
252
|
this.browserAdapter = browserAdapter;
|
|
186
253
|
this.input = input;
|
|
187
254
|
this.output = output;
|
|
188
255
|
this.errorOutput = errorOutput;
|
|
256
|
+
this.logger = logger;
|
|
189
257
|
this.messageBuffer = new MessageBuffer();
|
|
190
258
|
this.tools = this.createTools();
|
|
191
259
|
}
|
|
@@ -236,6 +304,43 @@ export class McpBrowserDevToolsServer {
|
|
|
236
304
|
}),
|
|
237
305
|
},
|
|
238
306
|
],
|
|
307
|
+
[
|
|
308
|
+
"new_tab",
|
|
309
|
+
{
|
|
310
|
+
definition: {
|
|
311
|
+
name: "new_tab",
|
|
312
|
+
description:
|
|
313
|
+
"Create a new browser tab and return the resulting target metadata.",
|
|
314
|
+
inputSchema: newTabInputSchema(this.config.browserFamily),
|
|
315
|
+
},
|
|
316
|
+
handler: async (args) =>
|
|
317
|
+
this.browserAdapter.createTab(args.url, {
|
|
318
|
+
browserFamily: args.browserFamily,
|
|
319
|
+
}),
|
|
320
|
+
},
|
|
321
|
+
],
|
|
322
|
+
[
|
|
323
|
+
"close_tab",
|
|
324
|
+
{
|
|
325
|
+
definition: {
|
|
326
|
+
name: "close_tab",
|
|
327
|
+
description:
|
|
328
|
+
"Close a browser tab by target id. Any attached session for that tab will disconnect.",
|
|
329
|
+
inputSchema: {
|
|
330
|
+
type: "object",
|
|
331
|
+
properties: {
|
|
332
|
+
targetId: {
|
|
333
|
+
type: "string",
|
|
334
|
+
},
|
|
335
|
+
},
|
|
336
|
+
required: ["targetId"],
|
|
337
|
+
additionalProperties: false,
|
|
338
|
+
},
|
|
339
|
+
},
|
|
340
|
+
handler: async (args) =>
|
|
341
|
+
this.browserAdapter.closeTarget(args.targetId),
|
|
342
|
+
},
|
|
343
|
+
],
|
|
239
344
|
[
|
|
240
345
|
"attach_tab",
|
|
241
346
|
{
|
|
@@ -294,6 +399,43 @@ export class McpBrowserDevToolsServer {
|
|
|
294
399
|
this.browserAdapter.getPageState(args.sessionId),
|
|
295
400
|
},
|
|
296
401
|
],
|
|
402
|
+
[
|
|
403
|
+
"wait_for",
|
|
404
|
+
{
|
|
405
|
+
definition: {
|
|
406
|
+
name: "wait_for",
|
|
407
|
+
description:
|
|
408
|
+
"Wait for page state such as selector visibility, URL, or ready state on an attached session.",
|
|
409
|
+
inputSchema: waitForInputSchema(),
|
|
410
|
+
},
|
|
411
|
+
handler: async (args) => {
|
|
412
|
+
if (
|
|
413
|
+
!args.selector &&
|
|
414
|
+
!args.url &&
|
|
415
|
+
!args.urlIncludes &&
|
|
416
|
+
!args.readyState
|
|
417
|
+
) {
|
|
418
|
+
throw new Error(
|
|
419
|
+
"wait_for requires at least one of selector, url, urlIncludes, or readyState",
|
|
420
|
+
);
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
if (!args.selector && args.state !== undefined) {
|
|
424
|
+
throw new Error("wait_for state requires selector");
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
return this.browserAdapter.waitFor(args.sessionId, {
|
|
428
|
+
selector: args.selector,
|
|
429
|
+
state: args.state,
|
|
430
|
+
url: args.url,
|
|
431
|
+
urlIncludes: args.urlIncludes,
|
|
432
|
+
readyState: args.readyState,
|
|
433
|
+
timeoutMs: args.timeoutMs,
|
|
434
|
+
pollIntervalMs: args.pollIntervalMs,
|
|
435
|
+
});
|
|
436
|
+
},
|
|
437
|
+
},
|
|
438
|
+
],
|
|
297
439
|
[
|
|
298
440
|
"navigate",
|
|
299
441
|
{
|
|
@@ -748,9 +890,11 @@ export class McpBrowserDevToolsServer {
|
|
|
748
890
|
|
|
749
891
|
this.input.on("data", (chunk) => {
|
|
750
892
|
sawInput = true;
|
|
751
|
-
if (
|
|
752
|
-
this.log(
|
|
893
|
+
if (this.config.debugStdio) {
|
|
894
|
+
this.logger.log(
|
|
895
|
+
"debug",
|
|
753
896
|
`stdin chunk bytes=${chunk.length} preview="${formatChunkPreview(chunk)}"`,
|
|
897
|
+
{ force: true },
|
|
754
898
|
);
|
|
755
899
|
}
|
|
756
900
|
|
|
@@ -758,7 +902,7 @@ export class McpBrowserDevToolsServer {
|
|
|
758
902
|
try {
|
|
759
903
|
messages = this.messageBuffer.push(chunk);
|
|
760
904
|
} catch (error) {
|
|
761
|
-
this.
|
|
905
|
+
this.logger.error(`failed to parse incoming message: ${error.message}`);
|
|
762
906
|
return;
|
|
763
907
|
}
|
|
764
908
|
|
|
@@ -767,13 +911,17 @@ export class McpBrowserDevToolsServer {
|
|
|
767
911
|
}
|
|
768
912
|
});
|
|
769
913
|
|
|
770
|
-
if (
|
|
914
|
+
if (this.config.debugStdio) {
|
|
771
915
|
this.input.on("end", () => {
|
|
772
|
-
this.log(`stdin ended after_input=${sawInput}
|
|
916
|
+
this.logger.log("debug", `stdin ended after_input=${sawInput}`, {
|
|
917
|
+
force: true,
|
|
918
|
+
});
|
|
773
919
|
});
|
|
774
920
|
|
|
775
921
|
this.input.on("close", () => {
|
|
776
|
-
this.log(`stdin closed after_input=${sawInput}
|
|
922
|
+
this.logger.log("debug", `stdin closed after_input=${sawInput}`, {
|
|
923
|
+
force: true,
|
|
924
|
+
});
|
|
777
925
|
});
|
|
778
926
|
}
|
|
779
927
|
|
|
@@ -781,15 +929,11 @@ export class McpBrowserDevToolsServer {
|
|
|
781
929
|
this.input.resume();
|
|
782
930
|
}
|
|
783
931
|
|
|
784
|
-
this.
|
|
932
|
+
this.logger.info(
|
|
785
933
|
`listening on stdio for MCP messages; browser=${this.config.browserFamily}`,
|
|
786
934
|
);
|
|
787
935
|
}
|
|
788
936
|
|
|
789
|
-
log(message) {
|
|
790
|
-
this.errorOutput.write(`[${SERVER_NAME}] ${message}\n`);
|
|
791
|
-
}
|
|
792
|
-
|
|
793
937
|
async dispatch(message) {
|
|
794
938
|
const response = await this.handleRequest(message);
|
|
795
939
|
if (!response) {
|
package/src/tcp-relay.mjs
CHANGED
|
@@ -3,6 +3,8 @@ import os from "node:os";
|
|
|
3
3
|
import process from "node:process";
|
|
4
4
|
|
|
5
5
|
import { isLoopbackHost, isTruthyFlag } from "./config.mjs";
|
|
6
|
+
import { createLogger } from "./logger.mjs";
|
|
7
|
+
import { PACKAGE_NAME } from "./package-info.mjs";
|
|
6
8
|
|
|
7
9
|
export const DEFAULT_RELAY_LISTEN_HOST = "127.0.0.1";
|
|
8
10
|
export const DEFAULT_RELAY_LISTEN_PORT = 9223;
|
|
@@ -129,6 +131,10 @@ export async function startTcpRelay({
|
|
|
129
131
|
targetHost,
|
|
130
132
|
targetPort,
|
|
131
133
|
errorOutput = process.stderr,
|
|
134
|
+
logger = createLogger({
|
|
135
|
+
output: errorOutput,
|
|
136
|
+
name: PACKAGE_NAME,
|
|
137
|
+
}),
|
|
132
138
|
} = {}) {
|
|
133
139
|
const openSockets = new Set();
|
|
134
140
|
|
|
@@ -154,7 +160,7 @@ export async function startTcpRelay({
|
|
|
154
160
|
});
|
|
155
161
|
|
|
156
162
|
upstreamSocket.on("error", (error) => {
|
|
157
|
-
|
|
163
|
+
logger.error(`relay target connection failed: ${error.message}`);
|
|
158
164
|
clientSocket.destroy();
|
|
159
165
|
});
|
|
160
166
|
|
package/src/wait-for.mjs
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
function sleep(ms) {
|
|
2
|
+
return new Promise((resolve) => {
|
|
3
|
+
setTimeout(resolve, ms);
|
|
4
|
+
});
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
const READY_STATE_ORDER = {
|
|
8
|
+
loading: 0,
|
|
9
|
+
interactive: 1,
|
|
10
|
+
complete: 2,
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
function normalizeOptionalString(value) {
|
|
14
|
+
return typeof value === "string" && value.trim() ? value.trim() : null;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function normalizeSelectorState(value) {
|
|
18
|
+
if (value === "present" || value === "visible" || value === "hidden") {
|
|
19
|
+
return value;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
return "visible";
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function normalizeReadyState(value) {
|
|
26
|
+
if (value === "interactive" || value === "complete") {
|
|
27
|
+
return value;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
return null;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function normalizeInteger(value, fallback) {
|
|
34
|
+
return Number.isInteger(value) && value > 0 ? value : fallback;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function readyStateMatches(current, expected) {
|
|
38
|
+
const currentRank = READY_STATE_ORDER[current] ?? -1;
|
|
39
|
+
const expectedRank = READY_STATE_ORDER[expected] ?? -1;
|
|
40
|
+
return currentRank >= expectedRank;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function selectorMatches(result, state) {
|
|
44
|
+
if (state === "hidden") {
|
|
45
|
+
return !result?.found || result.node?.visible === false;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
if (!result?.found) {
|
|
49
|
+
return false;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
if (state === "present") {
|
|
53
|
+
return true;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
return result.node?.visible === true;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function buildTimeoutMessage(options, lastPage, lastElement) {
|
|
60
|
+
const conditions = [];
|
|
61
|
+
if (options.selector) {
|
|
62
|
+
conditions.push(
|
|
63
|
+
`selector ${JSON.stringify(options.selector)} to become ${options.state}`,
|
|
64
|
+
);
|
|
65
|
+
}
|
|
66
|
+
if (options.url) {
|
|
67
|
+
conditions.push(`url to equal ${JSON.stringify(options.url)}`);
|
|
68
|
+
}
|
|
69
|
+
if (options.urlIncludes) {
|
|
70
|
+
conditions.push(`url to include ${JSON.stringify(options.urlIncludes)}`);
|
|
71
|
+
}
|
|
72
|
+
if (options.readyState) {
|
|
73
|
+
conditions.push(`readyState to reach ${options.readyState}`);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const observed = [];
|
|
77
|
+
if (lastPage?.url) {
|
|
78
|
+
observed.push(`last url=${JSON.stringify(lastPage.url)}`);
|
|
79
|
+
}
|
|
80
|
+
if (lastPage?.readyState) {
|
|
81
|
+
observed.push(`last readyState=${lastPage.readyState}`);
|
|
82
|
+
}
|
|
83
|
+
if (options.selector && lastElement) {
|
|
84
|
+
observed.push(
|
|
85
|
+
`last selector found=${Boolean(lastElement.found)} visible=${lastElement.node?.visible === true}`,
|
|
86
|
+
);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
return `Timed out after ${options.timeoutMs}ms waiting for ${conditions.join(
|
|
90
|
+
", ",
|
|
91
|
+
)}${observed.length > 0 ? `; ${observed.join("; ")}` : ""}`;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export function normalizeWaitForOptions(options = {}) {
|
|
95
|
+
const normalized = {
|
|
96
|
+
selector: normalizeOptionalString(options.selector),
|
|
97
|
+
state: normalizeSelectorState(options.state),
|
|
98
|
+
url: normalizeOptionalString(options.url),
|
|
99
|
+
urlIncludes: normalizeOptionalString(options.urlIncludes),
|
|
100
|
+
readyState: normalizeReadyState(options.readyState),
|
|
101
|
+
timeoutMs: normalizeInteger(options.timeoutMs, 10_000),
|
|
102
|
+
pollIntervalMs: normalizeInteger(options.pollIntervalMs, 100),
|
|
103
|
+
};
|
|
104
|
+
|
|
105
|
+
if (
|
|
106
|
+
!normalized.selector &&
|
|
107
|
+
!normalized.url &&
|
|
108
|
+
!normalized.urlIncludes &&
|
|
109
|
+
!normalized.readyState
|
|
110
|
+
) {
|
|
111
|
+
throw new Error(
|
|
112
|
+
"wait_for requires at least one of selector, url, urlIncludes, or readyState",
|
|
113
|
+
);
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
if (!normalized.selector && options.state !== undefined) {
|
|
117
|
+
throw new Error("wait_for state requires selector");
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
return normalized;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
export async function waitForPageCondition({
|
|
124
|
+
getPageState,
|
|
125
|
+
inspectElement,
|
|
126
|
+
options,
|
|
127
|
+
}) {
|
|
128
|
+
const normalized = normalizeWaitForOptions(options);
|
|
129
|
+
const startedAt = Date.now();
|
|
130
|
+
let attempts = 0;
|
|
131
|
+
let lastPage = null;
|
|
132
|
+
let lastElement = null;
|
|
133
|
+
|
|
134
|
+
while (true) {
|
|
135
|
+
attempts += 1;
|
|
136
|
+
|
|
137
|
+
if (normalized.url || normalized.urlIncludes || normalized.readyState) {
|
|
138
|
+
lastPage = await getPageState();
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
if (normalized.selector) {
|
|
142
|
+
lastElement = await inspectElement(normalized.selector);
|
|
143
|
+
if (lastElement?.error) {
|
|
144
|
+
throw new Error(lastElement.error);
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
const matchedSelector = normalized.selector
|
|
149
|
+
? selectorMatches(lastElement, normalized.state)
|
|
150
|
+
: true;
|
|
151
|
+
const matchedUrl = normalized.url ? lastPage?.url === normalized.url : true;
|
|
152
|
+
const matchedUrlIncludes = normalized.urlIncludes
|
|
153
|
+
? lastPage?.url?.includes(normalized.urlIncludes) === true
|
|
154
|
+
: true;
|
|
155
|
+
const matchedReadyState = normalized.readyState
|
|
156
|
+
? readyStateMatches(lastPage?.readyState, normalized.readyState)
|
|
157
|
+
: true;
|
|
158
|
+
|
|
159
|
+
if (
|
|
160
|
+
matchedSelector &&
|
|
161
|
+
matchedUrl &&
|
|
162
|
+
matchedUrlIncludes &&
|
|
163
|
+
matchedReadyState
|
|
164
|
+
) {
|
|
165
|
+
const browserFamily =
|
|
166
|
+
lastPage?.browserFamily ?? lastElement?.browserFamily ?? null;
|
|
167
|
+
|
|
168
|
+
return {
|
|
169
|
+
browserFamily,
|
|
170
|
+
matched: true,
|
|
171
|
+
waitedMs: Date.now() - startedAt,
|
|
172
|
+
attempts,
|
|
173
|
+
timeoutMs: normalized.timeoutMs,
|
|
174
|
+
pollIntervalMs: normalized.pollIntervalMs,
|
|
175
|
+
condition: {
|
|
176
|
+
selector: normalized.selector,
|
|
177
|
+
state: normalized.selector ? normalized.state : null,
|
|
178
|
+
url: normalized.url,
|
|
179
|
+
urlIncludes: normalized.urlIncludes,
|
|
180
|
+
readyState: normalized.readyState,
|
|
181
|
+
},
|
|
182
|
+
page: lastPage,
|
|
183
|
+
element: normalized.selector
|
|
184
|
+
? {
|
|
185
|
+
selector: normalized.selector,
|
|
186
|
+
found: Boolean(lastElement?.found),
|
|
187
|
+
locator:
|
|
188
|
+
lastElement?.locator ?? lastElement?.node?.locator ?? null,
|
|
189
|
+
node: lastElement?.found ? lastElement.node : null,
|
|
190
|
+
}
|
|
191
|
+
: null,
|
|
192
|
+
};
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
if (Date.now() - startedAt >= normalized.timeoutMs) {
|
|
196
|
+
throw new Error(buildTimeoutMessage(normalized, lastPage, lastElement));
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
await sleep(normalized.pollIntervalMs);
|
|
200
|
+
}
|
|
201
|
+
}
|