mcp-browser-dev-tools 0.2.2 → 0.3.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.
@@ -1,6 +1,7 @@
1
1
  import {
2
2
  exportHarLikeSummary,
3
3
  filterConsoleMessages,
4
+ InFlightRequests,
4
5
  summarizeNetworkRequests,
5
6
  } from "./session-events.mjs";
6
7
  import { DEFAULT_FIREFOX_BIDI_WS_URL } from "./config.mjs";
@@ -14,6 +15,38 @@ import {
14
15
  } from "./page-context.mjs";
15
16
  import { buildBidiKeyActions, buildBidiTextActions } from "./keyboard.mjs";
16
17
  import { sendCheckedInput } from "./input-delivery.mjs";
18
+ import {
19
+ applyNetworkOptions,
20
+ describeNetworkState,
21
+ inNetworkTurn,
22
+ mockHeaders,
23
+ takeMatchingRule,
24
+ throttled,
25
+ } from "./network-control.mjs";
26
+ import {
27
+ FrameKeys,
28
+ probeScope,
29
+ addFrameSnapshots,
30
+ frameElementSnapshot,
31
+ parseFrameRef,
32
+ restoreFrameSelector,
33
+ shiftFramePoints,
34
+ unknownFrame,
35
+ takeFileTarget,
36
+ assertFileInput,
37
+ uploadResult,
38
+ describePointer,
39
+ dragEnd,
40
+ dragPath,
41
+ pointerFields,
42
+ takeNextRef,
43
+ wheelScroll,
44
+ } from "./page-context.mjs";
45
+
46
+ const MOUSE_BUTTON_NUMBERS = { left: 0, middle: 1, right: 2 };
47
+ // Each step of a drag takes this long, so the page sees the moves as a
48
+ // gesture rather than one jump.
49
+ const DRAG_MOVE_MS = 16;
17
50
 
18
51
  const POINTER_SOURCE = {
19
52
  type: "pointer",
@@ -30,6 +63,22 @@ function pointerMove(point) {
30
63
  };
31
64
  }
32
65
 
66
+ // The point to send input to: in the frame's own viewport for an element
67
+ // in a frame, else in the top page's.
68
+ function inputPoint(resolved) {
69
+ return resolved.framePoint ?? resolved.point;
70
+ }
71
+
72
+ function withoutFrameInput(result) {
73
+ if (!result || typeof result !== "object") {
74
+ return result;
75
+ }
76
+ const rest = { ...result };
77
+ delete rest.inputContext;
78
+ delete rest.framePoint;
79
+ return rest;
80
+ }
81
+
33
82
  function toErrorMessage(error) {
34
83
  return error instanceof Error ? error.message : String(error);
35
84
  }
@@ -181,6 +230,26 @@ function normalizeWaitUntil(value) {
181
230
  return "complete";
182
231
  }
183
232
 
