@surea11y/core 1.2.0 → 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.
Files changed (168) hide show
  1. package/CHANGELOG.md +81 -7
  2. package/LICENSE +373 -21
  3. package/README.md +175 -35
  4. package/bin/surea11y-core.js +20 -0
  5. package/docs/API_STABILITY.md +27 -1
  6. package/docs/BINDING_AUTHORS_GUIDE.md +9 -9
  7. package/docs/CI_INTEGRATIONS.md +103 -0
  8. package/docs/ENGINE_OPTIONS.md +2 -0
  9. package/docs/I18N.md +12 -9
  10. package/docs/INTEGRATION.md +19 -1
  11. package/docs/LIMITATIONS.md +1 -1
  12. package/docs/OUTPUT_SCHEMA.md +1 -1
  13. package/docs/REPORT.md +1 -1
  14. package/docs/RULE_CATALOG.md +1 -1
  15. package/docs/SARIF.md +59 -0
  16. package/package.json +63 -18
  17. package/src/baseline.js +0 -0
  18. package/src/checks/automatic/area-alt-present.js +63 -31
  19. package/src/checks/automatic/aria-allowed-attr.js +204 -80
  20. package/src/checks/automatic/aria-allowed-role.js +23 -7
  21. package/src/checks/automatic/aria-braille-equivalent.js +34 -10
  22. package/src/checks/automatic/aria-conditional-attr.js +32 -14
  23. package/src/checks/automatic/aria-deprecated-role.js +26 -11
  24. package/src/checks/automatic/aria-hidden-body.js +48 -23
  25. package/src/checks/automatic/aria-hidden-focus.js +420 -66
  26. package/src/checks/automatic/aria-prohibited-attr.js +327 -60
  27. package/src/checks/automatic/aria-prohibited-children.js +111 -103
  28. package/src/checks/automatic/aria-required-attr.js +29 -15
  29. package/src/checks/automatic/aria-required-children.js +44 -24
  30. package/src/checks/automatic/aria-required-parent.js +64 -35
  31. package/src/checks/automatic/aria-role-name-present.js +49 -21
  32. package/src/checks/automatic/aria-roles-valid.js +24 -12
  33. package/src/checks/automatic/aria-valid-attr-value.js +46 -22
  34. package/src/checks/automatic/aria-valid-attr.js +19 -5
  35. package/src/checks/automatic/autocomplete-valid.js +76 -16
  36. package/src/checks/automatic/avoid-inline-spacing.js +23 -8
  37. package/src/checks/automatic/binary-control-name-present.js +62 -50
  38. package/src/checks/automatic/button-name-present.js +54 -24
  39. package/src/checks/automatic/bypass-blocks-present.js +51 -32
  40. package/src/checks/automatic/canvas-text-alternative-present.js +59 -26
  41. package/src/checks/automatic/combobox-name-present.js +40 -45
  42. package/src/checks/automatic/contrast-computable.js +363 -341
  43. package/src/checks/automatic/contrast-enhanced.js +489 -466
  44. package/src/checks/automatic/contrast-minimum.js +488 -465
  45. package/src/checks/automatic/css-orientation-lock.js +51 -35
  46. package/src/checks/automatic/definition-list-children-valid.js +46 -25
  47. package/src/checks/automatic/deprecated-elements-not-used.js +25 -9
  48. package/src/checks/automatic/dialog-name-present.js +47 -85
  49. package/src/checks/automatic/dlitem-parent-valid.js +25 -8
  50. package/src/checks/automatic/duplicate-id-aria.js +28 -9
  51. package/src/checks/automatic/embed-text-alternative-present.js +88 -35
  52. package/src/checks/automatic/form-control-programmatic-label-present.js +81 -196
  53. package/src/checks/automatic/form-control-single-label.js +50 -14
  54. package/src/checks/automatic/html-xml-lang-mismatch.js +36 -18
  55. package/src/checks/automatic/iframe-focusable-content.js +265 -22
  56. package/src/checks/automatic/iframe-name-present.js +33 -9
  57. package/src/checks/automatic/iframe-title-unique.js +32 -9
  58. package/src/checks/automatic/img-alt-present.js +54 -52
  59. package/src/checks/automatic/input-image-alt-present.js +141 -112
  60. package/src/checks/automatic/label-in-name.js +65 -41
  61. package/src/checks/automatic/language-page-present.js +111 -109
  62. package/src/checks/automatic/link-in-text-block.js +61 -19
  63. package/src/checks/automatic/link-name-present.js +47 -14
  64. package/src/checks/automatic/list-children-valid.js +40 -33
  65. package/src/checks/automatic/listbox-name-present.js +41 -19
  66. package/src/checks/automatic/listitem-parent-valid.js +48 -13
  67. package/src/checks/automatic/menuitem-name-present.js +41 -61
  68. package/src/checks/automatic/meta-refresh-no-exceptions.js +32 -11
  69. package/src/checks/automatic/meta-refresh-timing-absent.js +22 -6
  70. package/src/checks/automatic/meta-viewport-zoom-enabled.js +26 -7
  71. package/src/checks/automatic/meter-name-present.js +40 -36
  72. package/src/checks/automatic/nested-interactive-controls-absent.js +58 -15
  73. package/src/checks/automatic/object-text-alternative-present.js +93 -39
  74. package/src/checks/automatic/option-name-present.js +40 -21
  75. package/src/checks/automatic/page-title-present.js +19 -6
  76. package/src/checks/automatic/progressbar-name-present.js +49 -44
  77. package/src/checks/automatic/role-img-alt-present.js +211 -159
  78. package/src/checks/automatic/searchbox-name-present.js +41 -19
  79. package/src/checks/automatic/server-side-image-map-absent.js +27 -11
  80. package/src/checks/automatic/slider-name-present.js +42 -47
  81. package/src/checks/automatic/spinbutton-name-present.js +41 -19
  82. package/src/checks/automatic/summary-name-present.js +39 -17
  83. package/src/checks/automatic/svg-image-text-alternative-present.js +116 -47
  84. package/src/checks/automatic/svg-text-alternative-present.js +262 -230
  85. package/src/checks/automatic/tab-name-present.js +39 -60
  86. package/src/checks/automatic/table-headers-attr-valid.js +27 -10
  87. package/src/checks/automatic/table-th-has-data-cells.js +24 -8
  88. package/src/checks/automatic/target-size-minimum.js +123 -48
  89. package/src/checks/automatic/td-has-header.js +53 -12
  90. package/src/checks/automatic/textbox-name-present.js +41 -19
  91. package/src/checks/automatic/tooltip-name-present.js +39 -18
  92. package/src/checks/automatic/treeitem-name-present.js +40 -21
  93. package/src/checks/automatic/valid-lang.js +22 -6
  94. package/src/checks/automatic/video-poster-text-alternative-present.js +81 -36
  95. package/src/checks/manual/accesskeys-manual.js +17 -6
  96. package/src/checks/manual/area-alt-decorative-manual.js +194 -193
  97. package/src/checks/manual/area-alt-quality-manual.js +184 -141
  98. package/src/checks/manual/aria-checked-state-mismatch-manual.js +48 -34
  99. package/src/checks/manual/aria-text-manual.js +20 -11
  100. package/src/checks/manual/canvas-text-alternative-quality-manual.js +151 -114
  101. package/src/checks/manual/css-hidden-focus.js +375 -169
  102. package/src/checks/manual/embed-text-alternative-quality-manual.js +178 -162
  103. package/src/checks/manual/empty-heading-manual.js +41 -24
  104. package/src/checks/manual/empty-table-header-manual.js +69 -31
  105. package/src/checks/manual/focus-order-semantics-manual.js +60 -13
  106. package/src/checks/manual/form-control-programmatic-label-quality-manual.js +209 -246
  107. package/src/checks/manual/heading-order-manual.js +50 -8
  108. package/src/checks/manual/identical-links-same-purpose-manual.js +36 -12
  109. package/src/checks/manual/image-redundant-alt-manual.js +38 -8
  110. package/src/checks/manual/img-alt-decorative-manual.js +133 -96
  111. package/src/checks/manual/img-alt-quality-manual.js +178 -127
  112. package/src/checks/manual/input-image-alt-decorative-manual.js +127 -92
  113. package/src/checks/manual/input-image-alt-quality-manual.js +127 -92
  114. package/src/checks/manual/label-title-only-manual.js +44 -28
  115. package/src/checks/manual/landmark-banner-is-top-level-manual.js +95 -38
  116. package/src/checks/manual/landmark-contentinfo-is-top-level-manual.js +85 -32
  117. package/src/checks/manual/landmark-main-is-top-level-manual.js +69 -27
  118. package/src/checks/manual/landmark-no-duplicate-banner-manual.js +45 -33
  119. package/src/checks/manual/landmark-no-duplicate-contentinfo-manual.js +43 -31
  120. package/src/checks/manual/landmark-no-duplicate-main-manual.js +27 -21
  121. package/src/checks/manual/landmark-one-main-manual.js +38 -43
  122. package/src/checks/manual/landmark-unique-manual.js +78 -67
  123. package/src/checks/manual/link-name-quality-manual.js +45 -12
  124. package/src/checks/manual/media-transcript-present-manual.js +37 -22
  125. package/src/checks/manual/meta-viewport-large-manual.js +19 -6
  126. package/src/checks/manual/mouse-only-event-handlers-manual.js +40 -11
  127. package/src/checks/manual/no-autoplay-audio-manual.js +22 -6
  128. package/src/checks/manual/object-text-alternative-quality-manual.js +177 -154
  129. package/src/checks/manual/p-as-heading-manual.js +24 -7
  130. package/src/checks/manual/page-has-heading-one-manual.js +42 -32
  131. package/src/checks/manual/page-title-patterns-manual.js +80 -50
  132. package/src/checks/manual/presentation-role-conflict-manual.js +101 -47
  133. package/src/checks/manual/region-manual.js +244 -60
  134. package/src/checks/manual/scope-attr-valid-manual.js +13 -4
  135. package/src/checks/manual/scrollable-region-focusable-manual.js +39 -11
  136. package/src/checks/manual/skip-link-manual.js +42 -18
  137. package/src/checks/manual/svg-text-alternative-quality-manual.js +208 -165
  138. package/src/checks/manual/tabindex-manual.js +13 -4
  139. package/src/checks/manual/table-duplicate-name-manual.js +22 -11
  140. package/src/checks/manual/table-fake-caption-manual.js +48 -10
  141. package/src/checks/manual/video-caption-manual.js +17 -4
  142. package/src/checks/manual-review.js +58 -12
  143. package/src/core.js +41705 -29650
  144. package/src/index.js +2 -0
  145. package/src/report.js +109 -47
  146. package/src/sarif.js +190 -0
  147. package/surea11y.browser.js +37774 -0
  148. package/bin/core.js +0 -348
  149. package/docs/CLI.md +0 -75
  150. package/src/catalogs/composites.wcag.js +0 -490
  151. package/src/checks/rules-and-tags.full.csv +0 -19
  152. package/src/checks/rules-and-tags.full.json +0 -259
  153. package/src/core/aria-helpers.js +0 -970
  154. package/src/core/contrast-helpers.js +0 -1147
  155. package/src/core/dom-helpers.js +0 -4235
  156. package/src/core/dom-runner.js +0 -671
  157. package/src/core/frame-messaging.js +0 -210
  158. package/src/core/frame-scan.js +0 -178
  159. package/src/core/rollup-composites.js +0 -135
  160. package/src/core/rule-meta.js +0 -159
  161. package/src/coverage/wcag-facets.js +0 -1079
  162. package/src/coverage/wcag-version-map.js +0 -84
  163. package/src/i18n/en.js +0 -923
  164. package/src/i18n/fr.js +0 -844
  165. package/src/policy/contracts.js +0 -18
  166. package/src/policy/resolvePolicy.js +0 -55
  167. package/src/policy/schemas/engine-options.schema.json +0 -103
  168. package/src/policy/schemas/policy-contract.schema.json +0 -40
