mcp-browser-dev-tools 0.1.0 → 0.2.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.
@@ -1,1040 +1,14 @@
1
- function buildPayloadLiteral(payload) {
2
- return JSON.stringify(payload);
3
- }
1
+ import { pageScript } from "./page-script.mjs";
2
+
3
+ const PAGE_SCRIPT_SOURCE = pageScript.toString();
4
4
 
5
+ // Builds an expression that runs pageScript in the page with this payload.
6
+ // With serialize, the expression evaluates to the result as a JSON string.
5
7
  export function buildPageContextExpression(
6
8
  payload,
7
9
  { serialize = false } = {},
8
10
  ) {
9
- const body = `(() => {
10
- const payload = ${buildPayloadLiteral(payload)};
11
- const TEXT_LIMIT = 400;
12
- const VALUE_ONLY_INPUT_TYPES = [
13
- "date",
14
- "time",
15
- "datetime-local",
16
- "month",
17
- "week",
18
- "color",
19
- "range",
20
- ];
21
-
22
- function clipText(value, limit = TEXT_LIMIT) {
23
- if (typeof value !== "string") {
24
- return value ?? null;
25
- }
26
-
27
- return value.length > limit ? \`\${value.slice(0, limit)}...\` : value;
28
- }
29
-
30
- function normalizeText(value) {
31
- return typeof value === "string"
32
- ? value.replace(/\\s+/g, " ").trim()
33
- : "";
34
- }
35
-
36
- function getVisibleText(element) {
37
- if (!element) {
38
- return "";
39
- }
40
-
41
- if (typeof element.innerText === "string" && element.innerText.trim()) {
42
- return element.innerText;
43
- }
44
-
45
- return element.textContent ?? "";
46
- }
47
-
48
- function getLabelTextForControl(element) {
49
- if (!element || !element.id) {
50
- return "";
51
- }
52
-
53
- const label = document.querySelector(\`label[for="\${CSS.escape(element.id)}"]\`);
54
- return label ? normalizeText(getVisibleText(label)) : "";
55
- }
56
-
57
- function getAccessibleName(element) {
58
- if (!element) {
59
- return "";
60
- }
61
-
62
- const ariaLabel = element.getAttribute("aria-label");
63
- if (ariaLabel) {
64
- return normalizeText(ariaLabel);
65
- }
66
-
67
- const labelledBy = element.getAttribute("aria-labelledby");
68
- if (labelledBy) {
69
- const text = labelledBy
70
- .split(/\\s+/)
71
- .map((id) => document.getElementById(id))
72
- .filter(Boolean)
73
- .map((node) => normalizeText(getVisibleText(node)))
74
- .filter(Boolean)
75
- .join(" ");
76
- if (text) {
77
- return text;
78
- }
79
- }
80
-
81
- const labelText = getLabelTextForControl(element);
82
- if (labelText) {
83
- return labelText;
84
- }
85
-
86
- const alt = element.getAttribute("alt");
87
- if (alt) {
88
- return normalizeText(alt);
89
- }
90
-
91
- const title = element.getAttribute("title");
92
- if (title) {
93
- return normalizeText(title);
94
- }
95
-
96
- if (
97
- element instanceof HTMLInputElement ||
98
- element instanceof HTMLTextAreaElement
99
- ) {
100
- return normalizeText(element.value);
101
- }
102
-
103
- return normalizeText(getVisibleText(element));
104
- }
105
-
106
- function inferRole(element) {
107
- if (!element) {
108
- return null;
109
- }
110
-
111
- const explicitRole = element.getAttribute("role");
112
- if (explicitRole) {
113
- return explicitRole;
114
- }
115
-
116
- const tag = element.tagName.toLowerCase();
117
- if (tag === "a" && element.hasAttribute("href")) return "link";
118
- if (tag === "button") return "button";
119
- if (tag === "dialog") return "dialog";
120
- if (tag === "img") return "img";
121
- if (tag === "select") return "combobox";
122
- if (tag === "textarea") return "textbox";
123
- if (tag === "option") return "option";
124
- if (tag === "ul" || tag === "ol") return "list";
125
- if (tag === "li") return "listitem";
126
- if (tag === "input") {
127
- const type = (element.getAttribute("type") || "text").toLowerCase();
128
- if (type === "button" || type === "submit" || type === "reset") return "button";
129
- if (type === "checkbox") return "checkbox";
130
- if (type === "radio") return "radio";
131
- if (type === "range") return "slider";
132
- return "textbox";
133
- }
134
-
135
- return null;
136
- }
137
-
138
- function isVisible(element) {
139
- if (!element) {
140
- return false;
141
- }
142
-
143
- const style = getComputedStyle(element);
144
- const rect = element.getBoundingClientRect();
145
- if (
146
- element.hidden ||
147
- element.getAttribute("aria-hidden") === "true" ||
148
- style.display === "none" ||
149
- style.visibility === "hidden" ||
150
- style.visibility === "collapse" ||
151
- style.pointerEvents === "none"
152
- ) {
153
- return false;
154
- }
155
-
156
- return rect.width > 0 && rect.height > 0;
157
- }
158
-
159
- function isDisabled(element) {
160
- return Boolean(
161
- element &&
162
- (element.disabled === true ||
163
- element.getAttribute("aria-disabled") === "true"),
164
- );
165
- }
166
-
167
- function isEditable(element) {
168
- return Boolean(
169
- element &&
170
- (element.isContentEditable ||
171
- element instanceof HTMLTextAreaElement ||
172
- (element instanceof HTMLInputElement &&
173
- !["button", "submit", "reset", "checkbox", "radio", "file"].includes(
174
- (element.type || "text").toLowerCase(),
175
- ))),
176
- );
177
- }
178
-
179
- function isFocusable(element) {
180
- if (!element || isDisabled(element)) {
181
- return false;
182
- }
183
-
184
- if (typeof element.tabIndex === "number" && element.tabIndex >= 0) {
185
- return true;
186
- }
187
-
188
- const tag = element.tagName.toLowerCase();
189
- return ["a", "button", "input", "select", "textarea"].includes(tag);
190
- }
191
-
192
- function isClickable(element) {
193
- if (!element || isDisabled(element)) {
194
- return false;
195
- }
196
-
197
- const role = inferRole(element);
198
- const tag = element.tagName.toLowerCase();
199
- return (
200
- ["button", "link", "checkbox", "radio", "option"].includes(role) ||
201
- ["button", "a", "summary", "option"].includes(tag) ||
202
- typeof element.onclick === "function"
203
- );
204
- }
205
-
206
- function isScrollable(element) {
207
- if (!element) {
208
- return false;
209
- }
210
-
211
- return (
212
- element.scrollHeight > element.clientHeight ||
213
- element.scrollWidth > element.clientWidth
214
- );
215
- }
216
-
217
- function toAttributeObject(element) {
218
- return Object.fromEntries(
219
- Array.from(element.attributes, (attribute) => [
220
- attribute.name,
221
- attribute.value,
222
- ]),
223
- );
224
- }
225
-
226
- function summarizeLocator(locator) {
227
- if (!locator || typeof locator !== "object") {
228
- return null;
229
- }
230
-
231
- const summary = {};
232
- for (const key of ["locator", "strategy", "query", "role", "name", "error"]) {
233
- if (locator[key] !== undefined) {
234
- summary[key] = locator[key];
235
- }
236
- }
237
-
238
- return summary;
239
- }
240
-
241
- function describeElement(element, locator) {
242
- const rect = element.getBoundingClientRect();
243
- const style = getComputedStyle(element);
244
- const role = inferRole(element);
245
- const accessibleName = getAccessibleName(element);
246
-
247
- return {
248
- locator: summarizeLocator(locator),
249
- tagName: element.tagName,
250
- id: element.getAttribute("id"),
251
- className: element.getAttribute("class"),
252
- childElementCount: element.childElementCount,
253
- attributes: toAttributeObject(element),
254
- textContent: clipText(element.textContent ?? null),
255
- innerText: clipText(
256
- typeof element.innerText === "string" ? element.innerText : null,
257
- ),
258
- value:
259
- "value" in element && typeof element.value === "string"
260
- ? clipText(element.value)
261
- : null,
262
- accessibleName: accessibleName || null,
263
- role,
264
- visible: isVisible(element),
265
- disabled: isDisabled(element),
266
- focused: document.activeElement === element,
267
- editable: isEditable(element),
268
- focusable: isFocusable(element),
269
- clickable: isClickable(element),
270
- scrollable: isScrollable(element),
271
- checked: "checked" in element ? Boolean(element.checked) : null,
272
- selected: "selected" in element ? Boolean(element.selected) : null,
273
- open: "open" in element ? Boolean(element.open) : null,
274
- box: {
275
- x: rect.x,
276
- y: rect.y,
277
- width: rect.width,
278
- height: rect.height,
279
- top: rect.top,
280
- right: rect.right,
281
- bottom: rect.bottom,
282
- left: rect.left,
283
- },
284
- styles: {
285
- display: style.display,
286
- visibility: style.visibility,
287
- position: style.position,
288
- zIndex: style.zIndex,
289
- overflowX: style.overflowX,
290
- overflowY: style.overflowY,
291
- opacity: style.opacity,
292
- pointerEvents: style.pointerEvents,
293
- },
294
- outerHTML: clipText(element.outerHTML, 1200),
295
- };
296
- }
297
-
298
- function parseRoleLocator(value) {
299
- const match = value.match(/^([^\\[]+?)(?:\\[name=(?:"([^"]*)"|'([^']*)')\\])?$/);
300
- if (!match) {
301
- return {
302
- role: normalizeText(value) || null,
303
- name: null,
304
- };
305
- }
306
-
307
- return {
308
- role: normalizeText(match[1]) || null,
309
- name: normalizeText(match[2] ?? match[3] ?? "") || null,
310
- };
311
- }
312
-
313
- function collectCandidates() {
314
- return Array.from(
315
- document.querySelectorAll("body *"),
316
- );
317
- }
318
-
319
- function describePage() {
320
- return {
321
- url: location.href,
322
- title: document.title,
323
- readyState: document.readyState,
324
- visibilityState: document.visibilityState,
325
- viewport: {
326
- width: window.innerWidth,
327
- height: window.innerHeight,
328
- devicePixelRatio: window.devicePixelRatio,
329
- },
330
- scroll: {
331
- x: window.scrollX,
332
- y: window.scrollY,
333
- },
334
- };
335
- }
336
-
337
- function parseDocumentCookies() {
338
- const COOKIE_LIMIT = 100;
339
- const NAME_LIMIT = 120;
340
- const VALUE_LIMIT = 300;
341
- const cookieText =
342
- typeof document.cookie === "string" ? document.cookie.trim() : "";
343
-
344
- if (!cookieText) {
345
- return {
346
- totalEntries: 0,
347
- returnedEntries: 0,
348
- truncated: false,
349
- entries: [],
350
- source: "document.cookie",
351
- };
352
- }
353
-
354
- const rawEntries = cookieText
355
- .split(";")
356
- .map((entry) => entry.trim())
357
- .filter(Boolean);
358
- const entries = rawEntries.slice(0, COOKIE_LIMIT).map((entry) => {
359
- const separatorIndex = entry.indexOf("=");
360
- const name =
361
- separatorIndex === -1 ? entry : entry.slice(0, separatorIndex);
362
- const value =
363
- separatorIndex === -1 ? "" : entry.slice(separatorIndex + 1);
364
- return {
365
- name: clipText(name, NAME_LIMIT),
366
- value: clipText(value, VALUE_LIMIT),
367
- };
368
- });
369
-
370
- return {
371
- totalEntries: rawEntries.length,
372
- returnedEntries: entries.length,
373
- truncated: rawEntries.length > COOKIE_LIMIT,
374
- entries,
375
- source: "document.cookie",
376
- };
377
- }
378
-
379
- function snapshotStorage(storage, type) {
380
- const STORAGE_LIMIT = 100;
381
- const KEY_LIMIT = 200;
382
- const VALUE_LIMIT = 300;
383
-
384
- try {
385
- const totalEntries = storage.length;
386
- const entries = [];
387
- const limit = Math.min(totalEntries, STORAGE_LIMIT);
388
-
389
- for (let index = 0; index < limit; index += 1) {
390
- const key = storage.key(index);
391
- if (key === null) {
392
- continue;
393
- }
394
-
395
- entries.push({
396
- key: clipText(key, KEY_LIMIT),
397
- value: clipText(storage.getItem(key), VALUE_LIMIT),
398
- });
399
- }
400
-
401
- return {
402
- type,
403
- totalEntries,
404
- returnedEntries: entries.length,
405
- truncated: totalEntries > STORAGE_LIMIT,
406
- entries,
407
- };
408
- } catch (error) {
409
- return {
410
- type,
411
- totalEntries: 0,
412
- returnedEntries: 0,
413
- truncated: false,
414
- entries: [],
415
- error: error instanceof Error ? error.message : String(error),
416
- };
417
- }
418
- }
419
-
420
- function summarizeStorage(storage, type) {
421
- const SAMPLE_LIMIT = 20;
422
- const KEY_LIMIT = 80;
423
-
424
- try {
425
- const totalEntries = storage.length;
426
- const sampleKeys = [];
427
- const limit = Math.min(totalEntries, SAMPLE_LIMIT);
428
-
429
- for (let index = 0; index < limit; index += 1) {
430
- const key = storage.key(index);
431
- if (key !== null) {
432
- sampleKeys.push(clipText(key, KEY_LIMIT));
433
- }
434
- }
435
-
436
- return {
437
- type,
438
- totalEntries,
439
- sampleKeys,
440
- truncated: totalEntries > SAMPLE_LIMIT,
441
- };
442
- } catch (error) {
443
- return {
444
- type,
445
- totalEntries: 0,
446
- sampleKeys: [],
447
- truncated: false,
448
- error: error instanceof Error ? error.message : String(error),
449
- };
450
- }
451
- }
452
-
453
- function resolveLocator(rawLocator) {
454
- const locator = typeof rawLocator === "string" ? rawLocator.trim() : "";
455
- if (!locator) {
456
- throw new Error("selector must be a non-empty string");
457
- }
458
-
459
- if (locator.startsWith("text=")) {
460
- const query = normalizeText(locator.slice(5));
461
- const candidates = collectCandidates();
462
- const match =
463
- candidates.find(
464
- (element) =>
465
- isVisible(element) &&
466
- normalizeText(getVisibleText(element)) === query,
467
- ) ??
468
- candidates.find((element) => {
469
- const text = normalizeText(getVisibleText(element));
470
- return isVisible(element) && text && text.includes(query);
471
- });
472
-
473
- return {
474
- locator,
475
- strategy: "text",
476
- query,
477
- element: match ?? null,
478
- };
479
- }
480
-
481
- if (locator.startsWith("role=")) {
482
- const { role, name } = parseRoleLocator(locator.slice(5).trim());
483
- const candidates = collectCandidates();
484
- const match = candidates.find((element) => {
485
- const elementRole = normalizeText(inferRole(element) ?? "");
486
- const accessibleName = normalizeText(getAccessibleName(element));
487
- if (!elementRole || elementRole !== role) {
488
- return false;
489
- }
490
-
491
- if (!name) {
492
- return true;
493
- }
494
-
495
- return accessibleName === name || accessibleName.includes(name);
496
- });
497
-
498
- return {
499
- locator,
500
- strategy: "role",
501
- role,
502
- name,
503
- element: match ?? null,
504
- };
505
- }
506
-
507
- if (locator.startsWith("name=")) {
508
- const query = normalizeText(locator.slice(5));
509
- const candidates = collectCandidates();
510
- const match =
511
- candidates.find((element) => {
512
- const accessibleName = normalizeText(getAccessibleName(element));
513
- return isVisible(element) && accessibleName === query;
514
- }) ??
515
- candidates.find((element) => {
516
- const accessibleName = normalizeText(getAccessibleName(element));
517
- return (
518
- isVisible(element) && accessibleName && accessibleName.includes(query)
519
- );
520
- });
521
-
522
- return {
523
- locator,
524
- strategy: "name",
525
- query,
526
- element: match ?? null,
527
- };
528
- }
529
-
530
- const cssSelector = locator.startsWith("css=") ? locator.slice(4) : locator;
531
- try {
532
- return {
533
- locator,
534
- strategy: "css",
535
- query: cssSelector,
536
- element: document.querySelector(cssSelector),
537
- };
538
- } catch (error) {
539
- return {
540
- locator,
541
- strategy: "css",
542
- query: cssSelector,
543
- element: null,
544
- error: error instanceof Error ? error.message : String(error),
545
- };
546
- }
547
- }
548
-
549
- function ensureResolved(rawLocator) {
550
- const resolved = resolveLocator(rawLocator);
551
- if (resolved.error) {
552
- return {
553
- browserFamily: payload.browserFamily,
554
- selector: rawLocator,
555
- found: false,
556
- locator: summarizeLocator(resolved),
557
- error: resolved.error,
558
- };
559
- }
560
-
561
- if (!resolved.element) {
562
- return {
563
- browserFamily: payload.browserFamily,
564
- selector: rawLocator,
565
- found: false,
566
- locator: summarizeLocator(resolved),
567
- };
568
- }
569
-
570
- return resolved;
571
- }
572
-
573
- function dispatchInputEvents(element) {
574
- element.dispatchEvent(new Event("input", { bubbles: true, composed: true }));
575
- element.dispatchEvent(new Event("change", { bubbles: true, composed: true }));
576
- }
577
-
578
- // Assigning element.value directly also updates the value tracker React
579
- // keeps on the instance, so React would treat the next input event as a
580
- // no-op. The prototype setter bypasses that tracker.
581
- function setNativeValue(element, value) {
582
- const prototype = Object.getPrototypeOf(element);
583
- const descriptor = prototype
584
- ? Object.getOwnPropertyDescriptor(prototype, "value")
585
- : null;
586
- if (descriptor?.set) {
587
- descriptor.set.call(element, value);
588
- } else {
589
- element.value = value;
590
- }
591
- }
592
-
593
- function maybeScrollIntoView(element) {
594
- if (!element || payload.scrollIntoView === false) {
595
- return;
596
- }
597
-
598
- element.scrollIntoView({
599
- block: "center",
600
- inline: "center",
601
- behavior: "instant",
602
- });
603
- }
604
-
605
- function summarizeTarget(element) {
606
- return element
607
- ? {
608
- tagName: element.tagName,
609
- id: element.getAttribute("id"),
610
- className: element.getAttribute("class"),
611
- }
612
- : null;
613
- }
614
-
615
- function getDeepActiveElement() {
616
- let active = document.activeElement;
617
- while (active?.shadowRoot?.activeElement) {
618
- active = active.shadowRoot.activeElement;
619
- }
620
- return active;
621
- }
622
-
623
- function focusElement(element) {
624
- if (typeof element.focus === "function") {
625
- element.focus();
626
- }
627
-
628
- const active = getDeepActiveElement();
629
- return Boolean(
630
- active &&
631
- (active === element ||
632
- (element.isContentEditable &&
633
- typeof active.contains === "function" &&
634
- active.contains(element))),
635
- );
636
- }
637
-
638
- function findClickablePoint(element) {
639
- const rects =
640
- typeof element.getClientRects === "function"
641
- ? Array.from(element.getClientRects())
642
- : [];
643
- if (rects.length === 0) {
644
- rects.push(element.getBoundingClientRect());
645
- }
646
-
647
- for (const rect of rects) {
648
- const left = Math.max(rect.left, 0);
649
- const top = Math.max(rect.top, 0);
650
- const right = Math.min(rect.right, window.innerWidth);
651
- const bottom = Math.min(rect.bottom, window.innerHeight);
652
- if (right - left >= 1 && bottom - top >= 1) {
653
- return { x: (left + right) / 2, y: (top + bottom) / 2 };
654
- }
655
- }
656
-
657
- return null;
658
- }
659
-
660
- function hitTest(point) {
661
- let hit = document.elementFromPoint(point.x, point.y);
662
- while (hit?.shadowRoot) {
663
- const inner = hit.shadowRoot.elementFromPoint(point.x, point.y);
664
- if (!inner || inner === hit) {
665
- break;
666
- }
667
- hit = inner;
668
- }
669
- return hit;
670
- }
671
-
672
- function receivesPointerAt(element, hit) {
673
- for (let node = hit; node; node = node.parentNode ?? node.host ?? null) {
674
- if (node === element) {
675
- return true;
676
- }
677
- }
678
-
679
- // Styled checkboxes often hide the input behind its <label>, which
680
- // forwards the click to the control.
681
- const label =
682
- typeof hit?.closest === "function" ? hit.closest("label") : null;
683
- return Boolean(label && label.control === element);
684
- }
685
-
686
- function runAction() {
687
- switch (payload.action) {
688
- case "page_state":
689
- return {
690
- browserFamily: payload.browserFamily,
691
- page: describePage(),
692
- };
693
- case "inspect": {
694
- const resolved = ensureResolved(payload.selector);
695
- if (!resolved.element) {
696
- return resolved;
697
- }
698
-
699
- maybeScrollIntoView(resolved.element);
700
-
701
- return {
702
- browserFamily: payload.browserFamily,
703
- selector: payload.selector,
704
- found: true,
705
- node: describeElement(resolved.element, resolved),
706
- };
707
- }
708
- case "pointer_target": {
709
- const resolved = ensureResolved(payload.selector);
710
- if (!resolved.element) {
711
- return resolved;
712
- }
713
-
714
- maybeScrollIntoView(resolved.element);
715
- const point = findClickablePoint(resolved.element);
716
- const hit = point ? hitTest(point) : null;
717
- const receivesEvents = Boolean(
718
- hit && receivesPointerAt(resolved.element, hit),
719
- );
720
-
721
- return {
722
- browserFamily: payload.browserFamily,
723
- selector: payload.selector,
724
- found: true,
725
- point,
726
- receivesEvents,
727
- obscuredBy: receivesEvents ? null : summarizeTarget(hit),
728
- node: describeElement(resolved.element, resolved),
729
- };
730
- }
731
- case "prepare_type": {
732
- const resolved = ensureResolved(payload.selector);
733
- if (!resolved.element) {
734
- return resolved;
735
- }
736
-
737
- const element = resolved.element;
738
- const clear = payload.clear !== false;
739
- maybeScrollIntoView(element);
740
-
741
- const isTextControl =
742
- element instanceof HTMLInputElement ||
743
- element instanceof HTMLTextAreaElement;
744
- if (!isEditable(element) || isDisabled(element)) {
745
- throw new Error("Resolved element is not editable");
746
- }
747
- if (element.readOnly === true) {
748
- throw new Error("Resolved element is read-only");
749
- }
750
-
751
- // Pickers such as date or color inputs do not accept typed text, so
752
- // their value is set directly.
753
- if (
754
- element instanceof HTMLInputElement &&
755
- VALUE_ONLY_INPUT_TYPES.includes((element.type || "").toLowerCase())
756
- ) {
757
- focusElement(element);
758
- setNativeValue(element, payload.text);
759
- dispatchInputEvents(element);
760
- return {
761
- browserFamily: payload.browserFamily,
762
- selector: payload.selector,
763
- found: true,
764
- method: "value",
765
- typedText: payload.text,
766
- node: describeElement(element, resolved),
767
- };
768
- }
769
-
770
- if (!focusElement(element)) {
771
- throw new Error("Could not focus the resolved element");
772
- }
773
-
774
- if (isTextControl) {
775
- if (clear) {
776
- element.select();
777
- } else {
778
- const end = element.value.length;
779
- try {
780
- element.setSelectionRange(end, end);
781
- } catch {
782
- // email and number inputs do not support selection ranges.
783
- }
784
- }
785
- } else {
786
- const range = document.createRange();
787
- range.selectNodeContents(element);
788
- if (!clear) {
789
- range.collapse(false);
790
- }
791
- const selection = window.getSelection();
792
- selection.removeAllRanges();
793
- selection.addRange(range);
794
- }
795
-
796
- return {
797
- browserFamily: payload.browserFamily,
798
- selector: payload.selector,
799
- found: true,
800
- method: "native",
801
- node: describeElement(element, resolved),
802
- };
803
- }
804
- case "select": {
805
- const resolved = ensureResolved(payload.selector);
806
- if (!resolved.element) {
807
- return resolved;
808
- }
809
-
810
- if (!(resolved.element instanceof HTMLSelectElement)) {
811
- throw new Error("Resolved element is not a <select>");
812
- }
813
-
814
- const option =
815
- Array.from(resolved.element.options).find(
816
- (candidate) =>
817
- (payload.value &&
818
- (candidate.value === payload.value ||
819
- candidate.text === payload.value)) ||
820
- (payload.label &&
821
- normalizeText(candidate.text).includes(
822
- normalizeText(payload.label),
823
- )),
824
- ) ?? null;
825
-
826
- if (!option) {
827
- throw new Error("No matching <option> found");
828
- }
829
-
830
- resolved.element.value = option.value;
831
- dispatchInputEvents(resolved.element);
832
-
833
- return {
834
- browserFamily: payload.browserFamily,
835
- selector: payload.selector,
836
- found: true,
837
- selectedValue: option.value,
838
- selectedLabel: option.text,
839
- node: describeElement(resolved.element, resolved),
840
- };
841
- }
842
- case "focus": {
843
- if (payload.selector) {
844
- const resolved = ensureResolved(payload.selector);
845
- if (!resolved.element) {
846
- return resolved;
847
- }
848
-
849
- maybeScrollIntoView(resolved.element);
850
- if (!focusElement(resolved.element)) {
851
- throw new Error("Could not focus the resolved element");
852
- }
853
- }
854
-
855
- return {
856
- browserFamily: payload.browserFamily,
857
- selector: payload.selector ?? null,
858
- found: true,
859
- target: summarizeTarget(getDeepActiveElement() ?? document.body),
860
- };
861
- }
862
- case "scroll": {
863
- if (payload.selector) {
864
- const resolved = ensureResolved(payload.selector);
865
- if (!resolved.element) {
866
- return resolved;
867
- }
868
-
869
- resolved.element.scrollIntoView({
870
- block: payload.block || "center",
871
- inline: "nearest",
872
- });
873
-
874
- return {
875
- browserFamily: payload.browserFamily,
876
- selector: payload.selector,
877
- found: true,
878
- scrolled: true,
879
- node: describeElement(resolved.element, resolved),
880
- };
881
- }
882
-
883
- window.scrollBy({
884
- left: Number.isFinite(payload.deltaX) ? payload.deltaX : 0,
885
- top: Number.isFinite(payload.deltaY) ? payload.deltaY : 0,
886
- behavior: "instant",
887
- });
888
-
889
- return {
890
- browserFamily: payload.browserFamily,
891
- scrolled: true,
892
- pageXOffset: window.pageXOffset,
893
- pageYOffset: window.pageYOffset,
894
- viewport: {
895
- width: window.innerWidth,
896
- height: window.innerHeight,
897
- },
898
- };
899
- }
900
- case "network_snapshot": {
901
- const entries = [
902
- ...performance.getEntriesByType("navigation"),
903
- ...performance.getEntriesByType("resource"),
904
- ].map((entry, index) => ({
905
- requestId: \`snapshot-\${index + 1}-\${entry.name || "entry"}\`,
906
- url: entry.name || location.href,
907
- method: entry.entryType === "navigation" ? "GET" : "GET",
908
- resourceType: entry.initiatorType || entry.entryType || null,
909
- startedAt: entry.startTime ?? 0,
910
- completedAt: (entry.startTime ?? 0) + (entry.duration ?? 0),
911
- duration: entry.duration ?? null,
912
- transferSize:
913
- typeof entry.transferSize === "number" ? entry.transferSize : null,
914
- encodedBodySize:
915
- typeof entry.encodedBodySize === "number"
916
- ? entry.encodedBodySize
917
- : null,
918
- decodedBodySize:
919
- typeof entry.decodedBodySize === "number"
920
- ? entry.decodedBodySize
921
- : null,
922
- }));
923
-
924
- return {
925
- browserFamily: payload.browserFamily,
926
- entries,
927
- };
928
- }
929
- case "cookie_snapshot":
930
- return {
931
- browserFamily: payload.browserFamily,
932
- cookies: parseDocumentCookies(),
933
- };
934
- case "storage_snapshot":
935
- return {
936
- browserFamily: payload.browserFamily,
937
- storage: {
938
- localStorage: snapshotStorage(localStorage, "localStorage"),
939
- sessionStorage: snapshotStorage(sessionStorage, "sessionStorage"),
940
- },
941
- };
942
- case "debug_report": {
943
- const cookies = parseDocumentCookies();
944
- return {
945
- browserFamily: payload.browserFamily,
946
- page: describePage(),
947
- cookies: {
948
- totalEntries: cookies.totalEntries,
949
- returnedEntries: cookies.returnedEntries,
950
- truncated: cookies.truncated,
951
- sampleNames: cookies.entries.map((entry) => entry.name),
952
- },
953
- storage: {
954
- localStorage: summarizeStorage(localStorage, "localStorage"),
955
- sessionStorage: summarizeStorage(sessionStorage, "sessionStorage"),
956
- },
957
- };
958
- }
959
- case "restore_snapshot": {
960
- const snapshot = payload.snapshot ?? {};
961
- const clearStorage = payload.clearStorage === true;
962
- const snapshotUrl = snapshot.page?.url ?? null;
963
- const snapshotOrigin = snapshotUrl ? new URL(snapshotUrl).origin : null;
964
- const currentOrigin = location.origin;
965
-
966
- if (snapshotOrigin && snapshotOrigin !== currentOrigin) {
967
- throw new Error(
968
- "Snapshot origin " +
969
- snapshotOrigin +
970
- " does not match current origin " +
971
- currentOrigin,
972
- );
973
- }
974
-
975
- const restoreEntries = (storage, entries) => {
976
- const safeEntries = Array.isArray(entries) ? entries.slice(0, 100) : [];
977
- if (clearStorage) {
978
- storage.clear();
979
- }
980
-
981
- for (const entry of safeEntries) {
982
- if (!entry || typeof entry.key !== "string") {
983
- continue;
984
- }
985
-
986
- storage.setItem(entry.key, typeof entry.value === "string" ? entry.value : "");
987
- }
988
-
989
- return safeEntries.length;
990
- };
991
-
992
- const restoreCookies = (entries) => {
993
- const safeEntries = Array.isArray(entries) ? entries.slice(0, 100) : [];
994
- for (const entry of safeEntries) {
995
- if (!entry || typeof entry.name !== "string") {
996
- continue;
997
- }
998
-
999
- const encodedName = encodeURIComponent(entry.name);
1000
- const encodedValue = encodeURIComponent(
1001
- typeof entry.value === "string" ? entry.value : "",
1002
- );
1003
- document.cookie =
1004
- encodedName + "=" + encodedValue + "; path=/; SameSite=Lax";
1005
- }
1006
-
1007
- return safeEntries.length;
1008
- };
1009
-
1010
- return {
1011
- browserFamily: payload.browserFamily,
1012
- restoredAt: new Date().toISOString(),
1013
- clearStorage,
1014
- snapshotOrigin: snapshotOrigin ?? currentOrigin,
1015
- currentOrigin,
1016
- restored: {
1017
- cookies: restoreCookies(snapshot.cookies?.entries),
1018
- localStorage: restoreEntries(
1019
- localStorage,
1020
- snapshot.storage?.localStorage?.entries,
1021
- ),
1022
- sessionStorage: restoreEntries(
1023
- sessionStorage,
1024
- snapshot.storage?.sessionStorage?.entries,
1025
- ),
1026
- },
1027
- page: describePage(),
1028
- };
1029
- }
1030
- default:
1031
- throw new Error(\`Unsupported page action: \${payload.action}\`);
1032
- }
1033
- }
1034
-
1035
- return runAction();
1036
- })()`;
1037
-
11
+ const body = `(${PAGE_SCRIPT_SOURCE})(${JSON.stringify(payload)})`;
1038
12
  return serialize ? `JSON.stringify(${body})` : body;
1039
13
  }