233
+ // Names a request's type as CDP does where BiDi says enough: a document,
234
+ // fetch, or XHR. Older Firefox releases report neither field, so the type
235
+ // stays unknown.
236
+ export function bidiResourceType(request = {}) {
237
+ const { destination, initiatorType } = request;
238
+ if (destination === undefined && initiatorType === undefined) {
239
+ return null;
240
+ }
241
+ if (destination === "document" || destination === "iframe") {
242
+ return "Document";
243
+ }
244
+ if (initiatorType === "fetch") {
245
+ return "Fetch";
246
+ }
247
+ if (initiatorType === "xmlhttprequest") {
248
+ return "XHR";
249
+ }
250
+ return destination || initiatorType || "Other";
251
+ }
252
+
184
253
  function normalizeFirefoxEvent(method, params = {}) {
185
254
  if (method === "log.entryAdded") {
186
255
  return {
@@ -205,6 +274,22 @@ function normalizeFirefoxEvent(method, params = {}) {
205
274
  requestId: params.request?.request,
206
275
  method: params.request?.method,
207
276
  url: params.request?.url,
277
+ resourceType: bidiResourceType(params.request),
278
+ navigation: params.navigation ?? null,
279
+ source: "protocol",
280
+ };
281
+ }
282
+
283
+ if (method === "network.fetchError") {
284
+ return {
285
+ kind: "network",
286
+ phase: "failed",
287
+ completed: true,
288
+ failed: true,
289
+ timestamp: params.timestamp,
290
+ requestId: params.request?.request,
291
+ url: params.request?.url,
292
+ errorText: params.errorText ?? null,
208
293
  source: "protocol",
209
294
  };
210
295
  }
@@ -344,6 +429,7 @@ class FirefoxBidiTabSession {
344
429
  this.eventBufferSize = options.eventBufferSize ?? 200;
345
430
  this.connectedAt = new Date().toISOString();
346
431
  this.bufferedEvents = [];
432
+ this.inFlight = new InFlightRequests();
347
433
  this.subscription = null;
348
434
  this.closed = false;
349
435
  this.lastNavigationAt = null;
@@ -366,6 +452,7 @@ class FirefoxBidiTabSession {
366
452
  }
367
453
 
368
454
  pushEvent(event) {
455
+ this.inFlight.observe(event);
369
456
  this.bufferedEvents.push(event);
370
457
  if (this.bufferedEvents.length > this.eventBufferSize) {
371
458
  this.bufferedEvents.shift();
@@ -377,6 +464,10 @@ class FirefoxBidiTabSession {
377
464
  return this.bufferedEvents.slice(-safeLimit);
378
465
  }
379
466
 
467
+ pendingRequests() {
468
+ return this.inFlight.list();
469
+ }
470
+
380
471
  getConsoleMessages(limit = 50) {
381
472
  return filterConsoleMessages(this.bufferedEvents, limit);
382
473
  }
@@ -689,6 +780,15 @@ export class FirefoxBidiSessionManager {
689
780
  return;
690
781
  }
691
782
 
783
+ // A paused request is routed by its intercept, not its context, since
784
+ // a tab's intercept also pauses its iframes' requests.
785
+ if (
786
+ message.method === "network.beforeRequestSent" &&
787
+ message.params?.isBlocked
788
+ ) {
789
+ this.routeBlockedRequest(message.params);
790
+ }
791
+
692
792
  const contextId = resolveBidiEventContext(message.method, message.params);
693
793
  if (!contextId) {
694
794
  return;
@@ -818,6 +918,7 @@ export class FirefoxBidiSessionManager {
818
918
  "log.entryAdded",
819
919
  "network.beforeRequestSent",
820
920
  "network.responseCompleted",
921
+ "network.fetchError",
821
922
  "browsingContext.load",
822
923
  "browsingContext.contextDestroyed",
823
924
  "browsingContext.userPromptOpened",
@@ -835,6 +936,23 @@ export class FirefoxBidiSessionManager {
835
936
 
836
937
  async detachSession(sessionId) {
837
938
  const session = this.getSession(sessionId);
939
+ // A network call in progress finishes first, so its intercept and
940
+ // offline setting are known here and removed.
941
+ await inNetworkTurn(session, async () => {
942
+ session.closed = true;
943
+ if (session.interceptId) {
944
+ await this.send("network.removeIntercept", {
945
+ intercept: session.interceptId,
946
+ }).catch(() => {});
947
+ session.interceptId = null;
948
+ }
949
+ if (session.network?.offline) {
950
+ await this.send("emulation.setNetworkConditions", {
951
+ networkConditions: null,
952
+ contexts: [session.target.targetId],
953
+ }).catch(() => {});
954
+ }
955
+ });
838
956
 
839
957
  if (session.subscription) {
840
958
  await this.send("session.unsubscribe", {
@@ -900,7 +1018,7 @@ export class FirefoxBidiSessionManager {
900
1018
  return this.send("script.evaluate", {
901
1019
  expression,
902
1020
  target: {
903
- context: session.target.targetId,
1021
+ context: options.context ?? session.target.targetId,
904
1022
  },
905
1023
  awaitPromise: options.awaitPromise ?? true,
906
1024
  resultOwnership: "none",
@@ -913,6 +1031,16 @@ export class FirefoxBidiSessionManager {
913
1031
  }
914
1032
 
915
1033
  async runPageAction(session, payload, options = {}) {
1034
+ const route = parseFrameRef(payload.selector);
1035
+ if (route) {
1036
+ const result = await this.runInFrame(
1037
+ session,
1038
+ route.frameKey,
1039
+ { ...payload, selector: route.selector },
1040
+ options,
1041
+ );
1042
+ return restoreFrameSelector(result, route, payload.selector);
1043
+ }
916
1044
  const result = await this.evaluateInContext(
917
1045
  session,
918
1046
  buildPageContextExpression(
@@ -929,6 +1057,7 @@ export class FirefoxBidiSessionManager {
929
1057
  maxDomDepth: 0,
930
1058
  },
931
1059
  userActivation: options.userActivation ?? false,
1060
+ context: options.context,
932
1061
  },
933
1062
  );
934
1063
 
@@ -1048,17 +1177,22 @@ export class FirefoxBidiSessionManager {
1048
1177
  };
1049
1178
  }
1050
1179
 
1051
- async performActions(session, actions) {
1180
+ // Input for an element in a frame goes to that frame's context, at the
1181
+ // point in its own viewport: Firefox does not route input sent to the top
1182
+ // page into a cross-origin frame.
1183
+ async performActions(session, actions, context = null) {
1052
1184
  await this.send("input.performActions", {
1053
- context: session.target.targetId,
1185
+ context: context ?? session.target.targetId,
1054
1186
  actions,
1055
1187
  });
1056
1188
  }
1057
1189
 
1058
- async performKeyActions(session, actions) {
1059
- await this.performActions(session, [
1060
- { type: "key", id: "mcp-keyboard", actions },
1061
- ]);
1190
+ async performKeyActions(session, actions, context = null) {
1191
+ await this.performActions(
1192
+ session,
1193
+ [{ type: "key", id: "mcp-keyboard", actions }],
1194
+ context,
1195
+ );
1062
1196
  }
1063
1197
 
1064
1198
  async resolvePointerTarget(session, selector, options = {}) {
@@ -1066,17 +1200,33 @@ export class FirefoxBidiSessionManager {
1066
1200
  action: "pointer_target",
1067
1201
  selector,
1068
1202
  ...(options.inputProbe ? { inputProbe: options.inputProbe } : {}),
1203
+ ...(options.scrollIntoView === false ? { scrollIntoView: false } : {}),
1069
1204
  });
1070
1205
  assertPointerTarget(target);
1071
1206
  return target;
1072
1207
  }
1073
1208
 
1074
- async readInputProbe(session, token, disarm) {
1209
+ // A locator, scrolled into view unless scrollIntoView is false, or
1210
+ // viewport coordinates, which never scroll.
1211
+ async resolvePointer(session, target, options = {}) {
1212
+ if (typeof target === "string") {
1213
+ return this.resolvePointerTarget(session, target, options);
1214
+ }
1215
+ return this.runSnapshotAction(session.id, {
1216
+ action: "point_target",
1217
+ x: target.x,
1218
+ y: target.y,
1219
+ ...(options.inputProbe ? { inputProbe: options.inputProbe } : {}),
1220
+ });
1221
+ }
1222
+
1223
+ async readInputProbe(session, token, disarm, target = null) {
1075
1224
  try {
1076
1225
  const probe = await this.runPageAction(session, {
1077
1226
  action: "input_probe",
1078
1227
  token,
1079
1228
  disarm,
1229
+ ...probeScope(target),
1080
1230
  });
1081
1231
  return probe.armed ? probe : null;
1082
1232
  } catch {
@@ -1084,62 +1234,188 @@ export class FirefoxBidiSessionManager {
1084
1234
  }
1085
1235
  }
1086
1236
 
1087
- async click(sessionId, selector) {
1237
+ async click(sessionId, target, options = {}) {
1088
1238
  const session = this.getSession(sessionId);
1089
1239
  const token = crypto.randomUUID();
1090
- const target = await this.resolvePointerTarget(session, selector, {
1240
+ const resolved = await this.resolvePointer(session, target, {
1091
1241
  inputProbe: token,
1092
1242
  });
1093
- if (!target.found) {
1094
- return target;
1243
+ if (!resolved.found) {
1244
+ return resolved;
1245
+ }
1246
+ if (typeof target === "string") {
1247
+ assertEnabled(resolved);
1095
1248
  }
1096
- assertEnabled(target);
1097
1249
 
1250
+ const button = MOUSE_BUTTON_NUMBERS[options.button ?? "left"];
1251
+ const presses = [];
1252
+ for (let count = 0; count < (options.clickCount ?? 1); count += 1) {
1253
+ presses.push(
1254
+ { type: "pointerDown", button },
1255
+ { type: "pointerUp", button },
1256
+ );
1257
+ }
1098
1258
  const delivery = await sendCheckedInput({
1099
1259
  send: () =>
1100
- this.performActions(session, [
1101
- {
1102
- ...POINTER_SOURCE,
1103
- actions: [
1104
- pointerMove(target.point),
1105
- { type: "pointerDown", button: 0 },
1106
- { type: "pointerUp", button: 0 },
1107
- ],
1108
- },
1109
- ]),
1110
- readProbe: (disarm) => this.readInputProbe(session, token, disarm),
1111
- describe: `The click on "${selector}"`,
1260
+ this.performActions(
1261
+ session,
1262
+ [
1263
+ {
1264
+ ...POINTER_SOURCE,
1265
+ actions: [pointerMove(inputPoint(resolved)), ...presses],
1266
+ },
1267
+ ],
1268
+ resolved.inputContext,
1269
+ ),
1270
+ readProbe: (disarm) =>
1271
+ this.readInputProbe(session, token, disarm, target),
1272
+ describe: `The click on ${describePointer(target)}`,
1112
1273
  });
1113
1274
 
1114
1275
  return {
1115
1276
  browserFamily: "firefox",
1116
- selector,
1117
1277
  found: true,
1118
1278
  clicked: true,
1119
1279
  ...(delivery.resent ? { resent: true } : {}),
1120
- point: target.point,
1121
- node: delivery.node ?? target.node,
1280
+ ...pointerFields(target, resolved, delivery.node ?? resolved.node),
1122
1281
  };
1123
1282
  }
1124
1283
 
1125
- async hover(sessionId, selector) {
1284
+ async hover(sessionId, target) {
1126
1285
  const session = this.getSession(sessionId);
1127
- const target = await this.resolvePointerTarget(session, selector);
1286
+ const resolved = await this.resolvePointer(session, target);
1287
+ if (!resolved.found) {
1288
+ return resolved;
1289
+ }
1290
+
1291
+ await this.performActions(
1292
+ session,
1293
+ [{ ...POINTER_SOURCE, actions: [pointerMove(inputPoint(resolved))] }],
1294
+ resolved.inputContext,
1295
+ );
1296
+
1297
+ return {
1298
+ browserFamily: "firefox",
1299
+ found: true,
1300
+ hovered: true,
1301
+ ...pointerFields(target, resolved),
1302
+ };
1303
+ }
1304
+
1305
+ // Presses at from, moves through dragPath, and releases at to. The press
1306
+ // is checked for delivery on its own; the pointer stays down between the
1307
+ // two performActions calls, since the session keeps its input state.
1308
+ async drag(sessionId, from, to, options = {}) {
1309
+ const session = this.getSession(sessionId);
1310
+ const token = crypto.randomUUID();
1311
+ const source = await this.resolvePointer(session, from, {
1312
+ inputProbe: token,
1313
+ });
1314
+ if (!source.found) {
1315
+ await this.readInputProbe(session, token, true, from);
1316
+ return source;
1317
+ }
1318
+ // The drop point is read without scrolling, so the source stays put.
1319
+ const target = await this.resolvePointer(session, to, {
1320
+ scrollIntoView: false,
1321
+ });
1128
1322
  if (!target.found) {
1323
+ await this.readInputProbe(session, token, true, from);
1129
1324
  return target;
1130
1325
  }
1131
1326
 
1132
- await this.performActions(session, [
1133
- { ...POINTER_SOURCE, actions: [pointerMove(target.point)] },
1134
- ]);
1327
+ // A drag runs in one document: the top page's, or one frame's, with
1328
+ // points in that frame's viewport. Firefox cannot route input between
1329
+ // a frame and another document.
1330
+ if (source.inputContext !== target.inputContext) {
1331
+ await this.readInputProbe(session, token, true, from);
1332
+ throw new Error(
1333
+ "On Firefox, drag works within one document; the source and the drop target are in different frames",
1334
+ );
1335
+ }
1336
+ const context = source.inputContext ?? null;
1337
+ const start = context ? source.framePoint : source.point;
1338
+ const end = context ? target.framePoint : target.point;
1339
+ const html5 = { from: start, to: end };
1340
+ const inContext = context ? { context } : {};
1341
+ const { html5: draggable } = await this.runPageAction(
1342
+ session,
1343
+ { action: "html5_drag", ...html5, check: true },
1344
+ inContext,
1345
+ );
1346
+ if (draggable) {
1347
+ await this.readInputProbe(session, token, true, from);
1348
+ const { dropped } = await this.runPageAction(
1349
+ session,
1350
+ { action: "html5_drag", ...html5 },
1351
+ inContext,
1352
+ );
1353
+ return {
1354
+ browserFamily: "firefox",
1355
+ found: true,
1356
+ dragged: true,
1357
+ html5: true,
1358
+ synthetic: true,
1359
+ dropped,
1360
+ from: dragEnd(from, source),
1361
+ to: dragEnd(to, target),
1362
+ };
1363
+ }
1364
+
1365
+ let delivery;
1366
+ try {
1367
+ delivery = await sendCheckedInput({
1368
+ send: () =>
1369
+ this.performActions(
1370
+ session,
1371
+ [
1372
+ {
1373
+ ...POINTER_SOURCE,
1374
+ actions: [
1375
+ pointerMove(start),
1376
+ { type: "pointerDown", button: 0 },
1377
+ ],
1378
+ },
1379
+ ],
1380
+ context,
1381
+ ),
1382
+ readProbe: (disarm) =>
1383
+ this.readInputProbe(session, token, disarm, from),
1384
+ describe: `The press to drag ${describePointer(from)}`,
1385
+ });
1386
+ await this.performActions(
1387
+ session,
1388
+ [
1389
+ {
1390
+ ...POINTER_SOURCE,
1391
+ actions: [
1392
+ ...dragPath(start, end, options.steps).map((point) => ({
1393
+ ...pointerMove(point),
1394
+ duration: DRAG_MOVE_MS,
1395
+ })),
1396
+ { type: "pointerUp", button: 0 },
1397
+ ],
1398
+ },
1399
+ ],
1400
+ context,
1401
+ );
1402
+ } catch (error) {
1403
+ // A drag that failed partway must not leave the button down for the
1404
+ // next action.
1405
+ await this.send("input.releaseActions", {
1406
+ context: session.target.targetId,
1407
+ }).catch(() => {});
1408
+ throw error;
1409
+ }
1135
1410
 
1136
1411
  return {
1137
1412
  browserFamily: "firefox",
1138
- selector,
1139
1413
  found: true,
1140
- hovered: true,
1141
- point: target.point,
1142
- node: target.node,
1414
+ dragged: true,
1415
+ html5: false,
1416
+ ...(delivery.resent ? { resent: true } : {}),
1417
+ from: dragEnd(from, source),
1418
+ to: dragEnd(to, target),
1143
1419
  };
1144
1420
  }
1145
1421
 
@@ -1158,7 +1434,7 @@ export class FirefoxBidiSessionManager {
1158
1434
  { userActivation: true },
1159
1435
  );
1160
1436
  if (!prepared.found || prepared.method !== "native") {
1161
- return prepared;
1437
+ return withoutFrameInput(prepared);
1162
1438
  }
1163
1439
 
1164
1440
  let delivery = { node: null, resent: false };
@@ -1167,12 +1443,14 @@ export class FirefoxBidiSessionManager {
1167
1443
  ? buildBidiTextActions(text)
1168
1444
  : buildBidiKeyActions("Backspace");
1169
1445
  delivery = await sendCheckedInput({
1170
- send: () => this.performKeyActions(session, actions),
1171
- readProbe: (disarm) => this.readInputProbe(session, token, disarm),
1446
+ send: () =>
1447
+ this.performKeyActions(session, actions, prepared.inputContext),
1448
+ readProbe: (disarm) =>
1449
+ this.readInputProbe(session, token, disarm, selector),
1172
1450
  describe: `The text for "${selector}"`,
1173
1451
  });
1174
1452
  } else {
1175
- await this.readInputProbe(session, token, true);
1453
+ await this.readInputProbe(session, token, true, selector);
1176
1454
  }
1177
1455
 
1178
1456
  let node = delivery.node;
@@ -1195,6 +1473,206 @@ export class FirefoxBidiSessionManager {
1195
1473
  };
1196
1474
  }
1197
1475
 
1476
+ // Sets files on a file input. WebDriver BiDi sets them on an element; a
1477
+ // button that opens a chooser from script needs its hidden input passed.
1478
+ // BiDi URL patterns cannot express globs, so the tab's requests are all
1479
+ // intercepted while there are rules or extra headers, and each is matched
1480
+ // here. Throttling has no BiDi command.
1481
+ async setNetwork(sessionId, options) {
1482
+ const session = this.getSession(sessionId);
1483
+ // One call at a time per tab, so two calls cannot each add an intercept.
1484
+ return inNetworkTurn(session, () => {
1485
+ if (session.closed) {
1486
+ throw new Error(`Session ${sessionId} was detached`);
1487
+ }
1488
+ return this.applyNetwork(session, options);
1489
+ });
1490
+ }
1491
+
1492
+ async applyNetwork(session, options) {
1493
+ const state = applyNetworkOptions(session.network, options);
1494
+ if (throttled(state)) {
1495
+ throw new Error(
1496
+ "latencyMs, downloadKbps, and uploadKbps are Chromium only; Firefox has no network throttling over WebDriver BiDi",
1497
+ );
1498
+ }
1499
+ if (options.offline !== undefined || options.reset) {
1500
+ try {
1501
+ await this.send("emulation.setNetworkConditions", {
1502
+ networkConditions: state.offline ? { type: "offline" } : null,
1503
+ contexts: [session.target.targetId],
1504
+ });
1505
+ } catch (error) {
1506
+ if (state.offline) {
1507
+ throw new Error(
1508
+ `This Firefox cannot emulate offline: ${toErrorMessage(error)}`,
1509
+ { cause: error },
1510
+ );
1511
+ }
1512
+ }
1513
+ }
1514
+ // The rules apply before the intercept exists, so the first request it
1515
+ // pauses is already answered by them.
1516
+ session.network = state;
1517
+ const intercepting =
1518
+ state.rules.length > 0 || Object.keys(state.headers).length > 0;
1519
+ if (intercepting && !session.interceptId) {
1520
+ this.addingIntercepts = (this.addingIntercepts ?? 0) + 1;
1521
+ try {
1522
+ const added = await this.send("network.addIntercept", {
1523
+ phases: ["beforeRequestSent"],
1524
+ contexts: [session.target.targetId],
1525
+ });
1526
+ session.interceptId = added.intercept;
1527
+ if (session.closed) {
1528
+ await this.send("network.removeIntercept", {
1529
+ intercept: added.intercept,
1530
+ }).catch(() => {});
1531
+ session.interceptId = null;
1532
+ }
1533
+ } finally {
1534
+ this.addingIntercepts -= 1;
1535
+ for (const params of (this.unrouted ?? []).splice(0)) {
1536
+ this.routeBlockedRequest(params);
1537
+ }
1538
+ }
1539
+ } else if (!intercepting && session.interceptId) {
1540
+ const intercept = session.interceptId;
1541
+ session.interceptId = null;
1542
+ await this.send("network.removeIntercept", { intercept }).catch(() => {});
1543
+ }
1544
+ return { browserFamily: "firefox", ...describeNetworkState(state) };
1545
+ }
1546
+
1547
+ // Every intercept on this connection is one of ours. A paused request no
1548
+ // session claims either belongs to an intercept still being added, and
1549
+ // waits for it, or to one just removed, and is let go.
1550
+ routeBlockedRequest(params) {
1551
+ const owner = Array.from(this.sessions.values()).find(
1552
+ (session) =>
1553
+ session.interceptId && params.intercepts?.includes(session.interceptId),
1554
+ );
1555
+ if (owner) {
1556
+ void this.handleBlockedRequest(owner, params);
1557
+ } else if (this.addingIntercepts > 0) {
1558
+ (this.unrouted ??= []).push(params);
1559
+ } else {
1560
+ this.send("network.continueRequest", {
1561
+ request: params.request?.request,
1562
+ }).catch(() => {});
1563
+ }
1564
+ }
1565
+
1566
+ async handleBlockedRequest(session, params) {
1567
+ const request = params.request?.request;
1568
+ const rule = takeMatchingRule(session.network, params.request?.url ?? "");
1569
+ const stringValue = (value) => ({ type: "string", value });
1570
+ try {
1571
+ if (rule?.action === "block") {
1572
+ await this.send("network.failRequest", { request });
1573
+ } else if (rule) {
1574
+ await this.send("network.provideResponse", {
1575
+ request,
1576
+ statusCode: rule.status,
1577
+ headers: mockHeaders(rule).map(({ name, value }) => ({
1578
+ name,
1579
+ value: stringValue(value),
1580
+ })),
1581
+ body: stringValue(rule.body),
1582
+ });
1583
+ } else {
1584
+ const extra = session.network?.headers ?? {};
1585
+ const names = new Set(
1586
+ Object.keys(extra).map((name) => name.toLowerCase()),
1587
+ );
1588
+ const headers =
1589
+ names.size === 0
1590
+ ? undefined
1591
+ : [
1592
+ ...(params.request?.headers ?? []).filter(
1593
+ (header) => !names.has(header.name.toLowerCase()),
1594
+ ),
1595
+ ...Object.entries(extra).map(([name, value]) => ({
1596
+ name,
1597
+ value: stringValue(String(value)),
1598
+ })),
1599
+ ];
1600
+ await this.send("network.continueRequest", {
1601
+ request,
1602
+ ...(headers ? { headers } : {}),
1603
+ });
1604
+ }
1605
+ } catch {
1606
+ // Release the request if it is still paused; it may also have gone
1607
+ // away, for example because the page navigated.
1608
+ await this.send("network.continueRequest", { request }).catch(() => {});
1609
+ }
1610
+ }
1611
+
1612
+ // The page's report; Firefox has no counters like Chromium's over BiDi.
1613
+ async getPerformance(sessionId) {
1614
+ const report = await this.runPageAction(this.getSession(sessionId), {
1615
+ action: "performance",
1616
+ });
1617
+ return { ...report, metrics: null };
1618
+ }
1619
+
1620
+ async startTrace() {
1621
+ throw new Error(
1622
+ "record_trace is Chromium only; Firefox has no tracing over WebDriver BiDi",
1623
+ );
1624
+ }
1625
+
1626
+ async stopTrace() {
1627
+ return this.startTrace();
1628
+ }
1629
+
1630
+ async uploadFiles(sessionId, selector, files) {
1631
+ const session = this.getSession(sessionId);
1632
+ const token = crypto.randomUUID();
1633
+ const target = await this.runPageAction(session, {
1634
+ action: "file_input",
1635
+ selector,
1636
+ token,
1637
+ clear: files.length === 0,
1638
+ });
1639
+ if (!target.found) {
1640
+ return target;
1641
+ }
1642
+ if (target.cleared) {
1643
+ return uploadResult("firefox", selector, files);
1644
+ }
1645
+ if (!target.fileInput) {
1646
+ throw new Error(
1647
+ `"${selector}" is not a file input and has none inside; on Firefox, pass the <input type="file">, which may be hidden`,
1648
+ );
1649
+ }
1650
+ // The input and the files go to the document it is in, a frame's for a
1651
+ // frame ref.
1652
+ const route = parseFrameRef(selector);
1653
+ const context = route
1654
+ ? this.frameKeys(session).get(route.frameKey)?.id
1655
+ : undefined;
1656
+ const handle = await this.evaluateInContext(
1657
+ session,
1658
+ takeFileTarget(token),
1659
+ {
1660
+ context,
1661
+ },
1662
+ );
1663
+ const sharedId = handle.result?.sharedId;
1664
+ assertFileInput(target, files);
1665
+ await this.send("input.setFiles", {
1666
+ context: context ?? session.target.targetId,
1667
+ element: { sharedId },
1668
+ files,
1669
+ });
1670
+ return uploadResult("firefox", selector, files, {
1671
+ multiple: target.multiple,
1672
+ accept: target.accept,
1673
+ });
1674
+ }
1675
+
1198
1676
  async select(sessionId, selector, options = {}) {
1199
1677
  return this.runPageAction(
1200
1678
  this.getSession(sessionId),
@@ -1222,12 +1700,14 @@ export class FirefoxBidiSessionManager {
1222
1700
  { userActivation: true },
1223
1701
  );
1224
1702
  if (!focused.found) {
1225
- return focused;
1703
+ return withoutFrameInput(focused);
1226
1704
  }
1227
1705
 
1228
1706
  const delivery = await sendCheckedInput({
1229
- send: () => this.performKeyActions(session, actions),
1230
- readProbe: (disarm) => this.readInputProbe(session, token, disarm),
1707
+ send: () =>
1708
+ this.performKeyActions(session, actions, focused.inputContext),
1709
+ readProbe: (disarm) =>
1710
+ this.readInputProbe(session, token, disarm, selector),
1231
1711
  describe: `The key press "${key}"`,
1232
1712
  });
1233
1713
 
@@ -1240,9 +1720,51 @@ export class FirefoxBidiSessionManager {
1240
1720
  };
1241
1721
  }
1242
1722
 
1723
+ // A selector alone scrolls its element into view and deltas alone scroll
1724
+ // the page. Coordinates, or a selector with deltas, send a real mouse
1725
+ // wheel there, which scrolls whatever is under the pointer.
1243
1726
  async scroll(sessionId, options = {}) {
1727
+ const session = this.getSession(sessionId);
1728
+ if (wheelScroll(options)) {
1729
+ const target = options.selector ?? { x: options.x, y: options.y };
1730
+ const resolved = await this.resolvePointer(session, target);
1731
+ if (!resolved.found) {
1732
+ return resolved;
1733
+ }
1734
+ const wheel = {
1735
+ deltaX: options.deltaX ?? 0,
1736
+ deltaY: options.deltaY ?? 0,
1737
+ };
1738
+ const at = inputPoint(resolved);
1739
+ await this.performActions(
1740
+ session,
1741
+ [
1742
+ {
1743
+ type: "wheel",
1744
+ id: "mcp-wheel",
1745
+ actions: [
1746
+ {
1747
+ type: "scroll",
1748
+ x: Math.round(at.x),
1749
+ y: Math.round(at.y),
1750
+ ...wheel,
1751
+ origin: "viewport",
1752
+ },
1753
+ ],
1754
+ },
1755
+ ],
1756
+ resolved.inputContext,
1757
+ );
1758
+ return {
1759
+ browserFamily: "firefox",
1760
+ found: true,
1761
+ scrolled: true,
1762
+ wheel,
1763
+ ...pointerFields(target, resolved),
1764
+ };
1765
+ }
1244
1766
  return this.runPageAction(
1245
- this.getSession(sessionId),
1767
+ session,
1246
1768
  {
1247
1769
  action: "scroll",
1248
1770
  selector: options.selector,
@@ -1420,9 +1942,193 @@ export class FirefoxBidiSessionManager {
1420
1942
  };
1421
1943
  }
1422
1944
 
1945
+ async runSnapshotAction(sessionId, payload) {
1946
+ const session = this.getSession(sessionId);
1947
+ const result = await this.runPageAction(session, {
1948
+ ...payload,
1949
+ refStart: session.refStart ?? 1,
1950
+ });
1951
+ return takeNextRef(session, result);
1952
+ }
1953
+
1423
1954
  async snapshotControls(sessionId) {
1424
- return this.runPageAction(this.getSession(sessionId), {
1425
- action: "controls_snapshot",
1955
+ return this.runSnapshotAction(sessionId, { action: "controls_snapshot" });
1956
+ }
1957
+
1958
+ async trackChanges(sessionId, phase, options = {}) {
1959
+ const { frameKey, ...rest } = options;
1960
+ if (!frameKey) {
1961
+ return this.runSnapshotAction(sessionId, {
1962
+ action: `change_${phase}`,
1963
+ ...rest,
1964
+ });
1965
+ }
1966
+ // In a frame, refs number on from the frame's own last snapshot. A frame
1967
+ // that is gone ends tracking as a lost baseline does.
1968
+ const session = this.getSession(sessionId);
1969
+ const entry = this.frameKeys(session).get(frameKey);
1970
+ const result = entry
1971
+ ? await this.runInFrame(
1972
+ session,
1973
+ frameKey,
1974
+ { action: `change_${phase}`, ...rest, refStart: entry.refStart ?? 1 },
1975
+ { offset: false },
1976
+ ).catch(() => null)
1977
+ : null;
1978
+ if (!result || result.error?.startsWith("Unknown frame")) {
1979
+ if (phase === "baseline") {
1980
+ throw new Error(`Unknown frame ${frameKey}`);
1981
+ }
1982
+ return { document: "same", lost: true };
1983
+ }
1984
+ return takeNextRef(entry, result);
1985
+ }
1986
+
1987
+ frameKeys(session) {
1988
+ return (session.frameKeys ??= new FrameKeys());
1989
+ }
1990
+
1991
+ // The tab's iframes, outermost first, each with its parent's context.
1992
+ async listFrames(session) {
1993
+ const { contexts } = await this.send("browsingContext.getTree", {
1994
+ root: session.target.targetId,
1995
+ });
1996
+ const frames = [];
1997
+ const walk = (node) => {
1998
+ for (const child of node.children ?? []) {
1999
+ frames.push({
2000
+ id: child.context,
2001
+ url: child.url,
2002
+ parent: node.context,
2003
+ });
2004
+ walk(child);
2005
+ }
2006
+ };
2007
+ for (const root of contexts ?? []) {
2008
+ walk(root);
2009
+ }
2010
+ return frames;
2011
+ }
2012
+
2013
+ // Where the frame's viewport starts in the top page's viewport: the
2014
+ // content box of its owner element, found with the context locator in its
2015
+ // parent, plus the parent's own offset; null when the frame is gone or
2016
+ // hidden. With scroll, each owner is scrolled into view first.
2017
+ async frameOffset(session, frame, scroll = false) {
2018
+ const frames = await this.listFrames(session);
2019
+ const byId = new Map(frames.map((entry) => [entry.id, entry]));
2020
+ const chain = [];
2021
+ for (
2022
+ let entry = byId.get(frame.id);
2023
+ entry;
2024
+ entry = byId.get(entry.parent)
2025
+ ) {
2026
+ chain.unshift(entry);
2027
+ }
2028
+ if (chain.length === 0) {
2029
+ return null;
2030
+ }
2031
+ let offset = { x: 0, y: 0 };
2032
+ for (const entry of chain) {
2033
+ const located = await this.send("browsingContext.locateNodes", {
2034
+ context: entry.parent,
2035
+ locator: { type: "context", value: { context: entry.id } },
2036
+ }).catch(() => null);
2037
+ const sharedId = located?.nodes?.[0]?.sharedId;
2038
+ if (!sharedId) {
2039
+ return null;
2040
+ }
2041
+ const box = await this.send("script.callFunction", {
2042
+ functionDeclaration: `(element, scroll) => {
2043
+ if (scroll) element.scrollIntoView({ block: "center", inline: "center" });
2044
+ const rect = element.getBoundingClientRect();
2045
+ if (rect.width === 0 || rect.height === 0) return null;
2046
+ const style = getComputedStyle(element);
2047
+ return [
2048
+ rect.left + element.clientLeft + parseFloat(style.paddingLeft),
2049
+ rect.top + element.clientTop + parseFloat(style.paddingTop),
2050
+ ];
2051
+ }`,
2052
+ target: { context: entry.parent },
2053
+ arguments: [{ sharedId }, { type: "boolean", value: scroll }],
2054
+ awaitPromise: false,
2055
+ resultOwnership: "none",
2056
+ }).catch(() => null);
2057
+ const values = box?.result?.value;
2058
+ if (box?.type !== "success" || !Array.isArray(values)) {
2059
+ return null;
2060
+ }
2061
+ offset = {
2062
+ x: offset.x + values[0].value,
2063
+ y: offset.y + values[1].value,
2064
+ };
2065
+ }
2066
+ return offset;
2067
+ }
2068
+
2069
+ // Runs a page action in a frame's browsing context.
2070
+ async runInFrame(session, frameKey, payload, options = {}) {
2071
+ const frame = this.frameKeys(session).get(frameKey);
2072
+ if (!frame) {
2073
+ return unknownFrame(frameKey, payload.selector);
2074
+ }
2075
+ const positioned = options.offset !== false;
2076
+ const before = positioned
2077
+ ? await this.frameOffset(
2078
+ session,
2079
+ frame,
2080
+ options.scroll ?? payload.scrollIntoView !== false,
2081
+ )
2082
+ : { x: 0, y: 0 };
2083
+ if (!before) {
2084
+ return unknownFrame(frameKey, payload.selector);
2085
+ }
2086
+ const result = await this.runPageAction(session, payload, {
2087
+ ...options,
2088
+ context: frame.id,
2089
+ });
2090
+ if (!result || typeof result !== "object") {
2091
+ return result;
2092
+ }
2093
+ // The action may have scrolled the frame's ancestors, moving the frame.
2094
+ const offset =
2095
+ positioned && (result.point || result.node?.box)
2096
+ ? ((await this.frameOffset(session, frame)) ?? before)
2097
+ : before;
2098
+ return {
2099
+ ...shiftFramePoints(result, offset),
2100
+ inputContext: frame.id,
2101
+ ...(result.point ? { framePoint: result.point } : {}),
2102
+ };
2103
+ }
2104
+
2105
+ // The top page's headings and controls, then each iframe's.
2106
+ async snapshotPage(sessionId, options = {}) {
2107
+ const session = this.getSession(sessionId);
2108
+ const runInFrame = (key, payload, runOptions) =>
2109
+ this.runInFrame(session, key, payload, runOptions);
2110
+ const route = parseFrameRef(options.selector);
2111
+ if (route) {
2112
+ return frameElementSnapshot({
2113
+ route,
2114
+ frameKeys: this.frameKeys(session),
2115
+ runInFrame,
2116
+ options,
2117
+ });
2118
+ }
2119
+ const result = await this.runSnapshotAction(sessionId, {
2120
+ action: "snapshot",
2121
+ ...options,
2122
+ });
2123
+ if (options.selector) {
2124
+ return result;
2125
+ }
2126
+ return addFrameSnapshots({
2127
+ result,
2128
+ frames: await this.listFrames(session).catch(() => []),
2129
+ frameKeys: this.frameKeys(session),
2130
+ runInFrame,
2131
+ options,
1426
2132
  });
1427
2133
  }
1428
2134
 
@@ -1486,6 +2192,10 @@ export class FirefoxBidiSessionManager {
1486
2192
  }
1487
2193
  }
1488
2194
 
2195
+ pendingRequests(sessionId) {
2196
+ return this.getSession(sessionId).pendingRequests();
2197
+ }
2198
+
1489
2199
  getEvents(sessionId, limit) {
1490
2200
  return this.getSession(sessionId).getEvents(limit);
1491
2201
  }