mcp-browser-dev-tools 0.0.1-beta.2 → 0.0.1-beta.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,6 +2,7 @@ import {
2
2
  filterConsoleMessages,
3
3
  summarizeNetworkRequests,
4
4
  } from "./session-events.mjs";
5
+ import { buildPageContextExpression } from "./page-context.mjs";
5
6
 
6
7
  function toErrorMessage(error) {
7
8
  return error instanceof Error ? error.message : String(error);
@@ -108,6 +109,52 @@ export function summarizeBidiRemoteValue(value) {
108
109
  }
109
110
  }
110
111
 
112
+ function summarizeFirefoxStackFrames(callFrames = []) {
113
+ return callFrames.map((frame) => ({
114
+ functionName: frame.functionName || null,
115
+ url: frame.url || null,
116
+ lineNumber: frame.lineNumber ?? null,
117
+ columnNumber: frame.columnNumber ?? null,
118
+ }));
119
+ }
120
+
121
+ function firstFirefoxCallFrame(stackTrace) {
122
+ const frame = stackTrace?.callFrames?.[0];
123
+ if (!frame) {
124
+ return null;
125
+ }
126
+
127
+ return {
128
+ functionName: frame.functionName || null,
129
+ url: frame.url || null,
130
+ lineNumber: frame.lineNumber ?? null,
131
+ columnNumber: frame.columnNumber ?? null,
132
+ };
133
+ }
134
+
135
+ function screenshotMimeType(format) {
136
+ return format === "jpeg" ? "image/jpeg" : "image/png";
137
+ }
138
+
139
+ function formatScreenshotResult(data, format, extras = {}) {
140
+ return {
141
+ format,
142
+ mimeType: screenshotMimeType(format),
143
+ encoding: "base64",
144
+ byteLength: Buffer.byteLength(data, "base64"),
145
+ data,
146
+ ...extras,
147
+ };
148
+ }
149
+
150
+ function normalizeWaitUntil(value) {
151
+ if (value === "none" || value === "interactive") {
152
+ return value;
153
+ }
154
+
155
+ return "complete";
156
+ }
157
+
111
158
  function normalizeFirefoxEvent(method, params = {}) {
112
159
  if (method === "log.entryAdded") {
113
160
  return {
@@ -116,6 +163,10 @@ function normalizeFirefoxEvent(method, params = {}) {
116
163
  text: params.text,
117
164
  timestamp: params.timestamp,
118
165
  values: (params.args || []).map((arg) => summarizeBidiRemoteValue(arg)),
166
+ source: firstFirefoxCallFrame(params.stackTrace),
167
+ stackTrace: summarizeFirefoxStackFrames(params.stackTrace?.callFrames),
168
+ realm: params.source?.realm ?? null,
169
+ context: params.source?.context ?? null,
119
170
  };
120
171
  }
121
172
 
@@ -128,6 +179,7 @@ function normalizeFirefoxEvent(method, params = {}) {
128
179
  requestId: params.request?.request,
129
180
  method: params.request?.method,
130
181
  url: params.request?.url,
182
+ source: "protocol",
131
183
  };
132
184
  }
133
185
 
@@ -143,6 +195,7 @@ function normalizeFirefoxEvent(method, params = {}) {
143
195
  statusText: params.response?.statusText,
144
196
  mimeType: params.response?.mimeType,
145
197
  url: params.request?.url,
198
+ source: "protocol",
146
199
  };
147
200
  }
148
201
 
@@ -152,6 +205,7 @@ function normalizeFirefoxEvent(method, params = {}) {
152
205
  timestamp: params.timestamp ?? null,
153
206
  url: params.url ?? null,
154
207
  navigation: params.navigation ?? null,
208
+ context: params.context ?? null,
155
209
  };
156
210
  }
157
211
 
@@ -194,15 +248,27 @@ class FirefoxBidiTabSession {
194
248
  this.bufferedEvents = [];
195
249
  this.subscription = null;
196
250
  this.closed = false;
251
+ this.lastNavigationAt = null;
252
+ this.lastReloadAt = null;
253
+ this.viewportOverride = null;
197
254
  }
198
255
 
