@surea11y/puppeteer 1.4.2 → 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 CHANGED
@@ -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), and `'internals-hook'` when the scan asked about web components it could have read with the [internals hook](#web-components-the-internals-hook). `analyze()` also prints the internals note, once per scan, and a `.logger()` receives it (check `kind` to tell a note from a gap).
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
 
@@ -251,6 +265,40 @@ first.occurrences[0].screenshot;
251
265
 
252
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.
253
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
+
254
302
  ### Web components: the internals hook
255
303
 
256
304
  Many web components keep their `ElementInternals` in a private field and name themselves, set their states or give themselves a role through it:
@@ -285,6 +333,63 @@ With it, the checkbox above passes, an unnamed component that attaches internals
285
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.
286
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'`.
287
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
+
288
393
  ### Forced colors
289
394
 
290
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:
@@ -297,6 +402,24 @@ results.engine.environment.forcedColors; // 'active'
297
402
 
298
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.
299
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
+
300
423
  ### Registering a custom rule at runtime
301
424
 
302
425
  `@surea11y/core` supports registering additional rules per-scan via `engineOptions.customRules`. Use `.withCustomRules()` to register one:
@@ -383,6 +506,14 @@ A pack's own rules appear in `checksResults` like core's, with ids that start wi
383
506
 
384
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.
385
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
+ ```
516
+
386
517
  ### Element addressing beyond a CSS selector
387
518
 
388
519
  Every occurrence already carries `selector` and (with `.elementRef(true)`, above) a live `ElementHandle`. It also carries `structuralPath` — a sibling-index path from the document root down to the flagged element (e.g. `[1, 0, 2]`) — a more robust identity than a selector string alone, since it survives some DOM changes a selector wouldn't (an id/class rename, for instance). No opt-in needed; it's already on every `fail`/`cantTell` occurrence today. See [`OUTPUT_SCHEMA.md`](https://github.com/SureA11y/core/blob/main/docs/OUTPUT_SCHEMA.md) for the full field description.
@@ -413,7 +544,23 @@ try {
413
544
 
414
545
  ## TypeScript
415
546
 
416
- `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)` is typed as a static method. 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.
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).
417
564
 
418
565
  ## What changes with `@surea11y/core` 1.12
419
566
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@surea11y/puppeteer",
3
- "version": "1.4.2",
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.5.0",
49
- "@surea11y/core": "^1.12.0"
48
+ "@surea11y/binding-base": "^1.6.0",
49
+ "@surea11y/core": "^1.14.0"
50
50
  },
51
51
  "peerDependencies": {
52
52
  "puppeteer": ">=22.0.0"
@@ -1,4 +1,4 @@
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
@@ -49,9 +49,12 @@ export type {
49
49
  ScreenshotOptions,
50
50
  ScreenshotSkip,
51
51
  ScreenshotBox,
52
- OccurrenceScreenshot
52
+ OccurrenceScreenshot,
53
+ LocatedAnnouncement,
54
+ ReviewGroup
53
55
  } from '@surea11y/binding-base';
54
56
  import type {
57
+ LocatedAnnouncement,
55
58
  PackLike,
56
59
  WcagVersion,
57
60
  WcagLevelInput,
@@ -69,6 +72,8 @@ export type CheckResultMeta = Core.RuleMeta;
69
72
  export type CompositeResultDetails = Core.CompositeResult['data']['details'];
70
73
 
71
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[];
72
77
  /**
73
78
  * Only present when `.elementRef(true)` was used. `null` when this
74
79
  * occurrence has no single resolvable target element (e.g. `selector` was
@@ -90,6 +95,8 @@ export interface CheckResult extends Omit<Core.CheckResult, 'occurrences'> {
90
95
 
91
96
  /** surea11y's native top-level result shape -- see docs/OUTPUT_SCHEMA.md. */
92
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 }>;
93
100
  checksResults: CheckResult[];
94
101
  }
95
102
 
@@ -144,6 +151,28 @@ export class A11yCoreBuilder {
144
151
  */
145
152
  static installInternalsHook(page: Page): ReturnType<Page['evaluateOnNewDocument']>;
146
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
+
147
176
  /** Scope the scan to one region. Call multiple times for a multi-region union. */
148
177
  include(selector: string): this;
149
178
  /**
@@ -184,7 +213,8 @@ export class A11yCoreBuilder {
184
213
  /**
185
214
  * Where analyze() sends each scan gap instead of console.warn: called once
186
215
  * per gap, with the result of the frame it came from, and once per scan
187
- * for the internals-hook note (tell them apart by `kind`). `() => {}`
216
+ * for each of the internals-hook and listener-hook notes (tell them apart
217
+ * by `kind`). `() => {}`
188
218
  * silences them, `null` goes back to console.warn. A later call replaces it.
189
219
  */
190
220
  logger(fn: ((entry: ScanGap | ScanNote, result: A11yCoreResult) => void) | null): this;
@@ -201,6 +231,15 @@ export class A11yCoreBuilder {
201
231
  reportOnly(outcomes: Core.Outcome | Core.Outcome[]): this;
202
232
  /** Opt in to also scanning every sub-frame on the page (including cross-origin iframes). */
203
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;
204
243
  /** Opt in to resolving each fail/cantTell occurrence's selector to a live ElementHandle. */
205
244
  elementRef(enabled?: boolean): this;
206
245
  /**
@@ -210,6 +249,12 @@ export class A11yCoreBuilder {
210
249
  * it can't use.
211
250
  */
212
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;
213
258
  /** The rules this scan will run, worked out in Node with no page (@surea11y/core 1.12.0 and later). */
214
259
  plannedChecks(): PlannedCheck[];
215
260
  /** The criteria this scan will report in rulesResults, worked out in Node with no page. */
@@ -228,3 +273,25 @@ export class A11yCoreBuilder {
228
273
  */
229
274
  analyze(): Promise<A11yCoreResult | A11yCoreMultiFrameResult>;
230
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
+ }
@@ -1,6 +1,8 @@
1
1
  'use strict';
2
2
 
3
- const { runa11yCoreInPage, internalsHookScript } = require('@surea11y/core');
3
+ const core = require('@surea11y/core');
4
+
5
+ const { runa11yCoreInPage, internalsHookScript } = core;
4
6
  const {
5
7
  A11yCoreBuilderBase,
6
8
  createInPageScan,
@@ -149,6 +151,53 @@ class A11yCoreBuilder extends A11yCoreBuilderBase {
149
151
  return page.evaluateOnNewDocument(internalsHookScript());
150
152
  }
151
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
+
152
201
  constructor({ page, url } = {}) {
153
202
  super({ url });
154
203
  if (!page || typeof page.evaluate !== 'function') {
@@ -185,8 +234,14 @@ class A11yCoreBuilder extends A11yCoreBuilderBase {
185
234
  const runInFrame = async (frameOrPage, frameContextSelector) => {
186
235
  const frameUrl = this._url || (typeof frameOrPage.url === 'function' ? frameOrPage.url() : null);
187
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;
188
243
  const result = rethrowEngineError(
189
- await frameOrPage.evaluate(inPageScan, frameUrl, frameContextSelector, engineOptions, runOnly)
244
+ await frameOrPage.evaluate(inPageScan, frameUrl, frameContextSelector, frameEngineOptions, runOnly)
190
245
  );
191
246
  this._warnScanGaps(result, '@surea11y/puppeteer');
192
247
  // Right after the frame's scan, before reportOnly(): nothing unless
@@ -195,6 +250,14 @@ class A11yCoreBuilder extends A11yCoreBuilderBase {
195
250
  return this._elementRef ? this._attachElementRefs(frameOrPage, result) : result;
196
251
  };
197
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
+
198
261
  if (!this._scanFrames) {
199
262
  return this._applyReportOnly(await runInFrame(this._page, contextSelector));
200
263
  }
@@ -278,6 +341,58 @@ class A11yCoreBuilder extends A11yCoreBuilderBase {
278
341
  });
279
342
  }
280
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
+
281
396
  async _attachElementRefs(frameOrPage, result) {
282
397
  if (!Array.isArray(result.checksResults)) return result;
283
398
  for (const check of result.checksResults) {
@@ -296,6 +411,18 @@ class A11yCoreBuilder extends A11yCoreBuilderBase {
296
411
  }
297
412
  }
298
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
+
299
426
  // The occurrence's element as an ElementHandle, or null when it is gone (or
300
427
  // a shadow host on the way is). A handle to null is disposed, not leaked.
301
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 internals hook), an occurrence's
9
- // location as text, and the error analyze() throws for input the engine
10
- // cannot use.
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 };