@@ -1,671 +0,0 @@
1
- 'use strict';
2
-
3
- /**
4
- * DOM runner implementation.
5
- *
6
- * IMPORTANT:
7
- * - This function is inlined into generated core.js (Node + in-page runner).
8
- * - It intentionally references shared runtime helpers that core.js defines:
9
- * resolvePolicy, POLICY_CONTRACTS, resolveRuleDefI18n, ruleMatchesRunOnly,
10
- * normalizeRuleResult, normalizeLocale, createDomHelpers, normalizeSelectorList,
11
- * resolveContextRoots (src/core/dom-helpers.js -- also used by frame-scan.js),
12
- * normalizeRuleMeta (src/core/rule-meta.js -- used for engineOptions.customRules).
13
- */
14
-
15
- function runCore(pageUrl, contextSelector, engineOptions, runOnly, CHECK_DEFS, RULE_IMPLS, ENGINE_TAG, SCHEMA_VERSION, COMPOSITE_RULES) {
16
- // Normalize contrast options without mutating caller-provided engineOptions.
17
- function __normalizeContrastOptions(engineOptions2) {
18
- const eo = engineOptions2 && typeof engineOptions2 === 'object' ? engineOptions2 : {};
19
- const c = (eo.contrast && typeof eo.contrast === 'object') ? eo.contrast : {};
20
- const mode = (c.mode === 'auditorAssist') ? 'auditorAssist' : 'strictConformance';
21
- const rootCanvasFallback =
22
- (typeof c.rootCanvasFallback === 'string' && c.rootCanvasFallback.trim())
23
- ? c.rootCanvasFallback.trim()
24
- : '#ffffff';
25
- return { mode, rootCanvasFallback };
26
- }
27
-
28
- const engineOptionsResolved =
29
- (engineOptions && typeof engineOptions === 'object')
30
- ? { ...engineOptions, contrast: __normalizeContrastOptions(engineOptions) }
31
- : { contrast: __normalizeContrastOptions(null) };
32
-
33
- const policy = resolvePolicy(POLICY_CONTRACTS, engineOptionsResolved);
34
-
35
- // contextSelector accepts a single selector string (which may itself be a
36
- // comma-separated selector list -- ordinary CSS union semantics) OR an
37
- // array of selector strings for scanning multiple, possibly disjoint
38
- // regions in one run (a widely-used reference engine's multi-.include()
39
- // capability has no equivalent here otherwise). Both forms resolve via querySelectorAll,
40
- // not querySelector -- previously a single string only ever scanned its
41
- // FIRST match, silently ignoring the rest if it happened to match more
42
- // than one element. That was a real gap, not a deliberate "one region
43
- // only" design: switched to querySelectorAll for both forms so
44
- // "matches this selector" actually means all matches, consistently.
45
- // Shared with frame-scan.js (same resolution used to discover which
46
- // child <iframe>/<frame> elements fall within the same scan scope).
47
- const { ctxSelector, roots } = resolveContextRoots(document, contextSelector);
48
-
49
- // Default on: opt OUT with `includeShadowDom: false`, not opt in.
50
- const includeShadowDom = !(engineOptionsResolved && engineOptionsResolved.includeShadowDom === false);
51
- // Default off: hidden/collapsed content is excluded from rule evaluation
52
- // unless the caller explicitly opts in.
53
- const includeHiddenElements = !!(engineOptionsResolved && engineOptionsResolved.includeHiddenElements === true);
54
- const excludeSelectors = normalizeSelectorList(engineOptionsResolved && engineOptionsResolved.excludeSelectors);
55
- // Default off: explicit opt-in for "this scan target was never meant to
56
- // represent a real page" -- see helpers.isWholeDocumentScope().
57
- const fragment = !!(engineOptionsResolved && engineOptionsResolved.fragment === true);
58
-
59
- const url = pageUrl || (document.location && document.location.href) || null;
60
- const title = document.title || null;
61
- // Deterministic timestamp: only use host-provided value (no time-based logic).
62
- const timestamp =
63
- (engineOptionsResolved && typeof engineOptionsResolved.timestamp === 'string' && engineOptionsResolved.timestamp.trim())
64
- ? engineOptionsResolved.timestamp.trim()
65
- : null;
66
-
67
- // createDomHelpers()/createContrastHelpers() persist their element-keyed
68
- // caches (outerHtmlCache, selectorCache, etc.) on window.__a11ycoreSharedCache
69
- // so multiple helper instances created *within this run* can share them
70
- // deterministically. But a window/document is frequently reused across
71
- // SEPARATE runs -- e.g. Jest's jsdom environment creates one window per
72
- // test file, and mutating document.body between it() blocks is standard.
73
- // Those caches are keyed by element reference, not content, so a run that
74
- // reuses an already-cached element (document.body never changes identity)
75
- // would otherwise read stale data cached by an earlier, unrelated run on
76
- // the same window. Clearing at the start of every run keeps sharing scoped
77
- // to "this run" as intended, without leaking across runs.
78
- try {
79
- if (window && window.__a11ycoreSharedCache) window.__a11ycoreSharedCache = {};
80
- } catch {}
81
-
82
- const sharedHelpers = createDomHelpers({
83
- document,
84
- window,
85
- root: roots,
86
- includeShadowDom,
87
- includeHiddenElements,
88
- excludeSelectors,
89
- fragment,
90
- // Optional perf counters (bench/debug only). Deterministic and per-run.
91
- perfStats: !!(engineOptionsResolved && engineOptionsResolved.perfStats)
92
- });
93
-
94
- const profileRules = !!(engineOptionsResolved && engineOptionsResolved.profileRules);
95
- const ruleTimings = profileRules ? Object.create(null) : null;
96
-
97
- function nowMs() {
98
- // performance.now() if available, else Date.now()
99
- try {
100
- if (typeof performance !== 'undefined' && performance && typeof performance.now === 'function') {
101
- return performance.now();
102
- }
103
- } catch (e) {}
104
- return Date.now();
105
- }
106
-
107
- // =========================
108
- // Probes (optional evidence fed by the host app)
109
- // Keep deterministic + serializable + no-throws.
110
- // =========================
111
- function sanitizeProbeValue(v, depth) {
112
- // depth-bounded, JSON-safe sanitizer
113
- if (depth <= 0) return null;
114
- if (v == null) return null;
115
-
116
- const t = typeof v;
117
- if (t === 'string') return v.length > 2000 ? v.slice(0, 2000) : v;
118
- if (t === 'number') return Number.isFinite(v) ? v : null;
119
- if (t === 'boolean') return v;
120
- if (t === 'function') return null;
121
-
122
- if (Array.isArray(v)) {
123
- // cap arrays to avoid huge payloads
124
- const out = [];
125
- const n = Math.min(v.length, 200);
126
- for (let i = 0; i < n; i++) out.push(sanitizeProbeValue(v[i], depth - 1));
127
- return out;
128
- }
129
-
130
- if (t === 'object') {
131
- const out = {};
132
- const keys = Object.keys(v).sort();
133
- // cap object keys
134
- const n = Math.min(keys.length, 50);
135
- for (let i = 0; i < n; i++) {
136
- const k = keys[i];
137
- // only allow string keys
138
- if (typeof k !== 'string') continue;
139
- out[k] = sanitizeProbeValue(v[k], depth - 1);
140
- }
141
- return out;
142
- }
143
-
144
- return null;
145
- }
146
-
147
- let probes = null;
148
- try {
149
- const rawProbes = engineOptionsResolved && typeof engineOptionsResolved.probes === 'object' ? engineOptionsResolved.probes : null;
150
- probes = rawProbes ? sanitizeProbeValue(rawProbes, 6) : null;
151
- if (!probes || typeof probes !== 'object' || Array.isArray(probes)) probes = null;
152
- } catch (e) {
153
- probes = null;
154
- }
155
-
156
- // =========================
157
- // Runtime custom rules (engineOptions.customRules)
158
- // =========================
159
- // Same module shape as an internal rule file: { id, meta, runInPage, applicability?, data? }.
160
- // runInPage/applicability may be a real function (fine for same-realm/Node/jsdom callers)
161
- // or a function-source string (required for cross-realm callers, e.g. a Playwright
162
- // page.evaluate(runa11yCoreInPage, { engineOptions }) call -- engineOptions crosses a
163
- // structured-clone/JSON boundary there, so a live Function reference can't survive it,
164
- // but a string can). Reconstructed via `new Function`, matching exactly how build-core.js
165
- // already embeds each built-in rule's own runInPage source into the in-page runner.
166
- // Scan-scoped only (not added to the static CHECK_DEFS/getRulesCatalog() catalog) --
167
- // matches surea11y's existing "fresh engineOptions per call, no mutable global config"
168
- // design (see ROADMAP.md), rather than a widely-used reference engine's stateful global configure().
169
- let effectiveCheckDefs = CHECK_DEFS;
170
- let effectiveRuleImpls = RULE_IMPLS;
171
- let overriddenBuiltinIds = [];
172
- const rawCustomRules = Array.isArray(engineOptionsResolved.customRules) ? engineOptionsResolved.customRules : [];
173
- if (rawCustomRules.length) {
174
- function reviveRuleFn(value) {
175
- if (typeof value === 'function') return value;
176
- if (typeof value === 'string' && value.trim()) {
177
- try {
178
- const fn = new Function('return (' + value + ')')();
179
- if (typeof fn === 'function') return fn;
180
- } catch (e) {
181
- return null;
182
- }
183
- }
184
- return null;
185
- }
186
-
187
- const extraDefsById = new Map();
188
- const extraImpls = {};
189
- for (const c of rawCustomRules) {
190
- if (!c || typeof c !== 'object') continue;
191
- const ruleId = typeof c.id === 'string' ? c.id.trim() : '';
192
- if (!ruleId) continue;
193
- const runFn = reviveRuleFn(c.runInPage);
194
- if (typeof runFn !== 'function') continue; // invalid custom rule: skipped, not a crash
195
-
196
- const applicabilityFn = reviveRuleFn(c.applicability);
197
- const normalizedMeta = normalizeRuleMeta(ruleId, ruleId, c.meta, ENGINE_TAG);
198
-
199
- // Overriding a built-in rule id is supported (see docs/ENGINE_OPTIONS.md),
200
- // but a same-named custom rule is just as likely to be an accidental
201
- // collision (a generic name like "region" or "tabindex" picked without
202
- // realizing it's already a built-in id) as a deliberate override -- so
203
- // surface it either way rather than silently swapping the rule out.
204
- if (CHECK_DEFS.some((d) => d && d.ruleId === ruleId)) {
205
- overriddenBuiltinIds.push(ruleId);
206
- }
207
-
208
- extraDefsById.set(ruleId, {
209
- ruleId,
210
- title: normalizedMeta.title,
211
- description: normalizedMeta.description,
212
- i18n: normalizedMeta.i18n,
213
- helpUrl: normalizedMeta.helpUrl,
214
- tags: normalizedMeta.tags,
215
- wcagSc: normalizedMeta.wcagSc,
216
- normativeMappings: normalizedMeta.normativeMappings,
217
- defaultSeverity: normalizedMeta.defaultSeverity,
218
- defaultConfidence: normalizedMeta.defaultConfidence,
219
- type: normalizedMeta.type,
220
- coverage: normalizedMeta.coverage,
221
- data: (c.data === undefined ? null : c.data),
222
- ruleInterfaceVersion: normalizedMeta.ruleInterfaceVersion,
223
- ruleVersion: normalizedMeta.ruleVersion,
224
- normative: normalizedMeta.normative,
225
- atomic: normalizedMeta.atomic,
226
- deprecated: normalizedMeta.deprecated,
227
- deprecation: normalizedMeta.deprecation,
228
- category: normalizedMeta.category,
229
- standard: normalizedMeta.standard,
230
- applicability: normalizedMeta.applicability,
231
- expectation: normalizedMeta.expectation,
232
- references: normalizedMeta.references,
233
- requirements: normalizedMeta.requirements,
234
- mappings: normalizedMeta.mappings
235
- });
236
- extraImpls[ruleId] = { run: runFn, applicability: applicabilityFn || null };
237
- }
238
-
239
- if (extraDefsById.size) {
240
- effectiveCheckDefs = CHECK_DEFS
241
- .filter((d) => !extraDefsById.has(d.ruleId))
242
- .concat(Array.from(extraDefsById.values()));
243
- effectiveRuleImpls = { ...RULE_IMPLS, ...extraImpls };
244
- }
245
-
246
- if (overriddenBuiltinIds.length) {
247
- try {
248
- console.warn('[surea11y] customRules overriding built-in rule id(s) for this scan: ' + overriddenBuiltinIds.join(', '));
249
- } catch (e) {}
250
- }
251
- }
252
-
253
- const checksResults = [];
254
-
255
- for (const def of effectiveCheckDefs) {
256
- const t0 = ruleTimings ? nowMs() : 0;
257
- const defResolved = resolveRuleDefI18n(def, engineOptionsResolved);
258
- if (!ruleMatchesRunOnly(defResolved, runOnly, ENGINE_TAG)) continue;
259
-
260
- const implEntry = effectiveRuleImpls[defResolved.ruleId];
261
- const impl = implEntry && typeof implEntry.run === 'function' ? implEntry.run : null;
262
- const applicabilityFn = implEntry && typeof implEntry.applicability === 'function' ? implEntry.applicability : null;
263
- if (typeof impl !== 'function') continue;
264
-
265
- const ruleConfig =
266
- engineOptionsResolved && engineOptionsResolved.rules && engineOptionsResolved.rules[defResolved.ruleId]
267
- ? engineOptionsResolved.rules[defResolved.ruleId]
268
- : null;
269
-
270
- // Rule-scoped excludeSelectors (engineOptions.rules[ruleId].excludeSelectors)
271
- // apply on top of the global excludeSelectors for exactly this rule's
272
- // applicability check + run, then are cleared once this rule is done.
273
- // Safe because rule execution below is synchronous and one rule at a
274
- // time -- sharedHelpers is reused across all rules in this loop.
275
- if (typeof sharedHelpers.__setActiveRuleExcludeSelectors === 'function') {
276
- sharedHelpers.__setActiveRuleExcludeSelectors(ruleConfig && ruleConfig.excludeSelectors);
277
- }
278
-
279
- const ctx = {
280
- document,
281
- window,
282
- root: roots,
283
- rule: defResolved,
284
- config: ruleConfig,
285
- helpers: sharedHelpers,
286
- engineTag: ENGINE_TAG,
287
- contextSelector: ctxSelector,
288
- engineOptions: (engineOptionsResolved && typeof engineOptionsResolved === 'object') ? engineOptionsResolved : {},
289
-
290
- // Optional evidence channel provided by host app
291
- inputs: {
292
- probes
293
- }
294
- };
295
-
296
- if (typeof applicabilityFn === 'function') {
297
- let applicable = true;
298
- try {
299
- const res = applicabilityFn(ctx);
300
- if (typeof res === 'boolean') applicable = res;
301
- else if (res && typeof res === 'object' && typeof res.applicable === 'boolean') applicable = res.applicable;
302
- } catch (err) {
303
- const raw = {
304
- outcome: 'cantTell',
305
- occurrences: [],
306
- error: String(err && err.message ? err.message : err),
307
- engineOptions: { ...(ctx.engineOptions || {}), locale: normalizeLocale(engineOptionsResolved && engineOptionsResolved.locale) }
308
- };
309
- checksResults.push(normalizeRuleResult(defResolved, raw, SCHEMA_VERSION, policy, sharedHelpers));
310
- if (ruleTimings) ruleTimings[defResolved.ruleId] = (ruleTimings[defResolved.ruleId] || 0) + (nowMs() - t0);
311
- continue;
312
- }
313
-
314
- if (!applicable) {
315
- const raw = {
316
- outcome: 'notApplicable',
317
- occurrences: [],
318
- engineOptions: { ...(ctx.engineOptions || {}), locale: normalizeLocale(engineOptionsResolved && engineOptionsResolved.locale) }
319
- };
320
- checksResults.push(normalizeRuleResult(defResolved, raw, SCHEMA_VERSION, policy, sharedHelpers));
321
- if (ruleTimings) ruleTimings[defResolved.ruleId] = (ruleTimings[defResolved.ruleId] || 0) + (nowMs() - t0);
322
- continue;
323
- }
324
- }
325
-
326
- let result;
327
- try {
328
- result = impl(ctx);
329
- } catch (err) {
330
- result = {
331
- outcome: 'cantTell',
332
- occurrences: [],
333
- error: String(err && err.message ? err.message : err),
334
- engineOptions: { ...(ctx.engineOptions || {}), locale: normalizeLocale(engineOptionsResolved && engineOptionsResolved.locale) }
335
- };
336
- }
337
-
338
- if (!result || typeof result !== 'object') {
339
- if (ruleTimings) ruleTimings[defResolved.ruleId] = (ruleTimings[defResolved.ruleId] || 0) + (nowMs() - t0);
340
- continue;
341
- }
342
- if (!result.engineOptions) {
343
- result.engineOptions = { ...(ctx.engineOptions || {}), locale: normalizeLocale(engineOptionsResolved && engineOptionsResolved.locale) };
344
- }
345
- checksResults.push(normalizeRuleResult(defResolved, result, SCHEMA_VERSION, policy, sharedHelpers));
346
- if (ruleTimings) ruleTimings[defResolved.ruleId] = (ruleTimings[defResolved.ruleId] || 0) + (nowMs() - t0);
347
- }
348
-
349
- // Composite rollups below carry no occurrences/nodes of their own, so
350
- // they never exercise rule-scoped excludes -- but clear the "active
351
- // rule" state on sharedHelpers regardless, so nothing after this point
352
- // (composite aggregation, perf stats) can observe a stale rule's excludes.
353
- if (typeof sharedHelpers.__setActiveRuleExcludeSelectors === 'function') {
354
- sharedHelpers.__setActiveRuleExcludeSelectors(null);
355
- }
356
-
357
- // =========================
358
- // Composite rule aggregation (data-only rollups)
359
- // =========================
360
- const rulesResults = [];
361
- try {
362
- const composites = Array.isArray(COMPOSITE_RULES) ? COMPOSITE_RULES : [];
363
-
364
- // Determine target conformance level from runOnly.tags (already normalized by caller)
365
- const LEVEL_RANK = { A: 1, AA: 2, AAA: 3 };
366
-
367
- function inferTargetLevelFromRunOnly(runOnly2) {
368
- const tags = runOnly2 && Array.isArray(runOnly2.tags) ? runOnly2.tags : [];
369
- // tags are already lowercase
370
- if (tags.includes('wcag2aaa') || tags.includes('wcag22aaa') || tags.includes('wcag21aaa')) return 'AAA';
371
- if (tags.includes('wcag2aa') || tags.includes('wcag22aa') || tags.includes('wcag21aa')) return 'AA';
372
- if (tags.includes('wcag2a') || tags.includes('wcag22a') || tags.includes('wcag21a')) return 'A';
373
- return null; // if not specified, don't filter composites (back-compat)
374
- }
375
-
376
- function normalizeLevel(s) {
377
- const v = typeof s === 'string' ? s.trim().toUpperCase() : '';
378
- return (v === 'A' || v === 'AA' || v === 'AAA') ? v : null;
379
- }
380
-
381
- function isAllowedByTargetLevel(compositeLevel, targetLevel) {
382
- if (!targetLevel) return true;
383
- const c = LEVEL_RANK[compositeLevel];
384
- const t = LEVEL_RANK[targetLevel];
385
- if (!c || !t) return false; // unknown level => safest: exclude
386
- return c <= t;
387
- }
388
-
389
- const targetLevel = inferTargetLevelFromRunOnly(runOnly);
390
-
391
- // Severity rollup (deterministic)
392
- const SEVERITY_RANK = { minor: 1, moderate: 2, serious: 3, critical: 4 };
393
-
394
- function normalizeSeverity(s) {
395
- const v = typeof s === 'string' ? s.trim().toLowerCase() : '';
396
- return SEVERITY_RANK[v] ? v : null;
397
- }
398
-
399
- function maxSeverity(a, b) {
400
- if (!a) return b || null;
401
- if (!b) return a || null;
402
- return (SEVERITY_RANK[b] > SEVERITY_RANK[a]) ? b : a;
403
- }
404
-
405
- // Index atomic results by ruleId (deterministic)
406
- const byRuleId = Object.create(null);
407
- for (const rr of checksResults) {
408
- if (rr && typeof rr === 'object' && typeof rr.ruleId === 'string' && rr.ruleId) {
409
- byRuleId[rr.ruleId] = rr;
410
- }
411
- }
412
-
413
- function isNonEmptyString(s) {
414
- return typeof s === 'string' && !!s.trim();
415
- }
416
-
417
- function buildCompositeDef(entry) {
418
- if (!entry || typeof entry !== 'object') return null;
419
-
420
- const ruleId = isNonEmptyString(entry.id) ? entry.id.trim() : String(entry.id || '').trim();
421
- if (!ruleId) return null;
422
-
423
- const metaIn = (entry.meta && typeof entry.meta === 'object' && !Array.isArray(entry.meta)) ? entry.meta : {};
424
-
425
- const titleKey = (typeof metaIn.titleKey === 'string' && metaIn.titleKey.trim()) ? metaIn.titleKey.trim() : '';
426
- const descriptionKey = (typeof metaIn.descriptionKey === 'string' && metaIn.descriptionKey.trim()) ? metaIn.descriptionKey.trim() : '';
427
-
428
- const wcagSc = Array.isArray(metaIn.wcagSc) ? metaIn.wcagSc.map(String).map(s => s.trim()).filter(Boolean) : [];
429
-
430
- const tags = [];
431
- tags.push(String(ENGINE_TAG || 'a11ycore').toLowerCase());
432
- tags.push('composite');
433
-
434
- // Fixed WCAG-version-introduction lists (2.1 and 2.2 additions only -- every other
435
- // SC, including all pre-2.1 ones, is WCAG 2.0 baseline). Keep in sync with
436
- // src/coverage/wcag-version-map.js (the canonical copy the rule-authoring
437
- // consistency test checks against) -- this one has to stay a self-contained
438
- // literal since runCore is inlined via .toString() with no module access at runtime.
439
- const WCAG21_NEW_SCS = ['1.3.4', '1.3.5', '1.3.6', '1.4.10', '1.4.11', '1.4.12', '1.4.13', '2.1.4', '2.2.6', '2.3.3', '2.5.1', '2.5.2', '2.5.3', '2.5.4', '2.5.5', '2.5.6', '4.1.3'];
440
- const WCAG22_NEW_SCS = ['2.4.11', '2.4.12', '2.4.13', '2.5.7', '2.5.8', '3.2.6', '3.3.7', '3.3.8', '3.3.9'];
441
- const isWcag22Sc = wcagSc.some((sc) => WCAG22_NEW_SCS.includes(sc));
442
- const isWcag21Sc = !isWcag22Sc && wcagSc.some((sc) => WCAG21_NEW_SCS.includes(sc));
443
- const versionTagPrefix = isWcag22Sc ? 'wcag22' : (isWcag21Sc ? 'wcag21' : 'wcag2');
444
-
445
- const lvl = (typeof metaIn.level === 'string' ? metaIn.level.trim().toUpperCase() : '');
446
- if (lvl === 'A') {
447
- tags.push(versionTagPrefix + 'a');
448
- } else if (lvl === 'AA') {
449
- tags.push(versionTagPrefix + 'a', versionTagPrefix + 'aa');
450
- } else if (lvl === 'AAA') {
451
- tags.push(versionTagPrefix + 'a', versionTagPrefix + 'aa', versionTagPrefix + 'aaa');
452
- }
453
-
454
- // Build normativeMappings so downstream consumers (like adapters) can derive WCAG SC/level
455
- const normativeMappingsFromMeta = wcagSc.map((sc) => {
456
- const m = { standard: 'WCAG', requirement: sc };
457
- if (lvl === 'A' || lvl === 'AA' || lvl === 'AAA') m.level = lvl;
458
- return m;
459
- });
460
-
461
- const checksIds =
462
- Array.isArray(entry.checksIds)
463
- ? entry.checksIds.map(String).map(s => s.trim()).filter(Boolean)
464
- : [];
465
-
466
- return {
467
- ruleId,
468
- title: metaIn.title || ruleId,
469
- description: metaIn.description || '',
470
-
471
- i18n: (titleKey || descriptionKey) ? { titleKey: titleKey || '', descriptionKey: descriptionKey || '' } : null,
472
-
473
- helpUrl: '',
474
- tags,
475
-
476
- normativeMappings: normativeMappingsFromMeta,
477
-
478
- defaultSeverity: 'serious',
479
- defaultConfidence: 'medium',
480
- type: 'automatic',
481
- coverage: null,
482
-
483
- ruleInterfaceVersion: '1.0.0',
484
- ruleVersion: '0.0.0',
485
- normative: true,
486
- atomic: false,
487
- deprecated: false,
488
- deprecation: null,
489
- category: null,
490
- standard: null,
491
- applicability: '',
492
- expectation: '',
493
- references: [],
494
- requirements: null,
495
- mappings: null,
496
-
497
- // optional catalog meta passthrough
498
- data: {
499
- details: {
500
- kind: 'compositeRule',
501
- wcagSc,
502
- level: (typeof metaIn.level === 'string' && metaIn.level.trim()) ? metaIn.level.trim() : null
503
- }
504
- },
505
-
506
- __checksIds: checksIds
507
- };
508
- }
509
-
510
- for (let i = 0; i < composites.length; i++) {
511
- const entry = composites[i];
512
- const cDef0 = buildCompositeDef(entry);
513
- if (!cDef0) continue;
514
-
515
- // Conformance-level gate: if scan is AA, suppress AAA composites even if tags match
516
- const compositeLevel =
517
- cDef0 &&
518
- cDef0.data &&
519
- cDef0.data.details &&
520
- normalizeLevel(cDef0.data.details.level);
521
-
522
- if (!isAllowedByTargetLevel(compositeLevel, targetLevel)) continue;
523
-
524
- // Localize title/description (uses def.i18n.* keys)
525
- const cDefResolved = resolveRuleDefI18n(cDef0, engineOptionsResolved);
526
-
527
- // Apply same selection logic to composites
528
- if (!ruleMatchesRunOnly(cDefResolved, runOnly, ENGINE_TAG)) continue;
529
-
530
- const checksIds = Array.isArray(cDef0.__checksIds) ? cDef0.__checksIds : [];
531
-
532
- // rollup metrics (stable order)
533
- let failCount = 0;
534
- let cantTellCount = 0;
535
- let notApplicableCount = 0;
536
- let passCount = 0;
537
- let missingCount = 0;
538
-
539
- const contributors = [];
540
-
541
- let rolledFailSeverity = null; // max severity among FAIL contributors
542
- let rolledCantTellSeverity = null; // max severity among CANTTELL contributors (optional)
543
-
544
- for (let j = 0; j < checksIds.length; j++) {
545
- const tid = checksIds[j];
546
- const child = tid ? byRuleId[tid] : null;
547
-
548
- if (!child) {
549
- missingCount += 1;
550
- contributors.push({ testId: tid, outcome: 'missing' });
551
- continue;
552
- }
553
-
554
- const out = child.outcome;
555
- const childSev = normalizeSeverity(child && child.severity);
556
-
557
- contributors.push({ testId: tid, outcome: out, severity: childSev || null });
558
-
559
- if (out === 'fail' && childSev) {
560
- rolledFailSeverity = maxSeverity(rolledFailSeverity, childSev);
561
- } else if (out === 'cantTell' && childSev) {
562
- rolledCantTellSeverity = maxSeverity(rolledCantTellSeverity, childSev);
563
- }
564
-
565
- if (out === 'fail') failCount += 1;
566
- else if (out === 'cantTell') cantTellCount += 1;
567
- else if (out === 'notApplicable') notApplicableCount += 1;
568
- else if (out === 'pass') passCount += 1;
569
- }
570
-
571
- // outcome precedence:
572
- // fail if any fail
573
- // cantTell if any cantTell OR missing and none fail
574
- // notApplicable if all notApplicable (and there is at least one test)
575
- // pass otherwise
576
- let outcome = 'pass';
577
- let reasonCode = 'composite.rollup.pass.otherwise';
578
-
579
- if (failCount > 0) {
580
- outcome = 'fail';
581
- reasonCode = 'composite.rollup.fail.anyFail';
582
- } else if (cantTellCount > 0) {
583
- outcome = 'cantTell';
584
- reasonCode = 'composite.rollup.cantTell.anyCantTell';
585
- } else if (missingCount > 0) {
586
- outcome = 'cantTell';
587
- reasonCode = 'composite.rollup.cantTell.missingChild';
588
- } else if (checksIds.length > 0 && notApplicableCount === checksIds.length) {
589
- outcome = 'notApplicable';
590
- reasonCode = 'composite.rollup.notApplicable.allInapplicable';
591
- } else if (checksIds.length === 0) {
592
- outcome = 'cantTell';
593
- reasonCode = 'composite.rollup.cantTell.emptyComposite';
594
- }
595
-
596
- const raw = {
597
- outcome,
598
- occurrences: [],
599
-
600
- // REQUIRED by your reporting schema (top-level)
601
- summaryKey: 'Composite rule rollup',
602
- i18nKey: 'composite_rollup_summary',
603
- i18nParams: { reasonCode, testCount: String(checksIds.length) },
604
-
605
- // REQUIRED by your reporting schema (machine-readable payload)
606
- data: {
607
- details: {
608
- reasonCode,
609
- checksIds: checksIds.slice(),
610
- contributors,
611
- metrics: {
612
- failCount,
613
- cantTellCount,
614
- notApplicableCount,
615
- passCount,
616
- missingCount
617
- }
618
- }
619
- },
620
-
621
- engineOptions: {
622
- ...(engineOptionsResolved || {}),
623
- locale: normalizeLocale(engineOptionsResolved && engineOptionsResolved.locale)
624
- }
625
- };
626
-
627
- // Promote composite severity based on contributors (deterministic).
628
- // - If composite fails: use max severity among failing children.
629
- // - If composite cantTell: use max severity among cantTell children (fallback to failing if you prefer).
630
- if (outcome === 'fail' && rolledFailSeverity) {
631
- raw.severity = rolledFailSeverity;
632
- } else if (outcome === 'cantTell' && rolledCantTellSeverity) {
633
- raw.severity = rolledCantTellSeverity;
634
- }
635
-
636
- rulesResults.push(normalizeRuleResult(cDefResolved, raw, SCHEMA_VERSION, policy, sharedHelpers));
637
- }
638
- } catch (e) {
639
- // no-throws: omit rulesResults if anything goes wrong
640
- }
641
-
642
- // Optional perf counters passthrough (only when enabled). Deterministic.
643
- let perfStats = null;
644
- try {
645
- if (engineOptionsResolved && engineOptionsResolved.perfStats && sharedHelpers && typeof sharedHelpers.getPerfStats === 'function') {
646
- perfStats = sharedHelpers.getPerfStats();
647
- }
648
- } catch (e) {
649
- perfStats = null;
650
- }
651
-
652
- if (ruleTimings) {
653
- if (perfStats && engineOptionsResolved && engineOptionsResolved.profileRules) {
654
- perfStats.ruleTimings = ruleTimings; // (whatever your timing map is)
655
- }
656
- }
657
-
658
- return {
659
- engine: { tag: ENGINE_TAG, schemaVersion: SCHEMA_VERSION },
660
- url,
661
- title,
662
- timestamp,
663
- perfStats,
664
- contextSelector: ctxSelector,
665
- checksResults,
666
- rulesResults,
667
- overriddenBuiltinIds
668
- };
669
- }
670
-
671
- module.exports = { runCore };