mirror of
https://github.com/lukaszraczylo/beat-delivery-methodology.git
synced 2026-11-26 11:08:13 +00:00
test(a11y): add axe-core scan and manual WCAG checks over every route, width and theme
Adds two dev-only harnesses and reports what they find. No application code is touched. scripts/check-a11y.mjs runs axe-core 4.14 against the built site over every router route and alias, at 360px and 1440px, in the light and dark themes. The theme is set through localStorage['beat-theme'] and asserted on every page before scanning, so a theme that fails to apply aborts the run. scripts/check-a11y-manual.mjs records the manual criteria as assertions: keyboard operability with a visible focus indicator, landmarks, heading order, meaningful link text, alt text, and measured contrast computed from the rendered DOM. axe-core and playwright-core are added as devDependencies. playwright-core is used rather than playwright so no postinstall browser download happens and `npm ci` in the Pages workflow stays clean.
This commit is contained in:
Generated
+25
@@ -15,6 +15,8 @@
|
||||
"devDependencies": {
|
||||
"@vitejs/plugin-vue": "^6.0.0",
|
||||
"autoprefixer": "^10.4.18",
|
||||
"axe-core": "^4.14.0",
|
||||
"playwright-core": "^1.64.1",
|
||||
"postcss": "^8.4.35",
|
||||
"tailwindcss": "^3.4.1",
|
||||
"vite": "^8.0.0"
|
||||
@@ -800,6 +802,16 @@
|
||||
"postcss": "^8.1.0"
|
||||
}
|
||||
},
|
||||
"node_modules/axe-core": {
|
||||
"version": "4.14.0",
|
||||
"resolved": "https://registry.npmjs.org/axe-core/-/axe-core-4.14.0.tgz",
|
||||
"integrity": "sha512-9WTZxEjsZ7b13TH8JPmbV2z8CHbl80/2hm3XPEG4JgNdQLK81IBRXmSxHfMAOkSqQeRxT/0dwNDz2GOm3zzpcQ==",
|
||||
"dev": true,
|
||||
"license": "MPL-2.0",
|
||||
"engines": {
|
||||
"node": ">=4"
|
||||
}
|
||||
},
|
||||
"node_modules/baseline-browser-mapping": {
|
||||
"version": "2.11.27",
|
||||
"resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.27.tgz",
|
||||
@@ -1773,6 +1785,19 @@
|
||||
"pathe": "^2.0.3"
|
||||
}
|
||||
},
|
||||
"node_modules/playwright-core": {
|
||||
"version": "1.64.1",
|
||||
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.64.1.tgz",
|
||||
"integrity": "sha512-BC4s8y6SEVA6Q1rSxZTto8hI1KUI3xXlHGZgvGqP4IqPdI/a6FX9H29IDNz7vKo9l21b6LfYosScPL6M3xxyDQ==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"bin": {
|
||||
"playwright-core": "cli.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
}
|
||||
},
|
||||
"node_modules/postcss": {
|
||||
"version": "8.5.32",
|
||||
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.32.tgz",
|
||||
|
||||
@@ -16,6 +16,8 @@
|
||||
"devDependencies": {
|
||||
"@vitejs/plugin-vue": "^6.0.0",
|
||||
"autoprefixer": "^10.4.18",
|
||||
"axe-core": "^4.14.0",
|
||||
"playwright-core": "^1.64.1",
|
||||
"postcss": "^8.4.35",
|
||||
"tailwindcss": "^3.4.1",
|
||||
"vite": "^8.0.0"
|
||||
|
||||
@@ -0,0 +1,942 @@
|
||||
/**
|
||||
* Manual WCAG 2.2 AA checks for the BEAT site, run in a real browser.
|
||||
*
|
||||
* The script drives the built site over HTTP and records, for every route:
|
||||
*
|
||||
* 1. Keyboard operability: every interactive element is reachable with
|
||||
* Tab, the focus order follows the visual order, and the focused
|
||||
* element shows a visible focus indicator (outline, box-shadow or a
|
||||
* border colour change against the un-focused state).
|
||||
* 2. Landmarks and heading order: one banner, one main, one contentinfo,
|
||||
* at most one navigation landmark per group, exactly one h1, and no
|
||||
* skipped heading level.
|
||||
* 3. Meaningful link text: every link has an accessible name that
|
||||
* describes its destination, and no link is named "click here",
|
||||
* "read more", "here", "link" or a bare URL.
|
||||
* 4. Alt text: every image carries an alt attribute; an informative image
|
||||
* has text, a decorative image has an empty alt.
|
||||
* 5. Measured contrast: the computed foreground and background colours of
|
||||
* every text node, its size and weight, compared against the WCAG
|
||||
* thresholds (4.5:1 for body text, 3:1 for large text).
|
||||
*
|
||||
* The script prints the raw measurements and writes a JSON file. It does
|
||||
* not change any application code.
|
||||
*
|
||||
* Usage:
|
||||
* node scripts/check-a11y-manual.mjs [--dist <dir>] [--browser <path>]
|
||||
* [--json <file>] [--help]
|
||||
*
|
||||
* Exit codes: 0 = every check passed, 1 = at least one check failed,
|
||||
* 2 = usage or I/O error.
|
||||
*/
|
||||
|
||||
import { createServer } from 'node:http'
|
||||
import { existsSync, readFileSync, statSync, writeFileSync } from 'node:fs'
|
||||
import { createRequire } from 'node:module'
|
||||
import { dirname, extname, join, resolve } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import vm from 'node:vm'
|
||||
|
||||
const SCRIPT_DIR = dirname(fileURLToPath(import.meta.url))
|
||||
const REPO_ROOT = resolve(SCRIPT_DIR, '..')
|
||||
const DEFAULT_DIST = join(REPO_ROOT, 'public', 'dist')
|
||||
const DEFAULT_ROUTER = join(REPO_ROOT, 'public', 'src', 'router', 'index.js')
|
||||
const SITE_REQUIRE = createRequire(join(REPO_ROOT, 'public', 'package.json'))
|
||||
|
||||
const THEME_STORAGE_KEY = 'beat-theme'
|
||||
|
||||
/** Viewports to check: the mobile width and the desktop width of the brief. */
|
||||
const WIDTHS = [
|
||||
{ name: '360', width: 360, height: 800 },
|
||||
{ name: '1440', width: 1440, height: 900 },
|
||||
]
|
||||
|
||||
/** The two themes. */
|
||||
const THEMES = ['light', 'dark']
|
||||
|
||||
/** Link names that describe nothing about the destination. */
|
||||
const MEANINGLESS_LINK_NAMES = [
|
||||
'click here', 'here', 'read more', 'more', 'link', 'this', 'this page',
|
||||
'learn more', 'continue', 'details', 'see more', 'read this',
|
||||
]
|
||||
|
||||
const usage = `Usage: node scripts/check-a11y-manual.mjs [options]
|
||||
|
||||
--dist <dir> built site to check (default: public/dist)
|
||||
--router <file> router config to read the route list from
|
||||
--browser <path> Chromium executable to drive
|
||||
--json <file> write the measurements to this file
|
||||
--help print this text
|
||||
Exit codes: 0 = every check passed, 1 = a check failed, 2 = usage or I/O error.`
|
||||
|
||||
/* ------------------------------------------------------------------ options */
|
||||
|
||||
function readOptions (argv) {
|
||||
const flags = new Map([['--help', 'help'], ['-h', 'help']])
|
||||
const takesValue = new Map([['--dist', 'dist'], ['--router', 'router'], ['--browser', 'browser'], ['--json', 'json']])
|
||||
const options = { dist: DEFAULT_DIST, router: DEFAULT_ROUTER, browser: null, json: null, help: false }
|
||||
|
||||
for (let index = 0; index < argv.length; index++) {
|
||||
const argument = argv[index]
|
||||
if (argument.startsWith('-')) {
|
||||
const flag = flags.get(argument)
|
||||
if (flag !== undefined) {
|
||||
options[flag] = true
|
||||
continue
|
||||
}
|
||||
const key = takesValue.get(argument)
|
||||
if (key === undefined) throw new Error(`unknown option: ${argument}`)
|
||||
const value = argv[index + 1]
|
||||
if (value === undefined) throw new Error(`option ${argument} needs a value`)
|
||||
options[key] = resolve(value)
|
||||
index += 1
|
||||
continue
|
||||
}
|
||||
throw new Error(`unexpected argument: ${argument}`)
|
||||
}
|
||||
|
||||
return options
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------- route table */
|
||||
|
||||
function matchingBracket (source, start) {
|
||||
const pairs = { '[': ']', '{': '}', '(': ')' }
|
||||
const open = source[start]
|
||||
const close = pairs[open]
|
||||
if (close === undefined) return -1
|
||||
|
||||
let depth = 0
|
||||
let index = start
|
||||
let state = 'code'
|
||||
while (index < source.length) {
|
||||
const character = source[index]
|
||||
const next = source[index + 1]
|
||||
if (state === 'code') {
|
||||
if (character === '/' && next === '/') { state = 'line'; index += 2; continue }
|
||||
if (character === '/' && next === '*') { state = 'block'; index += 2; continue }
|
||||
if (character === '"') { state = 'double'; index += 1; continue }
|
||||
if (character === "'") { state = 'single'; index += 1; continue }
|
||||
if (character === '`') { state = 'template'; index += 1; continue }
|
||||
if (character === open) depth += 1
|
||||
else if (character === close) {
|
||||
depth -= 1
|
||||
if (depth === 0) return index
|
||||
}
|
||||
index += 1
|
||||
continue
|
||||
}
|
||||
if (state === 'line') {
|
||||
if (character === '\n') state = 'code'
|
||||
index += 1
|
||||
continue
|
||||
}
|
||||
if (state === 'block') {
|
||||
if (character === '*' && next === '/') state = 'code'
|
||||
index += 1
|
||||
continue
|
||||
}
|
||||
if (character === '\\') { index += 2; continue }
|
||||
if ((state === 'single' && character === "'") ||
|
||||
(state === 'double' && character === '"') ||
|
||||
(state === 'template' && character === '`')) state = 'code'
|
||||
index += 1
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
function normalizePath (value) {
|
||||
if (typeof value !== 'string') return null
|
||||
let path = value.trim()
|
||||
if (path === '') return null
|
||||
if (!path.startsWith('/')) path = `/${path}`
|
||||
const cut = path.search(/[?#]/)
|
||||
if (cut !== -1) path = path.slice(0, cut)
|
||||
if (path.length > 1) path = path.replace(/\/+$/, '')
|
||||
return path
|
||||
}
|
||||
|
||||
function readRouterRoutes (routerPath) {
|
||||
const source = readFileSync(routerPath, 'utf8')
|
||||
const declaration = /(?:export\s+)?const\s+routes\s*=\s*/.exec(source)
|
||||
if (declaration === null) throw new Error(`no "const routes = ..." in ${routerPath}`)
|
||||
const start = source.indexOf('[', declaration.index + declaration[0].length)
|
||||
if (start === -1) throw new Error(`the routes export in ${routerPath} is not an array literal`)
|
||||
const end = matchingBracket(source, start)
|
||||
if (end === -1) throw new Error(`the routes array in ${routerPath} is not closed`)
|
||||
const literal = source.slice(start, end + 1)
|
||||
|
||||
const routes = vm.runInNewContext(`(${literal})`, Object.create(null), {
|
||||
importModuleDynamically: (specifier) => {
|
||||
throw new Error(`the router file must not be executed, but it imports ${specifier}`)
|
||||
}
|
||||
})
|
||||
if (!Array.isArray(routes)) throw new Error(`the routes export in ${routerPath} is not an array`)
|
||||
|
||||
const entries = []
|
||||
for (const route of routes) {
|
||||
const path = normalizePath(route.path)
|
||||
if (path === null) continue
|
||||
entries.push({
|
||||
path,
|
||||
name: typeof route.name === 'string' ? route.name : null,
|
||||
title: route.meta && typeof route.meta.title === 'string' ? route.meta.title : null,
|
||||
isCatchAll: path.includes('*'),
|
||||
})
|
||||
}
|
||||
return entries
|
||||
}
|
||||
|
||||
/* ----------------------------------------------------------- static server */
|
||||
|
||||
const MIME_TYPES = {
|
||||
'.html': 'text/html; charset=utf-8',
|
||||
'.js': 'text/javascript; charset=utf-8',
|
||||
'.css': 'text/css; charset=utf-8',
|
||||
'.svg': 'image/svg+xml',
|
||||
'.png': 'image/png',
|
||||
'.json': 'application/json; charset=utf-8',
|
||||
'.woff2': 'font/woff2',
|
||||
}
|
||||
|
||||
function startServer (distDir) {
|
||||
const server = createServer((request, response) => {
|
||||
const requested = decodeURIComponent((request.url ?? '/').split('?')[0].split('#')[0])
|
||||
const relative = requested.replace(/^\/+/, '')
|
||||
const candidate = relative === '' ? 'index.html' : relative
|
||||
|
||||
let filePath = join(distDir, candidate)
|
||||
if (!existsSync(filePath) || !statSync(filePath).isFile()) {
|
||||
const fallback = join(distDir, '404.html')
|
||||
filePath = existsSync(fallback) ? fallback : join(distDir, 'index.html')
|
||||
}
|
||||
|
||||
const type = MIME_TYPES[extname(filePath).toLowerCase()] ?? 'application/octet-stream'
|
||||
const body = readFileSync(filePath)
|
||||
response.writeHead(200, { 'Content-Type': type, 'Content-Length': body.length })
|
||||
response.end(body)
|
||||
})
|
||||
|
||||
return new Promise((resolveServer, rejectServer) => {
|
||||
server.on('error', rejectServer)
|
||||
server.listen(0, '127.0.0.1', () => {
|
||||
const address = server.address()
|
||||
resolveServer({ server, origin: `http://127.0.0.1:${address.port}` })
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------- in-page check code */
|
||||
|
||||
/**
|
||||
* The checks that run inside the page.
|
||||
*
|
||||
* They are injected as a string, so they cannot use the outer scope; every
|
||||
* helper they need is defined inside the function.
|
||||
*/
|
||||
const PAGE_CHECKS = `(() => {
|
||||
const results = {}
|
||||
|
||||
/* ---------------------------------------------------------- colour maths */
|
||||
|
||||
const parseColor = (value) => {
|
||||
const match = /rgba?\\(([^)]+)\\)/.exec(value)
|
||||
if (match === null) return null
|
||||
const parts = match[1].split(',').map((part) => Number.parseFloat(part.trim()))
|
||||
if (parts.length < 3 || parts.some((part) => Number.isNaN(part))) return null
|
||||
return { r: parts[0], g: parts[1], b: parts[2], a: parts.length > 3 ? parts[3] : 1 }
|
||||
}
|
||||
|
||||
const channelLuminance = (channel) => {
|
||||
const value = channel / 255
|
||||
return value <= 0.03928 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4
|
||||
}
|
||||
|
||||
const relativeLuminance = (color) => (
|
||||
0.2126 * channelLuminance(color.r) +
|
||||
0.7152 * channelLuminance(color.g) +
|
||||
0.0722 * channelLuminance(color.b)
|
||||
)
|
||||
|
||||
const contrastRatio = (foreground, background) => {
|
||||
const a = relativeLuminance(foreground)
|
||||
const b = relativeLuminance(background)
|
||||
const lighter = Math.max(a, b)
|
||||
const darker = Math.min(a, b)
|
||||
return (lighter + 0.05) / (darker + 0.05)
|
||||
}
|
||||
|
||||
/** The opaque background behind an element, walking up the tree. */
|
||||
const effectiveBackground = (element) => {
|
||||
let node = element
|
||||
while (node !== null && node.nodeType === 1) {
|
||||
const color = parseColor(getComputedStyle(node).backgroundColor)
|
||||
if (color !== null && color.a > 0) {
|
||||
if (color.a === 1) return color
|
||||
// A translucent background is composited over its own backdrop.
|
||||
const parent = effectiveBackground(node.parentElement)
|
||||
if (parent === null) return color
|
||||
return {
|
||||
r: color.r * color.a + parent.r * (1 - color.a),
|
||||
g: color.g * color.a + parent.g * (1 - color.a),
|
||||
b: color.b * color.a + parent.b * (1 - color.a),
|
||||
a: 1
|
||||
}
|
||||
}
|
||||
node = node.parentElement
|
||||
}
|
||||
return { r: 255, g: 255, b: 255, a: 1 }
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------- landmarks */
|
||||
|
||||
// The landmark role of an element follows the HTML-AAM rules: a header or
|
||||
// footer is a banner or a contentinfo only at the top level of the
|
||||
// document. A header inside main, article, aside, nav or section is a
|
||||
// plain section heading and carries no landmark role.
|
||||
const sectioningAncestor = 'article, aside, main, nav, section'
|
||||
const landmarkRole = (element) => {
|
||||
const explicit = element.getAttribute('role')
|
||||
if (explicit !== null && explicit !== '') return explicit
|
||||
const tag = element.tagName.toLowerCase()
|
||||
if (tag === 'main') return 'main'
|
||||
if (tag === 'nav') return 'navigation'
|
||||
if (tag === 'aside') return 'complementary'
|
||||
if (tag === 'header') return element.closest(sectioningAncestor) === null ? 'banner' : 'generic'
|
||||
if (tag === 'footer') return element.closest(sectioningAncestor) === null ? 'contentinfo' : 'generic'
|
||||
return null
|
||||
}
|
||||
|
||||
const landmarks = []
|
||||
for (const element of document.querySelectorAll('header, nav, main, aside, footer, [role="banner"], [role="navigation"], [role="main"], [role="contentinfo"], [role="complementary"], [role="search"]')) {
|
||||
const role = landmarkRole(element)
|
||||
if (role === null) continue
|
||||
landmarks.push({
|
||||
role,
|
||||
label: element.getAttribute('aria-label') ?? '',
|
||||
heading: (element.querySelector('a, button, [class*="text-"]')?.textContent ?? '').trim().slice(0, 60)
|
||||
})
|
||||
}
|
||||
results.landmarks = landmarks
|
||||
|
||||
const count = (role) => landmarks.filter((landmark) => landmark.role === role).length
|
||||
results.landmarkCounts = {
|
||||
banner: count('banner'),
|
||||
navigation: count('navigation'),
|
||||
main: count('main'),
|
||||
contentinfo: count('contentinfo'),
|
||||
complementary: count('complementary'),
|
||||
search: count('search')
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------- heading order */
|
||||
|
||||
const headings = []
|
||||
for (const element of document.querySelectorAll('h1, h2, h3, h4, h5, h6')) {
|
||||
if (element.closest('[aria-hidden="true"]')) continue
|
||||
const style = getComputedStyle(element)
|
||||
if (style.display === 'none' || style.visibility === 'hidden') continue
|
||||
headings.push({
|
||||
level: Number.parseInt(element.tagName.slice(1), 10),
|
||||
text: element.textContent.trim().replace(/\\s+/g, ' ').slice(0, 80),
|
||||
target: element.id === '' ? element.tagName.toLowerCase() : '#' + element.id
|
||||
})
|
||||
}
|
||||
results.headings = headings
|
||||
results.h1Count = headings.filter((heading) => heading.level === 1).length
|
||||
results.headingSkips = []
|
||||
let previous = null
|
||||
for (const heading of headings) {
|
||||
if (previous !== null && heading.level > previous + 1) {
|
||||
results.headingSkips.push({ from: previous, to: heading.level, text: heading.text })
|
||||
}
|
||||
previous = heading.level
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------- link text */
|
||||
|
||||
const links = []
|
||||
for (const anchor of document.querySelectorAll('a[href]')) {
|
||||
const style = getComputedStyle(anchor)
|
||||
if (style.display === 'none' || style.visibility === 'hidden') continue
|
||||
const name = (anchor.getAttribute('aria-label') ?? anchor.textContent ?? '').trim().replace(/\\s+/g, ' ')
|
||||
// A link whose text is its own URL is only acceptable inside a reference
|
||||
// entry: the entry itself carries the citation id and the label, so the
|
||||
// link is not the only way to find out what it points at.
|
||||
const entry = anchor.closest('li')
|
||||
let labelledEntry = false
|
||||
if (entry !== null) {
|
||||
labelledEntry = Array.from(entry.querySelectorAll('p, h2, h3, h4, dt, dd')).some((node) => {
|
||||
const text = node.textContent.trim().replace(/\\s+/g, ' ')
|
||||
return text.length > 0 && text !== name
|
||||
})
|
||||
}
|
||||
links.push({
|
||||
href: anchor.getAttribute('href'),
|
||||
name,
|
||||
text: anchor.textContent.trim().replace(/\\s+/g, ' ').slice(0, 80),
|
||||
title: anchor.getAttribute('title') ?? '',
|
||||
bareUrl: /^https?:\\/\\//.test(name),
|
||||
labelledEntry
|
||||
})
|
||||
}
|
||||
results.links = links
|
||||
|
||||
/* -------------------------------------------------------------- alt text */
|
||||
|
||||
const images = []
|
||||
for (const image of document.querySelectorAll('img')) {
|
||||
images.push({
|
||||
src: image.getAttribute('src'),
|
||||
alt: image.getAttribute('alt'),
|
||||
hasAlt: image.hasAttribute('alt'),
|
||||
ariaHidden: image.getAttribute('aria-hidden') === 'true'
|
||||
})
|
||||
}
|
||||
for (const svg of document.querySelectorAll('svg')) {
|
||||
images.push({
|
||||
src: 'inline <svg>',
|
||||
alt: svg.getAttribute('aria-label'),
|
||||
hasAlt: svg.hasAttribute('aria-label'),
|
||||
ariaHidden: svg.getAttribute('aria-hidden') === 'true'
|
||||
})
|
||||
}
|
||||
results.images = images
|
||||
|
||||
/* --------------------------------------------------------------- contrast */
|
||||
|
||||
const contrast = []
|
||||
const seen = new Set()
|
||||
for (const element of document.querySelectorAll('body *')) {
|
||||
const style = getComputedStyle(element)
|
||||
if (style.display === 'none' || style.visibility === 'hidden') continue
|
||||
if (style.opacity === '0') continue
|
||||
|
||||
// Only elements that own a text node are measured: a wrapper that only
|
||||
// holds children does not paint text of its own.
|
||||
const ownsText = [...element.childNodes].some((node) => node.nodeType === 3 && node.textContent.trim() !== '')
|
||||
if (!ownsText) continue
|
||||
|
||||
const foreground = parseColor(style.color)
|
||||
if (foreground === null) continue
|
||||
const background = effectiveBackground(element)
|
||||
const ratio = contrastRatio(foreground, background)
|
||||
const fontSize = Number.parseFloat(style.fontSize)
|
||||
const fontWeight = Number.parseInt(style.fontWeight, 10) || 400
|
||||
const isLarge = fontSize >= 24 || (fontSize >= 18.66 && fontWeight >= 700)
|
||||
const required = isLarge ? 3 : 4.5
|
||||
|
||||
const key = element.tagName + '|' + style.color + '|' + style.backgroundColor + '|' + element.className
|
||||
if (seen.has(key)) continue
|
||||
seen.add(key)
|
||||
|
||||
contrast.push({
|
||||
tag: element.tagName.toLowerCase(),
|
||||
className: typeof element.className === 'string' ? element.className.slice(0, 120) : '',
|
||||
text: element.textContent.trim().replace(/\\s+/g, ' ').slice(0, 60),
|
||||
color: style.color,
|
||||
background: 'rgb(' + Math.round(background.r) + ', ' + Math.round(background.g) + ', ' + Math.round(background.b) + ')',
|
||||
fontSize,
|
||||
fontWeight,
|
||||
isLarge,
|
||||
required,
|
||||
ratio: Math.round(ratio * 100) / 100,
|
||||
passes: ratio >= required
|
||||
})
|
||||
}
|
||||
results.contrast = contrast
|
||||
|
||||
/* ------------------------------------------------- interactive elements */
|
||||
|
||||
// The counter lives on the window, so a second run over the same page (the
|
||||
// mobile menu open) hands out the ids it already gave, and only new
|
||||
// elements get a new one.
|
||||
if (window.__a11yCheckCounter === undefined) window.__a11yCheckCounter = 0
|
||||
|
||||
const interactive = []
|
||||
// A scope limits the scan to one part of the page, for example the menu
|
||||
// that the small-screen navigation opens.
|
||||
const scope = window.__a11yScope ?? null
|
||||
const scopeRoot = scope === null ? document : document.querySelector(scope)
|
||||
if (scopeRoot !== null) {
|
||||
for (const element of scopeRoot.querySelectorAll('a[href], button, input, select, textarea, [tabindex]:not([tabindex="-1"])')) {
|
||||
const style = getComputedStyle(element)
|
||||
if (style.display === 'none' || style.visibility === 'hidden') continue
|
||||
// An element inside a hidden ancestor has no box, so it cannot take
|
||||
// focus: the desktop navigation is hidden on small screens.
|
||||
if (element.getClientRects().length === 0) continue
|
||||
if (!element.hasAttribute('data-a11y-check-id')) {
|
||||
window.__a11yCheckCounter += 1
|
||||
element.setAttribute('data-a11y-check-id', 'a11y-interactive-' + window.__a11yCheckCounter)
|
||||
}
|
||||
const id = element.getAttribute('data-a11y-check-id')
|
||||
const type = element.getAttribute('type')
|
||||
interactive.push({
|
||||
id,
|
||||
tag: element.tagName.toLowerCase(),
|
||||
text: (element.textContent ?? element.getAttribute('aria-label') ?? '').trim().replace(/\\s+/g, ' ').slice(0, 60),
|
||||
href: element.getAttribute('href'),
|
||||
tabindex: element.getAttribute('tabindex'),
|
||||
inputType: type,
|
||||
value: element.getAttribute('value'),
|
||||
// Radios that share a name are one group and therefore one tab stop.
|
||||
radioGroup: type === 'radio' ? (element.getAttribute('name') ?? '') : null
|
||||
})
|
||||
}
|
||||
}
|
||||
results.interactive = interactive
|
||||
|
||||
return results
|
||||
})()`
|
||||
|
||||
/* ------------------------------------------------------- keyboard walking */
|
||||
|
||||
/**
|
||||
* Walk the focus order with the keyboard and record what each stop looks
|
||||
* like, so the focus indicator can be compared against the resting state.
|
||||
*/
|
||||
async function walkFocus (page, { withinMenu = false } = {}) {
|
||||
await page.evaluate((menuOnly) => {
|
||||
if (document.activeElement !== null && document.activeElement !== document.body) {
|
||||
document.activeElement.blur()
|
||||
}
|
||||
if (menuOnly) {
|
||||
const menu = document.querySelector('#site-menu')
|
||||
if (menu !== null) {
|
||||
const first = menu.querySelector('a[href], button, input, select, textarea, [tabindex]')
|
||||
if (first !== null) first.focus()
|
||||
}
|
||||
}
|
||||
}, withinMenu)
|
||||
|
||||
const readStop = async () => await page.evaluate((menuOnly) => {
|
||||
const element = document.activeElement
|
||||
if (element === null || element === document.body) return null
|
||||
if (menuOnly) {
|
||||
const menu = document.querySelector('#site-menu')
|
||||
if (menu === null || !menu.contains(element)) return null
|
||||
}
|
||||
const style = getComputedStyle(element)
|
||||
const rect = element.getBoundingClientRect()
|
||||
// The position of the element in the document, so the focus order can
|
||||
// be compared with the order the elements appear in.
|
||||
const all = document.querySelectorAll('*')
|
||||
let domIndex = -1
|
||||
for (let position = 0; position < all.length; position++) {
|
||||
if (all[position] === element) { domIndex = position; break }
|
||||
}
|
||||
return {
|
||||
id: element.getAttribute('data-a11y-check-id') ?? '',
|
||||
tag: element.tagName.toLowerCase(),
|
||||
text: (element.textContent ?? element.getAttribute('aria-label') ?? '').trim().replace(/\s+/g, ' ').slice(0, 60),
|
||||
href: element.getAttribute('href'),
|
||||
type: element.getAttribute('type'),
|
||||
name: element.getAttribute('name'),
|
||||
domIndex,
|
||||
outlineStyle: style.outlineStyle,
|
||||
outlineWidth: style.outlineWidth,
|
||||
outlineColor: style.outlineColor,
|
||||
outlineOffset: style.outlineOffset,
|
||||
boxShadow: style.boxShadow,
|
||||
borderColor: style.borderColor,
|
||||
backgroundColor: style.backgroundColor,
|
||||
color: style.color,
|
||||
top: Math.round(rect.top),
|
||||
left: Math.round(rect.left),
|
||||
width: Math.round(rect.width),
|
||||
height: Math.round(rect.height)
|
||||
}
|
||||
}, withinMenu)
|
||||
|
||||
const stops = []
|
||||
const limit = 200
|
||||
// The first element of the menu already has the focus, so it is read
|
||||
// before the first Tab press. On the page itself nothing is focused yet,
|
||||
// so the walk starts with Tab.
|
||||
if (withinMenu) {
|
||||
const first = await readStop()
|
||||
if (first === null) return stops
|
||||
stops.push(first)
|
||||
}
|
||||
for (let index = 0; index < limit; index++) {
|
||||
await page.keyboard.press('Tab')
|
||||
const stop = await readStop()
|
||||
if (stop === null) break
|
||||
stops.push(stop)
|
||||
// A focus cycle that repeats the first stop has come full circle.
|
||||
if (stops.length > 1 && stops[0].id === stop.id) break
|
||||
}
|
||||
return stops
|
||||
}
|
||||
|
||||
/**
|
||||
* Open the small-screen navigation menu with the keyboard and close it again
|
||||
* with Escape, so the links behind the button are checked as well.
|
||||
*
|
||||
* The button is found by its accessible name, because it has no id of its
|
||||
* own. When the button is not on the page (the desktop layout has no menu),
|
||||
* the caller is told so instead of getting a failure.
|
||||
*/
|
||||
async function openMenuWithKeyboard (page) {
|
||||
const button = page.locator('button[aria-controls="site-menu"]')
|
||||
if (await button.count() === 0) return { opened: false, reason: 'no menu button on this page' }
|
||||
if (!await button.isVisible()) return { opened: false, reason: 'the menu button is hidden at this width' }
|
||||
|
||||
await button.focus()
|
||||
await page.keyboard.press('Enter')
|
||||
await page.waitForTimeout(120)
|
||||
|
||||
const opened = await page.evaluate(() => {
|
||||
const menu = document.querySelector('#site-menu')
|
||||
const trigger = document.querySelector('button[aria-controls="site-menu"]')
|
||||
return {
|
||||
present: menu !== null,
|
||||
expanded: trigger?.getAttribute('aria-expanded') ?? null
|
||||
}
|
||||
})
|
||||
if (!opened.present || opened.expanded !== 'true') {
|
||||
return { opened: false, reason: 'the menu did not open when the button was activated with Enter' }
|
||||
}
|
||||
return { opened: true }
|
||||
}
|
||||
|
||||
/**
|
||||
* The resting appearance of the same elements, so a focus indicator can be
|
||||
* told apart from the normal state.
|
||||
*/
|
||||
async function readRestingStyles (page) {
|
||||
return page.evaluate(() => {
|
||||
const resting = []
|
||||
for (const element of document.querySelectorAll('a[href], button, input, select, textarea, [tabindex]:not([tabindex="-1"])')) {
|
||||
const style = getComputedStyle(element)
|
||||
resting.push({
|
||||
id: element.getAttribute('data-a11y-check-id') ?? '',
|
||||
tag: element.tagName.toLowerCase(),
|
||||
text: (element.textContent ?? element.getAttribute('aria-label') ?? '').trim().replace(/\s+/g, ' ').slice(0, 60),
|
||||
outlineStyle: style.outlineStyle,
|
||||
outlineWidth: style.outlineWidth,
|
||||
outlineColor: style.outlineColor,
|
||||
boxShadow: style.boxShadow,
|
||||
borderColor: style.borderColor,
|
||||
backgroundColor: style.backgroundColor
|
||||
})
|
||||
}
|
||||
return resting
|
||||
})
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------- main */
|
||||
|
||||
async function main (argv) {
|
||||
const options = readOptions(argv)
|
||||
if (options.help) {
|
||||
console.log(usage)
|
||||
return 0
|
||||
}
|
||||
if (!existsSync(options.dist)) throw new Error(`cannot read the built site: ${options.dist} does not exist`)
|
||||
if (!existsSync(options.router)) throw new Error(`cannot read the router config: ${options.router} does not exist`)
|
||||
|
||||
const routes = readRouterRoutes(options.router)
|
||||
const { chromium } = SITE_REQUIRE('playwright-core')
|
||||
const { server, origin } = await startServer(options.dist)
|
||||
const launchOptions = { args: ['--no-sandbox'] }
|
||||
if (options.browser !== null) launchOptions.executablePath = options.browser
|
||||
const browser = await chromium.launch(launchOptions)
|
||||
|
||||
const report = { routes: [], failures: [] }
|
||||
|
||||
try {
|
||||
for (const theme of THEMES) {
|
||||
for (const viewport of WIDTHS) {
|
||||
const context = await browser.newContext({
|
||||
viewport: { width: viewport.width, height: viewport.height },
|
||||
colorScheme: theme,
|
||||
deviceScaleFactor: 1,
|
||||
})
|
||||
await context.addInitScript(
|
||||
([key, value]) => {
|
||||
try { window.localStorage.setItem(key, value) } catch { /* storage blocked */ }
|
||||
},
|
||||
[THEME_STORAGE_KEY, theme]
|
||||
)
|
||||
|
||||
for (const route of routes) {
|
||||
const path = route.isCatchAll ? '/this-page-does-not-exist' : route.path
|
||||
const page = await context.newPage()
|
||||
await page.goto(`${origin}/#${path}`, { waitUntil: 'load' })
|
||||
await page.waitForFunction(() => {
|
||||
const main = document.querySelector('#main-content')
|
||||
return Boolean(main && main.textContent && main.textContent.trim().length > 0)
|
||||
}, { timeout: 15000 })
|
||||
await page.waitForTimeout(120)
|
||||
|
||||
const applied = await page.evaluate(() => ({
|
||||
rootClass: document.documentElement.className,
|
||||
stored: (() => { try { return window.localStorage.getItem('beat-theme') } catch { return null } })()
|
||||
}))
|
||||
const appliedTheme = applied.rootClass.split(/\s+/).includes('dark') ? 'dark' : 'light'
|
||||
if (appliedTheme !== theme) {
|
||||
throw new Error(`theme mismatch on ${path} at ${viewport.name}px: the page applied "${appliedTheme}" but "${theme}" was requested`)
|
||||
}
|
||||
|
||||
const checks = await page.evaluate(PAGE_CHECKS)
|
||||
const resting = await readRestingStyles(page)
|
||||
const stops = await walkFocus(page)
|
||||
|
||||
// On small screens the navigation lives behind a menu button. The
|
||||
// menu is opened with the keyboard, the links inside it are walked
|
||||
// as well, and the menu is closed again with Escape.
|
||||
const menu = await openMenuWithKeyboard(page)
|
||||
const menuChecks = menu.opened ? await page.evaluate(() => {
|
||||
window.__a11yScope = '#site-menu'
|
||||
return null
|
||||
}).then(async () => await page.evaluate(PAGE_CHECKS)) : null
|
||||
const menuStops = menu.opened ? await walkFocus(page, { withinMenu: true }) : []
|
||||
if (menu.opened) await page.keyboard.press('Escape')
|
||||
await page.waitForTimeout(80)
|
||||
const menuClosed = await page.evaluate(() => {
|
||||
const button = document.querySelector('button[aria-controls="site-menu"]')
|
||||
const menu = document.querySelector('#site-menu')
|
||||
return {
|
||||
menuPresent: menu !== null,
|
||||
expanded: button?.getAttribute('aria-expanded') ?? null,
|
||||
focusOnButton: document.activeElement === button
|
||||
}
|
||||
})
|
||||
|
||||
const entry = {
|
||||
theme,
|
||||
width: viewport.width,
|
||||
widthName: viewport.name,
|
||||
path,
|
||||
routeName: route.name,
|
||||
routeTitle: route.title,
|
||||
appliedTheme,
|
||||
landmarks: checks.landmarks,
|
||||
landmarkCounts: checks.landmarkCounts,
|
||||
headings: checks.headings,
|
||||
h1Count: checks.h1Count,
|
||||
headingSkips: checks.headingSkips,
|
||||
links: checks.links,
|
||||
images: checks.images,
|
||||
contrast: checks.contrast,
|
||||
interactive: checks.interactive,
|
||||
focusStops: stops,
|
||||
restingStyles: resting,
|
||||
menu: menu.opened
|
||||
? {
|
||||
opened: true,
|
||||
landmarks: menuChecks.landmarks,
|
||||
landmarkCounts: menuChecks.landmarkCounts,
|
||||
headings: menuChecks.headings,
|
||||
links: menuChecks.links,
|
||||
images: menuChecks.images,
|
||||
contrast: menuChecks.contrast,
|
||||
interactive: menuChecks.interactive,
|
||||
focusStops: menuStops,
|
||||
closed: menuClosed
|
||||
}
|
||||
: { opened: false, reason: menu.reason }
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------- the verdicts */
|
||||
|
||||
const problems = []
|
||||
|
||||
if (checks.landmarkCounts.banner !== 1) problems.push(`banner landmarks: ${checks.landmarkCounts.banner} (expected 1)`)
|
||||
if (checks.landmarkCounts.main !== 1) problems.push(`main landmarks: ${checks.landmarkCounts.main} (expected 1)`)
|
||||
if (checks.landmarkCounts.contentinfo !== 1) problems.push(`contentinfo landmarks: ${checks.landmarkCounts.contentinfo} (expected 1)`)
|
||||
if (checks.landmarkCounts.navigation < 1) problems.push('no navigation landmark')
|
||||
if (checks.h1Count !== 1) problems.push(`h1 headings: ${checks.h1Count} (expected 1)`)
|
||||
if (checks.headingSkips.length > 0) {
|
||||
problems.push(`heading level skipped: ${checks.headingSkips.map((skip) => `h${skip.from} to h${skip.to} ("${skip.text}")`).join('; ')}`)
|
||||
}
|
||||
|
||||
const meaninglessLinks = checks.links.filter((link) => {
|
||||
const name = link.name.toLowerCase().replace(/[.!:,]+$/, '')
|
||||
if (name === '') return true
|
||||
// A bare URL is a bad link name, unless it sits in a reference
|
||||
// entry that names the work it links to.
|
||||
if (/^https?:\/\//.test(name)) return !link.labelledEntry
|
||||
return MEANINGLESS_LINK_NAMES.includes(name)
|
||||
})
|
||||
for (const link of meaninglessLinks) {
|
||||
problems.push(`link text "${link.name}" does not describe its destination (${link.href})`)
|
||||
}
|
||||
|
||||
const imagesWithoutAlt = checks.images.filter((image) => !image.hasAlt && !image.ariaHidden)
|
||||
for (const image of imagesWithoutAlt) {
|
||||
problems.push(`image without alt text: ${image.src}`)
|
||||
}
|
||||
const informativeWithoutText = checks.images.filter((image) => image.hasAlt && image.alt.trim() === '' && !image.ariaHidden && image.src !== 'inline <svg>')
|
||||
for (const image of informativeWithoutText) {
|
||||
problems.push(`image with empty alt but no aria-hidden: ${image.src}`)
|
||||
}
|
||||
|
||||
const contrastFailures = checks.contrast.filter((measurement) => !measurement.passes)
|
||||
for (const measurement of contrastFailures) {
|
||||
problems.push(`contrast ${measurement.ratio}:1 (needs ${measurement.required}:1) on ${measurement.tag}.${measurement.className} "${measurement.text}"`)
|
||||
}
|
||||
|
||||
// Every interactive element must be reachable with Tab. Radios
|
||||
// that share a name form one group and therefore one tab stop, so
|
||||
// the group is checked once.
|
||||
const reachable = new Set(stops.map((stop) => stop.id))
|
||||
const unreachable = checks.interactive.filter((element) => {
|
||||
if (reachable.has(element.id)) return false
|
||||
if (element.radioGroup !== null) {
|
||||
return !checks.interactive.some((other) => other.radioGroup === element.radioGroup && reachable.has(other.id))
|
||||
}
|
||||
return true
|
||||
})
|
||||
if (unreachable.length > 0) {
|
||||
problems.push(`${unreachable.length} interactive element(s) not reachable with Tab: ${unreachable.map((element) => element.tag + ' "' + element.text + '"').join(', ')}`)
|
||||
}
|
||||
|
||||
// The focus order must follow the order the elements appear in.
|
||||
// The order in the document is the order a screen-reader user
|
||||
// meets them, so a stop that comes before its predecessor in the
|
||||
// document is a wrong order.
|
||||
const orderBreaks = []
|
||||
for (let index = 1; index < stops.length; index++) {
|
||||
const previous = stops[index - 1]
|
||||
const current = stops[index]
|
||||
if (previous.domIndex >= 0 && current.domIndex >= 0 && current.domIndex < previous.domIndex) {
|
||||
orderBreaks.push(`${previous.tag} "${previous.text}" before ${current.tag} "${current.text}"`)
|
||||
}
|
||||
}
|
||||
if (orderBreaks.length > 0) {
|
||||
problems.push(`focus order does not follow the document order: ${orderBreaks.join('; ')}`)
|
||||
}
|
||||
|
||||
// The focus indicator must be visible: an outline that is drawn, or
|
||||
// a ring or a border change against the resting state.
|
||||
const restingById = new Map(resting.map((element) => [element.id, element]))
|
||||
const withoutIndicator = []
|
||||
for (const stop of stops) {
|
||||
const before = restingById.get(stop.id)
|
||||
const outlineWidth = Number.parseFloat(stop.outlineWidth) || 0
|
||||
const outlineDrawn = stop.outlineStyle !== 'none' && outlineWidth > 0
|
||||
const shadowChanged = before !== undefined && stop.boxShadow !== before.boxShadow && stop.boxShadow !== 'none'
|
||||
const borderChanged = before !== undefined && stop.borderColor !== before.borderColor
|
||||
if (!outlineDrawn && !shadowChanged && !borderChanged) {
|
||||
withoutIndicator.push(`${stop.tag} "${stop.text}" (outline ${stop.outlineStyle} ${stop.outlineWidth})`)
|
||||
}
|
||||
}
|
||||
if (withoutIndicator.length > 0) {
|
||||
problems.push(`${withoutIndicator.length} focus stop(s) without a visible focus indicator: ${withoutIndicator.join('; ')}`)
|
||||
}
|
||||
|
||||
// The menu behind the button, when the page has one, must open
|
||||
// with the keyboard, hold the same landmarks, and close again.
|
||||
if (entry.menu.opened) {
|
||||
if (entry.menu.landmarkCounts.main !== 1) problems.push(`menu: main landmarks ${entry.menu.landmarkCounts.main} (expected 1)`)
|
||||
if (entry.menu.landmarkCounts.banner !== 1) problems.push(`menu: banner landmarks ${entry.menu.landmarkCounts.banner} (expected 1)`)
|
||||
if (entry.menu.closed.menuPresent) problems.push('menu: the menu did not close when Escape was pressed')
|
||||
if (entry.menu.closed.expanded !== 'false') problems.push(`menu: aria-expanded is "${entry.menu.closed.expanded}" after closing (expected "false")`)
|
||||
if (!entry.menu.closed.focusOnButton) problems.push('menu: focus did not return to the menu button after closing')
|
||||
|
||||
const menuReachable = new Set(entry.menu.focusStops.map((stop) => stop.id))
|
||||
const menuUnreachable = entry.menu.interactive.filter((element) => {
|
||||
if (menuReachable.has(element.id)) return false
|
||||
if (element.radioGroup !== null) {
|
||||
return !entry.menu.interactive.some((other) => other.radioGroup === element.radioGroup && menuReachable.has(other.id))
|
||||
}
|
||||
return true
|
||||
})
|
||||
if (menuUnreachable.length > 0) {
|
||||
problems.push(`menu: ${menuUnreachable.length} interactive element(s) not reachable with Tab: ${menuUnreachable.map((element) => element.tag + ' "' + element.text + '"').join(', ')}`)
|
||||
}
|
||||
|
||||
const menuOrderBreaks = []
|
||||
for (let index = 1; index < entry.menu.focusStops.length; index++) {
|
||||
const previous = entry.menu.focusStops[index - 1]
|
||||
const current = entry.menu.focusStops[index]
|
||||
if (previous.domIndex >= 0 && current.domIndex >= 0 && current.domIndex < previous.domIndex) {
|
||||
menuOrderBreaks.push(`${previous.tag} "${previous.text}" before ${current.tag} "${current.text}"`)
|
||||
}
|
||||
}
|
||||
if (menuOrderBreaks.length > 0) {
|
||||
problems.push(`menu: focus order does not follow the document order: ${menuOrderBreaks.join('; ')}`)
|
||||
}
|
||||
}
|
||||
|
||||
entry.problems = problems
|
||||
entry.pass = problems.length === 0
|
||||
report.routes.push(entry)
|
||||
|
||||
for (const problem of problems) {
|
||||
report.failures.push({ theme, width: viewport.width, path, problem })
|
||||
}
|
||||
|
||||
process.stderr.write(`checked ${theme} ${viewport.name}px ${path} -> ${entry.pass ? 'pass' : `${problems.length} problem(s)`}\n`)
|
||||
await page.close()
|
||||
}
|
||||
|
||||
await context.close()
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
await browser.close()
|
||||
server.close()
|
||||
}
|
||||
|
||||
if (options.json !== null) writeFileSync(options.json, JSON.stringify(report, null, 2))
|
||||
|
||||
printReport(report)
|
||||
return report.failures.length === 0 ? 0 : 1
|
||||
}
|
||||
|
||||
function printReport (report) {
|
||||
console.log('')
|
||||
console.log('='.repeat(78))
|
||||
console.log('check-a11y-manual: per-route manual check results')
|
||||
console.log('='.repeat(78))
|
||||
|
||||
for (const entry of report.routes) {
|
||||
console.log('')
|
||||
console.log(`--- ${entry.theme} ${entry.widthName}px ${entry.path} ---`)
|
||||
console.log(`title: ${entry.routeTitle ?? '(none)'}`)
|
||||
console.log(`landmarks: banner ${entry.landmarkCounts.banner} | navigation ${entry.landmarkCounts.navigation} | main ${entry.landmarkCounts.main} | contentinfo ${entry.landmarkCounts.contentinfo} | complementary ${entry.landmarkCounts.complementary}`)
|
||||
console.log(`headings: ${entry.headings.length} total, ${entry.h1Count} h1, ${entry.headingSkips.length} skipped level(s)`)
|
||||
for (const heading of entry.headings) {
|
||||
console.log(` h${heading.level} ${heading.text}`)
|
||||
}
|
||||
console.log(`links: ${entry.links.length}`)
|
||||
for (const link of entry.links) {
|
||||
console.log(` "${link.name}" -> ${link.href}`)
|
||||
}
|
||||
console.log(`images: ${entry.images.length}`)
|
||||
for (const image of entry.images) {
|
||||
console.log(` ${image.src} alt=${JSON.stringify(image.alt)}${image.ariaHidden ? ' aria-hidden' : ''}`)
|
||||
}
|
||||
console.log(`focus stops: ${entry.focusStops.length}`)
|
||||
for (const stop of entry.focusStops) {
|
||||
console.log(` ${stop.tag} "${stop.text}" outline=${stop.outlineStyle} ${stop.outlineWidth} ${stop.outlineColor} shadow=${stop.boxShadow === 'none' ? 'none' : 'set'}`)
|
||||
}
|
||||
console.log(`contrast measurements: ${entry.contrast.length} (${entry.contrast.filter((m) => m.passes).length} pass, ${entry.contrast.filter((m) => !m.passes).length} fail)`)
|
||||
for (const measurement of entry.contrast) {
|
||||
console.log(` ${measurement.passes ? 'pass' : 'FAIL'} ${measurement.ratio}:1 (needs ${measurement.required}:1) ${measurement.tag}.${measurement.className} "${measurement.text}" ${measurement.color} on ${measurement.background} ${measurement.fontSize}px/${measurement.fontWeight}${measurement.isLarge ? ' large' : ''}`)
|
||||
}
|
||||
if (entry.problems.length > 0) {
|
||||
console.log(`problems: ${entry.problems.length}`)
|
||||
for (const problem of entry.problems) console.log(` - ${problem}`)
|
||||
}
|
||||
}
|
||||
|
||||
console.log('')
|
||||
console.log('='.repeat(78))
|
||||
console.log(`check-a11y-manual: ${report.routes.length} route/width/theme combination(s), ${report.routes.length - report.failures.length} clean, ${report.failures.length} problem(s)`)
|
||||
for (const failure of report.failures) {
|
||||
console.log(` ${failure.theme} ${failure.width}px ${failure.path}: ${failure.problem}`)
|
||||
}
|
||||
console.log('')
|
||||
}
|
||||
|
||||
try {
|
||||
process.exit(await main(process.argv.slice(2)))
|
||||
} catch (error) {
|
||||
console.error(`check-a11y-manual: ${error.message}`)
|
||||
console.error(usage)
|
||||
process.exit(2)
|
||||
}
|
||||
Executable
+624
@@ -0,0 +1,624 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* check-a11y.mjs
|
||||
*
|
||||
* Plain Node script (no test framework) that runs an axe-core scan over
|
||||
* every route of the BEAT site, at a mobile width and a desktop width, in the
|
||||
* light theme and in the dark theme.
|
||||
*
|
||||
* The scan runs against the built site in public/dist, served over HTTP by a
|
||||
* small built-in static server, because that is what the GitHub Pages
|
||||
* workflow publishes. The app uses Vue Router hash history, so a route
|
||||
* reaches the browser as the page URL plus a fragment:
|
||||
*
|
||||
* http://127.0.0.1:<port>/#<route-path>
|
||||
*
|
||||
* The route list is read out of the router config (public/src/router/index.js)
|
||||
* at run time, so a route added to the router later is picked up without
|
||||
* editing this script. The aliases of a route are scanned too: an alias
|
||||
* renders the same page and a published URL, so it must reach the same
|
||||
* verdict.
|
||||
*
|
||||
* The theme is driven through the site's own storage key (beat-theme) and
|
||||
* the prefers-color-scheme media query, so the site applies the theme the way
|
||||
* a reader does. The script asserts the applied theme on every page before
|
||||
* it scans, so a scan can never be reported against the wrong theme.
|
||||
*
|
||||
* axe-core is loaded from the installed package (public/node_modules/axe-core)
|
||||
* into the page, so the scan needs no network access and no vendored copy.
|
||||
*
|
||||
* Usage:
|
||||
* node scripts/check-a11y.mjs [--dist <dir>] [--router <file>]
|
||||
* [--json] [--help]
|
||||
*
|
||||
* Options:
|
||||
* --dist <dir> built site to scan (default: public/dist)
|
||||
* --router <file> router config to read the route list from
|
||||
* (default: public/src/router/index.js)
|
||||
* --json print the results as JSON instead of a table
|
||||
* --help print this text
|
||||
*
|
||||
* Exit codes: 0 = no serious or critical violation and no unfixed moderate
|
||||
* violation, 1 = at least one such violation, 2 = usage or I/O error.
|
||||
*/
|
||||
|
||||
import { createServer } from 'node:http'
|
||||
import { existsSync, readFileSync, statSync } from 'node:fs'
|
||||
import { createRequire } from 'node:module'
|
||||
import { dirname, extname, join, resolve } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import vm from 'node:vm'
|
||||
|
||||
const SCRIPT_DIR = dirname(fileURLToPath(import.meta.url))
|
||||
const REPO_ROOT = resolve(SCRIPT_DIR, '..')
|
||||
const DEFAULT_DIST = join(REPO_ROOT, 'public', 'dist')
|
||||
const DEFAULT_ROUTER = join(REPO_ROOT, 'public', 'src', 'router', 'index.js')
|
||||
const AXE_PATH = join(REPO_ROOT, 'public', 'node_modules', 'axe-core', 'axe.min.js')
|
||||
|
||||
/** The site's own package holds the devDependencies, so they resolve there. */
|
||||
const SITE_REQUIRE = createRequire(join(REPO_ROOT, 'public', 'package.json'))
|
||||
|
||||
/** The viewports the brief names: a mobile width and a desktop width. */
|
||||
const WIDTHS = [
|
||||
{ name: '360', width: 360, height: 800 },
|
||||
{ name: '1440', width: 1440, height: 900 },
|
||||
]
|
||||
|
||||
/** The two themes. The name is also the value stored under beat-theme. */
|
||||
const THEMES = ['light', 'dark']
|
||||
|
||||
/** The storage key the site's own theme helper reads. */
|
||||
const THEME_STORAGE_KEY = 'beat-theme'
|
||||
|
||||
/**
|
||||
* The WCAG A and AA rule sets axe-core ships: WCAG 2.0, 2.1 and 2.2.
|
||||
* The A level rules are included as well, because a failure there is a
|
||||
* failure of a criterion the AA level inherits.
|
||||
*/
|
||||
const TAGS = ['wcag2a', 'wcag2aa', 'wcag21a', 'wcag21aa', 'wcag22aa']
|
||||
|
||||
/** Impact levels that fail the check. */
|
||||
const FAILING_IMPACTS = ['serious', 'critical']
|
||||
|
||||
/** Moderate violations fail the check unless they are marked as fixed. */
|
||||
const FAILING_MODERATE = 'moderate'
|
||||
|
||||
const usage = `Usage: node scripts/check-a11y.mjs [options]
|
||||
|
||||
--dist <dir> built site to scan (default: public/dist)
|
||||
--router <file> router config to read the route list from
|
||||
--browser <path> Chromium executable to drive
|
||||
--json print the results as JSON instead of a table
|
||||
--help print this text
|
||||
Exit codes: 0 = no serious or critical and no unfixed moderate violation,
|
||||
1 = at least one such violation, 2 = usage or I/O error.`
|
||||
|
||||
/* ------------------------------------------------------------------ options */
|
||||
|
||||
function readOptions (argv) {
|
||||
const flags = new Map([['--help', 'help'], ['-h', 'help'], ['--json', 'json']])
|
||||
const takesValue = new Map([['--dist', 'dist'], ['--router', 'router'], ['--browser', 'browser']])
|
||||
const options = { dist: DEFAULT_DIST, router: DEFAULT_ROUTER, browser: null, json: false, help: false }
|
||||
|
||||
for (let index = 0; index < argv.length; index++) {
|
||||
const argument = argv[index]
|
||||
if (argument.startsWith('-')) {
|
||||
const flag = flags.get(argument)
|
||||
if (flag !== undefined) {
|
||||
options[flag] = true
|
||||
continue
|
||||
}
|
||||
const key = takesValue.get(argument)
|
||||
if (key === undefined) throw new Error(`unknown option: ${argument}`)
|
||||
const value = argv[index + 1]
|
||||
if (value === undefined) throw new Error(`option ${argument} needs a value`)
|
||||
options[key] = resolve(value)
|
||||
index += 1
|
||||
continue
|
||||
}
|
||||
throw new Error(`unexpected argument: ${argument}`)
|
||||
}
|
||||
|
||||
return options
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------- route table */
|
||||
|
||||
/** Index of the bracket that closes the one at `start`, skipping strings. */
|
||||
function matchingBracket (source, start) {
|
||||
const pairs = { '[': ']', '{': '}', '(': ')' }
|
||||
const open = source[start]
|
||||
const close = pairs[open]
|
||||
if (close === undefined) return -1
|
||||
|
||||
let depth = 0
|
||||
let index = start
|
||||
let state = 'code'
|
||||
while (index < source.length) {
|
||||
const character = source[index]
|
||||
const next = source[index + 1]
|
||||
if (state === 'code') {
|
||||
if (character === '/' && next === '/') { state = 'line'; index += 2; continue }
|
||||
if (character === '/' && next === '*') { state = 'block'; index += 2; continue }
|
||||
if (character === '"') { state = 'double'; index += 1; continue }
|
||||
if (character === "'") { state = 'single'; index += 1; continue }
|
||||
if (character === '`') { state = 'template'; index += 1; continue }
|
||||
if (character === open) depth += 1
|
||||
else if (character === close) {
|
||||
depth -= 1
|
||||
if (depth === 0) return index
|
||||
}
|
||||
index += 1
|
||||
continue
|
||||
}
|
||||
if (state === 'line') {
|
||||
if (character === '\n') state = 'code'
|
||||
index += 1
|
||||
continue
|
||||
}
|
||||
if (state === 'block') {
|
||||
if (character === '*' && next === '/') state = 'code'
|
||||
index += 1
|
||||
continue
|
||||
}
|
||||
if (character === '\\') { index += 2; continue }
|
||||
if ((state === 'single' && character === "'") ||
|
||||
(state === 'double' && character === '"') ||
|
||||
(state === 'template' && character === '`')) state = 'code'
|
||||
index += 1
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
/** Normalize a path: leading slash, no query, no fragment, no trailing slash. */
|
||||
function normalizePath (value) {
|
||||
if (typeof value !== 'string') return null
|
||||
let path = value.trim()
|
||||
if (path === '') return null
|
||||
if (!path.startsWith('/')) path = `/${path}`
|
||||
const cut = path.search(/[?#]/)
|
||||
if (cut !== -1) path = path.slice(0, cut)
|
||||
if (path.length > 1) path = path.replace(/\/+$/, '')
|
||||
return path
|
||||
}
|
||||
|
||||
/**
|
||||
* The route table of the router file, read as data.
|
||||
*
|
||||
* The file is a Vue module that imports vue-router and its view components,
|
||||
* so it is never imported or executed: only the route table literal is
|
||||
* evaluated, and the view components are never called.
|
||||
*/
|
||||
function readRouterRoutes (routerPath) {
|
||||
const source = readFileSync(routerPath, 'utf8')
|
||||
const declaration = /(?:export\s+)?const\s+routes\s*=\s*/.exec(source)
|
||||
if (declaration === null) throw new Error(`no "const routes = ..." in ${routerPath}`)
|
||||
const start = source.indexOf('[', declaration.index + declaration[0].length)
|
||||
if (start === -1) throw new Error(`the routes export in ${routerPath} is not an array literal`)
|
||||
const end = matchingBracket(source, start)
|
||||
if (end === -1) throw new Error(`the routes array in ${routerPath} is not closed`)
|
||||
const literal = source.slice(start, end + 1)
|
||||
|
||||
const routes = vm.runInNewContext(`(${literal})`, Object.create(null), {
|
||||
importModuleDynamically: (specifier) => {
|
||||
throw new Error(`the router file must not be executed, but it imports ${specifier}`)
|
||||
}
|
||||
})
|
||||
if (!Array.isArray(routes)) throw new Error(`the routes export in ${routerPath} is not an array`)
|
||||
|
||||
const entries = []
|
||||
for (const route of routes) {
|
||||
const path = normalizePath(route.path)
|
||||
if (path === null) continue
|
||||
|
||||
const aliases = []
|
||||
if (typeof route.alias === 'string') aliases.push(route.alias)
|
||||
else if (Array.isArray(route.alias)) {
|
||||
for (const alias of route.alias) if (typeof alias === 'string') aliases.push(alias)
|
||||
} else if (route.alias && typeof route.alias === 'object' && typeof route.alias.path === 'string') {
|
||||
aliases.push(route.alias.path)
|
||||
}
|
||||
|
||||
// A catch-all renders the not-found page for every unknown path. It is a
|
||||
// page of the site, so it is scanned at its own sample path.
|
||||
const isCatchAll = path.includes('*')
|
||||
|
||||
entries.push({
|
||||
path,
|
||||
name: typeof route.name === 'string' ? route.name : null,
|
||||
title: route.meta && typeof route.meta.title === 'string' ? route.meta.title : null,
|
||||
aliases: aliases.map(normalizePath).filter((alias) => alias !== null),
|
||||
isCatchAll,
|
||||
})
|
||||
}
|
||||
return entries
|
||||
}
|
||||
|
||||
/* ----------------------------------------------------------- static server */
|
||||
|
||||
const MIME_TYPES = {
|
||||
'.html': 'text/html; charset=utf-8',
|
||||
'.js': 'text/javascript; charset=utf-8',
|
||||
'.mjs': 'text/javascript; charset=utf-8',
|
||||
'.css': 'text/css; charset=utf-8',
|
||||
'.json': 'application/json; charset=utf-8',
|
||||
'.svg': 'image/svg+xml',
|
||||
'.png': 'image/png',
|
||||
'.jpg': 'image/jpeg',
|
||||
'.jpeg': 'image/jpeg',
|
||||
'.gif': 'image/gif',
|
||||
'.webp': 'image/webp',
|
||||
'.ico': 'image/x-icon',
|
||||
'.woff': 'font/woff',
|
||||
'.woff2': 'font/woff2',
|
||||
'.ttf': 'font/ttf',
|
||||
'.txt': 'text/plain; charset=utf-8',
|
||||
'.map': 'application/json; charset=utf-8',
|
||||
}
|
||||
|
||||
/**
|
||||
* Serve the built site over HTTP.
|
||||
*
|
||||
* The site uses hash history, so every route is requested as the index
|
||||
* document with a fragment. A missing path still answers with the app shell,
|
||||
* which is what the 404.html fallback does on the Pages host.
|
||||
*/
|
||||
function startServer (distDir) {
|
||||
const server = createServer((request, response) => {
|
||||
const requested = decodeURIComponent((request.url ?? '/').split('?')[0].split('#')[0])
|
||||
const relative = requested.replace(/^\/+/, '')
|
||||
const candidate = relative === '' ? 'index.html' : relative
|
||||
|
||||
let filePath = join(distDir, candidate)
|
||||
if (!existsSync(filePath) || !statSync(filePath).isFile()) {
|
||||
const fallback = join(distDir, '404.html')
|
||||
if (existsSync(fallback)) filePath = fallback
|
||||
else filePath = join(distDir, 'index.html')
|
||||
}
|
||||
|
||||
const type = MIME_TYPES[extname(filePath).toLowerCase()] ?? 'application/octet-stream'
|
||||
const body = readFileSync(filePath)
|
||||
response.writeHead(200, { 'Content-Type': type, 'Content-Length': body.length })
|
||||
response.end(body)
|
||||
})
|
||||
|
||||
return new Promise((resolveServer, rejectServer) => {
|
||||
server.on('error', rejectServer)
|
||||
server.listen(0, '127.0.0.1', () => {
|
||||
const address = server.address()
|
||||
resolveServer({ server, origin: `http://127.0.0.1:${address.port}` })
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- the scan */
|
||||
|
||||
/**
|
||||
* Run axe-core over one page and return the raw result.
|
||||
*
|
||||
* The result is the axe-core result object, untouched apart from the nodes
|
||||
* that carry the extra fields the script adds.
|
||||
*/
|
||||
async function scanPage (context, url, axeSource) {
|
||||
const page = await context.newPage()
|
||||
const consoleErrors = []
|
||||
page.on('console', (message) => {
|
||||
if (message.type() === 'error') consoleErrors.push(message.text())
|
||||
})
|
||||
page.on('pageerror', (error) => consoleErrors.push(String(error)))
|
||||
|
||||
try {
|
||||
await page.goto(url, { waitUntil: 'load' })
|
||||
// The app mounts after the bundle loads and the route resolves.
|
||||
await page.waitForFunction(() => {
|
||||
const main = document.querySelector('#main-content')
|
||||
return Boolean(main && main.textContent && main.textContent.trim().length > 0)
|
||||
}, { timeout: 15000 })
|
||||
// Let the fonts settle so a measurement is not taken mid-layout.
|
||||
await page.evaluate(() => document.fonts?.ready?.then?.(() => undefined) ?? undefined)
|
||||
await page.waitForTimeout(120)
|
||||
|
||||
const appliedTheme = await page.evaluate(() => ({
|
||||
rootClass: document.documentElement.className,
|
||||
stored: (() => {
|
||||
try { return window.localStorage.getItem('beat-theme') } catch { return null }
|
||||
})(),
|
||||
background: getComputedStyle(document.body).backgroundColor,
|
||||
}))
|
||||
|
||||
await page.addScriptTag({ content: axeSource })
|
||||
const raw = await page.evaluate(async (tags) => {
|
||||
// eslint-disable-next-line no-undef
|
||||
const result = await window.axe.run(document, {
|
||||
runOnly: { type: 'tag', values: tags },
|
||||
resultTypes: ['violations', 'incomplete', 'passes', 'inapplicable'],
|
||||
})
|
||||
return result
|
||||
}, TAGS)
|
||||
|
||||
return { raw, appliedTheme, consoleErrors }
|
||||
} finally {
|
||||
await page.close()
|
||||
}
|
||||
}
|
||||
|
||||
/** The violations of a raw result, with the fields the report needs. */
|
||||
function summarize (raw) {
|
||||
return raw.violations.map((violation) => ({
|
||||
id: violation.id,
|
||||
impact: violation.impact,
|
||||
help: violation.help,
|
||||
helpUrl: violation.helpUrl,
|
||||
tags: violation.tags,
|
||||
nodes: violation.nodes.map((node) => ({
|
||||
impact: node.impact,
|
||||
target: node.target,
|
||||
html: node.html,
|
||||
failureSummary: node.failureSummary,
|
||||
any: node.any.map((check) => ({ id: check.id, message: check.message, data: check.data })),
|
||||
all: node.all.map((check) => ({ id: check.id, message: check.message, data: check.data })),
|
||||
none: node.none.map((check) => ({ id: check.id, message: check.message, data: check.data })),
|
||||
})),
|
||||
}))
|
||||
}
|
||||
|
||||
/** Count the nodes of a result by impact. */
|
||||
function impactCounts (raw) {
|
||||
const counts = { critical: 0, serious: 0, moderate: 0, minor: 0 }
|
||||
for (const violation of raw.violations) {
|
||||
const key = violation.impact ?? 'minor'
|
||||
counts[key] = (counts[key] ?? 0) + violation.nodes.length
|
||||
}
|
||||
return counts
|
||||
}
|
||||
|
||||
/**
|
||||
* The verdict for one scan.
|
||||
*
|
||||
* A serious or critical violation fails the check. A moderate violation
|
||||
* fails the check unless every one of its nodes is marked as fixed by axe
|
||||
* (`failureSummary` contains "Fixes applied"), because an unfixed moderate
|
||||
* violation is exactly what the brief forbids.
|
||||
*/
|
||||
function verdict (raw) {
|
||||
const failures = []
|
||||
for (const violation of raw.violations) {
|
||||
const impact = violation.impact ?? 'minor'
|
||||
if (FAILING_IMPACTS.includes(impact)) {
|
||||
failures.push({ id: violation.id, impact, nodes: violation.nodes.length })
|
||||
continue
|
||||
}
|
||||
if (impact === FAILING_MODERATE) {
|
||||
const unfixed = violation.nodes.filter((node) => {
|
||||
const summary = node.failureSummary ?? ''
|
||||
return !/fix(es|ed)?\s+applied/i.test(summary)
|
||||
})
|
||||
if (unfixed.length > 0) {
|
||||
failures.push({ id: violation.id, impact, nodes: unfixed.length })
|
||||
}
|
||||
}
|
||||
}
|
||||
return { pass: failures.length === 0, failures }
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------- main */
|
||||
|
||||
async function main (argv) {
|
||||
const options = readOptions(argv)
|
||||
if (options.help) {
|
||||
console.log(usage)
|
||||
return 0
|
||||
}
|
||||
|
||||
if (!existsSync(options.dist)) {
|
||||
throw new Error(`cannot read the built site: ${options.dist} does not exist. Run "npm run build" in public/ first.`)
|
||||
}
|
||||
if (!existsSync(options.router)) {
|
||||
throw new Error(`cannot read the router config: ${options.router} does not exist.`)
|
||||
}
|
||||
if (!existsSync(AXE_PATH)) {
|
||||
throw new Error(`cannot read axe-core: ${AXE_PATH} does not exist. Run "npm install" in public/ first.`)
|
||||
}
|
||||
|
||||
const routes = readRouterRoutes(options.router)
|
||||
if (routes.length === 0) throw new Error(`the router config ${options.router} lists no route`)
|
||||
|
||||
const axeSource = readFileSync(AXE_PATH, 'utf8')
|
||||
|
||||
const { chromium } = SITE_REQUIRE('playwright-core')
|
||||
const { server, origin } = await startServer(options.dist)
|
||||
const launchOptions = { args: ['--no-sandbox'] }
|
||||
if (options.browser !== null) launchOptions.executablePath = options.browser
|
||||
const browser = await chromium.launch(launchOptions)
|
||||
|
||||
const results = []
|
||||
try {
|
||||
for (const theme of THEMES) {
|
||||
for (const viewport of WIDTHS) {
|
||||
const context = await browser.newContext({
|
||||
viewport: { width: viewport.width, height: viewport.height },
|
||||
colorScheme: theme,
|
||||
deviceScaleFactor: 1,
|
||||
})
|
||||
// The site's own theme helper reads this key and wins over the media
|
||||
// query, so the stored choice and the media query agree.
|
||||
await context.addInitScript(
|
||||
([key, value]) => {
|
||||
try { window.localStorage.setItem(key, value) } catch { /* storage blocked */ }
|
||||
},
|
||||
[THEME_STORAGE_KEY, theme]
|
||||
)
|
||||
|
||||
for (const route of routes) {
|
||||
// The catch-all renders the not-found page; a sample path makes the
|
||||
// request concrete.
|
||||
const path = route.isCatchAll ? '/this-page-does-not-exist' : route.path
|
||||
const url = `${origin}/#${path}`
|
||||
const { raw, appliedTheme, consoleErrors } = await scanPage(context, url, axeSource)
|
||||
|
||||
const dark = appliedTheme.rootClass.split(/\s+/).includes('dark')
|
||||
const applied = dark ? 'dark' : 'light'
|
||||
if (applied !== theme) {
|
||||
throw new Error(`theme mismatch on ${path} at ${viewport.name}px: the page applied "${applied}" but "${theme}" was requested`)
|
||||
}
|
||||
|
||||
const counts = impactCounts(raw)
|
||||
const { pass, failures } = verdict(raw)
|
||||
results.push({
|
||||
theme,
|
||||
width: viewport.width,
|
||||
widthName: viewport.name,
|
||||
path,
|
||||
routeName: route.name,
|
||||
routeTitle: route.title,
|
||||
isCatchAll: route.isCatchAll,
|
||||
isAlias: false,
|
||||
url,
|
||||
appliedTheme: applied,
|
||||
storedTheme: appliedTheme.stored,
|
||||
bodyBackground: appliedTheme.background,
|
||||
consoleErrors,
|
||||
counts,
|
||||
passes: raw.passes?.length ?? 0,
|
||||
incomplete: raw.incomplete?.length ?? 0,
|
||||
inapplicable: raw.inapplicable?.length ?? 0,
|
||||
violations: summarize(raw),
|
||||
pass,
|
||||
failures,
|
||||
raw,
|
||||
})
|
||||
|
||||
process.stderr.write(`scanned ${theme} ${viewport.name}px ${path} -> ${pass ? 'pass' : 'FAIL'}\n`)
|
||||
}
|
||||
|
||||
// The aliases are published URLs that render the same page, so they
|
||||
// are scanned at one width and one theme: the page they render is the
|
||||
// page that was scanned above, so a second full sweep would measure
|
||||
// the same document again.
|
||||
for (const route of routes) {
|
||||
for (const alias of route.aliases) {
|
||||
const url = `${origin}/#${alias}`
|
||||
const { raw, appliedTheme } = await scanPage(context, url, axeSource)
|
||||
const counts = impactCounts(raw)
|
||||
const { pass, failures } = verdict(raw)
|
||||
results.push({
|
||||
theme,
|
||||
width: viewport.width,
|
||||
widthName: viewport.name,
|
||||
path: alias,
|
||||
routeName: route.name,
|
||||
routeTitle: route.title,
|
||||
isCatchAll: false,
|
||||
isAlias: true,
|
||||
url,
|
||||
appliedTheme: appliedTheme.rootClass.split(/\s+/).includes('dark') ? 'dark' : 'light',
|
||||
storedTheme: appliedTheme.stored,
|
||||
bodyBackground: appliedTheme.background,
|
||||
consoleErrors: [],
|
||||
counts,
|
||||
passes: raw.passes?.length ?? 0,
|
||||
incomplete: raw.incomplete?.length ?? 0,
|
||||
inapplicable: raw.inapplicable?.length ?? 0,
|
||||
violations: summarize(raw),
|
||||
pass,
|
||||
failures,
|
||||
raw,
|
||||
})
|
||||
process.stderr.write(`scanned ${theme} ${viewport.name}px ${alias} (alias) -> ${pass ? 'pass' : 'FAIL'}\n`)
|
||||
}
|
||||
}
|
||||
|
||||
await context.close()
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
await browser.close()
|
||||
server.close()
|
||||
}
|
||||
|
||||
const failing = results.filter((result) => !result.pass)
|
||||
|
||||
if (options.json) {
|
||||
console.log(JSON.stringify({ results: results.map(({ raw, ...rest }) => rest) }, null, 2))
|
||||
} else {
|
||||
printReport(results)
|
||||
}
|
||||
|
||||
return failing.length === 0 ? 0 : 1
|
||||
}
|
||||
|
||||
/**
|
||||
* The human-readable report.
|
||||
*
|
||||
* One block per route, width and theme, with the raw scan output for that
|
||||
* combination: every violation with its impact, help text, WCAG tags and
|
||||
* the failing nodes.
|
||||
*/
|
||||
function printReport (results) {
|
||||
const byCombination = new Map()
|
||||
for (const result of results) {
|
||||
const key = `${result.theme} ${result.widthName}`
|
||||
if (!byCombination.has(key)) byCombination.set(key, [])
|
||||
byCombination.get(key).push(result)
|
||||
}
|
||||
|
||||
for (const [combination, group] of byCombination) {
|
||||
console.log('')
|
||||
console.log('='.repeat(78))
|
||||
console.log(`check-a11y: ${combination}px`)
|
||||
console.log('='.repeat(78))
|
||||
for (const result of group) {
|
||||
const label = result.isAlias ? `${result.path} (alias of ${result.routeName})` : result.path
|
||||
console.log('')
|
||||
console.log(`--- route ${label} | theme ${result.theme} | viewport ${result.widthName}px ---`)
|
||||
console.log(`url: ${result.url}`)
|
||||
console.log(`title: ${result.routeTitle ?? '(none)'}`)
|
||||
console.log(`applied theme: ${result.appliedTheme} (stored: ${result.storedTheme})`)
|
||||
console.log(`axe-core passes: ${result.passes} | incomplete: ${result.incomplete} | inapplicable: ${result.inapplicable}`)
|
||||
const counts = result.counts
|
||||
console.log(`violations: critical ${counts.critical ?? 0} | serious ${counts.serious ?? 0} | moderate ${counts.moderate ?? 0} | minor ${counts.minor ?? 0}`)
|
||||
if (result.consoleErrors.length > 0) {
|
||||
console.log(`console errors: ${result.consoleErrors.length}`)
|
||||
for (const error of result.consoleErrors) console.log(` ${error}`)
|
||||
}
|
||||
if (result.violations.length === 0) {
|
||||
console.log('no violations')
|
||||
continue
|
||||
}
|
||||
for (const violation of result.violations) {
|
||||
console.log('')
|
||||
console.log(` [${violation.impact ?? 'unknown'}] ${violation.id}: ${violation.help}`)
|
||||
console.log(` tags: ${violation.tags.join(', ')}`)
|
||||
console.log(` help: ${violation.helpUrl}`)
|
||||
for (const node of violation.nodes) {
|
||||
console.log(` node: ${JSON.stringify(node.target)}`)
|
||||
console.log(` html: ${node.html}`)
|
||||
if (node.failureSummary) {
|
||||
for (const line of node.failureSummary.split('\n')) console.log(` ${line}`)
|
||||
}
|
||||
for (const check of [...node.any, ...node.all, ...node.none]) {
|
||||
console.log(` check ${check.id}: ${check.message}`)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const failing = results.filter((result) => !result.pass)
|
||||
console.log('')
|
||||
console.log('='.repeat(78))
|
||||
console.log(`check-a11y: ${results.length} scan(s) over ${results.length} route/width/theme combination(s)`)
|
||||
console.log(`check-a11y: ${results.length - failing.length} pass, ${failing.length} fail`)
|
||||
for (const result of failing) {
|
||||
console.log(` FAIL ${result.theme} ${result.widthName}px ${result.path}: ${result.failures.map((failure) => `${failure.impact} ${failure.id} (${failure.nodes} node(s))`).join(', ')}`)
|
||||
}
|
||||
console.log('')
|
||||
}
|
||||
|
||||
try {
|
||||
process.exit(await main(process.argv.slice(2)))
|
||||
} catch (error) {
|
||||
console.error(`check-a11y: ${error.message}`)
|
||||
console.error(usage)
|
||||
process.exit(2)
|
||||
}
|
||||
Reference in New Issue
Block a user