mcp-web-validator 1.3.51 → 1.3.53

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.
Files changed (172) hide show
  1. package/CHANGELOG.md +41 -0
  2. package/README.md +64 -4
  3. package/dist/audit-history.d.ts +9 -0
  4. package/dist/audit-history.js +27 -0
  5. package/dist/audit-history.js.map +1 -1
  6. package/dist/index.js +2508 -2
  7. package/dist/index.js.map +1 -1
  8. package/dist/modules/browser-ux/lighthouse-lab-probe.d.ts +21 -0
  9. package/dist/modules/browser-ux/lighthouse-lab-probe.js +190 -0
  10. package/dist/modules/browser-ux/lighthouse-lab-probe.js.map +1 -0
  11. package/dist/modules/browser-ux/lighthouse-lab.d.ts +61 -0
  12. package/dist/modules/browser-ux/lighthouse-lab.js +98 -0
  13. package/dist/modules/browser-ux/lighthouse-lab.js.map +1 -0
  14. package/dist/modules/browser-ux/media-diagnostics.d.ts +41 -0
  15. package/dist/modules/browser-ux/media-diagnostics.js +183 -0
  16. package/dist/modules/browser-ux/media-diagnostics.js.map +1 -0
  17. package/dist/modules/browser-ux/raw-rendered-diff.d.ts +70 -0
  18. package/dist/modules/browser-ux/raw-rendered-diff.js +262 -0
  19. package/dist/modules/browser-ux/raw-rendered-diff.js.map +1 -0
  20. package/dist/modules/browser-ux/raw-rendered-probe.d.ts +17 -0
  21. package/dist/modules/browser-ux/raw-rendered-probe.js +163 -0
  22. package/dist/modules/browser-ux/raw-rendered-probe.js.map +1 -0
  23. package/dist/modules/browser-ux/resource-failures-probe.d.ts +11 -0
  24. package/dist/modules/browser-ux/resource-failures-probe.js +231 -0
  25. package/dist/modules/browser-ux/resource-failures-probe.js.map +1 -0
  26. package/dist/modules/browser-ux/resource-failures.d.ts +79 -0
  27. package/dist/modules/browser-ux/resource-failures.js +178 -0
  28. package/dist/modules/browser-ux/resource-failures.js.map +1 -0
  29. package/dist/modules/browser-ux/viewport-parity-probe.d.ts +5 -0
  30. package/dist/modules/browser-ux/viewport-parity-probe.js +307 -0
  31. package/dist/modules/browser-ux/viewport-parity-probe.js.map +1 -0
  32. package/dist/modules/browser-ux/viewport-parity.d.ts +112 -0
  33. package/dist/modules/browser-ux/viewport-parity.js +224 -0
  34. package/dist/modules/browser-ux/viewport-parity.js.map +1 -0
  35. package/dist/modules/browser-ux/wcag-interactions.d.ts +95 -0
  36. package/dist/modules/browser-ux/wcag-interactions.js +360 -0
  37. package/dist/modules/browser-ux/wcag-interactions.js.map +1 -0
  38. package/dist/modules/change-regression/availability-history-store.d.ts +18 -0
  39. package/dist/modules/change-regression/availability-history-store.js +168 -0
  40. package/dist/modules/change-regression/availability-history-store.js.map +1 -0
  41. package/dist/modules/change-regression/crawler-log-correlation.d.ts +111 -0
  42. package/dist/modules/change-regression/crawler-log-correlation.js +374 -0
  43. package/dist/modules/change-regression/crawler-log-correlation.js.map +1 -0
  44. package/dist/modules/change-regression/google-common-crawler-ip.d.ts +15 -0
  45. package/dist/modules/change-regression/google-common-crawler-ip.js +129 -0
  46. package/dist/modules/change-regression/google-common-crawler-ip.js.map +1 -0
  47. package/dist/modules/change-regression/historical-comparisons.d.ts +120 -0
  48. package/dist/modules/change-regression/historical-comparisons.js +330 -0
  49. package/dist/modules/change-regression/historical-comparisons.js.map +1 -0
  50. package/dist/modules/change-regression/production-change-comparison.d.ts +68 -0
  51. package/dist/modules/change-regression/production-change-comparison.js +214 -0
  52. package/dist/modules/change-regression/production-change-comparison.js.map +1 -0
  53. package/dist/modules/change-regression/regression-alerts.d.ts +73 -0
  54. package/dist/modules/change-regression/regression-alerts.js +183 -0
  55. package/dist/modules/change-regression/regression-alerts.js.map +1 -0
  56. package/dist/modules/change-regression/strict-observation-time.d.ts +7 -0
  57. package/dist/modules/change-regression/strict-observation-time.js +31 -0
  58. package/dist/modules/change-regression/strict-observation-time.js.map +1 -0
  59. package/dist/modules/content-schema/citation-methodology-consistency.d.ts +108 -0
  60. package/dist/modules/content-schema/citation-methodology-consistency.js +360 -0
  61. package/dist/modules/content-schema/citation-methodology-consistency.js.map +1 -0
  62. package/dist/modules/content-schema/competitor-intent-comparison.d.ts +74 -0
  63. package/dist/modules/content-schema/competitor-intent-comparison.js +185 -0
  64. package/dist/modules/content-schema/competitor-intent-comparison.js.map +1 -0
  65. package/dist/modules/content-schema/empty-boilerplate-content.d.ts +36 -0
  66. package/dist/modules/content-schema/empty-boilerplate-content.js +225 -0
  67. package/dist/modules/content-schema/empty-boilerplate-content.js.map +1 -0
  68. package/dist/modules/content-schema/extract-citation-methodology.d.ts +6 -0
  69. package/dist/modules/content-schema/extract-citation-methodology.js +201 -0
  70. package/dist/modules/content-schema/extract-citation-methodology.js.map +1 -0
  71. package/dist/modules/content-schema/extract-competitor-intent.d.ts +2 -0
  72. package/dist/modules/content-schema/extract-competitor-intent.js +140 -0
  73. package/dist/modules/content-schema/extract-competitor-intent.js.map +1 -0
  74. package/dist/modules/content-schema/extract-main-content.d.ts +6 -0
  75. package/dist/modules/content-schema/extract-main-content.js +33 -0
  76. package/dist/modules/content-schema/extract-main-content.js.map +1 -0
  77. package/dist/modules/content-schema/extract-metadata-consistency.d.ts +3 -0
  78. package/dist/modules/content-schema/extract-metadata-consistency.js +62 -0
  79. package/dist/modules/content-schema/extract-metadata-consistency.js.map +1 -0
  80. package/dist/modules/content-schema/extract-product-claims.d.ts +3 -0
  81. package/dist/modules/content-schema/extract-product-claims.js +58 -0
  82. package/dist/modules/content-schema/extract-product-claims.js.map +1 -0
  83. package/dist/modules/content-schema/extract-structured-data.d.ts +3 -0
  84. package/dist/modules/content-schema/extract-structured-data.js +25 -0
  85. package/dist/modules/content-schema/extract-structured-data.js.map +1 -0
  86. package/dist/modules/content-schema/metadata-consistency.d.ts +66 -0
  87. package/dist/modules/content-schema/metadata-consistency.js +282 -0
  88. package/dist/modules/content-schema/metadata-consistency.js.map +1 -0
  89. package/dist/modules/content-schema/product-claims.d.ts +73 -0
  90. package/dist/modules/content-schema/product-claims.js +195 -0
  91. package/dist/modules/content-schema/product-claims.js.map +1 -0
  92. package/dist/modules/content-schema/same-language-duplicates.d.ts +52 -0
  93. package/dist/modules/content-schema/same-language-duplicates.js +158 -0
  94. package/dist/modules/content-schema/same-language-duplicates.js.map +1 -0
  95. package/dist/modules/content-schema/structured-data-validation.d.ts +37 -0
  96. package/dist/modules/content-schema/structured-data-validation.js +385 -0
  97. package/dist/modules/content-schema/structured-data-validation.js.map +1 -0
  98. package/dist/modules/external-metrics/crux-field-probe.d.ts +10 -0
  99. package/dist/modules/external-metrics/crux-field-probe.js +113 -0
  100. package/dist/modules/external-metrics/crux-field-probe.js.map +1 -0
  101. package/dist/modules/external-metrics/crux-field.d.ts +61 -0
  102. package/dist/modules/external-metrics/crux-field.js +231 -0
  103. package/dist/modules/external-metrics/crux-field.js.map +1 -0
  104. package/dist/modules/http-crawl/availability-observations.d.ts +68 -0
  105. package/dist/modules/http-crawl/availability-observations.js +206 -0
  106. package/dist/modules/http-crawl/availability-observations.js.map +1 -0
  107. package/dist/modules/http-crawl/availability-probe.d.ts +8 -0
  108. package/dist/modules/http-crawl/availability-probe.js +46 -0
  109. package/dist/modules/http-crawl/availability-probe.js.map +1 -0
  110. package/dist/modules/http-crawl/crawler-access-probe.d.ts +6 -0
  111. package/dist/modules/http-crawl/crawler-access-probe.js +79 -0
  112. package/dist/modules/http-crawl/crawler-access-probe.js.map +1 -0
  113. package/dist/modules/http-crawl/crawler-access.d.ts +75 -0
  114. package/dist/modules/http-crawl/crawler-access.js +404 -0
  115. package/dist/modules/http-crawl/crawler-access.js.map +1 -0
  116. package/dist/modules/http-crawl/http-delivery-probe.d.ts +3 -0
  117. package/dist/modules/http-crawl/http-delivery-probe.js +44 -0
  118. package/dist/modules/http-crawl/http-delivery-probe.js.map +1 -0
  119. package/dist/modules/http-crawl/http-delivery.d.ts +64 -0
  120. package/dist/modules/http-crawl/http-delivery.js +269 -0
  121. package/dist/modules/http-crawl/http-delivery.js.map +1 -0
  122. package/dist/modules/http-crawl/https-security.d.ts +84 -0
  123. package/dist/modules/http-crawl/https-security.js +441 -0
  124. package/dist/modules/http-crawl/https-security.js.map +1 -0
  125. package/dist/modules/http-crawl/non-html-directives.d.ts +74 -0
  126. package/dist/modules/http-crawl/non-html-directives.js +353 -0
  127. package/dist/modules/http-crawl/non-html-directives.js.map +1 -0
  128. package/dist/modules/http-crawl/redirect-canonical-chains.d.ts +80 -0
  129. package/dist/modules/http-crawl/redirect-canonical-chains.js +459 -0
  130. package/dist/modules/http-crawl/redirect-canonical-chains.js.map +1 -0
  131. package/dist/modules/http-crawl/redirect-canonical-probe.d.ts +6 -0
  132. package/dist/modules/http-crawl/redirect-canonical-probe.js +83 -0
  133. package/dist/modules/http-crawl/redirect-canonical-probe.js.map +1 -0
  134. package/dist/modules/http-crawl/sitemap-inventory-probe.d.ts +8 -0
  135. package/dist/modules/http-crawl/sitemap-inventory-probe.js +155 -0
  136. package/dist/modules/http-crawl/sitemap-inventory-probe.js.map +1 -0
  137. package/dist/modules/http-crawl/sitemap-inventory.d.ts +107 -0
  138. package/dist/modules/http-crawl/sitemap-inventory.js +557 -0
  139. package/dist/modules/http-crawl/sitemap-inventory.js.map +1 -0
  140. package/dist/modules/http-crawl/url-variants.d.ts +86 -0
  141. package/dist/modules/http-crawl/url-variants.js +379 -0
  142. package/dist/modules/http-crawl/url-variants.js.map +1 -0
  143. package/dist/modules/site-architecture/extract-internal-links.d.ts +3 -0
  144. package/dist/modules/site-architecture/extract-internal-links.js +88 -0
  145. package/dist/modules/site-architecture/extract-internal-links.js.map +1 -0
  146. package/dist/modules/site-architecture/extract-multilingual-page.d.ts +2 -0
  147. package/dist/modules/site-architecture/extract-multilingual-page.js +29 -0
  148. package/dist/modules/site-architecture/extract-multilingual-page.js.map +1 -0
  149. package/dist/modules/site-architecture/internal-link-graph-probe.d.ts +7 -0
  150. package/dist/modules/site-architecture/internal-link-graph-probe.js +116 -0
  151. package/dist/modules/site-architecture/internal-link-graph-probe.js.map +1 -0
  152. package/dist/modules/site-architecture/internal-link-graph.d.ts +113 -0
  153. package/dist/modules/site-architecture/internal-link-graph.js +414 -0
  154. package/dist/modules/site-architecture/internal-link-graph.js.map +1 -0
  155. package/dist/modules/site-architecture/internal-link-quality.d.ts +77 -0
  156. package/dist/modules/site-architecture/internal-link-quality.js +260 -0
  157. package/dist/modules/site-architecture/internal-link-quality.js.map +1 -0
  158. package/dist/modules/site-architecture/multilingual-clusters.d.ts +82 -0
  159. package/dist/modules/site-architecture/multilingual-clusters.js +363 -0
  160. package/dist/modules/site-architecture/multilingual-clusters.js.map +1 -0
  161. package/dist/network.d.ts +4 -0
  162. package/dist/network.js +18 -2
  163. package/dist/network.js.map +1 -1
  164. package/dist/presentation.d.ts +53 -0
  165. package/dist/presentation.js +526 -0
  166. package/dist/presentation.js.map +1 -1
  167. package/dist/screenshot.d.ts +2 -1
  168. package/dist/screenshot.js +4 -2
  169. package/dist/screenshot.js.map +1 -1
  170. package/dist/seo-auditor.js +16 -6
  171. package/dist/seo-auditor.js.map +1 -1
  172. package/package.json +7 -4
