mcp-browser-dev-tools 0.0.1 → 0.0.2

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.
@@ -1,7 +1,10 @@
1
1
  import {
2
+ exportHarLikeSummary,
2
3
  filterConsoleMessages,
3
4
  summarizeNetworkRequests,
4
5
  } from "./session-events.mjs";
6
+ import { DEFAULT_CDP_BASE_URL } from "./config.mjs";
7
+ import { waitForPageCondition } from "./wait-for.mjs";
5
8
  import { buildPageContextExpression } from "./page-context.mjs";
6
9
 
7
10
  function toErrorMessage(error) {
@@ -19,10 +22,53 @@ function normalizeTarget(target) {
19
22
  };
20
23
  }
21
24
 
25
+ function inferTitle(url) {
26
+ if (!url) {
27
+ return "New Tab";
28
+ }
29
+
30
+ try {
31
+ const parsed = new URL(url);
32
+ return parsed.hostname || url;
33
+ } catch {
34
+ return url;
35
+ }
36
+ }
37
+
22
38
  function cdpBrowserFamily(config) {
23
39
  return config.browserFamily === "edge" ? "edge" : "chromium";
24
40
  }
25
41
 
42
+ function buildDiscoveryBaseUrls(configuredBaseUrl) {
43
+ const configured = new URL(configuredBaseUrl);
44
+ const candidatePorts = [
45
+ configured.port || "9222",
46
+ "9223",
47
+ "9224",
48
+ "9225",
49
+ "9226",
50
+ ];
51
+ const seen = new Set();
52
+ const candidates = [];
53
+
54
+ for (const port of candidatePorts) {
55
+ const candidate = new URL(configured.toString());
56
+ candidate.port = port;
57
+ candidate.pathname = "/";
58
+ candidate.search = "";
59
+ candidate.hash = "";
60
+ const normalized = candidate.toString().replace(/\/+$/, "");
61
+ if (seen.has(normalized)) {
62
+ continue;
63
+ }
64
+
65
+ seen.add(normalized);
66
+ candidates.push(normalized);
67
+ }
68
+
69
+ return candidates;
70
+ }
71
+
26
72
  function summarizeRemoteObject(object) {
27
73
  if (!object) {
28
74
  return null;
@@ -655,6 +701,82 @@ export class CdpSession {
655
701
  return summarizeNetworkRequests(this.bufferedEvents, limit);
656
702
  }
657
703
 
704
+ async getCookies() {
705
+ return this.runPageAction({
706
+ action: "cookie_snapshot",
707
+ });
708
+ }
709
+
710
+ async getStorage() {
711
+ return this.runPageAction({
712
+ action: "storage_snapshot",
713
+ });
714
+ }
715
+
716
+ async captureDebugReport(options = {}) {
717
+ const consoleLimit =
718
+ Number.isInteger(options.consoleLimit) && options.consoleLimit > 0
719
+ ? options.consoleLimit
720
+ : 20;
721
+ const networkLimit =
722
+ Number.isInteger(options.networkLimit) && options.networkLimit > 0
723
+ ? options.networkLimit
724
+ : 20;
725
+ const includeScreenshot = options.includeScreenshot !== false;
726
+ const screenshotFormat = options.screenshotFormat ?? "png";
727
+ const snapshot = await this.runPageAction({
728
+ action: "debug_report",
729
+ });
730
+
731
+ return {
732
+ browserFamily: cdpBrowserFamily(this.config),
733
+ capturedAt: new Date().toISOString(),
734
+ page: {
735
+ ...(await this.getPageState()),
736
+ },
737
+ cookies: snapshot.cookies,
738
+ storage: snapshot.storage,
739
+ console: this.getConsoleMessages(consoleLimit),
740
+ network: this.getNetworkRequests(networkLimit),
741
+ screenshot: includeScreenshot
742
+ ? await this.takeScreenshot(screenshotFormat)
743
+ : null,
744
+ };
745
+ }
746
+
747
+ getHar(options = {}) {
748
+ return exportHarLikeSummary(this.bufferedEvents, {
749
+ limit: options.limit ?? 50,
750
+ page: {
751
+ title: this.target.title,
752
+ url: this.target.url,
753
+ },
754
+ });
755
+ }
756
+
757
+ async captureSessionSnapshot() {
758
+ return {
759
+ browserFamily: cdpBrowserFamily(this.config),
760
+ capturedAt: new Date().toISOString(),
761
+ page: await this.getPageState(),
762
+ ...(await this.getCookies()),
763
+ ...(await this.getStorage()),
764
+ };
765
+ }
766
+
767
+ async restoreSessionSnapshot(snapshot, options = {}) {
768
+ const result = await this.runPageAction({
769
+ action: "restore_snapshot",
770
+ snapshot,
771
+ clearStorage: options.clearStorage === true,
772
+ });
773
+
774
+ return {
775
+ ...result,
776
+ page: await this.getPageState(),
777
+ };
778
+ }
779
+
658
780
  async inspectElement(selector) {
659
781
  return this.runPageAction({
660
782
  action: "inspect",
@@ -883,20 +1005,222 @@ export class CdpSessionManager {
883
1005
  constructor(config) {
884
1006
  this.config = config;
885
1007
  this.sessions = new Map();
1008
+ this.resolvedBaseUrl = null;
1009
+ this.lastAttemptedBaseUrl = null;
1010
+ this.lastKnownBaseUrl = null;
1011
+ this.failedBaseUrlCooldownMs = 5_000;
1012
+ this.failedBaseUrlDeadlines = new Map();
1013
+ this.fetchTimeoutMs = 1_000;
886
1014
  }
887
1015
 
888
- async fetchJson(pathname) {
889
- const url = new URL(pathname, `${this.config.cdpBaseUrl}/`);
890
- const response = await fetch(url);
1016
+ shouldAutoDiscoverBaseUrl() {
1017
+ return this.config.cdpBaseUrl === DEFAULT_CDP_BASE_URL;
1018
+ }
1019
+
1020
+ markBaseUrlFailed(baseUrl) {
1021
+ this.failedBaseUrlDeadlines.set(
1022
+ baseUrl,
1023
+ Date.now() + this.failedBaseUrlCooldownMs,
1024
+ );
1025
+ }
1026
+
1027
+ invalidateBaseUrl(baseUrl) {
1028
+ this.markBaseUrlFailed(baseUrl);
1029
+
1030
+ if (this.resolvedBaseUrl === baseUrl) {
1031
+ this.resolvedBaseUrl = null;
1032
+ }
1033
+
1034
+ if (this.lastKnownBaseUrl === baseUrl) {
1035
+ this.lastKnownBaseUrl = null;
1036
+ }
1037
+ }
1038
+
1039
+ pruneFailedBaseUrls(now = Date.now()) {
1040
+ for (const [baseUrl, deadline] of this.failedBaseUrlDeadlines.entries()) {
1041
+ if (deadline <= now) {
1042
+ this.failedBaseUrlDeadlines.delete(baseUrl);
1043
+ }
1044
+ }
1045
+ }
1046
+
1047
+ async fetchJsonAt(baseUrl, pathname) {
1048
+ this.lastAttemptedBaseUrl = baseUrl;
1049
+ const url = new URL(pathname, `${baseUrl}/`);
1050
+ const response = await fetch(url, {
1051
+ signal: AbortSignal.timeout(this.fetchTimeoutMs),
1052
+ });
891
1053
  return parseJson(response);
892
1054
  }
893
1055
 
1056
+ async resolveBaseUrl(excludedBaseUrls = new Set()) {
1057
+ if (this.resolvedBaseUrl) {
1058
+ return this.resolvedBaseUrl;
1059
+ }
1060
+
1061
+ const candidates = this.shouldAutoDiscoverBaseUrl()
1062
+ ? buildDiscoveryBaseUrls(this.config.cdpBaseUrl)
1063
+ : [this.config.cdpBaseUrl];
1064
+ this.pruneFailedBaseUrls();
1065
+ const preferredCandidates = candidates.filter(
1066
+ (candidate) =>
1067
+ !excludedBaseUrls.has(candidate) &&
1068
+ !this.failedBaseUrlDeadlines.has(candidate),
1069
+ );
1070
+ const probeCandidates =
1071
+ preferredCandidates.length > 0
1072
+ ? preferredCandidates
1073
+ : candidates.filter((candidate) => !excludedBaseUrls.has(candidate));
1074
+ let lastError = null;
1075
+
1076
+ for (const candidate of probeCandidates) {
1077
+ try {
1078
+ const info = await this.fetchJsonAt(candidate, "/json/version");
1079
+ if (!info.webSocketDebuggerUrl) {
1080
+ this.invalidateBaseUrl(candidate);
1081
+ continue;
1082
+ }
1083
+
1084
+ this.failedBaseUrlDeadlines.delete(candidate);
1085
+ this.resolvedBaseUrl = candidate;
1086
+ this.lastKnownBaseUrl = candidate;
1087
+ return candidate;
1088
+ } catch (error) {
1089
+ this.invalidateBaseUrl(candidate);
1090
+ lastError = error;
1091
+ }
1092
+ }
1093
+
1094
+ throw lastError ?? new Error("Unable to resolve a CDP browser endpoint");
1095
+ }
1096
+
1097
+ async fetchJson(pathname) {
1098
+ const baseUrl = await this.resolveBaseUrl();
1099
+
1100
+ try {
1101
+ return await this.fetchJsonAt(baseUrl, pathname);
1102
+ } catch (error) {
1103
+ if (!this.shouldAutoDiscoverBaseUrl() || !this.resolvedBaseUrl) {
1104
+ throw error;
1105
+ }
1106
+
1107
+ this.invalidateBaseUrl(baseUrl);
1108
+ const rediscoveredBaseUrl = await this.resolveBaseUrl(new Set([baseUrl]));
1109
+ try {
1110
+ return await this.fetchJsonAt(rediscoveredBaseUrl, pathname);
1111
+ } catch (rediscoveredError) {
1112
+ this.invalidateBaseUrl(rediscoveredBaseUrl);
1113
+ throw rediscoveredError;
1114
+ }
1115
+ }
1116
+ }
1117
+
1118
+ async sendBrowserCommand(method, params = {}) {
1119
+ const info = await this.fetchJson("/json/version");
1120
+ if (!info.webSocketDebuggerUrl) {
1121
+ throw new Error("Browser endpoint does not expose a debugger websocket");
1122
+ }
1123
+
1124
+ const websocket = new WebSocket(info.webSocketDebuggerUrl);
1125
+
1126
+ return new Promise((resolve, reject) => {
1127
+ let settled = false;
1128
+
1129
+ const cleanup = () => {
1130
+ websocket.removeEventListener("open", handleOpen);
1131
+ websocket.removeEventListener("message", handleMessage);
1132
+ websocket.removeEventListener("error", handleError);
1133
+ websocket.removeEventListener("close", handleClose);
1134
+ };
1135
+
1136
+ const finish = (callback) => {
1137
+ if (settled) {
1138
+ return;
1139
+ }
1140
+
1141
+ settled = true;
1142
+ cleanup();
1143
+ callback();
1144
+
1145
+ if (websocket.readyState < WebSocket.CLOSING) {
1146
+ websocket.close();
1147
+ }
1148
+ };
1149
+
1150
+ const handleOpen = () => {
1151
+ try {
1152
+ websocket.send(
1153
+ JSON.stringify({
1154
+ id: 1,
1155
+ method,
1156
+ params,
1157
+ }),
1158
+ );
1159
+ } catch (error) {
1160
+ finish(() => reject(error));
1161
+ }
1162
+ };
1163
+
1164
+ const handleMessage = async (event) => {
1165
+ const raw = await readWebSocketData(event.data);
1166
+ const message = JSON.parse(raw);
1167
+ if (message.id !== 1) {
1168
+ return;
1169
+ }
1170
+
1171
+ if (message.error) {
1172
+ finish(() =>
1173
+ reject(
1174
+ new Error(
1175
+ `${message.error.message} (code ${message.error.code})`,
1176
+ ),
1177
+ ),
1178
+ );
1179
+ return;
1180
+ }
1181
+
1182
+ finish(() => resolve(message.result ?? {}));
1183
+ };
1184
+
1185
+ const handleError = () => {
1186
+ finish(() =>
1187
+ reject(
1188
+ new Error(`Failed to connect to ${info.webSocketDebuggerUrl}`),
1189
+ ),
1190
+ );
1191
+ };
1192
+
1193
+ const handleClose = () => {
1194
+ finish(() => reject(new Error("Browser debugger websocket closed")));
1195
+ };
1196
+
1197
+ websocket.addEventListener("open", handleOpen, { once: true });
1198
+ websocket.addEventListener("message", handleMessage);
1199
+ websocket.addEventListener("error", handleError, { once: true });
1200
+ websocket.addEventListener("close", handleClose, { once: true });
1201
+ }).catch((error) => {
1202
+ if (this.shouldAutoDiscoverBaseUrl() && this.resolvedBaseUrl) {
1203
+ this.invalidateBaseUrl(this.resolvedBaseUrl);
1204
+ }
1205
+
1206
+ throw error;
1207
+ });
1208
+ }
1209
+
894
1210
  async getBrowserStatus() {
895
1211
  try {
896
1212
  const info = await this.fetchJson("/json/version");
897
1213
  return {
898
1214
  available: true,
899
- endpoint: this.config.cdpBaseUrl,
1215
+ endpoint:
1216
+ this.resolvedBaseUrl ??
1217
+ this.lastKnownBaseUrl ??
1218
+ this.config.cdpBaseUrl,
1219
+ attemptedEndpoint:
1220
+ this.lastAttemptedBaseUrl ??
1221
+ this.resolvedBaseUrl ??
1222
+ this.lastKnownBaseUrl ??
1223
+ this.config.cdpBaseUrl,
900
1224
  sessionCount: this.sessions.size,
901
1225
  browser: info.Browser,
902
1226
  protocolVersion: info["Protocol-Version"],
@@ -905,7 +1229,15 @@ export class CdpSessionManager {
905
1229
  } catch (error) {
906
1230
  return {
907
1231
  available: false,
908
- endpoint: this.config.cdpBaseUrl,
1232
+ endpoint:
1233
+ this.resolvedBaseUrl ??
1234
+ this.lastKnownBaseUrl ??
1235
+ this.config.cdpBaseUrl,
1236
+ attemptedEndpoint:
1237
+ this.lastAttemptedBaseUrl ??
1238
+ this.resolvedBaseUrl ??
1239
+ this.lastKnownBaseUrl ??
1240
+ this.config.cdpBaseUrl,
909
1241
  sessionCount: this.sessions.size,
910
1242
  error: toErrorMessage(error),
911
1243
  };
@@ -925,6 +1257,33 @@ export class CdpSessionManager {
925
1257
  );
926
1258
  }
927
1259
 
1260
+ async createTab(url = "about:blank") {
1261
+ const targetUrl =
1262
+ typeof url === "string" && url.trim() ? url.trim() : "about:blank";
1263
+ const result = await this.sendBrowserCommand("Target.createTarget", {
1264
+ url: targetUrl,
1265
+ });
1266
+ const targetId = result.targetId;
1267
+ if (!targetId) {
1268
+ throw new Error("Browser did not return a target id for the new tab");
1269
+ }
1270
+ const target = (await this.listTargets()).find(
1271
+ (candidate) => candidate.targetId === targetId,
1272
+ );
1273
+
1274
+ return {
1275
+ browserFamily: cdpBrowserFamily(this.config),
1276
+ ...(target ?? {
1277
+ targetId,
1278
+ type: "page",
1279
+ title: inferTitle(targetUrl),
1280
+ url: targetUrl,
1281
+ attached: false,
1282
+ webSocketDebuggerUrl: null,
1283
+ }),
1284
+ };
1285
+ }
1286
+
928
1287
  async attachToTarget(targetId) {
929
1288
  const targets = await this.listTargets();
930
1289
  const target = targets.find((candidate) => candidate.targetId === targetId);
@@ -963,6 +1322,30 @@ export class CdpSessionManager {
963
1322
  };
964
1323
  }
965
1324
 
1325
+ async closeTarget(targetId) {
1326
+ const result = await this.sendBrowserCommand("Target.closeTarget", {
1327
+ targetId,
1328
+ });
1329
+ if (result.success === false) {
1330
+ throw new Error(`Failed to close target ${targetId}`);
1331
+ }
1332
+
1333
+ const detachedSessions = Array.from(this.sessions.values())
1334
+ .filter((session) => session.target.targetId === targetId)
1335
+ .map((session) => {
1336
+ session.markClosed?.();
1337
+ this.sessions.delete(session.id);
1338
+ return { sessionId: session.id };
1339
+ });
1340
+
1341
+ return {
1342
+ browserFamily: cdpBrowserFamily(this.config),
1343
+ closed: true,
1344
+ targetId,
1345
+ detachedSessions,
1346
+ };
1347
+ }
1348
+
966
1349
  async evaluate(sessionId, expression, options) {
967
1350
  return this.getSession(sessionId).evaluate(expression, options);
968
1351
  }
@@ -975,6 +1358,14 @@ export class CdpSessionManager {
975
1358
  return this.getSession(sessionId).getPageState();
976
1359
  }
977
1360
 
1361
+ async waitFor(sessionId, options = {}) {
1362
+ return waitForPageCondition({
1363
+ getPageState: () => this.getPageState(sessionId),
1364
+ inspectElement: (selector) => this.inspectElement(sessionId, selector),
1365
+ options,
1366
+ });
1367
+ }
1368
+
978
1369
  async navigate(sessionId, url, options) {
979
1370
  return this.getSession(sessionId).navigate(url, options);
980
1371
  }
@@ -1023,6 +1414,30 @@ export class CdpSessionManager {
1023
1414
  return this.getSession(sessionId).getNetworkRequests(limit);
1024
1415
  }
1025
1416
 
1417
+ async getCookies(sessionId) {
1418
+ return this.getSession(sessionId).getCookies();
1419
+ }
1420
+
1421
+ async getStorage(sessionId) {
1422
+ return this.getSession(sessionId).getStorage();
1423
+ }
1424
+
1425
+ async captureDebugReport(sessionId, options = {}) {
1426
+ return this.getSession(sessionId).captureDebugReport(options);
1427
+ }
1428
+
1429
+ getHar(sessionId, options = {}) {
1430
+ return this.getSession(sessionId).getHar(options);
1431
+ }
1432
+
1433
+ async captureSessionSnapshot(sessionId) {
1434
+ return this.getSession(sessionId).captureSessionSnapshot();
1435
+ }
1436
+
1437
+ async restoreSessionSnapshot(sessionId, snapshot, options = {}) {
1438
+ return this.getSession(sessionId).restoreSessionSnapshot(snapshot, options);
1439
+ }
1440
+
1026
1441
  async inspectElement(sessionId, selector) {
1027
1442
  return this.getSession(sessionId).inspectElement(selector);
1028
1443
  }