testsurfer 0.1.2 → 0.3.0

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.
Files changed (84) hide show
  1. package/README.md +52 -149
  2. package/dist/browser.d.ts +135 -1
  3. package/dist/browser.js +378 -2
  4. package/dist/browser.js.map +1 -1
  5. package/dist/cli.d.ts +16 -0
  6. package/dist/cli.js +140 -0
  7. package/dist/cli.js.map +1 -0
  8. package/dist/client.d.ts +12 -2
  9. package/dist/client.js +73 -4
  10. package/dist/client.js.map +1 -1
  11. package/dist/diff.d.ts +19 -0
  12. package/dist/diff.js +116 -0
  13. package/dist/diff.js.map +1 -0
  14. package/dist/events.d.ts +386 -0
  15. package/dist/events.js +1035 -0
  16. package/dist/events.js.map +1 -0
  17. package/dist/expect.d.ts +135 -26
  18. package/dist/expect.js +634 -130
  19. package/dist/expect.js.map +1 -1
  20. package/dist/frame.d.ts +88 -0
  21. package/dist/frame.js +194 -0
  22. package/dist/frame.js.map +1 -0
  23. package/dist/global.d.ts +12 -0
  24. package/dist/global.js +136 -0
  25. package/dist/global.js.map +1 -0
  26. package/dist/hooks.d.ts +28 -0
  27. package/dist/hooks.js +48 -0
  28. package/dist/hooks.js.map +1 -0
  29. package/dist/index.d.ts +22 -3
  30. package/dist/index.js +21 -3
  31. package/dist/index.js.map +1 -1
  32. package/dist/injected.d.ts +15 -0
  33. package/dist/injected.js +2025 -0
  34. package/dist/injected.js.map +1 -0
  35. package/dist/locator.d.ts +374 -86
  36. package/dist/locator.js +845 -244
  37. package/dist/locator.js.map +1 -1
  38. package/dist/media.d.ts +15 -0
  39. package/dist/media.js +83 -0
  40. package/dist/media.js.map +1 -0
  41. package/dist/net.d.ts +110 -0
  42. package/dist/net.js +498 -0
  43. package/dist/net.js.map +1 -0
  44. package/dist/page.d.ts +448 -5
  45. package/dist/page.js +1187 -31
  46. package/dist/page.js.map +1 -1
  47. package/dist/png.d.ts +28 -0
  48. package/dist/png.js +197 -0
  49. package/dist/png.js.map +1 -0
  50. package/dist/pwconfig.d.ts +66 -0
  51. package/dist/pwconfig.js +77 -0
  52. package/dist/pwconfig.js.map +1 -0
  53. package/dist/register.d.ts +6 -0
  54. package/dist/register.js +9 -0
  55. package/dist/register.js.map +1 -0
  56. package/dist/request.d.ts +29 -0
  57. package/dist/request.js +75 -0
  58. package/dist/request.js.map +1 -0
  59. package/dist/runner.d.ts +99 -15
  60. package/dist/runner.js +354 -58
  61. package/dist/runner.js.map +1 -1
  62. package/dist/screenshot.d.ts +35 -0
  63. package/dist/screenshot.js +171 -0
  64. package/dist/screenshot.js.map +1 -0
  65. package/dist/selector.d.ts +55 -0
  66. package/dist/selector.js +208 -0
  67. package/dist/selector.js.map +1 -0
  68. package/dist/selectors.d.ts +13 -0
  69. package/dist/selectors.js +16 -0
  70. package/dist/selectors.js.map +1 -0
  71. package/dist/serialize.d.ts +17 -0
  72. package/dist/serialize.js +149 -0
  73. package/dist/serialize.js.map +1 -0
  74. package/dist/shim.d.ts +15 -0
  75. package/dist/shim.js +211 -0
  76. package/dist/shim.js.map +1 -0
  77. package/dist/testinfo.d.ts +62 -0
  78. package/dist/testinfo.js +23 -0
  79. package/dist/testinfo.js.map +1 -0
  80. package/dist/values.d.ts +67 -0
  81. package/dist/values.js +293 -0
  82. package/dist/values.js.map +1 -0
  83. package/package.json +10 -3
  84. package/skills/testsurfer/SKILL.md +55 -0