@@ -0,0 +1,360 @@
1
+ import { defaultScreenshotBrowserRuntime } from "../../screenshot.js";
2
+ import { load } from "cheerio";
3
+ /** P1-12: bounded, browser-backed evidence from an inert, offline HTML sample. */
4
+ export const MAX_WCAG_HTML_BYTES = 180_000;
5
+ export const MAX_WCAG_CONTROLS = 120;
6
+ export const MAX_WCAG_TAB_STEPS = 24;
7
+ export const MAX_WCAG_FINDINGS = 12;
8
+ const DENY_ALL_PROXY = "http://127.0.0.1:9";
9
+ const CONTROL_SELECTOR = 'a[href],button,input:not([type="hidden"]),select,textarea,summary,[tabindex],'
10
+ + '[role="button"],[role="link"],[role="checkbox"],[role="switch"],[role="tab"],[role="menuitem"]';
11
+ export const WCAG_FINDING_CODES = [
12
+ "missing_accessible_name",
13
+ "positive_tabindex",
14
+ "aria_hidden_focusable",
15
+ "custom_role_not_keyboard_focusable",
16
+ "potential_focus_indicator_absent",
17
+ "focus_outside_viewport",
18
+ "summary_enter_not_toggled",
19
+ ];
20
+ export const WCAG_EVIDENCE_TYPES = ["rendered_dom", "keyboard_tab", "native_summary"];
21
+ function boundedViewport(value, fallback, min, max) {
22
+ const actual = value ?? fallback;
23
+ if (!Number.isSafeInteger(actual) || actual < min || actual > max) {
24
+ throw new Error("Unsupported WCAG viewport dimension");
25
+ }
26
+ return actual;
27
+ }
28
+ export function validateWcagInput(html, options = {}) {
29
+ if (typeof html !== "string" || html.trim().length === 0) {
30
+ throw new Error("Supply nonempty authorized HTML");
31
+ }
32
+ if (Buffer.byteLength(html, "utf8") > MAX_WCAG_HTML_BYTES) {
33
+ throw new Error("HTML exceeds the WCAG byte limit");
34
+ }
35
+ const maxTabSteps = options.maxTabSteps ?? MAX_WCAG_TAB_STEPS;
36
+ if (!Number.isSafeInteger(maxTabSteps) || maxTabSteps < 1 || maxTabSteps > MAX_WCAG_TAB_STEPS) {
37
+ throw new Error("Unsupported keyboard sampling budget");
38
+ }
39
+ return {
40
+ width: boundedViewport(options.viewportWidth, 960, 320, 1_440),
41
+ height: boundedViewport(options.viewportHeight, 720, 360, 1_080),
42
+ maxTabSteps,
43
+ };
44
+ }
45
+ export function emptyWcagReview(options = {}) {
46
+ return {
47
+ scope: "offline_sandboxed_rendered_html",
48
+ browser_executed: false, scripts_disabled: true,
49
+ viewport_width: options.viewportWidth ?? 960,
50
+ viewport_height: options.viewportHeight ?? 720,
51
+ resources_blocked: 0, scripts_present: 0,
52
+ controls_seen: 0, controls_inspected: 0, controls_truncated: false,
53
+ visible_controls_without_name: 0, positive_tabindex_controls: 0,
54
+ aria_hidden_focusable_controls: 0, custom_roles_without_tab_stop: 0,
55
+ tab_steps: 0, unique_tab_targets: 0, focus_indicator_review_leads: 0,
56
+ focus_outside_viewport: 0, native_summaries_tested: 0,
57
+ native_summaries_toggled: 0, keyboard_sampling_incomplete: false,
58
+ coverage_limited: true,
59
+ limitations: [
60
+ "The inert Chromium accessibility evidence review could not complete; no browser verification is claimed.",
61
+ ],
62
+ total_findings: 0, findings: [], findings_truncated: false,
63
+ };
64
+ }
65
+ /** Reduce only fixed-shape, no-content browser observations to deterministic findings. */
66
+ export function analyzeWcagEvidence(snapshot, focusSamples, options) {
67
+ const out = emptyWcagReview({
68
+ viewportWidth: options.viewportWidth,
69
+ viewportHeight: options.viewportHeight,
70
+ });
71
+ if (!Number.isSafeInteger(snapshot.controls_seen) || snapshot.controls_seen < 0
72
+ || snapshot.controls.length > MAX_WCAG_CONTROLS
73
+ || snapshot.controls_seen < snapshot.controls.length
74
+ || focusSamples.length > MAX_WCAG_TAB_STEPS) {
75
+ throw new Error("Invalid browser evidence bounds");
76
+ }
77
+ out.browser_executed = true;
78
+ out.resources_blocked = Math.max(0, options.resourcesBlocked ?? 0);
79
+ out.scripts_present = Math.max(0, snapshot.page_scripts_present);
80
+ out.controls_seen = snapshot.controls_seen;
81
+ out.controls_inspected = snapshot.controls.length;
82
+ out.controls_truncated = snapshot.controls_seen > snapshot.controls.length;
83
+ out.tab_steps = Math.min(options.tabSteps ?? focusSamples.length, MAX_WCAG_TAB_STEPS);
84
+ out.native_summaries_tested = Math.min(1, options.nativeSummariesTested ?? 0);
85
+ out.native_summaries_toggled = Math.min(out.native_summaries_tested, options.nativeSummariesToggled ?? 0);
86
+ out.keyboard_sampling_incomplete = options.keyboardIncomplete ?? false;
87
+ out.limitations = [
88
+ "Only supplied HTML in a fresh, script-disabled, offline Chromium page was rendered; external styles, fonts, images, frames and dynamic JavaScript behavior were not loaded or executed.",
89
+ "Only up to 120 DOM controls and 24 Tab steps at one viewport were sampled. This is not an exhaustive keyboard path, screen-reader test, accessibility-tree inspection or WCAG conformance assessment.",
90
+ "Accessible names and focus visibility are conservative rendered-DOM/computed-style heuristics; CSS background/border indicators, occlusion and all assistive-technology semantics require manual review.",
91
+ "Only a focused native <summary> may receive Enter. No links are activated, buttons clicked, form contents changed or submitted, or external resources requested by this tool.",
92
+ ];
93
+ const all = [];
94
+ function add(code, severity, evidence, index, message) {
95
+ all.push({ code, severity, evidence, control: index, message });
96
+ }
97
+ const inspected = new Set();
98
+ for (const item of snapshot.controls) {
99
+ if (!Number.isSafeInteger(item.index) || item.index < 1
100
+ || item.index > MAX_WCAG_CONTROLS || inspected.has(item.index)) {
101
+ throw new Error("Invalid control evidence index");
102
+ }
103
+ inspected.add(item.index);
104
+ if (!item.visible || !item.enabled)
105
+ continue;
106
+ if (!item.name_present) {
107
+ out.visible_controls_without_name++;
108
+ add("missing_accessible_name", "warning", "rendered_dom", item.index, "This visible control lacks a recognized accessible-name signal; verify the actual accessibility tree.");
109
+ }
110
+ if (item.positive_tabindex) {
111
+ out.positive_tabindex_controls++;
112
+ add("positive_tabindex", "warning", "rendered_dom", item.index, "A positive tabindex may reorder keyboard navigation; review intentional keyboard order.");
113
+ }
114
+ if (item.aria_hidden && item.focusable) {
115
+ out.aria_hidden_focusable_controls++;
116
+ add("aria_hidden_focusable", "warning", "rendered_dom", item.index, "A keyboard-focusable control is inside aria-hidden content; this may hide it from assistive technology.");
117
+ }
118
+ if (item.custom_role_without_tab_stop) {
119
+ out.custom_roles_without_tab_stop++;
120
+ add("custom_role_not_keyboard_focusable", "warning", "rendered_dom", item.index, "A custom interactive role has no native or declared Tab stop; check actual keyboard operation.");
121
+ }
122
+ }
123
+ const unique = new Set();
124
+ for (const item of focusSamples) {
125
+ if (!Number.isSafeInteger(item.index) || item.index < 1 || !inspected.has(item.index)
126
+ || unique.has(item.index))
127
+ continue;
128
+ unique.add(item.index);
129
+ if ((!item.outline_or_shadow_present || item.opacity_zero)) {
130
+ out.focus_indicator_review_leads++;
131
+ add("potential_focus_indicator_absent", "info", "keyboard_tab", item.index, "After Tab, no computed outline/shadow or an opacity-zero state was observed; a different focus indicator may exist.");
132
+ }
133
+ if (!item.inside_viewport) {
134
+ out.focus_outside_viewport++;
135
+ add("focus_outside_viewport", "info", "keyboard_tab", item.index, "The sampled Tab focus target did not intersect the viewport; verify visibility and page scrolling.");
136
+ }
137
+ }
138
+ out.unique_tab_targets = unique.size;
139
+ if (out.native_summaries_tested && !out.native_summaries_toggled) {
140
+ const summary = focusSamples.find((item) => item.summary);
141
+ add("summary_enter_not_toggled", "warning", "native_summary", summary?.index ?? 1, "Enter did not toggle the sampled native details summary in the isolated browser.");
142
+ }
143
+ all.sort((a, b) => (a.severity === b.severity ? 0 : a.severity === "warning" ? -1 : 1)
144
+ || a.control - b.control || a.code.localeCompare(b.code));
145
+ out.total_findings = all.length;
146
+ out.findings = all.slice(0, MAX_WCAG_FINDINGS);
147
+ out.findings_truncated = all.length > MAX_WCAG_FINDINGS;
148
+ return out;
149
+ }
150
+ /**
151
+ * Offline Chromium checks of supplied HTML: scripts disabled, network requests
152
+ * aborted, no link clicks, no form submissions, no browser profile reuse.
153
+ * The only Enter keypress is on a focused native HTML summary element.
154
+ */
155
+ export async function reviewWcagInteractions(html, options = {}, runtime = defaultScreenshotBrowserRuntime) {
156
+ const config = validateWcagInput(html, options);
157
+ // Defense-in-depth: even with Chromium scripting explicitly disabled, do
158
+ // not instantiate untrusted script, embedded frames or refresh navigation.
159
+ const $ = load(html);
160
+ const strippedScriptCount = $("script").length;
161
+ $("script,iframe,frame,frameset,object,embed,portal").remove();
162
+ $('meta[http-equiv="refresh" i]').remove();
163
+ $("*").each((_, element) => {
164
+ if (!("attribs" in element) || !element.attribs)
165
+ return;
166
+ for (const name of Object.keys(element.attribs)) {
167
+ if (/^on[a-z]+$/iu.test(name))
168
+ $(element).removeAttr(name);
169
+ }
170
+ });
171
+ const inertHtml = $.html();
172
+ let browser;
173
+ let pendingError;
174
+ let browserDeadline;
175
+ try {
176
+ // The pinned screenshot runtime launches a fresh sandboxed Chromium process.
177
+ // Port 9 is deliberately not serviced: the transport cannot reach page URLs.
178
+ browser = await runtime.launch(DENY_ALL_PROXY);
179
+ // A hard deadline also covers keyboard/evaluation operations, which are
180
+ // not governed by Puppeteer's navigation timeout.
181
+ browserDeadline = setTimeout(() => {
182
+ void browser?.close().catch(() => { });
183
+ }, 20_000);
184
+ browserDeadline.unref?.();
185
+ const page = await browser.newPage();
186
+ page.setDefaultTimeout(5_000);
187
+ page.setDefaultNavigationTimeout(8_000);
188
+ await page.setViewport({ width: config.width, height: config.height, deviceScaleFactor: 1 });
189
+ await page.setJavaScriptEnabled(false);
190
+ let blocked = 0;
191
+ await page.setRequestInterception(true);
192
+ page.on("request", (request) => {
193
+ blocked++;
194
+ void request.abort("blockedbyclient").catch(() => { });
195
+ });
196
+ await page.setContent(inertHtml, { waitUntil: "domcontentloaded", timeout: 8_000 });
197
+ // All browser-side data is reduced to booleans/counts, never raw HTML/text,
198
+ // attributes, CSS properties, input values, URLs, IDs or names.
199
+ const snapshot = await page.evaluate((selector, cap) => {
200
+ const dom = globalThis.document;
201
+ const compute = globalThis.getComputedStyle;
202
+ const all = Array.from(dom.querySelectorAll(selector));
203
+ const controls = [];
204
+ for (let i = 0; i < Math.min(all.length, cap); i++) {
205
+ const element = all[i];
206
+ const styles = compute(element);
207
+ const box = element.getBoundingClientRect();
208
+ const visible = styles.display !== "none" &&
209
+ styles.visibility !== "hidden" && styles.visibility !== "collapse" &&
210
+ box.width > 0 && box.height > 0 && !element.closest("[hidden],[inert]");
211
+ const tag = String(element.tagName).toLowerCase();
212
+ const type = String(element.getAttribute("type") ?? "").toLowerCase();
213
+ const role = String(element.getAttribute("role") ?? "").toLowerCase();
214
+ const native = ["button", "input", "select", "textarea", "a", "summary"].includes(tag);
215
+ const customRole = ["button", "link", "checkbox", "switch", "tab", "menuitem"].includes(role);
216
+ const nonempty = (value) => typeof value === "string" && value.trim().length > 0;
217
+ const describedBy = String(element.getAttribute("aria-labelledby") ?? "")
218
+ .split(/\s+/u).filter(Boolean).some((id) => nonempty(dom.getElementById(id)?.textContent));
219
+ const ariaLabel = nonempty(element.getAttribute("aria-label"));
220
+ const associatedLabel = Boolean(element.labels &&
221
+ Array.from(element.labels).some((label) => nonempty(label.textContent)));
222
+ const labelWrapping = nonempty(element.closest("label")?.textContent);
223
+ const title = nonempty(element.getAttribute("title"));
224
+ const text = ["a", "button", "summary"].includes(tag) && nonempty(element.textContent);
225
+ const alt = ["a", "button"].includes(tag) &&
226
+ Array.from(element.querySelectorAll("img")).some((image) => nonempty(image.getAttribute("alt")));
227
+ const inputAlt = tag === "input" && type === "image" && nonempty(element.getAttribute("alt"));
228
+ // Submit/reset have user-agent default names; input[type=button]
229
+ // without a value does not have that same fallback.
230
+ const nativeSubmit = tag === "input" && (["submit", "reset"].includes(type)
231
+ || (type === "button" && nonempty(element.value)));
232
+ controls.push({
233
+ index: i + 1,
234
+ visible: Boolean(visible),
235
+ enabled: !element.disabled && !element.closest("fieldset[disabled]"),
236
+ focusable: visible && element.tabIndex >= 0,
237
+ name_present: Boolean(describedBy || ariaLabel || associatedLabel ||
238
+ labelWrapping || title || text || alt || inputAlt || nativeSubmit),
239
+ positive_tabindex: element.tabIndex > 0,
240
+ aria_hidden: Boolean(element.closest('[aria-hidden="true" i]')),
241
+ custom_role_without_tab_stop: Boolean(customRole && !native && element.tabIndex < 0),
242
+ });
243
+ }
244
+ return {
245
+ controls_seen: all.length,
246
+ controls,
247
+ page_scripts_present: dom.querySelectorAll("script").length,
248
+ };
249
+ }, CONTROL_SELECTOR, MAX_WCAG_CONTROLS);
250
+ snapshot.page_scripts_present += strippedScriptCount;
251
+ const samples = [];
252
+ const focused = new Set();
253
+ let tabSteps = 0;
254
+ let keyboardIncomplete = false;
255
+ let summaryIndex;
256
+ // Autofocus in supplied markup should not skip the first Tab stop.
257
+ await page.evaluate(() => { globalThis.document.activeElement?.blur?.(); });
258
+ try {
259
+ const maxSteps = Math.min(config.maxTabSteps, Math.max(2, snapshot.controls_seen + 1));
260
+ for (let i = 0; i < maxSteps; i++) {
261
+ await page.keyboard.press("Tab");
262
+ tabSteps++;
263
+ const entry = await page.evaluate((selector, cap) => {
264
+ const dom = globalThis.document;
265
+ const compute = globalThis.getComputedStyle;
266
+ const current = dom.activeElement;
267
+ if (!current)
268
+ return null;
269
+ const all = Array.from(dom.querySelectorAll(selector));
270
+ const index = all.indexOf(current) + 1;
271
+ if (index < 1 || index > cap)
272
+ return null;
273
+ const style = compute(current);
274
+ const rect = current.getBoundingClientRect();
275
+ const outline = style.outlineStyle !== "none" &&
276
+ Number.parseFloat(style.outlineWidth) > 0;
277
+ const shadow = style.boxShadow && style.boxShadow !== "none";
278
+ const viewportWidth = globalThis.innerWidth;
279
+ const viewportHeight = globalThis.innerHeight;
280
+ return {
281
+ index,
282
+ outline_or_shadow_present: Boolean(outline || shadow),
283
+ inside_viewport: Boolean(rect.width > 0 && rect.height > 0 &&
284
+ rect.bottom > 0 && rect.right > 0 &&
285
+ rect.left < viewportWidth && rect.top < viewportHeight),
286
+ opacity_zero: Number.parseFloat(style.opacity) === 0,
287
+ summary: String(current.tagName).toLowerCase() === "summary",
288
+ };
289
+ }, CONTROL_SELECTOR, MAX_WCAG_CONTROLS);
290
+ if (!entry) {
291
+ // The browser has left the sampled control set or no focus occurred.
292
+ if (snapshot.controls_seen > MAX_WCAG_CONTROLS)
293
+ keyboardIncomplete = true;
294
+ break;
295
+ }
296
+ if (focused.has(entry.index))
297
+ break; // Wraparound is not a trap.
298
+ focused.add(entry.index);
299
+ samples.push(entry);
300
+ if (entry.summary && summaryIndex === undefined) {
301
+ summaryIndex = entry.index;
302
+ }
303
+ }
304
+ }
305
+ catch {
306
+ keyboardIncomplete = true;
307
+ }
308
+ let summariesTested = 0;
309
+ let summariesToggled = 0;
310
+ if (summaryIndex !== undefined) {
311
+ try {
312
+ // Only focus the *same* native summary reached by Tab, not an unrelated
313
+ // earlier summary that might be hidden or nested in an inactive widget.
314
+ const summaryReady = await page.evaluate((selector, index) => {
315
+ const dom = globalThis.document;
316
+ const s = dom.querySelectorAll(selector)[index - 1];
317
+ if (!s || String(s.tagName).toLowerCase() !== "summary"
318
+ || String(s.parentElement?.tagName).toLowerCase() !== "details")
319
+ return false;
320
+ s.focus();
321
+ return dom.activeElement === s;
322
+ }, CONTROL_SELECTOR, summaryIndex);
323
+ if (summaryReady) {
324
+ summariesTested = 1;
325
+ const before = await page.evaluate(() => Boolean(globalThis.document.activeElement?.closest("details")?.open));
326
+ await page.keyboard.press("Enter");
327
+ const after = await page.evaluate(() => Boolean(globalThis.document.activeElement?.closest("details")?.open));
328
+ summariesToggled = before !== after ? 1 : 0;
329
+ }
330
+ }
331
+ catch {
332
+ keyboardIncomplete = true;
333
+ }
334
+ }
335
+ return analyzeWcagEvidence(snapshot, samples, {
336
+ viewportWidth: config.width, viewportHeight: config.height,
337
+ resourcesBlocked: blocked, tabSteps,
338
+ nativeSummariesTested: summariesTested,
339
+ nativeSummariesToggled: summariesToggled,
340
+ keyboardIncomplete,
341
+ });
342
+ }
343
+ catch (cause) {
344
+ pendingError = cause;
345
+ throw cause;
346
+ }
347
+ finally {
348
+ if (browserDeadline)
349
+ clearTimeout(browserDeadline);
350
+ try {
351
+ if (browser)
352
+ await browser.close();
353
+ }
354
+ catch (cause) {
355
+ if (!pendingError)
356
+ throw cause;
357
+ }
358
+ }
359
+ }
360
+ //# sourceMappingURL=wcag-interactions.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"wcag-interactions.js","sourceRoot":"","sources":["../../../src/modules/browser-ux/wcag-interactions.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,+BAA+B,EAAiC,MAAM,qBAAqB,CAAC;AACrG,OAAO,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAE/B,kFAAkF;AAClF,MAAM,CAAC,MAAM,mBAAmB,GAAG,OAAO,CAAC;AAC3C,MAAM,CAAC,MAAM,iBAAiB,GAAG,GAAG,CAAC;AACrC,MAAM,CAAC,MAAM,kBAAkB,GAAG,EAAE,CAAC;AACrC,MAAM,CAAC,MAAM,iBAAiB,GAAG,EAAE,CAAC;AACpC,MAAM,cAAc,GAAG,oBAAoB,CAAC;AAC5C,MAAM,gBAAgB,GACpB,+EAA+E;MAC7E,gGAAgG,CAAC;AAErG,MAAM,CAAC,MAAM,kBAAkB,GAAG;IAChC,yBAAyB;IACzB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Runtime, type ScreenshotBrowserRuntime } from \"../../screenshot.js\";\nimport { load } from \"cheerio\";\n\n/** P1-12: bounded, browser-backed evidence from an inert, offline HTML sample. */\nexport const MAX_WCAG_HTML_BYTES = 180_000;\nexport const MAX_WCAG_CONTROLS = 120;\nexport const MAX_WCAG_TAB_STEPS = 24;\nexport const MAX_WCAG_FINDINGS = 12;\nconst DENY_ALL_PROXY = \"http://127.0.0.1:9\";\nconst CONTROL_SELECTOR =\n 'a[href],button,input:not([type=\"hidden\"]),select,textarea,summary,[tabindex],'\n + '[role=\"button\"],[role=\"link\"],[role=\"checkbox\"],[role=\"switch\"],[role=\"tab\"],[role=\"menuitem\"]';\n\nexport const WCAG_FINDING_CODES = [\n \"missing_accessible_name\",\n \"positive_tabindex\",\n \"aria_hidden_focusable\",\n \"custom_role_not_keyboard_focusable\",\n \"potential_focus_indicator_absent\",\n \"focus_outside_viewport\",\n \"summary_enter_not_toggled\",\n] as const;\nexport type WcagFindingCode = typeof WCAG_FINDING_CODES[number];\n\nexport const WCAG_EVIDENCE_TYPES = [\"rendered_dom\", \"keyboard_tab\", \"native_summary\"] as const;\nexport type WcagEvidenceType = typeof WCAG_EVIDENCE_TYPES[number];\n\nexport interface WcagControlEvidence {\n index: number;\n visible: boolean;\n enabled: boolean;\n focusable: boolean;\n name_present: boolean;\n positive_tabindex: boolean;\n aria_hidden: boolean;\n custom_role_without_tab_stop: boolean;\n}\n\nexport interface WcagFocusEvidence {\n index: number;\n outline_or_shadow_present: boolean;\n inside_viewport: boolean;\n opacity_zero: boolean;\n summary: boolean;\n}\n\nexport interface WcagRenderedSnapshot {\n controls_seen: number;\n controls: WcagControlEvidence[];\n page_scripts_present: number;\n}\n\nexport interface WcagFinding {\n code: WcagFindingCode;\n severity: \"warning\" | \"info\";\n evidence: WcagEvidenceType;\n control: number;\n message: string;\n}\n\nexport interface WcagInteractionReview {\n scope: \"offline_sandboxed_rendered_html\";\n browser_executed: boolean;\n scripts_disabled: true;\n viewport_width: number;\n viewport_height: number;\n resources_blocked: number;\n scripts_present: number;\n controls_seen: number;\n controls_inspected: number;\n controls_truncated: boolean;\n visible_controls_without_name: number;\n positive_tabindex_controls: number;\n aria_hidden_focusable_controls: number;\n custom_roles_without_tab_stop: number;\n tab_steps: number;\n unique_tab_targets: number;\n focus_indicator_review_leads: number;\n focus_outside_viewport: number;\n native_summaries_tested: number;\n native_summaries_toggled: number;\n keyboard_sampling_incomplete: boolean;\n coverage_limited: true;\n limitations: string[];\n total_findings: number;\n findings: WcagFinding[];\n findings_truncated: boolean;\n error?: string;\n}\n\nexport interface WcagReviewOptions {\n viewportWidth?: number;\n viewportHeight?: number;\n maxTabSteps?: number;\n}\n\nfunction boundedViewport(value: number | undefined, fallback: number, min: number, max: number): number {\n const actual = value ?? fallback;\n if (!Number.isSafeInteger(actual) || actual < min || actual > max) {\n throw new Error(\"Unsupported WCAG viewport dimension\");\n }\n return actual;\n}\n\nexport function validateWcagInput(html: string, options: WcagReviewOptions = {}): {\n width: number; height: number; maxTabSteps: number;\n} {\n if (typeof html !== \"string\" || html.trim().length === 0) {\n throw new Error(\"Supply nonempty authorized HTML\");\n }\n if (Buffer.byteLength(html, \"utf8\") > MAX_WCAG_HTML_BYTES) {\n throw new Error(\"HTML exceeds the WCAG byte limit\");\n }\n const maxTabSteps = options.maxTabSteps ?? MAX_WCAG_TAB_STEPS;\n if (!Number.isSafeInteger(maxTabSteps) || maxTabSteps < 1 || maxTabSteps > MAX_WCAG_TAB_STEPS) {\n throw new Error(\"Unsupported keyboard sampling budget\");\n }\n return {\n width: boundedViewport(options.viewportWidth, 960, 320, 1_440),\n height: boundedViewport(options.viewportHeight, 720, 360, 1_080),\n maxTabSteps,\n };\n}\n\nexport function emptyWcagReview(options: WcagReviewOptions = {}): WcagInteractionReview {\n return {\n scope: \"offline_sandboxed_rendered_html\",\n browser_executed: false, scripts_disabled: true,\n viewport_width: options.viewportWidth ?? 960,\n viewport_height: options.viewportHeight ?? 720,\n resources_blocked: 0, scripts_present: 0,\n controls_seen: 0, controls_inspected: 0, controls_truncated: false,\n visible_controls_without_name: 0, positive_tabindex_controls: 0,\n aria_hidden_focusable_controls: 0, custom_roles_without_tab_stop: 0,\n tab_steps: 0, unique_tab_targets: 0, focus_indicator_review_leads: 0,\n focus_outside_viewport: 0, native_summaries_tested: 0,\n native_summaries_toggled: 0, keyboard_sampling_incomplete: false,\n coverage_limited: true,\n limitations: [\n \"The inert Chromium accessibility evidence review could not complete; no browser verification is claimed.\",\n ],\n total_findings: 0, findings: [], findings_truncated: false,\n };\n}\n\n/** Reduce only fixed-shape, no-content browser observations to deterministic findings. */\nexport function analyzeWcagEvidence(\n snapshot: WcagRenderedSnapshot,\n focusSamples: WcagFocusEvidence[],\n options: {\n viewportWidth: number; viewportHeight: number;\n resourcesBlocked?: number; tabSteps?: number;\n nativeSummariesTested?: number; nativeSummariesToggled?: number;\n keyboardIncomplete?: boolean;\n },\n): WcagInteractionReview {\n const out = emptyWcagReview({\n viewportWidth: options.viewportWidth,\n viewportHeight: options.viewportHeight,\n });\n if (!Number.isSafeInteger(snapshot.controls_seen) || snapshot.controls_seen < 0\n || snapshot.controls.length > MAX_WCAG_CONTROLS\n || snapshot.controls_seen < snapshot.controls.length\n || focusSamples.length > MAX_WCAG_TAB_STEPS) {\n throw new Error(\"Invalid browser evidence bounds\");\n }\n out.browser_executed = true;\n out.resources_blocked = Math.max(0, options.resourcesBlocked ?? 0);\n out.scripts_present = Math.max(0, snapshot.page_scripts_present);\n out.controls_seen = snapshot.controls_seen;\n out.controls_inspected = snapshot.controls.length;\n out.controls_truncated = snapshot.controls_seen > snapshot.controls.length;\n out.tab_steps = Math.min(options.tabSteps ?? focusSamples.length, MAX_WCAG_TAB_STEPS);\n out.native_summaries_tested = Math.min(1, options.nativeSummariesTested ?? 0);\n out.native_summaries_toggled = Math.min(out.native_summaries_tested, options.nativeSummariesToggled ?? 0);\n out.keyboard_sampling_incomplete = options.keyboardIncomplete ?? false;\n out.limitations = [\n \"Only supplied HTML in a fresh, script-disabled, offline Chromium page was rendered; external styles, fonts, images, frames and dynamic JavaScript behavior were not loaded or executed.\",\n \"Only up to 120 DOM controls and 24 Tab steps at one viewport were sampled. This is not an exhaustive keyboard path, screen-reader test, accessibility-tree inspection or WCAG conformance assessment.\",\n \"Accessible names and focus visibility are conservative rendered-DOM/computed-style heuristics; CSS background/border indicators, occlusion and all assistive-technology semantics require manual review.\",\n \"Only a focused native <summary> may receive Enter. No links are activated, buttons clicked, form contents changed or submitted, or external resources requested by this tool.\",\n ];\n const all: WcagFinding[] = [];\n function add(code: WcagFindingCode, severity: \"warning\" | \"info\",\n evidence: WcagEvidenceType, index: number, message: string) {\n all.push({ code, severity, evidence, control: index, message });\n }\n const inspected = new Set<number>();\n for (const item of snapshot.controls) {\n if (!Number.isSafeInteger(item.index) || item.index < 1\n || item.index > MAX_WCAG_CONTROLS || inspected.has(item.index)) {\n throw new Error(\"Invalid control evidence index\");\n }\n inspected.add(item.index);\n if (!item.visible || !item.enabled) continue;\n if (!item.name_present) {\n out.visible_controls_without_name++;\n add(\"missing_accessible_name\", \"warning\", \"rendered_dom\", item.index,\n \"This visible control lacks a recognized accessible-name signal; verify the actual accessibility tree.\");\n }\n if (item.positive_tabindex) {\n out.positive_tabindex_controls++;\n add(\"positive_tabindex\", \"warning\", \"rendered_dom\", item.index,\n \"A positive tabindex may reorder keyboard navigation; review intentional keyboard order.\");\n }\n if (item.aria_hidden && item.focusable) {\n out.aria_hidden_focusable_controls++;\n add(\"aria_hidden_focusable\", \"warning\", \"rendered_dom\", item.index,\n \"A keyboard-focusable control is inside aria-hidden content; this may hide it from assistive technology.\");\n }\n if (item.custom_role_without_tab_stop) {\n out.custom_roles_without_tab_stop++;\n add(\"custom_role_not_keyboard_focusable\", \"warning\", \"rendered_dom\", item.index,\n \"A custom interactive role has no native or declared Tab stop; check actual keyboard operation.\");\n }\n }\n const unique = new Set<number>();\n for (const item of focusSamples) {\n if (!Number.isSafeInteger(item.index) || item.index < 1 || !inspected.has(item.index)\n || unique.has(item.index)) continue;\n unique.add(item.index);\n if ((!item.outline_or_shadow_present || item.opacity_zero)) {\n out.focus_indicator_review_leads++;\n add(\"potential_focus_indicator_absent\", \"info\", \"keyboard_tab\", item.index,\n \"After Tab, no computed outline/shadow or an opacity-zero state was observed; a different focus indicator may exist.\");\n }\n if (!item.inside_viewport) {\n out.focus_outside_viewport++;\n add(\"focus_outside_viewport\", \"info\", \"keyboard_tab\", item.index,\n \"The sampled Tab focus target did not intersect the viewport; verify visibility and page scrolling.\");\n }\n }\n out.unique_tab_targets = unique.size;\n if (out.native_summaries_tested && !out.native_summaries_toggled) {\n const summary = focusSamples.find((item) => item.summary);\n add(\"summary_enter_not_toggled\", \"warning\", \"native_summary\", summary?.index ?? 1,\n \"Enter did not toggle the sampled native details summary in the isolated browser.\");\n }\n all.sort((a, b) => (a.severity === b.severity ? 0 : a.severity === \"warning\" ? -1 : 1)\n || a.control - b.control || a.code.localeCompare(b.code));\n out.total_findings = all.length;\n out.findings = all.slice(0, MAX_WCAG_FINDINGS);\n out.findings_truncated = all.length > MAX_WCAG_FINDINGS;\n return out;\n}\n\n/**\n * Offline Chromium checks of supplied HTML: scripts disabled, network requests\n * aborted, no link clicks, no form submissions, no browser profile reuse.\n * The only Enter keypress is on a focused native HTML summary element.\n */\nexport async function reviewWcagInteractions(\n html: string,\n options: WcagReviewOptions = {},\n runtime: ScreenshotBrowserRuntime = defaultScreenshotBrowserRuntime,\n): Promise<WcagInteractionReview> {\n const config = validateWcagInput(html, options);\n // Defense-in-depth: even with Chromium scripting explicitly disabled, do\n // not instantiate untrusted script, embedded frames or refresh navigation.\n const $ = load(html);\n const strippedScriptCount = $(\"script\").length;\n $(\"script,iframe,frame,frameset,object,embed,portal\").remove();\n $('meta[http-equiv=\"refresh\" i]').remove();\n $(\"*\").each((_, element) => {\n if (!(\"attribs\" in element) || !element.attribs) return;\n for (const name of Object.keys(element.attribs)) {\n if (/^on[a-z]+$/iu.test(name)) $(element).removeAttr(name);\n }\n });\n const inertHtml = $.html();\n let browser: Awaited<ReturnType<ScreenshotBrowserRuntime[\"launch\"]>> | undefined;\n let pendingError: unknown;\n let browserDeadline: ReturnType<typeof setTimeout> | undefined;\n try {\n // The pinned screenshot runtime launches a fresh sandboxed Chromium process.\n // Port 9 is deliberately not serviced: the transport cannot reach page URLs.\n browser = await runtime.launch(DENY_ALL_PROXY);\n // A hard deadline also covers keyboard/evaluation operations, which are\n // not governed by Puppeteer's navigation timeout.\n browserDeadline = setTimeout(() => {\n void browser?.close().catch(() => {});\n }, 20_000);\n browserDeadline.unref?.();\n const page = await browser.newPage();\n page.setDefaultTimeout(5_000);\n page.setDefaultNavigationTimeout(8_000);\n await page.setViewport({ width: config.width, height: config.height, deviceScaleFactor: 1 });\n await page.setJavaScriptEnabled(false);\n let blocked = 0;\n await page.setRequestInterception(true);\n page.on(\"request\", (request) => {\n blocked++;\n void request.abort(\"blockedbyclient\").catch(() => {});\n });\n await page.setContent(inertHtml, { waitUntil: \"domcontentloaded\", timeout: 8_000 });\n\n // All browser-side data is reduced to booleans/counts, never raw HTML/text,\n // attributes, CSS properties, input values, URLs, IDs or names.\n const snapshot = await page.evaluate((selector: string, cap: number) => {\n const dom = (globalThis as any).document;\n const compute = (globalThis as any).getComputedStyle;\n const all: any[] = Array.from(dom.querySelectorAll(selector));\n const controls: WcagControlEvidence[] = [];\n for (let i = 0; i < Math.min(all.length, cap); i++) {\n const element = all[i];\n const styles = compute(element);\n const box = element.getBoundingClientRect();\n const visible = styles.display !== \"none\" &&\n styles.visibility !== \"hidden\" && styles.visibility !== \"collapse\" &&\n box.width > 0 && box.height > 0 && !element.closest(\"[hidden],[inert]\");\n const tag = String(element.tagName).toLowerCase();\n const type = String(element.getAttribute(\"type\") ?? \"\").toLowerCase();\n const role = String(element.getAttribute(\"role\") ?? \"\").toLowerCase();\n const native = [\"button\", \"input\", \"select\", \"textarea\", \"a\", \"summary\"].includes(tag);\n const customRole = [\"button\", \"link\", \"checkbox\", \"switch\", \"tab\", \"menuitem\"].includes(role);\n const nonempty = (value: unknown) => typeof value === \"string\" && value.trim().length > 0;\n const describedBy = String(element.getAttribute(\"aria-labelledby\") ?? \"\")\n .split(/\\s+/u).filter(Boolean).some((id) =>\n nonempty(dom.getElementById(id)?.textContent));\n const ariaLabel = nonempty(element.getAttribute(\"aria-label\"));\n const associatedLabel = Boolean(element.labels &&\n Array.from(element.labels).some((label: any) => nonempty(label.textContent)));\n const labelWrapping = nonempty(element.closest(\"label\")?.textContent);\n const title = nonempty(element.getAttribute(\"title\"));\n const text = [\"a\", \"button\", \"summary\"].includes(tag) && nonempty(element.textContent);\n const alt = [\"a\", \"button\"].includes(tag) &&\n Array.from(element.querySelectorAll(\"img\")).some((image: any) => nonempty(image.getAttribute(\"alt\")));\n const inputAlt = tag === \"input\" && type === \"image\" && nonempty(element.getAttribute(\"alt\"));\n // Submit/reset have user-agent default names; input[type=button]\n // without a value does not have that same fallback.\n const nativeSubmit = tag === \"input\" && ([\"submit\", \"reset\"].includes(type)\n || (type === \"button\" && nonempty(element.value)));\n controls.push({\n index: i + 1,\n visible: Boolean(visible),\n enabled: !element.disabled && !element.closest(\"fieldset[disabled]\"),\n focusable: visible && element.tabIndex >= 0,\n name_present: Boolean(describedBy || ariaLabel || associatedLabel ||\n labelWrapping || title || text || alt || inputAlt || nativeSubmit),\n positive_tabindex: element.tabIndex > 0,\n aria_hidden: Boolean(element.closest('[aria-hidden=\"true\" i]')),\n custom_role_without_tab_stop: Boolean(customRole && !native && element.tabIndex < 0),\n });\n }\n return {\n controls_seen: all.length,\n controls,\n page_scripts_present: dom.querySelectorAll(\"script\").length,\n } as WcagRenderedSnapshot;\n }, CONTROL_SELECTOR, MAX_WCAG_CONTROLS);\n snapshot.page_scripts_present += strippedScriptCount;\n\n const samples: WcagFocusEvidence[] = [];\n const focused = new Set<number>();\n let tabSteps = 0;\n let keyboardIncomplete = false;\n let summaryIndex: number | undefined;\n // Autofocus in supplied markup should not skip the first Tab stop.\n await page.evaluate(() => { (globalThis as any).document.activeElement?.blur?.(); });\n try {\n const maxSteps = Math.min(config.maxTabSteps, Math.max(2, snapshot.controls_seen + 1));\n for (let i = 0; i < maxSteps; i++) {\n await page.keyboard.press(\"Tab\");\n tabSteps++;\n const entry = await page.evaluate((selector: string, cap: number) => {\n const dom = (globalThis as any).document;\n const compute = (globalThis as any).getComputedStyle;\n const current = dom.activeElement;\n if (!current) return null;\n const all: any[] = Array.from(dom.querySelectorAll(selector));\n const index = all.indexOf(current) + 1;\n if (index < 1 || index > cap) return null;\n const style = compute(current);\n const rect = current.getBoundingClientRect();\n const outline = style.outlineStyle !== \"none\" &&\n Number.parseFloat(style.outlineWidth) > 0;\n const shadow = style.boxShadow && style.boxShadow !== \"none\";\n const viewportWidth = (globalThis as any).innerWidth;\n const viewportHeight = (globalThis as any).innerHeight;\n return {\n index,\n outline_or_shadow_present: Boolean(outline || shadow),\n inside_viewport: Boolean(rect.width > 0 && rect.height > 0 &&\n rect.bottom > 0 && rect.right > 0 &&\n rect.left < viewportWidth && rect.top < viewportHeight),\n opacity_zero: Number.parseFloat(style.opacity) === 0,\n summary: String(current.tagName).toLowerCase() === \"summary\",\n } as WcagFocusEvidence;\n }, CONTROL_SELECTOR, MAX_WCAG_CONTROLS);\n if (!entry) {\n // The browser has left the sampled control set or no focus occurred.\n if (snapshot.controls_seen > MAX_WCAG_CONTROLS) keyboardIncomplete = true;\n break;\n }\n if (focused.has(entry.index)) break; // Wraparound is not a trap.\n focused.add(entry.index);\n samples.push(entry);\n if (entry.summary && summaryIndex === undefined) {\n summaryIndex = entry.index;\n }\n }\n } catch {\n keyboardIncomplete = true;\n }\n\n let summariesTested = 0;\n let summariesToggled = 0;\n if (summaryIndex !== undefined) {\n try {\n // Only focus the *same* native summary reached by Tab, not an unrelated\n // earlier summary that might be hidden or nested in an inactive widget.\n const summaryReady = await page.evaluate((selector: string, index: number) => {\n const dom = (globalThis as any).document;\n const s: any = dom.querySelectorAll(selector)[index - 1];\n if (!s || String(s.tagName).toLowerCase() !== \"summary\"\n || String(s.parentElement?.tagName).toLowerCase() !== \"details\") return false;\n (s as any).focus();\n return dom.activeElement === s;\n }, CONTROL_SELECTOR, summaryIndex);\n if (summaryReady) {\n summariesTested = 1;\n const before = await page.evaluate(() =>\n Boolean((globalThis as any).document.activeElement?.closest(\"details\")?.open));\n await page.keyboard.press(\"Enter\");\n const after = await page.evaluate(() =>\n Boolean((globalThis as any).document.activeElement?.closest(\"details\")?.open));\n summariesToggled = before !== after ? 1 : 0;\n }\n } catch {\n keyboardIncomplete = true;\n }\n }\n return analyzeWcagEvidence(snapshot, samples, {\n viewportWidth: config.width, viewportHeight: config.height,\n resourcesBlocked: blocked, tabSteps,\n nativeSummariesTested: summariesTested,\n nativeSummariesToggled: summariesToggled,\n keyboardIncomplete,\n });\n } catch (cause) {\n pendingError = cause;\n throw cause;\n } finally {\n if (browserDeadline) clearTimeout(browserDeadline);\n try {\n if (browser) await browser.close();\n } catch (cause) {\n if (!pendingError) throw cause;\n }\n }\n}\n"]}
@@ -0,0 +1,18 @@
1
+ import { type AvailabilityObservation } from "../http-crawl/availability-observations.js";
2
+ export declare const MAX_AVAILABILITY_HISTORY = 10;
3
+ export declare const MAX_AVAILABILITY_HISTORY_FILE_BYTES = 24000;
4
+ export interface AvailabilitySavedRecord {
5
+ id: string;
6
+ saved_at: string;
7
+ observation: AvailabilityObservation;
8
+ }
9
+ export interface AvailabilityStoreResponse {
10
+ count: number;
11
+ records: AvailabilitySavedRecord[];
12
+ saved_id?: string;
13
+ evicted_id?: string;
14
+ }
15
+ /** Read-only, bounded, exact-URL history lookup. No global list or raw URL output. */
16
+ export declare function getAvailabilityHistory(url: string, root?: string): Promise<AvailabilityStoreResponse>;
17
+ /** Opt-in single HTTP observation save, with atomic write and ten-item eviction. */
18
+ export declare function saveAvailabilityObservation(url: string, observation: AvailabilityObservation, root?: string): Promise<AvailabilityStoreResponse>;
@@ -0,0 +1,168 @@
1
+ /**
2
+ * V02 local opt-in availability history. Separate from site-audit snapshots:
3
+ * stores only ten compact HTTP outcome observations; hosted Worker stays
4
+ * stateless. Uses the same guarded .mcp-validator directory convention.
5
+ */
6
+ import * as fs from "node:fs/promises";
7
+ import * as os from "node:os";
8
+ import * as path from "node:path";
9
+ import { randomUUID } from "node:crypto";
10
+ import { z } from "zod";
11
+ import { AVAILABILITY_FAILURE_CODES, validateAvailabilityObservation, } from "../http-crawl/availability-observations.js";
12
+ import { safeHttpResourceUrl } from "../http-crawl/non-html-directives.js";
13
+ export const MAX_AVAILABILITY_HISTORY = 10;
14
+ export const MAX_AVAILABILITY_HISTORY_FILE_BYTES = 24_000;
15
+ const SUBDIRECTORY = ".mcp-validator";
16
+ const FILENAME = "availability-history.json";
17
+ const observationSchema = z.object({
18
+ observed_at: z.string().max(40),
19
+ status_code: z.number().int().min(100).max(599).optional(),
20
+ failure: z.enum(AVAILABILITY_FAILURE_CODES).optional(),
21
+ cf_challenge: z.boolean().optional(),
22
+ elapsed_ms: z.number().int().min(0).max(120_000).optional(),
23
+ }).strict();
24
+ const storedRecordSchema = z.object({
25
+ id: z.string().uuid(),
26
+ saved_at: z.string().datetime({ offset: true }),
27
+ url: z.string().max(512),
28
+ observation: observationSchema,
29
+ }).strict();
30
+ const persistedSchema = z.object({
31
+ version: z.literal(1),
32
+ items: z.array(storedRecordSchema).max(MAX_AVAILABILITY_HISTORY),
33
+ }).strict();
34
+ function rootDirectory() {
35
+ const configured = process.env.MCP_WEB_VALIDATOR_WORKSPACE_ROOT;
36
+ if (configured === undefined)
37
+ return os.homedir();
38
+ if (!path.isAbsolute(configured))
39
+ throw new Error("Workspace root must be an absolute path.");
40
+ return configured;
41
+ }
42
+ async function historyPath(root, create) {
43
+ const resolvedRoot = await fs.realpath(root);
44
+ const dir = path.join(resolvedRoot, SUBDIRECTORY);
45
+ if (create)
46
+ await fs.mkdir(dir, { recursive: true, mode: 0o700 });
47
+ const entry = await fs.lstat(dir).catch((cause) => {
48
+ if (!create && cause.code === "ENOENT")
49
+ return undefined;
50
+ throw cause;
51
+ });
52
+ if (!entry)
53
+ return path.join(dir, FILENAME);
54
+ if (!entry.isDirectory() || entry.isSymbolicLink()) {
55
+ throw new Error("Availability history directory must be a real directory.");
56
+ }
57
+ const actualDir = await fs.realpath(dir);
58
+ if (path.dirname(actualDir) !== resolvedRoot) {
59
+ throw new Error("Availability history must remain inside its configured workspace root.");
60
+ }
61
+ return path.join(actualDir, FILENAME);
62
+ }
63
+ async function readHistory(root) {
64
+ const file = await historyPath(root, false);
65
+ const info = await fs.lstat(file).catch((cause) => {
66
+ if (cause.code === "ENOENT")
67
+ return undefined;
68
+ throw cause;
69
+ });
70
+ if (!info)
71
+ return [];
72
+ if (!info.isFile() || info.isSymbolicLink() || info.nlink !== 1 ||
73
+ info.size > MAX_AVAILABILITY_HISTORY_FILE_BYTES) {
74
+ throw new Error("Availability history must be a bounded regular file, not a link.");
75
+ }
76
+ let candidate;
77
+ try {
78
+ candidate = JSON.parse(await fs.readFile(file, "utf8"));
79
+ }
80
+ catch {
81
+ throw new Error("Availability history is unreadable; nothing was changed.");
82
+ }
83
+ const parsed = persistedSchema.safeParse(candidate);
84
+ if (!parsed.success) {
85
+ throw new Error("Availability history has invalid fields; nothing was changed.");
86
+ }
87
+ for (const record of parsed.data.items) {
88
+ if (!safeHttpResourceUrl(record.url)) {
89
+ throw new Error("Availability history has an unsafe URL label; nothing was changed.");
90
+ }
91
+ validateAvailabilityObservation(record.observation);
92
+ }
93
+ return parsed.data.items;
94
+ }
95
+ async function writeHistory(root, items) {
96
+ const file = await historyPath(root, true);
97
+ const contents = JSON.stringify({ version: 1, items });
98
+ if (Buffer.byteLength(contents, "utf8") > MAX_AVAILABILITY_HISTORY_FILE_BYTES) {
99
+ throw new Error("Availability history would exceed the 24 KB file limit.");
100
+ }
101
+ const temporary = path.join(path.dirname(file), "." + FILENAME + "." + randomUUID() + ".tmp");
102
+ let handle;
103
+ try {
104
+ handle = await fs.open(temporary, "wx", 0o600);
105
+ await handle.writeFile(contents, "utf8");
106
+ await handle.sync();
107
+ await handle.close();
108
+ handle = undefined;
109
+ await fs.rename(temporary, file);
110
+ }
111
+ finally {
112
+ if (handle)
113
+ await handle.close();
114
+ await fs.rm(temporary, { force: true });
115
+ }
116
+ }
117
+ function response(items, url, savedId, evictedId) {
118
+ const records = items.filter((item) => item.url === url)
119
+ .map(({ id, saved_at, observation }) => ({ id, saved_at, observation }));
120
+ return {
121
+ count: records.length, records,
122
+ ...(savedId ? { saved_id: savedId } : {}),
123
+ ...(evictedId ? { evicted_id: evictedId } : {}),
124
+ };
125
+ }
126
+ let pendingSave = Promise.resolve();
127
+ /** Read-only, bounded, exact-URL history lookup. No global list or raw URL output. */
128
+ export async function getAvailabilityHistory(url, root = rootDirectory()) {
129
+ const safe = safeHttpResourceUrl(url);
130
+ if (!safe)
131
+ throw new Error("History lookup requires a safe query-free URL label.");
132
+ return response(await readHistory(root), safe);
133
+ }
134
+ /** Opt-in single HTTP observation save, with atomic write and ten-item eviction. */
135
+ export function saveAvailabilityObservation(url, observation, root = rootDirectory()) {
136
+ const safe = safeHttpResourceUrl(url);
137
+ if (!safe)
138
+ throw new Error("History save requires a safe query-free URL label.");
139
+ validateAvailabilityObservation(observation);
140
+ const parsedObservation = observationSchema.parse(observation);
141
+ const action = async () => {
142
+ const items = await readHistory(root);
143
+ const sameUrl = items.filter((item) => item.url === safe);
144
+ const last = sameUrl.at(-1);
145
+ if (last && Date.parse(parsedObservation.observed_at) <=
146
+ Date.parse(last.observation.observed_at)) {
147
+ if (Date.parse(parsedObservation.observed_at) === Date.parse(last.observation.observed_at) &&
148
+ JSON.stringify(last.observation) === JSON.stringify(parsedObservation)) {
149
+ return response(items, safe, last.id);
150
+ }
151
+ throw new Error("Saved observations must advance chronologically for each exact URL.");
152
+ }
153
+ const newItem = {
154
+ id: randomUUID(), saved_at: new Date().toISOString(), url: safe,
155
+ observation: parsedObservation,
156
+ };
157
+ const next = [...items, newItem];
158
+ const removed = next.length > MAX_AVAILABILITY_HISTORY ? next.shift() : undefined;
159
+ await writeHistory(root, next);
160
+ // The archive is globally capped; never disclose an ID that belongs to
161
+ // some other exact URL when its oldest record is evicted.
162
+ return response(next, safe, newItem.id, removed?.url === safe ? removed.id : undefined);
163
+ };
164
+ const request = pendingSave.then(action, action);
165
+ pendingSave = request.catch(() => undefined);
166
+ return request;
167
+ }
168
+ //# sourceMappingURL=availability-history-store.js.map