codex-browser-use 0.0.0-stage → 4.8.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1497 @@
1
+ /**
2
+ * Pure JavaScript expression and function builders evaluated inside target pages
3
+ * and frames via CDP Runtime.evaluate / Runtime.callFunctionOn.
4
+ *
5
+ * Clean-room implementation supporting open Shadow DOM piercing, chained locators,
6
+ * same-origin iframe traversal, viewport-clamped hit-testing, semantic value setting,
7
+ * coordinate element inspection, and compact DOM snapshots.
8
+ */
9
+
10
+ const SHARED_DOM_HELPERS = `
11
+ const INTERACTIVE_SELECTOR = [
12
+ "button", "a[href]", "input", "select", "textarea", "summary",
13
+ '[role="button"]', '[role="checkbox"]', '[role="combobox"]', '[role="link"]',
14
+ '[role="listbox"]', '[role="menuitem"]', '[role="option"]', '[role="radio"]',
15
+ '[role="slider"]', '[role="spinbutton"]', '[role="switch"]', '[role="tab"]',
16
+ '[role="textbox"]', '[tabindex]:not([tabindex="-1"])'
17
+ ].join(",");
18
+
19
+ const isVisibleEl = (el) => {
20
+ if (!el || el.nodeType !== 1) return false;
21
+ const win = el.ownerDocument?.defaultView || window;
22
+ const style = win.getComputedStyle(el);
23
+ if (!style || style.display === "none" || style.visibility === "hidden" || style.opacity === "0") return false;
24
+ const rect = el.getBoundingClientRect();
25
+ return rect.width > 0 && rect.height > 0;
26
+ };
27
+
28
+ const deepElements = (root) => {
29
+ const out = [];
30
+ const stack = [root];
31
+ const seen = new Set();
32
+ while (stack.length > 0) {
33
+ const cur = stack.pop();
34
+ if (!cur || seen.has(cur)) continue;
35
+ seen.add(cur);
36
+ if (cur.nodeType === 1) {
37
+ out.push(cur);
38
+ if (cur.shadowRoot) stack.push(cur.shadowRoot);
39
+ }
40
+ const children = cur.children || (cur.documentElement ? [cur.documentElement] : null);
41
+ if (children) {
42
+ for (let i = children.length - 1; i >= 0; i--) stack.push(children[i]);
43
+ } else if (cur.childNodes) {
44
+ for (let i = cur.childNodes.length - 1; i >= 0; i--) {
45
+ if (cur.childNodes[i].nodeType === 1) stack.push(cur.childNodes[i]);
46
+ }
47
+ }
48
+ }
49
+ return out;
50
+ };
51
+
52
+ const querySelectorAllDeep = (root, css) => {
53
+ const matches = [];
54
+ const seen = new Set();
55
+ const visitRoot = (scope) => {
56
+ try {
57
+ for (const el of scope.querySelectorAll(css)) {
58
+ if (!seen.has(el)) { seen.add(el); matches.push(el); }
59
+ }
60
+ } catch (err) {
61
+ if (scope === root) throw err;
62
+ }
63
+ for (const el of deepElements(scope)) {
64
+ if (el.shadowRoot && !seen.has(el.shadowRoot)) {
65
+ seen.add(el.shadowRoot);
66
+ visitRoot(el.shadowRoot);
67
+ }
68
+ }
69
+ };
70
+ visitRoot(root);
71
+ return matches;
72
+ };
73
+
74
+ const implicitRoleOf = (el) => {
75
+ const explicit = el.getAttribute("role");
76
+ if (explicit) return explicit.trim().toLowerCase().split(/\\s+/)[0];
77
+ const tag = el.tagName.toLowerCase();
78
+ if (tag === "a" && el.hasAttribute("href")) return "link";
79
+ if (tag === "area" && el.hasAttribute("href")) return "link";
80
+ if (tag === "button" || tag === "summary") return "button";
81
+ if (tag === "select") return el.multiple || Number(el.size) > 1 ? "listbox" : "combobox";
82
+ if (tag === "textarea") return "textbox";
83
+ if (tag === "option") return "option";
84
+ if (tag === "img") return "img";
85
+ if (tag === "nav") return "navigation";
86
+ if (tag === "main") return "main";
87
+ if (tag === "header") return "banner";
88
+ if (tag === "footer") return "contentinfo";
89
+ if (tag === "aside") return "complementary";
90
+ if (tag === "form") return "form";
91
+ if (tag === "dialog") return "dialog";
92
+ if (tag === "ul" || tag === "ol") return "list";
93
+ if (tag === "li") return "listitem";
94
+ if (tag === "table") return "table";
95
+ if (tag === "tr") return "row";
96
+ if (tag === "th") return "columnheader";
97
+ if (tag === "td") return "cell";
98
+ if (/^h[1-6]$/.test(tag)) return "heading";
99
+ if (tag === "input") {
100
+ const type = (el.getAttribute("type") || "text").toLowerCase();
101
+ if (["button", "submit", "reset", "image"].includes(type)) return "button";
102
+ if (type === "checkbox") return "checkbox";
103
+ if (type === "radio") return "radio";
104
+ if (type === "range") return "slider";
105
+ if (type === "number") return "spinbutton";
106
+ if (type === "search") return "searchbox";
107
+ if (type === "hidden") return "";
108
+ return "textbox";
109
+ }
110
+ return "";
111
+ };
112
+
113
+ const LABELABLE_TAGS = new Set(["input", "textarea", "select", "button", "meter", "output", "progress"]);
114
+ const LABELABLE_ROLES = new Set([
115
+ "textbox", "searchbox", "spinbutton", "combobox", "listbox", "checkbox", "radio", "switch", "slider",
116
+ ]);
117
+
118
+ const labelTextFor = (el) => {
119
+ if (!el || !el.tagName) return "";
120
+ const tag = el.tagName.toLowerCase();
121
+ if (tag === "label") return "";
122
+ const doc = el.ownerDocument || document;
123
+ const labelledBy = el.getAttribute("aria-labelledby");
124
+ if (labelledBy) {
125
+ const text = labelledBy.split(/\\s+/).map((id) => doc.getElementById(id)?.innerText || doc.getElementById(id)?.textContent || "").join(" ").replace(/\\s+/g, " ").trim();
126
+ if (text) return text;
127
+ }
128
+ if (el.labels && el.labels.length > 0) {
129
+ const text = Array.from(el.labels).map((l) => l.innerText || l.textContent || "").join(" ").replace(/\\s+/g, " ").trim();
130
+ if (text) return text;
131
+ }
132
+ const isLabelable = LABELABLE_TAGS.has(tag) || Boolean(el.isContentEditable) || LABELABLE_ROLES.has(implicitRoleOf(el));
133
+ if (isLabelable) {
134
+ const parentLabel = el.parentElement?.closest("label");
135
+ if (parentLabel) {
136
+ const text = (parentLabel.innerText || parentLabel.textContent || "").replace(/\\s+/g, " ").trim();
137
+ if (text) return text;
138
+ }
139
+ }
140
+ return "";
141
+ };
142
+
143
+ const accessibleNameOf = (el) => {
144
+ const aria = el.getAttribute("aria-label");
145
+ if (aria && aria.trim()) return aria.trim();
146
+ const lbl = labelTextFor(el);
147
+ if (lbl) return lbl;
148
+ const tag = el.tagName.toLowerCase();
149
+ if (tag === "input" && ["button", "submit", "reset"].includes((el.type || "").toLowerCase())) {
150
+ if (el.value) return el.value.trim();
151
+ }
152
+ const text = (el.innerText || el.textContent || "").replace(/\\s+/g, " ").trim();
153
+ if (text) return text;
154
+ return (el.getAttribute("placeholder") || el.getAttribute("title") || el.getAttribute("alt") || el.value || "").trim();
155
+ };
156
+
157
+ const elementFromPointDeep = (doc, x, y) => {
158
+ let hit = doc.elementFromPoint(x, y);
159
+ while (hit && hit.shadowRoot) {
160
+ const inner = hit.shadowRoot.elementFromPoint(x, y);
161
+ if (!inner || inner === hit) break;
162
+ hit = inner;
163
+ }
164
+ return hit;
165
+ };
166
+
167
+ const tryFillRichEditor = (el, assigned, inputType = "insertText") => {
168
+ if (!el) return false;
169
+ const win = el.ownerDocument?.defaultView || window;
170
+ const setNativeValue = (node, val) => {
171
+ if (!node || !("value" in node)) return;
172
+ const desc = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(node), "value");
173
+ if (desc?.set) desc.set.call(node, val); else node.value = val;
174
+ node.dispatchEvent?.(new Event("input", { bubbles: true }));
175
+ node.dispatchEvent?.(new Event("change", { bubbles: true }));
176
+ };
177
+ try {
178
+ const cke = win?.CKEDITOR?.instances;
179
+ if (cke && typeof cke === "object") {
180
+ const ckeRoot = el.closest?.(".cke");
181
+ for (const inst of Object.values(cke)) {
182
+ if (inst && (inst.element?.$ === el || (el.id && inst.name === el.id) || (el.name && inst.name === el.name) || (ckeRoot && inst.container?.$ === ckeRoot))) {
183
+ const targetEl = inst.element?.$ || (el.tagName === "TEXTAREA" ? el : null);
184
+ const syncTextarea = () => {
185
+ try { inst.updateElement?.(); } catch (_e) {}
186
+ try {
187
+ const current = typeof inst.getData === "function" ? inst.getData() : assigned;
188
+ if (targetEl && "value" in targetEl && targetEl.value !== current) {
189
+ setNativeValue(targetEl, current);
190
+ }
191
+ } catch (_e) {}
192
+ };
193
+ const isAsyncSetData = typeof inst.setData === "function" &&
194
+ (typeof inst.once === "function" || inst.setData.length >= 2) &&
195
+ typeof Promise === "function";
196
+ if (isAsyncSetData) {
197
+ return new Promise((resolve) => {
198
+ let settled = false;
199
+ let timer = null;
200
+ const finish = () => {
201
+ if (settled) return;
202
+ settled = true;
203
+ if (timer !== null && typeof clearTimeout === "function") clearTimeout(timer);
204
+ syncTextarea();
205
+ resolve(true);
206
+ };
207
+ try { inst.once?.("dataReady", finish); } catch (_e) {}
208
+ try {
209
+ inst.setData(assigned, finish);
210
+ } catch (_e) {
211
+ finish();
212
+ return;
213
+ }
214
+ syncTextarea();
215
+ if (!settled && typeof setTimeout === "function") {
216
+ timer = setTimeout(finish, 300);
217
+ } else if (!settled) {
218
+ finish();
219
+ }
220
+ });
221
+ }
222
+ inst.setData?.(assigned);
223
+ syncTextarea();
224
+ return true;
225
+ }
226
+ }
227
+ }
228
+ } catch (_e) {}
229
+ try {
230
+ const ck5 = el.ckeditorInstance || el.closest?.(".ck-editor__editable")?.ckeditorInstance;
231
+ if (ck5 && typeof ck5.setData === "function") {
232
+ ck5.setData(assigned);
233
+ ck5.updateSourceElement?.();
234
+ if ("value" in el) {
235
+ const current = typeof ck5.getData === "function" ? ck5.getData() : assigned;
236
+ if (el.value !== current) setNativeValue(el, current);
237
+ }
238
+ return true;
239
+ }
240
+ } catch (_e) {}
241
+ try {
242
+ const tiny = el.id ? win?.tinymce?.get?.(el.id) : null;
243
+ if (tiny && typeof tiny.setContent === "function") {
244
+ tiny.setContent(assigned);
245
+ tiny.save?.();
246
+ if ("value" in el && typeof tiny.getContent === "function") {
247
+ const current = tiny.getContent();
248
+ if (el.value !== current) setNativeValue(el, current);
249
+ }
250
+ return true;
251
+ }
252
+ } catch (_e) {}
253
+ try {
254
+ const quill = el.__quill || el.closest?.(".ql-container")?.__quill;
255
+ if (quill && typeof quill.setText === "function") {
256
+ quill.setText(assigned);
257
+ return true;
258
+ }
259
+ } catch (_e) {}
260
+ if (el.isContentEditable) {
261
+ el.focus?.();
262
+ el.textContent = assigned;
263
+ el.dispatchEvent?.(typeof InputEvent === "function"
264
+ ? new InputEvent("input", { bubbles: true, composed: true, data: assigned, inputType })
265
+ : new Event("input", { bubbles: true, composed: true }));
266
+ el.dispatchEvent?.(new Event("change", { bubbles: true }));
267
+ return true;
268
+ }
269
+ return false;
270
+ };
271
+ `;
272
+
273
+ const SHARED_LOCATOR_RESOLVER = `
274
+ const parseRegexLiteral = (token) => {
275
+ const t = String(token || "").trim();
276
+ if (!t.startsWith("/")) return null;
277
+ const lastSlash = t.lastIndexOf("/");
278
+ if (lastSlash <= 0) return null;
279
+ const flags = t.slice(lastSlash + 1);
280
+ if (!/^[dgimsuvy]*$/.test(flags)) return null;
281
+ return new RegExp(t.slice(1, lastSlash), flags);
282
+ };
283
+
284
+ const splitPipeline = (input) => {
285
+ const parts = [];
286
+ let cur = "";
287
+ let quote = null;
288
+ let escaped = false;
289
+ let parenDepth = 0;
290
+ for (let i = 0; i < input.length; i++) {
291
+ const ch = input[i];
292
+ if (escaped) {
293
+ cur += ch;
294
+ escaped = false;
295
+ continue;
296
+ }
297
+ if (quote) {
298
+ cur += ch;
299
+ if (ch === "\\\\") escaped = true;
300
+ else if (ch === quote) quote = null;
301
+ continue;
302
+ }
303
+ if (ch === '"' || ch === "'") {
304
+ quote = ch;
305
+ cur += ch;
306
+ continue;
307
+ }
308
+ if (ch === "(") {
309
+ parenDepth++;
310
+ cur += ch;
311
+ continue;
312
+ }
313
+ if (ch === ")" && parenDepth > 0) {
314
+ parenDepth--;
315
+ cur += ch;
316
+ continue;
317
+ }
318
+ if (parenDepth === 0 && ch === ">" && input[i + 1] === ">") {
319
+ parts.push(cur.trim());
320
+ cur = "";
321
+ i++;
322
+ continue;
323
+ }
324
+ cur += ch;
325
+ }
326
+ if (cur.trim()) parts.push(cur.trim());
327
+ return parts.filter(Boolean);
328
+ };
329
+
330
+ const unquote = (s) => {
331
+ const t = s.trim();
332
+ if ((t.startsWith('"') && t.endsWith('"')) || (t.startsWith("'") && t.endsWith("'"))) {
333
+ return t.slice(1, -1);
334
+ }
335
+ return t;
336
+ };
337
+
338
+ const querySingle = (scope, step) => {
339
+ if (step.startsWith("text=")) {
340
+ const rawText = step.slice(5).trim();
341
+ const regex = parseRegexLiteral(rawText);
342
+ const exact = !regex && ((rawText.startsWith('"') && rawText.endsWith('"')) || (rawText.startsWith("'") && rawText.endsWith("'")));
343
+ const target = regex ? null : unquote(rawText);
344
+ const matchesText = (val) => regex ? regex.test(val) : (exact ? val === target : val.includes(target));
345
+ const all = deepElements(scope).filter((el) => {
346
+ const val = (el.innerText || el.textContent || "").replace(/\\s+/g, " ").trim();
347
+ return matchesText(val);
348
+ });
349
+ return all.filter((el) => !Array.from(el.children || []).some((child) => {
350
+ const val = (child.innerText || child.textContent || "").replace(/\\s+/g, " ").trim();
351
+ return matchesText(val);
352
+ }));
353
+ }
354
+ if (step.startsWith("role=")) {
355
+ const match = /^role=([a-zA-Z0-9_-]+)(?:\\[name=(?:"([^"]*)"|'([^']*)'|(\\/(?:\\\\.|[^/])+\\/[dgimsuvy]*))\\])?(?:\\[exact=(true|false)\\])?$/.exec(step);
356
+ if (!match) throw new Error("Invalid role locator: " + step);
357
+ const role = match[1].toLowerCase();
358
+ const nameRegex = match[4] ? parseRegexLiteral(match[4]) : null;
359
+ const name = nameRegex ? null : (match[2] !== undefined ? match[2] : match[3]);
360
+ const exact = match[5] !== "false";
361
+ return deepElements(scope).filter((el) => {
362
+ if (implicitRoleOf(el) !== role) return false;
363
+ if (nameRegex) return nameRegex.test(accessibleNameOf(el));
364
+ if (name === undefined) return true;
365
+ const actual = accessibleNameOf(el);
366
+ return exact ? actual === name : actual.toLowerCase().includes(name.toLowerCase());
367
+ });
368
+ }
369
+ if (step.startsWith("testid=")) {
370
+ const id = unquote(step.slice(7));
371
+ const escaped = CSS.escape(id);
372
+ return querySelectorAllDeep(scope, '[data-testid="' + escaped + '"],[data-test-id="' + escaped + '"],[data-test="' + escaped + '"]');
373
+ }
374
+ if (step.startsWith("label=")) {
375
+ const wanted = unquote(step.slice(6));
376
+ return deepElements(scope).filter((el) => labelTextFor(el) === wanted || (el.getAttribute("aria-label") || "").trim() === wanted);
377
+ }
378
+ if (step.startsWith("placeholder=")) {
379
+ const wanted = unquote(step.slice(12));
380
+ return querySelectorAllDeep(scope, '[placeholder="' + CSS.escape(wanted) + '"]');
381
+ }
382
+ return querySelectorAllDeep(scope, step.startsWith("css=") ? step.slice(4) : step);
383
+ };
384
+
385
+ const resolvePipeline = (rootScope, expr) => {
386
+ const steps = splitPipeline(expr);
387
+ if (steps.length === 0) throw new Error("Empty locator");
388
+ let current = [rootScope];
389
+ let initialized = false;
390
+ for (const step of steps) {
391
+ if (step === "first") {
392
+ current = current.length ? [current[0]] : [];
393
+ initialized = true;
394
+ continue;
395
+ }
396
+ if (step === "last") {
397
+ current = current.length ? [current[current.length - 1]] : [];
398
+ initialized = true;
399
+ continue;
400
+ }
401
+ if (/^nth=(-?\\d+)$/.test(step)) {
402
+ const idx = Number(RegExp.$1);
403
+ const resolved = idx < 0 ? current[current.length + idx] : current[idx];
404
+ current = resolved ? [resolved] : [];
405
+ initialized = true;
406
+ continue;
407
+ }
408
+ if (step === "visible=true" || step === "visible=false") {
409
+ const want = step === "visible=true";
410
+ const base = initialized ? current : deepElements(rootScope);
411
+ current = base.filter((el) => isVisibleEl(el) === want);
412
+ initialized = true;
413
+ continue;
414
+ }
415
+ if (step.startsWith("has-text=")) {
416
+ const rawNeedle = step.slice(9).trim();
417
+ const needleRe = parseRegexLiteral(rawNeedle);
418
+ const needle = needleRe ? null : unquote(rawNeedle);
419
+ const base = initialized ? current : deepElements(rootScope);
420
+ current = base.filter((el) => {
421
+ const txt = el.innerText || el.textContent || "";
422
+ return needleRe ? needleRe.test(txt) : txt.includes(needle);
423
+ });
424
+ initialized = true;
425
+ continue;
426
+ }
427
+ if (step.startsWith("has-not-text=")) {
428
+ const rawNeedle = step.slice(13).trim();
429
+ const needleRe = parseRegexLiteral(rawNeedle);
430
+ const needle = needleRe ? null : unquote(rawNeedle);
431
+ const base = initialized ? current : deepElements(rootScope);
432
+ current = base.filter((el) => {
433
+ const txt = el.innerText || el.textContent || "";
434
+ return !(needleRe ? needleRe.test(txt) : txt.includes(needle));
435
+ });
436
+ initialized = true;
437
+ continue;
438
+ }
439
+ if ((step.startsWith("has=(") || step.startsWith("has-not=(")) && step.endsWith(")")) {
440
+ const negate = step.startsWith("has-not=(");
441
+ const sub = step.slice(negate ? 9 : 5, -1);
442
+ const base = initialized ? current : deepElements(rootScope);
443
+ current = base.filter((el) => {
444
+ const matched = resolvePipeline(el, sub).length > 0;
445
+ return negate ? !matched : matched;
446
+ });
447
+ initialized = true;
448
+ continue;
449
+ }
450
+ if (step.startsWith("and=(") && step.endsWith(")")) {
451
+ const sub = step.slice(5, -1);
452
+ const other = resolvePipeline(rootScope, sub);
453
+ if (!initialized) {
454
+ current = other;
455
+ } else {
456
+ const otherSet = new Set(other);
457
+ current = current.filter((el) => otherSet.has(el));
458
+ }
459
+ initialized = true;
460
+ continue;
461
+ }
462
+ if (step.startsWith("or=(") && step.endsWith(")")) {
463
+ const sub = step.slice(4, -1);
464
+ const extra = resolvePipeline(rootScope, sub);
465
+ if (!initialized) {
466
+ current = extra;
467
+ } else {
468
+ const seen = new Set(current);
469
+ const combined = [...current];
470
+ for (const el of extra) {
471
+ if (!seen.has(el)) { seen.add(el); combined.push(el); }
472
+ }
473
+ if (combined.length > 1) {
474
+ const order = deepElements(rootScope);
475
+ const rank = new Map();
476
+ for (let k = 0; k < order.length; k++) rank.set(order[k], k);
477
+ combined.sort((a, b) => (rank.get(a) ?? 1e9) - (rank.get(b) ?? 1e9));
478
+ }
479
+ current = combined;
480
+ }
481
+ initialized = true;
482
+ continue;
483
+ }
484
+ const next = [];
485
+ const seen = new Set();
486
+ const scopes = initialized ? current : [rootScope];
487
+ for (const sc of scopes) {
488
+ for (const found of querySingle(sc, step)) {
489
+ if (!seen.has(found)) { seen.add(found); next.push(found); }
490
+ }
491
+ }
492
+ current = next;
493
+ initialized = true;
494
+ }
495
+ return current;
496
+ };
497
+
498
+ const resolveSameOriginTargetRoot = (sameOriginFrames) => {
499
+ let doc = document;
500
+ if (Array.isArray(sameOriginFrames) && sameOriginFrames.length > 0) {
501
+ for (const frameSel of sameOriginFrames) {
502
+ const matchedFrames = resolvePipeline(doc, frameSel);
503
+ if (matchedFrames.length === 0) return { error: "Iframe did not match: " + frameSel, code: "not_found", retryable: true };
504
+ if (matchedFrames.length > 1) return { error: "Iframe matched " + matchedFrames.length + " elements: " + frameSel, code: "multiple", retryable: false };
505
+ const frameEl = matchedFrames[0];
506
+ if (!frameEl.contentDocument) return { error: "Iframe is cross-origin or has no accessible document: " + frameSel, code: "invalid", retryable: false };
507
+ doc = frameEl.contentDocument;
508
+ }
509
+ }
510
+ return { root: doc };
511
+ };
512
+ `;
513
+
514
+ export const LOCATOR_RUNTIME_VERSION = 4;
515
+
516
+ const SHARED_RUNNER_CORE = `
517
+ const isDisabledEl = (el) => !!(el.matches?.(":disabled") || el.getAttribute?.("aria-disabled") === "true");
518
+ const cursorPt = (el) => {
519
+ if (!el || typeof el.getBoundingClientRect !== "function") return {};
520
+ const r = el.getBoundingClientRect();
521
+ return r && r.width > 0 && r.height > 0
522
+ ? { x: r.left + r.width / 2, y: r.top + r.height / 2, __cursorMove: true }
523
+ : {};
524
+ };
525
+ const fail = (message, code = "error", retryable = false) => ({ error: message, code, retryable });
526
+
527
+ const describeCandidate = (el) => {
528
+ const tag = el.tagName.toLowerCase();
529
+ const role = implicitRoleOf(el);
530
+ const ariaName = accessibleNameOf(el);
531
+ const testId = el.getAttribute?.("data-testid") || el.getAttribute?.("data-test-id") || el.getAttribute?.("data-test");
532
+ if (testId) return "testid=" + JSON.stringify(testId);
533
+ if (role && ariaName && ariaName.length <= 50) return "role=" + role + "[name=" + JSON.stringify(ariaName) + "]";
534
+ if (el.id && !/^\\d|:/.test(el.id)) return "css=#" + CSS.escape(el.id);
535
+ const txt = (el.innerText || el.textContent || "").replace(/\\s+/g, " ").trim();
536
+ if (txt && txt.length <= 45) return "text=" + JSON.stringify(txt);
537
+ const nameAttr = el.getAttribute?.("name");
538
+ return "css=" + tag + (nameAttr ? "[name=" + JSON.stringify(nameAttr) + "]" : "");
539
+ };
540
+
541
+ const suggestLocatorCandidates = (raw, limit = 4) => {
542
+ const rawStr = String(raw || "");
543
+ const stop = new Set(["role", "name", "css", "text", "exact", "true", "false", "first", "last", "button", "link", "textbox", "testid", "label", "placeholder"]);
544
+ const words = rawStr.toLowerCase().split(/[^a-z0-9]+/i).filter((w) => w.length >= 2 && !stop.has(w));
545
+ let candidates = [];
546
+ try {
547
+ candidates = querySelectorAllDeep(document, INTERACTIVE_SELECTOR);
548
+ } catch (_e) {
549
+ return [];
550
+ }
551
+ const scored = [];
552
+ const seen = new Set();
553
+ for (const el of candidates) {
554
+ if (!isVisibleEl(el)) continue;
555
+ const role = implicitRoleOf(el);
556
+ const name = accessibleNameOf(el);
557
+ const hay = (role + " " + name + " " + (el.id || "") + " " + (el.getAttribute?.("data-testid") || "") + " " + (el.getAttribute?.("name") || "")).toLowerCase();
558
+ let score = 0;
559
+ for (const w of words) {
560
+ if (hay.includes(w)) score += 3;
561
+ }
562
+ if (rawStr.toLowerCase().includes("role=" + role)) score += 1;
563
+ if (words.length === 0 || score > 0) {
564
+ const desc = describeCandidate(el);
565
+ if (!seen.has(desc)) {
566
+ seen.add(desc);
567
+ scored.push({ score, desc });
568
+ }
569
+ }
570
+ }
571
+ scored.sort((a, b) => b.score - a.score);
572
+ return scored.slice(0, limit).map((s) => s.desc);
573
+ };
574
+
575
+ const runLocatorAction = (raw, opts = {}, __userFn = null) => {
576
+ const mutation = opts.mutation ?? null;
577
+ const nextValue = opts.value ?? null;
578
+ const selectSpec = opts.select ?? null;
579
+ const waitState = opts.state ?? "visible";
580
+ const sameOriginFrames = opts.sameOriginFrames ?? null;
581
+ const crossOriginDirect = Boolean(opts.crossOriginDirect);
582
+ const force = Boolean(opts.force);
583
+ const attrName = opts.attrName ?? null;
584
+ const hasEvalArg = Boolean(opts.hasEvalArg);
585
+ const __evalArg = opts.evalArg;
586
+ const asyncEval = Boolean(opts.asyncEval);
587
+ const waitMs = Math.max(0, Math.round(Number(opts.inPageWaitMs) || 0));
588
+
589
+ const runOnce = () => {
590
+ let targetRoot = document;
591
+ try {
592
+ const resolvedFrame = resolveSameOriginTargetRoot(sameOriginFrames);
593
+ if (resolvedFrame.error) return fail(resolvedFrame.error, resolvedFrame.code, resolvedFrame.retryable);
594
+ targetRoot = resolvedFrame.root;
595
+ } catch (error) {
596
+ return fail("Invalid frame locator: " + error.message, "invalid", false);
597
+ }
598
+
599
+ let nodes;
600
+ try {
601
+ nodes = resolvePipeline(targetRoot, raw);
602
+ } catch (error) {
603
+ return fail("Invalid locator: " + error.message, "invalid", false);
604
+ }
605
+
606
+ if (mutation === "count") return { count: nodes.length };
607
+ if (mutation === "evalAll") {
608
+ if (typeof __userFn !== "function") return fail("Missing evaluation function", "invalid", false);
609
+ const out = hasEvalArg ? __userFn(nodes, __evalArg) : __userFn(nodes);
610
+ if (asyncEval || (out && typeof out.then === "function")) {
611
+ return Promise.resolve(out).then((value) => ({ count: nodes.length, value }));
612
+ }
613
+ return { count: nodes.length, value: out };
614
+ }
615
+ if (mutation === "allTextContents") {
616
+ return { count: nodes.length, values: nodes.map((el) => el.textContent || "") };
617
+ }
618
+ if (mutation === "allInnerTexts") {
619
+ return { count: nodes.length, values: nodes.map((el) => (el.innerText || "").trim()) };
620
+ }
621
+ if (mutation === "isVisible") {
622
+ return { value: nodes.length > 0 && isVisibleEl(nodes[0]) };
623
+ }
624
+ if (mutation === "isEnabled") {
625
+ return { value: nodes.length > 0 && !isDisabledEl(nodes[0]) };
626
+ }
627
+ if (mutation === "isChecked") {
628
+ const el = nodes[0];
629
+ const checked = el
630
+ ? (el instanceof HTMLInputElement ? !!el.checked : el.getAttribute?.("aria-checked") === "true")
631
+ : false;
632
+ return { value: checked };
633
+ }
634
+ if (mutation === "wait") {
635
+ if (waitState === "detached") return { count: nodes.length, satisfied: nodes.length === 0 };
636
+ if (waitState === "attached") return { count: nodes.length, satisfied: nodes.length > 0 };
637
+ const visibleCount = nodes.filter(isVisibleEl).length;
638
+ if (waitState === "visible") return { count: nodes.length, visibleCount, satisfied: visibleCount > 0 };
639
+ if (waitState === "hidden") return { count: nodes.length, visibleCount, satisfied: visibleCount === 0 };
640
+ return fail("Unsupported wait state: " + waitState, "invalid", false);
641
+ }
642
+
643
+ if (nodes.length === 0) return fail("Locator did not match any element: " + raw, "not_found", true);
644
+ if (nodes.length > 1) {
645
+ const previews = nodes.slice(0, 3).map((el, i) => {
646
+ const tag = el.tagName.toLowerCase();
647
+ const text = (el.innerText || el.getAttribute("aria-label") || el.id || "").replace(/\\s+/g, " ").trim().slice(0, 40);
648
+ return "#" + i + " <" + tag + (el.id ? "#" + el.id : "") + ">" + (text ? ' "' + text + '"' : "");
649
+ }).join(", ");
650
+ return fail("Locator matched " + nodes.length + " elements; narrow it (e.g. append >> first or >> nth=0): " + raw + " [" + previews + "]", "multiple", false);
651
+ }
652
+
653
+ const element = nodes[0];
654
+ if (mutation === "eval") {
655
+ if (typeof __userFn !== "function") return fail("Missing evaluation function", "invalid", false);
656
+ const out = hasEvalArg ? __userFn(element, __evalArg) : __userFn(element);
657
+ if (asyncEval || (out && typeof out.then === "function")) {
658
+ return Promise.resolve(out).then((value) => ({ count: 1, value }));
659
+ }
660
+ return { count: 1, value: out };
661
+ }
662
+ if (mutation === "attr") {
663
+ if (!attrName) return fail("Attribute name is required", "invalid", false);
664
+ return { count: 1, value: element.getAttribute(attrName) };
665
+ }
666
+ if (mutation === "inputValue") {
667
+ if (!(element instanceof HTMLInputElement || element instanceof HTMLTextAreaElement || element instanceof HTMLSelectElement)) {
668
+ return fail("Locator did not match an input, textarea, or select element: " + raw, "invalid", false);
669
+ }
670
+ return { count: 1, value: element.value ?? "" };
671
+ }
672
+ if (mutation === "text") {
673
+ return { count: 1, text: (element.innerText || element.textContent || "").trim() };
674
+ }
675
+ if (mutation === "textContent") {
676
+ return { count: 1, text: element.textContent };
677
+ }
678
+ if (mutation === "innerText") {
679
+ return { count: 1, text: (element.innerText || "").trim() };
680
+ }
681
+ if (mutation === "focus") {
682
+ if (!force && !isVisibleEl(element)) return fail("Locator matched a hidden element: " + raw, "not_visible", true);
683
+ element.scrollIntoView({ block: "center", inline: "center", behavior: "instant" });
684
+ element.focus();
685
+ return { count: 1, focused: true, ...cursorPt(element) };
686
+ }
687
+ if (mutation === "scrollIntoView") {
688
+ element.scrollIntoView({ block: "center", inline: "nearest", behavior: "instant" });
689
+ const rect = element.getBoundingClientRect();
690
+ return {
691
+ count: 1,
692
+ scrolled: true,
693
+ box: { x: rect.x, y: rect.y, width: rect.width, height: rect.height },
694
+ ...cursorPt(element),
695
+ };
696
+ }
697
+ if (mutation === "check" || mutation === "uncheck") {
698
+ if (!force && !isVisibleEl(element)) return fail("Locator matched a hidden element: " + raw, "not_visible", true);
699
+ if (!force && isDisabledEl(element)) return fail("Element is disabled: " + raw, "disabled", true);
700
+ const want = mutation === "check";
701
+ const isChecked = element instanceof HTMLInputElement
702
+ ? !!element.checked
703
+ : element.getAttribute("aria-checked") === "true";
704
+ if (isChecked === want) {
705
+ return { count: 1, changed: false, checked: isChecked, ...cursorPt(element) };
706
+ }
707
+ if (crossOriginDirect) {
708
+ element.scrollIntoView({ block: "center", inline: "center", behavior: "instant" });
709
+ element.click();
710
+ return { count: 1, changed: true, clicked: true, checked: want, ...cursorPt(element) };
711
+ }
712
+ }
713
+ if (mutation === "click") {
714
+ if (!force && !isVisibleEl(element)) return fail("Locator matched a hidden element: " + raw, "not_visible", true);
715
+ if (!force && isDisabledEl(element)) return fail("Element is disabled: " + raw, "disabled", true);
716
+ element.scrollIntoView({ block: "center", inline: "center", behavior: "instant" });
717
+ element.click();
718
+ return { count: 1, clicked: true, ...cursorPt(element) };
719
+ }
720
+ if (mutation === "hover") {
721
+ if (!force && !isVisibleEl(element)) return fail("Locator matched a hidden element: " + raw, "not_visible", true);
722
+ element.scrollIntoView({ block: "center", inline: "center", behavior: "instant" });
723
+ const rect = element.getBoundingClientRect();
724
+ if (rect.width === 0 || rect.height === 0) return fail("Locator matched an element with no visible box: " + raw, "not_visible", true);
725
+ return { count: 1, hovered: true, x: rect.x + rect.width / 2, y: rect.y + rect.height / 2, __cursorMove: true };
726
+ }
727
+ if (mutation === "box") {
728
+ if (!force && !isVisibleEl(element)) return fail("Locator matched a hidden element: " + raw, "not_visible", true);
729
+ element.scrollIntoView({ block: "center", inline: "center", behavior: "instant" });
730
+ const rect = element.getBoundingClientRect();
731
+ if (!rect || rect.width <= 0 || rect.height <= 0) {
732
+ return fail("Locator matched an element with no visible box: " + raw, "not_visible", true);
733
+ }
734
+ let offsetX = 0;
735
+ let offsetY = 0;
736
+ let fWin = element.ownerDocument?.defaultView || window;
737
+ while (fWin && fWin !== window) {
738
+ const frameEl = fWin.frameElement;
739
+ if (!frameEl) break;
740
+ const fr = frameEl.getBoundingClientRect();
741
+ offsetX += fr.left + (frameEl.clientLeft || 0);
742
+ offsetY += fr.top + (frameEl.clientTop || 0);
743
+ fWin = fWin.parent;
744
+ }
745
+ return {
746
+ count: 1,
747
+ box: {
748
+ x: offsetX + rect.left + (window.scrollX || 0),
749
+ y: offsetY + rect.top + (window.scrollY || 0),
750
+ width: rect.width,
751
+ height: rect.height,
752
+ },
753
+ ...cursorPt(element),
754
+ };
755
+ }
756
+ if (mutation === "fill" || mutation === "clear") {
757
+ if (!force && !isVisibleEl(element)) return fail("Locator matched a hidden element: " + raw, "not_visible", true);
758
+ if (!force && isDisabledEl(element)) return fail("Element is disabled: " + raw, "disabled", true);
759
+ if ((element instanceof HTMLInputElement || element instanceof HTMLTextAreaElement) && element.readOnly) {
760
+ return fail("Element is read-only: " + raw, "readonly", false);
761
+ }
762
+ element.scrollIntoView({ block: "center", inline: "center", behavior: "instant" });
763
+ const assigned = mutation === "clear" ? "" : String(nextValue ?? "");
764
+ const inputType = mutation === "clear" ? "deleteContentBackward" : "insertText";
765
+ const rich = tryFillRichEditor(element, assigned, inputType);
766
+ const donePayload = () => ({ count: 1, ...(mutation === "clear" ? { cleared: true } : { filled: true }), ...cursorPt(element) });
767
+ if (rich && typeof rich.then === "function") return rich.then(donePayload);
768
+ if (rich) return donePayload();
769
+ element.focus();
770
+ const descriptor = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(element), "value");
771
+ if (descriptor?.set) descriptor.set.call(element, assigned); else element.value = assigned;
772
+ element.dispatchEvent(typeof InputEvent === "function"
773
+ ? new InputEvent("input", { bubbles: true, composed: true, data: assigned, inputType })
774
+ : new Event("input", { bubbles: true, composed: true }));
775
+ element.dispatchEvent(new Event("change", { bubbles: true }));
776
+ return { count: 1, ...(mutation === "clear" ? { cleared: true } : { filled: true }), ...cursorPt(element) };
777
+ }
778
+ if (mutation === "select") {
779
+ if (!(element instanceof HTMLSelectElement)) return fail("Locator did not match a <select> element: " + raw, "invalid", false);
780
+ if (!force && element.disabled) return fail("Select element is disabled: " + raw, "disabled", true);
781
+ const wanted = Array.isArray(selectSpec) ? selectSpec : [selectSpec];
782
+ const options = Array.from(element.options);
783
+ const selected = [];
784
+ for (const spec of wanted) {
785
+ let opt = null;
786
+ if (typeof spec === "string") {
787
+ opt = options.find((o) => o.value === spec) || options.find((o) => o.label === spec || o.text.trim() === spec);
788
+ } else if (spec && typeof spec === "object") {
789
+ if (spec.index !== undefined) opt = options[spec.index];
790
+ else if (spec.value !== undefined) opt = options.find((o) => o.value === spec.value);
791
+ else if (spec.label !== undefined) opt = options.find((o) => o.label === spec.label || o.text.trim() === spec.label);
792
+ }
793
+ if (!opt) return fail("Select option not found: " + JSON.stringify(spec), "not_found", true);
794
+ if (opt.disabled) return fail("Select option is disabled: " + opt.text, "disabled", true);
795
+ selected.push(opt);
796
+ }
797
+ if (!element.multiple) {
798
+ for (const o of options) o.selected = o === selected[0];
799
+ } else {
800
+ for (const o of options) o.selected = selected.includes(o);
801
+ }
802
+ element.dispatchEvent(new Event("input", { bubbles: true, composed: true }));
803
+ element.dispatchEvent(new Event("change", { bubbles: true }));
804
+ return { count: 1, selected: selected.map((o) => o.value), ...cursorPt(element) };
805
+ }
806
+
807
+ if (!force && !isVisibleEl(element)) return fail("Locator matched a hidden element: " + raw, "not_visible", true);
808
+ if (!force && isDisabledEl(element)) return fail("Element is disabled: " + raw, "disabled", true);
809
+ element.scrollIntoView({ block: "center", inline: "center", behavior: "instant" });
810
+ const rect = element.getBoundingClientRect();
811
+ if (rect.width <= 0 || rect.height <= 0) return fail("Locator matched an element with no visible box: " + raw, "not_visible", true);
812
+
813
+ const doc = element.ownerDocument || document;
814
+ const win = doc.defaultView || window;
815
+ const vv = win.visualViewport;
816
+ const ox = vv?.offsetLeft ?? 0;
817
+ const oy = vv?.offsetTop ?? 0;
818
+ const vw = vv?.width ?? win.innerWidth;
819
+ const vh = vv?.height ?? win.innerHeight;
820
+ const vLeft = Math.max(rect.left, ox);
821
+ const vRight = Math.min(rect.right, ox + vw);
822
+ const vTop = Math.max(rect.top, oy);
823
+ const vBottom = Math.min(rect.bottom, oy + vh);
824
+ if (!force && (vRight <= vLeft || vBottom <= vTop)) {
825
+ return fail("Locator element is outside the viewport: " + raw, "not_visible", true);
826
+ }
827
+
828
+ const boxLeft = vRight > vLeft ? vLeft : rect.left;
829
+ const boxRight = vRight > vLeft ? vRight : rect.right;
830
+ const boxTop = vBottom > vTop ? vTop : rect.top;
831
+ const boxBottom = vBottom > vTop ? vBottom : rect.bottom;
832
+ const cx = (boxLeft + boxRight) / 2;
833
+ const cy = (boxTop + boxBottom) / 2;
834
+ const dx = Math.max(1, (boxRight - boxLeft) * 0.25);
835
+ const dy = Math.max(1, (boxBottom - boxTop) * 0.25);
836
+
837
+ const control = element instanceof HTMLInputElement || element instanceof HTMLButtonElement ||
838
+ element instanceof HTMLSelectElement || element instanceof HTMLTextAreaElement ? element : null;
839
+ const accepted = new Set([element, ...(control?.labels ? Array.from(control.labels) : [])]);
840
+ const matchesTarget = (node) => {
841
+ for (let cur = node; cur; cur = cur.parentNode || cur.host) {
842
+ if (accepted.has(cur)) return true;
843
+ if (cur.assignedSlot && accepted.has(cur.assignedSlot)) return true;
844
+ }
845
+ return false;
846
+ };
847
+
848
+ const points = [
849
+ { x: cx, y: cy },
850
+ { x: boxLeft + dx, y: boxTop + dy },
851
+ { x: boxRight - dx, y: boxTop + dy },
852
+ { x: boxLeft + dx, y: boxBottom - dy },
853
+ { x: boxRight - dx, y: boxBottom - dy },
854
+ ];
855
+ let chosen = null;
856
+ let firstHitTag = null;
857
+ for (const pt of points) {
858
+ const hit = elementFromPointDeep(doc, pt.x, pt.y);
859
+ if (firstHitTag === null) firstHitTag = hit?.tagName?.toLowerCase() ?? null;
860
+ if (hit && matchesTarget(hit)) {
861
+ chosen = pt;
862
+ break;
863
+ }
864
+ }
865
+ if (!force && !chosen) {
866
+ return fail("Locator element is covered by <" + (firstHitTag || "unknown") + ">: " + raw, "covered", true);
867
+ }
868
+
869
+ const pt = chosen || { x: rect.x + rect.width / 2, y: rect.y + rect.height / 2 };
870
+ const sameOriginRect = Array.isArray(sameOriginFrames) && sameOriginFrames.length > 0;
871
+ let offsetX = 0;
872
+ let offsetY = 0;
873
+ if (sameOriginRect) {
874
+ let fWin = element.ownerDocument.defaultView;
875
+ while (fWin && fWin !== window) {
876
+ const frameEl = fWin.frameElement;
877
+ if (!frameEl) break;
878
+ const fr = frameEl.getBoundingClientRect();
879
+ offsetX += fr.left + frameEl.clientLeft;
880
+ offsetY += fr.top + frameEl.clientTop;
881
+ fWin = fWin.parent;
882
+ }
883
+ }
884
+ return {
885
+ count: 1,
886
+ x: offsetX + pt.x,
887
+ y: offsetY + pt.y,
888
+ width: rect.width,
889
+ height: rect.height,
890
+ hitTag: firstHitTag,
891
+ ...(mutation === "check" || mutation === "uncheck"
892
+ ? { changed: true, checked: mutation === "check" }
893
+ : {}),
894
+ };
895
+ };
896
+
897
+ if (waitMs <= 0) return runOnce();
898
+
899
+ const isDone = (res) => mutation === "wait"
900
+ ? Boolean(res?.satisfied || (res?.error && !res.retryable))
901
+ : Boolean(res && (!res.error || !res.retryable));
902
+
903
+ return (async () => {
904
+ const initial = await runOnce();
905
+ if (isDone(initial) || typeof MutationObserver !== "function") return initial;
906
+ return await new Promise((resolve) => {
907
+ let done = false;
908
+ let polling = false;
909
+ const observers = [];
910
+ const finish = (res) => {
911
+ if (done) return;
912
+ done = true;
913
+ clearTimeout(timer);
914
+ clearInterval(interval);
915
+ for (const obs of observers) {
916
+ try { obs.disconnect(); } catch (_e) {}
917
+ }
918
+ resolve(res);
919
+ };
920
+ const check = async () => {
921
+ if (done || polling) return;
922
+ polling = true;
923
+ try {
924
+ const next = await runOnce();
925
+ if (isDone(next)) { finish(next); return; }
926
+ observeFrameRoot();
927
+ } catch (error) {
928
+ finish(fail(error?.message || "Locator evaluation failed", "error", false));
929
+ } finally {
930
+ polling = false;
931
+ }
932
+ };
933
+ const observeTarget = (root) => {
934
+ const target = root?.documentElement || root?.body || root;
935
+ if (!target || typeof target !== "object" || observers.some((o) => o.__target === target)) return;
936
+ try {
937
+ const obs = new MutationObserver(() => { void check(); });
938
+ obs.__target = target;
939
+ obs.observe(target, { childList: true, subtree: true, attributes: true, characterData: true });
940
+ observers.push(obs);
941
+ } catch (_e) {}
942
+ };
943
+ const observeFrameRoot = () => {
944
+ observeTarget(document);
945
+ if (Array.isArray(sameOriginFrames) && sameOriginFrames.length > 0) {
946
+ try {
947
+ const rf = resolveSameOriginTargetRoot(sameOriginFrames);
948
+ if (rf?.root && rf.root !== document) observeTarget(rf.root);
949
+ } catch (_e) {}
950
+ }
951
+ };
952
+ observeFrameRoot();
953
+ const interval = setInterval(() => { void check(); }, 100);
954
+ const timer = setTimeout(() => {
955
+ void (async () => {
956
+ try { finish(await runOnce()); }
957
+ catch (error) { finish(fail(error?.message || "Locator evaluation failed", "error", false)); }
958
+ })();
959
+ }, waitMs);
960
+ });
961
+ })();
962
+ };
963
+ `;
964
+
965
+ /**
966
+ * Install or verify the persistent in-page locator runtime (`globalThis.__buRt`).
967
+ * @returns {string}
968
+ */
969
+ export function locatorRuntimeInstallExpression() {
970
+ return `(() => {
971
+ if (globalThis.__buRt && globalThis.__buRt.v === ${LOCATOR_RUNTIME_VERSION}) {
972
+ return { installed: true, v: ${LOCATOR_RUNTIME_VERSION} };
973
+ }
974
+ ${SHARED_DOM_HELPERS}
975
+ ${SHARED_LOCATOR_RESOLVER}
976
+ ${SHARED_RUNNER_CORE}
977
+ Object.defineProperty(globalThis, "__buRt", {
978
+ value: {
979
+ v: ${LOCATOR_RUNTIME_VERSION},
980
+ run: runLocatorAction,
981
+ suggestCandidates: suggestLocatorCandidates,
982
+ },
983
+ configurable: true,
984
+ writable: true,
985
+ });
986
+ return { installed: true, v: ${LOCATOR_RUNTIME_VERSION} };
987
+ })()`;
988
+ }
989
+
990
+ /**
991
+ * Build a minimal (~250 byte) expression invoking the already-installed `globalThis.__buRt`.
992
+ * @param {string} selector
993
+ * @param {{mutation?:string|null, value?:string|null, select?:unknown, state?:string, sameOriginFrames?:string[], evalFn?:string|null, evalArg?:unknown, hasEvalArg?:boolean, asyncEval?:boolean, attrName?:string|null, force?:boolean, crossOriginDirect?:boolean, inPageWaitMs?:number}} [options]
994
+ * @returns {string}
995
+ */
996
+ export function locatorInvokeExpression(selector, options = {}) {
997
+ const waitMs = Math.max(0, Math.round(Number(options.inPageWaitMs) || 0));
998
+ const isAsync = Boolean(options.asyncEval || waitMs > 0 || options.mutation === "fill" || options.mutation === "clear");
999
+ const compactOpts = {};
1000
+ if (options.mutation != null) compactOpts.mutation = options.mutation;
1001
+ if (options.value != null) compactOpts.value = options.value;
1002
+ if (options.select != null) compactOpts.select = options.select;
1003
+ if (options.state && options.state !== "visible") compactOpts.state = options.state;
1004
+ if (Array.isArray(options.sameOriginFrames) && options.sameOriginFrames.length > 0) compactOpts.sameOriginFrames = options.sameOriginFrames;
1005
+ if (options.crossOriginDirect) compactOpts.crossOriginDirect = true;
1006
+ if (options.force) compactOpts.force = true;
1007
+ if (options.attrName != null) compactOpts.attrName = options.attrName;
1008
+ if (options.hasEvalArg) {
1009
+ compactOpts.hasEvalArg = true;
1010
+ compactOpts.evalArg = options.evalArg ?? null;
1011
+ }
1012
+ if (options.asyncEval) compactOpts.asyncEval = true;
1013
+ if (waitMs > 0) compactOpts.inPageWaitMs = waitMs;
1014
+
1015
+ const args = [JSON.stringify(selector), JSON.stringify(compactOpts)];
1016
+ if (options.evalFn) args.push(`(${options.evalFn})`);
1017
+ const call = `globalThis.__buRt.run(${args.join(",")})`;
1018
+ return isAsync
1019
+ ? `(async()=>globalThis.__buRt?.v===${LOCATOR_RUNTIME_VERSION}?await ${call}:{__buRtMissing:true})()`
1020
+ : `(()=>globalThis.__buRt?.v===${LOCATOR_RUNTIME_VERSION}?${call}:{__buRtMissing:true})()`;
1021
+ }
1022
+
1023
+ /**
1024
+ * Build a standalone Playwright-style locator & action expression executed via Runtime.evaluate.
1025
+ * Kept self-contained as fallback for stateless evaluators and direct test callers.
1026
+ * @param {string} selector
1027
+ * @param {{mutation?:string|null, value?:string|null, select?:unknown, state?:string, sameOriginFrames?:string[], evalFn?:string|null, evalArg?:unknown, hasEvalArg?:boolean, asyncEval?:boolean, attrName?:string|null, force?:boolean, crossOriginDirect?:boolean, inPageWaitMs?:number}} [options]
1028
+ * @returns {string}
1029
+ */
1030
+ export function locatorExpression(selector, options = {}) {
1031
+ const embeddedEvalFn = options.evalFn ? `(${options.evalFn})` : "null";
1032
+ const waitMs = Math.max(0, Math.round(Number(options.inPageWaitMs) || 0));
1033
+ const isAsync = Boolean(options.asyncEval || waitMs > 0 || options.mutation === "fill" || options.mutation === "clear");
1034
+ const wrapperStart = isAsync ? "(async () => {" : "(() => {";
1035
+ const evalAwait = isAsync ? "await " : "";
1036
+ const optsExpr = JSON.stringify({
1037
+ mutation: options.mutation ?? null,
1038
+ value: options.value ?? null,
1039
+ select: options.select ?? null,
1040
+ state: options.state ?? "visible",
1041
+ sameOriginFrames: options.sameOriginFrames ?? null,
1042
+ crossOriginDirect: Boolean(options.crossOriginDirect),
1043
+ force: Boolean(options.force),
1044
+ attrName: options.attrName ?? null,
1045
+ hasEvalArg: Boolean(options.hasEvalArg),
1046
+ evalArg: options.hasEvalArg ? (options.evalArg ?? null) : undefined,
1047
+ asyncEval: Boolean(options.asyncEval),
1048
+ inPageWaitMs: waitMs,
1049
+ });
1050
+ return `${wrapperStart}
1051
+ const mutation = ${JSON.stringify(options.mutation ?? null)};
1052
+ ${SHARED_DOM_HELPERS}
1053
+ ${SHARED_LOCATOR_RESOLVER}
1054
+ ${SHARED_RUNNER_CORE}
1055
+ return ${evalAwait}runLocatorAction(${JSON.stringify(selector)}, ${optsExpr}, ${embeddedEvalFn});
1056
+ })()`;
1057
+ }
1058
+
1059
+ /**
1060
+ * Build an in-page MutationObserver expression that waits for visible text without polling IPC.
1061
+ * @param {string} text
1062
+ * @param {{timeoutMs?:number}} [options]
1063
+ * @returns {string}
1064
+ */
1065
+ export function waitForTextExpression(text, { timeoutMs = 1_000 } = {}) {
1066
+ const waitMs = Math.max(0, Math.round(Number(timeoutMs) || 0));
1067
+ return `(async () => {
1068
+ const needle = ${JSON.stringify(String(text))};
1069
+ const readText = () => (document.body ? document.body.innerText : "");
1070
+ if (readText().includes(needle)) return { matched: true };
1071
+ const waitMs = ${waitMs};
1072
+ if (waitMs <= 0 || typeof MutationObserver !== "function") return { matched: false };
1073
+ return await new Promise((resolve) => {
1074
+ let done = false;
1075
+ let obs = null;
1076
+ const finish = (matched) => {
1077
+ if (done) return;
1078
+ done = true;
1079
+ clearTimeout(timer);
1080
+ clearInterval(interval);
1081
+ if (obs) {
1082
+ try { obs.disconnect(); } catch (_e) {}
1083
+ }
1084
+ resolve({ matched });
1085
+ };
1086
+ const check = () => {
1087
+ if (done) return;
1088
+ if (readText().includes(needle)) finish(true);
1089
+ };
1090
+ const target = document.documentElement || document.body || document;
1091
+ if (target) {
1092
+ try {
1093
+ obs = new MutationObserver(check);
1094
+ obs.observe(target, { childList: true, subtree: true, characterData: true });
1095
+ } catch (_e) {
1096
+ obs = null;
1097
+ }
1098
+ }
1099
+ const interval = setInterval(check, 100);
1100
+ const timer = setTimeout(() => finish(readText().includes(needle)), waitMs);
1101
+ });
1102
+ })()`;
1103
+ }
1104
+
1105
+ /**
1106
+ * Build a Runtime.evaluate expression (`returnByValue: false`) that resolves a single DOM node
1107
+ * across Shadow DOM and same-origin iframes (for `DOM.describeNode` -> `DOM.setFileInputFiles`).
1108
+ * @param {string} selector
1109
+ * @param {{sameOriginFrames?:string[]}} [options]
1110
+ * @returns {string}
1111
+ */
1112
+ export function locatorResolveNodeExpression(selector, { sameOriginFrames = null } = {}) {
1113
+ return `(() => {
1114
+ const raw = ${JSON.stringify(selector)};
1115
+ const sameOriginFrames = ${JSON.stringify(sameOriginFrames)};
1116
+ ${SHARED_DOM_HELPERS}
1117
+ ${SHARED_LOCATOR_RESOLVER}
1118
+ const resolvedFrame = resolveSameOriginTargetRoot(sameOriginFrames);
1119
+ if (resolvedFrame.error) throw new Error(resolvedFrame.error);
1120
+ const nodes = resolvePipeline(resolvedFrame.root, raw);
1121
+ if (nodes.length === 0) throw new Error("Locator did not match any element: " + raw);
1122
+ if (nodes.length > 1) throw new Error("Locator matched " + nodes.length + " elements: " + raw);
1123
+ return nodes[0];
1124
+ })()`;
1125
+ }
1126
+
1127
+ /**
1128
+ * Function declaration for Runtime.callFunctionOn to perform Shadow-DOM-aware
1129
+ * hit-testing and viewport-clamped coordinate calculation on a resolved DOM node.
1130
+ * @returns {string}
1131
+ */
1132
+ export function hitTestFunctionDeclaration() {
1133
+ return `function () {
1134
+ const el = this instanceof Element ? this : this.parentElement;
1135
+ if (!el || !el.isConnected) return { unpositioned: true, reason: "detached" };
1136
+ let rect = el.getClientRects()[0] || el.getBoundingClientRect();
1137
+ if (this instanceof Text) {
1138
+ const range = document.createRange();
1139
+ range.selectNode(this);
1140
+ rect = range.getClientRects()[0] || range.getBoundingClientRect();
1141
+ }
1142
+ if (!rect || rect.width <= 0 || rect.height <= 0) return { unpositioned: true, reason: "zero-box" };
1143
+ const win = el.ownerDocument?.defaultView || window;
1144
+ const vv = win.visualViewport;
1145
+ const ox = vv?.offsetLeft ?? 0;
1146
+ const oy = vv?.offsetTop ?? 0;
1147
+ const vw = vv?.width ?? win.innerWidth;
1148
+ const vh = vv?.height ?? win.innerHeight;
1149
+ const left = Math.max(rect.left, ox);
1150
+ const right = Math.min(rect.right, ox + vw);
1151
+ const top = Math.max(rect.top, oy);
1152
+ const bottom = Math.min(rect.bottom, oy + vh);
1153
+ if (right <= left || bottom <= top) return { offscreen: true, width: rect.width, height: rect.height };
1154
+
1155
+ const control = el instanceof HTMLInputElement || el instanceof HTMLButtonElement ||
1156
+ el instanceof HTMLSelectElement || el instanceof HTMLTextAreaElement ? el : null;
1157
+ const accepted = new Set([el, ...(control?.labels ? Array.from(control.labels) : [])]);
1158
+ const interactiveSel = 'button,a[href],input,select,textarea,[role="button"],[role="checkbox"],[role="combobox"],[role="link"],[role="menuitem"],[role="option"],[role="radio"],[role="switch"],[role="tab"],[role="textbox"]';
1159
+ const rootInteractive = el.closest(interactiveSel);
1160
+ if (rootInteractive) accepted.add(rootInteractive);
1161
+
1162
+ const hitAt = (x, y) => {
1163
+ const root = el.getRootNode();
1164
+ let node = root instanceof ShadowRoot ? root.elementFromPoint(x, y) : el.ownerDocument.elementFromPoint(x, y);
1165
+ while (node?.shadowRoot) {
1166
+ const inner = node.shadowRoot.elementFromPoint(x, y);
1167
+ if (!inner || inner === node) break;
1168
+ node = inner;
1169
+ }
1170
+ return node;
1171
+ };
1172
+
1173
+ const matchesTarget = (node) => {
1174
+ for (let cur = node; cur; cur = cur.parentNode || cur.host) {
1175
+ if (accepted.has(cur)) return true;
1176
+ if (cur.assignedSlot) {
1177
+ if (accepted.has(cur.assignedSlot)) return true;
1178
+ }
1179
+ }
1180
+ return false;
1181
+ };
1182
+
1183
+ const cx = (left + right) / 2;
1184
+ const cy = (top + bottom) / 2;
1185
+ const dx = Math.max(2, (right - left) * 0.25);
1186
+ const dy = Math.max(2, (bottom - top) * 0.25);
1187
+ const candidates = [
1188
+ { x: cx, y: cy },
1189
+ { x: left + dx, y: top + dy },
1190
+ { x: right - dx, y: top + dy },
1191
+ { x: left + dx, y: bottom - dy },
1192
+ { x: right - dx, y: bottom - dy },
1193
+ ];
1194
+ let firstHitTag = null;
1195
+ for (const pt of candidates) {
1196
+ const hit = hitAt(pt.x, pt.y);
1197
+ if (firstHitTag === null) firstHitTag = hit?.tagName?.toLowerCase() ?? null;
1198
+ if (hit && matchesTarget(hit)) {
1199
+ return { hitsTarget: true, point: pt, width: rect.width, height: rect.height };
1200
+ }
1201
+ }
1202
+ return { hitsTarget: false, hitTag: firstHitTag, point: { x: cx, y: cy }, width: rect.width, height: rect.height };
1203
+ }`;
1204
+ }
1205
+
1206
+ /**
1207
+ * Function declaration for Runtime.callFunctionOn to set values semantically across
1208
+ * inputs, textareas, checkboxes, radios, native selects, contenteditable elements, and tabs.
1209
+ * @returns {string}
1210
+ */
1211
+ export function smartSetValueFunctionDeclaration() {
1212
+ return `function (value) {
1213
+ const val = String(value);
1214
+ const role = this.getAttribute ? this.getAttribute("role") : null;
1215
+ if (this.isConnected !== false && typeof this.scrollIntoView === "function") {
1216
+ this.scrollIntoView({ block: "center", inline: "center", behavior: "instant" });
1217
+ }
1218
+ const ensureEditable = (label, checkReadOnly = false) => {
1219
+ if (!this.isConnected) throw new Error(label + " is no longer connected");
1220
+ if (this.matches(":disabled") || this.getAttribute("aria-disabled") === "true") {
1221
+ throw new Error(label + " is disabled");
1222
+ }
1223
+ if (checkReadOnly && (this instanceof HTMLInputElement || this instanceof HTMLTextAreaElement) && this.readOnly) {
1224
+ throw new Error(label + " is read-only");
1225
+ }
1226
+ };
1227
+ const resultStatus = (status) => {
1228
+ const rect = typeof this.getBoundingClientRect === "function" ? this.getBoundingClientRect() : null;
1229
+ return rect && rect.width > 0 && rect.height > 0
1230
+ ? { status, x: rect.left + rect.width / 2, y: rect.top + rect.height / 2, __cursorMove: true }
1231
+ : { status };
1232
+ };
1233
+ const emit = () => {
1234
+ this.dispatchEvent(new Event("input", { bubbles: true, composed: true }));
1235
+ this.dispatchEvent(new Event("change", { bubbles: true }));
1236
+ };
1237
+
1238
+ if (this instanceof HTMLInputElement && (this.type === "checkbox" || this.type === "radio")) {
1239
+ const kind = this.type === "radio" ? "Radio button" : role === "switch" ? "Switch" : "Checkbox";
1240
+ if (!["0", "1", "false", "true"].includes(val)) throw new Error(kind + " value must be 0, 1, false, or true");
1241
+ ensureEditable(kind);
1242
+ const checked = val === "1" || val === "true";
1243
+ const changed = this.checked !== checked || (this.type === "checkbox" && this.indeterminate);
1244
+ const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "checked")?.set;
1245
+ this.focus();
1246
+ if (setter) setter.call(this, checked); else this.checked = checked;
1247
+ if (this.type === "checkbox") this.indeterminate = false;
1248
+ if (changed) emit();
1249
+ return resultStatus("done");
1250
+ }
1251
+
1252
+ if (this instanceof HTMLSelectElement) {
1253
+ ensureEditable("Select");
1254
+ const options = Array.from(this.options);
1255
+ let opt = options.find((o) => o.value === val);
1256
+ if (!opt) {
1257
+ const byLabel = options.filter((o) => o.label === val || o.text.trim() === val);
1258
+ if (byLabel.length !== 1) {
1259
+ throw new Error(byLabel.length === 0 ? "Select option not found: " + val : "Select option label is ambiguous: " + val);
1260
+ }
1261
+ opt = byLabel[0];
1262
+ }
1263
+ if (opt.disabled) throw new Error("Select option is disabled: " + val);
1264
+ this.focus();
1265
+ const changed = !opt.selected;
1266
+ opt.selected = true;
1267
+ if (changed) emit();
1268
+ return resultStatus("done");
1269
+ }
1270
+
1271
+ if (this instanceof HTMLInputElement || this instanceof HTMLTextAreaElement) {
1272
+ if (this instanceof HTMLInputElement && this.type === "file") {
1273
+ throw new Error("File inputs require browser_upload_files");
1274
+ }
1275
+ ensureEditable("Input", true);
1276
+ const win = this.ownerDocument?.defaultView || window;
1277
+ const cke = win?.CKEDITOR?.instances;
1278
+ if (cke && typeof cke === "object") {
1279
+ for (const inst of Object.values(cke)) {
1280
+ if (inst && (inst.element?.$ === this || (this.id && inst.name === this.id) || (this.name && inst.name === this.name))) {
1281
+ inst.setData?.(val);
1282
+ inst.updateElement?.();
1283
+ return resultStatus("done");
1284
+ }
1285
+ }
1286
+ }
1287
+ const tiny = this.id ? win?.tinymce?.get?.(this.id) : null;
1288
+ if (tiny && typeof tiny.setContent === "function") {
1289
+ tiny.setContent(val);
1290
+ tiny.save?.();
1291
+ return resultStatus("done");
1292
+ }
1293
+ this.focus();
1294
+ const descriptor = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(this), "value");
1295
+ if (descriptor?.set) descriptor.set.call(this, val); else this.value = val;
1296
+ emit();
1297
+ return resultStatus("done");
1298
+ }
1299
+
1300
+ if (role === "tab") {
1301
+ ensureEditable("Tab");
1302
+ return this.getAttribute("aria-selected") === "true" ? resultStatus("done") : resultStatus("needs-click");
1303
+ }
1304
+
1305
+ const ck5 = this.ckeditorInstance || this.closest?.(".ck-editor__editable")?.ckeditorInstance;
1306
+ if (ck5 && typeof ck5.setData === "function") {
1307
+ ensureEditable("Editable element");
1308
+ ck5.setData(val);
1309
+ return resultStatus("done");
1310
+ }
1311
+ const quill = this.__quill || this.closest?.(".ql-container")?.__quill;
1312
+ if (quill && typeof quill.setText === "function") {
1313
+ ensureEditable("Editable element");
1314
+ quill.setText(val);
1315
+ return resultStatus("done");
1316
+ }
1317
+ if (this instanceof HTMLElement && this.isContentEditable) {
1318
+ ensureEditable("Editable element");
1319
+ this.focus();
1320
+ this.textContent = val;
1321
+ this.dispatchEvent(new InputEvent("input", { bubbles: true, composed: true, data: val, inputType: "insertText" }));
1322
+ this.dispatchEvent(new Event("change", { bubbles: true }));
1323
+ return resultStatus("done");
1324
+ }
1325
+
1326
+ if (typeof this.focus === "function") this.focus();
1327
+ const descriptor = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(this), "value");
1328
+ if (descriptor?.set) descriptor.set.call(this, val); else this.value = val;
1329
+ emit();
1330
+ return resultStatus("done");
1331
+ }`;
1332
+ }
1333
+
1334
+ /**
1335
+ * Function declaration for Runtime.callFunctionOn on an HTMLSelectElement.
1336
+ * @returns {string}
1337
+ */
1338
+ export function selectOptionFunctionDeclaration() {
1339
+ return `function (specList) {
1340
+ if (!(this instanceof HTMLSelectElement)) throw new Error("Target element is not a <select>");
1341
+ if (this.disabled) throw new Error("Select element is disabled");
1342
+ if (typeof this.scrollIntoView === "function") {
1343
+ this.scrollIntoView({ block: "center", inline: "center", behavior: "instant" });
1344
+ }
1345
+ if (typeof this.focus === "function") this.focus();
1346
+ const wanted = Array.isArray(specList) ? specList : [specList];
1347
+ const options = Array.from(this.options);
1348
+ const chosen = [];
1349
+ for (const spec of wanted) {
1350
+ let opt = null;
1351
+ if (typeof spec === "string") {
1352
+ opt = options.find((o) => o.value === spec) || options.find((o) => o.label === spec || o.text.trim() === spec);
1353
+ } else if (spec && typeof spec === "object") {
1354
+ if (spec.index !== undefined) opt = options[spec.index];
1355
+ else if (spec.value !== undefined) opt = options.find((o) => o.value === spec.value);
1356
+ else if (spec.label !== undefined) opt = options.find((o) => o.label === spec.label || o.text.trim() === spec.label);
1357
+ }
1358
+ if (!opt) throw new Error("Select option not found: " + JSON.stringify(spec));
1359
+ if (opt.disabled) throw new Error("Select option is disabled: " + opt.text);
1360
+ chosen.push(opt);
1361
+ }
1362
+ if (!this.multiple) {
1363
+ for (const o of options) o.selected = o === chosen[0];
1364
+ } else {
1365
+ for (const o of options) o.selected = chosen.includes(o);
1366
+ }
1367
+ this.dispatchEvent(new Event("input", { bubbles: true, composed: true }));
1368
+ this.dispatchEvent(new Event("change", { bubbles: true }));
1369
+ return chosen.map((o) => o.value);
1370
+ }`;
1371
+ }
1372
+
1373
+ /**
1374
+ * Inspect DOM elements at viewport coordinate (x, y) and generate ranked locators.
1375
+ * @param {number} x
1376
+ * @param {number} y
1377
+ * @returns {string}
1378
+ */
1379
+ export function inspectElementAtPointExpression(x, y) {
1380
+ return `(() => {
1381
+ const px = ${Number(x)};
1382
+ const py = ${Number(y)};
1383
+ ${SHARED_DOM_HELPERS}
1384
+ const stack = document.elementsFromPoint(px, py);
1385
+ const results = [];
1386
+ const seen = new Set();
1387
+
1388
+ const expandShadow = (el) => {
1389
+ if (!el || seen.has(el)) return;
1390
+ seen.add(el);
1391
+ const tag = el.tagName.toLowerCase();
1392
+ const role = implicitRoleOf(el) || null;
1393
+ const ariaName = accessibleNameOf(el) || null;
1394
+ const testId = el.getAttribute("data-testid") || el.getAttribute("data-test-id") || el.getAttribute("data-test") || null;
1395
+ const rect = el.getBoundingClientRect();
1396
+ const candidates = [];
1397
+ if (testId) candidates.push("testid=" + testId);
1398
+ if (role && ariaName && ariaName.length <= 60) candidates.push("role=" + role + "[name=" + JSON.stringify(ariaName) + "]");
1399
+ if (el.id && !/^\\d|:/.test(el.id)) candidates.push("css=#" + CSS.escape(el.id));
1400
+ const lbl = labelTextFor(el);
1401
+ if (lbl && lbl.length <= 60) candidates.push("label=" + lbl);
1402
+ const visibleText = (el.innerText || el.value || "").replace(/\\s+/g, " ").trim();
1403
+ if (visibleText && visibleText.length <= 60 && !candidates.some((c) => c.includes(visibleText))) {
1404
+ candidates.push("text=" + JSON.stringify(visibleText));
1405
+ }
1406
+ const cls = Array.from(el.classList || []).filter((c) => c && !/^[0-9]|[:]/.test(c)).slice(0, 2);
1407
+ candidates.push("css=" + tag + (cls.length ? "." + cls.map((c) => CSS.escape(c)).join(".") : ""));
1408
+ results.push({
1409
+ tagName: tag,
1410
+ role,
1411
+ ariaName: ariaName ? ariaName.slice(0, 120) : null,
1412
+ visibleText: visibleText ? visibleText.slice(0, 120) : null,
1413
+ testId,
1414
+ boundingBox: { x: Math.round(rect.x), y: Math.round(rect.y), width: Math.round(rect.width), height: Math.round(rect.height) },
1415
+ candidates,
1416
+ });
1417
+ if (el.shadowRoot) {
1418
+ for (const inner of el.shadowRoot.elementsFromPoint(px, py)) {
1419
+ if (inner !== el && results.length < 5) expandShadow(inner);
1420
+ }
1421
+ }
1422
+ };
1423
+
1424
+ for (const el of stack) {
1425
+ if (results.length >= 5) break;
1426
+ expandShadow(el);
1427
+ }
1428
+ return { x: px, y: py, elements: results };
1429
+ })()`;
1430
+ }
1431
+
1432
+ /**
1433
+ * Extract a compact, noise-stripped visible DOM snapshot with same-origin iframe expansion.
1434
+ * @param {number} [maxChars]
1435
+ * @returns {string}
1436
+ */
1437
+ export function domSnapshotExpression(maxChars = 24_000) {
1438
+ return `(() => {
1439
+ const limit = ${Math.max(1_000, Number(maxChars) || 24_000)};
1440
+ const SKIP_TAGS = new Set(["SCRIPT", "STYLE", "NOSCRIPT", "TEMPLATE", "SVG", "PATH", "DEFS", "META", "LINK"]);
1441
+ const ATTRS = ["id", "name", "role", "type", "href", "placeholder", "aria-label", "data-testid", "value", "disabled", "checked"];
1442
+ const out = [];
1443
+ let length = 0;
1444
+ let truncated = false;
1445
+
1446
+ const pushLine = (line) => {
1447
+ if (truncated) return;
1448
+ if (length + line.length + 1 > limit) {
1449
+ truncated = true;
1450
+ out.push("...(truncated)");
1451
+ return;
1452
+ }
1453
+ out.push(line);
1454
+ length += line.length + 1;
1455
+ };
1456
+
1457
+ const walk = (node, depth, frameDepth) => {
1458
+ if (truncated || !node) return;
1459
+ if (node.nodeType === 3) {
1460
+ const txt = (node.textContent || "").replace(/\\s+/g, " ").trim();
1461
+ if (txt) pushLine(" ".repeat(depth) + JSON.stringify(txt.slice(0, 200)));
1462
+ return;
1463
+ }
1464
+ if (node.nodeType !== 1) return;
1465
+ if (SKIP_TAGS.has(node.tagName)) return;
1466
+ const win = node.ownerDocument?.defaultView || window;
1467
+ const style = win.getComputedStyle(node);
1468
+ if (style && (style.display === "none" || style.visibility === "hidden")) return;
1469
+
1470
+ const tag = node.tagName.toLowerCase();
1471
+ const attrs = [];
1472
+ for (const name of ATTRS) {
1473
+ let val = name === "value" && "value" in node ? node.value : node.getAttribute(name);
1474
+ if (val === null || val === undefined || val === "") continue;
1475
+ if (name === "disabled" || name === "checked") val = "true";
1476
+ attrs.push(name + "=" + JSON.stringify(String(val).slice(0, 120)));
1477
+ }
1478
+ const isWrapper = (tag === "div" || tag === "span") && attrs.length === 0;
1479
+ const nextDepth = isWrapper ? depth : depth + 1;
1480
+ if (!isWrapper) {
1481
+ pushLine(" ".repeat(depth) + "<" + tag + (attrs.length ? " " + attrs.join(" ") : "") + ">");
1482
+ }
1483
+ if (tag === "iframe" && frameDepth < 3 && node.contentDocument?.body) {
1484
+ pushLine(" ".repeat(nextDepth) + "<!-- same-origin iframe -->");
1485
+ walk(node.contentDocument.body, nextDepth + 1, frameDepth + 1);
1486
+ return;
1487
+ }
1488
+ if (node.shadowRoot) {
1489
+ for (const child of node.shadowRoot.childNodes) walk(child, nextDepth, frameDepth);
1490
+ }
1491
+ for (const child of node.childNodes) walk(child, nextDepth, frameDepth);
1492
+ };
1493
+
1494
+ if (document.body) walk(document.body, 0, 0);
1495
+ return { title: document.title || "", url: location.href, truncated, snapshot: out.join("\\n") };
1496
+ })()`;
1497
+ }