a11yengine-mcp 0.0.0-stage → 1.4.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.mjs ADDED
@@ -0,0 +1,2461 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ import { chromium } from "playwright-core";
5
+ // src/utils/engineInfo.ts
6
+ /**
7
+ * Facts about the scanning engine that appear in user-facing reports.
8
+ * Keep these in sync with package.json; engineInfo.test.ts fails if they drift,
9
+ * so exported reports never misstate what produced them.
10
+ */
11
+ var AXE_CORE_VERSION = "4.12.1";
12
+ // src/utils/aiMock.ts
13
+ function getAIFix(ruleId, elementHtml, selector) {
14
+ const cleanHtml = elementHtml.trim();
15
+ const selectorSnippet = selector ? selector.split(" > ").pop() || selector : "target element";
16
+ const extractVisibleText = (html) => html.replace(/<[^>]*>/g, " ").replace(/\s+/g, " ").trim();
17
+ if (cleanHtml.includes("click") && (cleanHtml.startsWith("<div") || cleanHtml.startsWith("<span"))) return {
18
+ explanation: "An interactive action is attached to a non-interactive <div> or <span>. Screen readers will not announce this control as clickable, and keyboard users cannot navigate or press it via Tab/Enter/Space.",
19
+ whereToFix: `Target <${cleanHtml.startsWith("<span") ? "span" : "div"}> matching: ${selectorSnippet}`,
20
+ whatToDo: [
21
+ "1. Replace the non-semantic tag with a native <button type=\"button\"> (or add role=\"button\" tabIndex={0}).",
22
+ "2. Add a keyboard listener for Enter and Space keys if keeping a custom element.",
23
+ "3. Provide an accessible label if the element only contains an icon."
24
+ ],
25
+ attributesToApply: "type=\"button\" aria-label=\"Perform action\"",
26
+ reactCode: `// Option A (Recommended): Use native button or your Design System Button (Shadcn/MUI)\n<Button type="button" onClick={handleClick}>\n Perform Action\n</Button>\n\n// Option B: If retaining custom container, add accessibility contract\n<div\n role="button"\n tabIndex={0}\n onClick={handleClick}\n onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); handleClick(); } }}\n>\n Perform Action\n</div>`,
27
+ tailwindCode: `<!-- Replace div with native button preserving your existing utility classes -->\n<button\n type="button"\n onclick="handleClick()"\n class="px-4 py-2 bg-indigo-600 text-white rounded font-medium focus:ring-2 focus:ring-indigo-400 focus:outline-none"\n>\n Perform Action\n</button>`,
28
+ vueCode: `<template>\n <!-- Replace with native button -->\n <button\n type="button"\n @click="handleClick"\n class="px-4 py-2 bg-indigo-600 text-white rounded font-medium focus:ring-2 focus:ring-indigo-400 focus:outline-none"\n >\n Perform Action\n </button>\n</template>`
29
+ };
30
+ switch (ruleId) {
31
+ case "color-contrast": return {
32
+ explanation: "The text color contrast ratio fails WCAG 2.2 AA (requires >= 4.5:1 for normal text, 3:1 for large text 18pt+). Sighted users in bright environments and visually impaired users cannot read this text.",
33
+ whereToFix: `Text node within: ${selectorSnippet}`,
34
+ whatToDo: [
35
+ "1. Darken foreground text color on light backgrounds, or lighten it on dark backgrounds.",
36
+ "2. Ensure the resulting contrast ratio achieves at least 4.5:1 against the computed background.",
37
+ "3. Avoid using opacity/transparency on text elements that degrades contrast."
38
+ ],
39
+ attributesToApply: "className=\"text-slate-900 dark:text-slate-100\"",
40
+ reactCode: `// Update text color class to meet 4.5:1 ratio\n<span className="text-slate-900 dark:text-slate-100 font-medium">\n Accessible Notification Text\n</span>`,
41
+ tailwindCode: `<!-- Use high-contrast color tokens (>= 4.5:1) -->\n<span class="text-slate-900 dark:text-slate-100 font-medium">\n Accessible Notification Text\n</span>`,
42
+ vueCode: `<template>\n <span class="text-slate-900 dark:text-slate-100 font-medium">\n Accessible Notification Text\n </span>\n</template>`
43
+ };
44
+ case "image-alt": return {
45
+ explanation: "The image is missing an 'alt' attribute. Screen readers announce missing alt images as raw image filenames (e.g. 'IMG_4920.png'), providing no context to blind visitors.",
46
+ whereToFix: `Target <img> matching: ${selectorSnippet}`,
47
+ whatToDo: ["1. Add alt=\"...\" describing the purpose and content of this image.", "2. If the image is purely decorative/ambient, explicitly add alt=\"\" or aria-hidden=\"true\"."],
48
+ attributesToApply: "alt=\"Clear description of the image content\"",
49
+ reactCode: `// Informative Image:\n<Image\n src="/banner.png"\n alt="Analytics dashboard showing real-time conversion metrics"\n/>\n\n// Decorative Image:\n<Image src="/pattern.svg" alt="" aria-hidden="true" />`,
50
+ tailwindCode: `<!-- Informative image with descriptive alt text -->\n<img src="/banner.png" alt="Analytics dashboard showing real-time conversion metrics" class="rounded-lg shadow" />`,
51
+ vueCode: `<template>\n <img src="/banner.png" alt="Analytics dashboard showing real-time conversion metrics" class="rounded-lg shadow" />\n</template>`
52
+ };
53
+ case "label": return {
54
+ explanation: "This input field is not associated with a descriptive label. Screen reader users will only hear 'edit text' without knowing what data is requested (Name, Email, Password, etc.).",
55
+ whereToFix: `Form control matching: ${selectorSnippet}`,
56
+ whatToDo: ["1. Create an explicit <label> element with htmlFor=\"<input-id>\" matching the input's id.", "2. Alternatively, provide an aria-label or aria-labelledby attribute directly on the input component."],
57
+ attributesToApply: "id=\"user-email\" htmlFor=\"user-email\"",
58
+ reactCode: `// Option A: Explicit Label Link (Recommended)\n<div className="flex flex-col gap-1.5">\n <Label htmlFor="user-email">Email Address</Label>\n <Input id="user-email" type="email" placeholder="name@company.com" />\n</div>\n\n// Option B: Direct ARIA label\n<Input aria-label="Email Address" type="email" placeholder="name@company.com" />`,
59
+ tailwindCode: `<!-- Explicit label-input pairing -->\n<div class="flex flex-col gap-1.5">\n <label for="user-email" class="text-sm font-semibold text-slate-200">Email Address</label>\n <input id="user-email" type="email" placeholder="name@company.com" class="px-3 py-2 bg-slate-900 border rounded" />\n</div>`,
60
+ vueCode: `<template>\n <div class="flex flex-col gap-1.5">\n <label for="user-email" class="text-sm font-semibold text-slate-200">Email Address</label>\n <input id="user-email" type="email" placeholder="name@company.com" class="px-3 py-2 bg-slate-900 border rounded" />\n </div>\n</template>`
61
+ };
62
+ case "heading-order": return {
63
+ explanation: "Heading levels do not follow a sequential hierarchy (e.g. jumping from <h1> directly to <h3>). Screen reader users navigate pages by jumping between headings to build a mental map of content.",
64
+ whereToFix: `Heading element matching: ${selectorSnippet}`,
65
+ whatToDo: ["1. Adjust heading tag level (h1 -> h2 -> h3) sequentially without skipping levels.", "2. Use CSS classes for visual font size rather than skipping semantic heading levels."],
66
+ attributesToApply: "<h2> (descend sequentially from h1)",
67
+ reactCode: `// Adjust heading level to maintain sequential hierarchy\n<h1 className="text-3xl font-bold">Main Title</h1>\n<h2 className="text-2xl font-semibold">Section Subheading</h2>\n<h3 className="text-xl font-medium">Subsection Details</h3>`,
68
+ tailwindCode: `<!-- Sequential hierarchy with Tailwind styling -->\n<h1 class="text-3xl font-bold">Main Title</h1>\n<h2 class="text-2xl font-semibold">Section Subheading</h2>\n<h3 class="text-xl font-medium">Subsection Details</h3>`,
69
+ vueCode: `<template>\n <h1 class="text-3xl font-bold">Main Title</h1>\n <h2 class="text-2xl font-semibold">Section Subheading</h2>\n <h3 class="text-xl font-medium">Subsection Details</h3>\n</template>`
70
+ };
71
+ case "button-name":
72
+ case "link-name":
73
+ case "custom-aria-icon-missing": return {
74
+ explanation: "This interactive control has no readable text or accessible label (common on icon-only buttons). Screen readers announce it as 'button' or 'link' with zero indication of its action.",
75
+ whereToFix: `Interactive icon control matching: ${selectorSnippet}`,
76
+ whatToDo: ["1. Add an aria-label attribute specifying the exact action (e.g. aria-label=\"Close dialog\").", "2. Alternatively, include a visually hidden <span className=\"sr-only\">Label</span> inside the button."],
77
+ attributesToApply: "aria-label=\"Close dialog modal\"",
78
+ reactCode: `// Shadcn / Custom Button:\n<Button variant="ghost" size="icon" aria-label="Close dialog modal" onClick={onClose}>\n <X className="w-4 h-4" />\n</Button>\n\n// Or with visually hidden text:\n<button onClick={onClose}>\n <X className="w-4 h-4" />\n <span className="sr-only">Close dialog modal</span>\n</button>`,
79
+ tailwindCode: `<!-- Add aria-label to icon button -->\n<button type="button" aria-label="Close dialog modal" class="p-2 rounded hover:bg-slate-800">\n <svg class="w-5 h-5"><!-- Icon --></svg>\n</button>`,
80
+ vueCode: `<template>\n <button type="button" aria-label="Close dialog modal" @click="onClose" class="p-2 rounded hover:bg-slate-800">\n <svg class="w-5 h-5"><!-- Icon --></svg>\n </button>\n</template>`
81
+ };
82
+ case "custom-focus-outline-reset":
83
+ case "custom-focus-indicator-quality": return {
84
+ explanation: "Keyboard focus outline is removed (via outline:none or focus:outline-none) without providing an alternative visible indicator. Sighted keyboard navigators cannot see which element is active.",
85
+ whereToFix: `Focusable element matching: ${selectorSnippet}`,
86
+ whatToDo: ["1. Replace 'outline: none' with a prominent visible focus ring (focus-visible:ring-2).", "2. Ensure the focus ring contrast ratio is >= 3:1 against adjacent background colors."],
87
+ attributesToApply: "className=\"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-indigo-500 focus-visible:ring-offset-2\"",
88
+ reactCode: `// Add high-contrast focus ring for keyboard navigation\n<Button className="focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-indigo-500 focus-visible:ring-offset-2">\n Submit Form\n</Button>`,
89
+ tailwindCode: `<!-- Visible focus ring on keyboard tab -->\n<button class="px-4 py-2 bg-indigo-600 text-white rounded focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-indigo-500 focus-visible:ring-offset-2">\n Submit Form\n</button>`,
90
+ vueCode: `<template>\n <button class="px-4 py-2 bg-indigo-600 text-white rounded focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-indigo-500 focus-visible:ring-offset-2">\n Submit Form\n </button>\n</template>`
91
+ };
92
+ case "custom-tabindex-improper": return {
93
+ explanation: "Hardcoded positive tabindex (tabindex > 0) disrupts the sequential document reading order, causing jarring focus jumps across the layout for keyboard users.",
94
+ whereToFix: `Element matching: ${selectorSnippet}`,
95
+ whatToDo: ["1. Remove positive tabindex values (e.g. tabindex=\"3\").", "2. Rely on natural DOM source ordering, or use tabindex=\"0\" to include non-native items in natural order."],
96
+ attributesToApply: "tabIndex={0} (or remove positive tabIndex)",
97
+ reactCode: `// Remove positive tabindex; let DOM order dictate sequence\n<input type="text" placeholder="First Name" />\n<input type="text" placeholder="Last Name" />`,
98
+ tailwindCode: `<!-- Natural DOM order without positive tabindex -->\n<input type="text" placeholder="First Name" class="px-3 py-2 border rounded" />\n<input type="text" placeholder="Last Name" class="px-3 py-2 border rounded" />`,
99
+ vueCode: `<template>\n <input type="text" placeholder="First Name" class="px-3 py-2 border rounded" />\n <input type="text" placeholder="Last Name" class="px-3 py-2 border rounded" />\n</template>`
100
+ };
101
+ case "custom-keyboard-nav-missing": return {
102
+ explanation: "Element has click/action interactions but cannot be focused or triggered using only a keyboard.",
103
+ whereToFix: `Interactive container matching: ${selectorSnippet}`,
104
+ whatToDo: ["1. Convert to native <button type=\"button\">, or add tabIndex={0} and role=\"button\".", "2. Attach an onKeyDown listener handling 'Enter' and 'Space' keypresses."],
105
+ attributesToApply: "role=\"button\" tabIndex={0} onKeyDown={handleKeyDown}",
106
+ reactCode: `<div\n role="button"\n tabIndex={0}\n onClick={handleAction}\n onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); handleAction(); } }}\n className="cursor-pointer focus:ring-2 focus:ring-indigo-500"\n>\n Interactive Element\n</div>`,
107
+ tailwindCode: `<div role="button" tabindex="0" onclick="handleAction()" onkeydown="if(event.key==='Enter'||event.key===' '){event.preventDefault();handleAction();}" class="cursor-pointer focus:ring-2 focus:ring-indigo-500">\n Interactive Element\n</div>`,
108
+ vueCode: `<template>\n <div role="button" :tabindex="0" @click="handleAction" @keydown.enter.space.prevent="handleAction" class="cursor-pointer focus:ring-2 focus:ring-indigo-500">\n Interactive Element\n </div>\n</template>`
109
+ };
110
+ case "custom-accessible-name-mismatch": {
111
+ const visibleText = extractVisibleText(cleanHtml) || "this control";
112
+ return {
113
+ explanation: "Visible label text does not match the aria-label (WCAG 2.5.3 Label in Name). Speech-input users speaking the visible word on the screen cannot activate this control.",
114
+ whereToFix: `Button / Link matching: ${selectorSnippet}`,
115
+ whatToDo: [`1. Ensure the visible text ("${visibleText}") is included in the aria-label string.`, "2. Place the visible text at the beginning of the aria-label."],
116
+ attributesToApply: `aria-label="${visibleText}"`,
117
+ reactCode: `// Ensure visible text "${visibleText}" starts or is included in the aria-label\n<Button aria-label="${visibleText}">\n ${visibleText}\n</Button>`,
118
+ tailwindCode: `<!-- Visible text included in aria-label -->\n<button aria-label="${visibleText}" class="px-4 py-2 bg-indigo-600 text-white rounded font-bold">\n ${visibleText}\n</button>`,
119
+ vueCode: `<template>\n <button aria-label="${visibleText}" class="px-4 py-2 bg-indigo-600 text-white rounded font-bold">\n ${visibleText}\n </button>\n</template>`
120
+ };
121
+ }
122
+ case "custom-widget-contract": return {
123
+ explanation: "Collapsible accordion or tab element has aria-expanded but is missing an aria-controls reference to the target collapsible container ID.",
124
+ whereToFix: `Collapsible trigger matching: ${selectorSnippet}`,
125
+ whatToDo: ["1. Add aria-controls=\"<panel-id>\" matching the ID of the controlled panel.", "2. Ensure the panel has a matching id attribute and role=\"region\"."],
126
+ attributesToApply: "aria-expanded={isOpen} aria-controls=\"faq-answer-1\"",
127
+ reactCode: `// Link trigger with target panel\n<button\n type="button"\n aria-expanded={isOpen}\n aria-controls="faq-answer-1"\n onClick={() => setIsOpen(!isOpen)}\n>\n Frequently Asked Questions\n</button>\n<div id="faq-answer-1" role="region" hidden={!isOpen}>\n Answer details...\n</div>`,
128
+ tailwindCode: `<button type="button" aria-expanded="false" aria-controls="panel-1" onclick="toggle()">FAQ</button>\n<div id="panel-1" role="region" hidden>Answer details...</div>`,
129
+ vueCode: `<template>\n <button type="button" :aria-expanded="isOpen" aria-controls="panel-1" @click="isOpen = !isOpen">FAQ</button>\n <div id="panel-1" role="region" :hidden="!isOpen">Answer details...</div>\n</template>`
130
+ };
131
+ case "custom-touch-target-size": return {
132
+ explanation: "Interactive target is smaller than 24x24px (WCAG 2.5.8 Target Size Minimum), causing touch errors for mobile users and motor-impaired individuals.",
133
+ whereToFix: `Touch target matching: ${selectorSnippet}`,
134
+ whatToDo: ["1. Increase component dimensions or padding to achieve at least 24x24px (44x44px recommended).", "2. Alternatively, ensure adjacent interactive targets maintain at least 24px center-to-center spacing."],
135
+ attributesToApply: "className=\"min-w-[24px] min-h-[24px] p-2\"",
136
+ reactCode: `// Ensure target is at least 24x24px\n<Button size="icon" className="min-w-[24px] min-h-[24px] p-2">\n <Icon className="w-4 h-4" />\n</Button>`,
137
+ tailwindCode: `<button class="min-w-[24px] min-h-[24px] p-2 flex items-center justify-center">\n <svg class="w-4 h-4">...</svg>\n</button>`,
138
+ vueCode: `<template>\n <button class="min-w-[24px] min-h-[24px] p-2 flex items-center justify-center">\n <svg class="w-4 h-4">...</svg>\n </button>\n</template>`
139
+ };
140
+ case "custom-color-alone-required": return {
141
+ explanation: "Required input status is conveyed solely through red color without a text or glyph indicator (WCAG 1.4.1 Use of Color). Colorblind users cannot determine required fields.",
142
+ whereToFix: `Required input matching: ${selectorSnippet}`,
143
+ whatToDo: ["1. Add an asterisk '*' or '(required)' text inside the associated <label>.", "2. Add required and aria-required=\"true\" attributes to the input element."],
144
+ attributesToApply: "required aria-required=\"true\"",
145
+ reactCode: `<Label htmlFor="name">\n Full Name <span className="text-red-500" aria-hidden="true">*</span>\n <span className="sr-only">(required)</span>\n</Label>\n<Input id="name" required aria-required="true" />`,
146
+ tailwindCode: `<label for="name">Full Name <span class="text-red-500" aria-hidden="true">*</span> <span class="sr-only">(required)</span></label>\n<input id="name" required aria-required="true" class="border p-2" />`,
147
+ vueCode: `<template>\n <label for="name">Full Name <span class="text-red-500" aria-hidden="true">*</span></label>\n <input id="name" required aria-required="true" class="border p-2" />\n</template>`
148
+ };
149
+ default: return {
150
+ explanation: `This element violates the standard WCAG rule "${ruleId}". Blind or visually impaired individuals using screen readers or keyboard navigation may be blocked from correctly parsing, focusing, or interacting with this component.`,
151
+ whereToFix: `Target element matching: ${selectorSnippet}`,
152
+ whatToDo: ["1. Review element markup for proper semantic tags and ARIA contracts.", "2. Ensure high contrast, keyboard focusability, and descriptive accessible names."],
153
+ attributesToApply: "aria-label=\"Accessible element label\"",
154
+ reactCode: `// Wrap element with semantic tags and accessible attributes\n<div className="p-4 bg-slate-900 border border-slate-800 rounded">\n <span className="text-slate-100 font-medium">Accessible Content</span>\n</div>`,
155
+ tailwindCode: `<!-- Accessible markup preserving structure -->\n<div class="p-4 bg-slate-900 border border-slate-800 rounded">\n <span class="text-slate-100 font-medium">Accessible Content</span>\n</div>`,
156
+ vueCode: `<template>\n <div class="p-4 bg-slate-900 border border-slate-800 rounded">\n <span class="text-slate-100 font-medium">Accessible Content</span>\n </div>\n</template>`
157
+ };
158
+ }
159
+ }
160
+ // src/utils/findingPolicy.ts
161
+ /**
162
+ * Which findings may be reported as confirmed violations.
163
+ *
164
+ * Rule: a rule counts as a violation (in totals, scores, the ACR, everywhere) only when
165
+ * the ACT-rules benchmark (`npm run benchmark:act`) measures at least
166
+ * MIN_CONFIRMED_PRECISION precision for it over at least MIN_SCORED_CASES test cases.
167
+ * Everything else is reported under "Needs review" for a person to verify.
168
+ *
169
+ * - axe-core rules are confirmed by default (axe is benchmarked publicly by Deque and
170
+ * by our benchmark); a rule is listed in DEMOTED_AXE_RULES when our benchmark
171
+ * measures it below the bar.
172
+ * - A11yEngine heuristics start in Needs review and are listed in CONFIRMED_HEURISTICS
173
+ * only once the benchmark shows they meet the bar.
174
+ *
175
+ * The benchmark prints any rule whose classification disagrees with its measured
176
+ * precision, and `--check` fails the release when that happens.
177
+ */
178
+ var MIN_CONFIRMED_PRECISION = .9;
179
+ var TOOL_NAME = "A11yEngine";
180
+ var TOOL_VERSION = "1.4.0";
181
+ var TOOL_URL = "https://www.a11yengine.pro";
182
+ var REPORT_LIMITATIONS = [
183
+ "Automated testing detects only a subset of WCAG failures; a report with no confirmed findings does not mean the page conforms to WCAG or any law.",
184
+ "Findings with status \"needs_review\" may be false positives. Verify each one before changing code.",
185
+ "Results describe the rendered page at scan time; content behind interactions, logins or other states was not evaluated unless it was visible during the scan."
186
+ ];
187
+ var MAX_HTML_CHARS = 400;
188
+ /**
189
+ * Every WCAG success criterion a finding maps to. axe rules often map to several
190
+ * (e.g. `label` -> 1.3.1 and 4.1.2) via tags like "wcag131"; wcagSC holds only one.
191
+ */
192
+ function wcagCriteriaOf(v) {
193
+ const criteria = /* @__PURE__ */ new Set();
194
+ if (v.wcagSC) criteria.add(v.wcagSC);
195
+ for (const tag of v.wcagTags || []) {
196
+ const m = /^wcag(\d)(\d)(\d+)$/.exec(tag);
197
+ if (m) criteria.add(`${m[1]}.${m[2]}.${m[3]}`);
198
+ }
199
+ return [...criteria].sort((a, b) => a.localeCompare(b, void 0, { numeric: true }));
200
+ }
201
+ function sourceOf(v) {
202
+ if ((v.wcagTags || []).includes("custom-heuristic")) return "a11yengine-heuristic";
203
+ if (v.reviewReason?.startsWith("axe-core could not decide")) return "axe-core-incomplete";
204
+ return "axe-core";
205
+ }
206
+ function remediationSteps(v) {
207
+ const html = v.elementHtml || "";
208
+ const steps = getAIFix(v.ruleId, html, v.selector || "").whatToDo || [];
209
+ const generic = getAIFix("__no_template__", html, v.selector || "").whatToDo || [];
210
+ if (JSON.stringify(steps) === JSON.stringify(generic)) return [];
211
+ return steps.map((s) => s.replace(/^\d+\.\s*/, ""));
212
+ }
213
+ function toFinding(v, status) {
214
+ const html = v.elementHtml || "";
215
+ const finding = {
216
+ id: v.id,
217
+ ruleId: v.ruleId,
218
+ status,
219
+ source: sourceOf(v),
220
+ severity: v.severity,
221
+ wcag: (() => {
222
+ const criteria = wcagCriteriaOf(v);
223
+ return criteria.length ? {
224
+ criteria,
225
+ level: v.wcagLevel ?? null
226
+ } : null;
227
+ })(),
228
+ message: v.description,
229
+ help: v.help,
230
+ helpUrl: v.helpUrl,
231
+ target: {
232
+ selector: v.selector,
233
+ html: html.length > MAX_HTML_CHARS ? html.slice(0, MAX_HTML_CHARS) + "..." : html
234
+ },
235
+ remediation: {
236
+ steps: remediationSteps(v),
237
+ source: "a11yengine-template"
238
+ }
239
+ };
240
+ if (v.contrast) finding.evidence = { contrast: { ...v.contrast } };
241
+ if (status === "needs_review") finding.reviewReason = v.reviewReason || "Not confirmed by a rule that meets the precision policy. Verify manually.";
242
+ return finding;
243
+ }
244
+ function buildAgentReport(report, scannedAt = (/* @__PURE__ */ new Date()).toISOString()) {
245
+ const confirmed = report.sections.flatMap((s) => s.violations.map((v) => toFinding(v, "confirmed")));
246
+ const review = (report.needsReview || []).map((v) => toFinding(v, "needs_review"));
247
+ return {
248
+ schemaVersion: "1.0",
249
+ tool: {
250
+ name: TOOL_NAME,
251
+ version: TOOL_VERSION,
252
+ url: TOOL_URL,
253
+ engines: { axeCore: AXE_CORE_VERSION }
254
+ },
255
+ target: {
256
+ url: report.url,
257
+ scannedAt
258
+ },
259
+ policy: {
260
+ confirmedRule: `A rule is reported as confirmed only when it measures at least ${MIN_CONFIRMED_PRECISION * 100}% precision over at least 10 test cases on the W3C ACT Rules benchmark.`,
261
+ minPrecision: MIN_CONFIRMED_PRECISION,
262
+ minScoredCases: 10,
263
+ benchmark: "W3C ACT Rules test cases (https://act-rules.github.io/)"
264
+ },
265
+ limitations: [...report.pageWarnings || [], ...REPORT_LIMITATIONS],
266
+ summary: {
267
+ confirmed: {
268
+ total: confirmed.length,
269
+ critical: confirmed.filter((f) => f.severity === "critical").length,
270
+ high: confirmed.filter((f) => f.severity === "high").length,
271
+ medium: confirmed.filter((f) => f.severity === "medium").length,
272
+ low: confirmed.filter((f) => f.severity === "low").length
273
+ },
274
+ needsReview: review.length
275
+ },
276
+ findings: [...confirmed, ...review]
277
+ };
278
+ }
279
+ // src/engine/locate.ts
280
+ /**
281
+ * Runs in the page (passed to page.evaluate, so it must be self-contained).
282
+ * Returns one location per selector, in order.
283
+ */
284
+ function locateInPage(selectors) {
285
+ const isLibrary = (file) => /node_modules|\/@fs\/|\/\.vite\/deps\/|react-dom|chunk-[A-Z0-9]+/i.test(file);
286
+ const query = (sel) => {
287
+ try {
288
+ return document.querySelector(sel);
289
+ } catch {
290
+ return null;
291
+ }
292
+ };
293
+ const fromStack = (stack) => {
294
+ if (!stack) return void 0;
295
+ for (const line of stack.split("\n")) {
296
+ const m = line.match(/\(?((?:https?|file):\/\/[^\s)]+?):(\d+):(\d+)\)?\s*$/);
297
+ if (!m) continue;
298
+ const file = m[1].replace(/\?.*$/, "");
299
+ if (isLibrary(file)) continue;
300
+ return {
301
+ file,
302
+ line: Number(m[2]),
303
+ column: Number(m[3]),
304
+ approximate: true
305
+ };
306
+ }
307
+ };
308
+ const reactInfo = (el) => {
309
+ const key = Object.keys(el).find((k) => k.startsWith("__reactFiber$") || k.startsWith("__reactInternalInstance$"));
310
+ if (!key) return null;
311
+ let fiber = el[key];
312
+ let source;
313
+ const components = [];
314
+ for (let i = 0; fiber && i < 60; i++, fiber = fiber.return) {
315
+ const ds = fiber._debugSource;
316
+ if (!source && ds?.fileName && !isLibrary(ds.fileName)) source = {
317
+ file: ds.fileName,
318
+ line: ds.lineNumber,
319
+ column: ds.columnNumber
320
+ };
321
+ if (!source && fiber._debugStack) source = fromStack(String(fiber._debugStack.stack || fiber._debugStack));
322
+ const t = fiber.type;
323
+ const name = typeof t === "function" ? t.displayName || t.name : t && typeof t === "object" ? t.displayName || t.render?.displayName || t.render?.name || t.type?.displayName || t.type?.name : null;
324
+ if (name && !/^(Anonymous|_c\d*|Fragment)$/.test(name) && components.length < 8) components.push(name);
325
+ }
326
+ return {
327
+ framework: "react",
328
+ source,
329
+ components
330
+ };
331
+ };
332
+ const vueInfo = (el) => {
333
+ let node = el;
334
+ while (node && !node.__vueParentComponent && !node.__vue__) node = node.parentElement;
335
+ if (!node) return null;
336
+ const components = [];
337
+ let source;
338
+ let inst = node.__vueParentComponent;
339
+ if (inst) for (let i = 0; inst && i < 20; i++, inst = inst.parent) {
340
+ const t = inst.type || {};
341
+ const file = t.__file;
342
+ if (!source && file && !isLibrary(file)) source = { file };
343
+ const name = t.__name || t.name || (file ? String(file).split(/[\\/]/).pop()?.replace(/\.vue$/, "") : "");
344
+ if (name && components.length < 8) components.push(name);
345
+ }
346
+ else {
347
+ let vm = node.__vue__;
348
+ for (let i = 0; vm && i < 20; i++, vm = vm.$parent) {
349
+ const file = vm.$options?.__file;
350
+ if (!source && file && !isLibrary(file)) source = { file };
351
+ const name = vm.$options?.name || vm.$options?._componentTag;
352
+ if (name && components.length < 8) components.push(name);
353
+ }
354
+ }
355
+ return {
356
+ framework: "vue",
357
+ source,
358
+ components
359
+ };
360
+ };
361
+ const svelteInfo = (el) => {
362
+ let node = el;
363
+ while (node && !node.__svelte_meta) node = node.parentElement;
364
+ const loc = node?.__svelte_meta?.loc;
365
+ if (!loc?.file) return null;
366
+ return {
367
+ framework: "svelte",
368
+ source: {
369
+ file: loc.file,
370
+ line: loc.line,
371
+ column: loc.column
372
+ },
373
+ components: [String(loc.file).split(/[\\/]/).pop().replace(/\.svelte$/, "")]
374
+ };
375
+ };
376
+ const angularInfo = (el) => {
377
+ const ng = window.ng;
378
+ if (!ng?.getOwningComponent) return null;
379
+ const components = [];
380
+ let comp = ng.getOwningComponent(el);
381
+ for (let i = 0; comp && i < 8; i++) {
382
+ components.push(comp.constructor?.name);
383
+ const host = ng.getHostElement?.(comp);
384
+ comp = host?.parentElement ? ng.getOwningComponent(host.parentElement) : null;
385
+ }
386
+ return components.length ? {
387
+ framework: "angular",
388
+ components
389
+ } : null;
390
+ };
391
+ const attrSource = (el) => {
392
+ for (let node = el; node; node = node.parentElement) {
393
+ for (const a of Array.from(node.attributes)) {
394
+ if (!a.name.startsWith("data-")) continue;
395
+ const m = a.value.match(/([\w@./\\-]+\.(?:tsx|jsx|ts|js|vue|svelte|astro|html))(?::(\d+))?(?::(\d+))?/);
396
+ if (m) return {
397
+ file: m[1],
398
+ line: m[2] ? Number(m[2]) : void 0,
399
+ column: m[3] ? Number(m[3]) : void 0
400
+ };
401
+ }
402
+ if (node !== el) break;
403
+ }
404
+ };
405
+ const hintsFor = (el) => {
406
+ const hints = [];
407
+ const add = (v) => {
408
+ const s = (v || "").trim().replace(/\s+/g, " ");
409
+ if (s && s.length <= 80 && !hints.includes(s)) hints.push(s);
410
+ };
411
+ add(el.id && `id="${el.id}"`);
412
+ for (const a of [
413
+ "data-testid",
414
+ "data-test",
415
+ "data-cy",
416
+ "data-qa"
417
+ ]) add(el.getAttribute(a) && `${a}="${el.getAttribute(a)}"`);
418
+ add(el.getAttribute("aria-label"));
419
+ add(el.getAttribute("name") && `name="${el.getAttribute("name")}"`);
420
+ add(el.getAttribute("placeholder"));
421
+ add(el.getAttribute("alt"));
422
+ const text = (el.innerText || el.textContent || "").trim();
423
+ if (text && text.length <= 60) add(text);
424
+ else if (text) add(text.slice(0, 40));
425
+ const src = el.getAttribute("src") || el.getAttribute("href");
426
+ if (src && !src.startsWith("data:") && src !== "#") add(src.split("?")[0].split("/").pop());
427
+ for (const c of Array.from(el.classList)) {
428
+ if (/[:[\]]|\d/.test(c) && !/__/.test(c)) continue;
429
+ add(c.includes("__") ? c.split("__")[0] : c);
430
+ if (hints.length > 10) break;
431
+ }
432
+ return hints.slice(0, 8);
433
+ };
434
+ const contextFor = (el) => {
435
+ const lm = el.closest("dialog,[role=\"dialog\"],[role=\"alertdialog\"],nav,header,footer,main,aside,form,section[aria-label],[role=\"navigation\"],[role=\"banner\"]");
436
+ if (!lm) return void 0;
437
+ const label = lm.getAttribute("aria-label") || lm.getAttribute("aria-labelledby") && document.getElementById(lm.getAttribute("aria-labelledby"))?.textContent?.trim();
438
+ const kind = lm.getAttribute("role") || lm.tagName.toLowerCase();
439
+ return label ? `${kind} "${label.slice(0, 40)}"` : kind;
440
+ };
441
+ return selectors.map((sel) => {
442
+ const el = query(sel);
443
+ if (!el) return {
444
+ confidence: "hints",
445
+ searchHints: [],
446
+ notFound: true
447
+ };
448
+ const info = reactInfo(el) || vueInfo(el) || svelteInfo(el) || angularInfo(el);
449
+ const source = info && "source" in info && info.source ? info.source : attrSource(el);
450
+ const loc = {
451
+ confidence: source ? source.line && !source.approximate ? "exact" : "file" : info?.components?.length ? "component" : "hints",
452
+ searchHints: hintsFor(el)
453
+ };
454
+ if (info) loc.framework = info.framework;
455
+ if (source) loc.source = source;
456
+ if (info?.components?.length) loc.components = info.components;
457
+ const ctx = contextFor(el);
458
+ if (ctx) loc.context = ctx;
459
+ return loc;
460
+ });
461
+ }
462
+ /**
463
+ * Turns framework-reported paths into project-relative ones, e.g.
464
+ * "http://localhost:5173/src/App.tsx" or "C:\\app\\src\\App.tsx" -> "src/App.tsx".
465
+ */
466
+ function relativizeSource(src, projectRoot) {
467
+ let file = src.file.replace(/\\/g, "/").replace(/\?(?:vue|t=|v=|import|direct|inline|raw|used)[^/]*$/, "");
468
+ const url = file.match(/^(?:https?|file):\/\/[^/]*(\/.*)$/);
469
+ if (url) file = decodeURIComponent(url[1].replace(/[?#].*$/, "")).replace(/^\/@fs\//, "/");
470
+ if (projectRoot) {
471
+ const root = projectRoot.replace(/\\/g, "/").replace(/\/+$/, "") + "/";
472
+ const i = file.toLowerCase().indexOf(root.toLowerCase());
473
+ if (i >= 0) file = file.slice(i + root.length);
474
+ }
475
+ if (/^\/(src|app|pages|components|lib)\//.test(file)) file = file.slice(1);
476
+ return {
477
+ ...src,
478
+ file
479
+ };
480
+ }
481
+ // src/engine/sourcemap.ts
482
+ var B64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
483
+ function decodeVlq(segment) {
484
+ const out = [];
485
+ let value = 0;
486
+ let shift = 0;
487
+ for (const ch of segment) {
488
+ const digit = B64.indexOf(ch);
489
+ if (digit < 0) return [];
490
+ value += (digit & 31) << shift;
491
+ if (digit & 32) shift += 5;
492
+ else {
493
+ out.push(value & 1 ? -(value >>> 1) : value >>> 1);
494
+ value = 0;
495
+ shift = 0;
496
+ }
497
+ }
498
+ return out;
499
+ }
500
+ /** Original 1-based line and column for a 1-based generated position, or null */
501
+ function originalPosition(mappings, line, column) {
502
+ let srcLine = 0;
503
+ let srcCol = 0;
504
+ let best = null;
505
+ const lines = mappings.split(";");
506
+ for (let l = 0; l < lines.length && l < line; l++) {
507
+ let genCol = 0;
508
+ for (const seg of lines[l].split(",")) {
509
+ if (!seg) continue;
510
+ const v = decodeVlq(seg);
511
+ genCol += v[0];
512
+ if (v.length >= 4) {
513
+ srcLine += v[2];
514
+ srcCol += v[3];
515
+ if (l === line - 1 && genCol <= column - 1) best = {
516
+ line: srcLine + 1,
517
+ column: srcCol + 1
518
+ };
519
+ }
520
+ }
521
+ }
522
+ return best;
523
+ }
524
+ /**
525
+ * Replaces approximate positions in transformed dev-server modules with original
526
+ * ones. Only modules on `pageOrigin` are fetched.
527
+ */
528
+ async function resolveSourcePositions(sources, pageOrigin) {
529
+ const maps = /* @__PURE__ */ new Map();
530
+ const mapsFor = (url) => {
531
+ if (!maps.has(url)) maps.set(url, fetch(url).then((r) => r.ok ? r.text() : "").then((code) => {
532
+ const m = code.match(/sourceMappingURL=data:application\/json;(?:charset=utf-8;)?base64,([A-Za-z0-9+/=]+)\s*$/m);
533
+ if (!m) return null;
534
+ return JSON.parse(Buffer.from(m[1], "base64").toString("utf8")).mappings;
535
+ }).catch(() => null));
536
+ return maps.get(url);
537
+ };
538
+ for (const src of sources) {
539
+ if (!src?.approximate || !src.line || !src.column) continue;
540
+ let url;
541
+ try {
542
+ url = new URL(src.file);
543
+ } catch {
544
+ continue;
545
+ }
546
+ if (url.origin !== pageOrigin) continue;
547
+ const mappings = await mapsFor(src.file);
548
+ const pos = mappings && originalPosition(mappings, src.line, src.column);
549
+ if (pos) {
550
+ src.line = pos.line;
551
+ src.column = pos.column;
552
+ delete src.approximate;
553
+ }
554
+ }
555
+ }
556
+ // src/engine/fixGuidance.ts
557
+ /** Makes a <button> look like the element it replaces */
558
+ var BUTTON_RESET_CSS = "appearance:none; background:none; border:0; padding:0; margin:0; font:inherit; color:inherit; line-height:inherit; letter-spacing:inherit; text-align:inherit; cursor:pointer;";
559
+ /** Makes an <a> look like the element it replaces */
560
+ var LINK_RESET_CSS = "color:inherit; text-decoration:none; cursor:pointer;";
561
+ var SR_ONLY = "a visually hidden class (position:absolute; width:1px; height:1px; overflow:hidden; clip:rect(0 0 0 0); white-space:nowrap)";
562
+ var GUIDE = {
563
+ "button-name": {
564
+ visualImpact: "none",
565
+ strategy: "Add aria-label=\"<what the button does>\" (or text in " + SR_ONLY + "). Do not add visible text."
566
+ },
567
+ "link-name": {
568
+ visualImpact: "none",
569
+ strategy: "Add aria-label=\"<where it goes>\" or text in " + SR_ONLY + "; for image links, give the image alt text."
570
+ },
571
+ "image-alt": {
572
+ visualImpact: "none",
573
+ strategy: "Add alt describing the image; use alt=\"\" if it is purely decorative."
574
+ },
575
+ "input-image-alt": {
576
+ visualImpact: "none",
577
+ strategy: "Add alt describing the action of the image button."
578
+ },
579
+ "role-img-alt": {
580
+ visualImpact: "none",
581
+ strategy: "Add aria-label to the element with role=\"img\"."
582
+ },
583
+ "svg-img-alt": {
584
+ visualImpact: "none",
585
+ strategy: "Add <title> inside the SVG or aria-label on it."
586
+ },
587
+ "area-alt": {
588
+ visualImpact: "none",
589
+ strategy: "Add alt to each <area>."
590
+ },
591
+ "object-alt": {
592
+ visualImpact: "none",
593
+ strategy: "Add aria-label or fallback text to the <object>."
594
+ },
595
+ label: {
596
+ visualImpact: "none",
597
+ strategy: "Keep any visible text; connect a <label for> to it, or add aria-label/aria-labelledby. If there is no visible label, use a <label> in " + SR_ONLY + ". A placeholder is not a label."
598
+ },
599
+ "select-name": {
600
+ visualImpact: "none",
601
+ strategy: "Connect a <label for> or add aria-label to the <select>."
602
+ },
603
+ "aria-input-field-name": {
604
+ visualImpact: "none",
605
+ strategy: "Add aria-label or aria-labelledby to the custom field."
606
+ },
607
+ "aria-toggle-field-name": {
608
+ visualImpact: "none",
609
+ strategy: "Add aria-label or aria-labelledby to the toggle."
610
+ },
611
+ "aria-command-name": {
612
+ visualImpact: "none",
613
+ strategy: "Add aria-label to the element with the command role."
614
+ },
615
+ "aria-dialog-name": {
616
+ visualImpact: "none",
617
+ strategy: "Point aria-labelledby at the dialog heading, or add aria-label."
618
+ },
619
+ "aria-progressbar-name": {
620
+ visualImpact: "none",
621
+ strategy: "Add aria-label to the progress bar."
622
+ },
623
+ "aria-meter-name": {
624
+ visualImpact: "none",
625
+ strategy: "Add aria-label to the meter."
626
+ },
627
+ "aria-tooltip-name": {
628
+ visualImpact: "none",
629
+ strategy: "Give the tooltip text content or aria-label."
630
+ },
631
+ "frame-title": {
632
+ visualImpact: "none",
633
+ strategy: "Add a title attribute describing the frame."
634
+ },
635
+ "document-title": {
636
+ visualImpact: "none",
637
+ strategy: "Add a descriptive <title> in the document head."
638
+ },
639
+ "html-has-lang": {
640
+ visualImpact: "none",
641
+ strategy: "Add lang to <html>, e.g. lang=\"en\"."
642
+ },
643
+ "html-lang-valid": {
644
+ visualImpact: "none",
645
+ strategy: "Use a valid language code in <html lang>."
646
+ },
647
+ "valid-lang": {
648
+ visualImpact: "none",
649
+ strategy: "Use a valid language code in the lang attribute."
650
+ },
651
+ "aria-allowed-attr": {
652
+ visualImpact: "none",
653
+ strategy: "Remove ARIA attributes the role does not support."
654
+ },
655
+ "aria-required-attr": {
656
+ visualImpact: "none",
657
+ strategy: "Add the ARIA attributes the role requires."
658
+ },
659
+ "aria-valid-attr": {
660
+ visualImpact: "none",
661
+ strategy: "Fix misspelled ARIA attribute names."
662
+ },
663
+ "aria-valid-attr-value": {
664
+ visualImpact: "none",
665
+ strategy: "Use a valid value for the ARIA attribute (IDs must exist)."
666
+ },
667
+ "aria-roles": {
668
+ visualImpact: "none",
669
+ strategy: "Use a valid ARIA role, or none."
670
+ },
671
+ "aria-hidden-focus": {
672
+ visualImpact: "none",
673
+ strategy: "Remove focusable elements from aria-hidden content, or add tabindex=\"-1\" / inert to them."
674
+ },
675
+ "aria-hidden-body": {
676
+ visualImpact: "none",
677
+ strategy: "Remove aria-hidden from <body>."
678
+ },
679
+ "duplicate-id-aria": {
680
+ visualImpact: "none",
681
+ strategy: "Make IDs referenced by ARIA unique."
682
+ },
683
+ "label-content-name-mismatch": {
684
+ visualImpact: "none",
685
+ strategy: "Make aria-label start with the visible text."
686
+ },
687
+ tabindex: {
688
+ visualImpact: "none",
689
+ strategy: "Use tabindex=\"0\" or \"-1\" only; reorder the DOM instead of positive tabindex."
690
+ },
691
+ "scrollable-region-focusable": {
692
+ visualImpact: "none",
693
+ strategy: "Add tabindex=\"0\" plus role=\"region\" and aria-label to the scroll container."
694
+ },
695
+ "meta-refresh": {
696
+ visualImpact: "none",
697
+ strategy: "Remove the timed <meta http-equiv=\"refresh\">; redirect on the server or let the user refresh."
698
+ },
699
+ "meta-viewport": {
700
+ visualImpact: "none",
701
+ strategy: "Remove user-scalable=no and maximum-scale limits from the viewport meta tag."
702
+ },
703
+ "autocomplete-valid": {
704
+ visualImpact: "none",
705
+ strategy: "Use a valid autocomplete token, e.g. autocomplete=\"email\"."
706
+ },
707
+ bypass: {
708
+ visualImpact: "none",
709
+ strategy: "Add a skip link that is hidden until focused, or landmarks such as <main> and <nav>."
710
+ },
711
+ region: {
712
+ visualImpact: "none",
713
+ strategy: "Wrap content in landmarks (<header>, <nav>, <main>, <footer>); keep existing classes on the wrapper so layout does not change."
714
+ },
715
+ "landmark-one-main": {
716
+ visualImpact: "none",
717
+ structural: true,
718
+ strategy: "Change the main content wrapper to <main>, keeping its classes."
719
+ },
720
+ "landmark-unique": {
721
+ visualImpact: "none",
722
+ strategy: "Give repeated landmarks distinct aria-label values."
723
+ },
724
+ "heading-order": {
725
+ visualImpact: "none",
726
+ structural: true,
727
+ strategy: "Change the heading to the correct level and keep its classes. If styles target the tag (e.g. h4 { … }), add a class so it still looks the same."
728
+ },
729
+ "page-has-heading-one": {
730
+ visualImpact: "none",
731
+ strategy: "Make the page title an <h1>, keeping its classes; or add an <h1> in " + SR_ONLY + "."
732
+ },
733
+ "empty-heading": {
734
+ visualImpact: "none",
735
+ strategy: "Give the heading text (visually hidden if needed) or stop using a heading element."
736
+ },
737
+ "p-as-heading": {
738
+ visualImpact: "none",
739
+ structural: true,
740
+ strategy: "Change the styled <p> to the right heading level and keep its classes."
741
+ },
742
+ list: {
743
+ visualImpact: "none",
744
+ structural: true,
745
+ strategy: "Allow only <li> (and script/template) directly inside <ul>/<ol>; keep classes on moved elements."
746
+ },
747
+ listitem: {
748
+ visualImpact: "none",
749
+ structural: true,
750
+ strategy: "Put each <li> inside a <ul> or <ol> with list-style:none; padding:0; margin:0 so the layout stays the same."
751
+ },
752
+ "definition-list": {
753
+ visualImpact: "none",
754
+ structural: true,
755
+ strategy: "Allow only <dt>/<dd> groups inside <dl>."
756
+ },
757
+ dlitem: {
758
+ visualImpact: "none",
759
+ structural: true,
760
+ strategy: "Put <dt>/<dd> inside a <dl>."
761
+ },
762
+ "nested-interactive": {
763
+ visualImpact: "none",
764
+ structural: true,
765
+ strategy: "Move the inner control out of the outer one, or make the outer element non-interactive; keep classes and use positioning so it looks the same."
766
+ },
767
+ "empty-table-header": {
768
+ visualImpact: "none",
769
+ strategy: "Give the header cell text (visually hidden if needed)."
770
+ },
771
+ "th-has-data-cells": {
772
+ visualImpact: "none",
773
+ strategy: "Make header cells label data cells, or use <td>."
774
+ },
775
+ "td-headers-attr": {
776
+ visualImpact: "none",
777
+ strategy: "Point headers attributes at <th> IDs in the same table."
778
+ },
779
+ "image-redundant-alt": {
780
+ visualImpact: "none",
781
+ strategy: "Shorten the alt so it does not repeat the surrounding text."
782
+ },
783
+ "color-contrast": {
784
+ visualImpact: "minimal",
785
+ strategy: "Change the colour where it is defined (see colorSource), to the suggested same-hue shade with the smallest change. Prefer one token or rule over per-element overrides. This is a visible change: confirm with the person before applying."
786
+ },
787
+ "link-in-text-block": {
788
+ visualImpact: "minimal",
789
+ strategy: "Keep the link colour but ensure 3:1 contrast with the surrounding text and show an underline on hover and focus; or underline links in body text."
790
+ },
791
+ "target-size": {
792
+ visualImpact: "none",
793
+ strategy: "Enlarge only the clickable area: padding with a matching negative margin, or a transparent ::after overlay with position:absolute; inset:-Npx. The icon itself stays the same size."
794
+ },
795
+ "custom-touch-target-size": {
796
+ visualImpact: "none",
797
+ strategy: "Enlarge only the clickable area (padding plus negative margin, or a transparent ::after overlay). The icon stays the same size."
798
+ },
799
+ "custom-focus-outline-reset": {
800
+ visualImpact: "minimal",
801
+ strategy: "Restore a focus indicator only for keyboard users with :focus-visible, in the brand colour (e.g. outline: 2px solid <brand>; outline-offset: 2px). Mouse users see no change."
802
+ },
803
+ "custom-focus-indicator-quality": {
804
+ visualImpact: "minimal",
805
+ strategy: "Strengthen the :focus-visible style only (keyboard users); mouse styling is unchanged."
806
+ },
807
+ "custom-skip-link-missing": {
808
+ visualImpact: "none",
809
+ strategy: "Add a \"Skip to main content\" link that is hidden until it receives keyboard focus."
810
+ },
811
+ "custom-keyboard-nav-missing": {
812
+ visualImpact: "none",
813
+ structural: true,
814
+ strategy: `Replace the element with <button type="button"> (actions) or <a href> (navigation), keeping its classes, plus a style reset (${BUTTON_RESET_CSS}). Adding tabindex alone is not enough: Enter/Space handling and the role are still missing.`
815
+ }
816
+ };
817
+ var DEFAULT = {
818
+ visualImpact: "minimal",
819
+ strategy: "Prefer semantic HTML and ARIA attributes. Do not change layout, spacing, fonts or colours unless this rule requires it; check the page afterwards with verify_fix."
820
+ };
821
+ function guidanceFor(ruleId) {
822
+ return { ...GUIDE[ruleId] || DEFAULT };
823
+ }
824
+ // src/engine/color.ts
825
+ function parseColor(input) {
826
+ const s = input.trim().toLowerCase();
827
+ let m = s.match(/^#([0-9a-f]{3}|[0-9a-f]{6})$/);
828
+ if (m) {
829
+ const h = m[1].length === 3 ? m[1].replace(/./g, (c) => c + c) : m[1];
830
+ return [
831
+ 0,
832
+ 2,
833
+ 4
834
+ ].map((i) => parseInt(h.slice(i, i + 2), 16));
835
+ }
836
+ m = s.match(/^rgba?\(\s*([\d.]+)[,\s]+([\d.]+)[,\s]+([\d.]+)/);
837
+ if (m) return [
838
+ Number(m[1]),
839
+ Number(m[2]),
840
+ Number(m[3])
841
+ ];
842
+ return null;
843
+ }
844
+ var toHex = (c) => "#" + c.map((v) => Math.round(Math.min(255, Math.max(0, v))).toString(16).padStart(2, "0")).join("");
845
+ var lin = (v) => {
846
+ const c = v / 255;
847
+ return c <= .04045 ? c / 12.92 : ((c + .055) / 1.055) ** 2.4;
848
+ };
849
+ var gam = (v) => {
850
+ return (v <= .0031308 ? 12.92 * v : 1.055 * v ** (1 / 2.4) - .055) * 255;
851
+ };
852
+ function luminance([r, g, b]) {
853
+ return .2126 * lin(r) + .7152 * lin(g) + .0722 * lin(b);
854
+ }
855
+ function contrastRatio(a, b) {
856
+ const [l1, l2] = [luminance(a), luminance(b)].sort((x, y) => y - x);
857
+ return (l1 + .05) / (l2 + .05);
858
+ }
859
+ function toOklch([r, g, b]) {
860
+ const [lr, lg, lb] = [
861
+ lin(r),
862
+ lin(g),
863
+ lin(b)
864
+ ];
865
+ const l = Math.cbrt(.4122214708 * lr + .5363325363 * lg + .0514459929 * lb);
866
+ const m = Math.cbrt(.2119034982 * lr + .6806995451 * lg + .1073969566 * lb);
867
+ const s = Math.cbrt(.0883024619 * lr + .2817188376 * lg + .6299787005 * lb);
868
+ const L = .2104542553 * l + .793617785 * m - .0040720468 * s;
869
+ const A = 1.9779984951 * l - 2.428592205 * m + .4505937099 * s;
870
+ const B = .0259040371 * l + .7827717662 * m - .808675766 * s;
871
+ return [
872
+ L,
873
+ Math.hypot(A, B),
874
+ Math.atan2(B, A)
875
+ ];
876
+ }
877
+ function fromOklch(L, C, H) {
878
+ const A = C * Math.cos(H);
879
+ const B = C * Math.sin(H);
880
+ const l = (L + .3963377774 * A + .2158037573 * B) ** 3;
881
+ const m = (L - .1055613458 * A - .0638541728 * B) ** 3;
882
+ const s = (L - .0894841775 * A - 1.291485548 * B) ** 3;
883
+ return [
884
+ gam(4.0767416621 * l - 3.3077115913 * m + .2309699292 * s),
885
+ gam(-1.2684380046 * l + 2.6097574011 * m - .3413193965 * s),
886
+ gam(-.0041960863 * l - .7034186147 * m + 1.707614701 * s)
887
+ ];
888
+ }
889
+ var inGamut = (c) => c.every((v) => v >= -.5 && v <= 255.5);
890
+ /**
891
+ * Smallest lightness change (hue and chroma kept) to `which` that reaches `required`.
892
+ * Chroma is reduced only if the colour would otherwise leave the sRGB gamut.
893
+ */
894
+ function adjust(move, fixed, required, which) {
895
+ const [L0, C0, H] = toOklch(move);
896
+ const darker = luminance(move) <= luminance(fixed);
897
+ for (let step = 1; step <= 100; step++) {
898
+ const L = L0 + (darker ? -step : step) / 100;
899
+ if (L < 0 || L > 1) break;
900
+ let C = C0;
901
+ let rgb = fromOklch(L, C, H);
902
+ while (!inGamut(rgb) && C > 0) {
903
+ C = Math.max(0, C - .005);
904
+ rgb = fromOklch(L, C, H);
905
+ }
906
+ const clamped = rgb.map((v) => Math.round(Math.min(255, Math.max(0, v))));
907
+ const ratio = contrastRatio(clamped, fixed);
908
+ if (ratio >= required) return {
909
+ change: which,
910
+ from: toHex(move),
911
+ to: toHex(clamped),
912
+ ratio: Math.round(ratio * 100) / 100,
913
+ lightnessShift: step
914
+ };
915
+ }
916
+ return null;
917
+ }
918
+ /** Brand-matched options, smallest visual change first */
919
+ function suggestContrastFix(fg, bg, required) {
920
+ const f = parseColor(fg);
921
+ const b = parseColor(bg);
922
+ if (!f || !b) return [];
923
+ return [adjust(f, b, required, "foreground"), adjust(b, f, required, "background")].filter((x) => !!x).sort((x, y) => x.lightnessShift - y.lightnessShift);
924
+ }
925
+ // src/engine/cssSource.ts
926
+ var CssSourceFinder = class CssSourceFinder {
927
+ cdp;
928
+ headers = /* @__PURE__ */ new Map();
929
+ devIds = /* @__PURE__ */ new Map();
930
+ constructor(cdp) {
931
+ this.cdp = cdp;
932
+ }
933
+ static async attach(page) {
934
+ const cdp = await page.context().newCDPSession(page);
935
+ const finder = new CssSourceFinder(cdp);
936
+ cdp.on("CSS.styleSheetAdded", (e) => finder.headers.set(e.header.styleSheetId, e.header));
937
+ await cdp.send("DOM.enable");
938
+ await cdp.send("CSS.enable");
939
+ return finder;
940
+ }
941
+ async detach() {
942
+ await this.cdp.detach().catch(() => {});
943
+ }
944
+ /** Vite injects CSS modules as <style data-vite-dev-id="/abs/path.css"> */
945
+ async fileOf(styleSheetId) {
946
+ const h = styleSheetId ? this.headers.get(styleSheetId) : void 0;
947
+ if (!h) return { startLine: 0 };
948
+ if (h.sourceURL && !/^(about:|data:)/.test(h.sourceURL)) return {
949
+ file: h.sourceURL,
950
+ startLine: h.startLine || 0,
951
+ approximate: !!h.isInline
952
+ };
953
+ if (h.ownerNode) {
954
+ const key = String(h.ownerNode);
955
+ if (!this.devIds.has(key)) {
956
+ const attrs = (await this.cdp.send("DOM.describeNode", { backendNodeId: h.ownerNode }).catch(() => null))?.node?.attributes || [];
957
+ const i = attrs.indexOf("data-vite-dev-id");
958
+ this.devIds.set(key, i >= 0 ? attrs[i + 1] : null);
959
+ }
960
+ const devId = this.devIds.get(key);
961
+ if (devId) return {
962
+ file: devId,
963
+ startLine: h.startLine || 0,
964
+ approximate: true
965
+ };
966
+ }
967
+ return { startLine: h.startLine || 0 };
968
+ }
969
+ async describeRule(rule, prop) {
970
+ const where = await this.fileOf(rule.styleSheetId);
971
+ const selector = rule.selectorList?.text || "";
972
+ const src = {
973
+ kind: "css-rule",
974
+ value: String(prop.value).trim(),
975
+ selector
976
+ };
977
+ if (where.file) src.file = where.file;
978
+ const range = prop.range || rule.style?.range;
979
+ if (range) src.line = where.startLine + range.startLine + 1;
980
+ if (where.approximate) src.approximate = true;
981
+ const utility = selector.match(/^\.((?:[a-z0-9]+:)*(?:text|bg|border|fill|stroke)-[a-z]+(?:-\d{2,3})?(?:\/\d+)?)$/i);
982
+ if (utility) src.utilityClass = utility[1].replace(/\\/g, "");
983
+ return src;
984
+ }
985
+ /** Where the element's `property` (default: color) is set, following inheritance */
986
+ async find(selector, property = "color") {
987
+ const { root } = await this.cdp.send("DOM.getDocument", { depth: 0 });
988
+ const { nodeId } = await this.cdp.send("DOM.querySelector", {
989
+ nodeId: root.nodeId,
990
+ selector
991
+ }).catch(() => ({ nodeId: 0 }));
992
+ if (!nodeId) return null;
993
+ const styles = await this.cdp.send("CSS.getMatchedStylesForNode", { nodeId });
994
+ const levels = [{
995
+ inlineStyle: styles.inlineStyle,
996
+ matchedCSSRules: styles.matchedCSSRules || []
997
+ }, ...styles.inherited || []];
998
+ const declared = (style) => (style?.cssProperties || []).filter((p) => p.name === property && p.value && !p.disabled && p.parsedOk !== false && p.range);
999
+ let found = null;
1000
+ const allRules = levels.flatMap((level) => (level.matchedCSSRules || []).filter((m) => m.rule?.origin !== "user-agent"));
1001
+ for (const level of levels) {
1002
+ const rules = (level.matchedCSSRules || []).filter((m) => m.rule?.origin !== "user-agent");
1003
+ const inline = declared(level.inlineStyle).pop();
1004
+ let best = null;
1005
+ for (const m of rules) for (const p of declared(m.rule.style)) if (!best || p.important || !best.prop.important) best = {
1006
+ rule: m.rule,
1007
+ prop: p
1008
+ };
1009
+ if (inline && !best?.prop.important) {
1010
+ found = {
1011
+ kind: "inline-style",
1012
+ value: String(inline.value).trim()
1013
+ };
1014
+ break;
1015
+ }
1016
+ if (best) {
1017
+ found = await this.describeRule(best.rule, best.prop);
1018
+ break;
1019
+ }
1020
+ }
1021
+ if (!found) return null;
1022
+ const v = found.value.match(/var\(\s*(--[\w-]+)/);
1023
+ if (v) {
1024
+ for (const m of [...allRules].reverse()) {
1025
+ const p = (m.rule.style?.cssProperties || []).find((x) => x.name === v[1] && x.value);
1026
+ if (p) {
1027
+ const where = await this.describeRule(m.rule, p);
1028
+ found.variable = {
1029
+ name: v[1],
1030
+ value: where.value,
1031
+ selector: where.selector,
1032
+ file: where.file,
1033
+ line: where.line
1034
+ };
1035
+ break;
1036
+ }
1037
+ }
1038
+ if (!found.variable) found.variable = {
1039
+ name: v[1],
1040
+ value: ""
1041
+ };
1042
+ }
1043
+ return found;
1044
+ }
1045
+ };
1046
+ // src/engine/semantics.ts
1047
+ /** Runs in the page: elements with click handlers found through framework props */
1048
+ function collectClickables() {
1049
+ const NATIVE = "a[href],button,input,select,textarea,summary,label,option,[contenteditable=\"true\"]";
1050
+ const WIDGET_ROLES = /^(button|link|tab|menuitem|menuitemcheckbox|menuitemradio|checkbox|radio|switch|option|treeitem|slider|spinbutton|combobox|gridcell|row)$/;
1051
+ const selectorOf = (el) => {
1052
+ if (el.id && document.querySelectorAll("#" + CSS.escape(el.id)).length === 1) return "#" + CSS.escape(el.id);
1053
+ const parts = [];
1054
+ let node = el;
1055
+ while (node && node !== document.body && parts.length < 6) {
1056
+ if (node.id && document.querySelectorAll("#" + CSS.escape(node.id)).length === 1) {
1057
+ parts.unshift("#" + CSS.escape(node.id));
1058
+ break;
1059
+ }
1060
+ const tag = node.tagName.toLowerCase();
1061
+ const parent = node.parentElement;
1062
+ const same = parent ? Array.from(parent.children).filter((c) => c.tagName === node.tagName) : [];
1063
+ parts.unshift(same.length > 1 ? `${tag}:nth-of-type(${same.indexOf(node) + 1})` : tag);
1064
+ node = parent;
1065
+ }
1066
+ return parts.join(" > ");
1067
+ };
1068
+ const handlerOf = (el) => {
1069
+ const propsKey = Object.keys(el).find((k) => k.startsWith("__reactProps$"));
1070
+ const props = propsKey ? el[propsKey] : null;
1071
+ const reactFn = props && (props.onClick || props.onMouseDown || props.onPointerDown);
1072
+ if (typeof reactFn === "function") return {
1073
+ fn: String(reactFn),
1074
+ via: "react"
1075
+ };
1076
+ const vei = el._vei;
1077
+ const vueFn = vei && (vei.onClick || vei.onMousedown || vei.onPointerdown);
1078
+ if (vueFn) return {
1079
+ fn: String(vueFn.value || vueFn),
1080
+ via: "vue"
1081
+ };
1082
+ const attr = el.getAttribute("onclick");
1083
+ if (attr) return {
1084
+ fn: attr,
1085
+ via: "onclick"
1086
+ };
1087
+ return null;
1088
+ };
1089
+ const found = [];
1090
+ const pointerCandidates = [];
1091
+ const all = document.body ? Array.from(document.body.querySelectorAll("*")) : [];
1092
+ for (const el of all) {
1093
+ if (found.length > 200) break;
1094
+ const tag = el.tagName.toLowerCase();
1095
+ if ([
1096
+ "script",
1097
+ "style",
1098
+ "svg",
1099
+ "path",
1100
+ "html",
1101
+ "body"
1102
+ ].includes(tag)) continue;
1103
+ const role = el.getAttribute("role") || "";
1104
+ const isLink = tag === "a";
1105
+ const isButton = tag === "button" || role === "button" || tag === "input" && /^(button|submit)$/i.test(el.type);
1106
+ if (el.parentElement?.closest(NATIVE)) continue;
1107
+ const h = handlerOf(el);
1108
+ const style = getComputedStyle(el);
1109
+ const pointer = style.cursor === "pointer";
1110
+ if (!isLink && !isButton) {
1111
+ if (WIDGET_ROLES.test(role) || el.matches(NATIVE)) continue;
1112
+ if (el.querySelector("a[href],button")) continue;
1113
+ if (!h) {
1114
+ if (pointer && style.visibility !== "hidden" && el.offsetParent !== null) pointerCandidates.push(selectorOf(el));
1115
+ continue;
1116
+ }
1117
+ if (!pointer) continue;
1118
+ } else if (!h) {
1119
+ const hrefOk = isLink && !!el.getAttribute("href") && el.getAttribute("href") !== "#" && !/^javascript:/i.test(el.getAttribute("href") || "");
1120
+ if (isLink && !hrefOk || isButton && !isLink) pointerCandidates.push(selectorOf(el));
1121
+ continue;
1122
+ }
1123
+ found.push({
1124
+ selector: selectorOf(el),
1125
+ tag,
1126
+ html: el.outerHTML.slice(0, 300),
1127
+ href: el.getAttribute("href"),
1128
+ handler: h ? h.fn.slice(0, 600) : "",
1129
+ via: h ? h.via : "listener",
1130
+ pointer,
1131
+ display: style.display,
1132
+ boxSizing: style.boxSizing
1133
+ });
1134
+ }
1135
+ return {
1136
+ found,
1137
+ pointerCandidates: pointerCandidates.slice(0, 120)
1138
+ };
1139
+ }
1140
+ var NAVIGATES = /\b(navigate|navigateTo)\s*\(|\brouter\.(push|replace)\s*\(|\bhistory\.(push|replace)(State)?\s*\(|\blocation(\.href)?\s*=|\blocation\.(assign|replace)\s*\(|\bwindow\.open\s*\(|\$router\.(push|replace)/;
1141
+ function hash(s) {
1142
+ let h = 5381;
1143
+ for (let i = 0; i < s.length; i++) h = (h << 5) + h ^ s.charCodeAt(i);
1144
+ return (h >>> 0).toString(36);
1145
+ }
1146
+ /** Reset plus the original element's layout (buttons default to inline-block and border-box) */
1147
+ var keepLayout = (c, reset) => `${reset} display:${c.display}; box-sizing:${c.boxSizing};`;
1148
+ function classifyClickable(c) {
1149
+ const navigates = NAVIGATES.test(c.handler);
1150
+ const hrefOk = !!c.href && c.href !== "#" && !/^javascript:/i.test(c.href);
1151
+ const evidence = c.handler ? `Click handler (${c.via}): ${c.handler.replace(/\s+/g, " ").slice(0, 160)}` : "Click listener found on the element";
1152
+ let ruleId;
1153
+ let message;
1154
+ let strategy;
1155
+ if (c.tag === "a") {
1156
+ if (hrefOk) return null;
1157
+ if (navigates) {
1158
+ ruleId = "a11yengine-link-without-href";
1159
+ message = "This link navigates in a click handler but has no real href, so it cannot be opened in a new tab, bookmarked or reliably reached by every assistive technology.";
1160
+ strategy = "Keep the <a> and its classes; give it the real destination in href (with your router's Link component if it has one) and let the handler only add behaviour.";
1161
+ } else {
1162
+ ruleId = "a11yengine-link-used-as-button";
1163
+ message = "This <a> performs an action instead of going somewhere, so screen readers announce it as a link and Space does not activate it.";
1164
+ strategy = `Replace <a> with <button type="button">, keep the same classes and children, and add this reset so it looks identical: ${keepLayout(c, BUTTON_RESET_CSS)}`;
1165
+ }
1166
+ } else if (c.tag === "button" || /role="button"/.test(c.html) || c.tag === "input") {
1167
+ if (!navigates) return null;
1168
+ ruleId = "a11yengine-button-used-as-link";
1169
+ message = "This button only navigates to another page, so screen readers announce it as a button and it cannot be opened in a new tab.";
1170
+ strategy = `Replace it with <a href="…destination…"> (or your router's Link), keep the same classes and children, and add this reset so it looks identical: ${keepLayout(c, LINK_RESET_CSS)}`;
1171
+ } else {
1172
+ ruleId = "a11yengine-clickable-non-semantic";
1173
+ message = `This <${c.tag}> is clickable but is not a button or link: keyboard users cannot reach or activate it, and screen readers do not announce it as interactive.`;
1174
+ strategy = navigates ? `It navigates, so make it an <a href="…destination…"> (or your router's Link) with the same classes and children, plus: ${keepLayout(c, LINK_RESET_CSS)}` : `It performs an action, so make it a <button type="button"> with the same classes and children, plus: ${keepLayout(c, BUTTON_RESET_CSS)}`;
1175
+ }
1176
+ return {
1177
+ id: `${ruleId}-${hash(c.selector)}`,
1178
+ ruleId,
1179
+ status: "needs_review",
1180
+ source: "a11yengine-heuristic",
1181
+ severity: "high",
1182
+ wcag: {
1183
+ criteria: ["2.1.1", "4.1.2"],
1184
+ level: "A"
1185
+ },
1186
+ message,
1187
+ help: "Use <button> for actions and <a href> for navigation",
1188
+ helpUrl: "https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/button_role#accessibility_concerns",
1189
+ target: {
1190
+ selector: c.selector,
1191
+ html: c.html
1192
+ },
1193
+ reviewReason: `${evidence}. Whether it navigates was inferred from the handler's code; confirm the intended behaviour before changing the element.`,
1194
+ remediation: {
1195
+ steps: [strategy],
1196
+ source: "a11yengine-template"
1197
+ },
1198
+ fix: {
1199
+ visualImpact: "none",
1200
+ structural: true,
1201
+ strategy
1202
+ }
1203
+ };
1204
+ }
1205
+ /** Clickable-element findings for the loaded page (headless engine only) */
1206
+ async function findSemanticMisuse(page) {
1207
+ const { found, pointerCandidates } = await page.evaluate(collectClickables);
1208
+ if (pointerCandidates.length) {
1209
+ const cdp = await page.context().newCDPSession(page);
1210
+ try {
1211
+ for (const selector of pointerCandidates) {
1212
+ const r = await cdp.send("Runtime.evaluate", {
1213
+ expression: `document.querySelector(${JSON.stringify(selector)})`,
1214
+ objectGroup: "a11yengine-listeners"
1215
+ });
1216
+ if (!r?.result?.objectId) continue;
1217
+ const { listeners } = await cdp.send("DOMDebugger.getEventListeners", { objectId: r.result.objectId });
1218
+ const click = (listeners || []).find((l) => /^(click|mousedown|pointerdown|pointerup)$/.test(l.type));
1219
+ if (!click) continue;
1220
+ const html = await page.$eval(selector, (el) => {
1221
+ const cs = getComputedStyle(el);
1222
+ return {
1223
+ tag: el.tagName.toLowerCase(),
1224
+ html: el.outerHTML.slice(0, 300),
1225
+ href: el.getAttribute("href"),
1226
+ display: cs.display,
1227
+ boxSizing: cs.boxSizing
1228
+ };
1229
+ }).catch(() => null);
1230
+ if (!html) continue;
1231
+ found.push({
1232
+ selector,
1233
+ ...html,
1234
+ handler: String(click.handler?.description || ""),
1235
+ via: "listener",
1236
+ pointer: true
1237
+ });
1238
+ }
1239
+ } finally {
1240
+ await cdp.send("Runtime.releaseObjectGroup", { objectGroup: "a11yengine-listeners" }).catch(() => {});
1241
+ await cdp.detach().catch(() => {});
1242
+ }
1243
+ }
1244
+ return found.map(classifyClickable).filter((f) => !!f);
1245
+ }
1246
+ // src/engine/keyboard.ts
1247
+ /** Runs in the page: describes the focused element */
1248
+ function describeFocus() {
1249
+ const el = document.activeElement;
1250
+ if (!el || el === document.body || el === document.documentElement) return null;
1251
+ const selectorOf = (node) => {
1252
+ if (node.id && document.querySelectorAll("#" + CSS.escape(node.id)).length === 1) return "#" + CSS.escape(node.id);
1253
+ const parts = [];
1254
+ let cur = node;
1255
+ while (cur && cur !== document.body && parts.length < 6) {
1256
+ if (cur.id && document.querySelectorAll("#" + CSS.escape(cur.id)).length === 1) {
1257
+ parts.unshift("#" + CSS.escape(cur.id));
1258
+ break;
1259
+ }
1260
+ const parent = cur.parentElement;
1261
+ const same = parent ? Array.from(parent.children).filter((c) => c.tagName === cur.tagName) : [];
1262
+ const tag = cur.tagName.toLowerCase();
1263
+ parts.unshift(same.length > 1 ? `${tag}:nth-of-type(${same.indexOf(cur) + 1})` : tag);
1264
+ cur = parent;
1265
+ }
1266
+ return parts.join(" > ");
1267
+ };
1268
+ const r = el.getBoundingClientRect();
1269
+ const style = getComputedStyle(el);
1270
+ let hidden;
1271
+ if (r.width < 1 || r.height < 1) hidden = "zero size";
1272
+ else if (r.right < 0 || r.bottom < 0 || r.left > innerWidth + scrollX + 2e3) hidden = "off-screen";
1273
+ else if (style.visibility === "hidden" || Number(style.opacity) === 0) hidden = "invisible";
1274
+ else if (el.closest("[aria-hidden=\"true\"]")) hidden = "inside aria-hidden content";
1275
+ const name = (el.getAttribute("aria-label") || el.getAttribute("aria-labelledby") && document.getElementById(el.getAttribute("aria-labelledby"))?.textContent || el.innerText || el.getAttribute("title") || el.getAttribute("alt") || el.placeholder || "").trim().replace(/\s+/g, " ").slice(0, 60);
1276
+ return {
1277
+ selector: selectorOf(el),
1278
+ tag: el.tagName.toLowerCase(),
1279
+ role: el.getAttribute("role"),
1280
+ name,
1281
+ hidden,
1282
+ rect: r.width && r.height ? {
1283
+ x: r.left + scrollX,
1284
+ y: r.top + scrollY,
1285
+ width: r.width,
1286
+ height: r.height
1287
+ } : null,
1288
+ positiveTabindex: Number(el.getAttribute("tabindex")) > 0
1289
+ };
1290
+ }
1291
+ var PAD = 8;
1292
+ async function regionShot(page, rect) {
1293
+ const vp = page.viewportSize() || {
1294
+ width: 1280,
1295
+ height: 720
1296
+ };
1297
+ await page.evaluate((y) => window.scrollTo(0, Math.max(0, y - 100)), rect.y);
1298
+ const sy = await page.evaluate(() => scrollY);
1299
+ const clip = {
1300
+ x: Math.max(0, rect.x - PAD),
1301
+ y: Math.max(0, rect.y - sy - PAD),
1302
+ width: Math.min(vp.width, rect.width + 16),
1303
+ height: Math.min(vp.height, rect.height + 16)
1304
+ };
1305
+ if (clip.width < 1 || clip.height < 1) return null;
1306
+ return page.screenshot({
1307
+ clip,
1308
+ animations: "disabled",
1309
+ caret: "hide"
1310
+ }).catch(() => null);
1311
+ }
1312
+ async function walkKeyboard(page, maxTabs = 60) {
1313
+ await page.evaluate(() => {
1314
+ document.activeElement?.blur?.();
1315
+ window.scrollTo(0, 0);
1316
+ });
1317
+ const stops = [];
1318
+ const issues = [];
1319
+ let cycleComplete = false;
1320
+ let stuck = 0;
1321
+ let prevSelector = "";
1322
+ for (let i = 0; i < maxTabs; i++) {
1323
+ await page.keyboard.press("Tab");
1324
+ const f = await page.evaluate(describeFocus);
1325
+ if (!f) {
1326
+ if (stops.length) {
1327
+ cycleComplete = true;
1328
+ break;
1329
+ }
1330
+ continue;
1331
+ }
1332
+ if (stops.length && f.selector === stops[0].selector && stops.length > 1) {
1333
+ cycleComplete = true;
1334
+ break;
1335
+ }
1336
+ if (f.selector === prevSelector) {
1337
+ stuck++;
1338
+ if (stuck >= 2) {
1339
+ await page.keyboard.press("Shift+Tab");
1340
+ await page.keyboard.press("Escape");
1341
+ await page.keyboard.press("Tab");
1342
+ if ((await page.evaluate(describeFocus))?.selector === f.selector) {
1343
+ issues.push({
1344
+ ruleId: "keyboard-trap",
1345
+ wcag: "2.1.2",
1346
+ selector: f.selector,
1347
+ message: `Keyboard focus is trapped on this ${f.tag}: Tab, Shift+Tab and Escape do not move focus away.`
1348
+ });
1349
+ break;
1350
+ }
1351
+ stuck = 0;
1352
+ }
1353
+ continue;
1354
+ }
1355
+ stuck = 0;
1356
+ prevSelector = f.selector;
1357
+ let focusVisible = null;
1358
+ if (f.rect && !f.hidden) {
1359
+ const focused = await regionShot(page, f.rect);
1360
+ await page.keyboard.press("Shift+Tab");
1361
+ if ((await page.evaluate(describeFocus))?.selector !== f.selector) {
1362
+ const unfocused = await regionShot(page, f.rect);
1363
+ await page.keyboard.press("Tab");
1364
+ const back = await page.evaluate(describeFocus);
1365
+ if (focused && unfocused && back?.selector === f.selector) focusVisible = !focused.equals(unfocused);
1366
+ }
1367
+ }
1368
+ stops.push({
1369
+ n: stops.length + 1,
1370
+ selector: f.selector,
1371
+ tag: f.tag,
1372
+ role: f.role,
1373
+ name: f.name,
1374
+ focusVisible,
1375
+ ...f.hidden ? { hidden: f.hidden } : {}
1376
+ });
1377
+ if (f.hidden) issues.push({
1378
+ ruleId: "focus-on-hidden-element",
1379
+ wcag: "2.4.7",
1380
+ selector: f.selector,
1381
+ message: `Focus lands on a ${f.tag} that cannot be seen (${f.hidden}). Keyboard users lose track of where they are.`
1382
+ });
1383
+ else if (focusVisible === false) issues.push({
1384
+ ruleId: "focus-not-visible",
1385
+ wcag: "2.4.7",
1386
+ selector: f.selector,
1387
+ message: `Focusing this ${f.tag} changes nothing on screen, so keyboard users cannot see where focus is.`
1388
+ });
1389
+ if (f.positiveTabindex) issues.push({
1390
+ ruleId: "positive-tabindex",
1391
+ wcag: "2.4.3",
1392
+ selector: f.selector,
1393
+ message: `This ${f.tag} has a positive tabindex, which overrides the visual order for keyboard users.`
1394
+ });
1395
+ }
1396
+ return {
1397
+ stops,
1398
+ cycleComplete,
1399
+ issues
1400
+ };
1401
+ }
1402
+ // src/engine/themes.ts
1403
+ /** Class/attribute dark-mode switches in one selector (pure; exported for tests) */
1404
+ function togglesInSelector(selector) {
1405
+ const out = [];
1406
+ const cls = selector.match(/\.(dark|theme-dark|dark-mode|dark-theme|darkmode|is-dark)(?![\w-])/g);
1407
+ for (const c of cls || []) out.push({
1408
+ kind: "class",
1409
+ name: c.slice(1)
1410
+ });
1411
+ const attr = selector.matchAll(/\[\s*(data-theme|data-bs-theme|data-mode|data-color-scheme|data-color-mode|data-colors?-theme|theme)\s*[~|^$*]?=\s*["']?(dark[\w-]*)["']?\s*\]/gi);
1412
+ for (const m of attr) out.push({
1413
+ kind: "attribute",
1414
+ name: m[1].toLowerCase(),
1415
+ value: m[2]
1416
+ });
1417
+ return out;
1418
+ }
1419
+ /** Runs in the page */
1420
+ function detectThemesInPage() {
1421
+ const counts = /* @__PURE__ */ new Map();
1422
+ let mediaQuery = false;
1423
+ let unreadableSheets = 0;
1424
+ const toggles = (selector) => {
1425
+ const out = [];
1426
+ const cls = selector.match(/\.(dark|theme-dark|dark-mode|dark-theme|darkmode|is-dark)(?![\w-])/g);
1427
+ for (const c of cls || []) out.push({
1428
+ kind: "class",
1429
+ name: c.slice(1)
1430
+ });
1431
+ const attr = selector.matchAll(/\[\s*(data-theme|data-bs-theme|data-mode|data-color-scheme|data-color-mode|data-colors?-theme|theme)\s*[~|^$*]?=\s*["']?(dark[\w-]*)["']?\s*\]/gi);
1432
+ for (const m of attr) out.push({
1433
+ kind: "attribute",
1434
+ name: m[1].toLowerCase(),
1435
+ value: m[2]
1436
+ });
1437
+ return out;
1438
+ };
1439
+ const walk = (rules) => {
1440
+ for (const r of Array.from(rules)) {
1441
+ const media = r.conditionText || r.media?.mediaText || "";
1442
+ if (/prefers-color-scheme\s*:\s*dark/i.test(media)) mediaQuery = true;
1443
+ const sel = r.selectorText;
1444
+ if (sel) for (const t of toggles(sel)) {
1445
+ const key = `${t.kind}:${t.name}:${t.value || ""}`;
1446
+ const e = counts.get(key);
1447
+ if (e) e.n++;
1448
+ else counts.set(key, {
1449
+ t,
1450
+ n: 1
1451
+ });
1452
+ }
1453
+ const inner = r.cssRules;
1454
+ if (inner) walk(inner);
1455
+ }
1456
+ };
1457
+ for (const sheet of Array.from(document.styleSheets)) try {
1458
+ walk(sheet.cssRules);
1459
+ } catch {
1460
+ unreadableSheets++;
1461
+ }
1462
+ const meta = document.querySelector("meta[name=\"color-scheme\"]")?.getAttribute("content") || "";
1463
+ const rootScheme = getComputedStyle(document.documentElement).colorScheme;
1464
+ const colorScheme = meta || (rootScheme && rootScheme !== "normal" ? rootScheme : "");
1465
+ return {
1466
+ mediaQuery: mediaQuery || /dark/.test(colorScheme),
1467
+ toggles: [...counts.values()].sort((a, b) => b.n - a.n).map((e) => e.t).slice(0, 3),
1468
+ ...colorScheme ? { colorScheme } : {},
1469
+ unreadableSheets
1470
+ };
1471
+ }
1472
+ var hasDarkMode = (d) => d.mediaQuery || d.toggles.length > 0;
1473
+ /** Storage keys theme libraries read on startup (next-themes, VueUse, Nuxt, many hand-rolled) */
1474
+ var DARK_STORAGE_INIT = `(() => {
1475
+ try {
1476
+ for (const k of ['theme', 'color-theme', 'colorTheme', 'color-mode', 'colorMode', 'vueuse-color-scheme', 'nuxt-color-mode', 'darkMode'])
1477
+ if (localStorage.getItem(k) === null) localStorage.setItem(k, k === 'darkMode' ? 'true' : 'dark');
1478
+ } catch (e) {}
1479
+ })();`;
1480
+ /** Switches on the detected class/attribute toggles and waits for styles to apply */
1481
+ async function applyDarkToggles(page, toggles) {
1482
+ if (!toggles.length) return;
1483
+ await page.evaluate((ts) => {
1484
+ const root = document.documentElement;
1485
+ for (const t of ts) if (t.kind === "class") root.classList.add(t.name);
1486
+ else root.setAttribute(t.name, t.value || "dark");
1487
+ if (root.classList.contains("light")) root.classList.remove("light");
1488
+ return new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r)));
1489
+ }, toggles);
1490
+ }
1491
+ /** Page background and text colour, to confirm the mode actually changed */
1492
+ async function themeSignature(page) {
1493
+ return page.evaluate(() => {
1494
+ const parse = (c) => (c.match(/[\d.]+/g) || []).map(Number);
1495
+ const opaque = (c) => {
1496
+ const v = parse(c);
1497
+ return v.length >= 3 && (v.length < 4 || v[3] > .5);
1498
+ };
1499
+ let bg = "";
1500
+ for (const el of [document.body, document.documentElement]) {
1501
+ const c = el ? getComputedStyle(el).backgroundColor : "";
1502
+ if (c && opaque(c)) {
1503
+ bg = c;
1504
+ break;
1505
+ }
1506
+ }
1507
+ if (!bg) bg = matchMedia("(prefers-color-scheme: dark)").matches && /dark/.test(getComputedStyle(document.documentElement).colorScheme) ? "rgb(18, 18, 18)" : "rgb(255, 255, 255)";
1508
+ const lin = (v) => {
1509
+ const s = v / 255;
1510
+ return s <= .04045 ? s / 12.92 : ((s + .055) / 1.055) ** 2.4;
1511
+ };
1512
+ const [r, g, b] = parse(bg);
1513
+ return {
1514
+ background: bg,
1515
+ text: document.body ? getComputedStyle(document.body).color : "",
1516
+ backgroundLuminance: .2126 * lin(r) + .7152 * lin(g) + .0722 * lin(b)
1517
+ };
1518
+ });
1519
+ }
1520
+ /** Dark mode took effect when the background got clearly darker or the text colour changed */
1521
+ function darkModeApplied(light, dark) {
1522
+ return dark.backgroundLuminance < light.backgroundLuminance - .2 || light.text !== dark.text && dark.backgroundLuminance < .2;
1523
+ }
1524
+ /**
1525
+ * Merges findings from both modes. A finding on the same element in both modes is
1526
+ * reported once with themes ["light","dark"]; colour-contrast findings stay separate per
1527
+ * mode because the measured colours and the fix differ. Dark-mode ids end in "@dark".
1528
+ */
1529
+ function mergeThemeReports(light, dark) {
1530
+ const merged = light.findings.map((f) => ({
1531
+ ...f,
1532
+ themes: ["light"]
1533
+ }));
1534
+ const byId = new Map(merged.map((f) => [f.id, f]));
1535
+ for (const f of dark.findings) {
1536
+ const same = byId.get(f.id);
1537
+ if (same && f.ruleId !== "color-contrast" && same.status === f.status) {
1538
+ same.themes = ["light", "dark"];
1539
+ continue;
1540
+ }
1541
+ merged.push({
1542
+ ...f,
1543
+ id: `${f.id}@dark`,
1544
+ themes: ["dark"]
1545
+ });
1546
+ }
1547
+ const confirmed = merged.filter((f) => f.status === "confirmed");
1548
+ const count = (s) => confirmed.filter((f) => f.severity === s).length;
1549
+ return {
1550
+ ...light,
1551
+ summary: {
1552
+ confirmed: {
1553
+ total: confirmed.length,
1554
+ critical: count("critical"),
1555
+ high: count("high"),
1556
+ medium: count("medium"),
1557
+ low: count("low")
1558
+ },
1559
+ needsReview: merged.length - confirmed.length
1560
+ },
1561
+ findings: merged
1562
+ };
1563
+ }
1564
+ // src/engine/visual.ts
1565
+ /** Full-page PNG with animations stopped, so repeated shots are comparable */
1566
+ async function takeScreenshot(page) {
1567
+ return page.screenshot({
1568
+ fullPage: true,
1569
+ animations: "disabled",
1570
+ caret: "hide"
1571
+ });
1572
+ }
1573
+ /** Document-coordinate boxes of the given selectors (null when not found) */
1574
+ async function elementBoxes(page, selectors) {
1575
+ return page.evaluate((sels) => {
1576
+ return sels.map((s) => {
1577
+ try {
1578
+ const el = document.querySelector(s);
1579
+ if (!el) return null;
1580
+ const r = el.getBoundingClientRect();
1581
+ return {
1582
+ x: r.left + scrollX,
1583
+ y: r.top + scrollY,
1584
+ width: r.width,
1585
+ height: r.height
1586
+ };
1587
+ } catch {
1588
+ return null;
1589
+ }
1590
+ });
1591
+ }, selectors);
1592
+ }
1593
+ var CELL = 16;
1594
+ /** Runs in a blank page: diff two PNGs (data URLs) into changed grid regions */
1595
+ function diffInPage(args) {
1596
+ const load = (src) => new Promise((resolve, reject) => {
1597
+ const img = new Image();
1598
+ img.onload = () => resolve(img);
1599
+ img.onerror = reject;
1600
+ img.src = src;
1601
+ });
1602
+ return Promise.all([load(args.a), load(args.b)]).then(([ia, ib]) => {
1603
+ const w = Math.min(ia.width, ib.width);
1604
+ const h = Math.min(ia.height, ib.height);
1605
+ const pixels = (img) => {
1606
+ const c = document.createElement("canvas");
1607
+ c.width = w;
1608
+ c.height = h;
1609
+ const ctx = c.getContext("2d");
1610
+ ctx.drawImage(img, 0, 0);
1611
+ return ctx.getImageData(0, 0, w, h).data;
1612
+ };
1613
+ const pa = pixels(ia);
1614
+ const pb = pixels(ib);
1615
+ const cols = Math.ceil(w / args.cell);
1616
+ const rows = Math.ceil(h / args.cell);
1617
+ const grid = new Uint8Array(cols * rows);
1618
+ let changed = 0;
1619
+ for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) {
1620
+ const i = (y * w + x) * 4;
1621
+ if (Math.abs(pa[i] - pb[i]) > 24 || Math.abs(pa[i + 1] - pb[i + 1]) > 24 || Math.abs(pa[i + 2] - pb[i + 2]) > 24) {
1622
+ changed++;
1623
+ grid[Math.floor(y / args.cell) * cols + Math.floor(x / args.cell)] = 1;
1624
+ }
1625
+ }
1626
+ const seen = new Uint8Array(cols * rows);
1627
+ const regions = [];
1628
+ for (let start = 0; start < grid.length; start++) {
1629
+ if (!grid[start] || seen[start]) continue;
1630
+ let minX = cols, minY = rows, maxX = 0, maxY = 0;
1631
+ const stack = [start];
1632
+ seen[start] = 1;
1633
+ while (stack.length) {
1634
+ const k = stack.pop();
1635
+ const cx = k % cols;
1636
+ const cy = Math.floor(k / cols);
1637
+ minX = Math.min(minX, cx);
1638
+ maxX = Math.max(maxX, cx);
1639
+ minY = Math.min(minY, cy);
1640
+ maxY = Math.max(maxY, cy);
1641
+ for (const [dx, dy] of [
1642
+ [1, 0],
1643
+ [-1, 0],
1644
+ [0, 1],
1645
+ [0, -1]
1646
+ ]) {
1647
+ const nx = cx + dx;
1648
+ const ny = cy + dy;
1649
+ if (nx < 0 || ny < 0 || nx >= cols || ny >= rows) continue;
1650
+ const nk = ny * cols + nx;
1651
+ if (grid[nk] && !seen[nk]) {
1652
+ seen[nk] = 1;
1653
+ stack.push(nk);
1654
+ }
1655
+ }
1656
+ }
1657
+ regions.push({
1658
+ x: minX * args.cell,
1659
+ y: minY * args.cell,
1660
+ width: (maxX - minX + 1) * args.cell,
1661
+ height: (maxY - minY + 1) * args.cell
1662
+ });
1663
+ }
1664
+ return {
1665
+ changedPercent: changed / Math.max(1, w * h) * 100,
1666
+ regions,
1667
+ a: {
1668
+ width: ia.width,
1669
+ height: ia.height
1670
+ },
1671
+ b: {
1672
+ width: ib.width,
1673
+ height: ib.height
1674
+ }
1675
+ };
1676
+ });
1677
+ }
1678
+ var overlaps = (r, b, pad) => r.x < b.x + b.width + pad && r.x + r.width > b.x - pad && r.y < b.y + b.height + pad && r.y + r.height > b.y - pad;
1679
+ async function compareScreenshots(browser, before, after, fixedBoxes) {
1680
+ const ctx = await browser.newContext();
1681
+ try {
1682
+ const d = await (await ctx.newPage()).evaluate(diffInPage, {
1683
+ a: "data:image/png;base64," + before.toString("base64"),
1684
+ b: "data:image/png;base64," + after.toString("base64"),
1685
+ cell: CELL
1686
+ });
1687
+ const expectedRegions = [];
1688
+ const unexpectedRegions = [];
1689
+ for (const r of d.regions) (fixedBoxes.some((b) => overlaps(r, b, 12)) ? expectedRegions : unexpectedRegions).push(r);
1690
+ const pageSizeChanged = d.a.width !== d.b.width || d.a.height !== d.b.height;
1691
+ const verdict = !d.regions.length && !pageSizeChanged ? "no-visual-change" : !unexpectedRegions.length && !pageSizeChanged ? "only-fixed-elements-changed" : "unexpected-changes";
1692
+ return {
1693
+ changedPercent: Math.round(d.changedPercent * 1e3) / 1e3,
1694
+ pageSizeChanged,
1695
+ before: d.a,
1696
+ after: d.b,
1697
+ expectedRegions: expectedRegions.slice(0, 20),
1698
+ unexpectedRegions: unexpectedRegions.slice(0, 20),
1699
+ verdict
1700
+ };
1701
+ } finally {
1702
+ await ctx.close().catch(() => {});
1703
+ }
1704
+ }
1705
+ // src/utils/sarif.ts
1706
+ /**
1707
+ * SARIF 2.1.0 output for code-scanning tools (GitHub code scanning, IDE SARIF viewers).
1708
+ *
1709
+ * Findings are on a rendered web page, not in source files, so each result's location
1710
+ * is the page URL plus the element's CSS selector (as a logical location). Viewers can
1711
+ * list and track the alerts but cannot annotate source lines.
1712
+ * Severity mapping: confirmed critical/high -> error, confirmed medium/low -> warning,
1713
+ * needs_review -> note (never an error, since it may be a false positive).
1714
+ */
1715
+ var SARIF_SCHEMA = "https://json.schemastore.org/sarif-2.1.0.json";
1716
+ function levelOf(f) {
1717
+ if (f.status === "needs_review") return "note";
1718
+ return f.severity === "critical" || f.severity === "high" ? "error" : "warning";
1719
+ }
1720
+ function ruleTags(f) {
1721
+ const tags = ["accessibility"];
1722
+ if (f.wcag) f.wcag.criteria.forEach((c) => tags.push(`WCAG ${c}`));
1723
+ else tags.push("best-practice");
1724
+ return tags;
1725
+ }
1726
+ function toSarif(report) {
1727
+ const rulesById = /* @__PURE__ */ new Map();
1728
+ for (const f of report.findings) {
1729
+ if (rulesById.has(f.ruleId)) continue;
1730
+ rulesById.set(f.ruleId, {
1731
+ id: f.ruleId,
1732
+ name: f.ruleId,
1733
+ shortDescription: { text: f.help || f.ruleId },
1734
+ helpUri: f.helpUrl || void 0,
1735
+ properties: { tags: ruleTags(f) }
1736
+ });
1737
+ }
1738
+ const ruleIds = [...rulesById.keys()];
1739
+ return {
1740
+ $schema: SARIF_SCHEMA,
1741
+ version: "2.1.0",
1742
+ runs: [{
1743
+ tool: { driver: {
1744
+ name: report.tool.name,
1745
+ version: report.tool.version,
1746
+ informationUri: TOOL_URL,
1747
+ rules: [...rulesById.values()]
1748
+ } },
1749
+ results: report.findings.map((f) => ({
1750
+ ruleId: f.ruleId,
1751
+ ruleIndex: ruleIds.indexOf(f.ruleId),
1752
+ level: levelOf(f),
1753
+ message: { text: f.status === "needs_review" ? `Needs review: ${f.message} (${f.reviewReason})` : f.message },
1754
+ locations: [{
1755
+ physicalLocation: { artifactLocation: { uri: report.target.url } },
1756
+ logicalLocations: [{
1757
+ fullyQualifiedName: f.target.selector,
1758
+ kind: "element"
1759
+ }]
1760
+ }],
1761
+ partialFingerprints: { a11yengineFindingId: f.id },
1762
+ properties: {
1763
+ status: f.status,
1764
+ source: f.source,
1765
+ severity: f.severity,
1766
+ wcag: f.wcag,
1767
+ html: f.target.html
1768
+ }
1769
+ })),
1770
+ properties: { limitations: report.limitations }
1771
+ }]
1772
+ };
1773
+ }
1774
+ function toAgentPrompt(report) {
1775
+ const findings = report.findings.slice(0, 150);
1776
+ const omitted = report.findings.length - findings.length;
1777
+ const payload = {
1778
+ ...report,
1779
+ findings
1780
+ };
1781
+ const lines = [
1782
+ `# Accessibility fixes for ${report.target.url}`,
1783
+ "",
1784
+ `A11yEngine scanned this page on ${report.target.scannedAt}: ${report.summary.confirmed.total} confirmed finding(s) and ${report.summary.needsReview} needing review.`,
1785
+ "",
1786
+ "## Instructions",
1787
+ "1. Find the source code that renders each element in `findings` (use `target.selector` and `target.html`).",
1788
+ "2. Fix every finding with `status: \"confirmed\"`. Follow `helpUrl`; `remediation.steps`, when present, are generic guidance, so adapt them to this codebase and its components.",
1789
+ "3. For `status: \"needs_review\"`, do not change code until you have checked the element and confirmed the problem is real. `reviewReason` explains why it is unconfirmed.",
1790
+ "4. Do not remove content, hide elements from assistive technology, or add ARIA that duplicates native semantics just to silence a finding.",
1791
+ "5. Re-scan the page after your changes and report which findings are resolved.",
1792
+ "6. Do not state that the page is \"accessible\" or \"WCAG compliant\": see `limitations`.",
1793
+ ""
1794
+ ];
1795
+ if (omitted > 0) lines.push(`Note: ${omitted} further finding(s) were omitted to keep this brief short; export the full JSON report for all findings.`, "");
1796
+ lines.push("## Report (A11yEngine Agent Report v1)", "```json", JSON.stringify(payload, null, 2), "```");
1797
+ return lines.join("\n");
1798
+ }
1799
+ // src/engine/verify.ts
1800
+ var IDENTITY_ATTRS = [
1801
+ "id",
1802
+ "name",
1803
+ "data-testid",
1804
+ "data-test",
1805
+ "data-cy",
1806
+ "href",
1807
+ "src",
1808
+ "for",
1809
+ "type",
1810
+ "role"
1811
+ ];
1812
+ /** Rule + the element's tag, identifying attributes and short text, from its HTML */
1813
+ function elementFingerprint(f) {
1814
+ const html = f.target.html || "";
1815
+ const tag = (html.match(/^<\s*([a-z0-9-]+)/i)?.[1] || "").toLowerCase();
1816
+ const attrs = IDENTITY_ATTRS.map((a) => {
1817
+ const m = html.match(new RegExp(`\\s${a}\\s*=\\s*("([^"]*)"|'([^']*)')`, "i"));
1818
+ return m ? `${a}=${m[2] ?? m[3]}` : "";
1819
+ }).filter(Boolean).join("|");
1820
+ const text = html.replace(/<[^>]*>/g, " ").replace(/\s+/g, " ").trim().slice(0, 40);
1821
+ return `${f.ruleId}::${tag}::${attrs}::${text}`;
1822
+ }
1823
+ function diffReports(before, after) {
1824
+ const confirmed = (r) => r.findings.filter((f) => f.status === "confirmed");
1825
+ const remaining = new Map(confirmed(after).map((f) => [f.id, f]));
1826
+ const byPrint = /* @__PURE__ */ new Map();
1827
+ for (const f of remaining.values()) {
1828
+ const k = elementFingerprint(f);
1829
+ byPrint.set(k, [...byPrint.get(k) || [], f]);
1830
+ }
1831
+ const take = (f) => {
1832
+ remaining.delete(f.id);
1833
+ const k = elementFingerprint(f);
1834
+ byPrint.set(k, (byPrint.get(k) || []).filter((x) => x.id !== f.id));
1835
+ };
1836
+ const sameMode = (a, b) => !a.themes || !b.themes || a.themes.some((t) => b.themes.includes(t));
1837
+ const fixed = [];
1838
+ const stillFailing = [];
1839
+ for (const f of confirmed(before)) {
1840
+ const same = remaining.get(f.id) || byPrint.get(elementFingerprint(f))?.find((x) => sameMode(f, x));
1841
+ if (same) {
1842
+ take(same);
1843
+ stillFailing.push(same);
1844
+ } else fixed.push(f);
1845
+ }
1846
+ const introduced = [...remaining.values()];
1847
+ const review = (r) => r.findings.filter((f) => f.status === "needs_review").length;
1848
+ return {
1849
+ passed: stillFailing.length === 0 && introduced.length === 0,
1850
+ fixed,
1851
+ stillFailing,
1852
+ introduced,
1853
+ needsReview: {
1854
+ before: review(before),
1855
+ after: review(after)
1856
+ }
1857
+ };
1858
+ }
1859
+ // src/utils/pdfAudit.ts
1860
+ /** pdf.js PermissionFlag.COPY_FOR_ACCESSIBILITY (PDF permission bit 10) */
1861
+ var COPY_FOR_ACCESSIBILITY = 512;
1862
+ var TEXT_SAMPLE_PAGES = 5;
1863
+ /** WCAG technique PDF2 recommends bookmarks for long documents */
1864
+ var LONG_DOCUMENT_PAGES = 20;
1865
+ async function analyzePdf(pdf) {
1866
+ const checks = [];
1867
+ const [{ info }, markInfo, prefs, outline, permissions] = await Promise.all([
1868
+ pdf.getMetadata(),
1869
+ pdf.getMarkInfo().catch(() => null),
1870
+ pdf.getViewerPreferences().catch(() => null),
1871
+ pdf.getOutline().catch(() => null),
1872
+ pdf.getPermissions().catch(() => null)
1873
+ ]);
1874
+ const sampled = Math.min(pdf.numPages, TEXT_SAMPLE_PAGES);
1875
+ let textChars = 0;
1876
+ let structTree = null;
1877
+ for (let n = 1; n <= sampled; n++) {
1878
+ const page = await pdf.getPage(n);
1879
+ const content = await page.getTextContent();
1880
+ textChars += content.items.reduce((sum, item) => sum + (item.str || "").trim().length, 0);
1881
+ if (n === 1) structTree = await page.getStructTree().catch(() => null);
1882
+ }
1883
+ checks.push(textChars > 0 ? {
1884
+ id: "text-layer",
1885
+ label: "Text can be read by assistive technology",
1886
+ status: "pass",
1887
+ detail: `Extractable text found on the first ${sampled} page(s).`,
1888
+ wcag: ["1.1.1", "1.4.5"]
1889
+ } : {
1890
+ id: "text-layer",
1891
+ label: "Text can be read by assistive technology",
1892
+ status: "fail",
1893
+ detail: `No extractable text on the first ${sampled} page(s). The document is probably scanned images, which screen readers cannot read. Run OCR and tag the result.`,
1894
+ wcag: ["1.1.1", "1.4.5"]
1895
+ });
1896
+ const marked = markInfo?.Marked === true;
1897
+ const hasStructure = !!structTree && (structTree.children?.length ?? 0) > 0;
1898
+ checks.push({
1899
+ id: "tagged",
1900
+ label: "Document is tagged",
1901
+ status: marked && hasStructure ? "pass" : "fail",
1902
+ detail: marked && hasStructure ? "Document declares tags and has a structure tree. Whether the tags are correct still needs review." : marked ? "Document is marked as tagged, but the first page has no structure tree." : "Document is not tagged, so headings, lists, tables and reading order are not available to assistive technology.",
1903
+ wcag: ["1.3.1", "1.3.2"]
1904
+ });
1905
+ const title = String(info?.Title || "").trim();
1906
+ const displaysTitle = prefs?.DisplayDocTitle === true;
1907
+ checks.push({
1908
+ id: "title",
1909
+ label: "Document title is set and displayed",
1910
+ status: title && displaysTitle ? "pass" : "fail",
1911
+ detail: !title ? "No document title is set; viewers show the file name instead." : displaysTitle ? `Title: "${title}".` : `Title "${title}" is set, but DisplayDocTitle is off, so viewers show the file name instead.`,
1912
+ wcag: ["2.4.2"]
1913
+ });
1914
+ const lang = String(info?.Language || "").trim();
1915
+ checks.push({
1916
+ id: "language",
1917
+ label: "Document language is declared",
1918
+ status: lang ? "pass" : "fail",
1919
+ detail: lang ? `Language: ${lang}.` : "No document language is set, so screen readers may use the wrong pronunciation.",
1920
+ wcag: ["3.1.1"]
1921
+ });
1922
+ if (Array.isArray(permissions)) {
1923
+ const allowed = permissions.includes(COPY_FOR_ACCESSIBILITY);
1924
+ checks.push({
1925
+ id: "assistive-access",
1926
+ label: "Security settings allow assistive technology",
1927
+ status: allowed ? "pass" : "fail",
1928
+ detail: allowed ? "Document is restricted, but text access for accessibility is allowed." : "Document security blocks text access for accessibility, so screen readers may be unable to read it.",
1929
+ wcag: ["1.1.1", "4.1.2"]
1930
+ });
1931
+ }
1932
+ if (pdf.numPages > LONG_DOCUMENT_PAGES) {
1933
+ const hasBookmarks = Array.isArray(outline) && outline.length > 0;
1934
+ checks.push({
1935
+ id: "bookmarks",
1936
+ label: "Long document has bookmarks",
1937
+ status: hasBookmarks ? "pass" : "review",
1938
+ detail: hasBookmarks ? `${pdf.numPages} pages with bookmarks.` : `${pdf.numPages} pages and no bookmarks. Bookmarks help users find sections; consider adding them.`,
1939
+ wcag: ["2.4.5"]
1940
+ });
1941
+ }
1942
+ return checks;
1943
+ }
1944
+ // src/engine/pdf.ts
1945
+ /**
1946
+ * PDF checks for Node (CLI, MCP server): the same analyzePdf the extension runs,
1947
+ * with pdf.js's legacy Node build instead of the extension's worker.
1948
+ */
1949
+ var MAX_PDF_BYTES = 31457280;
1950
+ /** Checks a PDF from an http(s) URL or a local file path */
1951
+ async function auditPdf(source) {
1952
+ try {
1953
+ let data;
1954
+ if (/^https?:\/\//i.test(source)) {
1955
+ const response = await fetch(source);
1956
+ if (!response.ok) return {
1957
+ url: source,
1958
+ ok: false,
1959
+ error: `HTTP ${response.status}`,
1960
+ checks: []
1961
+ };
1962
+ data = new Uint8Array(await response.arrayBuffer());
1963
+ } else data = new Uint8Array(fs.readFileSync(source.replace(/^file:\/\//i, "")));
1964
+ if (data.byteLength > MAX_PDF_BYTES) return {
1965
+ url: source,
1966
+ ok: false,
1967
+ error: "File is larger than 30 MB",
1968
+ checks: []
1969
+ };
1970
+ const { getDocument } = await import("pdfjs-dist/legacy/build/pdf.mjs");
1971
+ const task = getDocument({
1972
+ data,
1973
+ isEvalSupported: false,
1974
+ verbosity: 0
1975
+ });
1976
+ const pdf = await task.promise;
1977
+ try {
1978
+ const checks = await analyzePdf(pdf);
1979
+ return {
1980
+ url: source,
1981
+ ok: true,
1982
+ pageCount: pdf.numPages,
1983
+ checks
1984
+ };
1985
+ } finally {
1986
+ await task.destroy();
1987
+ }
1988
+ } catch (err) {
1989
+ const message = String(err?.message || err || "Could not read PDF");
1990
+ return {
1991
+ url: source,
1992
+ ok: false,
1993
+ error: /password/i.test(message) ? "PDF is password-protected" : /Invalid PDF/i.test(message) ? "Not a valid PDF" : message,
1994
+ checks: []
1995
+ };
1996
+ }
1997
+ }
1998
+ // src/engine/groups.ts
1999
+ function groupFindings(findings) {
2000
+ const groups = /* @__PURE__ */ new Map();
2001
+ for (const f of findings) {
2002
+ const src = f.location?.source;
2003
+ const component = f.location?.components?.[0];
2004
+ const key = src?.file ? `file:${src.file}` : component ? `component:${component}` : "unlocated";
2005
+ let g = groups.get(key);
2006
+ if (!g) {
2007
+ g = {
2008
+ count: 0,
2009
+ rules: {},
2010
+ findingIds: []
2011
+ };
2012
+ if (src?.file) g.file = src.file;
2013
+ if (component) g.component = component;
2014
+ groups.set(key, g);
2015
+ }
2016
+ g.count++;
2017
+ g.rules[f.ruleId] = (g.rules[f.ruleId] || 0) + 1;
2018
+ g.findingIds.push(f.id);
2019
+ if (src?.line) g.lines = [.../* @__PURE__ */ new Set([...g.lines || [], src.line])].sort((a, b) => a - b);
2020
+ }
2021
+ return [...groups.entries()].sort(([ka, a], [kb, b]) => ka === "unlocated" ? 1 : kb === "unlocated" ? -1 : b.count - a.count).map(([, g]) => g);
2022
+ }
2023
+ // src/engine/index.ts
2024
+ /**
2025
+ * Headless A11yEngine: runs the exact scanner the extension ships (dist/axe.js +
2026
+ * dist/content.js) in Google Chrome via playwright-core, so the CLI, CI, the ACT
2027
+ * benchmark, the MCP server and agent integrations all produce the same results as
2028
+ * the side panel.
2029
+ *
2030
+ * Requires `npm run build` first (for dist/) and a local Google Chrome install.
2031
+ */
2032
+ /** Page-world stand-in for the extension APIs content.js uses */
2033
+ var CHROME_SHIM = `(() => {
2034
+ const c = window.chrome || {};
2035
+ c.runtime = {
2036
+ id: 'a11yengine-headless',
2037
+ onMessage: { addListener(f) { window.__a11yListener = f; } },
2038
+ sendMessage() { return Promise.resolve(); },
2039
+ getURL: (x) => x,
2040
+ };
2041
+ c.storage = { local: {
2042
+ get: (k, cb) => { cb && cb({}); return Promise.resolve({}); },
2043
+ set: (o, cb) => { cb && cb(); return Promise.resolve(); },
2044
+ } };
2045
+ try { window.chrome = c; } catch (e) {}
2046
+ })();`;
2047
+ /** dist/ next to this package: engine/dist/index.mjs -> ../../dist */
2048
+ function defaultDistDir() {
2049
+ const here = path.dirname(fileURLToPath(import.meta.url));
2050
+ return path.resolve(here, "../../dist");
2051
+ }
2052
+ function loadAssets(distDir = defaultDistDir()) {
2053
+ const read = (f) => {
2054
+ const p = path.join(distDir, f);
2055
+ if (!fs.existsSync(p)) throw new Error(`${p} not found. Run "npm run build" first.`);
2056
+ return fs.readFileSync(p, "utf8");
2057
+ };
2058
+ return {
2059
+ axeSrc: read("axe.js"),
2060
+ contentSrc: read("content.js")
2061
+ };
2062
+ }
2063
+ /** Sends a message to content.js's listener and waits for its reply */
2064
+ async function sendToScanner(page, message, timeoutMs) {
2065
+ return page.evaluate(({ message, timeout }) => new Promise((resolve) => {
2066
+ const t = setTimeout(() => resolve({
2067
+ success: false,
2068
+ error: "scan timed out"
2069
+ }), timeout);
2070
+ window.__a11yListener(message, {}, (r) => {
2071
+ clearTimeout(t);
2072
+ resolve(r);
2073
+ });
2074
+ }), {
2075
+ message,
2076
+ timeout: timeoutMs
2077
+ });
2078
+ }
2079
+ async function injectScanner(page, assets) {
2080
+ if (await page.evaluate(() => !!window.__a11yListener)) return;
2081
+ await page.addScriptTag({ content: assets.axeSrc });
2082
+ await page.addScriptTag({ content: assets.contentSrc });
2083
+ }
2084
+ /**
2085
+ * Injects the scanner into an already-loaded page and runs one scan.
2086
+ * The page's context must have CHROME_SHIM registered as an init script.
2087
+ */
2088
+ async function scanLoadedPage(page, assets, scanTimeoutMs = 3e4) {
2089
+ await injectScanner(page, assets);
2090
+ const resp = await sendToScanner(page, { action: "RUN_SCAN" }, scanTimeoutMs);
2091
+ if (!resp || !resp.success || !resp.report) throw new Error(resp?.error || "scan failed");
2092
+ return resp.report;
2093
+ }
2094
+ /**
2095
+ * The scanner is injected as inline scripts. Pages with a strict Content-Security-Policy
2096
+ * would block that, so contexts bypass CSP (the extension uses extension APIs instead).
2097
+ */
2098
+ var CONTEXT_OPTIONS = { bypassCSP: true };
2099
+ var NO_BROWSER_MESSAGE = "No Chromium-based browser found. Install Google Chrome or Microsoft Edge, set A11YENGINE_CHROME to a Chrome or Chromium executable, or run \"npx playwright install chromium\".";
2100
+ /**
2101
+ * Launches the first available browser: an explicit executable, then installed Google
2102
+ * Chrome, then Microsoft Edge (preinstalled on Windows), then Playwright's own Chromium.
2103
+ */
2104
+ async function launchBrowser(options) {
2105
+ const headless = options.headless ?? true;
2106
+ const executablePath = options.executablePath || process.env.A11YENGINE_CHROME || void 0;
2107
+ if (executablePath) {
2108
+ if (!fs.existsSync(executablePath)) throw new Error(`No browser at "${executablePath}" (from A11YENGINE_CHROME or executablePath). Point it at a Chrome or Chromium executable, or unset it to use installed Chrome or Edge.`);
2109
+ return chromium.launch({
2110
+ executablePath,
2111
+ headless
2112
+ });
2113
+ }
2114
+ const channels = options.channel ? [options.channel] : [
2115
+ "chrome",
2116
+ "msedge",
2117
+ void 0
2118
+ ];
2119
+ for (const channel of channels) try {
2120
+ return await chromium.launch({
2121
+ ...channel ? { channel } : {},
2122
+ headless
2123
+ });
2124
+ } catch (err) {
2125
+ const msg = String(err?.message || err);
2126
+ if (!/not found|doesn't exist|Executable|install/i.test(msg)) throw err;
2127
+ }
2128
+ throw new Error(NO_BROWSER_MESSAGE);
2129
+ }
2130
+ /**
2131
+ * Text of a dev-server build-error overlay (Vite, Next.js, webpack), or null. After an
2132
+ * edit that does not compile the page never renders, and saying why beats a timeout.
2133
+ */
2134
+ async function buildErrorOverlay(page) {
2135
+ return page.evaluate(detectBuildErrorOverlay).catch(() => null);
2136
+ }
2137
+ /**
2138
+ * Runs inside the page (must stay self-contained). Next.js 15+ always renders a
2139
+ * <nextjs-portal> for its dev-tools button, so only an open error dialog inside it
2140
+ * counts as an error.
2141
+ */
2142
+ function detectBuildErrorOverlay(doc = document) {
2143
+ const vite = doc.querySelector("vite-error-overlay");
2144
+ if (vite) return (vite.shadowRoot?.querySelector(".message")?.textContent || "Vite build error").trim();
2145
+ for (const portal of Array.from(doc.querySelectorAll("nextjs-portal"))) {
2146
+ const dialog = portal.shadowRoot?.querySelector("[data-nextjs-dialog], [data-nextjs-dialog-overlay]");
2147
+ if (dialog) return (dialog.textContent || "Next.js build error").replace(/\s+/g, " ").trim().slice(0, 500);
2148
+ }
2149
+ if (doc.querySelector("[data-nextjs-dialog-overlay], [data-nextjs-dialog]")) return "Next.js build error";
2150
+ if (doc.getElementById("webpack-dev-server-client-overlay")) return "webpack dev server shows a build error";
2151
+ return null;
2152
+ }
2153
+ /** Presses Tab and Shift+Tab from inside the dialog; true if focus ever leaves it */
2154
+ async function focusEscapes(page, dialogSelector) {
2155
+ const inside = () => page.evaluate((sel) => {
2156
+ const d = document.querySelector(sel);
2157
+ return !!d && d.contains(document.activeElement);
2158
+ }, dialogSelector);
2159
+ const focusFirst = () => page.evaluate((sel) => {
2160
+ const d = document.querySelector(sel);
2161
+ (d?.querySelector("a[href],button:not([disabled]),input:not([disabled]),select,textarea,[tabindex]:not([tabindex=\"-1\"])") || d)?.focus();
2162
+ }, dialogSelector);
2163
+ const count = await page.evaluate((sel) => {
2164
+ const d = document.querySelector(sel);
2165
+ return d ? d.querySelectorAll("a[href],button,input,select,textarea,[tabindex]").length : 0;
2166
+ }, dialogSelector);
2167
+ for (const key of ["Tab", "Shift+Tab"]) {
2168
+ await focusFirst();
2169
+ for (let i = 0; i < count + 3; i++) {
2170
+ await page.keyboard.press(key);
2171
+ if (!await inside()) return true;
2172
+ }
2173
+ }
2174
+ return false;
2175
+ }
2176
+ async function runActions(page, actions = []) {
2177
+ for (const a of actions) if ("click" in a) await page.click(a.click, { timeout: 1e4 });
2178
+ else if ("fill" in a) await page.fill(a.fill, a.value, { timeout: 1e4 });
2179
+ else if ("press" in a) await page.keyboard.press(a.press);
2180
+ else if ("waitFor" in a) await page.waitForSelector(a.waitFor, { timeout: 15e3 });
2181
+ else if ("waitMs" in a) await page.waitForTimeout(Math.min(a.waitMs, 1e4));
2182
+ }
2183
+ var A11yEngine = class A11yEngine {
2184
+ browser;
2185
+ assets;
2186
+ constructor(browser, assets) {
2187
+ this.browser = browser;
2188
+ this.assets = assets;
2189
+ }
2190
+ static async launch(options = {}) {
2191
+ const assets = loadAssets(options.distDir);
2192
+ const browser = await launchBrowser(options);
2193
+ return new A11yEngine(browser, assets);
2194
+ }
2195
+ /** Opens `url` in a fresh, isolated context, reaches the requested state, runs `fn` */
2196
+ async withPage(url, options, fn) {
2197
+ const ctxOptions = { ...CONTEXT_OPTIONS };
2198
+ if (options.storageStatePath) ctxOptions.storageState = options.storageStatePath;
2199
+ if (options.viewport) ctxOptions.viewport = options.viewport;
2200
+ if (options.colorScheme) ctxOptions.colorScheme = options.colorScheme;
2201
+ const ctx = await this.browser.newContext(ctxOptions);
2202
+ try {
2203
+ await ctx.addInitScript(CHROME_SHIM);
2204
+ if (options.colorScheme === "dark") await ctx.addInitScript(DARK_STORAGE_INIT);
2205
+ const page = await ctx.newPage();
2206
+ await page.goto(url, {
2207
+ waitUntil: options.waitUntil ?? "load",
2208
+ timeout: options.timeoutMs ?? 3e4
2209
+ });
2210
+ if (options.waitForSelector) try {
2211
+ await page.waitForSelector(options.waitForSelector, { timeout: options.timeoutMs ?? 3e4 });
2212
+ } catch (err) {
2213
+ const overlay = await buildErrorOverlay(page);
2214
+ if (overlay) throw new Error(`The dev server shows a build error, so the page did not render: ${overlay.slice(0, 500)}`);
2215
+ throw err;
2216
+ }
2217
+ const overlay = await buildErrorOverlay(page);
2218
+ if (overlay) throw new Error(`The dev server shows a build error, so the page did not render: ${overlay.slice(0, 500)}`);
2219
+ await runActions(page, options.actions);
2220
+ return await fn(page);
2221
+ } finally {
2222
+ await ctx.close().catch(() => {});
2223
+ }
2224
+ }
2225
+ async scanPage(page, options) {
2226
+ const screenshot = options.screenshot ? await takeScreenshot(page) : void 0;
2227
+ const report = await scanLoadedPage(page, this.assets);
2228
+ const agentReport = buildAgentReport(report);
2229
+ if (options.semantics !== false) {
2230
+ const misuse = await findSemanticMisuse(page).catch(() => []);
2231
+ if (misuse.length) {
2232
+ const dup = await page.evaluate(({ a, b }) => a.map((sa) => {
2233
+ try {
2234
+ const ea = document.querySelector(sa);
2235
+ return !!ea && b.some((sb) => document.querySelector(sb) === ea);
2236
+ } catch {
2237
+ return false;
2238
+ }
2239
+ }), {
2240
+ a: agentReport.findings.map((f) => f.ruleId === "custom-keyboard-nav-missing" ? f.target.selector : ""),
2241
+ b: misuse.map((m) => m.target.selector)
2242
+ }).catch(() => []);
2243
+ agentReport.findings = agentReport.findings.filter((_, i) => !dup[i]);
2244
+ agentReport.findings.push(...misuse);
2245
+ agentReport.summary.needsReview = agentReport.findings.filter((f) => f.status === "needs_review").length;
2246
+ }
2247
+ }
2248
+ if (options.locate !== false && agentReport.findings.length) {
2249
+ const locations = await page.evaluate(locateInPage, agentReport.findings.map((f) => f.target.selector)).catch(() => null);
2250
+ if (locations) await resolveSourcePositions(locations.map((l) => l.source), new URL(page.url()).origin).catch(() => {});
2251
+ locations?.forEach((loc, i) => {
2252
+ if (loc.source && loc.confidence === "file" && loc.source.line && !loc.source.approximate) loc.confidence = "exact";
2253
+ if (loc.source) loc.source = relativizeSource(loc.source, options.projectRoot);
2254
+ agentReport.findings[i].location = loc;
2255
+ });
2256
+ }
2257
+ if (options.fixGuidance !== false) {
2258
+ const css = agentReport.findings.filter((f) => f.ruleId === "color-contrast" && f.evidence?.contrast).length ? await CssSourceFinder.attach(page).catch(() => null) : null;
2259
+ try {
2260
+ for (const f of agentReport.findings) {
2261
+ if (!f.fix) f.fix = guidanceFor(f.ruleId);
2262
+ const c = f.evidence?.contrast;
2263
+ if (f.ruleId !== "color-contrast" || !c) continue;
2264
+ const required = parseFloat(c.required) || 4.5;
2265
+ let colorSource = css ? await css.find(f.target.selector).catch(() => null) : null;
2266
+ if (colorSource?.file) colorSource = {
2267
+ ...colorSource,
2268
+ ...relativizeSource({
2269
+ file: colorSource.file,
2270
+ line: colorSource.line
2271
+ }, options.projectRoot)
2272
+ };
2273
+ if (colorSource?.variable?.file) colorSource.variable = {
2274
+ ...colorSource.variable,
2275
+ ...relativizeSource({
2276
+ file: colorSource.variable.file,
2277
+ line: colorSource.variable.line
2278
+ }, options.projectRoot)
2279
+ };
2280
+ f.fix.contrast = {
2281
+ measured: c,
2282
+ suggestions: suggestContrastFix(c.fg, c.bg, required),
2283
+ colorSource
2284
+ };
2285
+ }
2286
+ } finally {
2287
+ await css?.detach();
2288
+ }
2289
+ }
2290
+ let boxes;
2291
+ if (options.screenshot) {
2292
+ const confirmed = agentReport.findings.filter((f) => f.status === "confirmed");
2293
+ const list = await elementBoxes(page, confirmed.map((f) => f.target.selector)).catch(() => []);
2294
+ boxes = Object.fromEntries(confirmed.map((f, i) => [f.id, list[i] ?? null]));
2295
+ }
2296
+ return {
2297
+ report,
2298
+ agentReport,
2299
+ screenshot,
2300
+ boxes
2301
+ };
2302
+ }
2303
+ /** Visual check between two scans' screenshots (see verify_fix) */
2304
+ async compareScreenshots(before, after, fixedBoxes) {
2305
+ return compareScreenshots(this.browser, before, after, fixedBoxes);
2306
+ }
2307
+ /** Scans a URL (http, https or file) in a fresh, isolated browser context. */
2308
+ async scanUrl(url, options = {}) {
2309
+ return this.withPage(url, options, (page) => this.scanPage(page, options));
2310
+ }
2311
+ /**
2312
+ * Scans light mode and, when the site has one, dark mode, and merges the findings.
2313
+ * Dark mode is switched on with every mechanism detected (colour-scheme emulation,
2314
+ * the site's class or attribute toggle, saved preferences), then checked: if the page
2315
+ * did not visibly change, the dark results are not presented as dark mode.
2316
+ */
2317
+ async scanThemes(url, options = {}) {
2318
+ const want = options.theme ?? "auto";
2319
+ let detected;
2320
+ let lightSig;
2321
+ let tryDark = false;
2322
+ let dark = null;
2323
+ let darkApplied;
2324
+ const light = await this.withPage(url, {
2325
+ ...options,
2326
+ colorScheme: "light"
2327
+ }, async (page) => {
2328
+ detected = await page.evaluate(detectThemesInPage);
2329
+ lightSig = await themeSignature(page);
2330
+ const lightResult = want === "dark" ? null : await this.scanPage(page, options);
2331
+ tryDark = want === "dark" || want === "both" || want === "auto" && hasDarkMode(detected);
2332
+ if (tryDark) {
2333
+ await page.emulateMedia({ colorScheme: "dark" });
2334
+ await applyDarkToggles(page, detected.toggles);
2335
+ if (darkModeApplied(lightSig, await themeSignature(page))) {
2336
+ darkApplied = true;
2337
+ dark = await this.scanPage(page, options);
2338
+ }
2339
+ }
2340
+ return lightResult;
2341
+ });
2342
+ if (tryDark && !darkApplied) dark = await this.withPage(url, {
2343
+ ...options,
2344
+ colorScheme: "dark"
2345
+ }, async (page) => {
2346
+ await applyDarkToggles(page, detected.toggles);
2347
+ darkApplied = darkModeApplied(lightSig, await themeSignature(page));
2348
+ return this.scanPage(page, options);
2349
+ });
2350
+ let note;
2351
+ if (tryDark && !darkApplied) {
2352
+ note = "Dark mode could not be switched on: the page looked the same with the system dark preference and the detected toggles. If the site has a theme switch, pass actions that click it (with theme: \"dark\").";
2353
+ if (want === "auto") dark = null;
2354
+ } else if (!tryDark && want === "auto") note = "No dark mode found in the page's stylesheets, so only light mode was scanned.";
2355
+ if (detected.unreadableSheets) note = [note, `${detected.unreadableSheets} stylesheet(s) from other origins could not be read for dark-mode detection.`].filter(Boolean).join(" ");
2356
+ const scanned = [...light ? ["light"] : [], ...dark ? ["dark"] : []];
2357
+ const agentReport = light && dark ? mergeThemeReports(light.agentReport, dark.agentReport) : light ? {
2358
+ ...light.agentReport,
2359
+ findings: light.agentReport.findings.map((f) => ({
2360
+ ...f,
2361
+ themes: ["light"]
2362
+ }))
2363
+ } : {
2364
+ ...dark.agentReport,
2365
+ findings: dark.agentReport.findings.map((f) => ({
2366
+ ...f,
2367
+ id: `${f.id}@dark`,
2368
+ themes: ["dark"]
2369
+ }))
2370
+ };
2371
+ const pageWarnings = [.../* @__PURE__ */ new Set([...light?.report.pageWarnings || [], ...dark?.report.pageWarnings || []])];
2372
+ return {
2373
+ agentReport,
2374
+ ...pageWarnings.length ? { pageWarnings } : {},
2375
+ byTheme: {
2376
+ ...light ? { light } : {},
2377
+ ...dark ? { dark } : {}
2378
+ },
2379
+ themes: {
2380
+ detected,
2381
+ scanned,
2382
+ ...tryDark ? { darkApplied } : {},
2383
+ ...note ? { note } : {}
2384
+ }
2385
+ };
2386
+ }
2387
+ /**
2388
+ * Checks the open dialog after `actions` (e.g. a click that opens it): focus moved
2389
+ * into it, focus contained, accessible name, aria-modal.
2390
+ */
2391
+ async checkDialog(url, options = {}) {
2392
+ return this.withPage(url, options, async (page) => {
2393
+ await injectScanner(page, this.assets);
2394
+ const resp = await sendToScanner(page, { action: "RUN_MODAL_SIMULATION" }, 15e3);
2395
+ if (resp?.violations?.length) {
2396
+ const kept = [];
2397
+ for (const v of resp.violations) {
2398
+ if (!String(v.id).startsWith("custom-focus-trap-escape")) {
2399
+ kept.push(v);
2400
+ continue;
2401
+ }
2402
+ if (await focusEscapes(page, v.selector)) {
2403
+ kept.push(v);
2404
+ resp.log?.push("Confirmed with real Tab / Shift+Tab presses: focus left the dialog.");
2405
+ } else resp.log?.push("✅ Real Tab / Shift+Tab presses kept focus inside the dialog (JavaScript focus trap).");
2406
+ }
2407
+ resp.violations = kept;
2408
+ }
2409
+ return {
2410
+ dialogFound: !!resp?.dialogFound,
2411
+ log: resp?.log || [],
2412
+ findings: (resp?.violations || []).map((v) => ({
2413
+ ruleId: v.ruleId,
2414
+ severity: v.severity,
2415
+ message: v.description,
2416
+ selector: v.selector,
2417
+ wcag: v.wcagSC
2418
+ }))
2419
+ };
2420
+ });
2421
+ }
2422
+ /**
2423
+ * Presses Tab through the page with a real keyboard: focus order, keyboard traps,
2424
+ * focus that is not visible and focus on hidden elements, with source locations.
2425
+ */
2426
+ async checkKeyboard(url, options = {}) {
2427
+ return this.withPage(url, options, async (page) => {
2428
+ const result = await walkKeyboard(page, options.maxTabs ?? 60);
2429
+ if (result.issues.length && options.locate !== false) {
2430
+ const locations = await page.evaluate(locateInPage, result.issues.map((i) => i.selector)).catch(() => null);
2431
+ if (locations) await resolveSourcePositions(locations.map((l) => l.source), new URL(page.url()).origin).catch(() => {});
2432
+ locations?.forEach((loc, i) => {
2433
+ if (loc.source) loc.source = relativizeSource(loc.source, options.projectRoot);
2434
+ result.issues[i].location = loc;
2435
+ });
2436
+ }
2437
+ return result;
2438
+ });
2439
+ }
2440
+ /** Scans an HTML string, served from `baseUrl` so relative URLs resolve. */
2441
+ async scanHtml(html, baseUrl = "http://a11yengine.local/") {
2442
+ const ctx = await this.browser.newContext(CONTEXT_OPTIONS);
2443
+ try {
2444
+ await ctx.addInitScript(CHROME_SHIM);
2445
+ await ctx.route(baseUrl, (route) => route.fulfill({
2446
+ status: 200,
2447
+ contentType: "text/html",
2448
+ body: html
2449
+ }));
2450
+ const page = await ctx.newPage();
2451
+ await page.goto(baseUrl, { waitUntil: "load" });
2452
+ return await this.scanPage(page, {});
2453
+ } finally {
2454
+ await ctx.close().catch(() => {});
2455
+ }
2456
+ }
2457
+ async close() {
2458
+ await this.browser.close().catch(() => {});
2459
+ }
2460
+ };
2461
+ export { A11yEngine, CHROME_SHIM, NO_BROWSER_MESSAGE, auditPdf, buildAgentReport, contrastRatio, defaultDistDir, detectBuildErrorOverlay, diffReports, elementFingerprint, groupFindings, loadAssets, mergeThemeReports, parseColor, scanLoadedPage, suggestContrastFix, TOOL_VERSION as t, toAgentPrompt, toSarif, togglesInSelector };