199
256
  bufferEvent(method, params) {
200
- this.bufferedEvents.push({
257
+ const capturedAt = new Date().toISOString();
258
+ if (method === "browsingContext.load" && params.url) {
259
+ this.target.url = params.url;
260
+ this.lastNavigationAt = capturedAt;
261
+ }
262
+
263
+ this.pushEvent({
201
264
  method,
202
- capturedAt: new Date().toISOString(),
265
+ capturedAt,
203
266
  ...normalizeFirefoxEvent(method, params),
204
267
  });
268
+ }
205
269
 
270
+ pushEvent(event) {
271
+ this.bufferedEvents.push(event);
206
272
  if (this.bufferedEvents.length > this.eventBufferSize) {
207
273
  this.bufferedEvents.shift();
208
274
  }
@@ -231,6 +297,9 @@ class FirefoxBidiTabSession {
231
297
  connectedAt: this.connectedAt,
232
298
  bufferedEvents: this.bufferedEvents.length,
233
299
  subscription: this.subscription,
300
+ lastNavigationAt: this.lastNavigationAt,
301
+ lastReloadAt: this.lastReloadAt,
302
+ viewportOverride: this.viewportOverride,
234
303
  };
235
304
  }
236
305
  }
@@ -466,6 +535,7 @@ export class FirefoxBidiSessionManager {
466
535
 
467
536
  session.subscription = subscription.subscription ?? null;
468
537
  this.sessions.set(session.id, session);
538
+ await this.seedBufferedState(session);
469
539
  return session.getSummary();
470
540
  }
471
541
 
@@ -488,53 +558,84 @@ export class FirefoxBidiSessionManager {
488
558
 
489
559
  async evaluate(sessionId, expression, options = {}) {
490
560
  const session = this.getSession(sessionId);
491
- const result = await this.send("script.evaluate", {
561
+ const result = await this.evaluateInContext(session, expression, options);
562
+
563
+ return {
564
+ result:
565
+ result.type === "success"
566
+ ? summarizeBidiRemoteValue(result.result)
567
+ : null,
568
+ exceptionDetails:
569
+ result.type === "exception" ? result.exceptionDetails : null,
570
+ realm: result.realm ?? null,
571
+ };
572
+ }
573
+
574
+ async evaluateInContext(session, expression, options = {}) {
575
+ return this.send("script.evaluate", {
492
576
  expression,
493
577
  target: {
494
578
  context: session.target.targetId,
495
579
  },
496
580
  awaitPromise: options.awaitPromise ?? true,
497
581
  resultOwnership: "none",
498
- serializationOptions: {
582
+ serializationOptions: options.serializationOptions ?? {
499
583
  maxObjectDepth: 5,
500
584
  maxDomDepth: 0,
501
585
  },
502
- userActivation: false,
586
+ userActivation: options.userActivation ?? false,
503
587
  });
588
+ }
504
589
 
505
- return {
506
- result:
507
- result.type === "success"
508
- ? summarizeBidiRemoteValue(result.result)
509
- : null,
510
- exceptionDetails:
511
- result.type === "exception" ? result.exceptionDetails : null,
512
- realm: result.realm ?? null,
513
- };
590
+ async runPageAction(session, payload, options = {}) {
591
+ const result = await this.evaluateInContext(
592
+ session,
593
+ buildPageContextExpression(
594
+ {
595
+ browserFamily: "firefox",
596
+ ...payload,
597
+ },
598
+ { serialize: true },
599
+ ),
600
+ {
601
+ awaitPromise: true,
602
+ serializationOptions: {
603
+ maxObjectDepth: 1,
604
+ maxDomDepth: 0,
605
+ },
606
+ userActivation: options.userActivation ?? false,
607
+ },
608
+ );
609
+
610
+ if (result.type !== "success") {
611
+ throw new Error(
612
+ result.exceptionDetails?.text || "Firefox page action failed",
613
+ );
614
+ }
615
+
616
+ const payloadText = summarizeBidiRemoteValue(result.result);
617
+ return JSON.parse(payloadText);
514
618
  }
515
619
 
516
620
  async getDocument(sessionId, depth) {
517
621
  const session = this.getSession(sessionId);
518
622
  const requestedDepth = normalizeRequestedDepth(depth);
519
- const result = await this.send("script.evaluate", {
520
- expression: `JSON.stringify({
623
+ const result = await this.evaluateInContext(
624
+ session,
625
+ `JSON.stringify({
521
626
  title: document.title,
522
627
  url: location.href,
523
628
  readyState: document.readyState,
524
629
  requestedDepth: ${JSON.stringify(requestedDepth)},
525
630
  outerHTML: document.documentElement ? document.documentElement.outerHTML : null
526
631
  })`,
527
- target: {
528
- context: session.target.targetId,
529
- },
530
- awaitPromise: true,
531
- resultOwnership: "none",
532
- serializationOptions: {
533
- maxObjectDepth: 1,
534
- maxDomDepth: 0,
632
+ {
633
+ serializationOptions: {
634
+ maxObjectDepth: 1,
635
+ maxDomDepth: 0,
636
+ },
535
637
  },
536
- userActivation: false,
537
- });
638
+ );
538
639
 
539
640
  if (result.type !== "success") {
540
641
  return {
@@ -550,11 +651,219 @@ export class FirefoxBidiSessionManager {
550
651
  };
551
652
  }
552
653
 
553
- async takeScreenshot(sessionId, format) {
654
+ async getPageState(sessionId) {
655
+ const session = this.getSession(sessionId);
656
+ const result = await this.runPageAction(session, {
657
+ action: "page_state",
658
+ });
659
+
660
+ return {
661
+ browserFamily: "firefox",
662
+ ...result.page,
663
+ lastNavigationAt: session.lastNavigationAt,
664
+ lastReloadAt: session.lastReloadAt,
665
+ viewportOverride: session.viewportOverride,
666
+ };
667
+ }
668
+
669
+ async navigate(sessionId, url, options = {}) {
670
+ const session = this.getSession(sessionId);
671
+ const waitUntil = normalizeWaitUntil(options.waitUntil);
672
+ const initiatedAt = new Date().toISOString();
673
+ const result = await this.send("browsingContext.navigate", {
674
+ context: session.target.targetId,
675
+ url,
676
+ wait: waitUntil,
677
+ });
678
+
679
+ session.target.url = url;
680
+ const page =
681
+ waitUntil === "none" ? null : await this.getPageState(sessionId);
682
+ return {
683
+ browserFamily: "firefox",
684
+ url,
685
+ navigation: result.navigation ?? null,
686
+ waitUntil,
687
+ initiatedAt,
688
+ page,
689
+ };
690
+ }
691
+
692
+ async reload(sessionId, options = {}) {
693
+ const session = this.getSession(sessionId);
694
+ const waitUntil = normalizeWaitUntil(options.waitUntil);
695
+ const reloadedAt = new Date().toISOString();
696
+ const result = await this.send("browsingContext.reload", {
697
+ context: session.target.targetId,
698
+ ignoreCache: options.ignoreCache ?? false,
699
+ wait: waitUntil,
700
+ });
701
+
702
+ session.lastReloadAt = reloadedAt;
703
+ const page =
704
+ waitUntil === "none" ? null : await this.getPageState(sessionId);
705
+ return {
706
+ browserFamily: "firefox",
707
+ url: session.target.url,
708
+ navigation: result.navigation ?? null,
709
+ waitUntil,
710
+ ignoreCache: options.ignoreCache ?? false,
711
+ reloadedAt,
712
+ page,
713
+ };
714
+ }
715
+
716
+ async click(sessionId, selector) {
717
+ return this.runPageAction(
718
+ this.getSession(sessionId),
719
+ {
720
+ action: "click",
721
+ selector,
722
+ },
723
+ { userActivation: true },
724
+ );
725
+ }
726
+
727
+ async hover(sessionId, selector) {
728
+ return this.runPageAction(
729
+ this.getSession(sessionId),
730
+ {
731
+ action: "hover",
732
+ selector,
733
+ },
734
+ { userActivation: true },
735
+ );
736
+ }
737
+
738
+ async type(sessionId, selector, text, options = {}) {
739
+ return this.runPageAction(
740
+ this.getSession(sessionId),
741
+ {
742
+ action: "type",
743
+ selector,
744
+ text,
745
+ clear: options.clear,
746
+ },
747
+ { userActivation: true },
748
+ );
749
+ }
750
+
751
+ async select(sessionId, selector, options = {}) {
752
+ return this.runPageAction(
753
+ this.getSession(sessionId),
754
+ {
755
+ action: "select",
756
+ selector,
757
+ value: options.value,
758
+ label: options.label,
759
+ },
760
+ { userActivation: true },
761
+ );
762
+ }
763
+
764
+ async pressKey(sessionId, key, selector = null) {
765
+ return this.runPageAction(
766
+ this.getSession(sessionId),
767
+ {
768
+ action: "press_key",
769
+ key,
770
+ selector,
771
+ },
772
+ { userActivation: true },
773
+ );
774
+ }
775
+
776
+ async scroll(sessionId, options = {}) {
777
+ return this.runPageAction(
778
+ this.getSession(sessionId),
779
+ {
780
+ action: "scroll",
781
+ selector: options.selector,
782
+ deltaX: options.deltaX,
783
+ deltaY: options.deltaY,
784
+ block: options.block,
785
+ },
786
+ { userActivation: true },
787
+ );
788
+ }
789
+
790
+ async setViewport(sessionId, options) {
554
791
  const session = this.getSession(sessionId);
555
- return this.send("browsingContext.captureScreenshot", {
792
+ const params = {
793
+ context: session.target.targetId,
794
+ viewport: {
795
+ width: options.width,
796
+ height: options.height,
797
+ },
798
+ };
799
+
800
+ if (
801
+ typeof options.deviceScaleFactor === "number" &&
802
+ options.deviceScaleFactor > 0
803
+ ) {
804
+ params.devicePixelRatio = options.deviceScaleFactor;
805
+ }
806
+
807
+ await this.send("browsingContext.setViewport", params);
808
+ session.viewportOverride = {
809
+ width: options.width,
810
+ height: options.height,
811
+ deviceScaleFactor: params.devicePixelRatio ?? null,
812
+ mobile: options.mobile ?? false,
813
+ appliedAt: new Date().toISOString(),
814
+ };
815
+
816
+ return {
817
+ browserFamily: "firefox",
818
+ applied: true,
819
+ viewport: session.viewportOverride,
820
+ page: await this.getPageState(sessionId),
821
+ };
822
+ }
823
+
824
+ async takeScreenshot(sessionId, format, options = {}) {
825
+ const session = this.getSession(sessionId);
826
+ const params = {
556
827
  context: session.target.targetId,
557
828
  format: screenshotFormat(format),
829
+ };
830
+
831
+ if (options.selector) {
832
+ const inspected = await this.runPageAction(session, {
833
+ action: "inspect",
834
+ selector: options.selector,
835
+ scrollIntoView: true,
836
+ });
837
+
838
+ if (!inspected.found) {
839
+ return {
840
+ browserFamily: "firefox",
841
+ format,
842
+ scope: "element",
843
+ selector: options.selector,
844
+ found: false,
845
+ };
846
+ }
847
+
848
+ params.origin = "viewport";
849
+ params.clip = {
850
+ type: "box",
851
+ x: Math.max(inspected.node.box?.x ?? 0, 0),
852
+ y: Math.max(inspected.node.box?.y ?? 0, 0),
853
+ width: Math.max(inspected.node.box?.width ?? 0, 1),
854
+ height: Math.max(inspected.node.box?.height ?? 0, 1),
855
+ };
856
+ }
857
+
858
+ const screenshot = await this.send(
859
+ "browsingContext.captureScreenshot",
860
+ params,
861
+ );
862
+ return formatScreenshotResult(screenshot.data, format, {
863
+ browserFamily: "firefox",
864
+ scope: options.selector ? "element" : "page",
865
+ selector: options.selector ?? null,
866
+ clip: params.clip ?? null,
558
867
  });
559
868
  }
560
869
 
@@ -567,62 +876,35 @@ export class FirefoxBidiSessionManager {
567
876
  }
568
877
 
569
878
  async inspectElement(sessionId, selector) {
570
- const session = this.getSession(sessionId);
571
- const result = await this.send("script.evaluate", {
572
- expression: `(() => {
573
- const selector = ${JSON.stringify(selector)};
574
- const element = document.querySelector(selector);
575
- if (!element) {
576
- return JSON.stringify({
577
- browserFamily: "firefox",
578
- selector,
579
- found: false
580
- });
581
- }
879
+ return this.runPageAction(this.getSession(sessionId), {
880
+ action: "inspect",
881
+ selector,
882
+ });
883
+ }
582
884
 
583
- const attributes = Object.fromEntries(
584
- Array.from(element.attributes, (attribute) => [attribute.name, attribute.value])
585
- );
885
+ async seedBufferedState(session) {
886
+ try {
887
+ const snapshot = await this.runPageAction(session, {
888
+ action: "network_snapshot",
889
+ });
586
890
 
587
- return JSON.stringify({
588
- browserFamily: "firefox",
589
- selector,
590
- found: true,
591
- node: {
592
- tagName: element.tagName,
593
- id: element.getAttribute("id"),
594
- className: element.getAttribute("class"),
595
- childElementCount: element.childElementCount,
596
- attributes,
597
- textContent: element.textContent,
598
- innerText: typeof element.innerText === "string" ? element.innerText : null,
599
- outerHTML: element.outerHTML
600
- }
891
+ for (const entry of snapshot?.entries ?? []) {
892
+ session.pushEvent({
893
+ method: "network.snapshotCaptured",
894
+ capturedAt: new Date().toISOString(),
895
+ kind: "network",
896
+ phase: "snapshot",
897
+ completed: true,
898
+ finished: true,
899
+ failed: false,
900
+ canceled: false,
901
+ source: "performance",
902
+ ...entry,
601
903
  });
602
- })()`,
603
- target: {
604
- context: session.target.targetId,
605
- },
606
- awaitPromise: true,
607
- resultOwnership: "none",
608
- serializationOptions: {
609
- maxObjectDepth: 1,
610
- maxDomDepth: 0,
611
- },
612
- userActivation: false,
613
- });
614
-
615
- if (result.type !== "success") {
616
- return {
617
- browserFamily: "firefox",
618
- selector,
619
- found: false,
620
- exceptionDetails: result.exceptionDetails ?? null,
621
- };
904
+ }
905
+ } catch {
906
+ // Ignore snapshot failures so attach still succeeds.
622
907
  }
623
-
624
- const payload = summarizeBidiRemoteValue(result.result);
625
- return JSON.parse(payload);
626
908
  }
627
909
 
628
910
  getEvents(sessionId, limit) {