1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
(function() {
// Snapshot caching: a MutationObserver marks the page dirty on any
// DOM change. When the page is clean and we have a cached result,
// return it without re-walking the tree (the expensive part). The
// observer and cache die with the document on navigation, so a
// fresh page always walks once.
// document.open() replaces the document but keeps the window, so
// an observer left on the old root would never fire again and the
// cached result would go stale. Re-attach when the root changed.
if (!window.__vsDirtyObserver || window.__vsDirtyObserver.__root !== document.documentElement) {
window.__vsDirty = true;
try {
if (window.__vsDirtyObserver) window.__vsDirtyObserver.disconnect();
window.__vsDirtyObserver = new MutationObserver(function() {
window.__vsDirty = true;
});
window.__vsDirtyObserver.__root = document.documentElement;
window.__vsDirtyObserver.observe(document.documentElement, {
subtree: true, childList: true, attributes: true, characterData: true,
});
// MutationObserver misses input `.value` changes (a property,
// not an attribute). Fills and real typing dispatch input and
// change, so mark dirty on those too, in the capture phase.
var __vsMark = function() { window.__vsDirty = true; };
document.addEventListener('input', __vsMark, true);
document.addEventListener('change', __vsMark, true);
} catch (e) { window.__vsDirty = true; }
}
if (window.__vsDirty === false && typeof window.__vsLastResult === 'string') {
return window.__vsLastResult;
}
const ROLES = {
'A': 'lnk', 'BUTTON': 'btn',
'TEXTAREA': 'ta', 'SELECT': 'sel',
'H1': 'hd', 'H2': 'hd', 'H3': 'hd', 'H4': 'hd', 'H5': 'hd', 'H6': 'hd',
'NAV': 'nav', 'MAIN': 'mn', 'HEADER': 'hdr', 'FOOTER': 'sec',
'IMG': 'img', 'UL': 'lst', 'OL': 'lst', 'LI': 'li',
'TABLE': 'tbl', 'TR': 'row', 'TD': 'cell', 'TH': 'cell',
'FORM': 'frm', 'P': 'p', 'ARTICLE': 'art', 'SECTION': 'sec',
// Embedded documents. The walker cannot cross the frame
// boundary, so the node carries the only thing an agent can
// act on: the resolved src. Without it an embedded viewer
// (pdf.js and friends) is a hole in the tree.
'IFRAME': 'ifr', 'FRAME': 'ifr', 'EMBED': 'ifr', 'OBJECT': 'ifr',
};
// Roles whose label is *only* the leaf text the user reads, not the
// entire subtree text. Containers (nav, main, hdr, sec, art, tbl,
// row, frm, lst) get an empty label — their identity is the
// structure they wrap, not the bag of text inside them.
const LEAF_LABEL_ROLES = new Set([
'lnk', 'btn', 'hd', 'p', 'li', 'cell', 'lbl', 'tf', 'ta', 'sel',
'chk', 'rad', 'img', 'itm',
]);
// Interactive roles get a hid=1 attr when the element cannot be
// seen or hit: display:none / visibility:hidden (checkVisibility)
// or a zero-size box. Sites keep hidden duplicates of buttons in
// the DOM (x.com login); without the marker an agent cannot tell
// the dead ref from the live one.
const INTERACTIVE_ROLES = new Set([
'btn', 'lnk', 'tf', 'ta', 'sel', 'chk', 'rad', 'itm',
]);
function hiddenFor(el, role) {
if (!INTERACTIVE_ROLES.has(role)) return false;
try {
if (el.checkVisibility && !el.checkVisibility()) return true;
const b = el.getBoundingClientRect();
return b.width < 0.5 || b.height < 0.5;
} catch (e) { return false; }
}
// ARIA role → vs short-form mapping. Modern React UIs (Radix,
// Headless UI, Reach UI, custom) render most actionable elements
// as `<div role="...">` rather than semantic HTML, so the HTML-tag
// table above misses them entirely. v0.1.8 consults `role="..."`
// before falling back to the tag map.
const ARIA_ROLES = {
'button': 'btn', 'link': 'lnk',
'checkbox': 'chk', 'switch': 'chk', 'radio': 'rad',
'textbox': 'tf', 'searchbox': 'tf', 'combobox': 'sel',
'listbox': 'lst', 'menu': 'lst', 'tree': 'lst',
'option': 'itm', 'menuitem': 'itm', 'menuitemcheckbox': 'chk',
'menuitemradio': 'rad', 'treeitem': 'itm', 'listitem': 'itm',
'tab': 'itm', 'tabpanel': 'sec',
'dialog': 'dlg', 'alertdialog': 'dlg',
'navigation': 'nav', 'main': 'mn', 'banner': 'hdr', 'contentinfo': 'sec',
'heading': 'hd', 'img': 'img', 'figure': 'img', 'region': 'sec',
'article': 'art', 'form': 'frm', 'search': 'frm',
'table': 'tbl', 'grid': 'tbl', 'row': 'row', 'gridcell': 'cell',
'cell': 'cell', 'columnheader': 'hdr', 'rowheader': 'hdr',
};
function inputRole(el) {
const t = (el.getAttribute('type') || 'text').toLowerCase();
if (t === 'submit' || t === 'button') return 'btn';
if (t === 'checkbox') return 'chk';
if (t === 'radio') return 'rad';
return 'tf';
}
function roleFor(el) {
if (el.tagName === 'INPUT') return inputRole(el);
const aria = el.getAttribute('role');
if (aria) {
const m = ARIA_ROLES[aria];
if (m) return m;
}
// Heuristic: any element with an explicit click handler or a
// tabindex that makes it focusable should expose `btn` so the
// agent can act on it. Catches the Radix/Headless pattern of
// `<div role="combobox" tabindex="0">` triggers.
if (el.tagName !== 'DIV' && el.tagName !== 'SPAN') {
return ROLES[el.tagName] || null;
}
const ti = el.getAttribute('tabindex');
if (ti !== null && ti !== '-1') return 'btn';
return ROLES[el.tagName] || null;
}
/// Direct (non-element-child) text under `el`, joined and trimmed.
/// Used for container-ish elements whose subtree we don't want to
/// scrape entirely.
function directText(el) {
let out = '';
for (const c of el.childNodes) {
if (c.nodeType === Node.TEXT_NODE) out += c.nodeValue;
}
return out.replace(/\s+/g, ' ').trim();
}
// Bot-challenge detection.
//
// A challenge (Turnstile, hCaptcha, reCAPTCHA) is a hole in the
// tree: its container is a bare <div> the role table ignores, and
// when the widget fails to render there is no iframe either, so
// the only trace left is a hidden response input that reads as an
// anonymous `tf ... hid=1`. An agent sees a form, submits it, gets
// rejected by the server, and concludes the form is broken — the
// page never said it was gated.
//
// The response input is the reliable marker: every provider
// creates it, under both implicit (`.cf-turnstile` div) and
// explicit (`turnstile.render(...)`) rendering.
const CHALLENGE_INPUTS = {
'cf-turnstile-response': 'turnstile',
'h-captcha-response': 'hcaptcha',
'g-recaptcha-response': 'recaptcha',
};
const CHALLENGE_CLASSES = [
['cf-turnstile', 'turnstile'],
['h-captcha', 'hcaptcha'],
['g-recaptcha', 'recaptcha'],
];
/// `{provider, state, box}` if `el` is a challenge widget or its
/// response field, else null.
///
/// `state` is `solved` (token present, submit away) or `pending`
/// (a challenge is up and unsolved). There is deliberately no
/// "unrendered" state: Turnstile draws its widget into a **closed**
/// shadow root, which `querySelector('iframe')` cannot see by
/// design, so the previous iframe-counting check reported "no
/// widget exists" for widgets that were on screen and clickable.
/// That is the worst possible error here — it tells an agent to
/// give up on something it could have solved in one click.
///
/// `box` is the widget's viewport rect, so an agent can go straight
/// to `vs click-at` without measuring it first.
function challengeFor(el) {
var provider = null;
var tokenEl = null;
var name = el.getAttribute && (el.getAttribute('name') || '');
if (name && CHALLENGE_INPUTS[name]) {
provider = CHALLENGE_INPUTS[name];
tokenEl = el;
} else {
var cls = '';
try { cls = String(el.className && el.className.baseVal !== undefined ? el.className.baseVal : (el.className || '')); } catch (e) { cls = ''; }
for (var i = 0; i < CHALLENGE_CLASSES.length; i += 1) {
if (cls.indexOf(CHALLENGE_CLASSES[i][0]) >= 0) {
provider = CHALLENGE_CLASSES[i][1];
break;
}
}
if (!provider) return null;
try {
tokenEl = el.querySelector('[name="cf-turnstile-response"],[name="h-captcha-response"],[name="g-recaptcha-response"]');
} catch (e) { tokenEl = null; }
}
var token = tokenEl && tokenEl.value ? tokenEl.value : '';
// The widget host: the response field's wrapper, or the
// container class we matched. Its rect is what an agent aims
// at — the interactive checkbox sits at the left of it.
var host = tokenEl && tokenEl.parentNode && tokenEl.parentNode.parentNode
? tokenEl.parentNode.parentNode
: el;
var box = null;
try {
var r = host.getBoundingClientRect();
if (r.width > 0 && r.height > 0) {
box = [Math.round(r.left), Math.round(r.top),
Math.round(r.width), Math.round(r.height)];
}
} catch (e) { box = null; }
return {
provider: provider,
state: token ? 'solved' : 'pending',
box: box,
};
}
const FIELD_ROLES = new Set(['tf', 'ta', 'sel', 'chk', 'rad']);
// Text of the elements that label a form field: aria-labelledby,
// else <label for> and a wrapping <label>. The control's own text
// (a wrapped <select>'s options) is left out.
function fieldLabel(el) {
var sources = [];
var ids = el.getAttribute('aria-labelledby');
if (ids) {
ids.split(/\s+/).forEach(function (id) {
var t = id && document.getElementById(id);
if (t) sources.push(t);
});
} else if (el.labels) {
for (var i = 0; i < el.labels.length; i++) sources.push(el.labels[i]);
}
var out = '';
function collect(n) {
if (n === el) return;
if (n.nodeType === 3) { out += n.nodeValue + ' '; return; }
if (n.nodeType !== 1) return;
var tag = n.tagName;
if (tag === 'SELECT' || tag === 'TEXTAREA' || tag === 'SCRIPT' || tag === 'STYLE') return;
for (var c = n.firstChild; c; c = c.nextSibling) collect(c);
}
sources.forEach(collect);
return out.replace(/\s+/g, ' ').trim().slice(0, 200);
}
function labelFor(el, role) {
const aria = el.getAttribute('aria-label');
if (aria) return aria.trim();
if (el.tagName === 'INPUT' || el.tagName === 'TEXTAREA') {
// Mask sensitive inputs so the agent never sees what the
// user typed via `vs prompt-input --secret` (or via the
// page directly). The HTML spec already marks `password`
// / `hidden` inputs as not-for-display; the `autocomplete`
// hints catch credit-card fields and similar.
const type = (el.getAttribute('type') || 'text').toLowerCase();
const ac = (el.getAttribute('autocomplete') || '').toLowerCase();
const sensitive = (
type === 'password' || type === 'hidden' ||
ac === 'current-password' || ac === 'new-password' ||
ac === 'one-time-code' ||
ac === 'cc-number' || ac === 'cc-csc'
);
if (sensitive) {
if (el.value) return '***';
return (el.placeholder || '').trim();
}
return (el.value || el.placeholder || '').trim();
}
if (el.tagName === 'IMG') return (el.alt || '').trim();
if (role === 'ifr') {
// `.src` / `.data` are already resolved against the base
// URL; the attribute is often relative and useless to an
// agent that wants to fetch it.
var frameSrc = String(el.src || el.data || el.getAttribute('src') || '');
if (!frameSrc && el.tagName === 'IFRAME' && el.getAttribute('srcdoc') !== null) {
return 'srcdoc:';
}
// A data: URL is the whole document inline — megabytes of
// it, sometimes. Keep the mime prefix, drop the payload.
if (frameSrc.slice(0, 5) === 'data:') {
return 'data:' + frameSrc.slice(5).split(';')[0].split(',')[0];
}
return frameSrc.slice(0, 500);
}
if (LEAF_LABEL_ROLES.has(role)) {
// Use innerText (capped) for leaf-ish nodes the user reads.
return (el.innerText || el.textContent || '')
.replace(/\s+/g, ' ').trim().slice(0, 200);
}
// Container roles: only the direct text (typically empty).
return directText(el).slice(0, 200);
}
// A change inside a same-origin frame must invalidate the cached
// top-level result too, so each walked frame document gets an
// observer that marks the top window dirty.
function watchFrame(doc) {
var w = doc.defaultView;
if (!w || w.__vsFrameObserved) return;
try {
var mark = function () { window.__vsDirty = true; };
new w.MutationObserver(mark).observe(doc.documentElement, {
subtree: true, childList: true, attributes: true, characterData: true,
});
doc.addEventListener('input', mark, true);
doc.addEventListener('change', mark, true);
Object.defineProperty(w, '__vsFrameObserved', { value: true, enumerable: false });
// The frame navigating replaces the document; the next
// walk sees a new one.
w.addEventListener('pagehide', mark);
} catch (e) { window.__vsDirty = true; }
}
let counter = (window.__vsRefCounter || 0);
function refFor(el) {
let r = el.getAttribute('data-vs-ref');
if (r) return parseInt(r, 10);
counter += 1;
el.setAttribute('data-vs-ref', String(counter));
return counter;
}
function visit(el) {
const role = roleFor(el);
const chal = challengeFor(el);
const children = [];
for (const c of el.children) {
const node = visit(c);
if (node) children.push(node);
}
// Pierce open shadow roots. Cookie consent layers (OneTrust,
// Cookiebot, Sourcepoint) and most web-component-based UIs put
// their actual buttons inside a shadow root, which the walker
// above would otherwise miss entirely.
if (el.shadowRoot) {
for (const c of el.shadowRoot.children) {
const node = visit(c);
if (node) children.push(node);
}
}
// Same-origin frames: their content becomes the ifr node's
// children, addressable by ref like anything else. A
// cross-origin frame throws on contentDocument and stays a
// leaf carrying its src.
if (el.tagName === 'IFRAME' || el.tagName === 'FRAME') {
var fdoc = null;
try { fdoc = el.contentDocument; } catch (e) { fdoc = null; }
if (fdoc && fdoc.body) {
watchFrame(fdoc);
for (const c of fdoc.body.children) {
const node = visit(c);
if (node) children.push(node);
}
}
}
// A challenge node is always kept, even when it is a roleless
// childless div — dropping it is exactly the bug.
if (!chal && !role && children.length === 0) return null;
if (!chal && !role && children.length === 1) return children[0];
const node = {
// Always allocate a real (non-zero) ref, even for roleless
// structural wrappers kept only to preserve tree shape.
// Ref 0 is the delta grammar's ROOT sentinel, so emitting it
// for a real node makes +/@ parent references ambiguous.
r: refFor(el),
role: role || 'el',
label: labelFor(el, role || 'el'),
children,
};
if (chal) {
node.chal = chal.provider + ':' + chal.state;
// Hand the agent the widget's rect so it can aim
// `vs click-at` at the checkbox without measuring first.
if (chal.box) node.chalbox = chal.box.join(',');
// Implicit rendering matches twice — once on the
// `.cf-turnstile` container, once on the response input
// inside it. Keep the outermost and clear the rest, so a
// page reports one challenge rather than two.
(function clearInner(kids) {
for (var i = 0; i < kids.length; i += 1) {
if (kids[i].chal) delete kids[i].chal;
if (kids[i].children) clearInner(kids[i].children);
}
})(children);
// Override the label: the response field would otherwise
// read as an anonymous masked input, which is what made
// this invisible in the first place.
node.label = chal.provider + ' challenge (' + chal.state + ')';
// Never mark a challenge hidden. It is legitimately
// zero-size when unrendered, and `hid=1` reads as "dead
// element, ignore it" — the opposite of what we mean.
return node;
}
if (role && hiddenFor(el, role)) node.hid = 1;
// Heading level and checked state, so a test can ask for an h1
// or assert a checkbox without a separate eval.
if (role === 'hd') {
var lvl = Number(el.getAttribute('aria-level')) ||
(/^H[1-6]$/.test(el.tagName) ? Number(el.tagName[1]) : 0);
if (lvl) node.lvl = lvl;
} else if (role === 'chk' || role === 'rad') {
var ac = el.getAttribute('aria-checked');
if (el.checked === true || ac === 'true') node.chk = 1;
}
// A form field's label is its value (what was typed), so the
// <label> text rides separately as `lbl=`.
if (FIELD_ROLES.has(role)) {
var named = fieldLabel(el);
if (named) node.flbl = named;
}
return node;
}
const docRef = refFor(document.documentElement);
const root = {
r: docRef,
role: 'doc',
label: document.title || '',
children: [],
};
const body = document.body;
if (body) {
for (const c of body.children) {
const n = visit(c);
if (n) root.children.push(n);
}
}
window.__vsRefCounter = counter;
// Shadow-piercing ref lookup used by act / wait / inspect helpers.
// Reinstalled on every walk so the closure picks up new shadow
// roots that appeared between snapshots.
window.__vsFindRef = function(r) {
const sel = '[data-vs-ref="' + String(r) + '"]';
function walk(root) {
const direct = root.querySelector(sel);
if (direct) return direct;
for (const el of root.querySelectorAll('*')) {
if (el.shadowRoot) {
const found = walk(el.shadowRoot);
if (found) return found;
}
if (el.tagName === 'IFRAME' || el.tagName === 'FRAME') {
let d = null;
try { d = el.contentDocument; } catch (e) { d = null; }
if (d) {
const found = walk(d);
if (found) return found;
}
}
}
return null;
}
return walk(document);
};
// An element's rect in the top viewport: a rect read inside a
// frame is relative to that frame, so add each enclosing frame's
// position and border.
window.__vsTopRect = function (el) {
const r = el.getBoundingClientRect();
let x = r.left, y = r.top;
let w = el.ownerDocument && el.ownerDocument.defaultView;
while (w && w !== window && w.frameElement) {
const f = w.frameElement;
const fr = f.getBoundingClientRect();
x += fr.left + f.clientLeft;
y += fr.top + f.clientTop;
w = f.ownerDocument.defaultView;
}
return { x: x, y: y, width: r.width, height: r.height };
};
// Labels are capped with slice(), which can cut an emoji between
// its two UTF-16 halves, and pages can carry lone surrogates too.
// JSON.stringify escapes a lone one as `\udXXX`, which serde_json
// rejects, failing the whole view. Swap any lone surrogate for
// U+FFFD.
function wellFormed(s) {
if (!/[\ud800-\udfff]/.test(s)) return s;
var out = '';
for (var i = 0; i < s.length; i++) {
var c = s.charCodeAt(i);
if (c >= 0xd800 && c <= 0xdbff) {
var d = s.charCodeAt(i + 1);
if (d >= 0xdc00 && d <= 0xdfff) { out += s[i] + s[i + 1]; i++; continue; }
out += '�';
} else if (c >= 0xdc00 && c <= 0xdfff) {
out += '�';
} else {
out += s[i];
}
}
return out;
}
var __vsResult = JSON.stringify(root, function (_k, v) {
return typeof v === 'string' ? wellFormed(v) : v;
});
window.__vsLastResult = __vsResult;
window.__vsDirty = false;
// The walker's globals are created here, after the download shim's
// document-start pass has already run, so re-hide them. Without
// this `Object.keys(window)` lists vibesurfer's snapshot cache and
// ref counter to the page.
if (typeof window.__vsHideGlobals === 'function') {
window.__vsHideGlobals([
'__vsDirty', '__vsDirtyObserver', '__vsRefCounter',
'__vsFindRef', '__vsLastResult', '__vsTopRect',
]);
}
return __vsResult;
})()