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

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,734 @@
1
+ function buildPayloadLiteral(payload) {
2
+ return JSON.stringify(payload);
3
+ }
4
+
5
+ export function buildPageContextExpression(
6
+ payload,
7
+ { serialize = false } = {},
8
+ ) {
9
+ const body = `(() => {
10
+ const payload = ${buildPayloadLiteral(payload)};
11
+ const TEXT_LIMIT = 400;
12
+
13
+ function clipText(value, limit = TEXT_LIMIT) {
14
+ if (typeof value !== "string") {
15
+ return value ?? null;
16
+ }
17
+
18
+ return value.length > limit ? \`\${value.slice(0, limit)}...\` : value;
19
+ }
20
+
21
+ function normalizeText(value) {
22
+ return typeof value === "string"
23
+ ? value.replace(/\\s+/g, " ").trim()
24
+ : "";
25
+ }
26
+
27
+ function getVisibleText(element) {
28
+ if (!element) {
29
+ return "";
30
+ }
31
+
32
+ if (typeof element.innerText === "string" && element.innerText.trim()) {
33
+ return element.innerText;
34
+ }
35
+
36
+ return element.textContent ?? "";
37
+ }
38
+
39
+ function getLabelTextForControl(element) {
40
+ if (!element || !element.id) {
41
+ return "";
42
+ }
43
+
44
+ const label = document.querySelector(\`label[for="\${CSS.escape(element.id)}"]\`);
45
+ return label ? normalizeText(getVisibleText(label)) : "";
46
+ }
47
+
48
+ function getAccessibleName(element) {
49
+ if (!element) {
50
+ return "";
51
+ }
52
+
53
+ const ariaLabel = element.getAttribute("aria-label");
54
+ if (ariaLabel) {
55
+ return normalizeText(ariaLabel);
56
+ }
57
+
58
+ const labelledBy = element.getAttribute("aria-labelledby");
59
+ if (labelledBy) {
60
+ const text = labelledBy
61
+ .split(/\\s+/)
62
+ .map((id) => document.getElementById(id))
63
+ .filter(Boolean)
64
+ .map((node) => normalizeText(getVisibleText(node)))
65
+ .filter(Boolean)
66
+ .join(" ");
67
+ if (text) {
68
+ return text;
69
+ }
70
+ }
71
+
72
+ const labelText = getLabelTextForControl(element);
73
+ if (labelText) {
74
+ return labelText;
75
+ }
76
+
77
+ const alt = element.getAttribute("alt");
78
+ if (alt) {
79
+ return normalizeText(alt);
80
+ }
81
+
82
+ const title = element.getAttribute("title");
83
+ if (title) {
84
+ return normalizeText(title);
85
+ }
86
+
87
+ if (
88
+ element instanceof HTMLInputElement ||
89
+ element instanceof HTMLTextAreaElement
90
+ ) {
91
+ return normalizeText(element.value);
92
+ }
93
+
94
+ return normalizeText(getVisibleText(element));
95
+ }
96
+
97
+ function inferRole(element) {
98
+ if (!element) {
99
+ return null;
100
+ }
101
+
102
+ const explicitRole = element.getAttribute("role");
103
+ if (explicitRole) {
104
+ return explicitRole;
105
+ }
106
+
107
+ const tag = element.tagName.toLowerCase();
108
+ if (tag === "a" && element.hasAttribute("href")) return "link";
109
+ if (tag === "button") return "button";
110
+ if (tag === "dialog") return "dialog";
111
+ if (tag === "img") return "img";
112
+ if (tag === "select") return "combobox";
113
+ if (tag === "textarea") return "textbox";
114
+ if (tag === "option") return "option";
115
+ if (tag === "ul" || tag === "ol") return "list";
116
+ if (tag === "li") return "listitem";
117
+ if (tag === "input") {
118
+ const type = (element.getAttribute("type") || "text").toLowerCase();
119
+ if (type === "button" || type === "submit" || type === "reset") return "button";
120
+ if (type === "checkbox") return "checkbox";
121
+ if (type === "radio") return "radio";
122
+ if (type === "range") return "slider";
123
+ return "textbox";
124
+ }
125
+
126
+ return null;
127
+ }
128
+
129
+ function isVisible(element) {
130
+ if (!element) {
131
+ return false;
132
+ }
133
+
134
+ const style = getComputedStyle(element);
135
+ const rect = element.getBoundingClientRect();
136
+ if (
137
+ element.hidden ||
138
+ element.getAttribute("aria-hidden") === "true" ||
139
+ style.display === "none" ||
140
+ style.visibility === "hidden" ||
141
+ style.visibility === "collapse" ||
142
+ style.pointerEvents === "none"
143
+ ) {
144
+ return false;
145
+ }
146
+
147
+ return rect.width > 0 && rect.height > 0;
148
+ }
149
+
150
+ function isDisabled(element) {
151
+ return Boolean(
152
+ element &&
153
+ (element.disabled === true ||
154
+ element.getAttribute("aria-disabled") === "true"),
155
+ );
156
+ }
157
+
158
+ function isEditable(element) {
159
+ return Boolean(
160
+ element &&
161
+ (element.isContentEditable ||
162
+ element instanceof HTMLTextAreaElement ||
163
+ (element instanceof HTMLInputElement &&
164
+ !["button", "submit", "reset", "checkbox", "radio", "file"].includes(
165
+ (element.type || "text").toLowerCase(),
166
+ ))),
167
+ );
168
+ }
169
+
170
+ function isFocusable(element) {
171
+ if (!element || isDisabled(element)) {
172
+ return false;
173
+ }
174
+
175
+ if (typeof element.tabIndex === "number" && element.tabIndex >= 0) {
176
+ return true;
177
+ }
178
+
179
+ const tag = element.tagName.toLowerCase();
180
+ return ["a", "button", "input", "select", "textarea"].includes(tag);
181
+ }
182
+
183
+ function isClickable(element) {
184
+ if (!element || isDisabled(element)) {
185
+ return false;
186
+ }
187
+
188
+ const role = inferRole(element);
189
+ const tag = element.tagName.toLowerCase();
190
+ return (
191
+ ["button", "link", "checkbox", "radio", "option"].includes(role) ||
192
+ ["button", "a", "summary", "option"].includes(tag) ||
193
+ typeof element.onclick === "function"
194
+ );
195
+ }
196
+
197
+ function isScrollable(element) {
198
+ if (!element) {
199
+ return false;
200
+ }
201
+
202
+ return (
203
+ element.scrollHeight > element.clientHeight ||
204
+ element.scrollWidth > element.clientWidth
205
+ );
206
+ }
207
+
208
+ function toAttributeObject(element) {
209
+ return Object.fromEntries(
210
+ Array.from(element.attributes, (attribute) => [
211
+ attribute.name,
212
+ attribute.value,
213
+ ]),
214
+ );
215
+ }
216
+
217
+ function summarizeLocator(locator) {
218
+ if (!locator || typeof locator !== "object") {
219
+ return null;
220
+ }
221
+
222
+ const summary = {};
223
+ for (const key of ["locator", "strategy", "query", "role", "name", "error"]) {
224
+ if (locator[key] !== undefined) {
225
+ summary[key] = locator[key];
226
+ }
227
+ }
228
+
229
+ return summary;
230
+ }
231
+
232
+ function describeElement(element, locator) {
233
+ const rect = element.getBoundingClientRect();
234
+ const style = getComputedStyle(element);
235
+ const role = inferRole(element);
236
+ const accessibleName = getAccessibleName(element);
237
+
238
+ return {
239
+ locator: summarizeLocator(locator),
240
+ tagName: element.tagName,
241
+ id: element.getAttribute("id"),
242
+ className: element.getAttribute("class"),
243
+ childElementCount: element.childElementCount,
244
+ attributes: toAttributeObject(element),
245
+ textContent: clipText(element.textContent ?? null),
246
+ innerText: clipText(
247
+ typeof element.innerText === "string" ? element.innerText : null,
248
+ ),
249
+ value:
250
+ "value" in element && typeof element.value === "string"
251
+ ? clipText(element.value)
252
+ : null,
253
+ accessibleName: accessibleName || null,
254
+ role,
255
+ visible: isVisible(element),
256
+ disabled: isDisabled(element),
257
+ focused: document.activeElement === element,
258
+ editable: isEditable(element),
259
+ focusable: isFocusable(element),
260
+ clickable: isClickable(element),
261
+ scrollable: isScrollable(element),
262
+ checked: "checked" in element ? Boolean(element.checked) : null,
263
+ selected: "selected" in element ? Boolean(element.selected) : null,
264
+ open: "open" in element ? Boolean(element.open) : null,
265
+ box: {
266
+ x: rect.x,
267
+ y: rect.y,
268
+ width: rect.width,
269
+ height: rect.height,
270
+ top: rect.top,
271
+ right: rect.right,
272
+ bottom: rect.bottom,
273
+ left: rect.left,
274
+ },
275
+ styles: {
276
+ display: style.display,
277
+ visibility: style.visibility,
278
+ position: style.position,
279
+ zIndex: style.zIndex,
280
+ overflowX: style.overflowX,
281
+ overflowY: style.overflowY,
282
+ opacity: style.opacity,
283
+ pointerEvents: style.pointerEvents,
284
+ },
285
+ outerHTML: clipText(element.outerHTML, 1200),
286
+ };
287
+ }
288
+
289
+ function parseRoleLocator(value) {
290
+ const match = value.match(/^([^\\[]+?)(?:\\[name=(?:"([^"]*)"|'([^']*)')\\])?$/);
291
+ if (!match) {
292
+ return {
293
+ role: normalizeText(value) || null,
294
+ name: null,
295
+ };
296
+ }
297
+
298
+ return {
299
+ role: normalizeText(match[1]) || null,
300
+ name: normalizeText(match[2] ?? match[3] ?? "") || null,
301
+ };
302
+ }
303
+
304
+ function collectCandidates() {
305
+ return Array.from(
306
+ document.querySelectorAll("body *"),
307
+ );
308
+ }
309
+
310
+ function describePage() {
311
+ return {
312
+ url: location.href,
313
+ title: document.title,
314
+ readyState: document.readyState,
315
+ visibilityState: document.visibilityState,
316
+ viewport: {
317
+ width: window.innerWidth,
318
+ height: window.innerHeight,
319
+ devicePixelRatio: window.devicePixelRatio,
320
+ },
321
+ scroll: {
322
+ x: window.scrollX,
323
+ y: window.scrollY,
324
+ },
325
+ };
326
+ }
327
+
328
+ function resolveLocator(rawLocator) {
329
+ const locator = typeof rawLocator === "string" ? rawLocator.trim() : "";
330
+ if (!locator) {
331
+ throw new Error("selector must be a non-empty string");
332
+ }
333
+
334
+ if (locator.startsWith("text=")) {
335
+ const query = normalizeText(locator.slice(5));
336
+ const candidates = collectCandidates();
337
+ const match =
338
+ candidates.find(
339
+ (element) =>
340
+ isVisible(element) &&
341
+ normalizeText(getVisibleText(element)) === query,
342
+ ) ??
343
+ candidates.find((element) => {
344
+ const text = normalizeText(getVisibleText(element));
345
+ return isVisible(element) && text && text.includes(query);
346
+ });
347
+
348
+ return {
349
+ locator,
350
+ strategy: "text",
351
+ query,
352
+ element: match ?? null,
353
+ };
354
+ }
355
+
356
+ if (locator.startsWith("role=")) {
357
+ const { role, name } = parseRoleLocator(locator.slice(5).trim());
358
+ const candidates = collectCandidates();
359
+ const match = candidates.find((element) => {
360
+ const elementRole = normalizeText(inferRole(element) ?? "");
361
+ const accessibleName = normalizeText(getAccessibleName(element));
362
+ if (!elementRole || elementRole !== role) {
363
+ return false;
364
+ }
365
+
366
+ if (!name) {
367
+ return true;
368
+ }
369
+
370
+ return accessibleName === name || accessibleName.includes(name);
371
+ });
372
+
373
+ return {
374
+ locator,
375
+ strategy: "role",
376
+ role,
377
+ name,
378
+ element: match ?? null,
379
+ };
380
+ }
381
+
382
+ if (locator.startsWith("name=")) {
383
+ const query = normalizeText(locator.slice(5));
384
+ const candidates = collectCandidates();
385
+ const match =
386
+ candidates.find((element) => {
387
+ const accessibleName = normalizeText(getAccessibleName(element));
388
+ return isVisible(element) && accessibleName === query;
389
+ }) ??
390
+ candidates.find((element) => {
391
+ const accessibleName = normalizeText(getAccessibleName(element));
392
+ return (
393
+ isVisible(element) && accessibleName && accessibleName.includes(query)
394
+ );
395
+ });
396
+
397
+ return {
398
+ locator,
399
+ strategy: "name",
400
+ query,
401
+ element: match ?? null,
402
+ };
403
+ }
404
+
405
+ const cssSelector = locator.startsWith("css=") ? locator.slice(4) : locator;
406
+ try {
407
+ return {
408
+ locator,
409
+ strategy: "css",
410
+ query: cssSelector,
411
+ element: document.querySelector(cssSelector),
412
+ };
413
+ } catch (error) {
414
+ return {
415
+ locator,
416
+ strategy: "css",
417
+ query: cssSelector,
418
+ element: null,
419
+ error: error instanceof Error ? error.message : String(error),
420
+ };
421
+ }
422
+ }
423
+
424
+ function ensureResolved(rawLocator) {
425
+ const resolved = resolveLocator(rawLocator);
426
+ if (resolved.error) {
427
+ return {
428
+ browserFamily: payload.browserFamily,
429
+ selector: rawLocator,
430
+ found: false,
431
+ locator: summarizeLocator(resolved),
432
+ error: resolved.error,
433
+ };
434
+ }
435
+
436
+ if (!resolved.element) {
437
+ return {
438
+ browserFamily: payload.browserFamily,
439
+ selector: rawLocator,
440
+ found: false,
441
+ locator: summarizeLocator(resolved),
442
+ };
443
+ }
444
+
445
+ return resolved;
446
+ }
447
+
448
+ function dispatchInputEvents(element) {
449
+ element.dispatchEvent(new Event("input", { bubbles: true, composed: true }));
450
+ element.dispatchEvent(new Event("change", { bubbles: true, composed: true }));
451
+ }
452
+
453
+ function maybeScrollIntoView(element) {
454
+ if (!element || payload.scrollIntoView === false) {
455
+ return;
456
+ }
457
+
458
+ element.scrollIntoView({ block: "center", inline: "center" });
459
+ }
460
+
461
+ function pressKeyOnTarget(target, key) {
462
+ const eventInit = {
463
+ key,
464
+ bubbles: true,
465
+ cancelable: true,
466
+ composed: true,
467
+ };
468
+ target.dispatchEvent(new KeyboardEvent("keydown", eventInit));
469
+ target.dispatchEvent(new KeyboardEvent("keypress", eventInit));
470
+ target.dispatchEvent(new KeyboardEvent("keyup", eventInit));
471
+ }
472
+
473
+ function runAction() {
474
+ switch (payload.action) {
475
+ case "page_state":
476
+ return {
477
+ browserFamily: payload.browserFamily,
478
+ page: describePage(),
479
+ };
480
+ case "inspect": {
481
+ const resolved = ensureResolved(payload.selector);
482
+ if (!resolved.element) {
483
+ return resolved;
484
+ }
485
+
486
+ maybeScrollIntoView(resolved.element);
487
+
488
+ return {
489
+ browserFamily: payload.browserFamily,
490
+ selector: payload.selector,
491
+ found: true,
492
+ node: describeElement(resolved.element, resolved),
493
+ };
494
+ }
495
+ case "click": {
496
+ const resolved = ensureResolved(payload.selector);
497
+ if (!resolved.element) {
498
+ return resolved;
499
+ }
500
+
501
+ maybeScrollIntoView(resolved.element);
502
+ if (typeof resolved.element.focus === "function") {
503
+ resolved.element.focus();
504
+ }
505
+
506
+ if (typeof resolved.element.click === "function") {
507
+ resolved.element.click();
508
+ } else {
509
+ resolved.element.dispatchEvent(
510
+ new MouseEvent("click", {
511
+ bubbles: true,
512
+ cancelable: true,
513
+ composed: true,
514
+ }),
515
+ );
516
+ }
517
+
518
+ return {
519
+ browserFamily: payload.browserFamily,
520
+ selector: payload.selector,
521
+ found: true,
522
+ clicked: true,
523
+ node: describeElement(resolved.element, resolved),
524
+ };
525
+ }
526
+ case "hover": {
527
+ const resolved = ensureResolved(payload.selector);
528
+ if (!resolved.element) {
529
+ return resolved;
530
+ }
531
+
532
+ maybeScrollIntoView(resolved.element);
533
+ const eventInit = {
534
+ bubbles: true,
535
+ cancelable: true,
536
+ composed: true,
537
+ };
538
+ resolved.element.dispatchEvent(new MouseEvent("mouseover", eventInit));
539
+ resolved.element.dispatchEvent(new MouseEvent("mouseenter", eventInit));
540
+ resolved.element.dispatchEvent(new MouseEvent("mousemove", eventInit));
541
+
542
+ return {
543
+ browserFamily: payload.browserFamily,
544
+ selector: payload.selector,
545
+ found: true,
546
+ hovered: true,
547
+ node: describeElement(resolved.element, resolved),
548
+ };
549
+ }
550
+ case "type": {
551
+ const resolved = ensureResolved(payload.selector);
552
+ if (!resolved.element) {
553
+ return resolved;
554
+ }
555
+
556
+ const clear = payload.clear !== false;
557
+ maybeScrollIntoView(resolved.element);
558
+ if (typeof resolved.element.focus === "function") {
559
+ resolved.element.focus();
560
+ }
561
+
562
+ if (
563
+ resolved.element instanceof HTMLInputElement ||
564
+ resolved.element instanceof HTMLTextAreaElement
565
+ ) {
566
+ resolved.element.value = clear
567
+ ? payload.text
568
+ : \`\${resolved.element.value}\${payload.text}\`;
569
+ dispatchInputEvents(resolved.element);
570
+ } else if (resolved.element.isContentEditable) {
571
+ resolved.element.textContent = clear
572
+ ? payload.text
573
+ : \`\${resolved.element.textContent ?? ""}\${payload.text}\`;
574
+ dispatchInputEvents(resolved.element);
575
+ } else {
576
+ throw new Error("Resolved element is not editable");
577
+ }
578
+
579
+ return {
580
+ browserFamily: payload.browserFamily,
581
+ selector: payload.selector,
582
+ found: true,
583
+ typedText: payload.text,
584
+ node: describeElement(resolved.element, resolved),
585
+ };
586
+ }
587
+ case "select": {
588
+ const resolved = ensureResolved(payload.selector);
589
+ if (!resolved.element) {
590
+ return resolved;
591
+ }
592
+
593
+ if (!(resolved.element instanceof HTMLSelectElement)) {
594
+ throw new Error("Resolved element is not a <select>");
595
+ }
596
+
597
+ const option =
598
+ Array.from(resolved.element.options).find(
599
+ (candidate) =>
600
+ (payload.value &&
601
+ (candidate.value === payload.value ||
602
+ candidate.text === payload.value)) ||
603
+ (payload.label &&
604
+ normalizeText(candidate.text).includes(
605
+ normalizeText(payload.label),
606
+ )),
607
+ ) ?? null;
608
+
609
+ if (!option) {
610
+ throw new Error("No matching <option> found");
611
+ }
612
+
613
+ resolved.element.value = option.value;
614
+ dispatchInputEvents(resolved.element);
615
+
616
+ return {
617
+ browserFamily: payload.browserFamily,
618
+ selector: payload.selector,
619
+ found: true,
620
+ selectedValue: option.value,
621
+ selectedLabel: option.text,
622
+ node: describeElement(resolved.element, resolved),
623
+ };
624
+ }
625
+ case "press_key": {
626
+ let target = document.activeElement instanceof HTMLElement
627
+ ? document.activeElement
628
+ : document.body;
629
+
630
+ if (payload.selector) {
631
+ const resolved = ensureResolved(payload.selector);
632
+ if (!resolved.element) {
633
+ return resolved;
634
+ }
635
+
636
+ maybeScrollIntoView(resolved.element);
637
+ if (typeof resolved.element.focus === "function") {
638
+ resolved.element.focus();
639
+ }
640
+ target = resolved.element;
641
+ }
642
+
643
+ pressKeyOnTarget(target, payload.key);
644
+
645
+ return {
646
+ browserFamily: payload.browserFamily,
647
+ key: payload.key,
648
+ dispatched: true,
649
+ target: target
650
+ ? {
651
+ tagName: target.tagName,
652
+ id: target.getAttribute("id"),
653
+ className: target.getAttribute("class"),
654
+ }
655
+ : null,
656
+ };
657
+ }
658
+ case "scroll": {
659
+ if (payload.selector) {
660
+ const resolved = ensureResolved(payload.selector);
661
+ if (!resolved.element) {
662
+ return resolved;
663
+ }
664
+
665
+ resolved.element.scrollIntoView({
666
+ block: payload.block || "center",
667
+ inline: "nearest",
668
+ });
669
+
670
+ return {
671
+ browserFamily: payload.browserFamily,
672
+ selector: payload.selector,
673
+ found: true,
674
+ scrolled: true,
675
+ node: describeElement(resolved.element, resolved),
676
+ };
677
+ }
678
+
679
+ window.scrollBy({
680
+ left: Number.isFinite(payload.deltaX) ? payload.deltaX : 0,
681
+ top: Number.isFinite(payload.deltaY) ? payload.deltaY : 0,
682
+ behavior: "instant",
683
+ });
684
+
685
+ return {
686
+ browserFamily: payload.browserFamily,
687
+ scrolled: true,
688
+ pageXOffset: window.pageXOffset,
689
+ pageYOffset: window.pageYOffset,
690
+ viewport: {
691
+ width: window.innerWidth,
692
+ height: window.innerHeight,
693
+ },
694
+ };
695
+ }
696
+ case "network_snapshot": {
697
+ const entries = [
698
+ ...performance.getEntriesByType("navigation"),
699
+ ...performance.getEntriesByType("resource"),
700
+ ].map((entry, index) => ({
701
+ requestId: \`snapshot-\${index + 1}-\${entry.name || "entry"}\`,
702
+ url: entry.name || location.href,
703
+ method: entry.entryType === "navigation" ? "GET" : "GET",
704
+ resourceType: entry.initiatorType || entry.entryType || null,
705
+ startedAt: entry.startTime ?? 0,
706
+ completedAt: (entry.startTime ?? 0) + (entry.duration ?? 0),
707
+ duration: entry.duration ?? null,
708
+ transferSize:
709
+ typeof entry.transferSize === "number" ? entry.transferSize : null,
710
+ encodedBodySize:
711
+ typeof entry.encodedBodySize === "number"
712
+ ? entry.encodedBodySize
713
+ : null,
714
+ decodedBodySize:
715
+ typeof entry.decodedBodySize === "number"
716
+ ? entry.decodedBodySize
717
+ : null,
718
+ }));
719
+
720
+ return {
721
+ browserFamily: payload.browserFamily,
722
+ entries,
723
+ };
724
+ }
725
+ default:
726
+ throw new Error(\`Unsupported page action: \${payload.action}\`);
727
+ }
728
+ }
729
+
730
+ return runAction();
731
+ })()`;
732
+
733
+ return serialize ? `JSON.stringify(${body})` : body;
734
+ }