@@ -0,0 +1,2025 @@
1
+ // @ts-nocheck
2
+ /**
3
+ * The page-side locator engine, installed lazily as `window.__tse`.
4
+ *
5
+ * Playwright locators address DOM elements, and most of the DOM (a
6
+ * plain `<div>` with text) never reaches vibesurfer's accessibility
7
+ * tree, so locators resolve here, in the page: CSS (piercing open
8
+ * shadow roots), XPath, text, role, label and attribute queries,
9
+ * chained, filtered and indexed, in one evaluate per call. vibesurfer
10
+ * still supplies trusted pointer input, layout and screenshots.
11
+ *
12
+ * This function is serialized with toString() and evaluated in the
13
+ * page, so it must be self-contained plain JavaScript (the file is
14
+ * excluded from type checking for that reason).
15
+ */
16
+ export function installEngine(SER) {
17
+ if (window.__tse)
18
+ return window.__tse;
19
+ // Page script may have replaced built-ins (window.Map = 1). Use the
20
+ // page's own when they are native, else a clean realm's.
21
+ const isNative = (f) => typeof f === 'function' && /\[native code\]/.test(Function.prototype.toString.call(f));
22
+ let cleanRealm = null;
23
+ const pristine = (name) => {
24
+ if (isNative(window[name]))
25
+ return window[name];
26
+ if (!cleanRealm) {
27
+ const f = document.createElement('iframe');
28
+ f.style.display = 'none';
29
+ (document.documentElement || document).appendChild(f);
30
+ cleanRealm = f.contentWindow;
31
+ f.remove();
32
+ }
33
+ return cleanRealm[name];
34
+ };
35
+ const Map = pristine('Map');
36
+ const Set = pristine('Set');
37
+ const WeakMap = pristine('WeakMap');
38
+ const WeakRef = pristine('WeakRef');
39
+ // --- basics ---------------------------------------------------------
40
+ const N = (s) => String(s == null ? '' : s).replace(/[\u200b\u00ad]/g, '').trim().replace(/\s+/g, ' ');
41
+ /** A label stands in for its control in value, check and fill operations, as in Playwright. */
42
+ const retarget = (e) => (e.nodeName === 'LABEL' && e.control ? e.control : e);
43
+ function parentOf(e) {
44
+ if (e.parentElement)
45
+ return e.parentElement;
46
+ const p = e.parentNode;
47
+ return p && p.nodeType === 11 && p.host ? p.host : null;
48
+ }
49
+ function contains(a, b) {
50
+ for (let e = b; e; e = parentOf(e))
51
+ if (e === a)
52
+ return true;
53
+ return false;
54
+ }
55
+ /** Elements under `root` in document order, entering open shadow roots. */
56
+ function allUnder(root, out) {
57
+ if (!out) {
58
+ // A scope element's own shadow root is part of its subtree, after its light children.
59
+ const top = [];
60
+ allUnder(root, top);
61
+ if (root.nodeType === 1 && root.shadowRoot)
62
+ allUnder(root.shadowRoot, top);
63
+ return top;
64
+ }
65
+ const kids = root.children || (root.nodeType === 9 ? [root.documentElement] : root.childNodes);
66
+ for (let i = 0; i < kids.length; i++) {
67
+ const c = kids[i];
68
+ if (!c || c.nodeType !== 1)
69
+ continue;
70
+ out.push(c);
71
+ // Light children before shadow content, as Playwright orders them.
72
+ allUnder(c, out);
73
+ if (c.shadowRoot)
74
+ allUnder(c.shadowRoot, out);
75
+ }
76
+ return out;
77
+ }
78
+ function docOrder(list) {
79
+ const seen = new Set();
80
+ const uniq = list.filter((e) => (seen.has(e) ? false : (seen.add(e), true)));
81
+ if (uniq.length < 2)
82
+ return uniq;
83
+ const rank = new Map();
84
+ const roots = new Set(uniq.map((e) => e.ownerDocument));
85
+ for (const d of roots)
86
+ allUnder(d).forEach((e, i) => rank.set(e, i));
87
+ return uniq.sort((a, b) => {
88
+ if (a.ownerDocument !== b.ownerDocument) {
89
+ return a.ownerDocument.compareDocumentPosition(b.ownerDocument) & 4 ? -1 : 1;
90
+ }
91
+ return (rank.get(a) ?? 0) - (rank.get(b) ?? 0);
92
+ });
93
+ }
94
+ function styleOf(e) {
95
+ const w = e.ownerDocument.defaultView || window;
96
+ return w.getComputedStyle(e);
97
+ }
98
+ // --- text -------------------------------------------------------------
99
+ const SKIP_TEXT = { SCRIPT: 1, NOSCRIPT: 1, STYLE: 1, TEMPLATE: 1, HEAD: 1 };
100
+ let textCache = new Map();
101
+ function elementText(e) {
102
+ if (textCache.has(e))
103
+ return textCache.get(e);
104
+ let t = '';
105
+ if (e.nodeType === 1 && SKIP_TEXT[e.nodeName])
106
+ t = '';
107
+ else if (e.nodeName === 'INPUT' && /^(button|submit|reset)$/i.test(e.type))
108
+ t = e.value;
109
+ else {
110
+ if (e.shadowRoot)
111
+ t += elementText(e.shadowRoot);
112
+ for (let c = e.firstChild; c; c = c.nextSibling) {
113
+ if (c.nodeType === 3)
114
+ t += c.nodeValue;
115
+ else if (c.nodeType === 1)
116
+ t += elementText(c);
117
+ }
118
+ }
119
+ textCache.set(e, t);
120
+ return t;
121
+ }
122
+ /** {s, exact} or {re:[src, flags]} -> predicate over raw text. */
123
+ function matcher(m, caseSensitiveDefault) {
124
+ if (!m)
125
+ return () => true;
126
+ if (m.re) {
127
+ const re = new RegExp(m.re[0], m.re[1].replace('g', ''));
128
+ return (t) => re.test(N(t));
129
+ }
130
+ const want = N(m.s);
131
+ if (m.exact)
132
+ return (t) => N(t) === want;
133
+ if (m.full)
134
+ return (t) => N(t).toLowerCase() === want.toLowerCase();
135
+ if (caseSensitiveDefault)
136
+ return (t) => N(t).includes(want);
137
+ const lw = want.toLowerCase();
138
+ return (t) => N(t).toLowerCase().includes(lw);
139
+ }
140
+ /**
141
+ * Exact text (`text="..."`, getByText exact): an element's full text
142
+ * when it has no child elements, otherwise one of its own text nodes.
143
+ */
144
+ function strictTextOk(e, want) {
145
+ if (!e.firstElementChild)
146
+ return N(elementText(e)) === want;
147
+ for (let c = e.firstChild; c; c = c.nextSibling)
148
+ if (c.nodeType === 3 && N(c.nodeValue) === want)
149
+ return true;
150
+ return false;
151
+ }
152
+ /** Playwright's text engine: the smallest elements whose text matches. */
153
+ function textQuery(root, m, legacy) {
154
+ if (legacy && m && m.exact && !m.re) {
155
+ const want = N(m.s);
156
+ const pool = root.nodeType === 1 ? [root, ...allUnder(root)] : allUnder(root);
157
+ return pool.filter((e) => !SKIP_TEXT[e.nodeName] && !(e.closest && e.closest('head')) && strictTextOk(e, want));
158
+ }
159
+ const ok = matcher(m);
160
+ // A text query chained off an element can match that element itself.
161
+ const pool = root.nodeType === 1 ? [root, ...allUnder(root)] : allUnder(root);
162
+ return pool.filter((e) => {
163
+ if (SKIP_TEXT[e.nodeName] || (e.closest && e.closest('head')))
164
+ return false;
165
+ if (!ok(elementText(e)))
166
+ return false;
167
+ for (let c = e.firstElementChild; c; c = c.nextElementSibling)
168
+ if (ok(elementText(c)))
169
+ return false;
170
+ if (e.shadowRoot)
171
+ for (let c = e.shadowRoot.firstElementChild; c; c = c.nextElementSibling)
172
+ if (ok(elementText(c)))
173
+ return false;
174
+ return true;
175
+ });
176
+ }
177
+ // --- visibility -------------------------------------------------------
178
+ function isVisible(e) {
179
+ if (!e.isConnected)
180
+ return false;
181
+ const st = styleOf(e);
182
+ if (st.display === 'contents') {
183
+ // A slot shows what is assigned to it, else its fallback children.
184
+ const assigned = e.nodeName === 'SLOT' ? e.assignedNodes({ flatten: true }) : [];
185
+ const kids = assigned.length ? assigned : [...e.childNodes];
186
+ for (const c of kids) {
187
+ if (c.nodeType === 1 && isVisible(c))
188
+ return true;
189
+ if (c.nodeType === 3) {
190
+ const r = document.createRange();
191
+ r.selectNodeContents(c);
192
+ const b = r.getBoundingClientRect();
193
+ if (b.width > 0 && b.height > 0)
194
+ return true;
195
+ }
196
+ }
197
+ return false;
198
+ }
199
+ if (st.visibility !== 'visible')
200
+ return false;
201
+ // Catches content inside a closed <details> and content-visibility.
202
+ if (typeof e.checkVisibility === 'function' && !e.checkVisibility())
203
+ return false;
204
+ const r = e.getBoundingClientRect();
205
+ return r.width > 0 && r.height > 0;
206
+ }
207
+ function hiddenForAria(e) {
208
+ if (tag(e) !== 'option' && styleOf(e).visibility === 'hidden')
209
+ return true;
210
+ // Not rendered: display:none somewhere above, unslotted shadow-host
211
+ // children, closed <details> content. <option> renders inside its
212
+ // select's popup, so only its own display counts.
213
+ if (tag(e) === 'option') {
214
+ if (styleOf(e).display === 'none')
215
+ return true;
216
+ }
217
+ else if (styleOf(e).display === 'contents') {
218
+ // No box of its own (a <slot>, a display:contents wrapper), so
219
+ // checkVisibility() says false; its content decides, below.
220
+ }
221
+ else if (typeof e.checkVisibility === 'function' && !e.checkVisibility()) {
222
+ return true;
223
+ }
224
+ for (let a = e; a; a = parentOf(a)) {
225
+ if (a.getAttribute && a.getAttribute('aria-hidden') === 'true')
226
+ return true;
227
+ if (a.nodeType === 1 && styleOf(a).display === 'none')
228
+ return true;
229
+ }
230
+ return false;
231
+ }
232
+ /** Rect in the top document's viewport, adding iframe offsets. */
233
+ function topRect(e) {
234
+ const r = e.getBoundingClientRect();
235
+ let x = r.left;
236
+ let y = r.top;
237
+ let w = e.ownerDocument.defaultView;
238
+ while (w && w.frameElement) {
239
+ const f = w.frameElement;
240
+ const fr = f.getBoundingClientRect();
241
+ x += fr.left + f.clientLeft;
242
+ y += fr.top + f.clientTop;
243
+ w = f.ownerDocument.defaultView;
244
+ }
245
+ return { x, y, width: r.width, height: r.height };
246
+ }
247
+ // --- roles and names --------------------------------------------------
248
+ const tag = (e) => e.nodeName.toLowerCase();
249
+ const attr = (e, n) => (e.getAttribute ? e.getAttribute(n) : null);
250
+ function landmarkScoped(e) {
251
+ for (let a = parentOf(e); a; a = parentOf(a)) {
252
+ if (/^(article|aside|main|nav|section)$/.test(tag(a)))
253
+ return true;
254
+ if (/^(article|complementary|main|navigation|region)$/.test(attr(a, 'role') || ''))
255
+ return true;
256
+ }
257
+ return false;
258
+ }
259
+ function implicitRole(e) {
260
+ const t = tag(e);
261
+ const type = (attr(e, 'type') || '').toLowerCase();
262
+ switch (t) {
263
+ case 'a':
264
+ case 'area':
265
+ return e.hasAttribute('href') ? 'link' : null;
266
+ case 'article': return 'article';
267
+ case 'aside': return 'complementary';
268
+ case 'blockquote': return 'blockquote';
269
+ case 'button': return 'button';
270
+ case 'caption': return 'caption';
271
+ case 'code': return 'code';
272
+ case 'datalist': return 'listbox';
273
+ case 'dd': return 'definition';
274
+ case 'del': return 'deletion';
275
+ case 'details': return 'group';
276
+ case 'dfn': return 'term';
277
+ case 'dialog': return 'dialog';
278
+ case 'dt': return 'term';
279
+ case 'em': return 'emphasis';
280
+ case 'fieldset': return 'group';
281
+ case 'figure': return 'figure';
282
+ case 'footer': return landmarkScoped(e) ? null : 'contentinfo';
283
+ case 'header': return landmarkScoped(e) ? null : 'banner';
284
+ case 'form': return accName(e) ? 'form' : null;
285
+ case 'h1':
286
+ case 'h2':
287
+ case 'h3':
288
+ case 'h4':
289
+ case 'h5':
290
+ case 'h6': return 'heading';
291
+ case 'hr': return 'separator';
292
+ case 'html': return 'document';
293
+ case 'img':
294
+ return attr(e, 'alt') === '' && !attr(e, 'title') && !attr(e, 'aria-label') && !attr(e, 'aria-labelledby')
295
+ ? 'presentation'
296
+ : 'img';
297
+ case 'input':
298
+ switch (type) {
299
+ case 'button':
300
+ case 'image':
301
+ case 'reset':
302
+ case 'submit': return 'button';
303
+ case 'checkbox': return 'checkbox';
304
+ case 'radio': return 'radio';
305
+ case 'range': return 'slider';
306
+ case 'number': return 'spinbutton';
307
+ case 'hidden': return null;
308
+ case 'file': return 'button';
309
+ case 'search': return e.hasAttribute('list') ? 'combobox' : 'searchbox';
310
+ default: return e.hasAttribute('list') ? 'combobox' : 'textbox';
311
+ }
312
+ case 'ins': return 'insertion';
313
+ case 'li': return 'listitem';
314
+ case 'main': return 'main';
315
+ case 'math': return 'math';
316
+ case 'menu': return 'list';
317
+ case 'meter': return 'meter';
318
+ case 'nav': return 'navigation';
319
+ case 'ol':
320
+ case 'ul': return 'list';
321
+ case 'optgroup': return 'group';
322
+ case 'option': return 'option';
323
+ case 'output': return 'status';
324
+ case 'p': return 'paragraph';
325
+ case 'progress': return 'progressbar';
326
+ case 'search': return 'search';
327
+ case 'section': return accName(e) ? 'region' : null;
328
+ case 'select': return e.multiple || e.size > 1 ? 'listbox' : 'combobox';
329
+ case 'strong': return 'strong';
330
+ case 'sub': return 'subscript';
331
+ case 'sup': return 'superscript';
332
+ case 'svg': return 'img';
333
+ case 'table': return 'table';
334
+ case 'tbody':
335
+ case 'thead':
336
+ case 'tfoot': return 'rowgroup';
337
+ case 'td': {
338
+ const tbl = e.closest('table');
339
+ const r = tbl && attr(tbl, 'role');
340
+ return r === 'grid' || r === 'treegrid' ? 'gridcell' : 'cell';
341
+ }
342
+ case 'th': {
343
+ const scope = attr(e, 'scope');
344
+ if (scope === 'row' || scope === 'rowgroup')
345
+ return 'rowheader';
346
+ return 'columnheader';
347
+ }
348
+ case 'textarea': return 'textbox';
349
+ case 'time': return 'time';
350
+ case 'tr': return 'row';
351
+ }
352
+ return null;
353
+ }
354
+ function roleOf(e) {
355
+ const explicit = (attr(e, 'role') || '').trim().split(/\s+/)[0];
356
+ if (explicit)
357
+ return explicit === 'none' ? 'presentation' : explicit;
358
+ return implicitRole(e);
359
+ }
360
+ /** The role without the name-dependent cases (form, section), for use inside name computation. */
361
+ function roleForName(e) {
362
+ const t = tag(e);
363
+ if (!attr(e, 'role') && (t === 'form' || t === 'section'))
364
+ return null;
365
+ return roleOf(e);
366
+ }
367
+ const NAME_FROM_CONTENT = new Set([
368
+ 'button', 'cell', 'checkbox', 'columnheader', 'gridcell', 'heading', 'link', 'menuitem',
369
+ 'menuitemcheckbox', 'menuitemradio', 'option', 'radio', 'row', 'rowheader', 'switch', 'tab',
370
+ 'tooltip', 'treeitem', 'listitem', 'term', 'definition',
371
+ ]);
372
+ /** CSS generated content (::before / ::after), which accessible names include. */
373
+ function pseudoText(e, which) {
374
+ try {
375
+ const c = (e.ownerDocument.defaultView || window).getComputedStyle(e, which).content;
376
+ if (!c || c === 'none' || c === 'normal')
377
+ return '';
378
+ const m = /^(["'])([\s\S]*)\1$/.exec(c);
379
+ return m ? m[2] : '';
380
+ }
381
+ catch (_) {
382
+ return '';
383
+ }
384
+ }
385
+ function contentName(e, skip, visited) {
386
+ let out = pseudoText(e, '::before');
387
+ const add = (s) => {
388
+ out += s;
389
+ };
390
+ const kids = e.shadowRoot ? [...e.shadowRoot.childNodes, ...e.childNodes] : [...e.childNodes];
391
+ for (const c of kids) {
392
+ if (c.nodeType === 3) {
393
+ add(c.nodeValue);
394
+ continue;
395
+ }
396
+ if (c.nodeType !== 1 || c === skip || SKIP_TEXT[c.nodeName])
397
+ continue;
398
+ if (hiddenForAria(c))
399
+ continue;
400
+ const block = /^(block|flex|grid|list-item|table)/.test(styleOf(c).display);
401
+ if (block)
402
+ add(' ');
403
+ if (c.nodeName === 'SLOT') {
404
+ for (const s of c.assignedNodes())
405
+ add(s.nodeType === 3 ? s.nodeValue : textAlternative(s, skip, visited, true));
406
+ }
407
+ else
408
+ add(textAlternative(c, skip, visited, true));
409
+ if (block)
410
+ add(' ');
411
+ }
412
+ out += pseudoText(e, '::after');
413
+ return out;
414
+ }
415
+ /** A simplified accname computation: labelledby, aria-label, native labels, content, title. */
416
+ function textAlternative(e, skip, visited, embedded) {
417
+ visited = visited || new Set();
418
+ if (visited.has(e))
419
+ return '';
420
+ visited.add(e);
421
+ const lb = attr(e, 'aria-labelledby');
422
+ if (lb && !embedded) {
423
+ const doc = e.getRootNode();
424
+ const parts = lb.split(/\s+/).map((id) => {
425
+ const t = doc.getElementById ? doc.getElementById(id) : e.ownerDocument.getElementById(id);
426
+ return t ? textAlternative(t, skip, visited, true) || N(t.textContent) : '';
427
+ });
428
+ const s = N(parts.join(' '));
429
+ if (s)
430
+ return s;
431
+ }
432
+ const al = N(attr(e, 'aria-label'));
433
+ if (al)
434
+ return al;
435
+ const t = tag(e);
436
+ if (t === 'input') {
437
+ const type = (e.type || '').toLowerCase();
438
+ if (embedded && !/^(button|submit|reset|image)$/.test(type))
439
+ return e.value || '';
440
+ if (/^(button|submit|reset)$/.test(type))
441
+ return e.value || (type === 'submit' ? 'Submit' : type === 'reset' ? 'Reset' : '');
442
+ if (type === 'image')
443
+ return attr(e, 'alt') || attr(e, 'title') || 'Submit';
444
+ }
445
+ if (embedded && t === 'select') {
446
+ const o = e.selectedOptions && e.selectedOptions[0];
447
+ return o ? N(o.textContent) : '';
448
+ }
449
+ if (embedded && t === 'textarea')
450
+ return e.value || '';
451
+ if (!embedded && e.labels && e.labels.length && t !== 'button') {
452
+ const s = N([...e.labels].map((l) => contentName(l, e, visited)).join(' '));
453
+ if (s)
454
+ return s;
455
+ }
456
+ if (t === 'img' || t === 'area') {
457
+ const alt = attr(e, 'alt');
458
+ if (alt)
459
+ return alt;
460
+ }
461
+ if (t === 'fieldset') {
462
+ const lg = [...e.children].find((c) => tag(c) === 'legend');
463
+ if (lg)
464
+ return N(contentName(lg, null, visited));
465
+ }
466
+ if (t === 'figure') {
467
+ const fc = [...e.children].find((c) => tag(c) === 'figcaption');
468
+ if (fc)
469
+ return N(contentName(fc, null, visited));
470
+ }
471
+ if (t === 'table' && e.caption)
472
+ return N(contentName(e.caption, null, visited));
473
+ if (t === 'svg') {
474
+ const st = [...e.children].find((c) => tag(c) === 'title');
475
+ if (st)
476
+ return N(st.textContent);
477
+ }
478
+ const role = roleForName(e);
479
+ if (embedded || NAME_FROM_CONTENT.has(role)) {
480
+ const s = contentName(e, skip, visited);
481
+ if (N(s))
482
+ return s;
483
+ }
484
+ return attr(e, 'title') || (!embedded && /^(input|textarea)$/.test(t) ? attr(e, 'placeholder') || '' : '');
485
+ }
486
+ function accName(e) {
487
+ return N(textAlternative(e, null, null, false));
488
+ }
489
+ function ariaChecked(e) {
490
+ if (tag(e) === 'input' && /^(checkbox|radio)$/i.test(e.type))
491
+ return e.indeterminate ? 'mixed' : e.checked;
492
+ const a = attr(e, 'aria-checked');
493
+ if (a === 'mixed')
494
+ return 'mixed';
495
+ if (a === 'true')
496
+ return true;
497
+ if (a === 'false')
498
+ return false;
499
+ return undefined;
500
+ }
501
+ function isDisabled(e) {
502
+ if (/^(button|input|select|textarea|option|optgroup|fieldset)$/.test(tag(e))) {
503
+ if (e.disabled)
504
+ return true;
505
+ if (tag(e) === 'option' && e.parentElement && tag(e.parentElement) === 'optgroup' && e.parentElement.disabled)
506
+ return true;
507
+ const fs = e.closest && e.closest('fieldset[disabled]');
508
+ if (fs) {
509
+ const lg = [...fs.children].find((c) => tag(c) === 'legend');
510
+ if (!lg || !lg.contains(e))
511
+ return true;
512
+ }
513
+ }
514
+ // aria-disabled reaches down only to elements that can be disabled.
515
+ if (attr(e, 'aria-disabled') === 'true')
516
+ return true;
517
+ const native = /^(button|input|select|textarea|option|optgroup|fieldset)$/.test(tag(e));
518
+ if (!native && !DISABLEABLE.has(roleOf(e) || ''))
519
+ return false;
520
+ for (let a = parentOf(e); a; a = parentOf(a))
521
+ if (attr(a, 'aria-disabled') === 'true')
522
+ return true;
523
+ return false;
524
+ }
525
+ const DISABLEABLE = new Set([
526
+ 'application', 'button', 'checkbox', 'columnheader', 'combobox', 'grid', 'gridcell', 'group', 'link',
527
+ 'listbox', 'menu', 'menubar', 'menuitem', 'menuitemcheckbox', 'menuitemradio', 'option', 'radio',
528
+ 'radiogroup', 'row', 'rowheader', 'scrollbar', 'searchbox', 'separator', 'slider', 'spinbutton',
529
+ 'switch', 'tab', 'tablist', 'textbox', 'toolbar', 'tree', 'treegrid', 'treeitem',
530
+ ]);
531
+ function roleQuery(root, q) {
532
+ const o = q.o || {};
533
+ const name = o.name ? matcher(o.name) : null;
534
+ return allUnder(root).filter((e) => {
535
+ if (roleOf(e) !== q.role)
536
+ return false;
537
+ if (!o.includeHidden && hiddenForAria(e))
538
+ return false;
539
+ if (o.checked !== undefined && (ariaChecked(e) ?? false) !== o.checked)
540
+ return false;
541
+ if (o.disabled !== undefined && isDisabled(e) !== o.disabled)
542
+ return false;
543
+ if (o.expanded !== undefined) {
544
+ const x = attr(e, 'aria-expanded');
545
+ if (x === null || (x === 'true') !== o.expanded)
546
+ return false;
547
+ }
548
+ if (o.pressed !== undefined) {
549
+ const p = attr(e, 'aria-pressed');
550
+ const v = p === 'mixed' ? 'mixed' : p === 'true';
551
+ if (v !== o.pressed)
552
+ return false;
553
+ }
554
+ if (o.selected !== undefined) {
555
+ const s = tag(e) === 'option' ? e.selected : attr(e, 'aria-selected') === 'true';
556
+ if (s !== o.selected)
557
+ return false;
558
+ }
559
+ if (o.level !== undefined) {
560
+ const m = /^h([1-6])$/.exec(tag(e));
561
+ const lvl = Number(attr(e, 'aria-level')) || (m ? Number(m[1]) : 0);
562
+ if (lvl !== o.level)
563
+ return false;
564
+ }
565
+ if (name && !name(accName(e)))
566
+ return false;
567
+ return true;
568
+ });
569
+ }
570
+ function labelsOf(e) {
571
+ const out = [];
572
+ if (e.labels)
573
+ for (const l of e.labels)
574
+ out.push(contentName(l, e));
575
+ const lb = attr(e, 'aria-labelledby');
576
+ if (lb) {
577
+ for (const id of lb.split(/\s+/)) {
578
+ const t = e.ownerDocument.getElementById(id);
579
+ if (t)
580
+ out.push(t.textContent);
581
+ }
582
+ }
583
+ const al = attr(e, 'aria-label');
584
+ if (al)
585
+ out.push(al);
586
+ return out;
587
+ }
588
+ function labelQuery(root, m) {
589
+ const ok = matcher(m);
590
+ return allUnder(root).filter((e) => labelsOf(e).some(ok));
591
+ }
592
+ function attrQuery(root, q) {
593
+ const ok = q.testid
594
+ ? q.t.re
595
+ ? matcher(q.t)
596
+ : (v) => v === q.t.s
597
+ : matcher(q.t);
598
+ return allUnder(root).filter((e) => {
599
+ const v = attr(e, q.a);
600
+ return v !== null && ok(v);
601
+ });
602
+ }
603
+ // --- CSS ---------------------------------------------------------------
604
+ //
605
+ // Playwright's CSS: the descendant combinator pierces open shadow
606
+ // roots, :scope and leading combinators refer to the chain's scope
607
+ // (so `>> ~ div` finds siblings), comma lists come back in document
608
+ // order, and :has-text(), :text(), :text-is(), :text-matches() and
609
+ // :visible work in any compound. Each compound is checked with the
610
+ // native matches(); combinators are walked here, right to left.
611
+ const CUSTOM_PSEUDO = /^(has-text|text|text-is|text-matches|visible|scope|is|where|not|has)$/;
612
+ const LIST_PSEUDO = /^(is|where|not|has)$/;
613
+ function splitList(s) {
614
+ const out = [];
615
+ let cur = '';
616
+ let depth = 0;
617
+ let quote = null;
618
+ for (let i = 0; i < s.length; i++) {
619
+ const c = s[i];
620
+ if (quote) {
621
+ cur += c;
622
+ if (c === '\\')
623
+ cur += s[++i] ?? '';
624
+ else if (c === quote)
625
+ quote = null;
626
+ continue;
627
+ }
628
+ if (c === '\\') {
629
+ cur += c + (s[++i] ?? '');
630
+ continue;
631
+ }
632
+ if (c === '"' || c === "'")
633
+ quote = c;
634
+ else if (c === '(' || c === '[')
635
+ depth++;
636
+ else if (c === ')' || c === ']')
637
+ depth--;
638
+ else if (c === ',' && depth === 0) {
639
+ out.push(cur);
640
+ cur = '';
641
+ continue;
642
+ }
643
+ cur += c;
644
+ }
645
+ out.push(cur);
646
+ return out;
647
+ }
648
+ /** A CSS string's value: `\a ` is a newline, `\"` a quote. */
649
+ const cssUnescape = (s) => s.replace(/\\([0-9a-fA-F]{1,6})\s?|\\([\s\S])/g, (_, hex, ch) => (hex ? String.fromCodePoint(parseInt(hex, 16)) : ch));
650
+ const unq = (v) => {
651
+ const m = /^\s*(["'])([\s\S]*)\1\s*$/.exec(v);
652
+ return m ? cssUnescape(m[2]) : v.trim();
653
+ };
654
+ /** One compound: native part for matches(), plus Playwright's own pseudos. */
655
+ function compound(src) {
656
+ let native = '';
657
+ const custom = [];
658
+ let depth = 0;
659
+ let quote = null;
660
+ for (let i = 0; i < src.length; i++) {
661
+ const c = src[i];
662
+ if (quote) {
663
+ native += c;
664
+ if (c === '\\')
665
+ native += src[++i] ?? '';
666
+ else if (c === quote)
667
+ quote = null;
668
+ continue;
669
+ }
670
+ if (c === '\\') {
671
+ native += c + (src[++i] ?? '');
672
+ continue;
673
+ }
674
+ if (c === '"' || c === "'")
675
+ quote = c;
676
+ else if (c === '(' || c === '[')
677
+ depth++;
678
+ else if (c === ')' || c === ']')
679
+ depth--;
680
+ else if (c === ':' && depth === 0 && src[i + 1] !== ':') {
681
+ const m = /^:([a-zA-Z-]+)/.exec(src.slice(i));
682
+ if (m && CUSTOM_PSEUDO.test(m[1])) {
683
+ let j = i + m[0].length;
684
+ let args = '';
685
+ if (src[j] === '(') {
686
+ let d = 0;
687
+ let qq = null;
688
+ const s0 = j;
689
+ for (; j < src.length; j++) {
690
+ const ch = src[j];
691
+ if (qq) {
692
+ if (ch === '\\')
693
+ j++;
694
+ else if (ch === qq)
695
+ qq = null;
696
+ continue;
697
+ }
698
+ if (ch === '"' || ch === "'")
699
+ qq = ch;
700
+ else if (ch === '(')
701
+ d++;
702
+ else if (ch === ')' && --d === 0)
703
+ break;
704
+ }
705
+ args = src.slice(s0 + 1, j);
706
+ j++;
707
+ }
708
+ custom.push(LIST_PSEUDO.test(m[1])
709
+ ? { name: m[1], list: splitList(args).map((x) => complex(x.trim())) }
710
+ : { name: m[1], args: splitList(args).map(unq), raw: args });
711
+ i = j - 1;
712
+ continue;
713
+ }
714
+ }
715
+ native += c;
716
+ }
717
+ return { native: native.trim() || '*', custom };
718
+ }
719
+ /** A complex selector as [compound, combinator, compound, ...]; a leading combinator gets :scope. */
720
+ function complex(sel) {
721
+ const parts = [];
722
+ let cur = '';
723
+ let depth = 0;
724
+ let quote = null;
725
+ const push = () => {
726
+ if (cur.trim())
727
+ parts.push(compound(cur.trim()));
728
+ cur = '';
729
+ };
730
+ for (let i = 0; i < sel.length; i++) {
731
+ const c = sel[i];
732
+ if (quote) {
733
+ cur += c;
734
+ if (c === '\\')
735
+ cur += sel[++i] ?? '';
736
+ else if (c === quote)
737
+ quote = null;
738
+ continue;
739
+ }
740
+ if (c === '\\') {
741
+ cur += c + (sel[++i] ?? '');
742
+ continue;
743
+ }
744
+ if (c === '"' || c === "'")
745
+ quote = c;
746
+ else if (c === '(' || c === '[')
747
+ depth++;
748
+ else if (c === ')' || c === ']')
749
+ depth--;
750
+ else if (depth === 0 && /[\s>+~]/.test(c)) {
751
+ push();
752
+ let comb = ' ';
753
+ let j = i;
754
+ while (j < sel.length && /[\s>+~]/.test(sel[j])) {
755
+ if (!/\s/.test(sel[j]))
756
+ comb = sel[j];
757
+ j++;
758
+ }
759
+ i = j - 1;
760
+ if (parts.length === 0) {
761
+ if (comb !== ' ')
762
+ parts.push(compound(':scope'), comb);
763
+ }
764
+ else if (j < sel.length)
765
+ parts.push(comb);
766
+ continue;
767
+ }
768
+ cur += c;
769
+ }
770
+ push();
771
+ return parts;
772
+ }
773
+ function customOk(e, c, scope) {
774
+ switch (c.name) {
775
+ case 'scope':
776
+ return e === scope;
777
+ case 'is':
778
+ case 'where':
779
+ return c.list.some((parts) => matchComplex(e, parts, parts.length - 1, scope, null, false));
780
+ case 'not':
781
+ return !c.list.some((parts) => matchComplex(e, parts, parts.length - 1, scope, null, false));
782
+ case 'has':
783
+ // Inside :has(), :scope is the element being tested.
784
+ {
785
+ // Sibling combinators can reach outside the element, so search its whole tree then.
786
+ const wide = c.list.some((parts) => parts.includes('+') || parts.includes('~'));
787
+ const pool = wide ? allUnder(e.getRootNode()) : [e, ...allUnder(e)];
788
+ return pool.some((d) => c.list.some((parts) => matchComplex(d, parts, parts.length - 1, e, e, false)));
789
+ }
790
+ }
791
+ if (/^(has-text|text|text-is)$/.test(c.name)) {
792
+ const raw = (c.raw || '').trim();
793
+ if (c.args.length !== 1 || (!/^(["'])[\s\S]*\1$/.test(raw) && /[\s>+~,]/.test(raw))) {
794
+ throw new Error(`Error: "${c.name === 'has-text' ? 'has-text' : 'text'}" engine expects a single string`);
795
+ }
796
+ }
797
+ if (c.name !== 'visible' && (SKIP_TEXT[e.nodeName] || (e.closest && e.closest('head'))))
798
+ return false;
799
+ const t = elementText(e);
800
+ const own = (ok) => {
801
+ if (!ok(t))
802
+ return false;
803
+ for (let k = e.firstElementChild; k; k = k.nextElementSibling)
804
+ if (ok(elementText(k)))
805
+ return false;
806
+ return true;
807
+ };
808
+ switch (c.name) {
809
+ case 'has-text':
810
+ return matcher({ s: c.args[0] || '' })(t);
811
+ case 'text':
812
+ return own(matcher({ s: c.args[0] || '' }));
813
+ case 'text-is':
814
+ return strictTextOk(e, N(c.args[0] || ''));
815
+ case 'text-matches':
816
+ return own(matcher({ re: [c.args[0] || '', c.args[1] || ''] }));
817
+ case 'visible':
818
+ return isVisible(e);
819
+ }
820
+ return false;
821
+ }
822
+ function cssError(sel) {
823
+ let bad = sel[sel.length - 1];
824
+ const stack = [];
825
+ for (const ch of sel) {
826
+ if (ch === '[' || ch === '(')
827
+ stack.push(ch);
828
+ else if (ch === ']' || ch === ')') {
829
+ if (!stack.length || stack.pop() !== (ch === ']' ? '[' : '(')) {
830
+ bad = ch;
831
+ break;
832
+ }
833
+ }
834
+ }
835
+ return new Error(`Error: Unexpected token "${bad}" while parsing css selector "${sel}". Did you mean to CSS.escape it?`);
836
+ }
837
+ /** A compound that names :scope, directly or inside :is()/:not()/... */
838
+ function hasScope(c) {
839
+ // A :scope inside :has() is :has's own element, not this one.
840
+ return c.custom.some((x) => x.name === 'scope' || (x.name !== 'has' && (x.list || []).some((parts) => parts.some((p) => typeof p === 'object' && hasScope(p)))));
841
+ }
842
+ /** Index of the first compound naming :scope at its top level, or -1. Cached on the parts array. */
843
+ function scopeIndex(parts) {
844
+ if (parts.sIdx === undefined) {
845
+ parts.sIdx = -1;
846
+ for (let i = 0; i < parts.length; i += 2) {
847
+ if (parts[i].custom.some((x) => x.name === 'scope')) {
848
+ parts.sIdx = i;
849
+ break;
850
+ }
851
+ }
852
+ }
853
+ return parts.sIdx;
854
+ }
855
+ /**
856
+ * Does `el` match compound i of `parts`, walking combinators
857
+ * leftward? With `bound`, matching starts at that element, as in
858
+ * jQuery and Playwright: a compound that does not name :scope must
859
+ * match inside it when it is the subject or an ancestor step (`>`,
860
+ * descendant); sibling steps may leave it, so `:scope ~ div` and
861
+ * `#a ~ :scope` work.
862
+ */
863
+ function matchComplex(el, parts, i, scope, bound, viaAncestor) {
864
+ const c = parts[i];
865
+ if (!el || el.nodeType !== 1 || !el.matches(c.native))
866
+ return false;
867
+ // The subject is bounded unless the selector names :scope (then
868
+ // :scope fixes where matching starts); ancestor steps always are.
869
+ const subjectBound = i === parts.length - 1 && scopeIndex(parts) < 0;
870
+ if (bound && (subjectBound || viaAncestor) && !(contains(bound, el) && (el !== bound || hasScope(c))))
871
+ return false;
872
+ for (const x of c.custom)
873
+ if (!customOk(el, x, scope))
874
+ return false;
875
+ if (i === 0)
876
+ return true;
877
+ switch (parts[i - 1]) {
878
+ case '>':
879
+ return matchComplex(parentOf(el), parts, i - 2, scope, bound, true);
880
+ case '+':
881
+ return matchComplex(el.previousElementSibling, parts, i - 2, scope, bound, false);
882
+ case '~':
883
+ for (let s = el.previousElementSibling; s; s = s.previousElementSibling)
884
+ if (matchComplex(s, parts, i - 2, scope, bound, false))
885
+ return true;
886
+ return false;
887
+ default:
888
+ for (let p = parentOf(el); p; p = parentOf(p))
889
+ if (matchComplex(p, parts, i - 2, scope, bound, true))
890
+ return true;
891
+ return false;
892
+ }
893
+ }
894
+ function validate(doc, parts, sel) {
895
+ for (let i = 0; i < parts.length; i += 2) {
896
+ try {
897
+ doc.querySelector(parts[i].native);
898
+ }
899
+ catch (_) {
900
+ throw cssError(sel);
901
+ }
902
+ for (const x of parts[i].custom)
903
+ for (const sub of x.list || [])
904
+ validate(doc, sub, sel);
905
+ }
906
+ }
907
+ function cssQuery(root, q) {
908
+ const scopeEl = root.nodeType === 9 ? root.documentElement : root.nodeType === 11 ? root.host : root;
909
+ const lists = splitList(q.sel).map((s) => s.trim()).filter(Boolean);
910
+ if (!lists.length)
911
+ throw cssError(q.sel);
912
+ const doc = root.nodeType === 9 ? root : root.ownerDocument;
913
+ const parsed = lists.map((l) => complex(l));
914
+ for (const parts of parsed)
915
+ validate(doc, parts, q.sel);
916
+ // :scope can reach siblings and the scope itself, so search the
917
+ // whole tree the scope lives in; otherwise only below it.
918
+ let pool;
919
+ if (/:scope/.test(q.sel) || parsed.some((parts) => parts[0].custom.some((c) => c.name === 'scope'))) {
920
+ const top = scopeEl.getRootNode();
921
+ pool = allUnder(top);
922
+ if (top.nodeType === 11)
923
+ pool.unshift(top.host);
924
+ }
925
+ else
926
+ pool = allUnder(root);
927
+ // Chained off an element (or a shadow root), matching is bounded by it.
928
+ const bound = root.nodeType === 9 ? null : scopeEl;
929
+ if (bound && root.nodeType === 1)
930
+ pool = [root, ...pool.filter((x) => x !== root)];
931
+ return pool.filter((e) => parsed.some((parts) => matchComplex(e, parts, parts.length - 1, scopeEl, bound, false)));
932
+ }
933
+ function xpathQuery(root, q) {
934
+ let xp = q.xp;
935
+ if (root.nodeType !== 9 && xp.startsWith('/'))
936
+ xp = '.' + xp;
937
+ const doc = root.nodeType === 9 ? root : root.ownerDocument;
938
+ const r = doc.evaluate(xp, root, null, 7, null);
939
+ const out = [];
940
+ for (let i = 0; i < r.snapshotLength; i++) {
941
+ const n = r.snapshotItem(i);
942
+ if (n && n.nodeType === 1)
943
+ out.push(n);
944
+ }
945
+ return out;
946
+ }
947
+ // --- resolution -------------------------------------------------------
948
+ function query(root, q) {
949
+ switch (q.k) {
950
+ case 'css':
951
+ if (q.light) {
952
+ try {
953
+ return [...root.querySelectorAll(q.sel)];
954
+ }
955
+ catch (_) {
956
+ throw cssError(q.sel);
957
+ }
958
+ }
959
+ return cssQuery(root, q);
960
+ case 'xpath': return xpathQuery(root, q);
961
+ case 'text': {
962
+ const found = textQuery(root, q.t, q.legacy);
963
+ // :light skips matches inside shadow roots.
964
+ return q.light ? found.filter((e) => !(e.getRootNode() instanceof ShadowRoot)) : found;
965
+ }
966
+ case 'role': return roleQuery(root, q);
967
+ case 'label': return labelQuery(root, q.t);
968
+ case 'attr': return attrQuery(root, q);
969
+ case 'and': {
970
+ const right = new Set(resolve(q.r, [root]));
971
+ return resolve(q.l, [root]).filter((e) => right.has(e));
972
+ }
973
+ case 'or': return docOrder([...resolve(q.l, [root]), ...resolve(q.r, [root])]);
974
+ }
975
+ throw new Error('unknown query ' + q.k);
976
+ }
977
+ function applyFilter(els, f) {
978
+ if (f.hasText) {
979
+ const ok = matcher(f.hasText);
980
+ els = els.filter((e) => ok(elementText(e)));
981
+ }
982
+ if (f.hasNotText) {
983
+ const ok = matcher(f.hasNotText);
984
+ els = els.filter((e) => !ok(elementText(e)));
985
+ }
986
+ if (f.has)
987
+ els = els.filter((e) => resolve(f.has, [e]).length > 0);
988
+ if (f.hasNot)
989
+ els = els.filter((e) => resolve(f.hasNot, [e]).length === 0);
990
+ if (f.visible !== undefined)
991
+ els = els.filter((e) => isVisible(e) === f.visible);
992
+ return els;
993
+ }
994
+ function pick(els, i) {
995
+ const e = i < 0 ? els[els.length + i] : els[i];
996
+ return e ? [e] : [];
997
+ }
998
+ /** Run a step chain. Each step searches inside the previous step's matches. */
999
+ function resolve(steps, roots) {
1000
+ let cur = roots;
1001
+ for (let si = 0; si < steps.length; si++) {
1002
+ const s = steps[si];
1003
+ if (s.q.k === 'self') {
1004
+ let out = cur.filter((e) => e.nodeType === 1);
1005
+ for (const f of s.f || [])
1006
+ out = applyFilter(out, f);
1007
+ if (s.i !== null && s.i !== undefined)
1008
+ out = pick(out, s.i);
1009
+ cur = out;
1010
+ }
1011
+ else if (s.q.k === 'handle') {
1012
+ const v = HANDLES.get(s.q.id);
1013
+ let out = isEl(v) ? [v] : [];
1014
+ for (const f of s.f || [])
1015
+ out = applyFilter(out, f);
1016
+ cur = out;
1017
+ }
1018
+ else if (s.q.k === 'frame') {
1019
+ // A frame hop needs exactly one <iframe> (first/last/nth pick one).
1020
+ if (cur.length > 1) {
1021
+ throw new Error(`Error: strict mode violation: ${s.q.d} resolved to ${cur.length} elements:\n` +
1022
+ cur.slice(0, 10).map((e, i) => ` ${i + 1}) ${preview(e)} aka ${aka(e)}`).join('\n'));
1023
+ }
1024
+ for (const e of cur) {
1025
+ if (e.nodeType === 1 && e.nodeName !== 'IFRAME' && e.nodeName !== 'FRAME') {
1026
+ throw new Error(`Error: ${s.q.d} resolved to ${preview(e)}, <iframe> was expected`);
1027
+ }
1028
+ }
1029
+ const docs = cur
1030
+ .map((e) => {
1031
+ try {
1032
+ return e.contentDocument;
1033
+ }
1034
+ catch (_) {
1035
+ return null;
1036
+ }
1037
+ })
1038
+ .filter(Boolean);
1039
+ // A cross-origin frame has a window but no document we may
1040
+ // read: the rest of the chain has to run inside it. Node does
1041
+ // that (`vs inspect eval --frame`) and moves points by `x, y`,
1042
+ // where the frame's content box sits in the top viewport.
1043
+ const xo = cur.length === 1 && docs.length === 0 && cur[0].contentWindow ? cur[0] : null;
1044
+ if (xo && steps.length > si + 1) {
1045
+ const t = topRect(xo);
1046
+ const cs = getComputedStyle(xo);
1047
+ const err = new Error(JSON.stringify({
1048
+ url: xo.src,
1049
+ rest: si + 1,
1050
+ x: t.x + xo.clientLeft + parseFloat(cs.paddingLeft || '0'),
1051
+ y: t.y + xo.clientTop + parseFloat(cs.paddingTop || '0'),
1052
+ }));
1053
+ err.name = 'XOFrame';
1054
+ throw err;
1055
+ }
1056
+ cur = docs;
1057
+ }
1058
+ else {
1059
+ let out = [];
1060
+ for (const r of cur)
1061
+ out.push(...query(r, s.q));
1062
+ out = cur.length > 1 ? docOrder(out) : out;
1063
+ for (const f of s.f || [])
1064
+ out = applyFilter(out, f);
1065
+ if (s.i !== null && s.i !== undefined)
1066
+ out = pick(out, s.i);
1067
+ cur = out;
1068
+ }
1069
+ }
1070
+ return cur;
1071
+ }
1072
+ // --- descriptions -----------------------------------------------------
1073
+ const VOID = new Set(['AREA', 'BASE', 'BR', 'COL', 'COMMAND', 'EMBED', 'HR', 'IMG', 'INPUT', 'KEYGEN', 'LINK', 'MENUITEM', 'META', 'PARAM', 'SOURCE', 'TRACK', 'WBR']);
1074
+ const BOOL_ATTR = new Set(['checked', 'selected', 'disabled', 'readonly', 'multiple']);
1075
+ const trim = (s, n) => (s.length > n ? s.slice(0, n - 1) + '\u2026' : s);
1076
+ /** An element as Playwright previews it in logs and strict-mode errors. */
1077
+ function preview(e) {
1078
+ if (e.nodeType === 9)
1079
+ return '#document';
1080
+ if (e.nodeType === 11)
1081
+ return '#document-fragment';
1082
+ const name = tag(e);
1083
+ const attrs = [...e.attributes]
1084
+ .filter((a) => a.name !== 'style' && a.name !== 'data-vs-ref')
1085
+ .map((a) => (!a.value && BOOL_ATTR.has(a.name) ? ` ${a.name}` : ` ${a.name}="${a.value}"`))
1086
+ .sort((a, b) => a.length - b.length);
1087
+ const at = trim(attrs.join(''), 500);
1088
+ const line = (s) => s.replace(/\n/g, '↵').replace(/\t/g, '⇆');
1089
+ if (VOID.has(e.nodeName))
1090
+ return line(`<${name}${at}/>`);
1091
+ const kids = e.childNodes;
1092
+ let onlyText = kids.length <= 5;
1093
+ for (const c of kids)
1094
+ onlyText = onlyText && c.nodeType === 3;
1095
+ const text = onlyText ? e.textContent || '' : kids.length ? '\u2026' : '';
1096
+ return line(`<${name}${at}>${trim(text, 50)}</${name}>`);
1097
+ }
1098
+ /** A short locator for an element, for strict-mode lists (Playwright's "aka"). */
1099
+ function aka(e) {
1100
+ const qs = (s) => `'${String(s).replace(/\\/g, '\\\\').replace(/'/g, "\\'")}'`;
1101
+ const tid = attr(e, 'data-testid');
1102
+ if (tid)
1103
+ return `getByTestId(${qs(tid)})`;
1104
+ const role = roleOf(e);
1105
+ const name = role ? accName(e) : '';
1106
+ if (role && name && !/^(generic|presentation|paragraph)$/.test(role))
1107
+ return `getByRole(${qs(role)}, { name: ${qs(name)} })`;
1108
+ const text = N(elementText(e));
1109
+ if (text && text.length <= 80)
1110
+ return `getByText(${qs(text)})`;
1111
+ if (role)
1112
+ return `getByRole(${qs(role)})`;
1113
+ if (e.id)
1114
+ return `locator(${qs('#' + e.id)})`;
1115
+ return `locator(${qs(tag(e))})`;
1116
+ }
1117
+ // --- input helpers ----------------------------------------------------
1118
+ const KEYS = {
1119
+ Enter: { code: 'Enter', keyCode: 13, text: '\r' },
1120
+ Tab: { code: 'Tab', keyCode: 9 },
1121
+ Backspace: { code: 'Backspace', keyCode: 8 },
1122
+ Delete: { code: 'Delete', keyCode: 46 },
1123
+ Escape: { code: 'Escape', keyCode: 27 },
1124
+ ArrowUp: { code: 'ArrowUp', keyCode: 38 },
1125
+ ArrowDown: { code: 'ArrowDown', keyCode: 40 },
1126
+ ArrowLeft: { code: 'ArrowLeft', keyCode: 37 },
1127
+ ArrowRight: { code: 'ArrowRight', keyCode: 39 },
1128
+ Home: { code: 'Home', keyCode: 36 },
1129
+ End: { code: 'End', keyCode: 35 },
1130
+ PageUp: { code: 'PageUp', keyCode: 33 },
1131
+ PageDown: { code: 'PageDown', keyCode: 34 },
1132
+ Shift: { code: 'ShiftLeft', keyCode: 16 },
1133
+ Control: { code: 'ControlLeft', keyCode: 17 },
1134
+ Alt: { code: 'AltLeft', keyCode: 18 },
1135
+ Meta: { code: 'MetaLeft', keyCode: 91 },
1136
+ Insert: { code: 'Insert', keyCode: 45 },
1137
+ F1: { code: 'F1', keyCode: 112 }, F2: { code: 'F2', keyCode: 113 }, F5: { code: 'F5', keyCode: 116 },
1138
+ ' ': { code: 'Space', keyCode: 32, text: ' ' },
1139
+ };
1140
+ const isMac = /Mac/.test(navigator.platform);
1141
+ function keyInfo(k, shift) {
1142
+ if (k === 'ControlOrMeta')
1143
+ k = isMac ? 'Meta' : 'Control';
1144
+ if (KEYS[k])
1145
+ return { key: k, ...KEYS[k] };
1146
+ if (k.length === 1 && k.charCodeAt(0) > 126)
1147
+ throw new Error(`Error: Unknown key: "${k}"`);
1148
+ if ([...k].length === 1 && k.length > 1)
1149
+ throw new Error(`Error: Unknown key: "${k}"`);
1150
+ if (k.length === 1) {
1151
+ const ch = shift && /[a-z]/.test(k) ? k.toUpperCase() : k;
1152
+ const up = k.toUpperCase();
1153
+ const code = /[A-Z]/.test(up) ? 'Key' + up : /[0-9]/.test(k) ? 'Digit' + k : '';
1154
+ return { key: ch, code, keyCode: up.charCodeAt(0), text: ch };
1155
+ }
1156
+ // Physical key codes Playwright also accepts as key names.
1157
+ const CODES = { Space: ' ', Minus: '-', Equal: '=', BracketLeft: '[', BracketRight: ']', Backslash: '\\', Semicolon: ';', Quote: "'", Comma: ',', Period: '.', Slash: '/', Backquote: '\x60', ShiftLeft: 'Shift', ShiftRight: 'Shift', ControlLeft: 'Control', ControlRight: 'Control', AltLeft: 'Alt', AltRight: 'Alt', MetaLeft: 'Meta', MetaRight: 'Meta', NumpadEnter: 'Enter' };
1158
+ if (CODES[k])
1159
+ return keyInfo(CODES[k], shift);
1160
+ if (/^Key[A-Z]$/.test(k))
1161
+ return keyInfo(k.slice(3).toLowerCase(), shift);
1162
+ if (/^Digit[0-9]$/.test(k))
1163
+ return keyInfo(k.slice(5), shift);
1164
+ if (/^F([1-9]|1[0-2])$/.test(k))
1165
+ return { key: k, code: k, keyCode: 111 + Number(k.slice(1)) };
1166
+ if (/^(CapsLock|NumLock|ScrollLock|Pause|ContextMenu|PrintScreen|AltGraph|Hyper|Super|Fn)$/.test(k))
1167
+ return { key: k, code: k, keyCode: 0 };
1168
+ throw new Error(`Error: Unknown key: "${k}"`);
1169
+ }
1170
+ function splitChord(chord) {
1171
+ const parts = chord.split('+');
1172
+ // "Shift++" and "+" name the plus key.
1173
+ if (parts.length > 1 && parts[parts.length - 1] === '') {
1174
+ parts.pop();
1175
+ parts[parts.length - 1] = '+';
1176
+ }
1177
+ return { mods: parts.slice(0, -1), key: parts[parts.length - 1] };
1178
+ }
1179
+ function editableTarget(e) {
1180
+ if (!e)
1181
+ return false;
1182
+ if (tag(e) === 'textarea')
1183
+ return !e.readOnly && !e.disabled;
1184
+ if (tag(e) === 'input')
1185
+ return !e.readOnly && !e.disabled && !/^(checkbox|radio|button|submit|reset|image|file|hidden|range|color)$/i.test(e.type);
1186
+ return !!e.isContentEditable;
1187
+ }
1188
+ function deepActive(doc) {
1189
+ let a = (doc || document).activeElement;
1190
+ for (;;) {
1191
+ if (a && a.shadowRoot && a.shadowRoot.activeElement)
1192
+ a = a.shadowRoot.activeElement;
1193
+ else if (a && /^(IFRAME|FRAME)$/.test(a.nodeName)) {
1194
+ let d = null;
1195
+ try {
1196
+ d = a.contentDocument;
1197
+ }
1198
+ catch (_) { }
1199
+ if (!d || !d.activeElement)
1200
+ break;
1201
+ a = d.activeElement;
1202
+ }
1203
+ else
1204
+ break;
1205
+ }
1206
+ return a;
1207
+ }
1208
+ function insertText(target, text) {
1209
+ const doc = target.ownerDocument;
1210
+ if (doc.execCommand('insertText', false, text))
1211
+ return;
1212
+ if ('value' in target && typeof target.selectionStart === 'number') {
1213
+ const s = target.selectionStart;
1214
+ const v = target.value;
1215
+ target.value = v.slice(0, s) + text + v.slice(target.selectionEnd);
1216
+ target.setSelectionRange(s + text.length, s + text.length);
1217
+ target.dispatchEvent(new InputEvent('input', { bubbles: true, composed: true, data: text, inputType: 'insertText' }));
1218
+ }
1219
+ }
1220
+ function moveFocus(from, back) {
1221
+ const doc = from ? from.ownerDocument : document;
1222
+ const all = allUnder(doc).filter((e) => e.tabIndex >= 0 && !isDisabled(e) && isVisible(e) && (e.tabIndex > 0 || /^(a|button|input|select|textarea|iframe|summary)$/.test(tag(e)) || e.hasAttribute('tabindex') || e.isContentEditable));
1223
+ const i = all.indexOf(from);
1224
+ const next = all[back ? (i <= 0 ? all.length - 1 : i - 1) : (i + 1) % all.length];
1225
+ if (next)
1226
+ next.focus();
1227
+ }
1228
+ const held = new Set();
1229
+ function keyEvent(target, type, info, mods) {
1230
+ const KE = (target.ownerDocument.defaultView || window).KeyboardEvent;
1231
+ const ev = new KE(type, {
1232
+ key: info.key,
1233
+ code: info.code,
1234
+ keyCode: info.keyCode,
1235
+ which: info.keyCode,
1236
+ charCode: type === 'keypress' ? (info.text || '').charCodeAt(0) || 0 : 0,
1237
+ bubbles: true,
1238
+ cancelable: true,
1239
+ composed: true,
1240
+ shiftKey: mods.has('Shift'),
1241
+ ctrlKey: mods.has('Control'),
1242
+ altKey: mods.has('Alt'),
1243
+ metaKey: mods.has('Meta'),
1244
+ location: 0,
1245
+ });
1246
+ // keyCode/which are read-only in the init dict on some engines.
1247
+ try {
1248
+ Object.defineProperty(ev, 'keyCode', { get: () => info.keyCode });
1249
+ Object.defineProperty(ev, 'which', { get: () => (type === 'keypress' ? ev.charCode || info.keyCode : info.keyCode) });
1250
+ }
1251
+ catch (_) { }
1252
+ return target.dispatchEvent(ev);
1253
+ }
1254
+ /** One key press with its default action, roughly as a browser would do it. */
1255
+ function pressKey(chord, phase) {
1256
+ const { mods: modList, key } = splitChord(chord);
1257
+ const mods = new Set([...held, ...modList.map((m) => (m === 'ControlOrMeta' ? (isMac ? 'Meta' : 'Control') : m))]);
1258
+ const info = keyInfo(key, mods.has('Shift'));
1259
+ const target = deepActive() || document.body;
1260
+ const down = phase !== 'up';
1261
+ const up = phase !== 'down';
1262
+ if (down) {
1263
+ for (const m of modList)
1264
+ keyEvent(target, 'keydown', keyInfo(m), mods);
1265
+ const ok = keyEvent(target, 'keydown', info, mods);
1266
+ if (/^(Shift|Control|Alt|Meta)$/.test(info.key)) {
1267
+ if (phase === 'down')
1268
+ held.add(info.key);
1269
+ }
1270
+ else if (ok)
1271
+ defaultAction(target, info, mods);
1272
+ }
1273
+ if (up) {
1274
+ keyEvent(deepActive() || target, 'keyup', info, mods);
1275
+ if (phase === 'up')
1276
+ held.delete(info.key);
1277
+ for (const m of modList.slice().reverse())
1278
+ keyEvent(deepActive() || target, 'keyup', keyInfo(m), mods);
1279
+ }
1280
+ }
1281
+ /** Arrow, Page and Home/End keys on a range or number input step its value, as the browser does. */
1282
+ function stepValue(target, key) {
1283
+ if (tag(target) !== 'input' || !/^(range|number)$/.test(target.type) || target.disabled || target.readOnly)
1284
+ return false;
1285
+ const deltas = { ArrowUp: 1, ArrowRight: 1, ArrowDown: -1, ArrowLeft: -1, PageUp: 10, PageDown: -10 };
1286
+ if (!(key in deltas) && key !== 'Home' && key !== 'End')
1287
+ return false;
1288
+ // Left and Right edit the text of a number field; only Up and Down step it.
1289
+ if (target.type === 'number' && !/^Arrow(Up|Down)$/.test(key))
1290
+ return false;
1291
+ const before = target.value;
1292
+ if (key === 'Home' || key === 'End') {
1293
+ if (target.type !== 'range')
1294
+ return false;
1295
+ target.value = key === 'Home' ? target.min || '0' : target.max || '100';
1296
+ }
1297
+ else {
1298
+ const n = deltas[key];
1299
+ try {
1300
+ if (n > 0)
1301
+ target.stepUp(Math.abs(n));
1302
+ else
1303
+ target.stepDown(Math.abs(n));
1304
+ }
1305
+ catch (_) {
1306
+ return false;
1307
+ }
1308
+ }
1309
+ if (target.value !== before) {
1310
+ target.dispatchEvent(new Event('input', { bubbles: true, composed: true }));
1311
+ target.dispatchEvent(new Event('change', { bubbles: true }));
1312
+ }
1313
+ return true;
1314
+ }
1315
+ function defaultAction(target, info, mods) {
1316
+ const cmd = mods.has('Control') || mods.has('Meta');
1317
+ const editable = editableTarget(target);
1318
+ if (!cmd && stepValue(target, info.key))
1319
+ return;
1320
+ if (cmd) {
1321
+ if (info.key.toLowerCase() === 'a') {
1322
+ if ('select' in target && editable && typeof target.select === 'function')
1323
+ target.select();
1324
+ else
1325
+ target.ownerDocument.execCommand('selectAll');
1326
+ }
1327
+ return;
1328
+ }
1329
+ if (info.text !== undefined && info.key !== 'Enter') {
1330
+ const ok = keyEvent(target, 'keypress', info, mods);
1331
+ if (ok && editable)
1332
+ insertText(target, info.text);
1333
+ return;
1334
+ }
1335
+ switch (info.key) {
1336
+ case 'Enter': {
1337
+ const ok = keyEvent(target, 'keypress', info, mods);
1338
+ if (!ok)
1339
+ return;
1340
+ if (tag(target) === 'textarea' || (target.isContentEditable && editable)) {
1341
+ target.ownerDocument.execCommand(target.isContentEditable ? 'insertParagraph' : 'insertLineBreak') ||
1342
+ insertText(target, '\n');
1343
+ }
1344
+ else if (tag(target) === 'input' && target.form) {
1345
+ const f = target.form;
1346
+ const b = f.querySelector('button:not([type]),button[type=submit],input[type=submit],input[type=image]');
1347
+ if (b)
1348
+ b.click();
1349
+ else
1350
+ f.requestSubmit ? f.requestSubmit() : f.submit();
1351
+ }
1352
+ else if (/^(a|button)$/.test(tag(target)) || (tag(target) === 'input' && /^(button|submit|reset)$/i.test(target.type))) {
1353
+ target.click();
1354
+ }
1355
+ return;
1356
+ }
1357
+ case 'Backspace':
1358
+ if (editable)
1359
+ target.ownerDocument.execCommand('delete');
1360
+ return;
1361
+ case 'Delete':
1362
+ if (editable)
1363
+ target.ownerDocument.execCommand('forwardDelete');
1364
+ return;
1365
+ case 'Tab':
1366
+ moveFocus(target, mods.has('Shift'));
1367
+ return;
1368
+ case 'ArrowLeft':
1369
+ case 'ArrowRight':
1370
+ case 'Home':
1371
+ case 'End':
1372
+ if (editable && typeof target.selectionStart === 'number') {
1373
+ const len = target.value.length;
1374
+ let p = target.selectionStart;
1375
+ if (info.key === 'ArrowLeft')
1376
+ p = Math.max(0, (target.selectionStart === target.selectionEnd ? p - 1 : p));
1377
+ else if (info.key === 'ArrowRight')
1378
+ p = Math.min(len, target.selectionStart === target.selectionEnd ? target.selectionEnd + 1 : target.selectionEnd);
1379
+ else
1380
+ p = info.key === 'Home' ? 0 : len;
1381
+ if (mods.has('Shift'))
1382
+ target.setSelectionRange(Math.min(p, target.selectionStart), Math.max(p, target.selectionEnd));
1383
+ else
1384
+ target.setSelectionRange(p, p);
1385
+ }
1386
+ return;
1387
+ case ' ':
1388
+ return;
1389
+ }
1390
+ }
1391
+ function mouseEvent(e, type, x, y, o) {
1392
+ const w = e.ownerDocument.defaultView || window;
1393
+ const Ctor = /^(pointer)/.test(type) ? w.PointerEvent || w.MouseEvent : w.MouseEvent;
1394
+ const ev = new Ctor(type, {
1395
+ bubbles: true,
1396
+ cancelable: true,
1397
+ composed: true,
1398
+ clientX: x,
1399
+ clientY: y,
1400
+ button: o.button,
1401
+ buttons: o.buttons || 0,
1402
+ detail: o.detail || 1,
1403
+ view: w,
1404
+ shiftKey: o.mods.has('Shift'),
1405
+ ctrlKey: o.mods.has('Control'),
1406
+ altKey: o.mods.has('Alt'),
1407
+ metaKey: o.mods.has('Meta'),
1408
+ pointerId: 1,
1409
+ pointerType: 'mouse',
1410
+ isPrimary: true,
1411
+ });
1412
+ return e.dispatchEvent(ev);
1413
+ }
1414
+ /** A synthetic click sequence, for buttons, modifiers and click counts native input cannot express. */
1415
+ function synthClick(e, a) {
1416
+ const button = { left: 0, middle: 1, right: 2 }[a.button || 'left'];
1417
+ const mods = new Set(a.modifiers || []);
1418
+ const r = e.getBoundingClientRect();
1419
+ const x = r.left + (a.position ? a.position.x : r.width / 2);
1420
+ const y = r.top + (a.position ? a.position.y : r.height / 2);
1421
+ const count = a.clickCount || 1;
1422
+ const o = { button, mods, buttons: 1 << (button === 1 ? 2 : button === 2 ? 1 : 0) };
1423
+ mouseEvent(e, 'pointerover', x, y, o);
1424
+ mouseEvent(e, 'mouseover', x, y, o);
1425
+ mouseEvent(e, 'pointermove', x, y, o);
1426
+ mouseEvent(e, 'mousemove', x, y, o);
1427
+ for (let i = 1; i <= count; i++) {
1428
+ o.detail = i;
1429
+ mouseEvent(e, 'pointerdown', x, y, o);
1430
+ if (mouseEvent(e, 'mousedown', x, y, o) && i === 1) {
1431
+ // The default action of a press: focus the nearest focusable ancestor, or clear focus.
1432
+ const f = e.closest('a[href],button,input,select,textarea,iframe,summary,[tabindex],[contenteditable]');
1433
+ const act = deepActive(e.ownerDocument);
1434
+ if (f && !isDisabled(f))
1435
+ f.focus();
1436
+ else if (act && act !== e.ownerDocument.body && !contains(act, e) && typeof act.blur === 'function')
1437
+ act.blur();
1438
+ }
1439
+ o.buttons = 0;
1440
+ mouseEvent(e, 'pointerup', x, y, o);
1441
+ mouseEvent(e, 'mouseup', x, y, o);
1442
+ if (button === 0) {
1443
+ if (i === 1 && typeof e.click === 'function' && !a.modifiers?.length)
1444
+ e.click();
1445
+ else
1446
+ mouseEvent(e, 'click', x, y, o);
1447
+ }
1448
+ else if (button === 2)
1449
+ mouseEvent(e, 'contextmenu', x, y, o);
1450
+ else
1451
+ mouseEvent(e, 'auxclick', x, y, o);
1452
+ if (i === 2 && button === 0)
1453
+ mouseEvent(e, 'dblclick', x, y, o);
1454
+ }
1455
+ }
1456
+ const EVENT_CLASS = {
1457
+ click: 'MouseEvent', dblclick: 'MouseEvent', mousedown: 'MouseEvent', mouseup: 'MouseEvent',
1458
+ mouseover: 'MouseEvent', mouseout: 'MouseEvent', mouseenter: 'MouseEvent', mouseleave: 'MouseEvent',
1459
+ mousemove: 'MouseEvent', contextmenu: 'MouseEvent', auxclick: 'MouseEvent',
1460
+ keydown: 'KeyboardEvent', keyup: 'KeyboardEvent', keypress: 'KeyboardEvent',
1461
+ pointerdown: 'PointerEvent', pointerup: 'PointerEvent', pointermove: 'PointerEvent',
1462
+ pointerover: 'PointerEvent', pointerout: 'PointerEvent', pointerenter: 'PointerEvent', pointerleave: 'PointerEvent',
1463
+ focus: 'FocusEvent', blur: 'FocusEvent', focusin: 'FocusEvent', focusout: 'FocusEvent',
1464
+ input: 'InputEvent', beforeinput: 'InputEvent',
1465
+ drag: 'DragEvent', dragstart: 'DragEvent', dragend: 'DragEvent', dragenter: 'DragEvent',
1466
+ dragleave: 'DragEvent', dragover: 'DragEvent', drop: 'DragEvent',
1467
+ touchstart: 'TouchEvent', touchend: 'TouchEvent', touchmove: 'TouchEvent', wheel: 'WheelEvent',
1468
+ };
1469
+ function dispatch(e, type, init) {
1470
+ const w = e.ownerDocument.defaultView || window;
1471
+ const cls = w[EVENT_CLASS[type]] || w.Event;
1472
+ const ev = new cls(type, { bubbles: true, cancelable: true, composed: true, ...(init || {}) });
1473
+ e.dispatchEvent(ev);
1474
+ }
1475
+ function fill(e, value) {
1476
+ const t = tag(e);
1477
+ if (t === 'input') {
1478
+ const type = (e.type || 'text').toLowerCase();
1479
+ if (/^(checkbox|radio|file|button|submit|reset|image|hidden|range)$/.test(type)) {
1480
+ throw new Error(`Error: Input of type "${type}" cannot be filled`);
1481
+ }
1482
+ if (/^(date|time|datetime-local|month|week|color|number)$/.test(type)) {
1483
+ e.focus();
1484
+ const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value').set;
1485
+ setter.call(e, value);
1486
+ if (type === 'number' && value !== '' && e.value === '')
1487
+ throw new Error('Error: Cannot type text into input[type=number]');
1488
+ e.dispatchEvent(new Event('input', { bubbles: true, composed: true }));
1489
+ e.dispatchEvent(new Event('change', { bubbles: true }));
1490
+ return;
1491
+ }
1492
+ }
1493
+ else if (t !== 'textarea' && !e.isContentEditable) {
1494
+ throw new Error('Error: Element is not an <input>, <textarea> or [contenteditable] element');
1495
+ }
1496
+ e.focus();
1497
+ if (t === 'input' || t === 'textarea') {
1498
+ e.select();
1499
+ }
1500
+ else {
1501
+ const sel = e.ownerDocument.getSelection();
1502
+ const r = e.ownerDocument.createRange();
1503
+ r.selectNodeContents(e);
1504
+ sel.removeAllRanges();
1505
+ sel.addRange(r);
1506
+ }
1507
+ const doc = e.ownerDocument;
1508
+ if (value === '') {
1509
+ if (!doc.execCommand('delete') && 'value' in e) {
1510
+ e.value = '';
1511
+ e.dispatchEvent(new InputEvent('input', { bubbles: true, composed: true, inputType: 'deleteContent' }));
1512
+ }
1513
+ }
1514
+ else if (!doc.execCommand('insertText', false, value)) {
1515
+ if ('value' in e) {
1516
+ const proto = t === 'textarea' ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype;
1517
+ Object.getOwnPropertyDescriptor(proto, 'value').set.call(e, value);
1518
+ }
1519
+ else
1520
+ e.textContent = value;
1521
+ e.dispatchEvent(new InputEvent('input', { bubbles: true, composed: true, data: value, inputType: 'insertText' }));
1522
+ }
1523
+ if (t === 'input' || t === 'textarea')
1524
+ e.dispatchEvent(new Event('change', { bubbles: true }));
1525
+ }
1526
+ function selectOption(e, wanted) {
1527
+ if (tag(e) !== 'select')
1528
+ throw new Error('Error: Element is not a <select> element');
1529
+ if (isDisabled(e))
1530
+ throw new Error('Error: Element is not enabled');
1531
+ const opts = [...e.options];
1532
+ const chosen = [];
1533
+ for (const w of wanted) {
1534
+ const o = opts.find((op) => w.index !== undefined
1535
+ ? op.index === w.index
1536
+ : w.value !== undefined && w.label !== undefined
1537
+ ? op.value === w.value && op.label === w.label
1538
+ : w.value !== undefined
1539
+ ? op.value === w.value
1540
+ : w.label !== undefined
1541
+ ? op.label === w.label
1542
+ : op.value === w.valueOrLabel || op.label === w.valueOrLabel);
1543
+ if (!o)
1544
+ return { missing: true };
1545
+ if (o.disabled)
1546
+ throw new Error('Error: Option being selected is not enabled');
1547
+ chosen.push(o);
1548
+ if (!e.multiple)
1549
+ break;
1550
+ }
1551
+ if (wanted.length && !chosen.length)
1552
+ return { missing: true };
1553
+ for (const o of opts)
1554
+ o.selected = chosen.includes(o);
1555
+ if (!wanted.length)
1556
+ e.selectedIndex = -1;
1557
+ e.dispatchEvent(new Event('input', { bubbles: true, composed: true }));
1558
+ e.dispatchEvent(new Event('change', { bubbles: true }));
1559
+ return { values: chosen.map((o) => o.value) };
1560
+ }
1561
+ // --- element ops ------------------------------------------------------
1562
+ function inputValue(e) {
1563
+ if (/^(input|textarea|select)$/.test(tag(e)))
1564
+ return e.value;
1565
+ throw new Error('Error: Node is not an <input>, <textarea> or <select> element');
1566
+ }
1567
+ function checkedState(e) {
1568
+ if (tag(e) === 'input' && /^(checkbox|radio)$/i.test(e.type))
1569
+ return e.checked;
1570
+ const c = ariaChecked(e);
1571
+ if (c === undefined) {
1572
+ const role = roleOf(e);
1573
+ if (!/^(checkbox|radio|switch|menuitemcheckbox|menuitemradio|option|treeitem)$/.test(role || '')) {
1574
+ throw new Error('Error: Not a checkbox or radio button');
1575
+ }
1576
+ return false;
1577
+ }
1578
+ return c === true;
1579
+ }
1580
+ function isEditable(e) {
1581
+ if (isDisabled(e))
1582
+ return false;
1583
+ if (/^(input|textarea|select)$/.test(tag(e))) {
1584
+ if (tag(e) === 'input' && /^(checkbox|radio|button|submit|reset|image|file|hidden|range|color)$/i.test(e.type)) {
1585
+ return !e.readOnly;
1586
+ }
1587
+ return !e.readOnly && attr(e, 'aria-readonly') !== 'true';
1588
+ }
1589
+ if (e.isContentEditable)
1590
+ return attr(e, 'aria-readonly') !== 'true';
1591
+ const role = roleOf(e);
1592
+ if (/^(checkbox|combobox|grid|gridcell|listbox|radiogroup|slider|spinbutton|textbox)$/.test(role || '')) {
1593
+ return attr(e, 'aria-readonly') !== 'true';
1594
+ }
1595
+ throw new Error('Error: Element is not an <input>, <textarea>, <select> or [contenteditable] and does not have a role allowing [aria-readonly]');
1596
+ }
1597
+ /** Scroll the element into view and find the point a click should land on. */
1598
+ function clickPoint(e, a) {
1599
+ if (!e.isConnected)
1600
+ return { retry: 'element is not attached to the DOM' };
1601
+ if (!a.force) {
1602
+ if (!isVisible(e))
1603
+ return { retry: 'element is not visible' };
1604
+ if (a.enabled !== false && isDisabled(e))
1605
+ return { retry: 'element is not enabled' };
1606
+ }
1607
+ if (typeof e.scrollIntoViewIfNeeded === 'function')
1608
+ e.scrollIntoViewIfNeeded(true);
1609
+ else
1610
+ e.scrollIntoView({ block: 'center', inline: 'center', behavior: 'instant' });
1611
+ const r = e.getBoundingClientRect();
1612
+ const rects = e.getClientRects();
1613
+ const first = rects.length ? rects[0] : r;
1614
+ const lx = a.position ? a.position.x : first.width / 2;
1615
+ const ly = a.position ? a.position.y : first.height / 2;
1616
+ const cx = first.left + lx;
1617
+ const cy = first.top + ly;
1618
+ if (!a.force) {
1619
+ const hit = e.ownerDocument.elementFromPoint(cx, cy);
1620
+ let deep = hit;
1621
+ while (deep && deep.shadowRoot) {
1622
+ const inner = deep.shadowRoot.elementFromPoint(cx, cy);
1623
+ if (!inner || inner === deep)
1624
+ break;
1625
+ deep = inner;
1626
+ }
1627
+ const ok = (h) => h && (contains(e, h) || (tag(e) === 'label' && e.control === h) || (h.nodeName === 'LABEL' && h.control === e));
1628
+ if (!ok(deep) && !ok(hit)) {
1629
+ return { retry: `${deep ? preview(deep) : 'nothing'} intercepts pointer events` };
1630
+ }
1631
+ }
1632
+ const t = topRect(e);
1633
+ // Remembered so settleFocus can tell whether the click moved focus.
1634
+ focusMoved = false;
1635
+ const d = e.ownerDocument;
1636
+ if (!d.__tsFocusWatch) {
1637
+ const mark = () => {
1638
+ focusMoved = true;
1639
+ };
1640
+ d.addEventListener('focusin', mark, true);
1641
+ d.addEventListener('focusout', mark, true);
1642
+ Object.defineProperty(d, '__tsFocusWatch', { value: true });
1643
+ }
1644
+ // Remembered so a click whose press and release landed on
1645
+ // different elements (the page re-rendered in between, and no click
1646
+ // event fired) can be sent again.
1647
+ clickSeen.up = false;
1648
+ clickSeen.click = false;
1649
+ if (!d.__tsClickWatch && d.defaultView) {
1650
+ d.defaultView.addEventListener('mouseup', (ev) => {
1651
+ if (ev.isTrusted)
1652
+ clickSeen.up = true;
1653
+ }, true);
1654
+ d.defaultView.addEventListener('click', (ev) => {
1655
+ if (ev.isTrusted)
1656
+ clickSeen.click = true;
1657
+ }, true);
1658
+ Object.defineProperty(d, '__tsClickWatch', { value: true });
1659
+ }
1660
+ return { x: t.x + (first.left - r.left) + lx, y: t.y + (first.top - r.top) + ly };
1661
+ }
1662
+ /**
1663
+ * Page state every reply carries: the URL, the iframe count (frames()
1664
+ * refreshes when it changes), and whether a service worker controls
1665
+ * the page, which marks its responses fromServiceWorker in proxy mode.
1666
+ */
1667
+ function here() {
1668
+ let sw = false;
1669
+ try {
1670
+ sw = !!(navigator.serviceWorker && navigator.serviceWorker.controller);
1671
+ }
1672
+ catch (_) {
1673
+ /* a sandboxed document may not ask */
1674
+ }
1675
+ return { u: location.href, fc: document.querySelectorAll('iframe,frame').length, sw };
1676
+ }
1677
+ let focusMoved = true;
1678
+ /** Trusted mouseup and click events since the last clickPoint. */
1679
+ const clickSeen = { up: true, click: true };
1680
+ /**
1681
+ * After a native click: a press on content moves focus to its nearest
1682
+ * focusable ancestor, or clears it. The headless view does not always
1683
+ * do that itself, and apps that save on blur depend on it.
1684
+ */
1685
+ function settleFocus(e) {
1686
+ const act = deepActive(e.ownerDocument);
1687
+ if (focusMoved || !act || act === e.ownerDocument.body)
1688
+ return true;
1689
+ focusMoved = true;
1690
+ if (contains(e, act) || contains(act, e))
1691
+ return true;
1692
+ const f = e.closest('a[href],area[href],button,input,select,textarea,iframe,summary,[tabindex],[contenteditable=""],[contenteditable="true"]');
1693
+ if (f && !isDisabled(f))
1694
+ f.focus();
1695
+ else if (typeof act.blur === 'function')
1696
+ act.blur();
1697
+ return true;
1698
+ }
1699
+ const OPS = {
1700
+ count: (els) => els.length,
1701
+ texts: (els) => els.map((e) => e.textContent || ''),
1702
+ elTexts: (els) => els.map((e) => elementText(e)),
1703
+ innerTexts: (els) => els.map((e) => e.innerText || ''),
1704
+ visibleAny: (els) => els.some(isVisible),
1705
+ evalAll: (els, a) => a.fnc(els, SER.des(a.arg)),
1706
+ describe: (els) => els.map(preview),
1707
+ adoptAll: (els) => els.map((e) => adopt(e)),
1708
+ refs: (els) => els.map((e) => {
1709
+ const own = attr(e, 'data-vs-ref');
1710
+ if (own)
1711
+ return [Number(own)];
1712
+ return [...e.querySelectorAll('[data-vs-ref]')].map((x) => Number(x.getAttribute('data-vs-ref')));
1713
+ }),
1714
+ };
1715
+ const ONE = {
1716
+ text: (e) => e.textContent || '',
1717
+ adopt: (e) => adopt(e),
1718
+ elText: (e) => elementText(e),
1719
+ innerText: (e) => {
1720
+ if (!(e instanceof (e.ownerDocument.defaultView || window).HTMLElement))
1721
+ throw new Error('Error: Node is not an HTMLElement');
1722
+ return e.innerText;
1723
+ },
1724
+ innerHTML: (e) => e.innerHTML,
1725
+ attr: (e, a) => attr(e, a.name),
1726
+ value: (e) => inputValue(retarget(e)),
1727
+ values: (e) => {
1728
+ e = retarget(e);
1729
+ if (tag(e) !== 'select' || !e.multiple)
1730
+ throw new Error('Error: Not a select element with a multiple attribute');
1731
+ return [...e.selectedOptions].map((o) => o.value);
1732
+ },
1733
+ checked: (e) => checkedState(retarget(e)),
1734
+ disabled: (e) => isDisabled(e),
1735
+ editable: (e) => isEditable(e),
1736
+ focused: (e) => {
1737
+ const root = e.getRootNode();
1738
+ return (root.activeElement || null) === e;
1739
+ },
1740
+ visible: (e) => isVisible(e),
1741
+ box: (e) => {
1742
+ if (!isVisible(e) && e.getBoundingClientRect().width === 0)
1743
+ return null;
1744
+ const t = topRect(e);
1745
+ return t.width === 0 && t.height === 0 ? null : t;
1746
+ },
1747
+ eval: (e, a) => a.fnc(e, SER.des(a.arg)),
1748
+ clickPoint: (e, a) => clickPoint(e, a),
1749
+ settleFocus: (e) => settleFocus(e),
1750
+ clickSeen: () => ({ up: clickSeen.up, click: clickSeen.click }),
1751
+ synthClick: (e, a) => {
1752
+ if (typeof e.scrollIntoViewIfNeeded === 'function')
1753
+ e.scrollIntoViewIfNeeded(true);
1754
+ synthClick(e, a);
1755
+ return true;
1756
+ },
1757
+ focus: (e) => {
1758
+ e.focus();
1759
+ return true;
1760
+ },
1761
+ blur: (e) => {
1762
+ e.blur();
1763
+ return true;
1764
+ },
1765
+ fill: (e, a) => {
1766
+ if (!a.force) {
1767
+ if (!isVisible(e))
1768
+ return { retry: 'element is not visible' };
1769
+ if (isDisabled(e))
1770
+ return { retry: 'element is not enabled' };
1771
+ if (e.readOnly || attr(e, 'aria-readonly') === 'true')
1772
+ return { retry: 'element is not editable' };
1773
+ }
1774
+ fill(retarget(e), a.value);
1775
+ return true;
1776
+ },
1777
+ refs: (e) => {
1778
+ // vibesurfer 0.2.16+ keeps refs in maps (__vsRefOf); older ones in an attribute.
1779
+ const refOf = (x) => {
1780
+ if (typeof window.__vsRefOf === 'function')
1781
+ return window.__vsRefOf(x);
1782
+ const a = attr(x, 'data-vs-ref');
1783
+ return a === null ? null : Number(a);
1784
+ };
1785
+ const own = refOf(e);
1786
+ if (own !== null)
1787
+ return [own];
1788
+ // The outermost reported elements inside.
1789
+ const out = [];
1790
+ const walk = (n) => {
1791
+ for (const c of n.children) {
1792
+ const r = refOf(c);
1793
+ if (r !== null)
1794
+ out.push(r);
1795
+ else
1796
+ walk(c);
1797
+ }
1798
+ if (n.shadowRoot)
1799
+ walk(n.shadowRoot);
1800
+ };
1801
+ walk(e);
1802
+ return out;
1803
+ },
1804
+ press: (e, a) => {
1805
+ if (deepActive(e.ownerDocument) !== e)
1806
+ e.focus();
1807
+ pressKey(a.key);
1808
+ return true;
1809
+ },
1810
+ selectOption: (e, a) => selectOption(retarget(e), a.values),
1811
+ selectText: (e) => {
1812
+ e.focus();
1813
+ if (typeof e.select === 'function')
1814
+ e.select();
1815
+ else {
1816
+ const r = e.ownerDocument.createRange();
1817
+ r.selectNodeContents(e);
1818
+ const s = e.ownerDocument.getSelection();
1819
+ s.removeAllRanges();
1820
+ s.addRange(r);
1821
+ }
1822
+ return true;
1823
+ },
1824
+ dispatch: (e, a) => {
1825
+ dispatch(e, a.type, a.init);
1826
+ return true;
1827
+ },
1828
+ scroll: (e) => {
1829
+ e.scrollIntoView({ block: 'center', inline: 'center', behavior: 'instant' });
1830
+ return true;
1831
+ },
1832
+ setFiles: (e, a) => {
1833
+ e = retarget(e);
1834
+ if (tag(e) !== 'input' || e.type !== 'file')
1835
+ throw new Error('Error: Node is not an HTMLInputElement');
1836
+ const dt = new DataTransfer();
1837
+ for (const f of a.files) {
1838
+ const bin = atob(f.b64);
1839
+ const bytes = new Uint8Array(bin.length);
1840
+ for (let i = 0; i < bin.length; i++)
1841
+ bytes[i] = bin.charCodeAt(i);
1842
+ dt.items.add(new File([bytes], f.name, { type: f.mimeType, lastModified: f.lastModified || Date.now() }));
1843
+ }
1844
+ e.files = dt.files;
1845
+ e.dispatchEvent(new Event('input', { bubbles: true, composed: true }));
1846
+ e.dispatchEvent(new Event('change', { bubbles: true }));
1847
+ return true;
1848
+ },
1849
+ checkedMixed: (e) => {
1850
+ e = retarget(e);
1851
+ if (tag(e) === 'input' && /^(checkbox|radio)$/i.test(e.type))
1852
+ return { c: e.checked, m: e.indeterminate };
1853
+ const c = ariaChecked(e);
1854
+ if (c === undefined)
1855
+ checkedState(e);
1856
+ return { c: c === true, m: c === 'mixed' };
1857
+ },
1858
+ css: (e, a) => styleOf(e).getPropertyValue(a.name) || styleOf(e)[a.name] || '',
1859
+ prop: (e, a) => a.name.split('.').reduce((o, k) => (o == null ? undefined : o[k]), e),
1860
+ role: (e) => roleOf(e) || '',
1861
+ name: (e) => accName(e),
1862
+ description: (e) => {
1863
+ const ids = attr(e, 'aria-describedby');
1864
+ if (ids)
1865
+ return N(ids.split(/\s+/).map((id) => { const t = e.ownerDocument.getElementById(id); return t ? t.textContent : ''; }).join(' '));
1866
+ return N(attr(e, 'aria-description') || attr(e, 'title') || '');
1867
+ },
1868
+ inViewport: (e, a) => {
1869
+ const w = e.ownerDocument.defaultView;
1870
+ const r = e.getBoundingClientRect();
1871
+ if (r.width === 0 || r.height === 0)
1872
+ return 0;
1873
+ const vx = Math.max(0, Math.min(r.right, w.innerWidth) - Math.max(r.left, 0));
1874
+ const vy = Math.max(0, Math.min(r.bottom, w.innerHeight) - Math.max(r.top, 0));
1875
+ return (vx * vy) / (r.width * r.height);
1876
+ },
1877
+ empty: (e) => {
1878
+ if (/^(input|textarea)$/.test(tag(e)))
1879
+ return !e.value;
1880
+ return !N(e.textContent);
1881
+ },
1882
+ classList: (e) => [...e.classList],
1883
+ outerHTML: (e) => e.outerHTML,
1884
+ };
1885
+ const SLOTS = new Map();
1886
+ let seq = 0;
1887
+ // Handles: page values the test holds by id (JSHandle, ElementHandle).
1888
+ const HANDLES = new Map();
1889
+ let handleSeq = 0;
1890
+ const adopt = (v) => {
1891
+ const id = ++handleSeq;
1892
+ HANDLES.set(id, v);
1893
+ return id;
1894
+ };
1895
+ SER.H.get = (id) => HANDLES.get(id);
1896
+ // Elements, documents and shadow roots come back as element handles.
1897
+ const frameIds = new WeakMap();
1898
+ const isEl = (v) => !!v && typeof v === 'object' && (v.nodeType === 1 || v.nodeType === 9 || v.nodeType === 11);
1899
+ const api = {
1900
+ /** Identifies this document: a new document installs a new engine. */
1901
+ doc: Math.random().toString(36).slice(2),
1902
+ /**
1903
+ * req: { steps, op, args, many } -> { n, v } for `many` ops,
1904
+ * { v } for one-element ops, { none } when nothing matches,
1905
+ * { strict: [previews], n } when more than one matches.
1906
+ */
1907
+ run(req, fn) {
1908
+ textCache = new Map();
1909
+ if (fn)
1910
+ req.args = { ...(req.args || {}), fnc: fn };
1911
+ const els = resolve(req.steps, [document]);
1912
+ const wrap = (v, n) => (v && typeof v.then === 'function' ? v.then((r) => ({ v: r, n })) : { v, n });
1913
+ if (req.many)
1914
+ return wrap(OPS[req.op](els, req.args || {}), els.length);
1915
+ if (els.length === 0)
1916
+ return { none: true };
1917
+ if (els.length > 1 && !req.first)
1918
+ return { strict: els.slice(0, 10).map((e) => `${preview(e)} aka ${aka(e)}`), n: els.length };
1919
+ const r = wrap(ONE[req.op](els[0], req.args || {}), 1);
1920
+ const p = preview(els[0]);
1921
+ return r && typeof r.then === 'function' ? r.then((x) => ({ ...x, p })) : { ...r, p };
1922
+ },
1923
+ key(chord, phase) {
1924
+ pressKey(chord, phase);
1925
+ return true;
1926
+ },
1927
+ insertText(text) {
1928
+ const t = deepActive() || document.body;
1929
+ if (editableTarget(t))
1930
+ insertText(t, text);
1931
+ return true;
1932
+ },
1933
+ /** Call f; park a promise result in a slot for take(). */
1934
+ exec(f) {
1935
+ let v;
1936
+ try {
1937
+ v = f();
1938
+ }
1939
+ catch (e) {
1940
+ return { e: { name: e && e.name, message: e && e.message !== undefined ? e.message : String(e), stack: e && e.stack } };
1941
+ }
1942
+ if (v && typeof v.then === 'function') {
1943
+ const id = ++seq;
1944
+ SLOTS.set(id, null);
1945
+ v.then((r) => SLOTS.set(id, { v: SER.ser(r) }), (e) => SLOTS.set(id, { e: { name: e && e.name, message: e && e.message !== undefined ? e.message : String(e), stack: e && e.stack } }));
1946
+ return { p: id };
1947
+ }
1948
+ return { v: SER.ser(v), ...here() };
1949
+ },
1950
+ h: (id) => HANDLES.get(id),
1951
+ drop(id) {
1952
+ HANDLES.delete(id);
1953
+ return true;
1954
+ },
1955
+ /** Adopt a value (or a promise of one): { id, el } with el true for an element. */
1956
+ adoptValue(v) {
1957
+ const prev = (x) => {
1958
+ if (x && typeof x === 'object' && x.nodeType === 3)
1959
+ return '#text=' + String(x.nodeValue).replace(/\n/g, '↵');
1960
+ if (isEl(x))
1961
+ return preview(x);
1962
+ if (x === null || x === undefined || typeof x !== 'object')
1963
+ return String(x);
1964
+ if (Array.isArray(x))
1965
+ return 'Array(' + x.length + ')';
1966
+ return x.constructor && x.constructor.name ? x.constructor.name : 'Object';
1967
+ };
1968
+ const done = (x) => ({ id: adopt(x), el: isEl(x), p: prev(x) });
1969
+ return v && typeof v.then === 'function' ? v.then(done) : done(v);
1970
+ },
1971
+ /** Same-origin and cross-origin iframes, depth first: [id, parentId, name, url]. */
1972
+ frames() {
1973
+ const out = [];
1974
+ const walk = (doc, parent) => {
1975
+ for (const f of allUnder(doc)) {
1976
+ if (f.nodeName !== 'IFRAME' && f.nodeName !== 'FRAME')
1977
+ continue;
1978
+ // The same iframe keeps its id, so Frame objects stay the same across listings.
1979
+ let id = frameIds.get(f);
1980
+ if (id === undefined) {
1981
+ id = adopt(f);
1982
+ frameIds.set(f, id);
1983
+ }
1984
+ let d = null;
1985
+ let url = '';
1986
+ try {
1987
+ d = f.contentDocument;
1988
+ url = d ? d.location.href : f.src;
1989
+ }
1990
+ catch (_) {
1991
+ url = f.src;
1992
+ }
1993
+ // Fifth: 1 for a cross-origin frame, which only `--frame` evals reach.
1994
+ out.push([id, parent, attr(f, 'name') || '', url, !d && f.contentWindow ? 1 : 0]);
1995
+ if (d)
1996
+ walk(d, id);
1997
+ }
1998
+ };
1999
+ walk(document, null);
2000
+ return out;
2001
+ },
2002
+ props(id) {
2003
+ const v = HANDLES.get(id);
2004
+ const out = [];
2005
+ if (v && typeof v === 'object')
2006
+ for (const k of Object.keys(v))
2007
+ out.push([k, adopt(v[k]), isEl(v[k])]);
2008
+ return out;
2009
+ },
2010
+ take(id) {
2011
+ if (!SLOTS.has(id))
2012
+ return { gone: true };
2013
+ const s = SLOTS.get(id);
2014
+ if (!s)
2015
+ return { p: id };
2016
+ SLOTS.delete(id);
2017
+ return { ...s, ...here() };
2018
+ },
2019
+ ser: SER.ser,
2020
+ des: SER.des,
2021
+ };
2022
+ Object.defineProperty(window, '__tse', { value: api, configurable: true, enumerable: false });
2023
+ return api;
2024
+ }
2025
+ //# sourceMappingURL=injected.js.map