@nostop/page 0.0.0-stage → 0.1.0-rc.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,2922 @@
1
+ //#region ../page-controller/src/ax/vendor/ax-core.js
2
+ function reconstructAXTree(root = document, options = {}) {
3
+ let serial = 0;
4
+ const nodes = [];
5
+ const lineBreakingIgnoredElements = /* @__PURE__ */ new Set();
6
+ const unresolvedRelations = [];
7
+ const byPath = /* @__PURE__ */ new Map();
8
+ const elementsById = /* @__PURE__ */ new Map();
9
+ const textsById = /* @__PURE__ */ new Map();
10
+ const idFor = () => `h${++serial}`;
11
+ const norm = (s) => String(s ?? "").replace(/[\t\n\f\r ]+/g, " ").replace(/^ +| +$/g, "");
12
+ const simplifyName = (s) => String(s ?? "").replace(/[\t\n\f\r ]+/g, " ");
13
+ const hiddenStyle = (el) => {
14
+ const cs = getComputedStyle(el);
15
+ return cs.display === "none" || cs.visibility === "hidden" || cs.visibility === "collapse" || cs.contentVisibility === "hidden";
16
+ };
17
+ const composedParent = (el) => el.assignedSlot || el.parentElement || el.getRootNode()?.host || null;
18
+ const editableStyle = (el) => {
19
+ const modify = getComputedStyle(el).webkitUserModify;
20
+ if (modify === "read-write-plaintext-only") return "plaintext";
21
+ if (modify === "read-write") return el.localName === "br" ? "plaintext" : "richtext";
22
+ };
23
+ const ancestorMatches = (el, predicate) => {
24
+ for (let current = el; current; current = composedParent(current)) if (predicate(current)) return true;
25
+ return false;
26
+ };
27
+ let focused = root.activeElement;
28
+ while (focused?.shadowRoot?.activeElement) focused = focused.shadowRoot.activeElement;
29
+ const focusedHiddenAncestors = /* @__PURE__ */ new Set();
30
+ for (let current = focused; current; current = composedParent(current)) if (current.getAttribute("aria-hidden") === "true") focusedHiddenAncestors.add(current);
31
+ const ariaHidden = (el) => ancestorMatches(el, (e) => e !== root.documentElement && e !== root.body && e.localName !== "option" && e.getAttribute("aria-hidden") === "true" && !focusedHiddenAncestors.has(e));
32
+ const inert = (el) => ancestorMatches(el, (e) => e.inert || e.hasAttribute("inert"));
33
+ const isHidden = (el) => ariaHidden(el) || inert(el) || hiddenStyle(el) || ancestorMatches(el, (e) => {
34
+ const style = getComputedStyle(e);
35
+ return style.display === "none" || style.contentVisibility === "hidden";
36
+ });
37
+ const hiddenReason = (el, isText) => {
38
+ if (ariaHidden(el)) return !isText && el.getAttribute("aria-hidden") === "true" ? "ariaHiddenElement" : "ariaHiddenSubtree";
39
+ if (ancestorMatches(el, (e) => getComputedStyle(e).display === "none")) return "notRendered";
40
+ if (inert(el)) return "inertElement";
41
+ if (ancestorMatches(el, (e) => {
42
+ const style = getComputedStyle(e);
43
+ return style.display === "none" || style.contentVisibility === "hidden";
44
+ })) return "notRendered";
45
+ if (["hidden", "collapse"].includes(getComputedStyle(el).visibility)) return "notVisible";
46
+ return "notRendered";
47
+ };
48
+ const siblingIndexes = /* @__PURE__ */ new WeakMap();
49
+ const paths = /* @__PURE__ */ new WeakMap();
50
+ const pathOf = (node) => {
51
+ if (paths.has(node)) return paths.get(node);
52
+ const parts = [];
53
+ let n = node;
54
+ while (n && n !== root) {
55
+ if (n.nodeType === Node.ELEMENT_NODE || n.nodeType === Node.TEXT_NODE) {
56
+ const parent = n.parentNode;
57
+ let indexes = parent && siblingIndexes.get(parent);
58
+ if (parent && !indexes) {
59
+ indexes = /* @__PURE__ */ new WeakMap();
60
+ let i = 0;
61
+ for (const child of parent.childNodes) indexes.set(child, i++);
62
+ siblingIndexes.set(parent, indexes);
63
+ }
64
+ const i = indexes?.get(n) ?? 0;
65
+ parts.push(n.nodeType === Node.TEXT_NODE ? `#text[${i}]` : `${n.localName}[${i}]`);
66
+ } else if (n.nodeType === Node.DOCUMENT_FRAGMENT_NODE && n.host) parts.push("#shadow-root[0]");
67
+ n = n.parentNode || n.host;
68
+ }
69
+ const path = parts.reverse().join("/");
70
+ paths.set(node, path);
71
+ return path;
72
+ };
73
+ const descendants = (el) => {
74
+ if (el.nodeType === Node.TEXT_NODE) return [];
75
+ if (el.localName === "slot") {
76
+ const assigned = el.assignedNodes({ flatten: true });
77
+ if (assigned.length) return assigned;
78
+ }
79
+ if (el.shadowRoot?.mode === "open") return [...el.shadowRoot.childNodes];
80
+ return [...el.childNodes];
81
+ };
82
+ const resolveId = (el, id) => el.getRootNode()?.getElementById?.(id) || null;
83
+ const referenceTargets = (el, attr) => {
84
+ const raw = el.getAttribute(attr);
85
+ if (raw) return raw.split(/[\t\n\f\r ]+/).map((id) => id && resolveId(el, id)).filter(Boolean);
86
+ const property = attr === "aria-labelledby" ? "ariaLabelledByElements" : attr === "aria-describedby" ? "ariaDescribedByElements" : null;
87
+ return property && el[property] ? [...el[property]] : [];
88
+ };
89
+ const transformText = (text, el) => {
90
+ if (!el || isHidden(el)) return text;
91
+ const transform = getComputedStyle(el).textTransform;
92
+ if (transform !== "uppercase" && transform !== "lowercase") return text;
93
+ let language;
94
+ for (let e = el; e; e = composedParent(e)) if (e.hasAttribute("lang")) {
95
+ language = e.getAttribute("lang") || void 0;
96
+ break;
97
+ }
98
+ try {
99
+ return transform === "uppercase" ? text.toLocaleUpperCase(language) : text.toLocaleLowerCase(language);
100
+ } catch {
101
+ return transform === "uppercase" ? text.toUpperCase() : text.toLowerCase();
102
+ }
103
+ };
104
+ const labelledByAttribute = (el) => el.hasAttribute("aria-labelledby") ? "aria-labelledby" : "aria-labeledby";
105
+ const visibleCaption = (el) => [...el.children].find((child) => child.localName === "caption" && !isHidden(child));
106
+ const generatedText = (el, pseudo) => {
107
+ if (isHidden(el)) return "";
108
+ const style = getComputedStyle(el, pseudo), value = style.content;
109
+ if (style.display === "none" || ["hidden", "collapse"].includes(style.visibility)) return "";
110
+ let quote = false, escaped = false, depth = 0, separator = -1;
111
+ for (let i = 0; i < value.length; i++) {
112
+ const c = value[i];
113
+ if (quote) {
114
+ if (escaped) escaped = false;
115
+ else if (c === "\\") escaped = true;
116
+ else if (c === "\"") quote = false;
117
+ continue;
118
+ }
119
+ if (c === "\"") quote = true;
120
+ else if (c === "(") depth++;
121
+ else if (c === ")") depth--;
122
+ else if (c === "/" && depth === 0) {
123
+ separator = i;
124
+ break;
125
+ }
126
+ }
127
+ const text = (separator < 0 ? value : value.slice(separator + 1)).trim();
128
+ const token = /"(?:[^"\\\n\r\f]|\\(?:[0-9a-fA-F]{1,6}(?:\r\n|[ \t\n\r\f])?|[^\n\r\f]))*"/y;
129
+ let index = 0, result = "";
130
+ while (index < text.length) {
131
+ while (/\s/.test(text[index] || "") && index < text.length) index++;
132
+ if (index === text.length) break;
133
+ token.lastIndex = index;
134
+ const match = token.exec(text);
135
+ if (!match) return "";
136
+ result += match[0].slice(1, -1).replace(/\\(?:([0-9a-fA-F]{1,6})(?:\r\n|[ \t\n\r\f])?|([^\n\r\f]))/g, (_, hex, character) => {
137
+ if (hex === void 0) return character;
138
+ const code = parseInt(hex, 16);
139
+ return String.fromCodePoint(!code || code > 1114111 || code >= 55296 && code <= 57343 ? 65533 : code);
140
+ });
141
+ index = token.lastIndex;
142
+ }
143
+ if (separator >= 0 || style.textTransform === "none") return result;
144
+ if (!["uppercase", "lowercase"].includes(style.textTransform)) return "";
145
+ let language;
146
+ for (let e = el; e; e = composedParent(e)) if (e.hasAttribute("lang")) {
147
+ language = e.getAttribute("lang") || void 0;
148
+ break;
149
+ }
150
+ try {
151
+ return style.textTransform === "uppercase" ? result.toLocaleUpperCase(language) : result.toLocaleLowerCase(language);
152
+ } catch {
153
+ return style.textTransform === "uppercase" ? result.toUpperCase() : result.toLowerCase();
154
+ }
155
+ };
156
+ const textAlternative = (el, seen = /* @__PURE__ */ new Set(), inReference = false, includeHidden = false, inLabel = false) => {
157
+ if (!el || seen.has(el)) return "";
158
+ const topLevelContent = !inReference && seen.size === 0;
159
+ const suppressInertContents = inReference && seen.size === 0 && inert(el) && !ariaHidden(el) && !hiddenStyle(el) && !ancestorMatches(el, (e) => {
160
+ const style = getComputedStyle(e);
161
+ return style.display === "none" || style.contentVisibility === "hidden";
162
+ });
163
+ seen.add(el);
164
+ if (inLabel) {
165
+ const embeddedRole = explicitRole(el), type = el.localName === "input" ? el.type : "";
166
+ if (el.localName === "select") return norm([...el.selectedOptions].map((option) => option.getAttribute("aria-label") || option.text).join(" "));
167
+ if ([
168
+ "slider",
169
+ "spinbutton",
170
+ "scrollbar"
171
+ ].includes(embeddedRole) || type === "range" || type === "number") return norm(el.getAttribute("aria-valuetext") ?? el.getAttribute("aria-valuenow") ?? el.value ?? "");
172
+ if (type === "password") return norm(value(el, "textbox") ?? "");
173
+ if (embeddedRole === "textbox") return norm("value" in el ? el.value : el.textContent);
174
+ if (el.localName === "textarea" || el.localName === "input" && ![
175
+ "checkbox",
176
+ "radio",
177
+ "button",
178
+ "submit",
179
+ "reset",
180
+ "image",
181
+ "hidden",
182
+ "file"
183
+ ].includes(type)) return norm(el.value);
184
+ }
185
+ if (el.localName === "slot") return norm(descendants(el).map((n) => n.nodeType === Node.TEXT_NODE ? transformText(n.nodeValue, n.parentElement) : n.nodeType === Node.ELEMENT_NODE && (includeHidden || !isHidden(n)) ? textAlternative(n, seen, inReference, includeHidden, inLabel) : "").join(" "));
186
+ const labelled = referenceTargets(el, labelledByAttribute(el));
187
+ if (labelled.length && !inReference) {
188
+ const widgetOwner = [
189
+ "button",
190
+ "input",
191
+ "select",
192
+ "textarea"
193
+ ].includes(el.localName) || (/* @__PURE__ */ new Set([
194
+ "button",
195
+ "checkbox",
196
+ "combobox",
197
+ "listbox",
198
+ "menuitem",
199
+ "menuitemcheckbox",
200
+ "menuitemradio",
201
+ "option",
202
+ "radio",
203
+ "searchbox",
204
+ "slider",
205
+ "spinbutton",
206
+ "switch",
207
+ "tab",
208
+ "textbox",
209
+ "treeitem"
210
+ ])).has(explicitRole(el));
211
+ const value = labelled.map((target) => {
212
+ const hidden = isHidden(target), text = textAlternative(target, /* @__PURE__ */ new Set(), true, hidden, widgetOwner);
213
+ const child = target.childNodes.length === 1 ? target.firstChild : null;
214
+ if (!text || target.hasAttribute("aria-label") || child?.nodeType !== Node.TEXT_NODE || norm(child.data) !== norm(text)) return text;
215
+ const boundary = (leading) => {
216
+ const run = leading ? child.data.match(/^[\t\n\f\r ]+/)?.[0] : child.data.match(/[\t\n\f\r ]+$/)?.[0];
217
+ if (!run) return false;
218
+ if (hidden) return true;
219
+ const range = child.ownerDocument.createRange();
220
+ range.setStart(child, leading ? 0 : child.length - run.length);
221
+ range.setEnd(child, leading ? run.length : child.length);
222
+ return [...range.getClientRects()].some((rect) => rect.width > 0);
223
+ };
224
+ return (boundary(true) ? " " : "") + norm(text) + (boundary(false) ? " " : "");
225
+ }).filter((text) => text !== "").join(" ");
226
+ if (norm(value)) return simplifyName(value);
227
+ }
228
+ const label = el.getAttribute("aria-label");
229
+ if (label != null && norm(label)) return inReference ? simplifyName(label) : norm(label);
230
+ if (el.localName === "button" && el.labels?.length) {
231
+ const labelText = [...el.labels].map((item) => textAlternative(item, /* @__PURE__ */ new Set([el]), false, includeHidden, true)).join(" ");
232
+ if (norm(labelText)) return norm(labelText);
233
+ }
234
+ if (el.localName === "optgroup") return norm(el.getAttribute("label") || "") || norm([...el.children].find((child) => child.localName === "legend")?.textContent || "");
235
+ if (el.localName === "fieldset") {
236
+ const legend = [...el.children].find((child) => child.localName === "legend");
237
+ const legendName = legend && !isHidden(legend) ? textAlternative(legend, seen, inReference, includeHidden) : "";
238
+ if (legendName || !inReference) return legendName;
239
+ }
240
+ if (el.localName === "img" || el.localName === "area") {
241
+ if (el.hasAttribute("alt")) return norm(el.getAttribute("alt"));
242
+ }
243
+ if (el.localName === "iframe" || el.localName === "frame") return norm(el.getAttribute("title"));
244
+ if (el.localName === "table") {
245
+ const caption = visibleCaption(el);
246
+ if (caption) {
247
+ const captionName = textAlternative(caption, new Set(seen), false, includeHidden);
248
+ if (captionName || !inReference) return captionName;
249
+ } else {
250
+ const summary = norm(el.getAttribute("summary") || "");
251
+ if (summary || !inReference) return summary;
252
+ }
253
+ }
254
+ if (el.localName === "input" && [
255
+ "button",
256
+ "submit",
257
+ "reset"
258
+ ].includes(el.type) && el.value) return norm(el.value);
259
+ if (el.localName === "input" || el.localName === "textarea" || el.localName === "select") {
260
+ const labels = el.labels ? [...el.labels].map((x) => textAlternative(x, /* @__PURE__ */ new Set([el]), false, false, true)).join(" ") : "";
261
+ if (norm(labels)) return norm(labels);
262
+ if (norm(el.getAttribute("title"))) return norm(el.getAttribute("title"));
263
+ if (el.localName === "select" && !inReference) return "";
264
+ const placeholder = el.getAttribute("placeholder") || el.getAttribute("aria-placeholder");
265
+ if (norm(placeholder)) return norm(placeholder);
266
+ }
267
+ if (el.localName === "button" || el.localName === "a" || /^h[1-6]$/.test(el.localName)) {
268
+ const title = el.getAttribute("title");
269
+ if (norm(title) && !norm(el.textContent)) return norm(title);
270
+ }
271
+ if (suppressInertContents) return "";
272
+ if (!inReference && seen.size > 1 && explicitRole(el) === "group") return norm(el.getAttribute("title"));
273
+ const content = generatedText(el, "::before") + descendants(el).map((n) => n.nodeType === Node.TEXT_NODE ? transformText(n.nodeValue, n.parentElement) : n.nodeType === Node.ELEMENT_NODE && (includeHidden || !isHidden(n)) ? textAlternative(n, seen, inReference, includeHidden, inLabel) : "").join(" ") + generatedText(el, "::after");
274
+ const normalized = norm(content);
275
+ if (inReference && !normalized && (el.getAttribute("title") || "").trim() !== (el.innerText || "").trim()) return norm(el.getAttribute("title"));
276
+ if (topLevelContent && normalized && ["normal", "nowrap"].includes(getComputedStyle(el).whiteSpace)) {
277
+ const children = descendants(el);
278
+ const emptyGroup = (node) => node?.nodeType === Node.ELEMENT_NODE && explicitRole(node) === "group" && !isHidden(node) && !norm(node.getAttribute("aria-label")) && !norm(node.getAttribute("aria-labelledby")) && !norm(node.getAttribute("title"));
279
+ const visibleSpace = (node, leading) => {
280
+ if (node?.nodeType !== Node.TEXT_NODE) return false;
281
+ const whitespace = leading ? node.data.match(/^[\t\n\f\r ]+/)?.[0] : node.data.match(/[\t\n\f\r ]+$/)?.[0];
282
+ if (!whitespace) return false;
283
+ const range = node.ownerDocument.createRange();
284
+ range.setStart(node, leading ? 0 : node.length - whitespace.length);
285
+ range.setEnd(node, leading ? whitespace.length : node.length);
286
+ return [...range.getClientRects()].some((rect) => rect.width > 0);
287
+ };
288
+ const first = children[0], last = children[children.length - 1];
289
+ const leading = emptyGroup(first) && visibleSpace(children[1], true);
290
+ let tailIndex = children.length - 1;
291
+ while (tailIndex >= 0 && children[tailIndex].nodeType === Node.TEXT_NODE && !norm(children[tailIndex].data) && !visibleSpace(children[tailIndex], false)) tailIndex--;
292
+ const tail = children[tailIndex];
293
+ const decorativeTail = tail?.nodeType === Node.ELEMENT_NODE && [
294
+ "inline-block",
295
+ "inline-flex",
296
+ "inline-grid"
297
+ ].includes(getComputedStyle(tail).display) && !norm(tail.textContent) && !norm(tail.getAttribute("aria-label")) && !norm(tail.getAttribute("title")) && !norm(tail.getAttribute("aria-labelledby")) && !generatedText(tail, "::before") && !generatedText(tail, "::after");
298
+ const preceding = decorativeTail ? children.slice(0, tailIndex).reverse().find((node) => node.nodeType === Node.ELEMENT_NODE || node.nodeType === Node.TEXT_NODE && norm(node.data)) : null;
299
+ let lastText = preceding?.nodeType === Node.ELEMENT_NODE ? preceding : null;
300
+ while (lastText?.nodeType === Node.ELEMENT_NODE) lastText = lastText.lastChild;
301
+ const trailing = emptyGroup(last) && visibleSpace(children[children.length - 2], false) || decorativeTail && visibleSpace(lastText, false);
302
+ return (leading ? " " : "") + normalized + (trailing ? " " : "");
303
+ }
304
+ return normalized;
305
+ };
306
+ const hasAriaName = (el) => !!norm(el.getAttribute("aria-label")) || referenceTargets(el, labelledByAttribute(el)).some((target) => norm(textAlternative(target, /* @__PURE__ */ new Set(), true, isHidden(target))));
307
+ const description = (el, computedName, computedRole) => {
308
+ const targets = referenceTargets(el, "aria-describedby");
309
+ if (targets.length) return norm(targets.map((target) => textAlternative(target, /* @__PURE__ */ new Set(), true, isHidden(target))).join(" "));
310
+ if (el.hasAttribute("aria-description")) return norm(el.getAttribute("aria-description"));
311
+ if (el.localName === "table" && hasAriaName(el)) {
312
+ const caption = visibleCaption(el);
313
+ if (caption) return textAlternative(caption);
314
+ }
315
+ const title = el.getAttribute("title");
316
+ if (norm(title)) {
317
+ const nativeLabels = el.labels ? [...el.labels].some((label) => !!norm(textAlternative(label, /* @__PURE__ */ new Set([el])))) : false;
318
+ if (!(computedName === norm(title) && !hasAriaName(el) && !nativeLabels && ([
319
+ "input",
320
+ "textarea",
321
+ "select",
322
+ "iframe",
323
+ "frame"
324
+ ].includes(el.localName) || [
325
+ "region",
326
+ "complementary",
327
+ "article",
328
+ "group",
329
+ "listbox",
330
+ "Abbr"
331
+ ].includes(computedRole) || (["button", "a"].includes(el.localName) || /^h[1-6]$/.test(el.localName)) && !norm(el.textContent))) && title.trim() !== (el.innerText || "").trim()) return norm(title);
332
+ }
333
+ return "";
334
+ };
335
+ const knownRoles = new Set("alert alertdialog application article banner blockquote button caption cell checkbox code columnheader combobox complementary contentinfo definition deletion dialog directory document emphasis feed figure form generic grid gridcell group heading img insertion link list listbox listitem log main marquee math menu menubar menuitem menuitemcheckbox menuitemradio meter navigation none note option paragraph presentation progressbar radio radiogroup region row rowgroup rowheader scrollbar search searchbox separator slider spinbutton status strong subscript superscript switch tab table tablist tabpanel term textbox time timer toolbar tooltip tree treegrid treeitem".split(" "));
336
+ const explicitRole = (el) => (el.getAttribute("role") || "").replace(/[A-Z]/g, (c) => c.toLowerCase()).split(/[\u0009-\u000d \u1680\u2000-\u200a\u2028\u205f\u3000]+/).find((token) => knownRoles.has(token)) || "";
337
+ const hasAuthorName = (el) => !!norm(el.getAttribute("aria-label")) || referenceTargets(el, labelledByAttribute(el)).length > 0 || el.hasAttribute("title");
338
+ const inSectioningAncestor = (el, includeMain) => {
339
+ for (let parent = composedParent(el); parent; parent = composedParent(parent)) {
340
+ const explicit = explicitRole(parent), tag = parent.localName;
341
+ if ([
342
+ "article",
343
+ "complementary",
344
+ "navigation",
345
+ "region"
346
+ ].includes(explicit) || includeMain && explicit === "main") return true;
347
+ if (!explicit && ([
348
+ "article",
349
+ "aside",
350
+ "nav",
351
+ "section"
352
+ ].includes(tag) || includeMain && tag === "main")) return true;
353
+ }
354
+ return false;
355
+ };
356
+ const tableLayoutCache = /* @__PURE__ */ new WeakMap();
357
+ const isLayoutTable = (table) => {
358
+ if (!table || table.localName !== "table") return false;
359
+ if (tableLayoutCache.has(table)) return tableLayoutCache.get(table);
360
+ const calculate = () => {
361
+ if (isHidden(table) || table.hasAttribute("role") || table.isContentEditable || editableStyle(table)) return false;
362
+ if (table.getAttribute("summary") || table.getAttribute("rules") || table.caption || table.tHead || table.tFoot || [...table.children].some((child) => ["col", "colgroup"].includes(child.localName))) return false;
363
+ const rows = [...table.rows];
364
+ if (rows.length >= 20) return false;
365
+ if (rows.length === 0 || rows.length === 1 && rows[0].cells.length === 1) return true;
366
+ const tableStyle = getComputedStyle(table);
367
+ if (tableStyle.transform !== "none") return false;
368
+ const spacing = tableStyle.borderSpacing.split(/\s+/).map(parseFloat);
369
+ const hasSpacing = spacing[0] > 0 && (spacing[1] ?? spacing[0]) > 0;
370
+ let valid = 0, colored = 0, bordered = 0;
371
+ const sides = [
372
+ 0,
373
+ 0,
374
+ 0,
375
+ 0
376
+ ], rowColors = [];
377
+ for (let rowIndex = 0; rowIndex < rows.length; rowIndex++) for (const cell of rows[rowIndex].cells) {
378
+ if (cell.localName === "th" || [
379
+ "headers",
380
+ "abbr",
381
+ "axis",
382
+ "scope"
383
+ ].some((attr) => !!cell.getAttribute(attr))) return false;
384
+ const style = getComputedStyle(cell);
385
+ if (style.transform !== "none") return false;
386
+ if (style.display !== "table-cell") continue;
387
+ const rect = cell.getBoundingClientRect();
388
+ if (rect.width < 1 || rect.height < 1) continue;
389
+ valid++;
390
+ if (style.emptyCells === "hide") return false;
391
+ const borders = [
392
+ "Top",
393
+ "Bottom",
394
+ "Left",
395
+ "Right"
396
+ ].map((side) => parseFloat(style[`border${side}Width`]) > 0);
397
+ for (const [index, present] of borders.entries()) if (present) sides[index]++;
398
+ if (borders[0] && borders[1] || borders[2] && borders[3]) bordered++;
399
+ const color = style.backgroundColor;
400
+ if (!/^rgba?\(/.test(color)) return false;
401
+ const transparent = /^rgba\([^)]*,\s*0(?:\.0+)?\)$/.test(color);
402
+ if (hasSpacing && !transparent && color !== tableStyle.backgroundColor) colored++;
403
+ if (rowIndex < 5 && rowIndex === rowColors.length) rowColors.push(getComputedStyle(rows[rowIndex]).backgroundColor);
404
+ }
405
+ if (valid <= 1) return true;
406
+ const needed = Math.floor(valid / 2);
407
+ if (bordered >= needed || sides.some((count) => count >= needed) || colored >= needed) return false;
408
+ if (rowColors.length > 2 && rowColors.every((color, index) => index === 0 || (index % 2 ? color !== rowColors[0] : color === rowColors[0]))) return false;
409
+ return true;
410
+ };
411
+ const result = calculate();
412
+ tableLayoutCache.set(table, result);
413
+ return result;
414
+ };
415
+ const directHtmlRoles = {
416
+ button: "button",
417
+ hr: "separator",
418
+ fieldset: "group",
419
+ optgroup: "group",
420
+ option: "option",
421
+ img: "image",
422
+ p: "paragraph",
423
+ nav: "navigation",
424
+ main: "main",
425
+ article: "article",
426
+ ul: "list",
427
+ ol: "list",
428
+ menu: "list",
429
+ li: "listitem",
430
+ caption: "caption",
431
+ textarea: "textbox",
432
+ meter: "meter",
433
+ progress: "progressbar",
434
+ blockquote: "blockquote",
435
+ dl: "DescriptionList",
436
+ dt: "term",
437
+ dd: "definition",
438
+ output: "status",
439
+ details: "group",
440
+ figure: "figure",
441
+ figcaption: "Figcaption",
442
+ dialog: "dialog",
443
+ address: "group"
444
+ };
445
+ const implicitRole = (el) => {
446
+ const n = el.localName;
447
+ const type = el.type;
448
+ if (el.namespaceURI === "http://www.w3.org/2000/svg" && n === "foreignObject") return "group";
449
+ if (el.namespaceURI === "http://www.w3.org/2000/svg" && n === "svg") {
450
+ if (el.parentElement?.closest("svg")) return "group";
451
+ return [...el.querySelectorAll("svg, text, [role], [aria-label], [aria-labelledby], [tabindex], a[href], button, input, select, textarea")].some((child) => !isHidden(child) && !["none", "presentation"].includes(explicitRole(child)) && (child.localName !== "svg" || hasAuthorName(child) || child.querySelector("[role], [aria-label], [aria-labelledby], [tabindex], text, button, input, select, textarea"))) ? "SvgRoot" : "image";
452
+ }
453
+ if (el.namespaceURI === "http://www.w3.org/1999/xhtml") {
454
+ const semanticRoles = {
455
+ strong: "strong",
456
+ em: "emphasis",
457
+ code: "code",
458
+ del: "deletion",
459
+ s: "deletion",
460
+ ins: "insertion",
461
+ sub: "subscript",
462
+ sup: "superscript",
463
+ mark: "mark",
464
+ search: "search",
465
+ time: "time",
466
+ abbr: "Abbr"
467
+ };
468
+ if (Object.hasOwn(semanticRoles, n)) return semanticRoles[n];
469
+ }
470
+ if (n === "html" || n === "head" || n === "body") return "none";
471
+ if (n === "a" && el.hasAttribute("href")) return "link";
472
+ if (n === "summary" && el.parentElement?.localName === "details") return el.parentElement.getAttribute("name") ? "DisclosureTriangleGrouped" : "DisclosureTriangle";
473
+ if (Object.hasOwn(directHtmlRoles, n)) return directHtmlRoles[n];
474
+ if (n === "iframe" || n === "frame") return "Iframe";
475
+ if (n === "br") return "LineBreak";
476
+ if (n === "label") return "LabelText";
477
+ if (n === "legend") return "Legend";
478
+ if (n === "h1" || n === "h2" || n === "h3" || n === "h4" || n === "h5" || n === "h6") return "heading";
479
+ if (n === "header") return inSectioningAncestor(el, true) ? "sectionheader" : "banner";
480
+ if (n === "footer") return inSectioningAncestor(el, true) ? "sectionfooter" : "contentinfo";
481
+ if (n === "section") return hasAuthorName(el) ? "region" : "generic";
482
+ if (n === "aside") return !inSectioningAncestor(el, false) || hasAuthorName(el) ? "complementary" : "generic";
483
+ if (n === "form") return "form";
484
+ if (n === "table") return isLayoutTable(el) ? "LayoutTable" : "table";
485
+ if (n === "thead" || n === "tfoot" || n === "tbody" && el.closest("table")) return "rowgroup";
486
+ if (n === "tr") return isLayoutTable(el.closest("table")) ? "LayoutTableRow" : "row";
487
+ if (n === "td") return isLayoutTable(el.closest("table")) ? "LayoutTableCell" : "cell";
488
+ if (n === "th") {
489
+ if (isLayoutTable(el.closest("table"))) return "LayoutTableCell";
490
+ const scope = el.getAttribute("scope")?.toLowerCase();
491
+ if (scope === "row" || scope === "rowgroup") return "rowheader";
492
+ if (scope === "col" || scope === "colgroup") return "columnheader";
493
+ return [...el.parentElement?.children || []].some((s) => s.localName === "td" && s.textContent.trim()) ? "rowheader" : "columnheader";
494
+ }
495
+ if (n === "select") return el.multiple || el.size > 1 ? "listbox" : "combobox";
496
+ if (n === "input") {
497
+ if ([
498
+ "button",
499
+ "submit",
500
+ "reset",
501
+ "image"
502
+ ].includes(type)) return "button";
503
+ return {
504
+ checkbox: "checkbox",
505
+ radio: "radio",
506
+ range: "slider",
507
+ number: "spinbutton",
508
+ search: "searchbox",
509
+ email: "textbox",
510
+ text: "textbox",
511
+ password: "textbox",
512
+ url: "textbox"
513
+ }[type] || "textbox";
514
+ }
515
+ if (!el.hasAttribute("role") && el.popover) return "group";
516
+ return "generic";
517
+ };
518
+ const presentationUndoAria = new Set("aria-atomic aria-braillelabel aria-brailleroledescription aria-busy aria-controls aria-current aria-describedby aria-description aria-details aria-flowto aria-keyshortcuts aria-label aria-labeledby aria-labelledby aria-live aria-owns aria-relevant aria-roledescription".split(" "));
519
+ const role = (el) => {
520
+ const explicit = explicitRole(el);
521
+ if (["presentation", "none"].includes(explicit)) {
522
+ const focusable = !el.matches(":disabled") && (el.tabIndex >= 0 || el.hasAttribute("tabindex") || el.isContentEditable);
523
+ const globalAria = !el.localName.includes("-") && [...el.attributes].some((a) => presentationUndoAria.has(a.name));
524
+ if (focusable || globalAria) return implicitRole(el);
525
+ }
526
+ return explicit === "img" ? "image" : explicit || implicitRole(el);
527
+ };
528
+ const rangeInfo = (el, r) => {
529
+ if (![
530
+ "slider",
531
+ "spinbutton",
532
+ "meter",
533
+ "progressbar",
534
+ "scrollbar"
535
+ ].includes(r)) return null;
536
+ const numberAttr = (name) => {
537
+ const raw = el.getAttribute(name);
538
+ if (raw === null) return void 0;
539
+ const s = raw.trim();
540
+ const n = /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/.test(s) ? Number(s) : NaN;
541
+ return Number.isFinite(n) ? Math.fround(n) : name.startsWith("aria-") ? 0 : void 0;
542
+ };
543
+ const nativeInput = el.localName === "input" && ["number", "range"].includes(el.type);
544
+ const nativeMeter = el.localName === "meter", nativeProgress = el.localName === "progress";
545
+ let min = numberAttr("aria-valuemin"), max = numberAttr("aria-valuemax");
546
+ if (min === void 0) min = nativeInput ? numberAttr("min") : nativeMeter ? Math.fround(el.min) : nativeProgress ? 0 : void 0;
547
+ if (max === void 0) max = nativeInput ? numberAttr("max") : nativeMeter || nativeProgress ? Math.fround(el.max) : void 0;
548
+ if (r === "slider" || r === "scrollbar") {
549
+ if (min === void 0) min = 0;
550
+ if (max === void 0) max = 100;
551
+ }
552
+ if (r === "meter" || r === "progressbar") {
553
+ if (min === void 0) min = 0;
554
+ if (max === void 0) max = 100;
555
+ }
556
+ let now = numberAttr("aria-valuenow");
557
+ if (now !== void 0) {
558
+ if (min !== void 0) now = Math.max(min, now);
559
+ if (max !== void 0) now = Math.min(max, now);
560
+ } else if (nativeInput) now = Number.isFinite(el.valueAsNumber) ? Math.fround(el.valueAsNumber) : void 0;
561
+ else if (nativeMeter) now = Math.fround(el.value);
562
+ else if (nativeProgress) now = el.hasAttribute("value") ? Math.fround(el.value) : void 0;
563
+ else if (r === "slider" || r === "scrollbar") now = Math.fround((min + max) / 2);
564
+ else if (r === "spinbutton") now = 0;
565
+ else if (r === "meter") now = min;
566
+ return {
567
+ min: min ?? 0,
568
+ max: max ?? 0,
569
+ now,
570
+ text: nativeInput ? el.value : ""
571
+ };
572
+ };
573
+ const value = (el, r) => {
574
+ const range = rangeInfo(el, r);
575
+ if (range) return range.now;
576
+ if (el.localName === "select") {
577
+ if (el.multiple || el.size > 1) return void 0;
578
+ const option = el.selectedOptions[0];
579
+ return (option?.getAttribute("aria-label") ?? option?.text ?? "") || void 0;
580
+ }
581
+ if (el.localName === "textarea" || el.localName === "input" && ![
582
+ "checkbox",
583
+ "radio",
584
+ "button",
585
+ "submit",
586
+ "reset",
587
+ "image"
588
+ ].includes(el.type)) {
589
+ if (!el.value) return void 0;
590
+ if (el.type === "password") {
591
+ const mask = {
592
+ disc: "•",
593
+ circle: "◦",
594
+ square: "▪"
595
+ }[getComputedStyle(el).webkitTextSecurity];
596
+ if (mask) return mask.repeat(el.value.length);
597
+ }
598
+ return el.value;
599
+ }
600
+ const explicitEditable = ["true", "plaintext-only"].includes(el.contentEditable);
601
+ const editableRoot = el.isContentEditable && !composedParent(el)?.isContentEditable;
602
+ if (explicitEditable || editableRoot || r === "textbox" && !["input", "textarea"].includes(el.localName)) return el.innerText || void 0;
603
+ };
604
+ const props = (el, r) => {
605
+ const p = {};
606
+ const describedby = el.getAttribute("aria-describedby");
607
+ if (describedby && describedby.split(/[\t\n\f\r ]+/).some((id) => id && resolveId(el, id))) p.describedby = describedby;
608
+ if (r === "link" && ["a", "area"].includes(el.localName) && el.hasAttribute("href") && el.href) p.url = el.href;
609
+ if (r === "image" && el.localName === "img" && el.currentSrc) p.url = el.currentSrc;
610
+ const live = (el.getAttribute("aria-live") || "").trim().toLowerCase() || {
611
+ alert: "assertive",
612
+ status: "polite",
613
+ log: "polite",
614
+ marquee: "off",
615
+ timer: "off"
616
+ }[r];
617
+ if (live && live !== "off") {
618
+ const atomic = (el.getAttribute("aria-atomic") || "").trim().toLowerCase();
619
+ p.live = live;
620
+ p.atomic = atomic === "true" ? true : atomic === "false" ? false : ["alert", "status"].includes(r);
621
+ p.relevant = (el.getAttribute("aria-relevant") || "").trim().toLowerCase() || "additions text";
622
+ }
623
+ let selectable = [
624
+ "gridcell",
625
+ "option",
626
+ "tab",
627
+ "treeitem"
628
+ ].includes(r);
629
+ if ([
630
+ "cell",
631
+ "columnheader",
632
+ "rowheader",
633
+ "row",
634
+ "column"
635
+ ].includes(r)) for (let parent = composedParent(el); parent; parent = composedParent(parent)) {
636
+ const parentRole = role(parent);
637
+ if ([
638
+ "table",
639
+ "grid",
640
+ "treegrid"
641
+ ].includes(parentRole)) {
642
+ selectable = parentRole !== "table";
643
+ break;
644
+ }
645
+ }
646
+ const selected = el.getAttribute("aria-selected");
647
+ if (selectable && selected !== null && selected !== "" && selected.toLowerCase() !== "undefined") p.selected = selected.toLowerCase() !== "false";
648
+ if (selectable && p.selected === void 0 && el.localName !== "option" && [
649
+ "option",
650
+ "treeitem",
651
+ "tab"
652
+ ].includes(r)) {
653
+ const widgetRoles = [
654
+ "listbox",
655
+ "tree",
656
+ "tablist"
657
+ ];
658
+ const widgetFor = (element) => {
659
+ for (let parent = composedParent(element); parent; parent = composedParent(parent)) if (widgetRoles.includes(role(parent))) return parent;
660
+ return null;
661
+ };
662
+ const widget = widgetFor(el);
663
+ if (!widget && r === "tab") p.selected = false;
664
+ if (widget && {
665
+ option: "listbox",
666
+ treeitem: "tree",
667
+ tab: "tablist"
668
+ }[r] === role(widget)) {
669
+ const multiselect = widget.getAttribute("aria-multiselectable");
670
+ const multiple = multiselect !== null && multiselect !== "" && !["false", "undefined"].includes(multiselect.toLowerCase());
671
+ const explicit = [...widget.querySelectorAll("[role]")].some((item) => {
672
+ const itemRole = role(item);
673
+ return widgetFor(item) === widget && (["option", "treeitem"].includes(itemRole) && (item.hasAttribute("aria-selected") || item.hasAttribute("aria-checked")) || itemRole === "tab" && (item.hasAttribute("aria-selected") || item.hasAttribute("aria-expanded")));
674
+ });
675
+ if (!multiple && !explicit) {
676
+ const active = focused?.getAttribute("aria-activedescendant");
677
+ p.selected = !!root.hasFocus() && (focused === el || !!active && resolveId(focused, active) === el);
678
+ }
679
+ }
680
+ }
681
+ const expanded = el.getAttribute("aria-expanded");
682
+ if (expanded !== null && expanded !== "" && expanded.toLowerCase() !== "undefined") p.expanded = expanded.toLowerCase() !== "false";
683
+ if (el.localName === "summary" && el.parentElement?.localName === "details") p.expanded = el.parentElement.open;
684
+ const popoverTarget = ["button", "input"].includes(el.localName) ? el.popoverTargetElement : null;
685
+ if (popoverTarget?.popover && !el.matches(":disabled") && !ancestorMatches(el, (ancestor) => ancestor === popoverTarget)) p.expanded = popoverTarget.matches(":popover-open");
686
+ const token = (attr) => {
687
+ const raw = el.getAttribute(attr);
688
+ return raw === null || raw === "" || raw === "undefined" ? null : raw;
689
+ };
690
+ const pressed = r === "button" ? token("aria-pressed") : null;
691
+ const checked = token("aria-checked");
692
+ const checkable = [
693
+ "checkbox",
694
+ "radio",
695
+ "switch",
696
+ "menuitemcheckbox",
697
+ "menuitemradio"
698
+ ].includes(r) || ["option", "treeitem"].includes(r) && checked !== null;
699
+ if (pressed !== null || checkable) {
700
+ const key = pressed !== null ? "pressed" : "checked";
701
+ if (el.localName === "input" && ["checkbox", "radio"].includes(el.type)) p[key] = el.type === "checkbox" && el.indeterminate ? "mixed" : String(el.checked);
702
+ else {
703
+ const raw = (pressed !== null ? pressed : checked)?.toLowerCase();
704
+ p[key] = raw === "mixed" ? [
705
+ "checkbox",
706
+ "menuitemcheckbox",
707
+ "option",
708
+ "treeitem"
709
+ ].includes(r) || pressed !== null ? "mixed" : "false" : raw == null || raw === "false" ? "false" : "true";
710
+ }
711
+ }
712
+ const range = rangeInfo(el, r);
713
+ if (range) {
714
+ p.valuemin = range.min;
715
+ p.valuemax = range.max;
716
+ p.valuetext = range.text;
717
+ }
718
+ const ariaDisabled = (element) => {
719
+ const raw = element.getAttribute("aria-disabled");
720
+ if (raw === null || raw === "" || raw.toLowerCase() === "undefined") return void 0;
721
+ return raw.toLowerCase() !== "false";
722
+ };
723
+ const editableParent = composedParent(el);
724
+ const cssEditableRoot = !!editableStyle(el) && !(editableParent && editableStyle(editableParent));
725
+ const canInheritDisabled = !["iframe", "frame"].includes(el.localName) && !isHidden(el) && (el.tabIndex >= 0 || el.hasAttribute("tabindex") || el.isContentEditable || cssEditableRoot || el.localName === "option" && !el.closest("datalist"));
726
+ const ownAriaDisabled = ariaDisabled(el);
727
+ const nativeDisabled = el.localName !== "fieldset" && el.matches(":disabled");
728
+ let inheritedDisabled = false;
729
+ if (ownAriaDisabled === void 0 && canInheritDisabled) for (let parent = composedParent(el); parent; parent = composedParent(parent)) {
730
+ if (parent.localName !== "fieldset" && parent.matches(":disabled")) {
731
+ inheritedDisabled = true;
732
+ break;
733
+ }
734
+ const state = ariaDisabled(parent);
735
+ if (state !== void 0) {
736
+ inheritedDisabled = state;
737
+ break;
738
+ }
739
+ }
740
+ const disabled = nativeDisabled || ownAriaDisabled === true || inheritedDisabled;
741
+ if (disabled) p.disabled = true;
742
+ if ([
743
+ "slider",
744
+ "spinbutton",
745
+ "scrollbar",
746
+ "separator"
747
+ ].includes(r)) {
748
+ delete p.readonly;
749
+ const rawReadonly = el.getAttribute("aria-readonly");
750
+ const ariaReadonly = ["slider", "spinbutton"].includes(r) && rawReadonly !== null && rawReadonly !== "" && !["false", "undefined"].includes(rawReadonly.toLowerCase());
751
+ const nativeReadonly = !!el.readOnly && (el.localName === "textarea" || el.localName === "input" && [
752
+ "text",
753
+ "search",
754
+ "url",
755
+ "tel",
756
+ "email",
757
+ "password",
758
+ "number",
759
+ "date",
760
+ "month",
761
+ "week",
762
+ "time",
763
+ "datetime-local"
764
+ ].includes(el.type));
765
+ if (!disabled && !ariaReadonly && !nativeReadonly) p.settable = true;
766
+ }
767
+ if (r === "spinbutton" && el.localName === "input") p.editable = "plaintext";
768
+ const popupAttr = (el.getAttribute("aria-haspopup") || "").trim().toLowerCase();
769
+ const popup = popupAttr === "true" ? "menu" : [
770
+ "menu",
771
+ "listbox",
772
+ "tree",
773
+ "grid",
774
+ "dialog"
775
+ ].includes(popupAttr) ? popupAttr : null;
776
+ if (popup) p.hasPopup = popup;
777
+ else if (r === "combobox") p.hasPopup = el.localName === "select" ? "menu" : "listbox";
778
+ if (el.localName === "select" && r === "combobox") p.expanded = el.matches(":open");
779
+ if ([
780
+ "grid",
781
+ "treegrid",
782
+ "gridcell",
783
+ "columnheader",
784
+ "rowheader"
785
+ ].includes(r)) {
786
+ let grid = null;
787
+ if ([
788
+ "gridcell",
789
+ "columnheader",
790
+ "rowheader"
791
+ ].includes(r)) for (let parent = composedParent(el); parent; parent = composedParent(parent)) {
792
+ const parentRole = explicitRole(parent);
793
+ if (["grid", "treegrid"].includes(parentRole)) {
794
+ grid = parent;
795
+ break;
796
+ }
797
+ if (parent.localName === "table" || parentRole === "table") break;
798
+ }
799
+ const raw = (el.getAttribute("aria-readonly") || "").trim().toLowerCase();
800
+ const supportsReadonly = ["grid", "treegrid"].includes(r) || !!grid;
801
+ const inherited = grid?.getAttribute("aria-readonly")?.trim().toLowerCase() === "true";
802
+ p.readonly = !disabled && supportsReadonly && (raw === "true" ? true : raw === "false" ? false : !!inherited);
803
+ }
804
+ const editableRoot = el.isContentEditable && !composedParent(el)?.isContentEditable;
805
+ if (!["iframe", "frame"].includes(el.localName) && !nativeDisabled && !isHidden(el) && (el.tabIndex >= 0 || el.hasAttribute("tabindex") || editableRoot || cssEditableRoot)) p.focusable = true;
806
+ let childHasFocusedElement = false;
807
+ if (["iframe", "frame"].includes(el.localName)) try {
808
+ const child = el.contentDocument, active = child?.activeElement;
809
+ childHasFocusedElement = !!active && active !== child.body && active !== child.documentElement;
810
+ } catch {}
811
+ if (el === focused && el !== root.body && el !== root.documentElement && root.hasFocus() && !childHasFocusedElement) p.focused = true;
812
+ const ariaInvalid = el.getAttribute("aria-invalid")?.trim().toLowerCase();
813
+ if (ariaInvalid) {
814
+ if (ariaInvalid === "false") p.invalid = "false";
815
+ else if (ariaInvalid === "grammar" || ariaInvalid === "spelling") {
816
+ if (r === "textbox") p.invalid = "true";
817
+ } else p.invalid = "true";
818
+ } else if (el.validity) {
819
+ const emptyRequiredText = r === "textbox" && el.required && el.value === "";
820
+ p.invalid = String(!(!el.validity.customError && (!el.willValidate || el.validity.valid || emptyRequiredText)));
821
+ }
822
+ if (el.localName === "textarea" || el.localName === "input" && [
823
+ "text",
824
+ "search",
825
+ "email",
826
+ "url",
827
+ "tel",
828
+ "password"
829
+ ].includes(el.type)) {
830
+ p.editable = "plaintext";
831
+ if (![
832
+ "slider",
833
+ "spinbutton",
834
+ "scrollbar",
835
+ "separator"
836
+ ].includes(r) && !el.readOnly && !disabled) p.settable = true;
837
+ if (r !== "searchbox") p.multiline = el.localName === "textarea";
838
+ if (r === "textbox") p.readonly = !disabled && !!el.readOnly;
839
+ } else {
840
+ const editable = editableStyle(el);
841
+ if (editable) p.editable = editable;
842
+ if (r === "textbox") {
843
+ const rawReadonly = el.getAttribute("aria-readonly");
844
+ const readonly = rawReadonly !== null && rawReadonly !== "" && !["false", "undefined"].includes(rawReadonly.toLowerCase()) && !el.isContentEditable;
845
+ if (!disabled && !readonly) p.settable = true;
846
+ p.multiline = el.getAttribute("aria-multiline") === "true";
847
+ p.readonly = !disabled && readonly;
848
+ }
849
+ }
850
+ if (el.localName === "input") {
851
+ if (el.disabled) p.disabled = true;
852
+ }
853
+ const shortcuts = el.getAttribute("aria-keyshortcuts");
854
+ if (shortcuts) p.keyshortcuts = shortcuts;
855
+ if (el.localName === "option") {
856
+ if (!(el.disabled || el.parentElement?.localName === "optgroup" && el.parentElement.disabled) && !el.closest("datalist") && !inert(el)) p.focusable = true;
857
+ if (!disabled) p.selected = el.selected;
858
+ }
859
+ if (el.localName === "optgroup") delete p.disabled;
860
+ if ([
861
+ "grid",
862
+ "listbox",
863
+ "tablist",
864
+ "treegrid",
865
+ "tree"
866
+ ].includes(r)) {
867
+ const raw = el.getAttribute("aria-multiselectable");
868
+ p.multiselectable = raw !== null && raw !== "" && raw.toLowerCase() !== "undefined" ? raw.toLowerCase() !== "false" : el.localName === "select" && el.multiple;
869
+ }
870
+ if ([
871
+ "combobox",
872
+ "gridcell",
873
+ "listbox",
874
+ "radiogroup",
875
+ "spinbutton",
876
+ "textbox",
877
+ "tree",
878
+ "columnheader",
879
+ "rowheader",
880
+ "treegrid"
881
+ ].includes(r) && !(r === "combobox" && el.localName === "select")) {
882
+ const raw = el.getAttribute("aria-required");
883
+ p.required = el.matches(":required") || raw !== null && raw !== "" && !["false", "undefined"].includes(raw.toLowerCase());
884
+ }
885
+ const orientationDefaults = {
886
+ listbox: "vertical",
887
+ menu: "vertical",
888
+ menubar: "horizontal",
889
+ scrollbar: "vertical",
890
+ separator: "horizontal",
891
+ slider: "horizontal",
892
+ tablist: "horizontal",
893
+ toolbar: "horizontal",
894
+ tree: "vertical"
895
+ };
896
+ if (Object.hasOwn(orientationDefaults, r) || [
897
+ "radiogroup",
898
+ "treegrid",
899
+ "combobox"
900
+ ].includes(r)) {
901
+ const orientation = el.getAttribute("aria-orientation")?.toLowerCase();
902
+ if (orientation === "horizontal" || orientation === "vertical") p.orientation = orientation;
903
+ else if (orientationDefaults[r]) p.orientation = orientationDefaults[r];
904
+ }
905
+ if (r === "heading") {
906
+ const raw = el.getAttribute("aria-level");
907
+ const match = raw?.match(/^\s*([+-]?\d+)/);
908
+ const parsed = match ? Number(match[1]) : 0;
909
+ const aria = raw ? Number.isSafeInteger(parsed) && parsed <= 2147483647 ? Math.max(1, parsed) : 1 : 0;
910
+ const native = /^h[1-6]$/.test(el.localName) ? Number(el.localName[1]) : 2;
911
+ p.level = aria >= 1 && aria <= 9 ? aria : native;
912
+ }
913
+ return p;
914
+ };
915
+ const redundantLabel = (label) => {
916
+ if (label?.localName !== "label") return false;
917
+ const control = label.control;
918
+ if (control?.localName !== "input" || !["checkbox", "radio"].includes(control.type) || isHidden(control)) return false;
919
+ if (norm(control.getAttribute("aria-label")) || (control.getAttribute(labelledByAttribute(control)) || "").split(/[\t\n\f\r ]+/).some((id) => id && resolveId(control, id))) return false;
920
+ const children = [...label.children];
921
+ return children.length === 0 || children.length === 1 && children[0] === control;
922
+ };
923
+ const add = (node, parentId, forcedRole) => {
924
+ options.checkBudget?.();
925
+ if (node.nodeType !== Node.TEXT_NODE && node.nodeType !== Node.ELEMENT_NODE) return null;
926
+ const directShadowChild = node.parentNode?.nodeType === Node.DOCUMENT_FRAGMENT_NODE && !!node.parentNode.host;
927
+ if (node.nodeType === Node.ELEMENT_NODE && node.localName === "head") return null;
928
+ if (node.nodeType === Node.ELEMENT_NODE && node.localName === "slot" && node.getRootNode()?.host && !node.hasChildNodes() && node.assignedNodes().length === 0) return null;
929
+ const plainSlot = node.nodeType === Node.ELEMENT_NODE && node.localName === "slot" && !!node.getRootNode()?.host && !isHidden(node) && getComputedStyle(node).display === "contents" && !node.id && !node.hasAttribute("role") && !node.hasAttribute("lang") && !node.getAttribute("title") && ![...node.attributes].some((a) => a.name.startsWith("aria-") || a.name.startsWith("on")) && !node.onclick;
930
+ const slotUsedForName = plainSlot && (() => {
931
+ for (let parent = node.parentElement; parent; parent = parent.parentElement) {
932
+ const parentRole = role(parent);
933
+ if ([
934
+ "button",
935
+ "heading",
936
+ "link",
937
+ "checkbox",
938
+ "radio",
939
+ "switch",
940
+ "tab",
941
+ "treeitem",
942
+ "option",
943
+ "menuitem",
944
+ "menuitemcheckbox",
945
+ "menuitemradio"
946
+ ].includes(parentRole) || parent.localName === "label" || parent.id) return true;
947
+ if (parentRole === "group") return false;
948
+ }
949
+ return false;
950
+ })();
951
+ if (plainSlot && !directShadowChild && !slotUsedForName) {
952
+ for (const child of descendants(node)) add(child, parentId);
953
+ return null;
954
+ }
955
+ const plainShadowHost = node.nodeType === Node.ELEMENT_NODE && !!node.shadowRoot && node.localName.includes("-") && !isHidden(node) && (getComputedStyle(node).position === "static" || getComputedStyle(node).display === "contents") && !node.id && !node.isContentEditable && !node.hasAttribute("role") && !node.hasAttribute("tabindex") && !node.getAttribute("title") && ![...node.attributes].some((a) => a.name.startsWith("aria-") || a.name.startsWith("on")) && !node.onclick;
956
+ const lineBreakingShadowHost = plainShadowHost && [
957
+ "block",
958
+ "flex",
959
+ "grid",
960
+ "flow-root"
961
+ ].includes(getComputedStyle(node).display);
962
+ if (plainShadowHost && !lineBreakingShadowHost && !node.assignedSlot && !directShadowChild) {
963
+ for (const child of descendants(node)) add(child, parentId);
964
+ return null;
965
+ }
966
+ let plainSpan = false, retainedIgnoredInline = false, ignoredBlockSpan = false;
967
+ if (node.nodeType === Node.ELEMENT_NODE && node.namespaceURI === "http://www.w3.org/1999/xhtml" && !node.localName.includes("-") && node.localName !== "slot" && !node.shadowRoot && !node.popover && !isHidden(node) && (!node.isContentEditable || node.localName === "span" && !node.hasAttribute("contenteditable") && composedParent(node)?.isContentEditable) && !node.id && !node.hasAttribute("role") && !node.hasAttribute("tabindex") && !node.getAttribute("title") && ![...node.attributes].some((a) => a.name.startsWith("aria-") || a.name.startsWith("on")) && !node.onclick && role(node) === "generic") {
968
+ const style = getComputedStyle(node), before = getComputedStyle(node, "::before").content, after = getComputedStyle(node, "::after").content;
969
+ const eligible = ["inline", "contents"].includes(style.display) && style.position === "static" && !["auto", "scroll"].includes(style.overflowX) && !["auto", "scroll"].includes(style.overflowY);
970
+ const requiresRetention = node.hasAttribute("lang") || !["none", "normal"].includes(before) || !["none", "normal"].includes(after);
971
+ plainSpan = eligible && !requiresRetention;
972
+ ignoredBlockSpan = node.localName === "span" && [
973
+ "block",
974
+ "flex",
975
+ "grid",
976
+ "flow-root"
977
+ ].includes(style.display) && style.position === "static" && !["auto", "scroll"].includes(style.overflowX) && !["auto", "scroll"].includes(style.overflowY) && !requiresRetention && !node.assignedSlot && !directShadowChild;
978
+ retainedIgnoredInline = eligible && requiresRetention && !node.assignedSlot && !directShadowChild || ignoredBlockSpan;
979
+ }
980
+ if (plainSpan && !node.assignedSlot) {
981
+ for (const child of descendants(node)) add(child, parentId);
982
+ return null;
983
+ }
984
+ const whitespaceText = node.nodeType === Node.TEXT_NODE && /^[\t\n\f\r ]+$/.test(node.nodeValue);
985
+ const whitespaceParent = whitespaceText ? node.parentElement || node.getRootNode()?.host : null;
986
+ if (whitespaceText && whitespaceParent?.localName === "select" && getComputedStyle(whitespaceParent, "::picker(select)").appearance !== "base-select") return null;
987
+ if (whitespaceText && whitespaceParent && !isHidden(whitespaceParent)) {
988
+ const style = getComputedStyle(whitespaceParent);
989
+ if (["normal", "nowrap"].includes(style.whiteSpace)) {
990
+ const range = root.createRange();
991
+ range.selectNodeContents(node);
992
+ if (![...range.getClientRects()].some((rect) => rect.width > 0)) return null;
993
+ const separates = (sibling, after, depth = 0) => {
994
+ if (sibling?.nodeType !== Node.ELEMENT_NODE) return false;
995
+ const siblingStyle = getComputedStyle(sibling);
996
+ if (siblingStyle.display === "none") return true;
997
+ if (sibling.localName === "img" || sibling.localName === "input" && sibling.type === "image") return false;
998
+ if (sibling.localName === "slot" && sibling.getRootNode()?.host && siblingStyle.display === "contents") return true;
999
+ if (["iframe", "frame"].includes(sibling.localName)) return true;
1000
+ const display = siblingStyle.display;
1001
+ if ([
1002
+ "inline-block",
1003
+ "inline-flex",
1004
+ "inline-grid",
1005
+ "inline-table",
1006
+ "block",
1007
+ "flow-root",
1008
+ "flex",
1009
+ "grid",
1010
+ "table"
1011
+ ].includes(display)) return true;
1012
+ if (display !== "inline" || depth >= 3) return false;
1013
+ const pseudo = getComputedStyle(sibling, after ? "::before" : "::after").content;
1014
+ if (!["none", "normal"].includes(pseudo)) return false;
1015
+ return separates(after ? sibling.firstChild : sibling.lastChild, after, depth + 1);
1016
+ };
1017
+ if (separates(node.previousSibling, false) || separates(node.nextSibling, true)) return null;
1018
+ }
1019
+ }
1020
+ const id = idFor();
1021
+ const path = pathOf(node);
1022
+ if (lineBreakingShadowHost) lineBreakingIgnoredElements.add(id);
1023
+ if (ignoredBlockSpan) lineBreakingIgnoredElements.add(id);
1024
+ const isText = node.nodeType === Node.TEXT_NODE;
1025
+ const el = isText ? null : node;
1026
+ const ownerSelect = el?.localName === "option" ? el.closest("select") : null;
1027
+ const richNativeOption = !!ownerSelect && !(el.childNodes.length === 1 && el.firstChild.nodeType === Node.TEXT_NODE) && getComputedStyle(ownerSelect, "::picker(select)").appearance === "base-select";
1028
+ const leafNativeOption = el?.localName === "option" && !richNativeOption;
1029
+ const visibilityElement = isText ? node.assignedSlot || node.parentElement || node.getRootNode()?.host : el;
1030
+ const redundant = isText ? redundantLabel(node.parentElement) : redundantLabel(el);
1031
+ const bodyStyle = el?.localName === "body" ? getComputedStyle(el) : null;
1032
+ const bodyInlineLayout = !!bodyStyle && (() => {
1033
+ let hasInline = false, hasBlock = false;
1034
+ const visit = (node) => {
1035
+ if (node.nodeType === Node.TEXT_NODE) {
1036
+ if (norm(node.nodeValue)) hasInline = true;
1037
+ return;
1038
+ }
1039
+ if (node.nodeType !== Node.ELEMENT_NODE) return;
1040
+ const style = getComputedStyle(node);
1041
+ if (style.display === "none" || ["absolute", "fixed"].includes(style.position)) return;
1042
+ if (style.display === "contents") {
1043
+ for (const child of node.childNodes) visit(child);
1044
+ return;
1045
+ }
1046
+ if (style.display.startsWith("inline")) hasInline = true;
1047
+ else hasBlock = true;
1048
+ };
1049
+ for (const child of el.childNodes) visit(child);
1050
+ return hasInline && !hasBlock;
1051
+ })();
1052
+ const bodyOwnScroll = !!bodyStyle && (["auto", "scroll"].includes(bodyStyle.overflowX) && el.scrollWidth > el.clientWidth || ["auto", "scroll"].includes(bodyStyle.overflowY) && el.scrollHeight > el.clientHeight);
1053
+ const plainBody = !!bodyStyle && !bodyInlineLayout && !el.hasAttribute("id") && !explicitRole(el) && ![...el.attributes].some((a) => a.name.startsWith("aria-")) && !el.getAttribute("title") && !el.isContentEditable && bodyStyle.position === "static" && !bodyOwnScroll && !!el.children.length && ![...el.childNodes].some((n) => n.nodeType === Node.TEXT_NODE && norm(n.nodeValue));
1054
+ const editingRoot = el?.localName === "tbody" && (["true", "plaintext-only"].includes(el.contentEditable) || !!editableStyle(el) && !(composedParent(el) && editableStyle(composedParent(el))));
1055
+ const plainTableBody = el?.localName === "tbody" && !!el.closest("table") && !isHidden(el) && !explicitRole(el) && ![...el.attributes].some((a) => a.name.startsWith("aria-") || a.name.startsWith("on")) && !el.hasAttribute("tabindex") && !el.getAttribute("title") && !editingRoot && !el.onclick;
1056
+ const plainBlockContainer = el?.localName === "div" && !isHidden(el) && !el.id && !el.popover && !explicitRole(el) && ![...el.attributes].some((a) => a.name.startsWith("aria-") || a.name.startsWith("on")) && !el.hasAttribute("tabindex") && !el.getAttribute("title") && !el.isContentEditable && !editableStyle(el) && !el.onclick && (() => {
1057
+ const style = getComputedStyle(el), before = getComputedStyle(el, "::before").content, after = getComputedStyle(el, "::after").content;
1058
+ const overflow = [
1059
+ "auto",
1060
+ "scroll",
1061
+ "hidden"
1062
+ ].includes(style.overflowX) && el.scrollWidth > el.clientWidth || [
1063
+ "auto",
1064
+ "scroll",
1065
+ "hidden"
1066
+ ].includes(style.overflowY) && el.scrollHeight > el.clientHeight;
1067
+ const blockDisplays = [
1068
+ "block",
1069
+ "flow-root",
1070
+ "flex",
1071
+ "grid",
1072
+ "table",
1073
+ "list-item"
1074
+ ];
1075
+ const inFlow = (child) => {
1076
+ const childStyle = getComputedStyle(child);
1077
+ return childStyle.display !== "none" && !["absolute", "fixed"].includes(childStyle.position);
1078
+ };
1079
+ const layoutChildren = [];
1080
+ const expand = (child, depth) => {
1081
+ if (child.nodeType === Node.ELEMENT_NODE && depth < 50 && getComputedStyle(child).display === "contents") for (const nested of descendants(child)) expand(nested, depth + 1);
1082
+ else layoutChildren.push(child);
1083
+ };
1084
+ for (const child of el.childNodes) expand(child, 0);
1085
+ const blockChildren = layoutChildren.some((child) => child.nodeType === Node.ELEMENT_NODE && inFlow(child) && blockDisplays.includes(getComputedStyle(child).display)) || layoutChildren.every((child) => child.nodeType === Node.TEXT_NODE ? !norm(child.data) : child.nodeType !== Node.ELEMENT_NODE || !inFlow(child));
1086
+ return [
1087
+ "block",
1088
+ "flow-root",
1089
+ "flex",
1090
+ "grid"
1091
+ ].includes(style.display) && style.position === "static" && !overflow && ["none", "normal"].includes(before) && ["none", "normal"].includes(after) && blockChildren;
1092
+ })();
1093
+ if (plainBlockContainer && ![...el.children].some((child) => !isHidden(child))) lineBreakingIgnoredElements.add(id);
1094
+ const plainCaption = el?.localName === "caption" && !isHidden(el) && !explicitRole(el) && ![...el.attributes].some((a) => a.name.startsWith("aria-") || a.name.startsWith("on")) && !el.hasAttribute("tabindex") && !el.getAttribute("title") && !el.isContentEditable && !el.onclick && (() => {
1095
+ const style = getComputedStyle(el), before = getComputedStyle(el, "::before").content, after = getComputedStyle(el, "::after").content;
1096
+ if (style.position !== "static" || ["auto", "scroll"].includes(style.overflowX) || ["auto", "scroll"].includes(style.overflowY) || !["none", "normal"].includes(before) || !["none", "normal"].includes(after)) return false;
1097
+ return ![...el.childNodes].some((child) => child.nodeType === Node.TEXT_NODE ? !!norm(child.nodeValue) : child.nodeType === Node.ELEMENT_NODE && !isHidden(child) && [
1098
+ "inline",
1099
+ "inline-block",
1100
+ "inline-flex",
1101
+ "inline-grid",
1102
+ "inline-table"
1103
+ ].includes(getComputedStyle(child).display));
1104
+ })();
1105
+ const legendGroup = el?.localName === "legend" ? el.closest("optgroup") : null;
1106
+ const legendSelect = legendGroup?.closest("select");
1107
+ const closedLegendPicker = legendSelect && !legendSelect.multiple && legendSelect.size <= 1 && !legendSelect.matches(":open") && getComputedStyle(legendSelect, "::picker(select)").appearance === "base-select";
1108
+ const ignoredGroupLegend = !!legendGroup && !closedLegendPicker && !isHidden(el) && !explicitRole(el) && !el.hasAttribute("tabindex") && !el.onclick && ![...el.attributes].some((a) => a.name.startsWith("on"));
1109
+ const listParent = el?.localName === "li" ? composedParent(el) : null;
1110
+ const parentListRole = listParent?.getAttribute("role") || "";
1111
+ const presentationalListItem = !!listParent && [
1112
+ "ul",
1113
+ "ol",
1114
+ "menu"
1115
+ ].includes(listParent.localName) && !!parentListRole && !["list", "directory"].includes(parentListRole) && !explicitRole(el) && !isHidden(el);
1116
+ const presentationalTable = el?.localName === "table" && !isHidden(el) && ["none", "presentation"].includes(role(el));
1117
+ const tableAncestor = el && [
1118
+ "tr",
1119
+ "td",
1120
+ "th"
1121
+ ].includes(el.localName) ? el.closest("table") : null;
1122
+ const tableRole = tableAncestor ? role(tableAncestor) : null;
1123
+ const tableWithoutSemantics = tableAncestor && ["none", "presentation"].includes(tableRole);
1124
+ const presentationalTableRow = el?.localName === "tr" && tableWithoutSemantics && !isHidden(el) && !explicitRole(el) && !el.hasAttribute("tabindex") && !el.getAttribute("title") && !el.isContentEditable && !el.onclick && ![...el.attributes].some((a) => a.name.startsWith("aria-") || a.name.startsWith("on"));
1125
+ const tableCellRole = el && ["td", "th"].includes(el.localName) && !explicitRole(el) && tableWithoutSemantics ? "generic" : el?.localName === "td" && !explicitRole(el) && ["grid", "treegrid"].includes(tableRole) ? "gridcell" : el?.localName === "tbody" && !explicitRole(el) && isLayoutTable(el.closest("table")) ? "generic" : null;
1126
+ const plainForeignObject = el?.namespaceURI === "http://www.w3.org/2000/svg" && el.localName === "foreignObject" && !isHidden(el) && !explicitRole(el) && !el.hasAttribute("tabindex") && !el.hasAttribute("title") && !el.isContentEditable && !el.onclick && ![...el.attributes].some((a) => a.name.startsWith("aria-") || a.name.startsWith("on")) && ![...el.children].some((c) => c.namespaceURI === "http://www.w3.org/2000/svg" && ["title", "desc"].includes(c.localName));
1127
+ const emptyAltImage = el?.localName === "img" && el.getAttribute("alt") === "" && !isHidden(el) && !explicitRole(el) && !el.hasAttribute("tabindex") && !el.getAttribute("title") && !el.onclick && ![...el.attributes].some((a) => a.name.startsWith("aria-") || a.name.startsWith("on"));
1128
+ if (emptyAltImage && getComputedStyle(el).display === "block") lineBreakingIgnoredElements.add(id);
1129
+ const uninterestingRoot = el?.localName === "html" || plainBody || plainTableBody || plainCaption || plainBlockContainer || retainedIgnoredInline || plainShadowHost || plainSlot || presentationalTableRow || plainSpan && !!el?.assignedSlot;
1130
+ const ignored = redundant || uninterestingRoot || ignoredGroupLegend || presentationalListItem || presentationalTable || plainForeignObject || emptyAltImage || !!visibilityElement && (isHidden(visibilityElement) || !isText && [
1131
+ "head",
1132
+ "title",
1133
+ "meta",
1134
+ "link",
1135
+ "style",
1136
+ "script",
1137
+ "noscript"
1138
+ ].includes(el.localName));
1139
+ const r = redundant || uninterestingRoot || ignoredGroupLegend || presentationalListItem || presentationalTable || plainForeignObject ? "none" : forcedRole || (isText ? "StaticText" : el.localName === "body" && !explicitRole(el) ? "generic" : tableCellRole || role(el));
1140
+ const nameBearing = r === "row" && (() => {
1141
+ for (let ancestor = composedParent(el); ancestor; ancestor = composedParent(ancestor)) {
1142
+ const ancestorRole = role(ancestor);
1143
+ if (["grid", "treegrid"].includes(ancestorRole)) return true;
1144
+ if (![
1145
+ "generic",
1146
+ "none",
1147
+ "group",
1148
+ "rowgroup"
1149
+ ].includes(ancestorRole)) return false;
1150
+ }
1151
+ return false;
1152
+ })() || [
1153
+ "button",
1154
+ "link",
1155
+ "heading",
1156
+ "image",
1157
+ "checkbox",
1158
+ "radio",
1159
+ "switch",
1160
+ "menuitem",
1161
+ "menuitemcheckbox",
1162
+ "menuitemradio",
1163
+ "tab",
1164
+ "textbox",
1165
+ "combobox",
1166
+ "listbox",
1167
+ "slider",
1168
+ "spinbutton",
1169
+ "searchbox",
1170
+ "option",
1171
+ "treeitem",
1172
+ "table",
1173
+ "cell",
1174
+ "LayoutTableCell",
1175
+ "gridcell",
1176
+ "rowheader",
1177
+ "columnheader",
1178
+ "Iframe",
1179
+ "term",
1180
+ "DisclosureTriangle",
1181
+ "DisclosureTriangleGrouped"
1182
+ ].includes(r);
1183
+ const textWhitespace = isText && visibilityElement ? getComputedStyle(visibilityElement).whiteSpace : "";
1184
+ const preserveTextWhitespace = [
1185
+ "pre",
1186
+ "pre-wrap",
1187
+ "break-spaces"
1188
+ ].includes(textWhitespace);
1189
+ let textName = isText ? preserveTextWhitespace ? node.nodeValue : textWhitespace === "pre-line" && !whitespaceText ? node.nodeValue.replace(/[\t\f\r ]+/g, " ").replace(/ *\n */g, "\n").replace(/^ +| +$/g, "") : whitespaceText ? " " : norm(node.nodeValue) : "";
1190
+ if (isText && !whitespaceText) textName = transformText(textName, visibilityElement);
1191
+ if (isText && !whitespaceText && visibilityElement && ["normal", "nowrap"].includes(getComputedStyle(visibilityElement).whiteSpace) && !isHidden(visibilityElement)) {
1192
+ const visibleRange = (start, end) => {
1193
+ const range = root.createRange();
1194
+ range.setStart(node, start);
1195
+ range.setEnd(node, end);
1196
+ return [...range.getClientRects()].some((rect) => rect.width > 0);
1197
+ };
1198
+ const leading = node.nodeValue.match(/^[\t\n\f\r ]+/)?.[0], trailing = node.nodeValue.match(/[\t\n\f\r ]+$/)?.[0];
1199
+ if (leading && visibleRange(0, leading.length)) textName = " " + textName;
1200
+ if (trailing && visibleRange(node.length - trailing.length, node.length)) textName += " ";
1201
+ }
1202
+ const optgroupSelect = el?.localName === "optgroup" ? el.closest("select") : null;
1203
+ const closedCustomGroup = optgroupSelect && !optgroupSelect.multiple && optgroupSelect.size <= 1 && !optgroupSelect.matches(":open") && getComputedStyle(optgroupSelect, "::picker(select)").appearance === "base-select";
1204
+ const groupName = el && r === "group" ? (() => {
1205
+ if (hasAriaName(el)) return textAlternative(el);
1206
+ if (["fieldset", "optgroup"].includes(el.localName)) {
1207
+ const native = textAlternative(el);
1208
+ if (native) return native;
1209
+ }
1210
+ return norm(el.getAttribute("title"));
1211
+ })() : null;
1212
+ const listboxName = el && r === "listbox" ? hasAriaName(el) || el.localName === "select" ? textAlternative(el) : (el.getAttribute("title") || "").trim() !== (el.innerText || "").trim() ? norm(el.getAttribute("title")) : "" : null;
1213
+ const slotContentsName = el?.localName === "slot" && [
1214
+ "button",
1215
+ "heading",
1216
+ "link",
1217
+ "checkbox",
1218
+ "radio",
1219
+ "switch",
1220
+ "tab",
1221
+ "menuitem",
1222
+ "menuitemcheckbox",
1223
+ "menuitemradio",
1224
+ "treeitem",
1225
+ "option"
1226
+ ].includes(r);
1227
+ const computedName = redundant || uninterestingRoot || ignoredGroupLegend || presentationalListItem || closedCustomGroup ? "" : isText ? textName : r === "LineBreak" ? "\n" : el?.localName === "slot" ? slotContentsName ? textAlternative(el) : "" : groupName !== null ? groupName : listboxName !== null ? listboxName : r === "Abbr" ? hasAriaName(el) ? textAlternative(el) : (el.getAttribute("title") || "").trim() !== (el.innerText || "").trim() ? norm(el.getAttribute("title")) : "" : nameBearing || ["fieldset", "optgroup"].includes(el.localName) || el.hasAttribute(labelledByAttribute(el)) ? textAlternative(el) : norm(el.getAttribute("aria-label") || ([
1228
+ "region",
1229
+ "complementary",
1230
+ "article"
1231
+ ].includes(r) ? el.getAttribute("title") : "") || "");
1232
+ const textEditable = isText && visibilityElement ? editableStyle(visibilityElement) : void 0;
1233
+ const textProps = textEditable ? { editable: textEditable } : {};
1234
+ const data = {
1235
+ id,
1236
+ parentId: parentId || null,
1237
+ domPath: path,
1238
+ role: r,
1239
+ name: computedName,
1240
+ description: isText || uninterestingRoot || ignoredGroupLegend || presentationalListItem ? "" : description(el, computedName, r),
1241
+ ignored,
1242
+ ignoredReason: ignored ? emptyAltImage ? "emptyAlt" : presentationalListItem || presentationalTable || plainForeignObject ? "presentationalRole" : ignoredGroupLegend ? null : redundant ? isText ? "presentationalRole" : "labelFor" : uninterestingRoot ? "uninteresting" : !isText && [
1243
+ "head",
1244
+ "title",
1245
+ "meta",
1246
+ "link",
1247
+ "style",
1248
+ "script",
1249
+ "noscript"
1250
+ ].includes(el.localName) ? "notRendered" : hiddenReason(visibilityElement, isText) : null,
1251
+ properties: isText ? textProps : redundant || uninterestingRoot || ignoredGroupLegend || presentationalListItem ? {} : props(el, r),
1252
+ relations: isText ? [] : []
1253
+ };
1254
+ if (el) elementsById.set(id, el);
1255
+ else if (isText && typeof options.onText === "function") textsById.set(id, node);
1256
+ if (!isText) {
1257
+ const nameTargets = referenceTargets(el, labelledByAttribute(el));
1258
+ const usableLabelReference = !!norm(nameTargets.map((target) => textAlternative(target, /* @__PURE__ */ new Set(), true, isHidden(target))).join(" "));
1259
+ for (const [type, attr] of [
1260
+ ["labelledby", labelledByAttribute(el)],
1261
+ ["describedby", "aria-describedby"],
1262
+ ["owns", "aria-owns"]
1263
+ ]) {
1264
+ if (el.localName === "slot" && type === "labelledby") continue;
1265
+ if (!el.getAttribute(attr) && ["labelledby", "describedby"].includes(type)) {
1266
+ for (const target of referenceTargets(el, attr)) if (type !== "labelledby" || usableLabelReference) data.relations.push({
1267
+ type,
1268
+ targetPath: pathOf(target),
1269
+ targetId: byPath.get(pathOf(target)) || null
1270
+ });
1271
+ }
1272
+ for (const token of (el.getAttribute(attr) || "").split(/[\t\n\f\r ]+/).filter(Boolean)) {
1273
+ const target = resolveId(el, token);
1274
+ if (!target) {
1275
+ unresolvedRelations.push({
1276
+ sourceId: id,
1277
+ type,
1278
+ token,
1279
+ reason: "missing-dom-target"
1280
+ });
1281
+ continue;
1282
+ }
1283
+ if (type === "labelledby" && !usableLabelReference) continue;
1284
+ data.relations.push({
1285
+ type,
1286
+ targetPath: pathOf(target),
1287
+ targetId: byPath.get(pathOf(target)) || null
1288
+ });
1289
+ }
1290
+ }
1291
+ if (!data.ignored) for (const [type, attr] of [
1292
+ ["controls", "aria-controls"],
1293
+ ["details", "aria-details"],
1294
+ ["flowto", "aria-flowto"],
1295
+ ["errormessage", "aria-errormessage"],
1296
+ ["activedescendant", "aria-activedescendant"]
1297
+ ]) {
1298
+ if (type === "errormessage" && data.properties.invalid === "false") continue;
1299
+ const tokens = [...new Set((el.getAttribute(attr) || "").split(/[\t\n\f\r ]+/).filter(Boolean))];
1300
+ for (const token of type === "activedescendant" ? tokens.slice(0, 1) : tokens) {
1301
+ const target = resolveId(el, token);
1302
+ if (target && !isHidden(target)) data.relations.push({
1303
+ type,
1304
+ targetPath: pathOf(target),
1305
+ targetId: byPath.get(pathOf(target)) || null
1306
+ });
1307
+ }
1308
+ }
1309
+ if (!data.ignored && !el.hasAttribute("aria-details") && ["button", "input"].includes(el.localName) && !el.matches(":disabled")) {
1310
+ const target = el.popoverTargetElement;
1311
+ const nextElement = (() => {
1312
+ for (let cursor = el; cursor; cursor = cursor.parentElement) if (cursor.nextElementSibling) return cursor.nextElementSibling;
1313
+ return null;
1314
+ })();
1315
+ if (target?.popover && target.popover !== "hint" && target.matches(":popover-open") && target !== nextElement && !ancestorMatches(el, (e) => e === target) && !isHidden(target)) data.relations.push({
1316
+ type: "details",
1317
+ targetPath: pathOf(target),
1318
+ targetId: byPath.get(pathOf(target)) || null
1319
+ });
1320
+ }
1321
+ if (!usableLabelReference && !norm(el.getAttribute("aria-label")) && el.labels) for (const label of el.labels) data.relations.push({
1322
+ type: "labelledby",
1323
+ targetPath: pathOf(label),
1324
+ targetId: byPath.get(pathOf(label)) || null
1325
+ });
1326
+ if (el.localName === "fieldset" && !hasAriaName(el)) {
1327
+ const legend = [...el.children].find((child) => child.localName === "legend");
1328
+ if (legend && !isHidden(legend) && textAlternative(legend)) data.relations.push({
1329
+ type: "labelledby",
1330
+ targetPath: pathOf(legend),
1331
+ targetId: byPath.get(pathOf(legend)) || null
1332
+ });
1333
+ }
1334
+ if (el.localName === "table" && !hasAriaName(el)) {
1335
+ const caption = visibleCaption(el);
1336
+ if (caption && textAlternative(caption)) data.relations.push({
1337
+ type: "labelledby",
1338
+ targetPath: pathOf(caption),
1339
+ targetId: byPath.get(pathOf(caption)) || null
1340
+ });
1341
+ }
1342
+ }
1343
+ const v = isText ? void 0 : value(el, r);
1344
+ if (v !== void 0) data.value = v;
1345
+ nodes.push(data);
1346
+ byPath.set(path, id);
1347
+ if (isText || el && !leafNativeOption && ![
1348
+ "script",
1349
+ "style",
1350
+ "noscript",
1351
+ "textarea"
1352
+ ].includes(el.localName)) for (const child of descendants(node)) add(child, id);
1353
+ return id;
1354
+ };
1355
+ Node.ELEMENT_NODE, [...root.childNodes], root.body?.textContent;
1356
+ const rootId = idFor();
1357
+ const rootProperties = {
1358
+ url: root.location.href,
1359
+ focusable: true
1360
+ };
1361
+ if (root.hasFocus() && !["iframe", "frame"].includes(focused?.localName)) rootProperties.focused = true;
1362
+ const rootName = root.documentElement?.getAttribute("aria-label") ? "" : norm(root.title || "");
1363
+ nodes.push({
1364
+ id: rootId,
1365
+ parentId: null,
1366
+ domPath: "",
1367
+ role: "RootWebArea",
1368
+ name: rootName,
1369
+ description: "",
1370
+ ignored: false,
1371
+ ignoredReason: null,
1372
+ properties: rootProperties,
1373
+ relations: []
1374
+ });
1375
+ for (const child of [...root.childNodes]) add(child, rootId);
1376
+ const relationTargets = new Map(nodes.map((n) => [n.id, n]));
1377
+ for (const n of nodes) n.relations = (n.relations || []).filter((relation) => {
1378
+ relation.targetId = byPath.get(relation.targetPath) || null;
1379
+ if (relation.targetId) {
1380
+ if ([
1381
+ "controls",
1382
+ "details",
1383
+ "flowto",
1384
+ "errormessage",
1385
+ "owns"
1386
+ ].includes(relation.type) && relationTargets.get(relation.targetId)?.ignored) return false;
1387
+ return true;
1388
+ }
1389
+ unresolvedRelations.push({
1390
+ sourceId: n.id,
1391
+ type: relation.type,
1392
+ targetPath: relation.targetPath,
1393
+ reason: "target-not-reconstructed"
1394
+ });
1395
+ return false;
1396
+ });
1397
+ for (const n of nodes) {
1398
+ const el = elementsById.get(n.id);
1399
+ if (!el) continue;
1400
+ if (!n.ignored && n.relations.some((relation) => relation.type === "labelledby")) n.properties.labelledby = null;
1401
+ for (const type of [
1402
+ "controls",
1403
+ "details",
1404
+ "flowto",
1405
+ "errormessage",
1406
+ "activedescendant",
1407
+ "owns"
1408
+ ]) if (n.relations.some((relation) => relation.type === type)) n.properties[type] = type === "activedescendant" ? null : type === "details" ? el.getAttribute("aria-details") ?? "" : el.getAttribute(`aria-${type}`);
1409
+ }
1410
+ const nodeMap = new Map(nodes.map((n) => [n.id, n]));
1411
+ const claimed = /* @__PURE__ */ new Set();
1412
+ const ownedOrder = /* @__PURE__ */ new Map();
1413
+ for (const owner of nodes) {
1414
+ const el = elementsById.get(owner.id);
1415
+ if (!el || el.isContentEditable || [
1416
+ "input",
1417
+ "textarea",
1418
+ "iframe",
1419
+ "frame",
1420
+ "img",
1421
+ "br",
1422
+ "select",
1423
+ "option"
1424
+ ].includes(el.localName) || ariaHidden(el)) continue;
1425
+ for (const relation of owner.relations || []) {
1426
+ if (relation.type !== "owns" || !relation.targetId || claimed.has(relation.targetId)) continue;
1427
+ const target = nodeMap.get(relation.targetId), child = elementsById.get(relation.targetId);
1428
+ if (!target || !child || [
1429
+ "area",
1430
+ "option",
1431
+ "optgroup"
1432
+ ].includes(child.localName) || isHidden(child) || child.contains(el)) continue;
1433
+ let cyclic = false;
1434
+ for (let parent = owner; parent; parent = nodeMap.get(parent.parentId)) if (parent.id === target.id) {
1435
+ cyclic = true;
1436
+ break;
1437
+ }
1438
+ if (cyclic) continue;
1439
+ target.parentId = owner.id;
1440
+ claimed.add(target.id);
1441
+ const order = ownedOrder.get(owner.id) || [];
1442
+ order.push(target.id);
1443
+ ownedOrder.set(owner.id, order);
1444
+ }
1445
+ }
1446
+ for (const n of nodes) {
1447
+ if (!["listitem", "treeitem"].includes(n.role) || n.ignored) continue;
1448
+ const raw = elementsById.get(n.id)?.getAttribute("aria-level");
1449
+ if (raw !== null && raw !== void 0 && raw !== "") {
1450
+ const match = raw.match(/^\s*([+-]?\d+)/);
1451
+ const parsed = match ? Number(match[1]) : 0;
1452
+ n.properties.level = Number.isSafeInteger(parsed) && parsed <= 2147483647 ? Math.max(1, parsed) : 1;
1453
+ continue;
1454
+ }
1455
+ let level = n.role === "treeitem" ? 1 : 0;
1456
+ for (let parent = nodeMap.get(n.parentId); parent; parent = nodeMap.get(parent.parentId)) {
1457
+ if (n.role === "listitem" && parent.role === "list") level++;
1458
+ if (n.role === "treeitem") {
1459
+ if (parent.role === "group") level++;
1460
+ else if (parent.role === "tree") break;
1461
+ }
1462
+ }
1463
+ n.properties.level = Math.max(1, level);
1464
+ }
1465
+ const groups = /* @__PURE__ */ new Map();
1466
+ for (const n of nodes) {
1467
+ const children = groups.get(n.parentId) || [];
1468
+ children.push(n);
1469
+ groups.set(n.parentId, children);
1470
+ }
1471
+ for (const [parent, order] of ownedOrder) {
1472
+ const children = groups.get(parent) || [], byChild = new Map(children.map((n) => [n.id, n]));
1473
+ groups.set(parent, [...children.filter((n) => !order.includes(n.id)), ...order.map((id) => byChild.get(id)).filter(Boolean)]);
1474
+ }
1475
+ const ordered = [];
1476
+ const visit = (id) => {
1477
+ for (const child of groups.get(id) || []) {
1478
+ ordered.push(child);
1479
+ visit(child.id);
1480
+ }
1481
+ };
1482
+ visit(null);
1483
+ nodes.splice(0, nodes.length, ...ordered);
1484
+ const byId = new Map(nodes.map((n) => [n.id, n]));
1485
+ const keep = /* @__PURE__ */ new Set();
1486
+ const childrenByParent = /* @__PURE__ */ new Map();
1487
+ for (const n of nodes) {
1488
+ const siblings = childrenByParent.get(n.parentId) || [];
1489
+ siblings.push(n);
1490
+ childrenByParent.set(n.parentId, siblings);
1491
+ }
1492
+ const keepAncestors = (id) => {
1493
+ while (id && !keep.has(id)) {
1494
+ keep.add(id);
1495
+ id = byId.get(id)?.parentId;
1496
+ }
1497
+ };
1498
+ for (const id of lineBreakingIgnoredElements) keepAncestors(id);
1499
+ for (const n of nodes) if (!n.ignored) keepAncestors(n.id);
1500
+ for (const n of nodes) for (const relation of n.relations || []) if (relation.targetId) {
1501
+ keepAncestors(relation.targetId);
1502
+ const pending = [relation.targetId];
1503
+ while (pending.length) {
1504
+ const id = pending.pop();
1505
+ for (const child of childrenByParent.get(id) || []) {
1506
+ keep.add(child.id);
1507
+ pending.push(child.id);
1508
+ }
1509
+ }
1510
+ }
1511
+ for (const n of nodes) {
1512
+ const el = elementsById.get(n.id);
1513
+ if (!n.ignored || !el) continue;
1514
+ if (el.hasAttribute("lang")) keep.add(n.id);
1515
+ if (role(el) === "menu") keep.add(n.id);
1516
+ if (el.localName === "li" && n.ignoredReason === "notVisible") {
1517
+ const style = getComputedStyle(el);
1518
+ if (style.display === "list-item" && (style.listStyleType !== "none" || style.listStyleImage !== "none")) keep.add(n.id);
1519
+ }
1520
+ }
1521
+ const retainedRelationTargets = new Set(nodes.flatMap((n) => (n.relations || []).map((r) => r.targetId).filter(Boolean)));
1522
+ for (const n of nodes) {
1523
+ const el = elementsById.get(n.id);
1524
+ if (n.ignoredReason === "notVisible" && el && [
1525
+ "div",
1526
+ "nav",
1527
+ "section"
1528
+ ].includes(el.localName) && role(el) !== "menu" && !el.hasAttribute("lang") && !el.hasAttribute("aria-owns") && !retainedRelationTargets.has(n.id) && !lineBreakingIgnoredElements.has(n.id)) keep.delete(n.id);
1529
+ }
1530
+ const retained = nodes.filter((n) => keep.has(n.id));
1531
+ for (const n of retained) while (n.parentId && !keep.has(n.parentId)) n.parentId = byId.get(n.parentId)?.parentId || null;
1532
+ for (const n of retained) if (n.ignored) {
1533
+ n.role = "none";
1534
+ n.name = "";
1535
+ n.description = "";
1536
+ n.properties = {};
1537
+ n.relations = [];
1538
+ delete n.value;
1539
+ }
1540
+ if (typeof options.onElement === "function") for (const node of retained) {
1541
+ const element = elementsById.get(node.id);
1542
+ if (element) options.onElement(node.id, element);
1543
+ }
1544
+ if (typeof options.onText === "function") for (const node of retained) {
1545
+ const text = textsById.get(node.id);
1546
+ if (text) options.onText(node.id, text);
1547
+ }
1548
+ return {
1549
+ schema: "rea-ax-reconstruction/v1",
1550
+ frameUrl: root.location.href,
1551
+ rootId,
1552
+ nodes: retained,
1553
+ unresolvedRelations,
1554
+ limitations: [
1555
+ "No closed shadow DOM",
1556
+ "No native UA shadow subtree",
1557
+ "No Blink AX cache/layout fragments",
1558
+ "Native listbox active selection history is not exposed as a DOM property",
1559
+ "Ignored-node retention is an approximation",
1560
+ "addEventListener listeners cannot be enumerated by page JavaScript; clickable spans can be flattened incorrectly",
1561
+ "DOM paths are capture-local identities"
1562
+ ]
1563
+ };
1564
+ }
1565
+ /**
1566
+ * Estimate visual text runs for one connected DOM Text node. The returned
1567
+ * offsets are UTF-16 offsets in that node; ids are local to this invocation.
1568
+ * Serialize with `(${estimateInlineFragments.toString()})(textNode)`.
1569
+ * This is not an AX tree, an InlineTextBox implementation, or an AX eligibility
1570
+ * test. The caller must associate the node with an already identified parent.
1571
+ */
1572
+ function estimateInlineFragments(node) {
1573
+ const result = {
1574
+ kind: "dom-range-estimate",
1575
+ fragments: [],
1576
+ limitations: [
1577
+ "Range geometry does not expose Blink layout fragments or AX eligibility.",
1578
+ "CSS generated content, ellipsis and internal text are not reconstructed; case transforms are approximate and unsupported text-transform values are not applied.",
1579
+ "Bidi runs are inferred from geometry, not Unicode bidi levels; font fallback, ligatures, ruby, columns, vertical writing and grapheme geometry may split or merge differently.",
1580
+ "Whitespace and line-end spaces are approximated; geometry can include clipped or occluded text.",
1581
+ "Closed shadow roots and native control internals are excluded; button light DOM is estimated. A closed host and its light children cannot always be detected.",
1582
+ "Offsets and synthetic ids are local to this node and snapshot; no DOM or AX identity is implied."
1583
+ ],
1584
+ skipped: null
1585
+ };
1586
+ if (!node || node.nodeType !== 3 || !node.isConnected) {
1587
+ result.skipped = "not-connected-text";
1588
+ return result;
1589
+ }
1590
+ const root = node.getRootNode();
1591
+ if (root && root.host && root.mode !== "open") {
1592
+ result.skipped = "closed-shadow";
1593
+ return result;
1594
+ }
1595
+ const controls = /* @__PURE__ */ new Set([
1596
+ "input",
1597
+ "textarea",
1598
+ "select",
1599
+ "option",
1600
+ "optgroup",
1601
+ "meter",
1602
+ "progress",
1603
+ "output"
1604
+ ]);
1605
+ let element = node.parentElement || root.host;
1606
+ for (let e = element; e;) {
1607
+ if (controls.has(e.localName) || e.localName === "button" && e.getRootNode() !== root) {
1608
+ result.skipped = "native-control";
1609
+ return result;
1610
+ }
1611
+ if (e.hasAttribute("hidden") || e.hasAttribute("inert") || e.getAttribute("aria-hidden") === "true") {
1612
+ result.skipped = "hidden-or-inert";
1613
+ return result;
1614
+ }
1615
+ const style = getComputedStyle(e);
1616
+ if (style.display === "none" || style.contentVisibility === "hidden") {
1617
+ result.skipped = "not-rendered";
1618
+ return result;
1619
+ }
1620
+ e = e.assignedSlot || e.parentElement || e.getRootNode().host || null;
1621
+ }
1622
+ if (!element || getComputedStyle(element).visibility !== "visible") {
1623
+ result.skipped = "not-visible";
1624
+ return result;
1625
+ }
1626
+ const style = getComputedStyle(element);
1627
+ const preserve = /^(pre|pre-wrap|break-spaces)$/.test(style.whiteSpace);
1628
+ const preserveBreaks = preserve || style.whiteSpace === "pre-line";
1629
+ const vertical = /^(vertical|sideways)/.test(style.writingMode);
1630
+ const text = node.data;
1631
+ let language = "";
1632
+ for (let e = element; e; e = e.assignedSlot || e.parentElement || e.getRootNode().host || null) if (e.hasAttribute("lang")) {
1633
+ language = e.getAttribute("lang");
1634
+ break;
1635
+ }
1636
+ const mode = style.textTransform;
1637
+ if (/(^|\s)capitalize(\s|$)/.test(mode)) {
1638
+ result.skipped = "unsupported-text-transform";
1639
+ return result;
1640
+ }
1641
+ const changeCase = (s) => {
1642
+ try {
1643
+ if (mode === "uppercase") return s.toLocaleUpperCase(language || void 0);
1644
+ if (mode === "lowercase") return s.toLocaleLowerCase(language || void 0);
1645
+ } catch {
1646
+ if (mode === "uppercase") return s.toUpperCase();
1647
+ if (mode === "lowercase") return s.toLowerCase();
1648
+ }
1649
+ return s;
1650
+ };
1651
+ const transformed = changeCase(text);
1652
+ const caseTransformed = mode === "uppercase" || mode === "lowercase";
1653
+ const segments = typeof Intl.Segmenter === "function" ? [...new Intl.Segmenter(void 0, { granularity: "grapheme" }).segment(text)].map((x) => ({
1654
+ text: x.segment,
1655
+ start: x.index,
1656
+ end: x.index + x.segment.length
1657
+ })) : (() => {
1658
+ let pos = 0;
1659
+ return Array.from(text, (s) => {
1660
+ const start = pos;
1661
+ pos += s.length;
1662
+ return {
1663
+ text: s,
1664
+ start,
1665
+ end: pos
1666
+ };
1667
+ });
1668
+ })();
1669
+ const range = node.ownerDocument.createRange();
1670
+ let current = null, lastSpace = false, previousRect = null;
1671
+ const flush = () => {
1672
+ if (current && current.text) {
1673
+ current.id = `estimated-${result.fragments.length}`;
1674
+ result.fragments.push(current);
1675
+ }
1676
+ current = null;
1677
+ previousRect = null;
1678
+ };
1679
+ for (const part of segments) {
1680
+ if (preserveBreaks && part.text === "\n") {
1681
+ if (style.whiteSpace === "pre-line" && current?.text.endsWith(" ")) {
1682
+ const trailing = text.slice(current.start, part.start).match(/[\t\f ]+$/)?.[0];
1683
+ if (trailing) {
1684
+ current.text = current.text.replace(/ +$/, "");
1685
+ current.end -= trailing.length;
1686
+ }
1687
+ }
1688
+ flush();
1689
+ result.fragments.push({
1690
+ id: "",
1691
+ start: part.start,
1692
+ end: part.end,
1693
+ text: "\n",
1694
+ line: null,
1695
+ rect: null
1696
+ });
1697
+ lastSpace = false;
1698
+ continue;
1699
+ }
1700
+ const ws = /^[\t\n\f\r ]+$/.test(part.text);
1701
+ if (!preserve && ws && lastSpace) {
1702
+ if (current) current.end = part.end;
1703
+ continue;
1704
+ }
1705
+ lastSpace = !preserve && ws;
1706
+ range.setStart(node, part.start);
1707
+ range.setEnd(node, part.end);
1708
+ const rect = [...range.getClientRects()].find((r) => r.width > .01 && r.height > .01);
1709
+ const value = !preserve && ws ? " " : caseTransformed ? transformed.slice(changeCase(text.slice(0, part.start)).length, changeCase(text.slice(0, part.end)).length) : part.text;
1710
+ if (!rect) {
1711
+ if (ws && current) {
1712
+ if (!preserve && !current.text.endsWith(" ")) current.text += " ";
1713
+ current.end = part.end;
1714
+ }
1715
+ continue;
1716
+ }
1717
+ const line = vertical ? rect.left : rect.top;
1718
+ if (current && Math.abs(current.line - line) > 1) flush();
1719
+ if (current && previousRect) {
1720
+ if ((vertical ? Math.min(Math.abs(previousRect.bottom - rect.top), Math.abs(previousRect.top - rect.bottom)) : Math.min(Math.abs(previousRect.right - rect.left), Math.abs(previousRect.left - rect.right))) > 1) flush();
1721
+ }
1722
+ if (!current) current = {
1723
+ id: "",
1724
+ start: part.start,
1725
+ end: part.end,
1726
+ text: "",
1727
+ line,
1728
+ rect: {
1729
+ left: rect.left,
1730
+ top: rect.top,
1731
+ right: rect.right,
1732
+ bottom: rect.bottom
1733
+ }
1734
+ };
1735
+ current.text += value;
1736
+ current.end = part.end;
1737
+ current.rect.left = Math.min(current.rect.left, rect.left);
1738
+ current.rect.top = Math.min(current.rect.top, rect.top);
1739
+ current.rect.right = Math.max(current.rect.right, rect.right);
1740
+ current.rect.bottom = Math.max(current.rect.bottom, rect.bottom);
1741
+ previousRect = rect;
1742
+ }
1743
+ flush();
1744
+ range.detach();
1745
+ for (let start = 0; start < result.fragments.length;) {
1746
+ if (result.fragments[start].line === null) {
1747
+ start++;
1748
+ continue;
1749
+ }
1750
+ let end = start + 1;
1751
+ while (end < result.fragments.length && result.fragments[end].line !== null && Math.abs(result.fragments[end].line - result.fragments[start].line) <= 1) end++;
1752
+ const ordered = result.fragments.slice(start, end).sort((a, b) => vertical ? a.rect.top - b.rect.top : a.rect.left - b.rect.left);
1753
+ result.fragments.splice(start, end - start, ...ordered);
1754
+ start = end;
1755
+ }
1756
+ result.fragments.forEach((fragment, i) => {
1757
+ fragment.id = `estimated-${i}`;
1758
+ });
1759
+ return result;
1760
+ }
1761
+ var signature = (node, element) => {
1762
+ const { focused, ...properties } = node.properties || {};
1763
+ return JSON.stringify({
1764
+ path: node.domPath,
1765
+ role: node.role,
1766
+ name: node.name,
1767
+ description: node.description,
1768
+ ignored: node.ignored,
1769
+ value: node.value,
1770
+ properties,
1771
+ activation: element ? activation(element) : null
1772
+ });
1773
+ };
1774
+ function activation(element) {
1775
+ const attrs = [
1776
+ "href",
1777
+ "target",
1778
+ "download",
1779
+ "formaction",
1780
+ "formmethod",
1781
+ "formtarget",
1782
+ "formenctype",
1783
+ "formnovalidate",
1784
+ "type",
1785
+ "min",
1786
+ "max",
1787
+ "step"
1788
+ ];
1789
+ const form = element.form, view = element.ownerDocument.defaultView;
1790
+ const action = form ? Object.getOwnPropertyDescriptor(view.HTMLFormElement.prototype, "action").get.call(form) : null;
1791
+ return {
1792
+ element: attrs.map((name) => [name, element.getAttribute(name)]),
1793
+ resolvedHref: element.href || null,
1794
+ resolvedFormAction: element.formAction || null,
1795
+ form: form ? {
1796
+ attributes: [
1797
+ "action",
1798
+ "method",
1799
+ "target",
1800
+ "enctype",
1801
+ "novalidate"
1802
+ ].map((name) => [name, view.Element.prototype.getAttribute.call(form, name)]),
1803
+ action
1804
+ } : null
1805
+ };
1806
+ }
1807
+ function checkAriaReadOnly(element) {
1808
+ if ((element.getAttribute("aria-readonly") || "").trim().toLowerCase() === "true") throw new Error("blocked: element is read-only");
1809
+ }
1810
+ function ariaDisabled(element) {
1811
+ const value = element?.getAttribute("aria-disabled");
1812
+ return value !== null && value !== void 0 && value !== "" && !["false", "undefined"].includes(value.toLowerCase());
1813
+ }
1814
+ function unavailableOption(element) {
1815
+ const style = element.ownerDocument.defaultView.getComputedStyle(element);
1816
+ return element.disabled || element.hidden || ariaDisabled(element) || (element.getAttribute("aria-hidden") || "").trim().toLowerCase() === "true" || style.display === "none" || style.visibility === "hidden" || style.visibility === "collapse" || style.contentVisibility === "hidden" || Number(style.opacity) === 0;
1817
+ }
1818
+ var parent = (node) => node.assignedSlot || node.parentElement || node.getRootNode()?.host || null;
1819
+ function labelBindings(element) {
1820
+ const result = [];
1821
+ for (let node = element; node; node = parent(node)) if (node.localName === "label") {
1822
+ const control = node.control, checkable = control?.localName === "input" && ["checkbox", "radio"].includes(control.type);
1823
+ result.push({
1824
+ label: node,
1825
+ control,
1826
+ form: control?.form || null,
1827
+ activation: control ? JSON.stringify(activation(control)) : null,
1828
+ checked: checkable ? control.checked : null,
1829
+ indeterminate: checkable ? control.indeterminate : null
1830
+ });
1831
+ }
1832
+ return result;
1833
+ }
1834
+ function sameLabelBindings(before, after) {
1835
+ return before.length === after.length && before.every((binding, index) => binding.label === after[index].label && binding.control === after[index].control && binding.form === after[index].form && binding.activation === after[index].activation && binding.checked === after[index].checked && binding.indeterminate === after[index].indeterminate);
1836
+ }
1837
+ var referenceAttributes = [
1838
+ ["aria-labelledby", "ariaLabelledByElements"],
1839
+ ["aria-labeledby", null],
1840
+ ["aria-describedby", "ariaDescribedByElements"],
1841
+ ["aria-controls", "ariaControlsElements"],
1842
+ ["aria-details", "ariaDetailsElements"],
1843
+ ["aria-errormessage", "ariaErrorMessageElements"],
1844
+ ["aria-flowto", "ariaFlowToElements"],
1845
+ ["aria-owns", "ariaOwnsElements"],
1846
+ ["aria-activedescendant", "ariaActiveDescendantElement"]
1847
+ ];
1848
+ function referenceBindings(element) {
1849
+ const result = [];
1850
+ for (const [attribute, property] of referenceAttributes) {
1851
+ if (!element.hasAttribute(attribute)) continue;
1852
+ const raw = element.getAttribute(attribute), reflected = property ? element[property] : void 0;
1853
+ const targets = reflected !== void 0 && reflected !== null ? attribute === "aria-activedescendant" ? [reflected] : [...reflected] : (raw || "").split(/[\t\n\f\r ]+/).filter(Boolean).map((id) => element.getRootNode()?.getElementById?.(id) || null);
1854
+ result.push({
1855
+ attribute,
1856
+ raw,
1857
+ targets
1858
+ });
1859
+ }
1860
+ return result;
1861
+ }
1862
+ function sameReferenceBindings(before, after) {
1863
+ return before.length === after.length && before.every((entry, index) => entry.attribute === after[index].attribute && entry.raw === after[index].raw && entry.targets.length === after[index].targets.length && entry.targets.every((target, i) => target === after[index].targets[i]));
1864
+ }
1865
+ var editableInputTypes = /* @__PURE__ */ new Set([
1866
+ "text",
1867
+ "search",
1868
+ "email",
1869
+ "tel",
1870
+ "url",
1871
+ "password",
1872
+ "number",
1873
+ "date",
1874
+ "month",
1875
+ "week",
1876
+ "time",
1877
+ "datetime-local"
1878
+ ]);
1879
+ var sanitizedInputTypes = /* @__PURE__ */ new Set([
1880
+ "number",
1881
+ "date",
1882
+ "month",
1883
+ "week",
1884
+ "time",
1885
+ "datetime-local"
1886
+ ]);
1887
+ function checkUsable(element, doc) {
1888
+ if (!element.isConnected || element.ownerDocument !== doc) throw new Error("stale_node: element is no longer in this document");
1889
+ for (let node = element; node; node = parent(node)) {
1890
+ const style = doc.defaultView.getComputedStyle(node);
1891
+ if (node.hidden || node.inert || style.display === "none" || node === element && (style.visibility === "hidden" || style.visibility === "collapse") || style.contentVisibility === "hidden" || Number(style.opacity) === 0) throw new Error("blocked: element is hidden or inert");
1892
+ if (ariaDisabled(node)) throw new Error("blocked: element is aria-disabled");
1893
+ }
1894
+ if (element.matches(":disabled")) throw new Error("blocked: element is disabled");
1895
+ }
1896
+ function checkFrameAncestors(doc) {
1897
+ for (let view = doc.defaultView; view !== view.top;) {
1898
+ let frame;
1899
+ try {
1900
+ frame = view.frameElement;
1901
+ } catch {
1902
+ throw new Error("blocked: frame ancestor is not accessible");
1903
+ }
1904
+ if (!frame) throw new Error("blocked: frame ancestor is not accessible");
1905
+ checkUsable(frame, frame.ownerDocument);
1906
+ for (let node = frame; node; node = parent(node)) if ((node.getAttribute("aria-hidden") || "").trim().toLowerCase() === "true") throw new Error("blocked: frame ancestor is aria-hidden");
1907
+ view = frame.ownerDocument.defaultView;
1908
+ }
1909
+ }
1910
+ function deepestAt(root, x, y) {
1911
+ let hit = root.elementFromPoint(x, y);
1912
+ while (hit?.shadowRoot) {
1913
+ const deeper = hit.shadowRoot.elementFromPoint(x, y);
1914
+ if (!deeper || deeper === hit) break;
1915
+ hit = deeper;
1916
+ }
1917
+ return hit;
1918
+ }
1919
+ function checkHit(element, doc, point, allowedOccluder) {
1920
+ let view = doc.defaultView;
1921
+ const rect = element.getBoundingClientRect(), left = Math.max(0, rect.left), right = Math.min(view.innerWidth, rect.right), top = Math.max(0, rect.top), bottom = Math.min(view.innerHeight, rect.bottom);
1922
+ if (right <= left || bottom <= top) throw new Error("blocked: element has no visible intersection with viewport; scroll first");
1923
+ let x = point?.x ?? (left + right) / 2, y = point?.y ?? (top + bottom) / 2;
1924
+ if (x < left || x >= right || y < top || y >= bottom) throw new Error("blocked: point is outside the visible element");
1925
+ const hit = deepestAt(doc, x, y);
1926
+ let found = false;
1927
+ for (let current = hit; current; current = parent(current)) if (current === element || current === allowedOccluder) {
1928
+ found = true;
1929
+ break;
1930
+ }
1931
+ if (!found) throw new Error("blocked: element is obscured at the requested point");
1932
+ while (view !== view.top) {
1933
+ let frame;
1934
+ try {
1935
+ frame = view.frameElement;
1936
+ } catch {
1937
+ throw new Error("blocked: frame ancestor is not accessible");
1938
+ }
1939
+ if (!frame) throw new Error("blocked: frame ancestor is not accessible");
1940
+ const outer = frame.ownerDocument.defaultView;
1941
+ for (let ancestor = frame; ancestor; ancestor = parent(ancestor)) {
1942
+ const style = outer.getComputedStyle(ancestor);
1943
+ if (style.transform !== "none" || !["1", "normal"].includes(style.zoom)) throw new Error("blocked: transformed frame requires trusted browser input");
1944
+ }
1945
+ const bounds = frame.getBoundingClientRect();
1946
+ if (Math.abs(bounds.width - frame.offsetWidth) > 1 || Math.abs(bounds.height - frame.offsetHeight) > 1) throw new Error("blocked: scaled frame requires trusted browser input");
1947
+ x += bounds.left + frame.clientLeft;
1948
+ y += bounds.top + frame.clientTop;
1949
+ if (x < 0 || y < 0 || x >= outer.innerWidth || y >= outer.innerHeight || deepestAt(frame.ownerDocument, x, y) !== frame) throw new Error("blocked: frame is obscured or outside viewport");
1950
+ view = outer;
1951
+ }
1952
+ }
1953
+ function createPageAgent({ document: doc = globalThis.document, maxNodes = 5e4, maxDurationMs = 5e3 } = {}) {
1954
+ if (!doc?.defaultView || doc.defaultView.document !== doc) throw new Error("invalid: document must be an active same-origin document");
1955
+ if (!Number.isInteger(maxNodes) || maxNodes < 1 || maxNodes > 25e4 || !Number.isInteger(maxDurationMs) || maxDurationMs < 1 || maxDurationMs > 3e4) throw new Error("invalid: capture budget is out of range");
1956
+ let closed = false, current = null, sequence = 0, gestureActive = false;
1957
+ const waits = /* @__PURE__ */ new Set();
1958
+ const bytes = /* @__PURE__ */ new Uint8Array(12);
1959
+ crypto.getRandomValues(bytes);
1960
+ const sessionId = Array.from(bytes, (n) => n.toString(16).padStart(2, "0")).join("");
1961
+ function ensure() {
1962
+ if (closed) throw new Error("session_closed: agent has been destroyed");
1963
+ try {
1964
+ if (!doc.defaultView || doc.defaultView.document !== doc) throw new Error();
1965
+ } catch {
1966
+ throw new Error("stale_document: frame navigated or became inaccessible");
1967
+ }
1968
+ }
1969
+ function capture() {
1970
+ const elements = /* @__PURE__ */ new Map(), texts = /* @__PURE__ */ new Map();
1971
+ let visited = 0;
1972
+ const start = performance.now();
1973
+ const checkBudget = () => {
1974
+ if (++visited > maxNodes || performance.now() - start > maxDurationMs) throw new Error("budget_exceeded: capture exceeded its node or time limit");
1975
+ };
1976
+ const tree = reconstructAXTree(doc, {
1977
+ checkBudget,
1978
+ onElement: (id, element) => elements.set(id, element),
1979
+ onText: (id, text) => texts.set(id, text)
1980
+ });
1981
+ if (performance.now() - start > maxDurationMs) throw new Error("budget_exceeded: capture exceeded its time limit");
1982
+ return {
1983
+ tree,
1984
+ elements,
1985
+ texts
1986
+ };
1987
+ }
1988
+ function snapshot() {
1989
+ ensure();
1990
+ if (gestureActive) throw new Error("gesture_active: wait for the drag to finish");
1991
+ const { tree, elements, texts } = capture(), snapshotId = `${sessionId}:${++sequence}`, labels = /* @__PURE__ */ new Map(), references = /* @__PURE__ */ new Map();
1992
+ for (const [id, element] of elements) {
1993
+ const bindings = labelBindings(element);
1994
+ if (bindings.length) labels.set(id, bindings);
1995
+ const refs = referenceBindings(element);
1996
+ if (refs.length) references.set(id, refs);
1997
+ }
1998
+ current = {
1999
+ snapshotId,
2000
+ href: doc.location.href,
2001
+ treeNodes: tree.nodes,
2002
+ elements,
2003
+ texts,
2004
+ labels,
2005
+ references,
2006
+ visualTargets: /* @__PURE__ */ new Map(),
2007
+ textValues: new Map([...texts].map(([id, text]) => [id, text.data])),
2008
+ forms: new Map([...elements].map(([id, element]) => [id, element.form || null])),
2009
+ nodes: new Map(tree.nodes.map((node) => [node.id, signature(node, elements.get(node.id))]))
2010
+ };
2011
+ return {
2012
+ schemaVersion: "page-agent/v1",
2013
+ snapshotId,
2014
+ tree,
2015
+ limitations: [
2016
+ "Page-only approximation; not the native Chromium accessibility tree.",
2017
+ "Actions use synthetic DOM events, not trusted user input.",
2018
+ "Frames are separate sessions; cross-origin documents require independent integration."
2019
+ ]
2020
+ };
2021
+ }
2022
+ function tree({ includeIgnored = false } = {}) {
2023
+ const result = snapshot(), children = /* @__PURE__ */ new Map();
2024
+ for (const node of result.tree.nodes) {
2025
+ const list = children.get(node.parentId) || [];
2026
+ list.push(node);
2027
+ children.set(node.parentId, list);
2028
+ }
2029
+ const lines = [];
2030
+ function visit(parentId, depth) {
2031
+ for (const node of children.get(parentId) || []) {
2032
+ const visible = includeIgnored || !node.ignored;
2033
+ if (visible) lines.push(`${" ".repeat(depth)}[${node.id}] ${node.role}${node.name ? ` ${JSON.stringify(node.name)}` : ""}${node.ignored ? " (ignorado)" : ""}`);
2034
+ visit(node.id, depth + (visible ? 1 : 0));
2035
+ }
2036
+ }
2037
+ visit(null, 0);
2038
+ return {
2039
+ schemaVersion: result.schemaVersion,
2040
+ snapshotId: result.snapshotId,
2041
+ lines,
2042
+ limitations: result.limitations
2043
+ };
2044
+ }
2045
+ function query({ role, name } = {}) {
2046
+ if (typeof role !== "string" || !role || !(name === void 0 || typeof name === "string")) throw new Error("invalid: role is required and name must be a string");
2047
+ const result = snapshot();
2048
+ return {
2049
+ snapshotId: result.snapshotId,
2050
+ nodes: result.tree.nodes.filter((node) => !node.ignored && node.role === role && (name === void 0 || node.name === name))
2051
+ };
2052
+ }
2053
+ function waitFor({ role, name, timeoutMs = 5e3, intervalMs = 100, signal } = {}) {
2054
+ ensure();
2055
+ if (!Number.isInteger(timeoutMs) || timeoutMs < 0 || timeoutMs > 6e4 || !Number.isInteger(intervalMs) || intervalMs < 20 || intervalMs > 1e3) throw new Error("invalid: wait timeout or interval");
2056
+ if (signal && (typeof signal.addEventListener !== "function" || typeof signal.aborted !== "boolean")) throw new Error("invalid: signal must be an AbortSignal");
2057
+ return new Promise((resolve, reject) => {
2058
+ let timer, finished = false;
2059
+ const started = performance.now();
2060
+ const finish = (error, result) => {
2061
+ if (finished) return;
2062
+ finished = true;
2063
+ clearTimeout(timer);
2064
+ signal?.removeEventListener("abort", abort);
2065
+ waits.delete(cancel);
2066
+ error ? reject(error) : resolve(result);
2067
+ };
2068
+ const abort = () => finish(/* @__PURE__ */ new Error("aborted: wait cancelled")), cancel = () => finish(/* @__PURE__ */ new Error("session_closed: agent has been destroyed"));
2069
+ const poll = () => {
2070
+ try {
2071
+ const result = query({
2072
+ role,
2073
+ name
2074
+ });
2075
+ if (result.nodes.length) {
2076
+ finish(null, result);
2077
+ return;
2078
+ }
2079
+ const remaining = timeoutMs - (performance.now() - started);
2080
+ if (remaining <= 0) {
2081
+ finish(/* @__PURE__ */ new Error("timeout: element not found"));
2082
+ return;
2083
+ }
2084
+ timer = setTimeout(poll, Math.min(intervalMs, remaining));
2085
+ } catch (error) {
2086
+ finish(error);
2087
+ }
2088
+ };
2089
+ waits.add(cancel);
2090
+ signal?.addEventListener("abort", abort, { once: true });
2091
+ if (signal?.aborted) abort();
2092
+ else poll();
2093
+ });
2094
+ }
2095
+ function resolve({ snapshotId, nodeId }) {
2096
+ ensure();
2097
+ if (gestureActive) throw new Error("gesture_active: wait for the drag to finish");
2098
+ if (!current || snapshotId !== current.snapshotId || doc.location.href !== current.href) throw new Error("stale_snapshot: request a new snapshot");
2099
+ const visual = current.visualTargets.get(nodeId);
2100
+ if (visual) {
2101
+ const element = visual.element;
2102
+ checkUsable(element, doc);
2103
+ checkFrameAncestors(doc);
2104
+ const rect = element.getBoundingClientRect(), attrs = JSON.stringify([...element.attributes].map((a) => [a.name, a.value]));
2105
+ if (element.parentNode !== visual.parent || attrs !== visual.attrs || (element.form || null) !== visual.form || JSON.stringify(activation(element)) !== visual.activation || !sameReferenceBindings(visual.references, referenceBindings(element)) || !sameLabelBindings(visual.labels, labelBindings(element)) || [
2106
+ rect.x,
2107
+ rect.y,
2108
+ rect.width,
2109
+ rect.height
2110
+ ].some((v, i) => v !== visual.rect[i]) || deepestAt(doc, visual.x, visual.y) !== element) throw new Error("stale_node: visual target changed");
2111
+ return element;
2112
+ }
2113
+ const element = current.elements.get(nodeId), expected = current.nodes.get(nodeId);
2114
+ if (!element || !expected) throw new Error("unsupported: node has no actionable DOM element");
2115
+ checkUsable(element, doc);
2116
+ checkFrameAncestors(doc);
2117
+ if (!sameReferenceBindings(current.references.get(nodeId) || [], referenceBindings(element))) throw new Error("stale_node: accessible references changed");
2118
+ if (!sameLabelBindings(current.labels.get(nodeId) || [], labelBindings(element))) throw new Error("stale_node: associated label control changed");
2119
+ const live = capture();
2120
+ let liveId;
2121
+ for (const [id, candidate] of live.elements) if (candidate === element) {
2122
+ liveId = id;
2123
+ break;
2124
+ }
2125
+ const node = live.tree.nodes.find((item) => item.id === liveId);
2126
+ if (!node || node.ignored || current.forms.get(nodeId) !== (element.form || null) || signature(node, element) !== expected) throw new Error("stale_node: target semantics or position changed");
2127
+ return element;
2128
+ }
2129
+ function textFragments({ snapshotId, nodeId }) {
2130
+ ensure();
2131
+ if (!current || snapshotId !== current.snapshotId || doc.location.href !== current.href) throw new Error("stale_snapshot: request a new snapshot");
2132
+ const text = current.texts.get(nodeId), expected = current.nodes.get(nodeId);
2133
+ if (!text || !expected) throw new Error("unsupported: node is not a retained DOM text node");
2134
+ if (text.data !== current.textValues.get(nodeId)) throw new Error("stale_node: text changed");
2135
+ if (text.length > 2048) throw new Error("budget_exceeded: text exceeds 2048 UTF-16 code units");
2136
+ const live = capture();
2137
+ let liveId;
2138
+ for (const [id, candidate] of live.texts) if (candidate === text) {
2139
+ liveId = id;
2140
+ break;
2141
+ }
2142
+ const node = live.tree.nodes.find((item) => item.id === liveId);
2143
+ if (!node || node.ignored || signature(node) !== expected) throw new Error("stale_node: text semantics or position changed");
2144
+ return estimateInlineFragments(text);
2145
+ }
2146
+ function focusForEditing(element, request) {
2147
+ element.focus({ preventScroll: true });
2148
+ if (doc.activeElement !== element && !element.matches(":focus")) throw new Error("blocked: focus moved away from target");
2149
+ resolve(request);
2150
+ checkHit(element, doc);
2151
+ }
2152
+ function checkClickTarget(element) {
2153
+ checkAriaReadOnly(element);
2154
+ for (let node = element; node; node = parent(node)) if (node.localName === "label" && node.control) {
2155
+ checkUsable(node.control, doc);
2156
+ checkAriaReadOnly(node.control);
2157
+ }
2158
+ checkHit(element, doc);
2159
+ }
2160
+ function click(request) {
2161
+ const element = resolve(request);
2162
+ checkClickTarget(element);
2163
+ if (typeof element.click !== "function") throw new Error("unsupported: target cannot be clicked");
2164
+ element.click();
2165
+ return {
2166
+ dispatched: true,
2167
+ trusted: false
2168
+ };
2169
+ }
2170
+ function doubleClick(request) {
2171
+ const element = resolve(request);
2172
+ checkClickTarget(element);
2173
+ const view = doc.defaultView, coords = point(element);
2174
+ const initialRect = element.getBoundingClientRect(), bounds = [
2175
+ initialRect.x,
2176
+ initialRect.y,
2177
+ initialRect.width,
2178
+ initialRect.height
2179
+ ];
2180
+ const revalidate = () => {
2181
+ if (resolve(request) !== element) throw new Error("stale_node: double-click target changed");
2182
+ const rect = element.getBoundingClientRect();
2183
+ if ([
2184
+ rect.x,
2185
+ rect.y,
2186
+ rect.width,
2187
+ rect.height
2188
+ ].some((value, index) => value !== bounds[index])) throw new Error("stale_node: double-click target moved");
2189
+ checkClickTarget(element);
2190
+ checkHit(element, doc, {
2191
+ x: coords.clientX,
2192
+ y: coords.clientY
2193
+ });
2194
+ };
2195
+ const fire = (type, detail, buttons, pointer = false) => {
2196
+ const Constructor = pointer ? view.PointerEvent : view.MouseEvent;
2197
+ return element.dispatchEvent(new Constructor(type, {
2198
+ ...coords,
2199
+ view,
2200
+ detail,
2201
+ button: 0,
2202
+ buttons,
2203
+ bubbles: true,
2204
+ cancelable: true,
2205
+ composed: true,
2206
+ pointerId: 1,
2207
+ pointerType: "mouse",
2208
+ isPrimary: true
2209
+ }));
2210
+ };
2211
+ let pressed = false, mousePressed = false;
2212
+ try {
2213
+ for (let detail = 1; detail <= 2; detail++) {
2214
+ if (detail === 2) revalidate();
2215
+ pressed = true;
2216
+ fire("pointerdown", detail, 1, true);
2217
+ revalidate();
2218
+ mousePressed = true;
2219
+ fire("mousedown", detail, 1);
2220
+ revalidate();
2221
+ fire("pointerup", detail, 0, true);
2222
+ fire("mouseup", detail, 0);
2223
+ pressed = false;
2224
+ mousePressed = false;
2225
+ revalidate();
2226
+ fire("click", detail, 0);
2227
+ }
2228
+ revalidate();
2229
+ fire("dblclick", 2, 0);
2230
+ return {
2231
+ dispatched: true,
2232
+ trusted: false
2233
+ };
2234
+ } finally {
2235
+ if (pressed) {
2236
+ const target = element.isConnected ? element : doc;
2237
+ target.dispatchEvent(new view.PointerEvent("pointercancel", {
2238
+ ...coords,
2239
+ view,
2240
+ bubbles: true,
2241
+ composed: true,
2242
+ pointerId: 1,
2243
+ pointerType: "mouse",
2244
+ isPrimary: true
2245
+ }));
2246
+ if (mousePressed) target.dispatchEvent(new view.MouseEvent("mouseup", {
2247
+ ...coords,
2248
+ view,
2249
+ button: 0,
2250
+ buttons: 0,
2251
+ bubbles: true,
2252
+ cancelable: true,
2253
+ composed: true
2254
+ }));
2255
+ }
2256
+ }
2257
+ }
2258
+ function dispatchInputAndChange(element, valueStillExpected) {
2259
+ const form = element.form || null, parentNode = element.parentNode, href = doc.location.href, editable = element.isContentEditable;
2260
+ const attributes = [
2261
+ "id",
2262
+ "name",
2263
+ "type",
2264
+ "form",
2265
+ "contenteditable"
2266
+ ].map((name) => element.getAttribute(name));
2267
+ const activationBefore = JSON.stringify(activation(element)), labelsBefore = labelBindings(element), referencesBefore = referenceBindings(element);
2268
+ element.dispatchEvent(new doc.defaultView.Event("input", {
2269
+ bubbles: true,
2270
+ composed: true
2271
+ }));
2272
+ try {
2273
+ ensure();
2274
+ if (doc.location.href !== href || element.parentNode !== parentNode || (element.form || null) !== form || element.isContentEditable !== editable || attributes.some((value, index) => element.getAttribute([
2275
+ "id",
2276
+ "name",
2277
+ "type",
2278
+ "form",
2279
+ "contenteditable"
2280
+ ][index]) !== value) || JSON.stringify(activation(element)) !== activationBefore) return false;
2281
+ if (!sameReferenceBindings(referencesBefore, referenceBindings(element))) return false;
2282
+ if (!sameLabelBindings(labelsBefore, labelBindings(element))) return false;
2283
+ checkUsable(element, doc);
2284
+ checkFrameAncestors(doc);
2285
+ checkAriaReadOnly(element);
2286
+ if (element.readOnly === true) return false;
2287
+ if (!valueStillExpected()) return false;
2288
+ } catch {
2289
+ return false;
2290
+ }
2291
+ element.dispatchEvent(new doc.defaultView.Event("change", { bubbles: true }));
2292
+ return true;
2293
+ }
2294
+ function fill(request) {
2295
+ const element = resolve(request);
2296
+ if (typeof request.value !== "string" || request.value.length > 1e6) throw new Error("invalid: value must be a string of at most 1000000 characters");
2297
+ checkHit(element, doc);
2298
+ checkAriaReadOnly(element);
2299
+ if (element.matches(":read-only") && !element.isContentEditable) throw new Error("blocked: element is read-only");
2300
+ const tag = element.localName, type = tag === "input" ? element.type : "";
2301
+ if (!(tag === "input" && editableInputTypes.has(type) || tag === "textarea" || element.isContentEditable)) throw new Error("unsupported: element is not a supported editable control");
2302
+ if (tag === "input" && sanitizedInputTypes.has(type)) {
2303
+ const probe = doc.createElement("input");
2304
+ probe.type = type;
2305
+ Object.getOwnPropertyDescriptor(doc.defaultView.HTMLInputElement.prototype, "value").set.call(probe, request.value);
2306
+ if (probe.value !== request.value) throw new Error("invalid: value would be sanitized");
2307
+ }
2308
+ focusForEditing(element, request);
2309
+ checkAriaReadOnly(element);
2310
+ if (element.matches(":read-only") && !element.isContentEditable) throw new Error("blocked: element is read-only");
2311
+ if (tag === "input" && editableInputTypes.has(type)) Object.getOwnPropertyDescriptor(doc.defaultView.HTMLInputElement.prototype, "value").set.call(element, request.value);
2312
+ else if (tag === "textarea") Object.getOwnPropertyDescriptor(doc.defaultView.HTMLTextAreaElement.prototype, "value").set.call(element, request.value);
2313
+ else if (element.isContentEditable) element.textContent = request.value;
2314
+ else throw new Error("blocked: element is no longer editable");
2315
+ const changeDispatched = dispatchInputAndChange(element, () => element.isContentEditable ? element.textContent === request.value : element.value === request.value);
2316
+ const actual = element.isContentEditable ? element.textContent : element.value;
2317
+ return {
2318
+ dispatched: true,
2319
+ trusted: false,
2320
+ applied: element.isConnected && actual === request.value,
2321
+ changeDispatched
2322
+ };
2323
+ }
2324
+ function select(request) {
2325
+ const element = resolve(request);
2326
+ if (element.localName !== "select") throw new Error("unsupported: select requires a native select control");
2327
+ checkAriaReadOnly(element);
2328
+ const values = element.multiple ? request.values : [request.value];
2329
+ if (!Array.isArray(values) || !element.multiple && values.length !== 1 || values.length > 1e4 || values.some((value) => typeof value !== "string") || values.reduce((sum, value) => sum + value.length, 0) > 1e6 || new Set(values).size !== values.length) throw new Error("invalid: provide unique option values within size limits");
2330
+ checkHit(element, doc);
2331
+ focusForEditing(element, request);
2332
+ checkAriaReadOnly(element);
2333
+ const options = [...element.options], desired = new Set(values);
2334
+ const counts = new Map(values.map((value) => [value, 0]));
2335
+ for (const option of options) if (counts.has(option.value)) counts.set(option.value, counts.get(option.value) + 1);
2336
+ if ([...counts.values()].some((count) => count !== 1)) throw new Error("invalid: each value must identify exactly one option");
2337
+ const changed = options.filter((option) => option.selected !== desired.has(option.value));
2338
+ for (const option of changed) if (unavailableOption(option) || option.parentElement?.localName === "optgroup" && unavailableOption(option.parentElement)) throw new Error("blocked: option is hidden or disabled");
2339
+ if (options.every((option) => option.selected === desired.has(option.value))) return {
2340
+ dispatched: false,
2341
+ applied: true
2342
+ };
2343
+ for (const option of options) option.selected = desired.has(option.value);
2344
+ const valuesBefore = options.map((option) => option.value);
2345
+ return {
2346
+ dispatched: true,
2347
+ changeDispatched: dispatchInputAndChange(element, () => element.options.length === options.length && options.every((option, index) => element.options[index] === option && option.value === valuesBefore[index] && option.selected === desired.has(option.value)) && changed.every((option) => !unavailableOption(option) && !(option.parentElement?.localName === "optgroup" && unavailableOption(option.parentElement)))),
2348
+ applied: element.isConnected && element.options.length === options.length && options.every((option) => option.isConnected && option.closest("select") === element && option.selected === desired.has(option.value))
2349
+ };
2350
+ }
2351
+ function setChecked(request) {
2352
+ const element = resolve(request);
2353
+ if (element.localName !== "input" || !["checkbox", "radio"].includes(element.type)) throw new Error("unsupported: setChecked requires a native checkbox or radio");
2354
+ checkAriaReadOnly(element);
2355
+ if (typeof request.checked !== "boolean") throw new Error("invalid: checked must be boolean");
2356
+ if (element.type === "radio" && !request.checked) throw new Error("unsupported: a radio can only be selected");
2357
+ checkHit(element, doc);
2358
+ focusForEditing(element, request);
2359
+ checkAriaReadOnly(element);
2360
+ if (element.checked === request.checked) return {
2361
+ dispatched: false,
2362
+ applied: true
2363
+ };
2364
+ element.click();
2365
+ return {
2366
+ dispatched: true,
2367
+ applied: element.isConnected && element.ownerDocument === doc && element.checked === request.checked
2368
+ };
2369
+ }
2370
+ function setRange(request) {
2371
+ const element = resolve(request);
2372
+ if (element.localName !== "input" || element.type !== "range") throw new Error("unsupported: setRange requires a native range input");
2373
+ checkAriaReadOnly(element);
2374
+ if (typeof request.value !== "number" || !Number.isFinite(request.value)) throw new Error("invalid: range value must be a finite number");
2375
+ const probe = doc.createElement("input");
2376
+ probe.type = "range";
2377
+ for (const name of [
2378
+ "min",
2379
+ "max",
2380
+ "step",
2381
+ "value"
2382
+ ]) if (element.hasAttribute(name)) probe.setAttribute(name, element.getAttribute(name));
2383
+ probe.valueAsNumber = request.value;
2384
+ if (probe.valueAsNumber !== request.value) throw new Error("invalid: range value would be clamped or rounded");
2385
+ checkHit(element, doc);
2386
+ focusForEditing(element, request);
2387
+ checkAriaReadOnly(element);
2388
+ if (element.valueAsNumber === request.value) return {
2389
+ dispatched: false,
2390
+ applied: true
2391
+ };
2392
+ Object.getOwnPropertyDescriptor(doc.defaultView.HTMLInputElement.prototype, "valueAsNumber").set.call(element, request.value);
2393
+ return {
2394
+ dispatched: true,
2395
+ changeDispatched: dispatchInputAndChange(element, () => element.valueAsNumber === request.value),
2396
+ applied: element.isConnected && element.ownerDocument === doc && element.valueAsNumber === request.value
2397
+ };
2398
+ }
2399
+ function key(request) {
2400
+ const element = resolve(request);
2401
+ if (typeof request.key !== "string" || !request.key || request.key.length > 64 || !(request.code === void 0 || typeof request.code === "string" && request.code.length <= 64)) throw new Error("invalid: key and code must be short strings");
2402
+ checkAriaReadOnly(element);
2403
+ for (const name of [
2404
+ "ctrlKey",
2405
+ "altKey",
2406
+ "shiftKey",
2407
+ "metaKey"
2408
+ ]) if (request[name] !== void 0 && typeof request[name] !== "boolean") throw new Error(`invalid: ${name} must be boolean`);
2409
+ checkHit(element, doc);
2410
+ focusForEditing(element, request);
2411
+ checkAriaReadOnly(element);
2412
+ const init = {
2413
+ key: request.key,
2414
+ code: request.code || "",
2415
+ ctrlKey: request.ctrlKey === true,
2416
+ altKey: request.altKey === true,
2417
+ shiftKey: request.shiftKey === true,
2418
+ metaKey: request.metaKey === true,
2419
+ bubbles: true,
2420
+ cancelable: true,
2421
+ composed: true
2422
+ };
2423
+ const accepted = element.dispatchEvent(new doc.defaultView.KeyboardEvent("keydown", init));
2424
+ const keyupDispatched = element.isConnected && (doc.activeElement === element || element.matches(":focus"));
2425
+ if (keyupDispatched) element.dispatchEvent(new doc.defaultView.KeyboardEvent("keyup", init));
2426
+ return {
2427
+ dispatched: true,
2428
+ trusted: false,
2429
+ defaultPrevented: !accepted,
2430
+ keyupDispatched,
2431
+ nativeDefault: false
2432
+ };
2433
+ }
2434
+ function point(element) {
2435
+ const rect = element.getBoundingClientRect(), view = doc.defaultView;
2436
+ const left = Math.max(0, rect.left), right = Math.min(view.innerWidth, rect.right), top = Math.max(0, rect.top), bottom = Math.min(view.innerHeight, rect.bottom);
2437
+ return {
2438
+ clientX: (left + right) / 2,
2439
+ clientY: (top + bottom) / 2
2440
+ };
2441
+ }
2442
+ function targetAt({ snapshotId, x, y } = {}) {
2443
+ ensure();
2444
+ if (!current || snapshotId !== current.snapshotId || doc.location.href !== current.href) throw new Error("stale_snapshot: request new snapshot");
2445
+ if (!Number.isFinite(x) || !Number.isFinite(y) || x < 0 || y < 0 || x >= doc.defaultView.innerWidth || y >= doc.defaultView.innerHeight) throw new Error("invalid: coordinates must be inside viewport");
2446
+ if (current.visualTargets.size >= maxNodes) throw new Error("budget_exceeded: too many visual targets");
2447
+ const element = deepestAt(doc, x, y);
2448
+ if (!element) throw new Error("unsupported: no element at coordinates");
2449
+ checkUsable(element, doc);
2450
+ checkFrameAncestors(doc);
2451
+ const rect = element.getBoundingClientRect(), nodeId = `v${current.visualTargets.size + 1}`;
2452
+ current.visualTargets.set(nodeId, {
2453
+ element,
2454
+ parent: element.parentNode,
2455
+ attrs: JSON.stringify([...element.attributes].map((a) => [a.name, a.value])),
2456
+ form: element.form || null,
2457
+ activation: JSON.stringify(activation(element)),
2458
+ references: referenceBindings(element),
2459
+ labels: labelBindings(element),
2460
+ rect: [
2461
+ rect.x,
2462
+ rect.y,
2463
+ rect.width,
2464
+ rect.height
2465
+ ],
2466
+ x,
2467
+ y
2468
+ });
2469
+ return {
2470
+ snapshotId,
2471
+ nodeId,
2472
+ tag: element.localName,
2473
+ role: element.getAttribute("role"),
2474
+ label: element.getAttribute("aria-label"),
2475
+ bounds: {
2476
+ x: rect.x,
2477
+ y: rect.y,
2478
+ width: rect.width,
2479
+ height: rect.height
2480
+ }
2481
+ };
2482
+ }
2483
+ function visualSurfaces({ snapshotId } = {}) {
2484
+ ensure();
2485
+ if (!current || snapshotId !== current.snapshotId || doc.location.href !== current.href) throw new Error("stale_snapshot: request new snapshot");
2486
+ const ids = new Map([...current.elements].map(([id, element]) => [element, id])), surfaces = [];
2487
+ let visited = 0;
2488
+ const start = performance.now();
2489
+ const visit = (root) => {
2490
+ for (const element of root.querySelectorAll("*")) {
2491
+ if (++visited > maxNodes || performance.now() - start > maxDurationMs) throw new Error("budget_exceeded: visual surface scan exceeded its limits");
2492
+ if (element.localName === "canvas" || element.localName === "svg" || element.getAttribute("role") === "application") {
2493
+ const rect = element.getBoundingClientRect(), style = doc.defaultView.getComputedStyle(element);
2494
+ if (rect.width > 0 && rect.height > 0 && style.display !== "none" && style.visibility !== "hidden") surfaces.push({
2495
+ nodeId: ids.get(element) ?? null,
2496
+ tag: element.localName,
2497
+ role: element.getAttribute("role"),
2498
+ label: element.getAttribute("aria-label"),
2499
+ bounds: {
2500
+ x: rect.x,
2501
+ y: rect.y,
2502
+ width: rect.width,
2503
+ height: rect.height
2504
+ },
2505
+ pointerEvents: style.pointerEvents
2506
+ });
2507
+ }
2508
+ if (element.shadowRoot) visit(element.shadowRoot);
2509
+ }
2510
+ };
2511
+ visit(doc);
2512
+ return surfaces;
2513
+ }
2514
+ function draggableCandidates({ snapshotId } = {}) {
2515
+ ensure();
2516
+ if (!current || snapshotId !== current.snapshotId || doc.location.href !== current.href) throw new Error("stale_snapshot: request new snapshot");
2517
+ const results = [];
2518
+ let visited = 0;
2519
+ const start = performance.now();
2520
+ for (const node of current.treeNodes) {
2521
+ if (++visited > maxNodes || performance.now() - start > maxDurationMs) throw new Error("budget_exceeded: draggable scan exceeded its limits");
2522
+ const element = current.elements.get(node.id);
2523
+ if (!element || node.ignored) continue;
2524
+ const hints = [];
2525
+ if (element.draggable) hints.push("draggable");
2526
+ if (element.getAttribute("aria-grabbed") === "true" || element.getAttribute("aria-grabbed") === "false") hints.push("aria-grabbed");
2527
+ const cursor = doc.defaultView.getComputedStyle(element).cursor;
2528
+ if (cursor === "grab" || cursor === "grabbing") hints.push(`cursor:${cursor}`);
2529
+ if (hints.length) {
2530
+ const rect = element.getBoundingClientRect();
2531
+ let text = "";
2532
+ if (!node.name && node.role === "group") {
2533
+ const walker = doc.createTreeWalker(element, doc.defaultView.NodeFilter.SHOW_TEXT);
2534
+ let next, seen = 0;
2535
+ while (text.length < 160 && seen++ < 200 && (next = walker.nextNode())) text += ` ${next.data.slice(0, 160 - text.length)}`;
2536
+ text = text.replace(/\s+/g, " ").trim();
2537
+ }
2538
+ results.push({
2539
+ nodeId: node.id,
2540
+ role: node.role,
2541
+ name: node.name,
2542
+ text,
2543
+ hints,
2544
+ bounds: {
2545
+ x: rect.x,
2546
+ y: rect.y,
2547
+ width: rect.width,
2548
+ height: rect.height
2549
+ }
2550
+ });
2551
+ }
2552
+ }
2553
+ return results;
2554
+ }
2555
+ function hover(request) {
2556
+ const element = resolve(request);
2557
+ checkHit(element, doc);
2558
+ const coords = point(element), view = doc.defaultView;
2559
+ const chain = [];
2560
+ for (let current = element; current; current = parent(current)) chain.push(current);
2561
+ const fire = (target, type, kind, bubbles) => {
2562
+ const Constructor = kind === "pointer" ? view.PointerEvent : view.MouseEvent;
2563
+ target.dispatchEvent(new Constructor(type, {
2564
+ ...coords,
2565
+ bubbles,
2566
+ cancelable: true,
2567
+ composed: true,
2568
+ view,
2569
+ pointerId: 1,
2570
+ pointerType: "mouse"
2571
+ }));
2572
+ };
2573
+ const revalidate = () => {
2574
+ ensure();
2575
+ if (!current || current.snapshotId !== request.snapshotId || doc.location.href !== current.href) throw new Error("stale_snapshot: hover interrupted by navigation or new snapshot");
2576
+ let node = element;
2577
+ for (const ancestor of chain) {
2578
+ if (node !== ancestor || !ancestor.isConnected) throw new Error("stale_node: hover target or ancestry changed");
2579
+ node = parent(node);
2580
+ }
2581
+ if (node) throw new Error("stale_node: hover ancestry changed");
2582
+ checkUsable(element, doc);
2583
+ checkFrameAncestors(doc);
2584
+ checkHit(element, doc, {
2585
+ x: coords.clientX,
2586
+ y: coords.clientY
2587
+ });
2588
+ };
2589
+ fire(element, "pointerover", "pointer", true);
2590
+ revalidate();
2591
+ for (const ancestor of [...chain].reverse()) {
2592
+ fire(ancestor, "pointerenter", "pointer", false);
2593
+ revalidate();
2594
+ }
2595
+ fire(element, "mouseover", "mouse", true);
2596
+ revalidate();
2597
+ for (const ancestor of [...chain].reverse()) {
2598
+ fire(ancestor, "mouseenter", "mouse", false);
2599
+ revalidate();
2600
+ }
2601
+ fire(element, "pointermove", "pointer", true);
2602
+ revalidate();
2603
+ fire(element, "mousemove", "mouse", true);
2604
+ return {
2605
+ dispatched: true,
2606
+ trusted: false,
2607
+ nativeHover: false
2608
+ };
2609
+ }
2610
+ function dragTo(request) {
2611
+ if (![
2612
+ "html5",
2613
+ "pointer",
2614
+ "pointer-paced"
2615
+ ].includes(request.mode)) throw new Error("invalid: drag mode must be html5, pointer or pointer-paced");
2616
+ if (request.targetNodeId === request.nodeId) throw new Error("invalid: source and destination must differ");
2617
+ const source = resolve(request), target = resolve({
2618
+ snapshotId: request.snapshotId,
2619
+ nodeId: request.targetNodeId
2620
+ });
2621
+ if (source === target) throw new Error("invalid: source and destination must differ");
2622
+ const visual = current.visualTargets.get(request.targetNodeId), targetPoint = visual ? {
2623
+ x: visual.x,
2624
+ y: visual.y
2625
+ } : void 0;
2626
+ const visualSource = current.visualTargets.get(request.nodeId), sourcePoint = visualSource ? {
2627
+ x: visualSource.x,
2628
+ y: visualSource.y
2629
+ } : void 0;
2630
+ checkAriaReadOnly(source);
2631
+ checkUsable(target, doc);
2632
+ checkHit(source, doc, sourcePoint);
2633
+ checkHit(target, doc, targetPoint);
2634
+ const view = doc.defaultView, start = sourcePoint ? {
2635
+ clientX: sourcePoint.x,
2636
+ clientY: sourcePoint.y
2637
+ } : point(source), end = targetPoint ? {
2638
+ clientX: targetPoint.x,
2639
+ clientY: targetPoint.y
2640
+ } : point(target);
2641
+ const targetRect = target.getBoundingClientRect(), targetParent = target.parentNode;
2642
+ const targetBounds = [
2643
+ targetRect.x,
2644
+ targetRect.y,
2645
+ targetRect.width,
2646
+ targetRect.height
2647
+ ];
2648
+ const checkDestination = (allowSource = false) => {
2649
+ const rect = target.getBoundingClientRect();
2650
+ if (!source.isConnected || target.parentNode !== targetParent || [
2651
+ rect.x,
2652
+ rect.y,
2653
+ rect.width,
2654
+ rect.height
2655
+ ].some((value, index) => value !== targetBounds[index])) throw new Error("stale_node: drag destination changed");
2656
+ checkUsable(target, doc);
2657
+ checkFrameAncestors(doc);
2658
+ checkHit(target, doc, {
2659
+ x: end.clientX,
2660
+ y: end.clientY
2661
+ }, allowSource ? source : null);
2662
+ };
2663
+ if (request.mode === "html5") {
2664
+ const dataTransfer = new view.DataTransfer();
2665
+ const send = (element, type, coords) => element.dispatchEvent(new view.DragEvent(type, {
2666
+ ...coords,
2667
+ bubbles: true,
2668
+ cancelable: true,
2669
+ composed: true,
2670
+ view,
2671
+ dataTransfer
2672
+ }));
2673
+ if (!send(source, "dragstart", start)) return {
2674
+ dispatched: true,
2675
+ trusted: false,
2676
+ mode: "html5",
2677
+ dropDispatched: false,
2678
+ reason: "dragstart_cancelled"
2679
+ };
2680
+ let accepted = false, dropped = false;
2681
+ try {
2682
+ checkDestination();
2683
+ send(target, "dragenter", end);
2684
+ checkDestination();
2685
+ accepted = !send(target, "dragover", end);
2686
+ checkDestination();
2687
+ if (accepted) {
2688
+ send(target, "drop", end);
2689
+ dropped = true;
2690
+ }
2691
+ } finally {
2692
+ if (source.isConnected) send(source, "dragend", end);
2693
+ }
2694
+ return {
2695
+ dispatched: true,
2696
+ trusted: false,
2697
+ mode: "html5",
2698
+ dropDispatched: dropped,
2699
+ accepted
2700
+ };
2701
+ }
2702
+ const send = (element, type, coords, buttons) => {
2703
+ const Constructor = type.startsWith("pointer") ? view.PointerEvent : view.MouseEvent;
2704
+ element.dispatchEvent(new Constructor(type, {
2705
+ ...coords,
2706
+ bubbles: true,
2707
+ cancelable: true,
2708
+ composed: true,
2709
+ view,
2710
+ button: 0,
2711
+ buttons,
2712
+ pointerId: 1,
2713
+ pointerType: "mouse",
2714
+ isPrimary: true
2715
+ }));
2716
+ };
2717
+ const middle = {
2718
+ clientX: (start.clientX + end.clientX) / 2,
2719
+ clientY: (start.clientY + end.clientY) / 2
2720
+ };
2721
+ if (request.mode === "pointer-paced") {
2722
+ gestureActive = true;
2723
+ return (async () => {
2724
+ const pause = () => new Promise((resolve) => view.setTimeout(resolve, 50));
2725
+ let pressed = false, mousePressed = false, completed = false;
2726
+ try {
2727
+ pressed = true;
2728
+ send(source, "pointerdown", start, 1);
2729
+ checkDestination();
2730
+ mousePressed = true;
2731
+ send(source, "mousedown", start, 1);
2732
+ checkDestination();
2733
+ await pause();
2734
+ for (const coords of [middle, end]) {
2735
+ ensure();
2736
+ if (!current || current.snapshotId !== request.snapshotId || doc.location.href !== current.href) throw new Error("stale_snapshot: drag interrupted by navigation or new snapshot");
2737
+ checkDestination(true);
2738
+ send(source, "pointermove", coords, 1);
2739
+ send(source, "mousemove", coords, 1);
2740
+ await pause();
2741
+ }
2742
+ ensure();
2743
+ if (!current || current.snapshotId !== request.snapshotId || doc.location.href !== current.href) throw new Error("stale_snapshot: drag interrupted by navigation or new snapshot");
2744
+ checkDestination(true);
2745
+ send(source, "pointerup", end, 0);
2746
+ send(source.isConnected ? source : doc, "mouseup", end, 0);
2747
+ completed = true;
2748
+ return {
2749
+ dispatched: true,
2750
+ trusted: false,
2751
+ mode: "pointer-paced"
2752
+ };
2753
+ } finally {
2754
+ try {
2755
+ if (pressed && !completed) {
2756
+ const release = source.isConnected ? source : doc;
2757
+ send(release, "pointercancel", start, 0);
2758
+ if (mousePressed) send(release, "mouseup", start, 0);
2759
+ }
2760
+ } finally {
2761
+ gestureActive = false;
2762
+ }
2763
+ }
2764
+ })();
2765
+ }
2766
+ let pressed = false, mousePressed = false, completed = false;
2767
+ try {
2768
+ pressed = true;
2769
+ send(source, "pointerdown", start, 1);
2770
+ checkDestination();
2771
+ mousePressed = true;
2772
+ send(source, "mousedown", start, 1);
2773
+ checkDestination();
2774
+ for (const coords of [middle, end]) {
2775
+ send(source, "pointermove", coords, 1);
2776
+ checkDestination(true);
2777
+ send(source, "mousemove", coords, 1);
2778
+ checkDestination(true);
2779
+ }
2780
+ send(source, "pointerup", end, 0);
2781
+ send(source.isConnected ? source : doc, "mouseup", end, 0);
2782
+ completed = true;
2783
+ } finally {
2784
+ if (pressed && !completed) {
2785
+ const release = source.isConnected ? source : doc;
2786
+ send(release, "pointercancel", start, 0);
2787
+ if (mousePressed) send(release, "mouseup", start, 0);
2788
+ }
2789
+ }
2790
+ return {
2791
+ dispatched: true,
2792
+ trusted: false,
2793
+ mode: "pointer"
2794
+ };
2795
+ }
2796
+ function focus(request) {
2797
+ const element = resolve(request);
2798
+ if (typeof element.focus !== "function") throw new Error("unsupported: cannot focus target");
2799
+ element.focus();
2800
+ return { focused: doc.activeElement === element || element.matches(":focus") };
2801
+ }
2802
+ function scrollIntoView(request) {
2803
+ resolve(request).scrollIntoView({
2804
+ block: "center",
2805
+ inline: "nearest",
2806
+ behavior: "instant"
2807
+ });
2808
+ return { requested: true };
2809
+ }
2810
+ function scrollTarget(request) {
2811
+ ensure();
2812
+ if (gestureActive) throw new Error("gesture_active: wait for the drag to finish");
2813
+ if (!current || request.snapshotId !== current.snapshotId || doc.location.href !== current.href) throw new Error("stale_snapshot: request a new snapshot");
2814
+ const x = request.x ?? 0, y = request.y ?? 0;
2815
+ if (!Number.isFinite(x) || !Number.isFinite(y)) throw new Error("invalid: scroll offsets must be finite numbers");
2816
+ checkFrameAncestors(doc);
2817
+ return {
2818
+ element: request.nodeId === void 0 ? null : resolve(request),
2819
+ x,
2820
+ y
2821
+ };
2822
+ }
2823
+ function scroll(request = {}) {
2824
+ const { element, x, y } = scrollTarget(request), view = doc.defaultView;
2825
+ const position = () => element ? {
2826
+ x: element.scrollLeft,
2827
+ y: element.scrollTop
2828
+ } : {
2829
+ x: view.scrollX,
2830
+ y: view.scrollY
2831
+ };
2832
+ const before = position();
2833
+ (element || view).scrollBy({
2834
+ left: x,
2835
+ top: y,
2836
+ behavior: "instant"
2837
+ });
2838
+ const after = position();
2839
+ return {
2840
+ requested: {
2841
+ x,
2842
+ y
2843
+ },
2844
+ before,
2845
+ after,
2846
+ moved: before.x !== after.x || before.y !== after.y
2847
+ };
2848
+ }
2849
+ function wheel(request = {}) {
2850
+ const { element, x, y } = scrollTarget(request), view = doc.defaultView, target = element || doc.documentElement;
2851
+ if (element) checkHit(element, doc);
2852
+ const coords = element ? point(element) : {
2853
+ clientX: view.innerWidth / 2,
2854
+ clientY: view.innerHeight / 2
2855
+ };
2856
+ const event = new view.WheelEvent("wheel", {
2857
+ ...coords,
2858
+ deltaX: x,
2859
+ deltaY: y,
2860
+ deltaMode: 0,
2861
+ bubbles: true,
2862
+ cancelable: true,
2863
+ composed: true,
2864
+ view
2865
+ });
2866
+ target.dispatchEvent(event);
2867
+ return {
2868
+ dispatched: true,
2869
+ trusted: false,
2870
+ defaultPrevented: event.defaultPrevented,
2871
+ nativeDefault: false
2872
+ };
2873
+ }
2874
+ function frame(request) {
2875
+ const element = resolve(request);
2876
+ if (!["iframe", "frame"].includes(element.localName)) throw new Error("unsupported: node is not a frame");
2877
+ let child;
2878
+ try {
2879
+ child = element.contentDocument;
2880
+ } catch {}
2881
+ if (!child?.defaultView) throw new Error("frame_unavailable: cross-origin or inactive frame");
2882
+ return createPageAgent({
2883
+ document: child,
2884
+ maxNodes,
2885
+ maxDurationMs
2886
+ });
2887
+ }
2888
+ function destroy() {
2889
+ closed = true;
2890
+ current = null;
2891
+ for (const cancel of waits) cancel();
2892
+ }
2893
+ return Object.freeze({
2894
+ snapshot,
2895
+ tree,
2896
+ query,
2897
+ waitFor,
2898
+ textFragments,
2899
+ click,
2900
+ doubleClick,
2901
+ fill,
2902
+ select,
2903
+ setChecked,
2904
+ setRange,
2905
+ key,
2906
+ targetAt,
2907
+ visualSurfaces,
2908
+ draggableCandidates,
2909
+ hover,
2910
+ dragTo,
2911
+ focus,
2912
+ scrollIntoView,
2913
+ scroll,
2914
+ wheel,
2915
+ frame,
2916
+ destroy
2917
+ });
2918
+ }
2919
+ //#endregion
2920
+ export { createPageAgent };
2921
+
2922
+ //# sourceMappingURL=ax-core-oj-p6gBY.js.map