mcp-browser-dev-tools 0.0.1-beta.1

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.
@@ -0,0 +1,599 @@
1
+ import {
2
+ filterConsoleMessages,
3
+ summarizeNetworkRequests,
4
+ } from "./session-events.mjs";
5
+
6
+ function toErrorMessage(error) {
7
+ return error instanceof Error ? error.message : String(error);
8
+ }
9
+
10
+ function normalizeTarget(target) {
11
+ return {
12
+ targetId: target.id,
13
+ type: target.type,
14
+ title: target.title,
15
+ url: target.url,
16
+ attached: Boolean(target.attached),
17
+ webSocketDebuggerUrl: target.webSocketDebuggerUrl,
18
+ };
19
+ }
20
+
21
+ function summarizeRemoteObject(object) {
22
+ if (!object) {
23
+ return null;
24
+ }
25
+
26
+ if (object.value !== undefined) {
27
+ return object.value;
28
+ }
29
+
30
+ if (object.description) {
31
+ return object.description;
32
+ }
33
+
34
+ if (object.unserializableValue) {
35
+ return object.unserializableValue;
36
+ }
37
+
38
+ return {
39
+ type: object.type,
40
+ subtype: object.subtype,
41
+ className: object.className,
42
+ };
43
+ }
44
+
45
+ function toAttributeObject(attributes = []) {
46
+ const result = {};
47
+ for (let index = 0; index < attributes.length; index += 2) {
48
+ result[attributes[index]] = attributes[index + 1] ?? "";
49
+ }
50
+
51
+ return result;
52
+ }
53
+
54
+ function normalizeEvent(method, params) {
55
+ if (method === "Runtime.consoleAPICalled") {
56
+ return {
57
+ kind: "console",
58
+ level: params.type,
59
+ timestamp: params.timestamp,
60
+ values: (params.args || []).map(summarizeRemoteObject),
61
+ };
62
+ }
63
+
64
+ if (method === "Runtime.exceptionThrown") {
65
+ return {
66
+ kind: "exception",
67
+ timestamp: params.timestamp,
68
+ text: params.exceptionDetails?.text,
69
+ url: params.exceptionDetails?.url,
70
+ lineNumber: params.exceptionDetails?.lineNumber,
71
+ columnNumber: params.exceptionDetails?.columnNumber,
72
+ };
73
+ }
74
+
75
+ if (method === "Log.entryAdded") {
76
+ return {
77
+ kind: "log",
78
+ level: params.entry?.level,
79
+ text: params.entry?.text,
80
+ url: params.entry?.url,
81
+ timestamp: params.entry?.timestamp,
82
+ };
83
+ }
84
+
85
+ if (method === "Network.requestWillBeSent") {
86
+ return {
87
+ kind: "network",
88
+ phase: "request",
89
+ completed: false,
90
+ timestamp: params.timestamp,
91
+ requestId: params.requestId,
92
+ method: params.request?.method,
93
+ url: params.request?.url,
94
+ resourceType: params.type,
95
+ };
96
+ }
97
+
98
+ if (method === "Network.responseReceived") {
99
+ return {
100
+ kind: "network",
101
+ phase: "response",
102
+ completed: false,
103
+ timestamp: params.timestamp,
104
+ requestId: params.requestId,
105
+ url: params.response?.url,
106
+ resourceType: params.type,
107
+ status: params.response?.status,
108
+ statusText: params.response?.statusText,
109
+ mimeType: params.response?.mimeType,
110
+ };
111
+ }
112
+
113
+ if (method === "Network.loadingFinished") {
114
+ return {
115
+ kind: "network",
116
+ phase: "finished",
117
+ completed: true,
118
+ failed: false,
119
+ timestamp: params.timestamp,
120
+ requestId: params.requestId,
121
+ };
122
+ }
123
+
124
+ if (method === "Network.loadingFailed") {
125
+ return {
126
+ kind: "network",
127
+ phase: "failed",
128
+ completed: true,
129
+ failed: true,
130
+ timestamp: params.timestamp,
131
+ requestId: params.requestId,
132
+ errorText: params.errorText,
133
+ canceled: params.canceled ?? false,
134
+ };
135
+ }
136
+
137
+ return {
138
+ kind: "raw",
139
+ method,
140
+ params,
141
+ };
142
+ }
143
+
144
+ async function parseJson(response) {
145
+ if (!response.ok) {
146
+ throw new Error(
147
+ `CDP endpoint returned ${response.status} ${response.statusText}`,
148
+ );
149
+ }
150
+
151
+ return response.json();
152
+ }
153
+
154
+ async function readWebSocketData(data) {
155
+ if (typeof data === "string") {
156
+ return data;
157
+ }
158
+
159
+ if (data instanceof ArrayBuffer) {
160
+ return Buffer.from(data).toString("utf8");
161
+ }
162
+
163
+ if (ArrayBuffer.isView(data)) {
164
+ return Buffer.from(data.buffer, data.byteOffset, data.byteLength).toString(
165
+ "utf8",
166
+ );
167
+ }
168
+
169
+ if (typeof data?.text === "function") {
170
+ return data.text();
171
+ }
172
+
173
+ return String(data);
174
+ }
175
+
176
+ export class CdpSession {
177
+ constructor(target, options = {}) {
178
+ this.id = crypto.randomUUID();
179
+ this.target = target;
180
+ this.eventBufferSize = options.eventBufferSize ?? 200;
181
+ this.onClosed = options.onClosed ?? null;
182
+ this.bufferedEvents = [];
183
+ this.pending = new Map();
184
+ this.nextMessageId = 1;
185
+ this.connectedAt = new Date().toISOString();
186
+ this.websocket = null;
187
+ this.closed = false;
188
+ }
189
+
190
+ markClosed() {
191
+ if (this.closed) {
192
+ return;
193
+ }
194
+
195
+ this.closed = true;
196
+ this.rejectPending(new Error("CDP session closed"));
197
+ this.onClosed?.(this);
198
+ }
199
+
200
+ async connect() {
201
+ if (!this.target.webSocketDebuggerUrl) {
202
+ throw new Error(
203
+ `Target ${this.target.targetId} does not expose a debugger websocket`,
204
+ );
205
+ }
206
+
207
+ this.websocket = new WebSocket(this.target.webSocketDebuggerUrl);
208
+
209
+ await new Promise((resolve, reject) => {
210
+ let settled = false;
211
+
212
+ this.websocket.addEventListener(
213
+ "open",
214
+ () => {
215
+ if (settled) {
216
+ return;
217
+ }
218
+ settled = true;
219
+ resolve();
220
+ },
221
+ { once: true },
222
+ );
223
+
224
+ this.websocket.addEventListener(
225
+ "error",
226
+ () => {
227
+ if (settled) {
228
+ return;
229
+ }
230
+ settled = true;
231
+ reject(
232
+ new Error(
233
+ `Failed to connect to ${this.target.webSocketDebuggerUrl}`,
234
+ ),
235
+ );
236
+ },
237
+ { once: true },
238
+ );
239
+
240
+ this.websocket.addEventListener("close", () => {
241
+ this.markClosed();
242
+ if (!settled) {
243
+ settled = true;
244
+ reject(new Error(`Debugger websocket closed before it connected`));
245
+ }
246
+ });
247
+
248
+ this.websocket.addEventListener("message", (event) => {
249
+ void this.handleMessage(event.data);
250
+ });
251
+ });
252
+
253
+ await Promise.all([
254
+ this.send("Page.enable"),
255
+ this.send("Runtime.enable"),
256
+ this.send("DOM.enable"),
257
+ this.send("Log.enable"),
258
+ this.send("Network.enable"),
259
+ ]);
260
+
261
+ return this.getSummary();
262
+ }
263
+
264
+ async handleMessage(data) {
265
+ const raw = await readWebSocketData(data);
266
+ const message = JSON.parse(raw);
267
+
268
+ if (message.id) {
269
+ const pending = this.pending.get(message.id);
270
+ if (!pending) {
271
+ return;
272
+ }
273
+
274
+ this.pending.delete(message.id);
275
+ if (message.error) {
276
+ pending.reject(
277
+ new Error(`${message.error.message} (code ${message.error.code})`),
278
+ );
279
+ return;
280
+ }
281
+
282
+ pending.resolve(message.result);
283
+ return;
284
+ }
285
+
286
+ if (!message.method) {
287
+ return;
288
+ }
289
+
290
+ this.bufferEvent(message.method, message.params ?? {});
291
+ }
292
+
293
+ bufferEvent(method, params) {
294
+ this.bufferedEvents.push({
295
+ method,
296
+ capturedAt: new Date().toISOString(),
297
+ ...normalizeEvent(method, params),
298
+ });
299
+
300
+ if (this.bufferedEvents.length > this.eventBufferSize) {
301
+ this.bufferedEvents.shift();
302
+ }
303
+ }
304
+
305
+ rejectPending(error) {
306
+ for (const pending of this.pending.values()) {
307
+ pending.reject(error);
308
+ }
309
+ this.pending.clear();
310
+ }
311
+
312
+ send(method, params = {}) {
313
+ if (!this.websocket || this.websocket.readyState !== WebSocket.OPEN) {
314
+ throw new Error(`CDP session ${this.id} is not connected`);
315
+ }
316
+
317
+ const id = this.nextMessageId++;
318
+ const payload = JSON.stringify({ id, method, params });
319
+
320
+ return new Promise((resolve, reject) => {
321
+ this.pending.set(id, { resolve, reject });
322
+ try {
323
+ this.websocket.send(payload);
324
+ } catch (error) {
325
+ this.pending.delete(id);
326
+ reject(error);
327
+ }
328
+ });
329
+ }
330
+
331
+ async evaluate(expression, options = {}) {
332
+ const result = await this.send("Runtime.evaluate", {
333
+ expression,
334
+ awaitPromise: options.awaitPromise ?? true,
335
+ returnByValue: options.returnByValue ?? true,
336
+ replMode: true,
337
+ });
338
+
339
+ return {
340
+ result: summarizeRemoteObject(result.result),
341
+ exceptionDetails: result.exceptionDetails ?? null,
342
+ };
343
+ }
344
+
345
+ async getDocument(depth = 2) {
346
+ return this.send("DOM.getDocument", {
347
+ depth,
348
+ pierce: true,
349
+ });
350
+ }
351
+
352
+ async takeScreenshot(format = "png") {
353
+ return this.send("Page.captureScreenshot", { format });
354
+ }
355
+
356
+ getConsoleMessages(limit = 50) {
357
+ return filterConsoleMessages(this.bufferedEvents, limit);
358
+ }
359
+
360
+ getNetworkRequests(limit = 50) {
361
+ return summarizeNetworkRequests(this.bufferedEvents, limit);
362
+ }
363
+
364
+ async inspectElement(selector) {
365
+ const document = await this.getDocument(1);
366
+ const rootNodeId = document.root?.nodeId;
367
+ if (!rootNodeId) {
368
+ throw new Error("Unable to resolve the DOM root node");
369
+ }
370
+
371
+ const { nodeId } = await this.send("DOM.querySelector", {
372
+ nodeId: rootNodeId,
373
+ selector,
374
+ });
375
+
376
+ if (!nodeId) {
377
+ return {
378
+ browserFamily: "chromium",
379
+ selector,
380
+ found: false,
381
+ };
382
+ }
383
+
384
+ const [description, attributes, outerHtml, textContent] = await Promise.all(
385
+ [
386
+ this.send("DOM.describeNode", {
387
+ nodeId,
388
+ depth: 1,
389
+ pierce: true,
390
+ }),
391
+ this.send("DOM.getAttributes", { nodeId }),
392
+ this.send("DOM.getOuterHTML", { nodeId }),
393
+ this.readNodeText(nodeId),
394
+ ],
395
+ );
396
+
397
+ return {
398
+ browserFamily: "chromium",
399
+ selector,
400
+ found: true,
401
+ node: {
402
+ nodeId,
403
+ backendNodeId: description.node?.backendNodeId ?? null,
404
+ nodeName: description.node?.nodeName ?? null,
405
+ localName: description.node?.localName ?? null,
406
+ nodeType: description.node?.nodeType ?? null,
407
+ childNodeCount: description.node?.childNodeCount ?? 0,
408
+ attributes: toAttributeObject(attributes.attributes),
409
+ textContent: textContent.textContent,
410
+ innerText: textContent.innerText,
411
+ outerHTML: outerHtml.outerHTML ?? null,
412
+ },
413
+ };
414
+ }
415
+
416
+ async readNodeText(nodeId) {
417
+ let objectId = null;
418
+
419
+ try {
420
+ const resolved = await this.send("DOM.resolveNode", { nodeId });
421
+ objectId = resolved.object?.objectId ?? null;
422
+ if (!objectId) {
423
+ return {
424
+ textContent: null,
425
+ innerText: null,
426
+ };
427
+ }
428
+
429
+ const result = await this.send("Runtime.callFunctionOn", {
430
+ objectId,
431
+ functionDeclaration:
432
+ "function() { return { textContent: this.textContent ?? null, innerText: typeof this.innerText === 'string' ? this.innerText : null }; }",
433
+ returnByValue: true,
434
+ silent: true,
435
+ });
436
+
437
+ return (
438
+ result.result?.value ?? {
439
+ textContent: null,
440
+ innerText: null,
441
+ }
442
+ );
443
+ } catch {
444
+ return {
445
+ textContent: null,
446
+ innerText: null,
447
+ };
448
+ } finally {
449
+ if (objectId) {
450
+ await this.send("Runtime.releaseObject", { objectId }).catch(() => {});
451
+ }
452
+ }
453
+ }
454
+
455
+ getEvents(limit = 50) {
456
+ const safeLimit = Math.max(1, limit);
457
+ return this.bufferedEvents.slice(-safeLimit);
458
+ }
459
+
460
+ getSummary() {
461
+ return {
462
+ sessionId: this.id,
463
+ targetId: this.target.targetId,
464
+ title: this.target.title,
465
+ url: this.target.url,
466
+ browserFamily: "chromium",
467
+ connectedAt: this.connectedAt,
468
+ bufferedEvents: this.bufferedEvents.length,
469
+ };
470
+ }
471
+
472
+ async close() {
473
+ if (!this.websocket || this.websocket.readyState >= WebSocket.CLOSING) {
474
+ this.markClosed();
475
+ return;
476
+ }
477
+
478
+ this.websocket.close();
479
+ }
480
+ }
481
+
482
+ export class CdpSessionManager {
483
+ constructor(config) {
484
+ this.config = config;
485
+ this.sessions = new Map();
486
+ }
487
+
488
+ async fetchJson(pathname) {
489
+ const url = new URL(pathname, `${this.config.cdpBaseUrl}/`);
490
+ const response = await fetch(url);
491
+ return parseJson(response);
492
+ }
493
+
494
+ async getBrowserStatus() {
495
+ try {
496
+ const info = await this.fetchJson("/json/version");
497
+ return {
498
+ available: true,
499
+ endpoint: this.config.cdpBaseUrl,
500
+ sessionCount: this.sessions.size,
501
+ browser: info.Browser,
502
+ protocolVersion: info["Protocol-Version"],
503
+ userAgent: info["User-Agent"],
504
+ };
505
+ } catch (error) {
506
+ return {
507
+ available: false,
508
+ endpoint: this.config.cdpBaseUrl,
509
+ sessionCount: this.sessions.size,
510
+ error: toErrorMessage(error),
511
+ };
512
+ }
513
+ }
514
+
515
+ async listTargets() {
516
+ const targets = await this.fetchJson("/json/list");
517
+ return targets
518
+ .filter((target) => target.type === "page")
519
+ .map(normalizeTarget);
520
+ }
521
+
522
+ listSessions() {
523
+ return Array.from(this.sessions.values(), (session) =>
524
+ session.getSummary(),
525
+ );
526
+ }
527
+
528
+ async attachToTarget(targetId) {
529
+ const targets = await this.listTargets();
530
+ const target = targets.find((candidate) => candidate.targetId === targetId);
531
+ if (!target) {
532
+ throw new Error(`No page target found for ${targetId}`);
533
+ }
534
+
535
+ const session = new CdpSession(target, {
536
+ eventBufferSize: this.config.eventBufferSize,
537
+ onClosed: (closedSession) => {
538
+ this.sessions.delete(closedSession.id);
539
+ },
540
+ });
541
+ await session.connect();
542
+ this.sessions.set(session.id, session);
543
+ return session.getSummary();
544
+ }
545
+
546
+ getSession(sessionId) {
547
+ const session = this.sessions.get(sessionId);
548
+ if (!session) {
549
+ throw new Error(`No active session found for ${sessionId}`);
550
+ }
551
+
552
+ return session;
553
+ }
554
+
555
+ async detachSession(sessionId) {
556
+ const session = this.getSession(sessionId);
557
+ await session.close();
558
+ this.sessions.delete(sessionId);
559
+ return {
560
+ detached: true,
561
+ sessionId,
562
+ };
563
+ }
564
+
565
+ async evaluate(sessionId, expression, options) {
566
+ return this.getSession(sessionId).evaluate(expression, options);
567
+ }
568
+
569
+ async getDocument(sessionId, depth) {
570
+ return this.getSession(sessionId).getDocument(depth);
571
+ }
572
+
573
+ async takeScreenshot(sessionId, format) {
574
+ return this.getSession(sessionId).takeScreenshot(format);
575
+ }
576
+
577
+ getConsoleMessages(sessionId, limit) {
578
+ return this.getSession(sessionId).getConsoleMessages(limit);
579
+ }
580
+
581
+ getNetworkRequests(sessionId, limit) {
582
+ return this.getSession(sessionId).getNetworkRequests(limit);
583
+ }
584
+
585
+ async inspectElement(sessionId, selector) {
586
+ return this.getSession(sessionId).inspectElement(selector);
587
+ }
588
+
589
+ getEvents(sessionId, limit) {
590
+ return this.getSession(sessionId).getEvents(limit);
591
+ }
592
+
593
+ async closeAll() {
594
+ await Promise.allSettled(
595
+ Array.from(this.sessions.values(), (session) => session.close()),
596
+ );
597
+ this.sessions.clear();
598
+ }
599
+ }