@a11y-pulse/disclosure-operability-audit 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,976 @@
1
+ // src/audit.ts
2
+ import {
3
+ releaseStashedElements,
4
+ stashedElementSelectors
5
+ } from "@a11y-pulse/browser-adaptor";
6
+ import { truncateHtml } from "@a11y-pulse/browser-adaptor/dom";
7
+
8
+ // src/browser-scripts.ts
9
+ function installDisclosureScript(stashKey, triggerLimit, skipLimit, scanLimit, options = {}) {
10
+ const HTML_LIMIT = 2e3;
11
+ const COMPOSITE = "[role=menu],[role=menubar],[role=toolbar],[role=tablist],[role=listbox]";
12
+ const COMPOSITE_ITEM = /* @__PURE__ */ new Set([
13
+ "treeitem",
14
+ "row",
15
+ "gridcell",
16
+ "columnheader",
17
+ "rowheader",
18
+ "option",
19
+ "tab"
20
+ ]);
21
+ const NOT_A_DISCLOSURE = /* @__PURE__ */ new Set([
22
+ "tab",
23
+ "combobox",
24
+ "scrollbar",
25
+ "slider",
26
+ "spinbutton",
27
+ "textbox",
28
+ "searchbox",
29
+ "radio",
30
+ "checkbox",
31
+ "switch",
32
+ "option",
33
+ "treeitem",
34
+ "row",
35
+ "gridcell"
36
+ ]);
37
+ const CHECKABLE = /* @__PURE__ */ new Set(["checkbox", "radio", "switch", "menuitemcheckbox", "menuitemradio"]);
38
+ const riskyName = options.riskyNamePattern ? new RegExp(options.riskyNamePattern, "i") : null;
39
+ const FOCUSABLE = "a[href],button,input,select,textarea,summary,[tabindex],[contenteditable=''],[contenteditable=true]";
40
+ function everyElement(root, out) {
41
+ for (const element of root.querySelectorAll("*")) {
42
+ out.push(element);
43
+ if (element.shadowRoot) {
44
+ everyElement(element.shadowRoot, out);
45
+ }
46
+ }
47
+ return out;
48
+ }
49
+ function isShown(element, anywhere = false) {
50
+ const rect = element.getBoundingClientRect();
51
+ if (rect.width <= 0 || rect.height <= 0) {
52
+ return false;
53
+ }
54
+ const pageWidth = Math.max(document.documentElement.scrollWidth, window.innerWidth);
55
+ if (!anywhere && (rect.right + window.scrollX <= 0 || rect.bottom + window.scrollY <= 0 || rect.left + window.scrollX >= pageWidth)) {
56
+ return false;
57
+ }
58
+ if (typeof element.checkVisibility !== "function") {
59
+ return true;
60
+ }
61
+ return element.checkVisibility({
62
+ opacityProperty: true,
63
+ visibilityProperty: true,
64
+ // The older names, for engines that shipped before the rename.
65
+ checkOpacity: true,
66
+ checkVisibilityCSS: true
67
+ });
68
+ }
69
+ function role(element) {
70
+ return element.getAttribute("role")?.trim().toLowerCase() || null;
71
+ }
72
+ function controlled(element) {
73
+ const root = element.getRootNode();
74
+ const found = [];
75
+ for (const id of (element.getAttribute("aria-controls") ?? "").split(/\s+/)) {
76
+ const target = id && typeof root.getElementById === "function" ? root.getElementById(id) : null;
77
+ if (target) {
78
+ found.push(target);
79
+ }
80
+ }
81
+ return found;
82
+ }
83
+ function navigates(element) {
84
+ const link = element.closest("a[href], area[href]");
85
+ if (!link) {
86
+ return false;
87
+ }
88
+ const href = (link.getAttribute("href") ?? "").trim();
89
+ return !(href === "" || href.startsWith("#") || /^javascript:/i.test(href));
90
+ }
91
+ function submits(element) {
92
+ if (element instanceof HTMLButtonElement) {
93
+ return element.form !== null && element.type !== "button";
94
+ }
95
+ if (element instanceof HTMLInputElement) {
96
+ return element.type === "submit" || element.type === "image" || element.type === "reset";
97
+ }
98
+ return false;
99
+ }
100
+ function isCheckable(element) {
101
+ if (element instanceof HTMLInputElement) {
102
+ return element.type === "checkbox" || element.type === "radio";
103
+ }
104
+ const elementRole = role(element);
105
+ return elementRole !== null && CHECKABLE.has(elementRole);
106
+ }
107
+ function nameOf(element) {
108
+ const root = element.getRootNode();
109
+ let parts = [];
110
+ for (const id of (element.getAttribute("aria-labelledby") ?? "").split(/\s+/)) {
111
+ const label = id && typeof root.getElementById === "function" ? root.getElementById(id) : null;
112
+ if (label) {
113
+ parts.push(label.textContent ?? "");
114
+ }
115
+ }
116
+ if (parts.join("").trim() === "") {
117
+ parts = [element.getAttribute("aria-label") ?? ""];
118
+ }
119
+ if (parts.join("").trim() === "") {
120
+ parts = [element.textContent ?? ""];
121
+ for (const named of element.querySelectorAll("img[alt], [aria-label]")) {
122
+ parts.push(named.getAttribute("alt") ?? named.getAttribute("aria-label") ?? "");
123
+ }
124
+ if (element instanceof HTMLInputElement) {
125
+ parts.push(element.value);
126
+ }
127
+ parts.push(element.getAttribute("title") ?? "");
128
+ }
129
+ return parts.join(" ").replace(/\s+/g, " ").trim();
130
+ }
131
+ function isTextEntry(element) {
132
+ if (role(element) === "combobox" || element instanceof HTMLTextAreaElement) {
133
+ return true;
134
+ }
135
+ if (element instanceof HTMLInputElement) {
136
+ return !["button", "checkbox", "radio"].includes(element.type);
137
+ }
138
+ return element instanceof HTMLElement && element.isContentEditable;
139
+ }
140
+ function isDisabled(element) {
141
+ return element.disabled === true || element.getAttribute("aria-disabled") === "true" || element.closest("[inert]") !== null || element.closest("fieldset[disabled]") !== null;
142
+ }
143
+ function isButtonLike(element) {
144
+ const tag = element.localName;
145
+ return tag === "button" || role(element) === "button" || role(element) === "menuitem" || element instanceof HTMLInputElement && element.type === "button" || tag === "a" && !navigates(element) || element.hasAttribute("tabindex");
146
+ }
147
+ function isTrigger(element) {
148
+ const tag = element.localName;
149
+ if (tag === "details" || tag === "summary" || tag === "select" || tag === "option") {
150
+ return false;
151
+ }
152
+ if (element.hasAttribute("aria-expanded")) {
153
+ return true;
154
+ }
155
+ if (!options.includeControlsOnly || !element.hasAttribute("aria-controls")) {
156
+ return false;
157
+ }
158
+ const elementRole = role(element);
159
+ const popup = element.getAttribute("aria-haspopup");
160
+ if (elementRole !== null && NOT_A_DISCLOSURE.has(elementRole) || popup === "dialog" || !isButtonLike(element) || isTextEntry(element)) {
161
+ return false;
162
+ }
163
+ const targets = controlled(element);
164
+ return targets.length > 0 && targets.every((target) => !isShown(target));
165
+ }
166
+ function skipReason(element) {
167
+ if (!isShown(element)) {
168
+ return "hidden";
169
+ }
170
+ if (isDisabled(element)) {
171
+ return "disabled";
172
+ }
173
+ if (isCheckable(element)) {
174
+ return "checkable";
175
+ }
176
+ if (isTextEntry(element)) {
177
+ return "text-entry";
178
+ }
179
+ const elementRole = role(element);
180
+ if (elementRole !== null && COMPOSITE_ITEM.has(elementRole)) {
181
+ return "composite-item";
182
+ }
183
+ if (navigates(element)) {
184
+ return "navigating-link";
185
+ }
186
+ if (submits(element)) {
187
+ return "submits-form";
188
+ }
189
+ if (riskyName?.test(nameOf(element))) {
190
+ return "risky-name";
191
+ }
192
+ const focusable = element instanceof HTMLElement && element.tabIndex >= 0;
193
+ if (!focusable && !element.hasAttribute("tabindex") && element.querySelector(FOCUSABLE)) {
194
+ return "state-on-container";
195
+ }
196
+ return null;
197
+ }
198
+ function html(element) {
199
+ return element.outerHTML.slice(0, HTML_LIMIT);
200
+ }
201
+ const eligible = [];
202
+ const skippedElements = [];
203
+ const skipped = [];
204
+ let skippedTotal = 0;
205
+ for (const element of everyElement(document, [])) {
206
+ if (!isTrigger(element)) {
207
+ continue;
208
+ }
209
+ const reason = skipReason(element);
210
+ if (reason === null) {
211
+ eligible.push(element);
212
+ continue;
213
+ }
214
+ skippedTotal++;
215
+ if (skipped.length < skipLimit) {
216
+ skipped.push({ html: html(element), reason });
217
+ skippedElements.push(element);
218
+ }
219
+ }
220
+ const sampled = eligible.length <= triggerLimit ? eligible : Array.from(
221
+ { length: triggerLimit },
222
+ (_, i) => eligible[Math.floor(i * eligible.length / triggerLimit)]
223
+ );
224
+ const store = window;
225
+ store[stashKey] = [...sampled, ...skippedElements];
226
+ store[`${stashKey}Controls`] = sampled.map((trigger) => controlled(trigger)[0] ?? null);
227
+ function deepActiveElement() {
228
+ let active = document.activeElement;
229
+ while (active?.shadowRoot?.activeElement) {
230
+ active = active.shadowRoot.activeElement;
231
+ }
232
+ return active;
233
+ }
234
+ const originalFocus = deepActiveElement();
235
+ const originalScroll = { x: window.scrollX, y: window.scrollY };
236
+ let baseline = null;
237
+ let scroll = originalScroll;
238
+ let current = null;
239
+ let focusAtBegin = null;
240
+ let clicks = 0;
241
+ let geometry = "";
242
+ const blocked = { submits: 0, navigations: 0 };
243
+ const onSubmit = (event) => {
244
+ event.preventDefault();
245
+ event.stopImmediatePropagation();
246
+ blocked.submits++;
247
+ };
248
+ const onClick = (event) => {
249
+ if (event.isTrusted && current !== null && event.composedPath().includes(current)) {
250
+ clicks++;
251
+ }
252
+ };
253
+ const onNavigate = (event) => {
254
+ if (event.hashChange || event.destination?.sameDocument || !event.cancelable) {
255
+ return;
256
+ }
257
+ event.preventDefault();
258
+ blocked.navigations++;
259
+ };
260
+ const navigation = window.navigation;
261
+ const formPrototype = typeof HTMLFormElement === "function" ? HTMLFormElement.prototype : null;
262
+ const originalSubmit = formPrototype?.submit;
263
+ const originalRequestSubmit = formPrototype?.requestSubmit;
264
+ window.addEventListener("submit", onSubmit, true);
265
+ window.addEventListener("click", onClick, true);
266
+ navigation?.addEventListener("navigate", onNavigate);
267
+ if (formPrototype) {
268
+ formPrototype.submit = function submit() {
269
+ blocked.submits++;
270
+ };
271
+ if (originalRequestSubmit) {
272
+ formPrototype.requestSubmit = function requestSubmit() {
273
+ blocked.submits++;
274
+ };
275
+ }
276
+ }
277
+ function unblock() {
278
+ window.removeEventListener("submit", onSubmit, true);
279
+ window.removeEventListener("click", onClick, true);
280
+ navigation?.removeEventListener("navigate", onNavigate);
281
+ if (formPrototype && originalSubmit) {
282
+ formPrototype.submit = originalSubmit;
283
+ }
284
+ if (formPrototype && originalRequestSubmit) {
285
+ formPrototype.requestSubmit = originalRequestSubmit;
286
+ }
287
+ }
288
+ function geometryOf(targets) {
289
+ return targets.map((target) => {
290
+ const rect = target.getBoundingClientRect();
291
+ return `${Math.round(rect.width)}x${Math.round(rect.height)}`;
292
+ }).join(",");
293
+ }
294
+ function inMotion(trigger, targets) {
295
+ if (typeof document.getAnimations !== "function") {
296
+ return false;
297
+ }
298
+ for (const animation of document.getAnimations()) {
299
+ const effect = animation.effect;
300
+ const timing = effect?.getComputedTiming?.();
301
+ if (animation.playState !== "running" || !timing || timing.iterations === Number.POSITIVE_INFINITY) {
302
+ continue;
303
+ }
304
+ const target = effect?.target ?? null;
305
+ if (target === null || targets.length === 0 || trigger.contains(target) || targets.some((controlled2) => controlled2.contains(target) || target.contains(controlled2))) {
306
+ return true;
307
+ }
308
+ }
309
+ return false;
310
+ }
311
+ function behindModal(trigger) {
312
+ for (const modal of document.querySelectorAll("dialog[open], [aria-modal=true]")) {
313
+ if (modal.contains(trigger)) {
314
+ continue;
315
+ }
316
+ if (modal.localName !== "dialog") {
317
+ if (isShown(modal)) {
318
+ return true;
319
+ }
320
+ continue;
321
+ }
322
+ try {
323
+ if (modal.matches(":modal")) {
324
+ return true;
325
+ }
326
+ } catch {
327
+ }
328
+ }
329
+ return false;
330
+ }
331
+ function shownOutside(trigger) {
332
+ const elements = everyElement(document.body ?? document, []);
333
+ if (elements.length > scanLimit) {
334
+ return null;
335
+ }
336
+ return elements.filter((element) => !trigger.contains(element) && isShown(element, true));
337
+ }
338
+ function read(index) {
339
+ const trigger = sampled[index];
340
+ const targets = controlled(trigger);
341
+ let appeared = null;
342
+ let disappeared = null;
343
+ if (baseline !== null) {
344
+ const now = shownOutside(trigger);
345
+ if (now !== null) {
346
+ const seen = new Set(now);
347
+ appeared = now.filter((element) => !baseline.has(element)).length;
348
+ disappeared = [...baseline].filter((element) => !seen.has(element)).length;
349
+ }
350
+ }
351
+ const nowGeometry = geometryOf(targets);
352
+ const resized = nowGeometry !== geometry;
353
+ geometry = nowGeometry;
354
+ return {
355
+ connected: trigger.isConnected,
356
+ expanded: trigger.getAttribute("aria-expanded"),
357
+ controlled: targets.length > 0 ? targets.some((target) => isShown(target)) : null,
358
+ appeared,
359
+ disappeared,
360
+ focused: deepActiveElement() === trigger,
361
+ settling: resized || inMotion(trigger, targets),
362
+ clicks,
363
+ blocked: { ...blocked }
364
+ };
365
+ }
366
+ function pointer(target, types, bubbles) {
367
+ for (const type of types) {
368
+ const init = { bubbles, cancelable: true, composed: true };
369
+ target.dispatchEvent(
370
+ type.startsWith("pointer") && typeof PointerEvent === "function" ? new PointerEvent(type, init) : new MouseEvent(type, init)
371
+ );
372
+ }
373
+ }
374
+ const api = {
375
+ begin(index) {
376
+ const trigger = sampled[index];
377
+ const shown = shownOutside(trigger);
378
+ scroll = { x: window.scrollX, y: window.scrollY };
379
+ baseline = shown === null ? null : new Set(shown);
380
+ current = trigger;
381
+ focusAtBegin = deepActiveElement();
382
+ clicks = 0;
383
+ blocked.submits = 0;
384
+ blocked.navigations = 0;
385
+ geometry = geometryOf(controlled(trigger));
386
+ return read(index);
387
+ },
388
+ focus(index) {
389
+ const trigger = sampled[index];
390
+ if (trigger instanceof HTMLElement || trigger instanceof SVGElement) {
391
+ trigger.focus({ preventScroll: true });
392
+ }
393
+ return deepActiveElement() === trigger;
394
+ },
395
+ read,
396
+ ready(index, action) {
397
+ const trigger = sampled[index];
398
+ if (!trigger.isConnected || trigger.closest("[inert]") !== null || behindModal(trigger)) {
399
+ return false;
400
+ }
401
+ const active = deepActiveElement();
402
+ if (action === "key") {
403
+ return active === trigger;
404
+ }
405
+ return active === trigger || active === null || active === document.body || active === focusAtBegin;
406
+ },
407
+ blur(index) {
408
+ const trigger = sampled[index];
409
+ if (trigger instanceof HTMLElement || trigger instanceof SVGElement) {
410
+ trigger.blur();
411
+ }
412
+ },
413
+ click(index) {
414
+ const trigger = sampled[index];
415
+ if (trigger instanceof HTMLElement) {
416
+ trigger.click();
417
+ } else {
418
+ pointer(trigger, ["click"], true);
419
+ }
420
+ },
421
+ hover(index, on) {
422
+ const trigger = sampled[index];
423
+ pointer(trigger, on ? ["pointerover", "mouseover"] : ["pointerout", "mouseout"], true);
424
+ for (let target = trigger; target; target = target.parentElement) {
425
+ pointer(
426
+ target,
427
+ on ? ["pointerenter", "mouseenter"] : ["pointerleave", "mouseleave"],
428
+ false
429
+ );
430
+ }
431
+ },
432
+ end() {
433
+ baseline = null;
434
+ current = null;
435
+ window.scrollTo(scroll.x, scroll.y);
436
+ },
437
+ finish() {
438
+ const active = deepActiveElement();
439
+ if (originalFocus?.isConnected && originalFocus !== document.body && (originalFocus instanceof HTMLElement || originalFocus instanceof SVGElement)) {
440
+ originalFocus.focus({ preventScroll: true });
441
+ } else if (active instanceof HTMLElement && active !== document.body) {
442
+ active.blur();
443
+ }
444
+ window.scrollTo(originalScroll.x, originalScroll.y);
445
+ unblock();
446
+ delete store[`${stashKey}Api`];
447
+ }
448
+ };
449
+ store[`${stashKey}Api`] = api;
450
+ return {
451
+ triggers: sampled.map((trigger) => ({
452
+ html: html(trigger),
453
+ role: role(trigger),
454
+ expanded: trigger.getAttribute("aria-expanded"),
455
+ hasControlled: controlled(trigger).length > 0,
456
+ inTabOrder: trigger instanceof HTMLElement && trigger.tabIndex >= 0,
457
+ inComposite: trigger.closest(COMPOSITE) !== null,
458
+ spaceExpected: trigger.localName === "button" || role(trigger) === "button",
459
+ link: trigger.localName === "a" && trigger.hasAttribute("href")
460
+ })),
461
+ skipped,
462
+ skippedTotal,
463
+ eligible: eligible.length
464
+ };
465
+ }
466
+ function callDisclosureScript(stashKey, method, ...args) {
467
+ const api = window[`${stashKey}Api`];
468
+ if (!api) {
469
+ return { gone: true };
470
+ }
471
+ return api[method](...args) ?? null;
472
+ }
473
+ function isDisclosureInstalledScript(stashKey) {
474
+ return `${stashKey}Api` in window;
475
+ }
476
+
477
+ // src/classify.ts
478
+ var FAILING = /* @__PURE__ */ new Set([
479
+ "not-focusable",
480
+ "keyboard-inoperable",
481
+ "state-not-exposed"
482
+ ]);
483
+ function expandedChanged(attempt) {
484
+ return attempt.expandedBefore !== attempt.expandedAfter;
485
+ }
486
+ function changed(attempt) {
487
+ return expandedChanged(attempt) || attempt.contentChanged;
488
+ }
489
+ function classifyTrigger(observation) {
490
+ const signals = [];
491
+ const respondsToPointer = observation.pointer.click === true || observation.pointer.hover === true;
492
+ const working = observation.attempts.filter(changed);
493
+ const blocked = observation.blocked.submit || observation.blocked.navigation;
494
+ if (observation.navigated) {
495
+ signals.push("navigated");
496
+ } else if (observation.removed) {
497
+ signals.push("trigger-removed");
498
+ } else if (!observation.focusable) {
499
+ if (respondsToPointer) {
500
+ signals.push("not-focusable");
501
+ } else if (!blocked) {
502
+ signals.push("unresponsive");
503
+ }
504
+ } else if (observation.openedOnFocus) {
505
+ if (!observation.openedOnFocus.expandedChanged) {
506
+ signals.push("opens-on-focus");
507
+ }
508
+ } else if (working.length === 0) {
509
+ if (respondsToPointer) {
510
+ signals.push("keyboard-inoperable");
511
+ } else if (!blocked) {
512
+ signals.push("unresponsive");
513
+ }
514
+ } else {
515
+ if (working.some((attempt) => attempt.contentChanged && !expandedChanged(attempt))) {
516
+ signals.push("state-not-exposed");
517
+ }
518
+ if (working.every((attempt) => !attempt.contentChanged)) {
519
+ signals.push("state-without-content");
520
+ }
521
+ const works = (key) => working.some((attempt) => attempt.key === key);
522
+ const tried = (key) => observation.attempts.some((attempt) => attempt.key === key);
523
+ if (works("Enter") && tried("Space") && !works("Space") && observation.spaceExpected) {
524
+ signals.push("space-inoperable");
525
+ }
526
+ if (works("Space") && tried("Enter") && !works("Enter")) {
527
+ signals.push("enter-inoperable");
528
+ }
529
+ if (working.some((attempt) => attempt.restoredBy === "click")) {
530
+ signals.push("pointer-only-close");
531
+ }
532
+ }
533
+ if (!observation.restored && !observation.navigated && !observation.removed) {
534
+ signals.push("not-restored");
535
+ }
536
+ if (observation.blocked.submit && !observation.navigated) {
537
+ signals.push("submit-blocked");
538
+ }
539
+ if (observation.blocked.navigation && !observation.navigated) {
540
+ signals.push("navigation-blocked");
541
+ }
542
+ if (observation.focusable && !observation.inTabOrder && !observation.inComposite && !observation.navigated) {
543
+ signals.push("not-in-tab-order");
544
+ }
545
+ const verdict = signals.some((signal) => FAILING.has(signal)) ? "failed" : signals.length > 0 ? "review" : null;
546
+ signals.sort((a, b) => Number(FAILING.has(b)) - Number(FAILING.has(a)));
547
+ return { verdict, signals };
548
+ }
549
+
550
+ // src/audit.ts
551
+ var DEFAULT_TRIGGER_LIMIT = 20;
552
+ var DEFAULT_ACTIVATION_TIMEOUT_MS = 250;
553
+ var DEFAULT_RISKY_NAME_PATTERN = "\\b(delete|remove|erase|log\\s?out|sign\\s?out|unsubscribe|pay|buy|purchase|send|order\\s+now|(place|confirm|complete|submit)\\s+(your\\s+|my\\s+)?order)\\b";
554
+ var SKIP_LIMIT = 10;
555
+ var SCAN_LIMIT = 5e3;
556
+ var POLL_INTERVAL_MS = 25;
557
+ var SETTLE_LIMIT_MS = 1e3;
558
+ var IDLE_WATCH_MS = 50;
559
+ var STASH_KEY = "__a11yPulseDisclosure";
560
+ var DocumentReplacedError = class extends Error {
561
+ constructor() {
562
+ super("The document was replaced while a disclosure trigger was being operated");
563
+ this.name = "DocumentReplacedError";
564
+ }
565
+ };
566
+ var TriggerRemoved = class extends Error {
567
+ };
568
+ function pageDiff({ stable }, reading) {
569
+ return stable ? (reading.appeared ?? 0) + (reading.disappeared ?? 0) : 0;
570
+ }
571
+ function contentChanged(exercise, from, to) {
572
+ return from.controlled !== to.controlled || pageDiff(exercise, from) !== pageDiff(exercise, to);
573
+ }
574
+ function differs(exercise, from, to) {
575
+ return from.expanded !== to.expanded || contentChanged(exercise, from, to);
576
+ }
577
+ async function poll(exercise, timeout, done, extend) {
578
+ const { probe, index } = exercise;
579
+ let reading = await probe.read(index);
580
+ for (let waited = 0; ; waited += POLL_INTERVAL_MS) {
581
+ if (!reading.connected) {
582
+ throw new TriggerRemoved();
583
+ }
584
+ if (done(reading)) {
585
+ return reading;
586
+ }
587
+ if (waited >= timeout && !(waited < SETTLE_LIMIT_MS && extend?.(reading))) {
588
+ return reading;
589
+ }
590
+ await probe.sleep(POLL_INTERVAL_MS);
591
+ reading = await probe.read(index);
592
+ }
593
+ }
594
+ async function awaitSettled(exercise) {
595
+ const { probe, index } = exercise;
596
+ let calm = 0;
597
+ for (let waited = 0; waited < SETTLE_LIMIT_MS; waited += POLL_INTERVAL_MS) {
598
+ const reading = await probe.read(index);
599
+ if (!reading.connected) {
600
+ throw new TriggerRemoved();
601
+ }
602
+ calm = reading.settling ? 0 : calm + 1;
603
+ if (calm >= 2) {
604
+ return;
605
+ }
606
+ await probe.sleep(POLL_INTERVAL_MS);
607
+ }
608
+ }
609
+ async function awaitChange(exercise, timeout, clicksBefore = null) {
610
+ const { initial } = exercise;
611
+ const started = Date.now();
612
+ const busy = (reading) => reading.settling || clicksBefore !== null && reading.clicks > clicksBefore;
613
+ const first = await poll(
614
+ exercise,
615
+ timeout,
616
+ (reading) => differs(exercise, initial, reading),
617
+ busy
618
+ );
619
+ if (!differs(exercise, initial, first) || initial.expanded === null) {
620
+ return first;
621
+ }
622
+ const both = (reading) => reading.expanded !== initial.expanded && contentChanged(exercise, initial, reading);
623
+ return poll(
624
+ exercise,
625
+ Math.max(0, timeout - (Date.now() - started)),
626
+ both,
627
+ (reading) => reading.settling
628
+ );
629
+ }
630
+ async function focusForKey({ probe, index }) {
631
+ if (!await probe.focus(index)) {
632
+ return false;
633
+ }
634
+ await probe.sleep(POLL_INTERVAL_MS);
635
+ return probe.ready(index, "key");
636
+ }
637
+ async function restore(exercise, first) {
638
+ const { probe, index, initial, timeout } = exercise;
639
+ const restored = (reading) => !differs(exercise, initial, reading);
640
+ const act = async (step) => {
641
+ if (step === "blur") {
642
+ await probe.blur(index);
643
+ } else if (step === "Escape") {
644
+ await probe.pressKey("Escape");
645
+ } else if (step === "click") {
646
+ if (!await probe.ready(index, "click")) {
647
+ return false;
648
+ }
649
+ await probe.click(index);
650
+ } else {
651
+ if (!await focusForKey(exercise)) {
652
+ return false;
653
+ }
654
+ await probe.pressKey(step);
655
+ }
656
+ return true;
657
+ };
658
+ const now = await probe.read(index);
659
+ const order = first === "Enter" || first === "Space" ? now.focused ? [first, "Escape", "click"] : ["Escape", first, "click"] : [first, "Escape", "click"];
660
+ for (const step of new Set(order)) {
661
+ const { clicks } = await probe.read(index);
662
+ if (!await act(step)) {
663
+ continue;
664
+ }
665
+ const busy = (reading) => reading.settling || step === "click" || reading.clicks > clicks;
666
+ if (restored(await poll(exercise, timeout, restored, busy))) {
667
+ await awaitSettled(exercise);
668
+ return step;
669
+ }
670
+ }
671
+ return null;
672
+ }
673
+ function keysFor(trigger) {
674
+ return trigger.link && !trigger.spaceExpected ? ["Enter"] : ["Enter", "Space"];
675
+ }
676
+ async function exerciseTrigger(probe, index, trigger, timeout) {
677
+ const observation = {
678
+ focusable: false,
679
+ inTabOrder: trigger.inTabOrder,
680
+ inComposite: trigger.inComposite,
681
+ spaceExpected: trigger.spaceExpected,
682
+ openedOnFocus: null,
683
+ attempts: [],
684
+ pointer: { click: null, hover: null },
685
+ blocked: { submit: false, navigation: false },
686
+ removed: false,
687
+ navigated: false,
688
+ restored: true
689
+ };
690
+ const attempts = [];
691
+ const keysTried = [];
692
+ const done = () => ({ observation: { ...observation, attempts }, keysTried });
693
+ const noteBlocked = ({ blocked }) => {
694
+ observation.blocked.submit ||= blocked.submits > 0;
695
+ observation.blocked.navigation ||= blocked.navigations > 0;
696
+ return blocked.submits > 0 || blocked.navigations > 0;
697
+ };
698
+ const operate = async () => {
699
+ const initial = await probe.begin(index);
700
+ if (!initial.connected) {
701
+ throw new TriggerRemoved();
702
+ }
703
+ const exercise = { probe, index, timeout, initial, stable: true };
704
+ await probe.sleep(IDLE_WATCH_MS);
705
+ exercise.stable = pageDiff(exercise, await probe.read(index)) === 0;
706
+ const changedFromInitial = (reading) => differs(exercise, initial, reading);
707
+ const pointerTimeout = Math.min(timeout, 150);
708
+ const tryHover = async () => {
709
+ await probe.hover(index, true);
710
+ observation.pointer.hover = changedFromInitial(await awaitChange(exercise, pointerTimeout));
711
+ await probe.hover(index, false);
712
+ if (observation.pointer.hover) {
713
+ const closed = await poll(
714
+ exercise,
715
+ timeout,
716
+ (reading) => !changedFromInitial(reading),
717
+ (reading) => reading.settling
718
+ );
719
+ observation.restored = !changedFromInitial(closed) || await restore(exercise, "Escape") !== null;
720
+ }
721
+ };
722
+ const tryPointer = async () => {
723
+ if (!await probe.ready(index, "click")) {
724
+ return;
725
+ }
726
+ await probe.click(index);
727
+ const clicked = await awaitChange(exercise, pointerTimeout);
728
+ observation.pointer.click = changedFromInitial(clicked);
729
+ if (noteBlocked(clicked)) {
730
+ return;
731
+ }
732
+ if (observation.pointer.click) {
733
+ await awaitSettled(exercise);
734
+ observation.restored = await restore(exercise, "click") !== null;
735
+ return;
736
+ }
737
+ await tryHover();
738
+ };
739
+ const exerciseKeys = async () => {
740
+ observation.focusable = await probe.focus(index);
741
+ if (!observation.focusable) {
742
+ await tryPointer();
743
+ return;
744
+ }
745
+ const afterFocus = await poll(exercise, IDLE_WATCH_MS, changedFromInitial);
746
+ if (changedFromInitial(afterFocus)) {
747
+ observation.openedOnFocus = { expandedChanged: afterFocus.expanded !== initial.expanded };
748
+ observation.restored = await restore(exercise, "blur") !== null;
749
+ return;
750
+ }
751
+ let clickedToNoEffect = false;
752
+ for (const key of keysFor(trigger)) {
753
+ if (!await focusForKey(exercise)) {
754
+ return;
755
+ }
756
+ const { clicks } = await probe.read(index);
757
+ keysTried.push(key);
758
+ await probe.pressKey(key);
759
+ const after = await awaitChange(exercise, timeout, clicks);
760
+ const attempt = {
761
+ key,
762
+ expandedBefore: initial.expanded,
763
+ expandedAfter: after.expanded,
764
+ contentChanged: contentChanged(exercise, initial, after),
765
+ restoredBy: null
766
+ };
767
+ attempts.push(attempt);
768
+ const stopped = noteBlocked(after);
769
+ if (changedFromInitial(after)) {
770
+ await awaitSettled(exercise);
771
+ attempt.restoredBy = await restore(exercise, key);
772
+ if (attempt.restoredBy === null) {
773
+ observation.restored = false;
774
+ return;
775
+ }
776
+ } else if (after.clicks > clicks) {
777
+ clickedToNoEffect = true;
778
+ }
779
+ if (stopped) {
780
+ return;
781
+ }
782
+ if (clickedToNoEffect) {
783
+ break;
784
+ }
785
+ }
786
+ if (attempts.some((attempt) => attempt.restoredBy !== null)) {
787
+ return;
788
+ }
789
+ if (clickedToNoEffect) {
790
+ observation.pointer.click = false;
791
+ await tryHover();
792
+ } else {
793
+ await tryPointer();
794
+ }
795
+ };
796
+ await exerciseKeys();
797
+ const last = await probe.read(index);
798
+ if (!last.connected) {
799
+ throw new TriggerRemoved();
800
+ }
801
+ noteBlocked(last);
802
+ if (observation.restored && (last.expanded !== initial.expanded || last.controlled !== initial.controlled)) {
803
+ observation.restored = await restore(exercise, keysTried.at(-1) ?? "click") !== null;
804
+ }
805
+ };
806
+ try {
807
+ await operate();
808
+ } catch (error) {
809
+ if (error instanceof TriggerRemoved) {
810
+ observation.removed = true;
811
+ try {
812
+ await probe.pressKey("Escape");
813
+ } catch {
814
+ }
815
+ } else if (error instanceof DocumentReplacedError) {
816
+ observation.navigated = true;
817
+ } else {
818
+ throw error;
819
+ }
820
+ }
821
+ if (!observation.navigated) {
822
+ try {
823
+ await probe.end(index);
824
+ } catch (error) {
825
+ if (!(error instanceof DocumentReplacedError)) {
826
+ throw error;
827
+ }
828
+ observation.navigated = true;
829
+ }
830
+ }
831
+ return done();
832
+ }
833
+ async function runDisclosureLoop(probe, triggers, timeout) {
834
+ const exercised = [];
835
+ for (const [index, trigger] of triggers.entries()) {
836
+ const outcome = await exerciseTrigger(probe, index, trigger, timeout);
837
+ exercised.push(outcome);
838
+ if (outcome.observation.navigated) {
839
+ return { exercised, stopped: "navigated" };
840
+ }
841
+ }
842
+ return { exercised, stopped: null };
843
+ }
844
+ function createAdaptorProbe(adaptor) {
845
+ const call = async (method, ...args) => {
846
+ let answer;
847
+ try {
848
+ answer = await adaptor.evaluate(callDisclosureScript, STASH_KEY, method, ...args);
849
+ } catch (error) {
850
+ await new Promise((resolve) => setTimeout(resolve, 100));
851
+ let installed = false;
852
+ try {
853
+ installed = await adaptor.evaluate(isDisclosureInstalledScript, STASH_KEY);
854
+ } catch {
855
+ }
856
+ if (installed) {
857
+ throw error;
858
+ }
859
+ throw new DocumentReplacedError();
860
+ }
861
+ if (answer !== null && typeof answer === "object" && "gone" in answer) {
862
+ throw new DocumentReplacedError();
863
+ }
864
+ return answer;
865
+ };
866
+ return {
867
+ begin: (index) => call("begin", index),
868
+ focus: (index) => call("focus", index),
869
+ read: (index) => call("read", index),
870
+ ready: (index, action) => call("ready", index, action),
871
+ blur: (index) => call("blur", index),
872
+ pressKey: (key) => adaptor.pressKey(key),
873
+ click: (index) => call("click", index),
874
+ hover: (index, on) => call("hover", index, on),
875
+ end: (index) => call("end", index),
876
+ sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms))
877
+ };
878
+ }
879
+ async function selectorsFor(adaptor, collection) {
880
+ const count = collection.triggers.length;
881
+ const all = await stashedElementSelectors(
882
+ adaptor,
883
+ STASH_KEY,
884
+ Array.from({ length: count + collection.skipped.length }, (_, i) => i)
885
+ );
886
+ const withControls = collection.triggers.flatMap(
887
+ (trigger, i) => trigger.hasControlled ? [i] : []
888
+ );
889
+ const found = await stashedElementSelectors(adaptor, `${STASH_KEY}Controls`, withControls);
890
+ const controls = collection.triggers.map(() => null);
891
+ for (const [i, index] of withControls.entries()) {
892
+ controls[index] = found[i];
893
+ }
894
+ return { triggers: all.slice(0, count), controls, skipped: all.slice(count) };
895
+ }
896
+ async function runDisclosureOperabilityAudit(adaptor, options = {}) {
897
+ const triggerLimit = options.triggerLimit ?? DEFAULT_TRIGGER_LIMIT;
898
+ const timeout = options.activationTimeout ?? DEFAULT_ACTIVATION_TIMEOUT_MS;
899
+ const riskyNamePattern = options.riskyNamePattern === void 0 ? DEFAULT_RISKY_NAME_PATTERN : options.riskyNamePattern;
900
+ if (riskyNamePattern !== null) {
901
+ new RegExp(riskyNamePattern, "i");
902
+ }
903
+ await adaptor.ensureFocusReporting();
904
+ const collection = await adaptor.evaluate(
905
+ installDisclosureScript,
906
+ STASH_KEY,
907
+ triggerLimit,
908
+ SKIP_LIMIT,
909
+ SCAN_LIMIT,
910
+ { includeControlsOnly: options.includeControlsOnly ?? false, riskyNamePattern }
911
+ );
912
+ let stopped = null;
913
+ try {
914
+ const selectors = await selectorsFor(adaptor, collection);
915
+ await releaseStashedElements(adaptor, STASH_KEY);
916
+ await releaseStashedElements(adaptor, `${STASH_KEY}Controls`);
917
+ const loop = await runDisclosureLoop(createAdaptorProbe(adaptor), collection.triggers, timeout);
918
+ stopped = loop.stopped;
919
+ const failed = [];
920
+ const needsReview = [];
921
+ const passed = [];
922
+ for (const [index, { observation, keysTried }] of loop.exercised.entries()) {
923
+ const collected = collection.triggers[index];
924
+ const { verdict, signals } = classifyTrigger(observation);
925
+ const trigger = {
926
+ selector: selectors.triggers[index],
927
+ html: truncateHtml(collected.html),
928
+ role: collected.role,
929
+ expanded: collected.expanded,
930
+ controls: selectors.controls[index],
931
+ signals,
932
+ keysTried,
933
+ attempts: [...observation.attempts],
934
+ pointer: observation.pointer,
935
+ openedOnFocus: observation.openedOnFocus !== null,
936
+ restored: observation.restored && !observation.removed && !observation.navigated
937
+ };
938
+ (verdict === "failed" ? failed : verdict === "review" ? needsReview : passed).push(trigger);
939
+ }
940
+ const skipped = collection.skipped.map(({ html, reason }, i) => ({
941
+ selector: selectors.skipped[i],
942
+ html: truncateHtml(html),
943
+ reason
944
+ }));
945
+ return {
946
+ failed,
947
+ needsReview,
948
+ passed,
949
+ skipped,
950
+ stopped,
951
+ summary: {
952
+ checked: loop.exercised.length,
953
+ failed: failed.length,
954
+ needsReview: needsReview.length,
955
+ passed: passed.length,
956
+ skipped: collection.skippedTotal,
957
+ unchecked: collection.eligible - loop.exercised.length
958
+ }
959
+ };
960
+ } finally {
961
+ if (stopped === null) {
962
+ try {
963
+ await adaptor.evaluate(callDisclosureScript, STASH_KEY, "finish");
964
+ } catch {
965
+ }
966
+ }
967
+ }
968
+ }
969
+ export {
970
+ DEFAULT_ACTIVATION_TIMEOUT_MS,
971
+ DEFAULT_RISKY_NAME_PATTERN,
972
+ DEFAULT_TRIGGER_LIMIT,
973
+ classifyTrigger,
974
+ runDisclosureOperabilityAudit
975
+ };
976
+ //# sourceMappingURL=index.js.map