mcp-browser-dev-tools 0.0.6 → 0.2.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.
@@ -6,6 +6,7 @@ import {
6
6
  import { DEFAULT_CDP_BASE_URL } from "./config.mjs";
7
7
  import { waitForPageCondition } from "./wait-for.mjs";
8
8
  import {
9
+ assertEnabled,
9
10
  assertPointerTarget,
10
11
  buildPageContextExpression,
11
12
  } from "./page-context.mjs";
@@ -359,6 +360,21 @@ async function readWebSocketData(data) {
359
360
  return String(data);
360
361
  }
361
362
 
363
+ // CDP reports a thrown value as text "Uncaught". An error's message is on
364
+ // the first line of its description ("Error: message"); a thrown primitive
365
+ // is in value.
366
+ function pageExceptionMessage(details) {
367
+ const exception = details.exception;
368
+ const description = exception?.description;
369
+ if (typeof description === "string" && description.trim()) {
370
+ return description.split("\n")[0].replace(/^[A-Za-z]*Error: /, "");
371
+ }
372
+ if (exception && "value" in exception && exception.value !== undefined) {
373
+ return String(exception.value);
374
+ }
375
+ return details.text || "Page action failed";
376
+ }
377
+
362
378
  export class CdpSession {
363
379
  constructor(target, options = {}) {
364
380
  this.id = crypto.randomUUID();
@@ -568,6 +584,10 @@ export class CdpSession {
568
584
  waiter = { method, predicate, resolve, reject, timer };
569
585
  this.eventWaiters.add(waiter);
570
586
  });
587
+ // Callers await the promise only after sending their command, so a
588
+ // rejection before then (the tab closing, or a timeout) must not count as
589
+ // unhandled; it still reaches the caller when it awaits.
590
+ promise.catch(() => {});
571
591
 
572
592
  return {
573
593
  promise,
@@ -620,13 +640,67 @@ export class CdpSession {
620
640
  });
621
641
  }
622
642
 
643
+ // REPL mode allows top-level await but, like the DevTools console, returns
644
+ // a promise the expression evaluates to without awaiting it. So evaluate by
645
+ // reference, await a returned promise, and only then read the value.
623
646
  async evaluate(expression, options = {}) {
624
- const result = await this.evaluateRuntime(expression, options);
625
-
626
- return {
627
- result: summarizeRemoteObject(result.result),
628
- exceptionDetails: result.exceptionDetails ?? null,
647
+ const awaitPromise = options.awaitPromise ?? true;
648
+ const returnByValue = options.returnByValue ?? true;
649
+ let response = await this.evaluateRuntime(expression, {
650
+ ...options,
651
+ awaitPromise,
652
+ returnByValue: false,
653
+ });
654
+ const objectIds = new Set();
655
+ const hold = (reply) => {
656
+ for (const objectId of [
657
+ reply.result?.objectId,
658
+ reply.exceptionDetails?.exception?.objectId,
659
+ ]) {
660
+ if (objectId) {
661
+ objectIds.add(objectId);
662
+ }
663
+ }
629
664
  };
665
+ hold(response);
666
+
667
+ try {
668
+ if (
669
+ awaitPromise &&
670
+ !response.exceptionDetails &&
671
+ response.result?.subtype === "promise"
672
+ ) {
673
+ response = await this.send("Runtime.awaitPromise", {
674
+ promiseObjectId: response.result.objectId,
675
+ returnByValue,
676
+ });
677
+ hold(response);
678
+ } else if (
679
+ returnByValue &&
680
+ !response.exceptionDetails &&
681
+ response.result?.objectId &&
682
+ response.result.type !== "symbol"
683
+ ) {
684
+ response = await this.send("Runtime.callFunctionOn", {
685
+ functionDeclaration: "function () { return this; }",
686
+ objectId: response.result.objectId,
687
+ returnByValue: true,
688
+ });
689
+ hold(response);
690
+ }
691
+
692
+ // As on Firefox, a thrown error is reported only in exceptionDetails.
693
+ return {
694
+ result: response.exceptionDetails
695
+ ? null
696
+ : summarizeRemoteObject(response.result),
697
+ exceptionDetails: response.exceptionDetails ?? null,
698
+ };
699
+ } finally {
700
+ for (const objectId of objectIds) {
701
+ this.send("Runtime.releaseObject", { objectId }).catch(() => {});
702
+ }
703
+ }
630
704
  }
631
705
 
632
706
  async getDocument(depth = 2) {
@@ -653,7 +727,7 @@ export class CdpSession {
653
727
  );
654
728
 
655
729
  if (result.exceptionDetails) {
656
- throw new Error(result.exceptionDetails.text || "Page action failed");
730
+ throw new Error(pageExceptionMessage(result.exceptionDetails));
657
731
  }
658
732
 
659
733
  const value = result.result?.value ?? summarizeRemoteObject(result.result);
@@ -804,10 +878,19 @@ export class CdpSession {
804
878
  };
805
879
  }
806
880
 
807
- async inspectElement(selector) {
881
+ async snapshotControls() {
882
+ return this.runPageAction({ action: "controls_snapshot" });
883
+ }
884
+
885
+ async readText(options = {}) {
886
+ return this.runPageAction({ action: "read_text", ...options });
887
+ }
888
+
889
+ async inspectElement(selector, options = {}) {
808
890
  return this.runPageAction({
809
891
  action: "inspect",
810
892
  selector,
893
+ textChecks: options.textChecks,
811
894
  });
812
895
  }
813
896
 
@@ -840,6 +923,7 @@ export class CdpSession {
840
923
  if (!target.found) {
841
924
  return target;
842
925
  }
926
+ assertEnabled(target);
843
927
 
844
928
  const press = { button: "left", clickCount: 1 };
845
929
  await this.dispatchMouse("mouseMoved", target.point);
@@ -1484,7 +1568,9 @@ export class CdpSessionManager {
1484
1568
  async waitFor(sessionId, options = {}) {
1485
1569
  return waitForPageCondition({
1486
1570
  getPageState: () => this.getPageState(sessionId),
1487
- inspectElement: (selector) => this.inspectElement(sessionId, selector),
1571
+ inspectElement: (selector, options) =>
1572
+ this.inspectElement(sessionId, selector, options),
1573
+ evaluate: (expression) => this.evaluate(sessionId, expression),
1488
1574
  options,
1489
1575
  });
1490
1576
  }
@@ -1561,8 +1647,16 @@ export class CdpSessionManager {
1561
1647
  return this.getSession(sessionId).restoreSessionSnapshot(snapshot, options);
1562
1648
  }
1563
1649
 
1564
- async inspectElement(sessionId, selector) {
1565
- return this.getSession(sessionId).inspectElement(selector);
1650
+ async readText(sessionId, options) {
1651
+ return this.getSession(sessionId).readText(options);
1652
+ }
1653
+
1654
+ async snapshotControls(sessionId) {
1655
+ return this.getSession(sessionId).snapshotControls();
1656
+ }
1657
+
1658
+ async inspectElement(sessionId, selector, options) {
1659
+ return this.getSession(sessionId).inspectElement(selector, options);
1566
1660
  }
1567
1661
 
1568
1662
  getEvents(sessionId, limit) {
package/src/config.mjs CHANGED
@@ -41,6 +41,10 @@ export function isTruthyFlag(value) {
41
41
  return value === "1" || value === "true";
42
42
  }
43
43
 
44
+ export function isFalsyFlag(value) {
45
+ return value === "0" || value === "false";
46
+ }
47
+
44
48
  export function isLoopbackOrigin(value) {
45
49
  const url = new URL(value);
46
50
  return isLoopbackHost(url.hostname);
@@ -114,7 +118,7 @@ export function loadConfig(env = process.env) {
114
118
  firefoxBidiWsUrl,
115
119
  allowRemoteEndpoints,
116
120
  allowRemoteCdp: allowRemoteEndpoints,
117
- enableEvaluate: isTruthyFlag(env.MCP_BROWSER_ENABLE_EVAL),
121
+ enableEvaluate: !isFalsyFlag(env.MCP_BROWSER_ENABLE_EVAL),
118
122
  enableUnsafeLaunchArgs: isTruthyFlag(
119
123
  env.MCP_BROWSER_ENABLE_UNSAFE_LAUNCH_ARGS,
120
124
  ),
@@ -126,6 +130,7 @@ export function loadConfig(env = process.env) {
126
130
  debugStdio: logging.debugStdio,
127
131
  logFile: logging.logFile,
128
132
  userDataDir: env.MCP_BROWSER_USER_DATA_DIR?.trim() || null,
133
+ timingLogFile: env.MCP_BROWSER_TIMING_LOG?.trim() || null,
129
134
  protocolVersion:
130
135
  env.MCP_PROTOCOL_VERSION?.trim() || DEFAULT_PROTOCOL_VERSION,
131
136
  };
@@ -4,8 +4,10 @@ import {
4
4
  summarizeNetworkRequests,
5
5
  } from "./session-events.mjs";
6
6
  import { DEFAULT_FIREFOX_BIDI_WS_URL } from "./config.mjs";
7
+ import { wrapTopLevelAwait } from "./top-level-await.mjs";
7
8
  import { waitForPageCondition } from "./wait-for.mjs";
8
9
  import {
10
+ assertEnabled,
9
11
  assertPointerTarget,
10
12
  buildPageContextExpression,
11
13
  } from "./page-context.mjs";
@@ -869,7 +871,11 @@ export class FirefoxBidiSessionManager {
869
871
 
870
872
  async evaluate(sessionId, expression, options = {}) {
871
873
  const session = this.getSession(sessionId);
872
- const result = await this.evaluateInContext(session, expression, options);
874
+ const result = await this.evaluateInContext(
875
+ session,
876
+ wrapTopLevelAwait(expression) ?? expression,
877
+ options,
878
+ );
873
879
 
874
880
  return {
875
881
  result:
@@ -980,7 +986,9 @@ export class FirefoxBidiSessionManager {
980
986
  async waitFor(sessionId, options = {}) {
981
987
  return waitForPageCondition({
982
988
  getPageState: () => this.getPageState(sessionId),
983
- inspectElement: (selector) => this.inspectElement(sessionId, selector),
989
+ inspectElement: (selector, options) =>
990
+ this.inspectElement(sessionId, selector, options),
991
+ evaluate: (expression) => this.evaluate(sessionId, expression),
984
992
  options,
985
993
  });
986
994
  }
@@ -1060,6 +1068,7 @@ export class FirefoxBidiSessionManager {
1060
1068
  if (!target.found) {
1061
1069
  return target;
1062
1070
  }
1071
+ assertEnabled(target);
1063
1072
 
1064
1073
  await this.performActions(session, [
1065
1074
  {
@@ -1358,10 +1367,24 @@ export class FirefoxBidiSessionManager {
1358
1367
  };
1359
1368
  }
1360
1369
 
1361
- async inspectElement(sessionId, selector) {
1370
+ async snapshotControls(sessionId) {
1371
+ return this.runPageAction(this.getSession(sessionId), {
1372
+ action: "controls_snapshot",
1373
+ });
1374
+ }
1375
+
1376
+ async readText(sessionId, options = {}) {
1377
+ return this.runPageAction(this.getSession(sessionId), {
1378
+ action: "read_text",
1379
+ ...options,
1380
+ });
1381
+ }
1382
+
1383
+ async inspectElement(sessionId, selector, options = {}) {
1362
1384
  return this.runPageAction(this.getSession(sessionId), {
1363
1385
  action: "inspect",
1364
1386
  selector,
1387
+ textChecks: options.textChecks,
1365
1388
  });
1366
1389
  }
1367
1390
 
@@ -0,0 +1,99 @@
1
+ export function validateValue(path, value, schema) {
2
+ if (schema.type === "object") {
3
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
4
+ throw new Error(`${path} must be an object`);
5
+ }
6
+
7
+ const properties = schema.properties ?? {};
8
+ const required = schema.required ?? [];
9
+ for (const key of required) {
10
+ if (value[key] === undefined) {
11
+ throw new Error(`${path}.${key} is required`);
12
+ }
13
+ }
14
+
15
+ if (schema.additionalProperties === false) {
16
+ for (const key of Object.keys(value)) {
17
+ if (!(key in properties)) {
18
+ throw new Error(`${path}.${key} is not allowed`);
19
+ }
20
+ }
21
+ }
22
+
23
+ for (const [key, propertySchema] of Object.entries(properties)) {
24
+ if (value[key] !== undefined) {
25
+ validateValue(`${path}.${key}`, value[key], propertySchema);
26
+ }
27
+ }
28
+
29
+ return;
30
+ }
31
+
32
+ if (schema.type === "array") {
33
+ if (!Array.isArray(value)) {
34
+ throw new Error(`${path} must be an array`);
35
+ }
36
+
37
+ if (schema.minItems !== undefined && value.length < schema.minItems) {
38
+ throw new Error(`${path} must have at least ${schema.minItems} items`);
39
+ }
40
+
41
+ if (schema.maxItems !== undefined && value.length > schema.maxItems) {
42
+ throw new Error(`${path} must have at most ${schema.maxItems} items`);
43
+ }
44
+
45
+ if (schema.items) {
46
+ value.forEach((item, index) => {
47
+ validateValue(`${path}[${index}]`, item, schema.items);
48
+ });
49
+ }
50
+
51
+ return;
52
+ }
53
+
54
+ if (schema.type === "string") {
55
+ if (typeof value !== "string") {
56
+ throw new Error(`${path} must be a string`);
57
+ }
58
+
59
+ if (schema.enum && !schema.enum.includes(value)) {
60
+ throw new Error(`${path} must be one of: ${schema.enum.join(", ")}`);
61
+ }
62
+
63
+ return;
64
+ }
65
+
66
+ if (schema.type === "boolean") {
67
+ if (typeof value !== "boolean") {
68
+ throw new Error(`${path} must be a boolean`);
69
+ }
70
+
71
+ return;
72
+ }
73
+
74
+ if (schema.type === "integer") {
75
+ if (!Number.isInteger(value)) {
76
+ throw new Error(`${path} must be an integer`);
77
+ }
78
+
79
+ if (schema.minimum !== undefined && value < schema.minimum) {
80
+ throw new Error(`${path} must be >= ${schema.minimum}`);
81
+ }
82
+
83
+ if (schema.maximum !== undefined && value > schema.maximum) {
84
+ throw new Error(`${path} must be <= ${schema.maximum}`);
85
+ }
86
+
87
+ return;
88
+ }
89
+
90
+ if (schema.type === "number") {
91
+ if (typeof value !== "number" || Number.isNaN(value)) {
92
+ throw new Error(`${path} must be a number`);
93
+ }
94
+
95
+ if (schema.minimum !== undefined && value < schema.minimum) {
96
+ throw new Error(`${path} must be >= ${schema.minimum}`);
97
+ }
98
+ }
99
+ }