@surea11y/puppeteer 1.4.1 → 1.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +195 -9
- package/package.json +3 -3
- package/src/A11yCoreBuilder.d.ts +100 -5
- package/src/A11yCoreBuilder.js +186 -4
- package/src/index.js +5 -5
package/README.md
CHANGED
|
@@ -5,12 +5,12 @@ A Puppeteer binding for [`@surea11y/core`](https://github.com/SureA11y/core) —
|
|
|
5
5
|
## Install
|
|
6
6
|
|
|
7
7
|
```bash
|
|
8
|
-
npm install @surea11y/puppeteer puppeteer
|
|
8
|
+
npm install @surea11y/core @surea11y/puppeteer puppeteer
|
|
9
9
|
```
|
|
10
10
|
|
|
11
|
-
`@surea11y/core` 1.12.0 or later, the engine, comes with
|
|
11
|
+
`@surea11y/core` 1.12.0 or later, the engine, comes with the binding as a regular dependency, so a project that doesn't list it still works. List it in your own `package.json` too, as the line above does: your project and the binding then share one copy, so whatever you do with core directly, writing a SARIF log or an HTML report (`@surea11y/core/sarif`, `/report`), reading the rule catalogue or keeping a baseline, reads results with the same core that produced them. When your core can't match the binding's range, as with a linked checkout (`file:../core`) or a fork, add `"overrides": { "@surea11y/core": "$@surea11y/core" }` beside it.
|
|
12
12
|
|
|
13
|
-
|
|
13
|
+
**Coming in 2.0:** core becomes a peer dependency, so the binding will no longer install it for you, and the `overrides` entry is no longer needed. Add `@surea11y/core` to your `package.json` now and 2.0 needs no change.
|
|
14
14
|
|
|
15
15
|
Puppeteer downloads its own bundled Chrome as part of `npm install` — unlike the Playwright binding, there's no separate browser-install step needed for `npm test` to work.
|
|
16
16
|
|
|
@@ -85,7 +85,7 @@ Each of the four takes a string or an array of strings. Anything else, such as `
|
|
|
85
85
|
|
|
86
86
|
`.exclude(selector)` above excludes globally. Pass a second argument to scope it to specific rule IDs instead: `.exclude('.mat-select', { rules: ['aria-required-children'] })` skips `.mat-select` for that rule only — every other rule still sees it. Global and rule-scoped `.exclude()` calls compose freely.
|
|
87
87
|
|
|
88
|
-
**Create one builder per scan.** `A11yCoreBuilder` is a mutable object with no reset between `.analyze()` calls — `include()`/`exclude()`/`withRules()`/`disableRules()`/`withTags()`/`disableTags()`/`options()`/`withCustomRules()`/`withPacks()` all push onto or merge into internal state that persists for the instance's lifetime. Calling one of them again before a second `.analyze()` call *accumulates* on top of the first scan's scope rather than replacing it (this is exactly what makes "call `.include()` several times for one scan," above, work — the same accumulation just also applies across separate scans if you reuse an instance). `.reportOnly()`/`.frames()`/`.elementRef()`/`.withWcag()`/`.withBestPractices()`/`.includeMode()`/`.wcagLevel()`/`.logger()` are the exception: each call replaces the previous value instead of merging with it.
|
|
88
|
+
**Create one builder per scan.** `A11yCoreBuilder` is a mutable object with no reset between `.analyze()` calls — `include()`/`exclude()`/`withRules()`/`disableRules()`/`withTags()`/`disableTags()`/`options()`/`withCustomRules()`/`withPacks()` all push onto or merge into internal state that persists for the instance's lifetime. Calling one of them again before a second `.analyze()` call *accumulates* on top of the first scan's scope rather than replacing it (this is exactly what makes "call `.include()` several times for one scan," above, work — the same accumulation just also applies across separate scans if you reuse an instance). `.reportOnly()`/`.frames()`/`.elementRef()`/`.screenshots()`/`.withWcag()`/`.withBestPractices()`/`.includeMode()`/`.wcagLevel()`/`.logger()` are the exception: each call replaces the previous value instead of merging with it.
|
|
89
89
|
|
|
90
90
|
This binding works against both browsers Puppeteer supports — Chrome (the default) and Firefox via `puppeteer.launch({ browser: 'firefox' })` — verified with a real Firefox run, see `tests/cross-browser.test.js`. There's no WebKit option; that's a Playwright-only engine.
|
|
91
91
|
|
|
@@ -122,13 +122,27 @@ const results = await new A11yCoreBuilder({ page })
|
|
|
122
122
|
|
|
123
123
|
A batch job that writes `getScanGaps(results)` into its own report can pass `.logger(() => {})` to keep its output to the report, and `.logger(null)` brings `console.warn` back. Anything other than a function or `null` throws a `TypeError` at the call, and a later call replaces the logger. Either way, `getScanGaps(results)` still lists every gap.
|
|
124
124
|
|
|
125
|
-
`getScanNotes(results)` says how the page was scanned, which a gap doesn't cover, and nothing was left out: `'forced-colors'` when the page was shown in [forced colors](#forced-colors),
|
|
125
|
+
`getScanNotes(results)` says how the page was scanned, which a gap doesn't cover, and nothing was left out: `'forced-colors'` when the page was shown in [forced colors](#forced-colors), `'internals-hook'` when the scan asked about web components it could have read with the [internals hook](#web-components-the-internals-hook), and `'listener-hook'` or `'live-region-hook'` when findings that the [listener hook](#click-handlers-added-from-script-the-listener-hook) or the [live-region hook](#live-regions-the-live-region-hook-and-announcements) would have decided were judged without it (with `findingCount` and the `rules`). `analyze()` also prints each hook note, once per scan, and a `.logger()` receives it (check `kind` to tell a note from a gap).
|
|
126
126
|
|
|
127
127
|
See `examples/e2e-test-example.test.js` for a fuller, runnable version (`npm run example:e2e`) — one test proving real violations get caught (unlabeled button, missing `alt`), one proving a mistyped `.include()` scope is caught rather than passed, one proving a well-formed page passes cleanly, and one gating a page on a pack's checklist. It uses `node:test` directly rather than a dedicated test-runner package: Puppeteer has no first-party test runner the way `@playwright/test` is the default for Playwright, and `node:test` is a zero-new-dependency choice that already matches this project's own test suite.
|
|
128
128
|
|
|
129
|
+
### Failing only on serious problems
|
|
130
|
+
|
|
131
|
+
Every rule result has a severity: `critical`, `serious`, `moderate` or `minor` (a profile can set its own). To start by blocking on serious problems while the rest are still reported, gate on `getGatingFailures(results, { failOnSeverity })` (`@surea11y/binding-base` 1.6.0 and later): the failing rules at that level or above, the same ones `surea11y scan --fail-on-severity` counts for the page. `formatFailures()` takes the same option and still lists the failures below the level, marked as ones that don't fail the test.
|
|
132
|
+
|
|
133
|
+
```js
|
|
134
|
+
const { A11yCoreBuilder, formatFailures, getGatingFailures } = require('@surea11y/puppeteer');
|
|
135
|
+
|
|
136
|
+
const results = await new A11yCoreBuilder({ page }).analyze();
|
|
137
|
+
const gate = { failOnSeverity: 'serious' };
|
|
138
|
+
assert.deepStrictEqual(getGatingFailures(results, gate), [], formatFailures(results, gate));
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
`fail` keeps its meaning, a definite violation; the level only picks which failures stop the test, and every failure stays in `results`. A level that isn't one of the four throws a `TypeError`. `SEVERITIES` lists them, least to most severe.
|
|
142
|
+
|
|
129
143
|
### Readable console/CI output on failure
|
|
130
144
|
|
|
131
|
-
A bare length/equality assertion alone gets you a *working* gate, but the failure message is a raw, deeply-nested object diff — hundreds of lines for a handful of violations. `formatFailures(results)` turns that into a short, scannable block (one entry per occurrence, numbered, with rule ID/severity/location/hint), followed by the result's scan gaps and the `@surea11y/core` release that produced it, that you hand to your assertion library's own failure-message parameter, as above. A real failure then prints:
|
|
145
|
+
A bare length/equality assertion alone gets you a *working* gate, but the failure message is a raw, deeply-nested object diff — hundreds of lines for a handful of violations. `formatFailures(results)` turns that into a short, scannable block (one entry per occurrence, numbered, with rule ID/severity/location/hint), followed by the result's scan gaps and the `@surea11y/core` release that produced it, that you hand to your assertion library's own failure-message parameter, as above. Each occurrence is read by its own outcome, and the list follows the order a review takes: failures first, then the [questions](#findings-that-need-review-leans-and-how-to-check) that likely fail, those that likely pass, and those only a person can answer. A real failure then prints:
|
|
132
146
|
|
|
133
147
|
```
|
|
134
148
|
AssertionError [ERR_ASSERTION]: 1) button-name-present (serious): This button has no accessible name.
|
|
@@ -153,7 +167,7 @@ Before the version line, it also prints the result's notes (`getScanNotes()`, ab
|
|
|
153
167
|
|
|
154
168
|
An element inside a shadow tree is located through its shadow hosts, as `my-app >>> my-card >>> img`; `formatOccurrenceLocation(occurrence)` gives that line on its own. Passing `results.checksResults` instead of `results` still works and lists the findings alone.
|
|
155
169
|
|
|
156
|
-
Deliberately a plain function, not a custom `expect` matcher — no dependency on any particular assertion library, so it works the same with `node:assert`, Jest, Vitest, or a hand-rolled `if`/`throw`. Defaults to `fail`/`cantTell` outcomes (the ones that report something found); pass `{ outcomes: [...] }` to narrow further. It throws a `TypeError` for the `{ topFrame, frames }` result of a `.frames(true)` scan: format `topFrame` and each frame on its own (below). A thrown rule (`occurrences: []`, `error` set — see [`OUTPUT_SCHEMA.md`](https://github.com/SureA11y/core/blob/main/docs/OUTPUT_SCHEMA.md)) is still surfaced using its `error` message rather than silently dropped.
|
|
170
|
+
Deliberately a plain function, not a custom `expect` matcher — no dependency on any particular assertion library, so it works the same with `node:assert`, Jest, Vitest, or a hand-rolled `if`/`throw`. Defaults to `fail`/`cantTell` outcomes (the ones that report something found); pass `{ outcomes: [...] }` to narrow further, by outcome or by review group (`'leanFail'`, `'leanPass'`, `'open'`), and `{ howToCheck: true }` to list each question's steps (see [below](#findings-that-need-review-leans-and-how-to-check)). An outcome it doesn't know throws a `TypeError`. It throws a `TypeError` for the `{ topFrame, frames }` result of a `.frames(true)` scan: format `topFrame` and each frame on its own (below). A thrown rule (`occurrences: []`, `error` set — see [`OUTPUT_SCHEMA.md`](https://github.com/SureA11y/core/blob/main/docs/OUTPUT_SCHEMA.md)) is still surfaced using its `error` message rather than silently dropped.
|
|
157
171
|
|
|
158
172
|
### Scanning every frame, including cross-origin iframes
|
|
159
173
|
|
|
@@ -220,6 +234,71 @@ This resolves the occurrence to an `ElementHandle` instead of leaving you to re-
|
|
|
220
234
|
|
|
221
235
|
Each `ElementHandle` holds a browser-side reference until garbage collected or explicitly disposed — for a scan with many violations that you're keeping around a while (rather than using immediately, as above), call `occurrence.elementHandle.dispose()` when you're done with it, per [Puppeteer's own `ElementHandle` guidance](https://pptr.dev/api/puppeteer.elementhandle).
|
|
222
236
|
|
|
237
|
+
### A picture of each failing element
|
|
238
|
+
|
|
239
|
+
Opt in with `.screenshots()`, and each occurrence the scan flags gets a `screenshot` field: a picture of the element, with a box drawn around it, or the reason there is none.
|
|
240
|
+
|
|
241
|
+
```js
|
|
242
|
+
const results = await new A11yCoreBuilder({ page })
|
|
243
|
+
.screenshots({ dir: 'a11y-shots', padding: 16 })
|
|
244
|
+
.analyze();
|
|
245
|
+
|
|
246
|
+
const [first] = results.checksResults.filter((r) => r.outcome === 'fail');
|
|
247
|
+
first.occurrences[0].screenshot;
|
|
248
|
+
// { path: 'a11y-shots/element-3f9a1c07.png', box: { x: 20, y: 20, width: 120, height: 40 } }
|
|
249
|
+
```
|
|
250
|
+
|
|
251
|
+
| Option | Default | |
|
|
252
|
+
|---|---|---|
|
|
253
|
+
| `dir` | none | Write each picture there. Without it, each comes back as `{ buffer, box }`, a PNG for you to store your own way. |
|
|
254
|
+
| `outcomes` | `['fail']` | Which occurrences to picture. For contrast, `['fail', 'cantTell']` shows the background the engine couldn't judge. |
|
|
255
|
+
| `padding` | `0` | CSS pixels of context around the element. |
|
|
256
|
+
| `highlight` | `true` | Draw a box around the element, over the page; the element itself is never restyled. |
|
|
257
|
+
| `max` | `50` | At most this many pictures per scan, frames included. |
|
|
258
|
+
|
|
259
|
+
- **One picture per element.** Several rules can flag the same element; it's pictured once, and each of their occurrences carries the same `screenshot`. A file is named after where the element is, so it keeps its name from run to run, and `formatFailures()` names it under each finding (` screenshot: a11y-shots/element-3f9a1c07.png`).
|
|
260
|
+
- **`box`** is where the element shows in the picture, in CSS pixels; the PNG is larger by the device pixel ratio. `cropped: true` says only part of it shows, as for an element taller than the viewport, which is pictured from its top-left corner.
|
|
261
|
+
- **No picture, and why**: `{ skipped }` with `'no-element'` (no selector, or nothing matches it any more), `'page-level'` (a finding about the whole page, on `<html>`, `<head>` or `<body>`), `'not-rendered'` (such as `display: none`), `'zero-size'`, `'off-screen'` (such as `left: -9999px`), `'max-reached'`, or `'capture-failed'` with the browser's `error`. A failed picture never fails the scan.
|
|
262
|
+
- **The page is put back.** Each element is scrolled into view for its picture, and afterwards every scroll position is restored and the box removed, also when a picture fails. Something drawn over the element, such as a sticky header, shows as it does on screen.
|
|
263
|
+
- **Frames.** With `.frames(true)`, an element in an `<iframe>`, cross-origin ones included, is pictured on the page as it shows there.
|
|
264
|
+
- **Off by default.** Pictures of real pages can hold personal data, and they end up as CI artifacts.
|
|
265
|
+
|
|
266
|
+
The pictures are taken right after each frame's scan, before `.reportOnly()` trims the result, and combine with `.elementRef(true)`. Focus, hover, animations or content that loads late can still differ from what the scan saw. An option it can't use throws a `TypeError` with `code: 'INVALID_ENGINE_OPTIONS'` at the call, and so does `.analyze()` with `options({ output: { includeSelector: false } })`, since each element is found by its selector. Works in Chrome and Firefox.
|
|
267
|
+
|
|
268
|
+
### Findings that need review: leans and how to check
|
|
269
|
+
|
|
270
|
+
A `cantTell` is a question for a person: the engine couldn't prove the answer from the page. With `@surea11y/core` 1.14, a question says more:
|
|
271
|
+
|
|
272
|
+
- **Which way it leans.** Where the page's evidence points one way, the occurrence has a `lean`: `toward` (`'fail'` or `'pass'`), `why`, and sometimes a `caution` saying what could make it wrong. A skipped heading level leans fail; `aria-checked` on a native checkbox leans pass. A lean counted against the W3C ACT test cases on five cases or more also says how often it was right (`measured`). The outcome stays `cantTell` either way. See core's [`LEANS.md`](https://github.com/SureA11y/core/blob/main/docs/LEANS.md).
|
|
273
|
+
- **How to check it.** Each question of a core rule carries `howToCheck`: `steps` starting from the element it names, and what a person sees if it passes (`passWhen`) or fails (`failWhen`), in the scan's locale. The engine in the page leaves them out; `analyze()` adds them, with the steps of your packs' rules too.
|
|
274
|
+
|
|
275
|
+
`formatFailures()` shows both: each question says beside its severity whether it likely fails, likely passes or needs review, then why, the caution, and with `{ howToCheck: true }` the steps:
|
|
276
|
+
|
|
277
|
+
```
|
|
278
|
+
2) heading-order (minor, likely fails): This heading jumps from level 1 to level 3, skipping a level.
|
|
279
|
+
at html > body > main > h3
|
|
280
|
+
Go down one level at a time, so an <h2> is followed by an <h3> rather than an <h4>, and the outline of the page stays easy to follow.
|
|
281
|
+
Why it likely fails: The heading skips a level after the one before it.
|
|
282
|
+
How to check:
|
|
283
|
+
1. Find the heading the report names and note its level and the previous heading's level (from the report or the Accessibility pane).
|
|
284
|
+
...
|
|
285
|
+
```
|
|
286
|
+
|
|
287
|
+
To gate a test on the questions that likely fail as well as the failures, use `@surea11y/core`'s `leaningFailures(results)`, which works on this binding's results (a `.frames(true)` tree included). It leaves out the rules whose criteria are outside the scan's target, and with `{ wcagOnly: true }` the best-practice rules too:
|
|
288
|
+
|
|
289
|
+
```js
|
|
290
|
+
const { leaningFailures } = require('@surea11y/core');
|
|
291
|
+
|
|
292
|
+
const results = await new A11yCoreBuilder({ page }).analyze();
|
|
293
|
+
const failures = results.checksResults.filter((r) => r.outcome === 'fail');
|
|
294
|
+
assert.ok(
|
|
295
|
+
failures.length === 0 && leaningFailures(results).length === 0,
|
|
296
|
+
formatFailures(results, { outcomes: ['fail', 'leanFail'] })
|
|
297
|
+
);
|
|
298
|
+
```
|
|
299
|
+
|
|
300
|
+
Don't trim such a result with `.reportOnly(['fail'])` first: it drops the `cantTell` rules, and their leans with them. `.reportOnly()` filters whole rules by their outcome, while a rule's occurrences can sit in different tiers (`occurrenceOutcome`), which `formatFailures()` reads one by one. For CI reports, core's `renderJunitReport(results, { leanFailAs: 'failure' })` and `renderSarifReport(results, { leanFailAs: 'error' })` gate on the same findings, and both carry the steps.
|
|
301
|
+
|
|
223
302
|
### Web components: the internals hook
|
|
224
303
|
|
|
225
304
|
Many web components keep their `ElementInternals` in a private field and name themselves, set their states or give themselves a role through it:
|
|
@@ -254,6 +333,63 @@ With it, the checkbox above passes, an unnamed component that attaches internals
|
|
|
254
333
|
- **For test and audit runs.** The hook wraps `HTMLElement.prototype.attachInternals` (components get the same internals back), adds a stack frame to errors thrown through it, and keeps its record under a global symbol, where any script on the page can read every component's internals. That's why it's opt-in.
|
|
255
334
|
- **Without it**, `analyze()` says so once per scan when it asked about such components (`1 custom element was asked about because the scan could not read...`), and `getScanNotes()` gives that note as `kind: 'internals-hook'`.
|
|
256
335
|
|
|
336
|
+
### Click handlers added from script: the listener hook
|
|
337
|
+
|
|
338
|
+
Most pages add their click handlers from script, where no page script can list them afterwards:
|
|
339
|
+
|
|
340
|
+
```html
|
|
341
|
+
<div class="save" role="button" tabindex="0">Save</div>
|
|
342
|
+
<script>
|
|
343
|
+
document.querySelector('.save').addEventListener('click', save);
|
|
344
|
+
</script>
|
|
345
|
+
```
|
|
346
|
+
|
|
347
|
+
Enter and Space don't fire `click` on a `<div>`, so this button does nothing from the keyboard. Without help the scan can't see the listener, so `click-handler-keyboard-operable` doesn't report the element at all. `A11yCoreBuilder.installListenerHook(page)` installs `@surea11y/core`'s opt-in listener hook (core 1.14.0 and later), which records the click, key, focus and mouse listeners a page adds, so the keyboard rules judge them. Call it **before** `page.goto()`, as the internals hook:
|
|
348
|
+
|
|
349
|
+
```js
|
|
350
|
+
const page = await browser.newPage();
|
|
351
|
+
await A11yCoreBuilder.installListenerHook(page); // before goto
|
|
352
|
+
await page.goto('https://example.com/');
|
|
353
|
+
|
|
354
|
+
const results = await new A11yCoreBuilder({ page }).analyze();
|
|
355
|
+
results.engine.environment.listenerHook; // 'early'
|
|
356
|
+
```
|
|
357
|
+
|
|
358
|
+
With it:
|
|
359
|
+
|
|
360
|
+
- **The button above fails** `click-handler-keyboard-operable` (`CLICK_HANDLER_NO_KEY_LISTENER`): it's a focusable control with no key listener on it, inside it, above it, on the document or on the window. Once it listens for `keydown`, it passes.
|
|
361
|
+
- **A key listener only above the element** (on an ancestor, the document or the window) is asked about: it may handle this element's keys, or only others'.
|
|
362
|
+
- **A click listener on a container**, as a framework that delegates events from its root adds, makes no element inside it a candidate, so delegated handlers never fail.
|
|
363
|
+
- **Pointer listeners** added from script are asked about by `mouse-only-event-handlers`, unless the element also has a keyboard equivalent.
|
|
364
|
+
- **`widget-keyboard-focusable`** counts the listeners too when it asks about a widget Tab never reaches.
|
|
365
|
+
|
|
366
|
+
It works in Chrome and Firefox.
|
|
367
|
+
|
|
368
|
+
- **Before the page loads.** Only a hook that ran before the page's scripts proves an element has no key listener. Called after `page.goto()`, it has no effect until the next navigation, and a new tab the page opens itself doesn't get it.
|
|
369
|
+
- **For test and audit runs.** The hook wraps `addEventListener`, `removeEventListener` and the `on…` property setters (listeners themselves aren't wrapped, and run as before), and keeps its record under a global symbol. That's why it's opt-in.
|
|
370
|
+
- **Without it**, `analyze()` says once per scan when findings the hook would have decided were judged without it (`1 finding (click-handler-keyboard-operable) was judged without seeing the listeners the page adds from script...`), and `getScanNotes()` gives that note as `kind: 'listener-hook'`, with `findingCount` and the `rules`.
|
|
371
|
+
|
|
372
|
+
Core's [`INTEGRATION.md`](https://github.com/SureA11y/core/blob/main/docs/INTEGRATION.md#seeing-listeners-added-from-script-the-listener-hook) has the details, and its binding authors' guide the reason codes each hook decides.
|
|
373
|
+
|
|
374
|
+
### Live regions: the live-region hook and announcements()
|
|
375
|
+
|
|
376
|
+
`A11yCoreBuilder.installLiveRegionHook(page)` installs `@surea11y/core`'s opt-in live-region hook (core 1.14.0 and later), which records what the page's live regions are given while it runs. The scan then asks about a region added with its text already in it, and one shown and filled at once, which screen readers commonly don't announce. And `A11yCoreBuilder.announcements(page)` returns what the page made available to announce, so a test can check that an action told the user something:
|
|
377
|
+
|
|
378
|
+
```js
|
|
379
|
+
const page = await browser.newPage();
|
|
380
|
+
await A11yCoreBuilder.installLiveRegionHook(page); // before goto
|
|
381
|
+
await page.goto('https://example.com/settings');
|
|
382
|
+
|
|
383
|
+
await page.click('#save');
|
|
384
|
+
const said = await A11yCoreBuilder.announcements(page);
|
|
385
|
+
// [{ text: 'Saved', politeness: 'polite', time: 1234.5, order: 7, behindModal: false, selector: '#status' }]
|
|
386
|
+
assert.ok(said.some((a) => a.text === 'Saved'));
|
|
387
|
+
```
|
|
388
|
+
|
|
389
|
+
Each entry names its region by `selector` (and `shadowHostSelectors` inside a shadow root; `null` for a region that has since left the page, such as a toast). It's `null` without the hook. A text given to a region behind an open modal dialog, which assistive technology did not get, is left out unless you pass `{ includeBehindModal: true }`, and comes marked `behindModal: true`. This is what the page made available to announce, not what a screen reader said. The hook only observes, with one `MutationObserver`; see core's [`INTEGRATION.md`](https://github.com/SureA11y/core/blob/main/docs/INTEGRATION.md#seeing-what-live-regions-are-given-the-live-region-hook).
|
|
390
|
+
|
|
391
|
+
With it, `live-region-announcements` also asks about a region the page added with its text already in it (`LIVE_REGION_INSERTED_WITH_CONTENT`; `role="alert"` is left out, since an alert added that way is announced) and a hidden region shown and filled at once (`LIVE_REGION_SHOWN_AND_FILLED`), even if it has left the page since, like a toast. The result records the hook in `engine.environment.liveRegionHook`, and without it `getScanNotes()` gives a `'live-region-hook'` note when findings it would have decided were judged without it.
|
|
392
|
+
|
|
257
393
|
### Forced colors
|
|
258
394
|
|
|
259
395
|
A page shown in forced colors (Windows high contrast) draws in the user's colors, not its own. `results.engine.environment.forcedColors` says which it was: `'active'` or `'none'`. To check a page under forced colors on purpose, emulate it before scanning:
|
|
@@ -266,6 +402,24 @@ results.engine.environment.forcedColors; // 'active'
|
|
|
266
402
|
|
|
267
403
|
This works in Chrome. In Firefox, Puppeteer can't emulate it: `emulateMediaFeatures()` throws, saying it needs CDP. The contrast rules still measure the page's own colors under forced colors, since WCAG judges contrast in those, so results match a scan with forced colors off; a contrast finding the engine couldn't measure that way carries `details.forcedColors: true`. When forced colors were active, `formatFailures()` adds a line saying so, since it's easy to miss on a CI agent with high contrast turned on.
|
|
268
404
|
|
|
405
|
+
### Dark mode and phone width: scans under conditions
|
|
406
|
+
|
|
407
|
+
A page can fail differently in dark mode or at phone width: text that reads well on white fails contrast on a dark background, and a target big enough at 1280 pixels shrinks at 320. `.conditions()` scans the page as it is, then under each condition, and returns one result:
|
|
408
|
+
|
|
409
|
+
```js
|
|
410
|
+
const results = await new A11yCoreBuilder({ page })
|
|
411
|
+
.conditions([{ colorScheme: 'dark' }, { width: 320 }, { colorScheme: 'dark', width: 320 }])
|
|
412
|
+
.analyze();
|
|
413
|
+
```
|
|
414
|
+
|
|
415
|
+
A condition sets a color scheme (`'light'` or `'dark'`, with `page.emulateMediaFeatures()`), a viewport width in CSS pixels (with `page.setViewport()`, keeping the rest of the viewport), or both. The viewport and color scheme are put back after the last scan, even when one throws. In Firefox, widths work; a color scheme needs the DevTools protocol, which Puppeteer has only in Chrome, so `.analyze()` rejects before any scan when a condition sets one there.
|
|
416
|
+
|
|
417
|
+
- A rule's outcome is its worst across the scans, so a contrast failure only in dark mode fails the rule.
|
|
418
|
+
- An occurrence is listed once per element, rule and reason code, with the `conditions` it appeared under (`['default', 'dark']`); `formatFailures()` prints them as `seen in: default, dark`.
|
|
419
|
+
- `results.conditionRuns` lists each scan's condition and `engine.environment`.
|
|
420
|
+
|
|
421
|
+
Each condition is a full scan, so three conditions take about four times as long as one scan. `.frames(true)` can't be combined with `.conditions()` yet. A picture taken with `.screenshots()` under a condition has the condition in its file name.
|
|
422
|
+
|
|
269
423
|
### Registering a custom rule at runtime
|
|
270
424
|
|
|
271
425
|
`@surea11y/core` supports registering additional rules per-scan via `engineOptions.customRules`. Use `.withCustomRules()` to register one:
|
|
@@ -321,6 +475,14 @@ results.engine.profile; // 'en301549-v4.1.1'
|
|
|
321
475
|
|
|
322
476
|
A pack brings rules, variants of core's rules, a standard or a checklist, and their profiles and messages, from a package of its own: a national standard such as RGAA, or your organisation's accessibility policy. `@surea11y/core` runs a pack as it runs its own rules and standards, so its results, rollups and report entries look like core's. Packs need `@surea11y/core` 1.11.1 or later.
|
|
323
477
|
|
|
478
|
+
Install a published pack in your project, beside core and this package:
|
|
479
|
+
|
|
480
|
+
```bash
|
|
481
|
+
npm install @surea11y/core @surea11y/puppeteer puppeteer @acme/a11y-policy
|
|
482
|
+
```
|
|
483
|
+
|
|
484
|
+
Your project, this package and the pack then share one copy of core, so the core that checks the pack is the one that runs it. With two copies, a scan can skip the pack (see "When a pack doesn't run" below).
|
|
485
|
+
|
|
324
486
|
`.withPacks()` registers packs in the page, and in every frame with `.frames(true)`, before the scan; a pack's profile is chosen with `.options({ profile })`:
|
|
325
487
|
|
|
326
488
|
```js
|
|
@@ -342,7 +504,15 @@ A pack's own rules appear in `checksResults` like core's, with ids that start wi
|
|
|
342
504
|
|
|
343
505
|
**Writing a pack.** A pack is an object made with `definePack` from `@surea11y/core/pack`. [`examples/acme-policy-pack.js`](./examples/acme-policy-pack.js) is a small one: a house rule, a checklist profile (WCAG 2.2 A and AA, `region`, and the house rule) and two checklist items. `npm run example:pack` scans a page with it, and [`examples/e2e-test-example.test.js`](./examples/e2e-test-example.test.js) uses it as a test gate. For a pack of your own, `npx surea11y-pack new <folder>` (from `@surea11y/core`) writes a package that works as generated, with its tests, docs and lint; core's [`PACKS.md`](https://github.com/SureA11y/core/blob/main/docs/PACKS.md) is the guide.
|
|
344
506
|
|
|
345
|
-
**When a pack doesn't run.** `.withPacks()` builds the page's script with the `@surea11y/core` this binding loads, and checks each pack as it does: `.analyze()` throws before scanning for a pack that core can't run, such as one whose `core` range leaves out the installed core, or whose profile names a rule that doesn't exist. A pack the page then doesn't run (one named with a raw `.options({ packs })` and never registered, or a page running another core version, when two copies of core are installed) is listed in `results.skippedPacks` with the reason. `getScanGaps()` reports that as `'pack-skipped'`, and `.analyze()` warns about it, so a test gate that asserts on `getScanGaps(results)` fails rather than passing with the pack's checks never run.
|
|
507
|
+
**When a pack doesn't run.** `.withPacks()` builds the page's script with the `@surea11y/core` this binding loads, and checks each pack as it does: `.analyze()` throws before scanning for a pack that core can't run, such as one whose `core` range leaves out the installed core, or whose profile names a rule that doesn't exist. A pack the page then doesn't run (one named with a raw `.options({ packs })` and never registered, or a page running another core version, when two copies of core are installed) is listed in `results.skippedPacks` with the reason. `getScanGaps()` reports that as `'pack-skipped'`, and `.analyze()` warns about it, so a test gate that asserts on `getScanGaps(results)` fails rather than passing with the pack's checks never run.
|
|
508
|
+
|
|
509
|
+
### Style sheets from another origin
|
|
510
|
+
|
|
511
|
+
A page's script can't read the rules of a style sheet served from another origin (a CDN, a fonts service), so a check that reads the CSS, such as `css-orientation-lock`, can't tell whether it holds an orientation lock and asks about it. With `@surea11y/core` 1.14.0 or later, `.analyze()` asks the page which sheets it can't read, fetches them from Node (without the browser's cookies), and gives core their text, which it then checks. It's on by default, as axe fetches such sheets; each request is given up after five seconds, and a sheet that can't be fetched leaves the check asking as before. To send no request but the page's own:
|
|
512
|
+
|
|
513
|
+
```js
|
|
514
|
+
await new A11yCoreBuilder({ page }).fetchStyleSheets(false).analyze();
|
|
515
|
+
```
|
|
346
516
|
|
|
347
517
|
### Element addressing beyond a CSS selector
|
|
348
518
|
|
|
@@ -374,7 +544,23 @@ try {
|
|
|
374
544
|
|
|
375
545
|
## TypeScript
|
|
376
546
|
|
|
377
|
-
`src/A11yCoreBuilder.d.ts` (re-exported from `src/index.d.ts`, wired up via `package.json`'s `types` field) ships types for the whole builder API plus `@surea11y/core`'s native result shapes (`A11yCoreResult`, `CheckResult`, `Occurrence`, `CompositeResult`, etc.). The result shapes are `@surea11y/core`'s own types (its `ScanResult` and the rest), with `elementHandle` added to an occurrence, so they follow the engine: `engine.version`, `contextMatch`, `skippedCustomRules`, `shadowHostSelectors` and `margin` are all declared. `EngineError`, `ScanGap`, `ScanNote` and `EngineErrorCode` come from `@surea11y/binding-base`, and so do the types of `withWcag()` and `wcagLevel()` (`WcagVersion`, `WcagLevelInput`), of `plannedChecks()`/`plannedCriteria()` (`PlannedCheck`, `PlannedCriterion`)
|
|
547
|
+
`src/A11yCoreBuilder.d.ts` (re-exported from `src/index.d.ts`, wired up via `package.json`'s `types` field) ships types for the whole builder API plus `@surea11y/core`'s native result shapes (`A11yCoreResult`, `CheckResult`, `Occurrence`, `CompositeResult`, etc.). The result shapes are `@surea11y/core`'s own types (its `ScanResult` and the rest), with `elementHandle` added to an occurrence, so they follow the engine: `engine.version`, `contextMatch`, `skippedCustomRules`, `shadowHostSelectors` and `margin` are all declared. `EngineError`, `ScanGap`, `ScanNote` and `EngineErrorCode` come from `@surea11y/binding-base`, and so do the types of `withWcag()` and `wcagLevel()` (`WcagVersion`, `WcagLevelInput`), of `plannedChecks()`/`plannedCriteria()` (`PlannedCheck`, `PlannedCriterion`) of `withPacks()`, which takes a pack made with `definePack` (`PackLike`), and of `.screenshots()` (`ScreenshotOptions`, and `OccurrenceScreenshot` for an occurrence's `screenshot`). `A11yCoreBuilder.installInternalsHook(page)`, `installListenerHook(page)`, `installLiveRegionHook(page)` and `announcements(page)` are typed as static methods, the last resolving to `LocatedAnnouncement[] | null` (from `@surea11y/binding-base`). Code that handles every `ScanGap` kind it knows and treats the rest in an `else` branch needs a branch for `'pack-skipped'`, which carries `pack` rather than `selectors`. `analyze()` is typed `Promise<A11yCoreResult | A11yCoreMultiFrameResult>` — narrow on `'topFrame' in results` (or cast, if you already know which mode you called) to get the specific shape back, since a fluent builder can't statically track that `.frames(true)` was called earlier in the chain. `puppeteer` is a `peerDependencies` entry (not just `devDependencies`) since the class's `page` argument and `Occurrence#elementHandle` both come from it — consumers need their own `puppeteer` install for the types to resolve, same as they already do to construct a `Page` in the first place.
|
|
548
|
+
|
|
549
|
+
## What changes with `@surea11y/core` 1.14
|
|
550
|
+
|
|
551
|
+
With `@surea11y/core` 1.14.0, what a scan through this binding shows differently (core's [`CHANGELOG.md`](https://github.com/SureA11y/core/blob/main/CHANGELOG.md) has the full list):
|
|
552
|
+
|
|
553
|
+
- **Status messages.** `live-region-announcements` (4.1.3) asks about a live region hidden with `aria-hidden` or `inert`, or left `aria-busy`. With [`installLiveRegionHook()`](#live-regions-the-live-region-hook-and-announcements) it also asks about one added with its text or shown and filled at once, and `announcements()` reads what the page made available to announce, each region named by its selector.
|
|
554
|
+
- **Listeners added from script.** With [`installListenerHook()`](#click-handlers-added-from-script-the-listener-hook), `click-handler-keyboard-operable` judges a click listener added with `addEventListener` as an inline `onclick`, and fails a focusable control that no key listener can reach (`CLICK_HANDLER_NO_KEY_LISTENER`); `mouse-only-event-handlers` asks about pointer listeners added from script. Both rules' messages now say "click handler" rather than "onclick handler".
|
|
555
|
+
- **Roles that depend on context.** `aria-allowed-attr` no longer fails `aria-expanded` on a text input whose `list` names a `<datalist>` (a combobox), and now judges `<td>`: `cell` in a table, `gridcell` in a grid. `label-in-name` checks a `<td>` in a grid. `heading-order` and `page-has-heading-one` count a heading marked `role="none"` that can take focus or has a global ARIA attribute, as browsers do.
|
|
556
|
+
- **Style sheets from another origin are checked.** `.analyze()` fetches, from Node, the style sheets the page can't read and core checks them, so `css-orientation-lock` finds a lock in a CDN's CSS instead of asking (`.fetchStyleSheets(false)` turns it off). [More](#style-sheets-from-another-origin).
|
|
557
|
+
- **No WCAG criterion passes on its rules alone.** A rollup passes only for a criterion whose rules check all it asks, and none is listed as checked in full yet, so where its rules all pass it is `cantTell` (`composite.rollup.cantTell.partialCheck`). A rollup whose rules all found nothing is `notApplicable` only for 2.4.3, 2.4.4, 2.4.7, 2.4.9, 2.5.3 and 4.1.1, whose rules find every case, and `cantTell` otherwise (`composite.rollup.cantTell.partialCoverage`). `page-title-patterns` asks about every page title, so 2.4.2 is `cantTell` on a page with one. A gate that asserted a criterion `pass` or `notApplicable` now sees `cantTell`; gate on failures (`getGatingFailures()`, or `outcome === 'fail'`) instead.
|
|
558
|
+
- **New checks.** `click-handler-keyboard-operable` (2.1.1, 2.1.3) fails a button-like role with a click handler the keyboard can't reach, and asks about one with no key handler. `focus-not-removed-by-script` (2.1.1, 2.4.7) fails an element whose `onfocus` only blurs it. `aria-owns-valid` (1.3.1, 4.1.2) fails an element owned twice. These ask, and never fail: `widget-keyboard-focusable` (a widget Tab never reaches), `invalid-field-error-message` (3.3.1), `live-region-announcements` (4.1.3), `aria-expanded-state-mismatch`, `moving-content-pausable` (2.2.2), `image-of-text` (1.4.5), and the best practices `label-for-valid` and `control-name-title-only`.
|
|
559
|
+
- **Placeholders below the contrast ratio fail** when the page chose their colours; in the browser's own colours they pass. They used to be questions.
|
|
560
|
+
- **More questions in some places**, fewer in others: `css-hidden-focus` asks about a link in a closed off-canvas menu or a container clipped to nothing; contrast is measured over solid backgrounds, empty background layers, `::before` strips and drop shadows it used to ask about; `link-name-quality` knows more French generic phrases.
|
|
561
|
+
- **Questions lean, and say how to answer them.** A `cantTell` occurrence can carry a `lean` (which way the evidence points, and why) and carries `howToCheck` (the steps to answer it), which `analyze()` adds. `formatFailures()` lists findings in the order a review takes and shows both. [More](#findings-that-need-review-leans-and-how-to-check).
|
|
562
|
+
- **Two more opt-in hooks.** `A11yCoreBuilder.installListenerHook(page)` lets the keyboard rules see click handlers added from script, and `A11yCoreBuilder.installLiveRegionHook(page)` records what live regions are given, which `A11yCoreBuilder.announcements(page)` returns. [More](#click-handlers-added-from-script-the-listener-hook).
|
|
563
|
+
- **Some reason codes are split by cause** (`LIST_ITEM_ROLE_OVERRIDDEN`, `LIST_ROLE_OVERRIDDEN`, `DUPLICATE_ID_IN_SHADOW_TREE`, `DEFAULT_LANG_INVALID`, `IMAGE_ONLY_CONTROL_CONTENT`, `HEADING_LIKE_NUMBER`, `HEADING_LIKE_LINK`). Core's baselines still match a 1.13 entry to its finding under the new code, and `migrateBaselineEntries()` rewrites a baseline; see core's [`BASELINE.md`](https://github.com/SureA11y/core/blob/main/docs/BASELINE.md#upgrading).
|
|
378
564
|
|
|
379
565
|
## What changes with `@surea11y/core` 1.12
|
|
380
566
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@surea11y/puppeteer",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.5.0",
|
|
4
4
|
"description": "Accessibility (a11y, WCAG) checks for Puppeteer scripts and tests: scan the live page with new A11yCoreBuilder({ page }).analyze() and get only proven violations, with findings that need human review listed separately.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"accessibility",
|
|
@@ -45,8 +45,8 @@
|
|
|
45
45
|
"LICENSE"
|
|
46
46
|
],
|
|
47
47
|
"dependencies": {
|
|
48
|
-
"@surea11y/binding-base": "^1.
|
|
49
|
-
"@surea11y/core": "^1.
|
|
48
|
+
"@surea11y/binding-base": "^1.6.0",
|
|
49
|
+
"@surea11y/core": "^1.14.0"
|
|
50
50
|
},
|
|
51
51
|
"peerDependencies": {
|
|
52
52
|
"puppeteer": ">=22.0.0"
|
package/src/A11yCoreBuilder.d.ts
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
|
-
import type { Page, ElementHandle } from 'puppeteer';
|
|
1
|
+
import type { Page, ElementHandle, Frame } from 'puppeteer';
|
|
2
2
|
import type * as Core from '@surea11y/core';
|
|
3
3
|
|
|
4
4
|
// The result shapes are @surea11y/core's own types (shipped since core
|
|
5
5
|
// 1.9.0, checked there against real scan results), re-exported under the
|
|
6
6
|
// names this file has always used. The binding adds `elementHandle` to an
|
|
7
|
-
// occurrence when .elementRef(true) is used,
|
|
7
|
+
// occurrence when .elementRef(true) is used, `screenshot` when
|
|
8
|
+
// .screenshots() is, and the { topFrame, frames }
|
|
8
9
|
// shape of a .frames(true) scan. See core's docs/OUTPUT_SCHEMA.md for what
|
|
9
10
|
// each field means.
|
|
10
11
|
|
|
@@ -44,9 +45,26 @@ export type {
|
|
|
44
45
|
OccurrenceLocation,
|
|
45
46
|
PackLike,
|
|
46
47
|
WcagVersion,
|
|
47
|
-
WcagLevel
|
|
48
|
+
WcagLevel,
|
|
49
|
+
ScreenshotOptions,
|
|
50
|
+
ScreenshotSkip,
|
|
51
|
+
ScreenshotBox,
|
|
52
|
+
OccurrenceScreenshot,
|
|
53
|
+
LocatedAnnouncement,
|
|
54
|
+
ReviewGroup
|
|
55
|
+
} from '@surea11y/binding-base';
|
|
56
|
+
import type {
|
|
57
|
+
LocatedAnnouncement,
|
|
58
|
+
PackLike,
|
|
59
|
+
WcagVersion,
|
|
60
|
+
WcagLevelInput,
|
|
61
|
+
ScanGap,
|
|
62
|
+
ScanNote,
|
|
63
|
+
PlannedCheck,
|
|
64
|
+
PlannedCriterion,
|
|
65
|
+
ScreenshotOptions,
|
|
66
|
+
OccurrenceScreenshot
|
|
48
67
|
} from '@surea11y/binding-base';
|
|
49
|
-
import type { PackLike, WcagVersion, WcagLevelInput, ScanGap, ScanNote, PlannedCheck, PlannedCriterion } from '@surea11y/binding-base';
|
|
50
68
|
|
|
51
69
|
export type Category = Core.RuleMeta['category'];
|
|
52
70
|
export type LocaleResolutionReason = Core.LocaleResolution['reason'];
|
|
@@ -54,6 +72,8 @@ export type CheckResultMeta = Core.RuleMeta;
|
|
|
54
72
|
export type CompositeResultDetails = Core.CompositeResult['data']['details'];
|
|
55
73
|
|
|
56
74
|
export interface Occurrence extends Core.Occurrence {
|
|
75
|
+
/** With .conditions(): the conditions it was found under, 'default' for the page as it was. */
|
|
76
|
+
conditions?: string[];
|
|
57
77
|
/**
|
|
58
78
|
* Only present when `.elementRef(true)` was used. `null` when this
|
|
59
79
|
* occurrence has no single resolvable target element (e.g. `selector` was
|
|
@@ -61,6 +81,12 @@ export interface Occurrence extends Core.Occurrence {
|
|
|
61
81
|
* A11yCoreBuilder#elementRef.
|
|
62
82
|
*/
|
|
63
83
|
elementHandle?: ElementHandle | null;
|
|
84
|
+
/**
|
|
85
|
+
* Only present when `.screenshots()` was used and this occurrence's own
|
|
86
|
+
* outcome is one it pictures: the picture, or why there is none. The
|
|
87
|
+
* occurrences about the same element share one object.
|
|
88
|
+
*/
|
|
89
|
+
screenshot?: OccurrenceScreenshot;
|
|
64
90
|
}
|
|
65
91
|
|
|
66
92
|
export interface CheckResult extends Omit<Core.CheckResult, 'occurrences'> {
|
|
@@ -69,6 +95,8 @@ export interface CheckResult extends Omit<Core.CheckResult, 'occurrences'> {
|
|
|
69
95
|
|
|
70
96
|
/** surea11y's native top-level result shape -- see docs/OUTPUT_SCHEMA.md. */
|
|
71
97
|
export interface A11yCoreResult extends Omit<Core.ScanResult, 'checksResults'> {
|
|
98
|
+
/** With .conditions(): each scan's condition ('default' first) and environment. */
|
|
99
|
+
conditionRuns?: Array<{ condition: string; environment: Record<string, unknown> | null }>;
|
|
72
100
|
checksResults: CheckResult[];
|
|
73
101
|
}
|
|
74
102
|
|
|
@@ -123,6 +151,28 @@ export class A11yCoreBuilder {
|
|
|
123
151
|
*/
|
|
124
152
|
static installInternalsHook(page: Page): ReturnType<Page['evaluateOnNewDocument']>;
|
|
125
153
|
|
|
154
|
+
/**
|
|
155
|
+
* Installs @surea11y/core's opt-in listener hook in `page`, so the keyboard
|
|
156
|
+
* rules see the event listeners the page adds from script. Call it before
|
|
157
|
+
* page.goto(). Needs @surea11y/core 1.14.0 or later.
|
|
158
|
+
*/
|
|
159
|
+
static installListenerHook(page: Page): ReturnType<Page['evaluateOnNewDocument']>;
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* Installs @surea11y/core's opt-in live-region hook in `page`, which
|
|
163
|
+
* records what its live regions are given. Call it before page.goto().
|
|
164
|
+
* Needs @surea11y/core 1.14.0 or later.
|
|
165
|
+
*/
|
|
166
|
+
static installLiveRegionHook(page: Page): ReturnType<Page['evaluateOnNewDocument']>;
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* What `page`'s live regions were given since it loaded, in order, each
|
|
170
|
+
* region named by its selector; null without the live-region hook. Texts
|
|
171
|
+
* given to a region behind an open modal dialog only with
|
|
172
|
+
* `includeBehindModal: true`.
|
|
173
|
+
*/
|
|
174
|
+
static announcements(page: Page, options?: { includeBehindModal?: boolean }): Promise<LocatedAnnouncement[] | null>;
|
|
175
|
+
|
|
126
176
|
/** Scope the scan to one region. Call multiple times for a multi-region union. */
|
|
127
177
|
include(selector: string): this;
|
|
128
178
|
/**
|
|
@@ -163,7 +213,8 @@ export class A11yCoreBuilder {
|
|
|
163
213
|
/**
|
|
164
214
|
* Where analyze() sends each scan gap instead of console.warn: called once
|
|
165
215
|
* per gap, with the result of the frame it came from, and once per scan
|
|
166
|
-
* for the internals-hook
|
|
216
|
+
* for each of the internals-hook and listener-hook notes (tell them apart
|
|
217
|
+
* by `kind`). `() => {}`
|
|
167
218
|
* silences them, `null` goes back to console.warn. A later call replaces it.
|
|
168
219
|
*/
|
|
169
220
|
logger(fn: ((entry: ScanGap | ScanNote, result: A11yCoreResult) => void) | null): this;
|
|
@@ -180,8 +231,30 @@ export class A11yCoreBuilder {
|
|
|
180
231
|
reportOnly(outcomes: Core.Outcome | Core.Outcome[]): this;
|
|
181
232
|
/** Opt in to also scanning every sub-frame on the page (including cross-origin iframes). */
|
|
182
233
|
frames(enabled?: boolean): this;
|
|
234
|
+
/**
|
|
235
|
+
* Also scan the page under each condition after scanning it as it is
|
|
236
|
+
* (@surea11y/binding-base 1.6.0): a color scheme, a viewport width, or
|
|
237
|
+
* both. analyze() returns one merged result: a rule's outcome is its worst
|
|
238
|
+
* across the scans, each occurrence lists the `conditions` it appeared
|
|
239
|
+
* under, and `conditionRuns` gives each scan's environment. The viewport
|
|
240
|
+
* and scheme are put back afterwards. Not combined with frames(true) yet.
|
|
241
|
+
*/
|
|
242
|
+
conditions(list: ReadonlyArray<ScanCondition> | null): this;
|
|
183
243
|
/** Opt in to resolving each fail/cantTell occurrence's selector to a live ElementHandle. */
|
|
184
244
|
elementRef(enabled?: boolean): this;
|
|
245
|
+
/**
|
|
246
|
+
* Opt in to a picture of each element the scan flags, on its occurrences'
|
|
247
|
+
* `screenshot` field: a Buffer, or a file in `dir`. `false` turns them
|
|
248
|
+
* off. Throws a TypeError with code 'INVALID_ENGINE_OPTIONS' for an option
|
|
249
|
+
* it can't use.
|
|
250
|
+
*/
|
|
251
|
+
screenshots(options?: ScreenshotOptions | boolean): this;
|
|
252
|
+
/**
|
|
253
|
+
* Fetch, from Node, the style sheets the page can't read (another origin's)
|
|
254
|
+
* and give core their text, so checks that read the CSS can check them. On
|
|
255
|
+
* by default; needs @surea11y/core 1.14.0 or later.
|
|
256
|
+
*/
|
|
257
|
+
fetchStyleSheets(enabled?: boolean): this;
|
|
185
258
|
/** The rules this scan will run, worked out in Node with no page (@surea11y/core 1.12.0 and later). */
|
|
186
259
|
plannedChecks(): PlannedCheck[];
|
|
187
260
|
/** The criteria this scan will report in rulesResults, worked out in Node with no page. */
|
|
@@ -200,3 +273,25 @@ export class A11yCoreBuilder {
|
|
|
200
273
|
*/
|
|
201
274
|
analyze(): Promise<A11yCoreResult | A11yCoreMultiFrameResult>;
|
|
202
275
|
}
|
|
276
|
+
|
|
277
|
+
/** The four severities, least to most severe (@surea11y/binding-base 1.6.0 and later). */
|
|
278
|
+
export const SEVERITIES: ReadonlyArray<Core.Severity>;
|
|
279
|
+
|
|
280
|
+
/**
|
|
281
|
+
* The failing rule results that should fail a test: every `fail`, or with
|
|
282
|
+
* `failOnSeverity` only those whose severity is that level or above, as
|
|
283
|
+
* `surea11y scan --fail-on-severity` counts them. `fail` keeps its meaning;
|
|
284
|
+
* the level only picks which failures stop the test. Throws a TypeError for
|
|
285
|
+
* a level that is not a severity. From @surea11y/binding-base 1.6.0.
|
|
286
|
+
*/
|
|
287
|
+
export function getGatingFailures(
|
|
288
|
+
input: A11yCoreResult | ReadonlyArray<CheckResult>,
|
|
289
|
+
opts?: { failOnSeverity?: Core.Severity }
|
|
290
|
+
): CheckResult[];
|
|
291
|
+
|
|
292
|
+
/** A condition to scan the page under with .conditions(). */
|
|
293
|
+
export interface ScanCondition {
|
|
294
|
+
colorScheme?: 'light' | 'dark';
|
|
295
|
+
/** The viewport's width in CSS pixels; its height is kept. */
|
|
296
|
+
width?: number;
|
|
297
|
+
}
|
package/src/A11yCoreBuilder.js
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
const
|
|
3
|
+
const core = require('@surea11y/core');
|
|
4
|
+
|
|
5
|
+
const { runa11yCoreInPage, internalsHookScript } = core;
|
|
4
6
|
const {
|
|
5
7
|
A11yCoreBuilderBase,
|
|
6
8
|
createInPageScan,
|
|
@@ -82,6 +84,19 @@ const inPageScan = createInPageScan(runa11yCoreInPage);
|
|
|
82
84
|
* const [firstFail] = results.checksResults.filter(r => r.outcome === 'fail');
|
|
83
85
|
* await firstFail.occurrences[0].elementHandle.screenshot({ path: 'flagged.png' });
|
|
84
86
|
*
|
|
87
|
+
* Or let the scan take a picture of each element it flags, with
|
|
88
|
+
* `.screenshots()` (@surea11y/binding-base's, see its README): each
|
|
89
|
+
* occurrence gets a `screenshot` field, the picture (a Buffer, or a file in
|
|
90
|
+
* `dir`) or why there is none. The element is scrolled into view and marked
|
|
91
|
+
* with a box drawn over the page, and the page is put back afterwards; in
|
|
92
|
+
* every frame with `.frames(true)`, including cross-origin ones:
|
|
93
|
+
*
|
|
94
|
+
* const results = await new A11yCoreBuilder({ page })
|
|
95
|
+
* .screenshots({ dir: 'a11y-shots', padding: 16 })
|
|
96
|
+
* .analyze();
|
|
97
|
+
* // results.checksResults[i].occurrences[j].screenshot
|
|
98
|
+
* // -> { path: 'a11y-shots/element-3f9a1c07.png', box: { x, y, width, height } }
|
|
99
|
+
*
|
|
85
100
|
* Register your own rule(s) for just this scan with
|
|
86
101
|
* `.withCustomRules([...])` (@surea11y/core's `engineOptions.customRules`
|
|
87
102
|
* escape hatch -- see ../core/docs/ENGINE_OPTIONS.md). Pass a real,
|
|
@@ -110,8 +125,8 @@ const inPageScan = createInPageScan(runa11yCoreInPage);
|
|
|
110
125
|
* top of the first scan's scope rather than replacing it (intentional for
|
|
111
126
|
* "call include() several times for one scan" -- see above -- but a footgun
|
|
112
127
|
* if you hold one instance across multiple assertions).
|
|
113
|
-
* reportOnly()/frames()/elementRef() are the exception: each
|
|
114
|
-
* the previous value rather than merging with it.
|
|
128
|
+
* reportOnly()/frames()/elementRef()/screenshots() are the exception: each
|
|
129
|
+
* call replaces the previous value rather than merging with it.
|
|
115
130
|
*/
|
|
116
131
|
class A11yCoreBuilder extends A11yCoreBuilderBase {
|
|
117
132
|
/**
|
|
@@ -136,6 +151,53 @@ class A11yCoreBuilder extends A11yCoreBuilderBase {
|
|
|
136
151
|
return page.evaluateOnNewDocument(internalsHookScript());
|
|
137
152
|
}
|
|
138
153
|
|
|
154
|
+
/**
|
|
155
|
+
* Installs @surea11y/core's opt-in listener hook in `page`, so the
|
|
156
|
+
* keyboard rules see the event listeners the page adds from script
|
|
157
|
+
* (`addEventListener`, `el.onclick = fn`), which no page script can list.
|
|
158
|
+
* Without it a `<div role="button">` given a click listener from script
|
|
159
|
+
* goes unjudged. Call it before page.goto(), as installInternalsHook():
|
|
160
|
+
* Puppeteer runs it before the page's own scripts in every frame and
|
|
161
|
+
* after each navigation. Needs @surea11y/core 1.14.0 or later. Resolves
|
|
162
|
+
* to what evaluateOnNewDocument() resolves to.
|
|
163
|
+
* @param {import('puppeteer').Page} page
|
|
164
|
+
*/
|
|
165
|
+
static installListenerHook(page) {
|
|
166
|
+
return installHook(page, 'installListenerHook', 'listenerHookScript');
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* Installs @surea11y/core's opt-in live-region hook in `page`, which
|
|
171
|
+
* records what the page's live regions are given while it runs: the
|
|
172
|
+
* scan then asks about a region added with its text already in it, and
|
|
173
|
+
* A11yCoreBuilder.announcements(page) returns what the page made
|
|
174
|
+
* available to announce. Call it before page.goto(), as
|
|
175
|
+
* installInternalsHook(). Needs @surea11y/core 1.14.0 or later.
|
|
176
|
+
* @param {import('puppeteer').Page} page
|
|
177
|
+
*/
|
|
178
|
+
static installLiveRegionHook(page) {
|
|
179
|
+
return installHook(page, 'installLiveRegionHook', 'liveRegionHookScript');
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* What `page`'s live regions were given since it loaded, as the
|
|
184
|
+
* live-region hook recorded it, in order: `[{ text, politeness, time,
|
|
185
|
+
* order, behindModal, selector }]`, each region named by its selector (and
|
|
186
|
+
* `shadowHostSelectors` inside a shadow root; null for a region that has
|
|
187
|
+
* since left the page). null where installLiveRegionHook(page) wasn't
|
|
188
|
+
* called before the page loaded. What the page made available to
|
|
189
|
+
* announce, not what a screen reader said. A text given to a region
|
|
190
|
+
* behind an open modal dialog, which assistive technology did not get, is
|
|
191
|
+
* listed only with `{ includeBehindModal: true }`, marked `behindModal`.
|
|
192
|
+
* Needs @surea11y/core 1.14.0 or later.
|
|
193
|
+
* @param {import('puppeteer').Page} page
|
|
194
|
+
* @param {{ includeBehindModal?: boolean }} [options]
|
|
195
|
+
* @returns {Promise<Array<object>|null>}
|
|
196
|
+
*/
|
|
197
|
+
static announcements(page, options) {
|
|
198
|
+
return new A11yCoreBuilder({ page })._announcementsIn(page, options);
|
|
199
|
+
}
|
|
200
|
+
|
|
139
201
|
constructor({ page, url } = {}) {
|
|
140
202
|
super({ url });
|
|
141
203
|
if (!page || typeof page.evaluate !== 'function') {
|
|
@@ -172,13 +234,30 @@ class A11yCoreBuilder extends A11yCoreBuilderBase {
|
|
|
172
234
|
const runInFrame = async (frameOrPage, frameContextSelector) => {
|
|
173
235
|
const frameUrl = this._url || (typeof frameOrPage.url === 'function' ? frameOrPage.url() : null);
|
|
174
236
|
if (packScript) await frameOrPage.evaluate(packScript);
|
|
237
|
+
// The text of the style sheets the frame can't read, fetched from Node
|
|
238
|
+
// (binding-base 1.6.0 and core 1.14.0; nothing with older ones).
|
|
239
|
+
const frameEngineOptions =
|
|
240
|
+
typeof this._styleSheetEngineOptions === 'function'
|
|
241
|
+
? await this._styleSheetEngineOptions(frameOrPage, engineOptions)
|
|
242
|
+
: engineOptions;
|
|
175
243
|
const result = rethrowEngineError(
|
|
176
|
-
await frameOrPage.evaluate(inPageScan, frameUrl, frameContextSelector,
|
|
244
|
+
await frameOrPage.evaluate(inPageScan, frameUrl, frameContextSelector, frameEngineOptions, runOnly)
|
|
177
245
|
);
|
|
178
246
|
this._warnScanGaps(result, '@surea11y/puppeteer');
|
|
247
|
+
// Right after the frame's scan, before reportOnly(): nothing unless
|
|
248
|
+
// .screenshots() was called.
|
|
249
|
+
if (this._screenshots) await this._screenshotFrame(frameOrPage, result);
|
|
179
250
|
return this._elementRef ? this._attachElementRefs(frameOrPage, result) : result;
|
|
180
251
|
};
|
|
181
252
|
|
|
253
|
+
// .conditions() (binding-base 1.6.0): the page as it is, then under each
|
|
254
|
+
// condition, merged into one result.
|
|
255
|
+
if (this._conditions) {
|
|
256
|
+
return this._applyReportOnly(
|
|
257
|
+
await this._scanUnderConditions(() => runInFrame(this._page, contextSelector), this._conditionDriver())
|
|
258
|
+
);
|
|
259
|
+
}
|
|
260
|
+
|
|
182
261
|
if (!this._scanFrames) {
|
|
183
262
|
return this._applyReportOnly(await runInFrame(this._page, contextSelector));
|
|
184
263
|
}
|
|
@@ -223,6 +302,97 @@ class A11yCoreBuilder extends A11yCoreBuilderBase {
|
|
|
223
302
|
* Mutates and returns the same result object -- it's a fresh object from
|
|
224
303
|
* this scan, not shared external state.
|
|
225
304
|
*/
|
|
305
|
+
/**
|
|
306
|
+
* binding-base's screenshots step for one scanned frame (or the page),
|
|
307
|
+
* with the <iframe>s leading to it: each frame's frameElement(), a handle
|
|
308
|
+
* in its parent, disposed afterwards.
|
|
309
|
+
*/
|
|
310
|
+
async _screenshotFrame(frameOrPage, result) {
|
|
311
|
+
const framePath = [];
|
|
312
|
+
const parentOf = (f) => (typeof f.parentFrame === 'function' ? f.parentFrame() : null);
|
|
313
|
+
for (let f = frameOrPage; parentOf(f); f = parentOf(f)) {
|
|
314
|
+
// null when the frame detached after its scan: binding-base fails
|
|
315
|
+
// that frame's pictures.
|
|
316
|
+
const iframe = await f.frameElement().catch(() => null);
|
|
317
|
+
framePath.unshift({ frame: parentOf(f), iframe });
|
|
318
|
+
}
|
|
319
|
+
try {
|
|
320
|
+
await this._captureScreenshots(result, frameOrPage, framePath);
|
|
321
|
+
} finally {
|
|
322
|
+
await Promise.all(framePath.map((step) => (step.iframe ? step.iframe.dispose().catch(() => {}) : null)));
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
/** For binding-base's screenshots step: runs `fn(...args)` in the frame. */
|
|
327
|
+
_evaluateInFrame(frameOrPage, fn, args) {
|
|
328
|
+
return frameOrPage.evaluate(fn, ...args);
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
/**
|
|
332
|
+
* For binding-base's screenshots step: a PNG of `box`, CSS pixels in the
|
|
333
|
+
* viewport. Puppeteer's clip is relative to the document, so the box is
|
|
334
|
+
* moved by the page's scroll; captureBeyondViewport: false keeps Chrome
|
|
335
|
+
* from laying the page out again for the picture, as the default would.
|
|
336
|
+
*/
|
|
337
|
+
_captureBox(box, view) {
|
|
338
|
+
return this._page.screenshot({
|
|
339
|
+
clip: { x: box.x + view.scroll.x, y: box.y + view.scroll.y, width: box.width, height: box.height },
|
|
340
|
+
captureBeyondViewport: false
|
|
341
|
+
});
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
/**
|
|
345
|
+
* The driver steps .conditions() scans need: the viewport's width with
|
|
346
|
+
* page.setViewport() (the rest of the viewport kept) and the color scheme
|
|
347
|
+
* with page.emulateMediaFeatures(). Each condition sets both, from the
|
|
348
|
+
* page as it was, so one condition's width or scheme doesn't carry into
|
|
349
|
+
* the next; at the end the viewport goes back, and the page is left dark
|
|
350
|
+
* if it was dark before (a scheme emulated by the caller, or the
|
|
351
|
+
* system's), or with the scheme no longer emulated.
|
|
352
|
+
*/
|
|
353
|
+
_conditionDriver() {
|
|
354
|
+
const page = this._page;
|
|
355
|
+
let viewport = null;
|
|
356
|
+
// The scheme a condition without one goes back to: the one the page was
|
|
357
|
+
// in, named, since clearing the emulation would give the system's, which
|
|
358
|
+
// a caller may have emulated away from.
|
|
359
|
+
let baseScheme = 'light';
|
|
360
|
+
// The scheme is emulated, and put back, only when a condition sets one:
|
|
361
|
+
// page.emulateMediaFeatures() needs the DevTools protocol, which Firefox
|
|
362
|
+
// over WebDriver BiDi doesn't have, where setViewport() works.
|
|
363
|
+
const usesScheme = this._conditions.some((c) => c.colorScheme);
|
|
364
|
+
const scheme = (value) => page.emulateMediaFeatures([{ name: 'prefers-color-scheme', value }]);
|
|
365
|
+
return {
|
|
366
|
+
save: async () => {
|
|
367
|
+
const browser = typeof page.browser === 'function' ? page.browser() : null;
|
|
368
|
+
if (usesScheme && browser && browser.cdpSupported === false) {
|
|
369
|
+
throw new Error(
|
|
370
|
+
'A11yCoreBuilder.conditions(): a colorScheme needs the DevTools protocol (Chrome), which this browser does not offer to Puppeteer; ' +
|
|
371
|
+
'scan the widths alone here, or the color schemes in Chrome.'
|
|
372
|
+
);
|
|
373
|
+
}
|
|
374
|
+
const before = await page.evaluate(() => ({
|
|
375
|
+
width: innerWidth,
|
|
376
|
+
height: innerHeight,
|
|
377
|
+
deviceScaleFactor: devicePixelRatio,
|
|
378
|
+
dark: matchMedia('(prefers-color-scheme: dark)').matches
|
|
379
|
+
}));
|
|
380
|
+
viewport = page.viewport() || { width: before.width, height: before.height, deviceScaleFactor: before.deviceScaleFactor };
|
|
381
|
+
baseScheme = before.dark ? 'dark' : 'light';
|
|
382
|
+
return { viewport };
|
|
383
|
+
},
|
|
384
|
+
apply: async (condition) => {
|
|
385
|
+
await page.setViewport({ ...viewport, width: condition.width || viewport.width });
|
|
386
|
+
if (usesScheme) await scheme(condition.colorScheme || baseScheme);
|
|
387
|
+
},
|
|
388
|
+
restore: async (state) => {
|
|
389
|
+
if (!state) return;
|
|
390
|
+
await page.setViewport(state.viewport);
|
|
391
|
+
if (usesScheme) await scheme(baseScheme);
|
|
392
|
+
}
|
|
393
|
+
};
|
|
394
|
+
}
|
|
395
|
+
|
|
226
396
|
async _attachElementRefs(frameOrPage, result) {
|
|
227
397
|
if (!Array.isArray(result.checksResults)) return result;
|
|
228
398
|
for (const check of result.checksResults) {
|
|
@@ -241,6 +411,18 @@ class A11yCoreBuilder extends A11yCoreBuilderBase {
|
|
|
241
411
|
}
|
|
242
412
|
}
|
|
243
413
|
|
|
414
|
+
// One of core's hook scripts (1.14.0 and later for the listener and
|
|
415
|
+
// live-region hooks), registered to run before the page's own scripts.
|
|
416
|
+
function installHook(page, method, scriptName) {
|
|
417
|
+
if (!page || typeof page.evaluateOnNewDocument !== 'function') {
|
|
418
|
+
throw new TypeError(`A11yCoreBuilder.${method}() requires a Puppeteer Page (with an .evaluateOnNewDocument() method).`);
|
|
419
|
+
}
|
|
420
|
+
if (typeof core[scriptName] !== 'function') {
|
|
421
|
+
throw new Error(`A11yCoreBuilder.${method}() needs @surea11y/core 1.14.0 or later, which has ${scriptName}().`);
|
|
422
|
+
}
|
|
423
|
+
return page.evaluateOnNewDocument(core[scriptName]());
|
|
424
|
+
}
|
|
425
|
+
|
|
244
426
|
// The occurrence's element as an ElementHandle, or null when it is gone (or
|
|
245
427
|
// a shadow host on the way is). A handle to null is disposed, not leaked.
|
|
246
428
|
async function resolveElementHandle(frameOrPage, occurrence) {
|
package/src/index.js
CHANGED
|
@@ -5,9 +5,9 @@ const { formatFailures } = require('./formatFailures');
|
|
|
5
5
|
|
|
6
6
|
// Re-exported from @surea11y/binding-base, as formatFailures is, so a test
|
|
7
7
|
// needs only this package: what a result says it left out, how the page was
|
|
8
|
-
// scanned (forced colors, the
|
|
9
|
-
//
|
|
10
|
-
//
|
|
11
|
-
const { getScanGaps, getScanNotes, formatOccurrenceLocation, EngineError } = require('@surea11y/binding-base');
|
|
8
|
+
// scanned (forced colors, the hooks), an occurrence's location as text, the
|
|
9
|
+
// error analyze() throws for input the engine cannot use, and the failures
|
|
10
|
+
// that fail a test at a severity.
|
|
11
|
+
const { getScanGaps, getScanNotes, formatOccurrenceLocation, EngineError, getGatingFailures, SEVERITIES } = require('@surea11y/binding-base');
|
|
12
12
|
|
|
13
|
-
module.exports = { A11yCoreBuilder, formatFailures, getScanGaps, getScanNotes, formatOccurrenceLocation, EngineError };
|
|
13
|
+
module.exports = { A11yCoreBuilder, formatFailures, getScanGaps, getScanNotes, formatOccurrenceLocation, EngineError, getGatingFailures, SEVERITIES };
|