mcp-browser-dev-tools 0.0.1-beta.1 → 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.
@@ -0,0 +1,719 @@
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 describeElement(element, locator) {
218
+ const rect = element.getBoundingClientRect();
219
+ const style = getComputedStyle(element);
220
+ const role = inferRole(element);
221
+ const accessibleName = getAccessibleName(element);
222
+
223
+ return {
224
+ locator,
225
+ tagName: element.tagName,
226
+ id: element.getAttribute("id"),
227
+ className: element.getAttribute("class"),
228
+ childElementCount: element.childElementCount,
229
+ attributes: toAttributeObject(element),
230
+ textContent: clipText(element.textContent ?? null),
231
+ innerText: clipText(
232
+ typeof element.innerText === "string" ? element.innerText : null,
233
+ ),
234
+ value:
235
+ "value" in element && typeof element.value === "string"
236
+ ? clipText(element.value)
237
+ : null,
238
+ accessibleName: accessibleName || null,
239
+ role,
240
+ visible: isVisible(element),
241
+ disabled: isDisabled(element),
242
+ focused: document.activeElement === element,
243
+ editable: isEditable(element),
244
+ focusable: isFocusable(element),
245
+ clickable: isClickable(element),
246
+ scrollable: isScrollable(element),
247
+ checked: "checked" in element ? Boolean(element.checked) : null,
248
+ selected: "selected" in element ? Boolean(element.selected) : null,
249
+ open: "open" in element ? Boolean(element.open) : null,
250
+ box: {
251
+ x: rect.x,
252
+ y: rect.y,
253
+ width: rect.width,
254
+ height: rect.height,
255
+ top: rect.top,
256
+ right: rect.right,
257
+ bottom: rect.bottom,
258
+ left: rect.left,
259
+ },
260
+ styles: {
261
+ display: style.display,
262
+ visibility: style.visibility,
263
+ position: style.position,
264
+ zIndex: style.zIndex,
265
+ overflowX: style.overflowX,
266
+ overflowY: style.overflowY,
267
+ opacity: style.opacity,
268
+ pointerEvents: style.pointerEvents,
269
+ },
270
+ outerHTML: clipText(element.outerHTML, 1200),
271
+ };
272
+ }
273
+
274
+ function parseRoleLocator(value) {
275
+ const match = value.match(/^([^\\[]+?)(?:\\[name=(?:"([^"]*)"|'([^']*)')\\])?$/);
276
+ if (!match) {
277
+ return {
278
+ role: normalizeText(value) || null,
279
+ name: null,
280
+ };
281
+ }
282
+
283
+ return {
284
+ role: normalizeText(match[1]) || null,
285
+ name: normalizeText(match[2] ?? match[3] ?? "") || null,
286
+ };
287
+ }
288
+
289
+ function collectCandidates() {
290
+ return Array.from(
291
+ document.querySelectorAll("body *"),
292
+ );
293
+ }
294
+
295
+ function describePage() {
296
+ return {
297
+ url: location.href,
298
+ title: document.title,
299
+ readyState: document.readyState,
300
+ visibilityState: document.visibilityState,
301
+ viewport: {
302
+ width: window.innerWidth,
303
+ height: window.innerHeight,
304
+ devicePixelRatio: window.devicePixelRatio,
305
+ },
306
+ scroll: {
307
+ x: window.scrollX,
308
+ y: window.scrollY,
309
+ },
310
+ };
311
+ }
312
+
313
+ function resolveLocator(rawLocator) {
314
+ const locator = typeof rawLocator === "string" ? rawLocator.trim() : "";
315
+ if (!locator) {
316
+ throw new Error("selector must be a non-empty string");
317
+ }
318
+
319
+ if (locator.startsWith("text=")) {
320
+ const query = normalizeText(locator.slice(5));
321
+ const candidates = collectCandidates();
322
+ const match =
323
+ candidates.find(
324
+ (element) =>
325
+ isVisible(element) &&
326
+ normalizeText(getVisibleText(element)) === query,
327
+ ) ??
328
+ candidates.find((element) => {
329
+ const text = normalizeText(getVisibleText(element));
330
+ return isVisible(element) && text && text.includes(query);
331
+ });
332
+
333
+ return {
334
+ locator,
335
+ strategy: "text",
336
+ query,
337
+ element: match ?? null,
338
+ };
339
+ }
340
+
341
+ if (locator.startsWith("role=")) {
342
+ const { role, name } = parseRoleLocator(locator.slice(5).trim());
343
+ const candidates = collectCandidates();
344
+ const match = candidates.find((element) => {
345
+ const elementRole = normalizeText(inferRole(element) ?? "");
346
+ const accessibleName = normalizeText(getAccessibleName(element));
347
+ if (!elementRole || elementRole !== role) {
348
+ return false;
349
+ }
350
+
351
+ if (!name) {
352
+ return true;
353
+ }
354
+
355
+ return accessibleName === name || accessibleName.includes(name);
356
+ });
357
+
358
+ return {
359
+ locator,
360
+ strategy: "role",
361
+ role,
362
+ name,
363
+ element: match ?? null,
364
+ };
365
+ }
366
+
367
+ if (locator.startsWith("name=")) {
368
+ const query = normalizeText(locator.slice(5));
369
+ const candidates = collectCandidates();
370
+ const match =
371
+ candidates.find((element) => {
372
+ const accessibleName = normalizeText(getAccessibleName(element));
373
+ return isVisible(element) && accessibleName === query;
374
+ }) ??
375
+ candidates.find((element) => {
376
+ const accessibleName = normalizeText(getAccessibleName(element));
377
+ return (
378
+ isVisible(element) && accessibleName && accessibleName.includes(query)
379
+ );
380
+ });
381
+
382
+ return {
383
+ locator,
384
+ strategy: "name",
385
+ query,
386
+ element: match ?? null,
387
+ };
388
+ }
389
+
390
+ const cssSelector = locator.startsWith("css=") ? locator.slice(4) : locator;
391
+ try {
392
+ return {
393
+ locator,
394
+ strategy: "css",
395
+ query: cssSelector,
396
+ element: document.querySelector(cssSelector),
397
+ };
398
+ } catch (error) {
399
+ return {
400
+ locator,
401
+ strategy: "css",
402
+ query: cssSelector,
403
+ element: null,
404
+ error: error instanceof Error ? error.message : String(error),
405
+ };
406
+ }
407
+ }
408
+
409
+ function ensureResolved(rawLocator) {
410
+ const resolved = resolveLocator(rawLocator);
411
+ if (resolved.error) {
412
+ return {
413
+ browserFamily: payload.browserFamily,
414
+ selector: rawLocator,
415
+ found: false,
416
+ locator: resolved,
417
+ error: resolved.error,
418
+ };
419
+ }
420
+
421
+ if (!resolved.element) {
422
+ return {
423
+ browserFamily: payload.browserFamily,
424
+ selector: rawLocator,
425
+ found: false,
426
+ locator: resolved,
427
+ };
428
+ }
429
+
430
+ return resolved;
431
+ }
432
+
433
+ function dispatchInputEvents(element) {
434
+ element.dispatchEvent(new Event("input", { bubbles: true, composed: true }));
435
+ element.dispatchEvent(new Event("change", { bubbles: true, composed: true }));
436
+ }
437
+
438
+ function maybeScrollIntoView(element) {
439
+ if (!element || payload.scrollIntoView === false) {
440
+ return;
441
+ }
442
+
443
+ element.scrollIntoView({ block: "center", inline: "center" });
444
+ }
445
+
446
+ function pressKeyOnTarget(target, key) {
447
+ const eventInit = {
448
+ key,
449
+ bubbles: true,
450
+ cancelable: true,
451
+ composed: true,
452
+ };
453
+ target.dispatchEvent(new KeyboardEvent("keydown", eventInit));
454
+ target.dispatchEvent(new KeyboardEvent("keypress", eventInit));
455
+ target.dispatchEvent(new KeyboardEvent("keyup", eventInit));
456
+ }
457
+
458
+ function runAction() {
459
+ switch (payload.action) {
460
+ case "page_state":
461
+ return {
462
+ browserFamily: payload.browserFamily,
463
+ page: describePage(),
464
+ };
465
+ case "inspect": {
466
+ const resolved = ensureResolved(payload.selector);
467
+ if (!resolved.element) {
468
+ return resolved;
469
+ }
470
+
471
+ maybeScrollIntoView(resolved.element);
472
+
473
+ return {
474
+ browserFamily: payload.browserFamily,
475
+ selector: payload.selector,
476
+ found: true,
477
+ node: describeElement(resolved.element, resolved),
478
+ };
479
+ }
480
+ case "click": {
481
+ const resolved = ensureResolved(payload.selector);
482
+ if (!resolved.element) {
483
+ return resolved;
484
+ }
485
+
486
+ maybeScrollIntoView(resolved.element);
487
+ if (typeof resolved.element.focus === "function") {
488
+ resolved.element.focus();
489
+ }
490
+
491
+ if (typeof resolved.element.click === "function") {
492
+ resolved.element.click();
493
+ } else {
494
+ resolved.element.dispatchEvent(
495
+ new MouseEvent("click", {
496
+ bubbles: true,
497
+ cancelable: true,
498
+ composed: true,
499
+ }),
500
+ );
501
+ }
502
+
503
+ return {
504
+ browserFamily: payload.browserFamily,
505
+ selector: payload.selector,
506
+ found: true,
507
+ clicked: true,
508
+ node: describeElement(resolved.element, resolved),
509
+ };
510
+ }
511
+ case "hover": {
512
+ const resolved = ensureResolved(payload.selector);
513
+ if (!resolved.element) {
514
+ return resolved;
515
+ }
516
+
517
+ maybeScrollIntoView(resolved.element);
518
+ const eventInit = {
519
+ bubbles: true,
520
+ cancelable: true,
521
+ composed: true,
522
+ };
523
+ resolved.element.dispatchEvent(new MouseEvent("mouseover", eventInit));
524
+ resolved.element.dispatchEvent(new MouseEvent("mouseenter", eventInit));
525
+ resolved.element.dispatchEvent(new MouseEvent("mousemove", eventInit));
526
+
527
+ return {
528
+ browserFamily: payload.browserFamily,
529
+ selector: payload.selector,
530
+ found: true,
531
+ hovered: true,
532
+ node: describeElement(resolved.element, resolved),
533
+ };
534
+ }
535
+ case "type": {
536
+ const resolved = ensureResolved(payload.selector);
537
+ if (!resolved.element) {
538
+ return resolved;
539
+ }
540
+
541
+ const clear = payload.clear !== false;
542
+ maybeScrollIntoView(resolved.element);
543
+ if (typeof resolved.element.focus === "function") {
544
+ resolved.element.focus();
545
+ }
546
+
547
+ if (
548
+ resolved.element instanceof HTMLInputElement ||
549
+ resolved.element instanceof HTMLTextAreaElement
550
+ ) {
551
+ resolved.element.value = clear
552
+ ? payload.text
553
+ : \`\${resolved.element.value}\${payload.text}\`;
554
+ dispatchInputEvents(resolved.element);
555
+ } else if (resolved.element.isContentEditable) {
556
+ resolved.element.textContent = clear
557
+ ? payload.text
558
+ : \`\${resolved.element.textContent ?? ""}\${payload.text}\`;
559
+ dispatchInputEvents(resolved.element);
560
+ } else {
561
+ throw new Error("Resolved element is not editable");
562
+ }
563
+
564
+ return {
565
+ browserFamily: payload.browserFamily,
566
+ selector: payload.selector,
567
+ found: true,
568
+ typedText: payload.text,
569
+ node: describeElement(resolved.element, resolved),
570
+ };
571
+ }
572
+ case "select": {
573
+ const resolved = ensureResolved(payload.selector);
574
+ if (!resolved.element) {
575
+ return resolved;
576
+ }
577
+
578
+ if (!(resolved.element instanceof HTMLSelectElement)) {
579
+ throw new Error("Resolved element is not a <select>");
580
+ }
581
+
582
+ const option =
583
+ Array.from(resolved.element.options).find(
584
+ (candidate) =>
585
+ (payload.value &&
586
+ (candidate.value === payload.value ||
587
+ candidate.text === payload.value)) ||
588
+ (payload.label &&
589
+ normalizeText(candidate.text).includes(
590
+ normalizeText(payload.label),
591
+ )),
592
+ ) ?? null;
593
+
594
+ if (!option) {
595
+ throw new Error("No matching <option> found");
596
+ }
597
+
598
+ resolved.element.value = option.value;
599
+ dispatchInputEvents(resolved.element);
600
+
601
+ return {
602
+ browserFamily: payload.browserFamily,
603
+ selector: payload.selector,
604
+ found: true,
605
+ selectedValue: option.value,
606
+ selectedLabel: option.text,
607
+ node: describeElement(resolved.element, resolved),
608
+ };
609
+ }
610
+ case "press_key": {
611
+ let target = document.activeElement instanceof HTMLElement
612
+ ? document.activeElement
613
+ : document.body;
614
+
615
+ if (payload.selector) {
616
+ const resolved = ensureResolved(payload.selector);
617
+ if (!resolved.element) {
618
+ return resolved;
619
+ }
620
+
621
+ maybeScrollIntoView(resolved.element);
622
+ if (typeof resolved.element.focus === "function") {
623
+ resolved.element.focus();
624
+ }
625
+ target = resolved.element;
626
+ }
627
+
628
+ pressKeyOnTarget(target, payload.key);
629
+
630
+ return {
631
+ browserFamily: payload.browserFamily,
632
+ key: payload.key,
633
+ dispatched: true,
634
+ target: target
635
+ ? {
636
+ tagName: target.tagName,
637
+ id: target.getAttribute("id"),
638
+ className: target.getAttribute("class"),
639
+ }
640
+ : null,
641
+ };
642
+ }
643
+ case "scroll": {
644
+ if (payload.selector) {
645
+ const resolved = ensureResolved(payload.selector);
646
+ if (!resolved.element) {
647
+ return resolved;
648
+ }
649
+
650
+ resolved.element.scrollIntoView({
651
+ block: payload.block || "center",
652
+ inline: "nearest",
653
+ });
654
+
655
+ return {
656
+ browserFamily: payload.browserFamily,
657
+ selector: payload.selector,
658
+ found: true,
659
+ scrolled: true,
660
+ node: describeElement(resolved.element, resolved),
661
+ };
662
+ }
663
+
664
+ window.scrollBy({
665
+ left: Number.isFinite(payload.deltaX) ? payload.deltaX : 0,
666
+ top: Number.isFinite(payload.deltaY) ? payload.deltaY : 0,
667
+ behavior: "instant",
668
+ });
669
+
670
+ return {
671
+ browserFamily: payload.browserFamily,
672
+ scrolled: true,
673
+ pageXOffset: window.pageXOffset,
674
+ pageYOffset: window.pageYOffset,
675
+ viewport: {
676
+ width: window.innerWidth,
677
+ height: window.innerHeight,
678
+ },
679
+ };
680
+ }
681
+ case "network_snapshot": {
682
+ const entries = [
683
+ ...performance.getEntriesByType("navigation"),
684
+ ...performance.getEntriesByType("resource"),
685
+ ].map((entry, index) => ({
686
+ requestId: \`snapshot-\${index + 1}-\${entry.name || "entry"}\`,
687
+ url: entry.name || location.href,
688
+ method: entry.entryType === "navigation" ? "GET" : "GET",
689
+ resourceType: entry.initiatorType || entry.entryType || null,
690
+ startedAt: entry.startTime ?? 0,
691
+ completedAt: (entry.startTime ?? 0) + (entry.duration ?? 0),
692
+ duration: entry.duration ?? null,
693
+ transferSize:
694
+ typeof entry.transferSize === "number" ? entry.transferSize : null,
695
+ encodedBodySize:
696
+ typeof entry.encodedBodySize === "number"
697
+ ? entry.encodedBodySize
698
+ : null,
699
+ decodedBodySize:
700
+ typeof entry.decodedBodySize === "number"
701
+ ? entry.decodedBodySize
702
+ : null,
703
+ }));
704
+
705
+ return {
706
+ browserFamily: payload.browserFamily,
707
+ entries,
708
+ };
709
+ }
710
+ default:
711
+ throw new Error(\`Unsupported page action: \${payload.action}\`);
712
+ }
713
+ }
714
+
715
+ return runAction();
716
+ })()`;
717
+
718
+ return serialize ? `JSON.stringify(${body})` : body;
719
+ }