1040
14
 
@@ -1051,6 +25,16 @@ function describeTarget(target) {
1051
25
  return `<${target.tagName.toLowerCase()}${id}${className}>`;
1052
26
  }
1053
27
 
28
+ // Marks errors for elements that may become usable soon, such as one still
29
+ // covered by a banner, so actions can retry them until their timeout.
30
+ export const ELEMENT_NOT_ACTIONABLE = "ELEMENT_NOT_ACTIONABLE";
31
+
32
+ function notActionable(message) {
33
+ const error = new Error(message);
34
+ error.code = ELEMENT_NOT_ACTIONABLE;
35
+ return error;
36
+ }
37
+
1054
38
  // Real pointer input lands on whatever is painted at the point, so refuse to
1055
39
  // send it when the resolved element is off-screen or covered.
1056
40
  export function assertPointerTarget(target) {
@@ -1059,15 +43,22 @@ export function assertPointerTarget(target) {
1059
43
  }
1060
44
 
1061
45
  if (!target.point) {
1062
- throw new Error(
46
+ throw notActionable(
1063
47
  `Element "${target.selector}" has no visible area inside the viewport`,
1064
48
  );
1065
49
  }
1066
50
 
1067
51
  if (!target.receivesEvents) {
1068
52
  const { x, y } = target.point;
1069
- throw new Error(
53
+ throw notActionable(
1070
54
  `Element "${target.selector}" is covered by ${describeTarget(target.obscuredBy)} at (${Math.round(x)}, ${Math.round(y)}); close or scroll past the covering element first`,
1071
55
  );
1072
56
  }
1073
57
  }
58
+
59
+ // A click on a disabled control does nothing, so report it instead.
60
+ export function assertEnabled(target) {
61
+ if (target.found && target.node?.disabled === true) {
62
+ throw notActionable(`Element "${target.selector}" is disabled`);
63
+ }
64
+ }