@surea11y/playwright 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 CHANGED
@@ -5,13 +5,13 @@ A Playwright binding for [`@surea11y/core`](https://github.com/SureA11y/core)
5
5
  ## Install
6
6
 
7
7
  ```bash
8
- npm install @surea11y/playwright playwright
8
+ npm install @surea11y/core @surea11y/playwright playwright
9
9
  npx playwright install chromium # every test launches a real browser -- npm install alone doesn't fetch it
10
10
  ```
11
11
 
12
- `@surea11y/core` 1.12.0 or later, the engine, comes with it as a regular dependency, so the line above is all you need, whatever your package manager.
12
+ `@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.
13
13
 
14
- If your project uses core directly too, to write a SARIF log or an HTML report (`@surea11y/core/sarif`, `/report`), read the rule catalogue, or keep a baseline, keep one copy of it, so those read results with the same core that produced them. A compatible range in your own `package.json` (`"@surea11y/core": "^1.12.0"`) is enough: npm installs core once. When yours 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, and the binding uses your copy, which needs to be 1.12.0 or later. 1.4.0 made core a peer dependency instead; 1.4.1 undoes that, because Yarn, npm 6 and npm with `legacy-peer-deps` don't install peers, and a project with an older core pinned couldn't install the binding at all.
14
+ **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.
15
15
 
16
16
  `npm test` (in this repo) only needs Chromium. The cross-browser regression tests in `tests/cross-browser.test.js` (proving this works against Firefox/WebKit too, not just Chromium) additionally need `npx playwright install firefox webkit`. `npm test` also compiles `tests/types/usage.ts` with TypeScript against the shipped types (`typescript` is a dev dependency only).
17
17
 
@@ -84,7 +84,7 @@ The four take a string or an array of strings. `undefined` (a missing config val
84
84
 
85
85
  `.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.
86
86
 
87
- **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.
87
+ **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.
88
88
 
89
89
  ### When `.include()` matches nothing, or doesn't parse
90
90
 
@@ -114,7 +114,7 @@ const results = await new A11yCoreBuilder({ page })
114
114
 
115
115
  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.
116
116
 
117
- `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).
117
+ `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).
118
118
 
119
119
  ### Errors from the engine
120
120
 
@@ -163,9 +163,23 @@ To also fail when the scan left something out (an `.include()` that matched noth
163
163
 
164
164
  See `examples/playwright-test-example.spec.js` for a fuller, runnable version (`npm run example:e2e`) — one test proving real violations get caught (unlabeled button, missing `alt`), one proving a well-formed page passes cleanly.
165
165
 
166
+ ### Failing only on serious problems
167
+
168
+ 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.
169
+
170
+ ```js
171
+ const { A11yCoreBuilder, formatFailures, getGatingFailures } = require('@surea11y/playwright');
172
+
173
+ const results = await new A11yCoreBuilder({ page }).analyze();
174
+ const gate = { failOnSeverity: 'serious' };
175
+ expect(getGatingFailures(results, gate), formatFailures(results, gate)).toEqual([]);
176
+ ```
177
+
178
+ `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.
179
+
166
180
  ### Readable console/CI output on failure
167
181
 
168
- `expect(x).toEqual([])` 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/selector/hint) that you hand to your assertion library's own failure-message parameter, as above. A real failure then prints:
182
+ `expect(x).toEqual([])` 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/selector/hint) 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:
169
183
 
170
184
  ```
171
185
  Error: 1) button-name-present (serious): This button has no accessible name.
@@ -182,7 +196,7 @@ Scanned with @surea11y/core 1.12.0.
182
196
 
183
197
  Given the whole result, as here, it also lists what the scan left out (see `getScanGaps()` above; a scan whose `.include()` matched nothing never reads as "No accessibility violations found.") and its notes (`getScanNotes()`, such as a page shown in forced colors), and ends with the core release that produced the result. It still accepts `results.checksResults` alone, without those two parts. A finding inside a shadow tree is located through its shadow hosts, as `my-app >>> my-card >>> img` (`formatOccurrenceLocation(occurrence)` gives that line on its own); that notation is for reading, not a selector `document.querySelector()` takes. For a `.frames(true)` scan, format `results.topFrame` and each frame on its own: both functions throw a `TypeError` for the `{ topFrame, frames }` shape rather than report it as clean.
184
198
 
185
- ...with Playwright's own raw diff still printed underneath (unavoidable — `toEqual` always includes it), but the readable summary now comes first, where it's actually useful. Deliberately a plain function, not a custom `expect` matcher — no dependency on any particular assertion library, so it works the same with Playwright's `expect`, Jest, Vitest, or a hand-rolled `if`/`throw`. Defaults to `fail`/`cantTell` outcomes (the ones that report findings; a `notApplicable` rule can carry one occurrence saying why it had nothing to judge, which is left out); pass `{ outcomes: [...] }` to narrow further. A thrown rule (`occurrences: []`, `error` set) is still surfaced using its `error` message rather than silently dropped.
199
+ ...with Playwright's own raw diff still printed underneath (unavoidable — `toEqual` always includes it), but the readable summary now comes first, where it's actually useful. Deliberately a plain function, not a custom `expect` matcher — no dependency on any particular assertion library, so it works the same with Playwright's `expect`, Jest, Vitest, or a hand-rolled `if`/`throw`. Defaults to `fail`/`cantTell` outcomes (the ones that report findings; a `notApplicable` rule can carry one occurrence saying why it had nothing to judge, which is left out); 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`. A thrown rule (`occurrences: []`, `error` set) is still surfaced using its `error` message rather than silently dropped.
186
200
 
187
201
  ### Scanning every frame, including cross-origin iframes
188
202
 
@@ -243,6 +257,77 @@ This resolves each occurrence to an `ElementHandle` in its own frame instead of
243
257
 
244
258
  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 [Playwright's own `ElementHandle` guidance](https://playwright.dev/docs/api/class-elementhandle).
245
259
 
260
+ ### A picture of each failing element
261
+
262
+ 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.
263
+
264
+ ```js
265
+ const results = await new A11yCoreBuilder({ page })
266
+ .screenshots({ dir: 'a11y-shots', padding: 16 })
267
+ .analyze();
268
+
269
+ const [first] = results.checksResults.filter((r) => r.outcome === 'fail');
270
+ first.occurrences[0].screenshot;
271
+ // { path: 'a11y-shots/element-3f9a1c07.png', box: { x: 20, y: 20, width: 120, height: 40 } }
272
+ ```
273
+
274
+ | Option | Default | |
275
+ |---|---|---|
276
+ | `dir` | none | Write each picture there. Without it, each comes back as `{ buffer, box }`, a PNG for you to store your own way. |
277
+ | `outcomes` | `['fail']` | Which occurrences to picture. For contrast, `['fail', 'cantTell']` shows the background the engine couldn't judge. |
278
+ | `padding` | `0` | CSS pixels of context around the element. |
279
+ | `highlight` | `true` | Draw a box around the element, over the page; the element itself is never restyled. |
280
+ | `max` | `50` | At most this many pictures per scan, frames included. |
281
+
282
+ - **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`).
283
+ - **`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.
284
+ - **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.
285
+ - **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.
286
+ - **Frames.** With `.frames(true)`, an element in an `<iframe>`, cross-origin ones included, is pictured on the page as it shows there.
287
+ - **Off by default.** Pictures of real pages can hold personal data, and they end up as CI artifacts.
288
+
289
+ 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 Chromium, Firefox and WebKit.
290
+
291
+ ### Findings that need review: leans and how to check
292
+
293
+ 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:
294
+
295
+ - **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).
296
+ - **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.
297
+
298
+ `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:
299
+
300
+ ```
301
+ 2) heading-order (minor, likely fails): This heading jumps from level 1 to level 3, skipping a level.
302
+ at html > body > main > h3
303
+ 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.
304
+ Why it likely fails: The heading skips a level after the one before it.
305
+ How to check:
306
+ 1. Find the heading the report names and note its level and the previous heading's level (from the report or the Accessibility pane).
307
+ ...
308
+ ```
309
+
310
+ 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:
311
+
312
+ ```js
313
+ const { test, expect } = require('@playwright/test');
314
+ const { leaningFailures } = require('@surea11y/core');
315
+ const { A11yCoreBuilder, formatFailures } = require('@surea11y/playwright');
316
+
317
+ test('no failures, and no questions that likely fail', async ({ page }) => {
318
+ await page.goto('https://example.com/');
319
+
320
+ const results = await new A11yCoreBuilder({ page }).analyze();
321
+ const failures = results.checksResults.filter((r) => r.outcome === 'fail');
322
+ expect(
323
+ [...failures, ...leaningFailures(results)],
324
+ formatFailures(results, { outcomes: ['fail', 'leanFail'] })
325
+ ).toEqual([]);
326
+ });
327
+ ```
328
+
329
+ 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.
330
+
246
331
  ### Web components: the internals hook
247
332
 
248
333
  Many web components keep their `ElementInternals` in a private field and name themselves, set their states or give themselves a role through it:
@@ -280,6 +365,57 @@ With it, the checkbox above passes, an unnamed component that attaches internals
280
365
  - **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.
281
366
  - **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'`.
282
367
 
368
+ ### Click handlers added from script: the listener hook
369
+
370
+ Most pages add their click handlers from script, where no page script can list them afterwards:
371
+
372
+ ```html
373
+ <div class="save" role="button" tabindex="0">Save</div>
374
+ <script>
375
+ document.querySelector('.save').addEventListener('click', save);
376
+ </script>
377
+ ```
378
+
379
+ 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(pageOrContext)` 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()`, on the page or its browser context, as the internals hook:
380
+
381
+ ```js
382
+ const context = await browser.newContext();
383
+ await A11yCoreBuilder.installListenerHook(context); // before any page navigates
384
+ const page = await context.newPage();
385
+ await page.goto('https://example.com/');
386
+
387
+ const results = await new A11yCoreBuilder({ page }).analyze();
388
+ results.engine.environment.listenerHook; // 'early'
389
+ ```
390
+
391
+ With `@playwright/test`, install it in a `beforeEach` on the `context` fixture, or on `page` before the test navigates.
392
+
393
+ With it, the button above fails (`CLICK_HANDLER_NO_KEY_LISTENER`: no key listener anywhere a key event from it goes), and `mouse-only-event-handlers` and `widget-keyboard-focusable` count the listeners too. Only a hook installed before the page's scripts (`'early'`) proves a listener is missing; one installed later is `'late'`, and the rules then only ask. It wraps `addEventListener`, `removeEventListener` and the `on…` setters, with the page getting the same results and errors, and keeps its record under a global symbol: install it for test and audit runs. Without it, `getScanNotes()` gives a `'listener-hook'` note when findings it would have decided were judged without it. 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.
394
+
395
+ ### Live regions: the live-region hook and announcements()
396
+
397
+ `A11yCoreBuilder.installLiveRegionHook(pageOrContext)` 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:
398
+
399
+ ```js
400
+ const { test, expect } = require('@playwright/test');
401
+ const { A11yCoreBuilder } = require('@surea11y/playwright');
402
+
403
+ test.beforeEach(async ({ context }) => {
404
+ await A11yCoreBuilder.installLiveRegionHook(context); // before the test navigates
405
+ });
406
+
407
+ test('saving says so', async ({ page }) => {
408
+ await page.goto('https://example.com/settings');
409
+ await page.getByRole('button', { name: 'Save' }).click();
410
+
411
+ const said = await A11yCoreBuilder.announcements(page);
412
+ // [{ text: 'Saved', politeness: 'polite', time: 1234.5, order: 7, behindModal: false, selector: '#status' }]
413
+ expect(said.map((a) => a.text)).toContain('Saved');
414
+ });
415
+ ```
416
+
417
+ 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. `announcements()` reads the page's top frame. 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).
418
+
283
419
  ### Forced colors
284
420
 
285
421
  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, in Chromium, Firefox or WebKit:
@@ -292,6 +428,24 @@ results.engine.environment.forcedColors; // 'active'
292
428
 
293
429
  `browser.newContext({ forcedColors: 'active' })` does the same for a whole context, and `@playwright/test` takes it as a `use` option. 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.
294
430
 
431
+ ### Dark mode and phone width: scans under conditions
432
+
433
+ 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:
434
+
435
+ ```js
436
+ const results = await new A11yCoreBuilder({ page })
437
+ .conditions([{ colorScheme: 'dark' }, { width: 320 }, { colorScheme: 'dark', width: 320 }])
438
+ .analyze();
439
+ ```
440
+
441
+ A condition sets a color scheme (`'light'` or `'dark'`, with `page.emulateMedia()`), a viewport width in CSS pixels (with `page.setViewportSize()`, keeping the height), or both. The viewport and color scheme are put back after the last scan, even when one throws.
442
+
443
+ - A rule's outcome is its worst across the scans, so a contrast failure only in dark mode fails the rule.
444
+ - 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`.
445
+ - `results.conditionRuns` lists each scan's condition and `engine.environment`.
446
+
447
+ 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.
448
+
295
449
  ### Registering a custom rule at runtime
296
450
 
297
451
  `@surea11y/core` supports registering additional rules per-scan via `engineOptions.customRules`. Use `.withCustomRules()` to register one:
@@ -347,6 +501,14 @@ results.engine.profile; // 'en301549-v4.1.1'
347
501
 
348
502
  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.
349
503
 
504
+ Install a published pack in your project, beside core and this package:
505
+
506
+ ```bash
507
+ npm install @surea11y/core @surea11y/playwright playwright @acme/a11y-policy
508
+ ```
509
+
510
+ 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).
511
+
350
512
  `.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 })`:
351
513
 
352
514
  ```js
@@ -368,7 +530,15 @@ A pack's own rules appear in `checksResults` like core's, with ids that start wi
368
530
 
369
531
  **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/playwright-test-example.spec.js`](./examples/playwright-test-example.spec.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.
370
532
 
371
- **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. Install the pack beside the binding, so npm resolves one core for both.
533
+ **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.
534
+
535
+ ### Style sheets from another origin
536
+
537
+ 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 with the page's own request API (so the page's cookies go with them), 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:
538
+
539
+ ```js
540
+ await new A11yCoreBuilder({ page }).fetchStyleSheets(false).analyze();
541
+ ```
372
542
 
373
543
  ### Element addressing beyond a CSS selector
374
544
 
@@ -376,7 +546,22 @@ Every occurrence already carries `selector` and (with `.elementRef(true)`, above
376
546
 
377
547
  ## TypeScript
378
548
 
379
- `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 and the result (`A11yCoreResult`, `CheckResult`, `Occurrence`, `CompositeResult`, etc.). The result types are built on the ones `@surea11y/core` ships, so they carry every field the engine returns (`engine.version`, `engine.environment`, `contextMatch`, `skippedCustomRules`, `shadowHostSelectors`, `margin`, ...); this package adds `elementHandle` and the `.frames(true)` shape. `EngineError`/`EngineErrorCode`, `getScanGaps()`/`ScanGap`, `getScanNotes()`/`ScanNote` and `formatOccurrenceLocation()` are typed too, and so are `withWcag()` and `wcagLevel()` (`WcagVersion`, `WcagLevelInput`), `plannedChecks()`/`plannedCriteria()` (`PlannedCheck`, `PlannedCriterion`), the static `installInternalsHook()`, and `withPacks()`, which takes a pack made with `definePack` (`PackLike`). 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. `playwright` is a `peerDependencies` entry (not just `devDependencies`) since the class's `page` argument and `Occurrence#elementHandle` both come from it — consumers need their own `playwright` install for the types to resolve, same as they already do to construct a `Page` in the first place.
549
+ `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 and the result (`A11yCoreResult`, `CheckResult`, `Occurrence`, `CompositeResult`, etc.). The result types are built on the ones `@surea11y/core` ships, so they carry every field the engine returns (`engine.version`, `engine.environment`, `contextMatch`, `skippedCustomRules`, `shadowHostSelectors`, `margin`, ...); this package adds `elementHandle`, `screenshot` (`OccurrenceScreenshot`) and the `.frames(true)` shape. `EngineError`/`EngineErrorCode`, `getScanGaps()`/`ScanGap`, `getScanNotes()`/`ScanNote` and `formatOccurrenceLocation()` are typed too, and so are `withWcag()` and `wcagLevel()` (`WcagVersion`, `WcagLevelInput`), `plannedChecks()`/`plannedCriteria()` (`PlannedCheck`, `PlannedCriterion`), the static `installInternalsHook()`, `installListenerHook()` and `installLiveRegionHook()` (each taking a `Page` or a `BrowserContext`) and `announcements(page)`, which resolves to `LocatedAnnouncement[] | null`, `formatFailures()`'s review groups (`ReviewGroup`) and `howToCheck` option, `withPacks()`, which takes a pack made with `definePack` (`PackLike`), and `.screenshots()` (`ScreenshotOptions`). 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. `playwright` is a `peerDependencies` entry (not just `devDependencies`) since the class's `page` argument and `Occurrence#elementHandle` both come from it — consumers need their own `playwright` install for the types to resolve, same as they already do to construct a `Page` in the first place.
550
+
551
+ ## What changes with `@surea11y/core` 1.14
552
+
553
+ 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):
554
+
555
+ - **No WCAG criterion passes yet.** A criterion's rollup passes only when its rules check everything 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`). A gate that asserted a criterion `pass` or `notApplicable` now sees `cantTell`; gate on `fail`, as `getGatingFailures()` does.
556
+ - **More questions.** `page-title-patterns` asks about every page title, so 2.4.2 is `cantTell` on a page with one, and `duplicate-id` asks about 4.1.1 under WCAG 2.0 and 2.1 too.
557
+ - **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).
558
+ - **New rules.** `widget-keyboard-focusable` (2.1.1) asks about a widget Tab never reaches. `click-handler-keyboard-operable` (2.1.1, 2.1.3) fails a `role="button"`, `link`, `checkbox` or `switch` with a click handler that nothing can bring keyboard focus to, 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. `moving-content-pausable` (2.2.2) asks about content an animation moves for more than five seconds. `invalid-field-error-message` (3.3.1) asks about a field marked `aria-invalid` whose error message can't be reached. `live-region-announcements` (4.1.3) asks about a live region hidden with `aria-hidden` or `inert`, or left `aria-busy`. `aria-owns-valid` (1.3.1, 4.1.2) fails an element owned twice. `aria-expanded-state-mismatch` (4.1.2) asks about `aria-expanded` that contradicts what its `aria-controls` names, `image-of-text` (1.4.5) whether text drawn in an image could be real text, and the best practices `label-for-valid` and `control-name-title-only` about a `<label for>` that labels nothing and a control named only by its `title`.
559
+ - **Two more opt-in hooks.** With [`installListenerHook()`](#click-handlers-added-from-script-the-listener-hook), the keyboard rules judge click listeners added with `addEventListener`, and fail a focusable control no key listener can reach (`CLICK_HANDLER_NO_KEY_LISTENER`). With [`installLiveRegionHook()`](#live-regions-the-live-region-hook-and-announcements), `live-region-announcements` also asks about a region added with its text or shown and filled at once, and `A11yCoreBuilder.announcements(page)` returns what the page made available to announce.
560
+ - **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).
561
+ - **Contrast is measured on more of what the page draws:** text on a page with no background in each color scheme it can be drawn in, `::first-line` and `::first-letter`, `font-size-adjust`, outlined and shadowed text, solid background layers and drop shadows it used to ask about. A placeholder whose colors the page chose fails below the ratio; in the browser's own colors it isn't reported.
562
+ - **Roles, names and hidden content follow browsers more closely**, among them `aria-allowed-attr` on a text input with a `<datalist>` (a combobox) and on `<td>`, every associated `<label>` joined into a name, and `hidden` that the page's CSS displays again hiding nothing.
563
+ - **A selector at the top of a shadow root** is now written so it can't match a sibling outside it (`img:not(* > *)`), so the selector a result gives, and `elementRef(true)`, point at the right element.
564
+ - **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).
380
565
 
381
566
  ## What changes with `@surea11y/core` 1.12
382
567
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@surea11y/playwright",
3
- "version": "1.4.1",
3
+ "version": "1.5.0",
4
4
  "description": "Accessibility (a11y, WCAG) checks for Playwright 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",
@@ -46,8 +46,8 @@
46
46
  "LICENSE"
47
47
  ],
48
48
  "dependencies": {
49
- "@surea11y/binding-base": "^1.4.0",
50
- "@surea11y/core": "^1.12.0"
49
+ "@surea11y/binding-base": "^1.6.0",
50
+ "@surea11y/core": "^1.14.0"
51
51
  },
52
52
  "peerDependencies": {
53
53
  "playwright": ">=1.0.0"
@@ -1,11 +1,12 @@
1
- import type { Page, BrowserContext, ElementHandle } from 'playwright';
1
+ import type { Page, BrowserContext, ElementHandle, Frame } from 'playwright';
2
2
  import type * as Core from '@surea11y/core';
3
3
 
4
4
  // The result shapes are @surea11y/core's own types (shipped with it since
5
5
  // 1.9.0, and checked there against real scan results), so they follow the
6
6
  // engine instead of a copy of its docs. This file only adds what the
7
7
  // binding puts on top: `elementHandle` on an occurrence with
8
- // .elementRef(true), and the { topFrame, frames } shape of .frames(true).
8
+ // .elementRef(true), `screenshot` with .screenshots(), and the
9
+ // { topFrame, frames } shape of .frames(true).
9
10
  // Every name this file exported before is still exported.
10
11
 
11
12
  import type {
@@ -24,7 +25,9 @@ import type {
24
25
  Margin,
25
26
  MarginDeclaration,
26
27
  ContextMatch,
27
- CompositeResult
28
+ CompositeResult,
29
+ Lean,
30
+ HowToCheck
28
31
  } from '@surea11y/core';
29
32
 
30
33
  export type {
@@ -43,7 +46,9 @@ export type {
43
46
  Margin,
44
47
  MarginDeclaration,
45
48
  ContextMatch,
46
- CompositeResult
49
+ CompositeResult,
50
+ Lean,
51
+ HowToCheck
47
52
  };
48
53
 
49
54
  /**
@@ -55,8 +60,34 @@ export type {
55
60
  * page's scripts broke a JavaScript built-in the engine relies on).
56
61
  */
57
62
  export { EngineError } from '@surea11y/binding-base';
58
- export type { EngineErrorCode, PackLike, WcagVersion, WcagLevel, WcagLevelInput, PlannedCheck, PlannedCriterion } from '@surea11y/binding-base';
59
- import type { PackLike, WcagVersion, WcagLevelInput, ScanGap, ScanNote, PlannedCheck, PlannedCriterion } from '@surea11y/binding-base';
63
+ export type {
64
+ EngineErrorCode,
65
+ PackLike,
66
+ WcagVersion,
67
+ WcagLevel,
68
+ WcagLevelInput,
69
+ PlannedCheck,
70
+ PlannedCriterion,
71
+ ScreenshotOptions,
72
+ ScreenshotSkip,
73
+ ScreenshotBox,
74
+ OccurrenceScreenshot,
75
+ LocatedAnnouncement,
76
+ ReviewGroup
77
+ } from '@surea11y/binding-base';
78
+ import type {
79
+ LocatedAnnouncement,
80
+ ReviewGroup,
81
+ PackLike,
82
+ WcagVersion,
83
+ WcagLevelInput,
84
+ ScanGap,
85
+ ScanNote,
86
+ PlannedCheck,
87
+ PlannedCriterion,
88
+ ScreenshotOptions,
89
+ OccurrenceScreenshot
90
+ } from '@surea11y/binding-base';
60
91
 
61
92
  export type Category = Core.RuleMeta['category'];
62
93
  export type LocaleResolutionReason = Core.LocaleResolution['reason'];
@@ -64,12 +95,20 @@ export type CheckResultMeta = Core.RuleMeta;
64
95
  export type CompositeResultDetails = Core.CompositeResult['data']['details'];
65
96
 
66
97
  export interface Occurrence extends Core.Occurrence {
98
+ /** With .conditions(): the conditions it was found under, 'default' for the page as it was. */
99
+ conditions?: string[];
67
100
  /**
68
101
  * Only present when `.elementRef(true)` was used. `null` when this
69
102
  * occurrence has no single resolvable target element (e.g. `selector` was
70
103
  * `""`, or a shadow host on the way is gone) -- see A11yCoreBuilder#elementRef.
71
104
  */
72
105
  elementHandle?: ElementHandle | null;
106
+ /**
107
+ * Only present when `.screenshots()` was used and this occurrence's own
108
+ * outcome is one it pictures: the picture, or why there is none. The
109
+ * occurrences about the same element share one object.
110
+ */
111
+ screenshot?: OccurrenceScreenshot;
73
112
  }
74
113
 
75
114
  export interface CheckResult extends Omit<Core.CheckResult, 'occurrences'> {
@@ -78,6 +117,8 @@ export interface CheckResult extends Omit<Core.CheckResult, 'occurrences'> {
78
117
 
79
118
  /** surea11y's native top-level result shape -- see docs/OUTPUT_SCHEMA.md. */
80
119
  export interface A11yCoreResult extends Omit<Core.ScanResult, 'checksResults'> {
120
+ /** With .conditions(): each scan's condition ('default' first) and environment. */
121
+ conditionRuns?: Array<{ condition: string; environment: Record<string, unknown> | null }>;
81
122
  checksResults: CheckResult[];
82
123
  }
83
124
 
@@ -133,6 +174,30 @@ export class A11yCoreBuilder {
133
174
  */
134
175
  static installInternalsHook(pageOrContext: Page | BrowserContext): Promise<void>;
135
176
 
177
+ /**
178
+ * Installs @surea11y/core's opt-in listener hook on a Page, or on a
179
+ * BrowserContext for every page it opens, so the keyboard rules see the
180
+ * event listeners the page adds from script. Call it before page.goto().
181
+ * Needs @surea11y/core 1.14.0 or later.
182
+ */
183
+ static installListenerHook(pageOrContext: Page | BrowserContext): Promise<void>;
184
+
185
+ /**
186
+ * Installs @surea11y/core's opt-in live-region hook on a Page, or on a
187
+ * BrowserContext for every page it opens, which records what its live
188
+ * regions are given. Call it before page.goto(). Needs @surea11y/core
189
+ * 1.14.0 or later.
190
+ */
191
+ static installLiveRegionHook(pageOrContext: Page | BrowserContext): Promise<void>;
192
+
193
+ /**
194
+ * What `page`'s live regions were given since it loaded, in order, each
195
+ * region named by its selector; null without the live-region hook. Texts
196
+ * given to a region behind an open modal dialog only with
197
+ * `includeBehindModal: true`.
198
+ */
199
+ static announcements(page: Page, options?: { includeBehindModal?: boolean }): Promise<LocatedAnnouncement[] | null>;
200
+
136
201
  /** Scope the scan to one region. Call multiple times for a multi-region union. */
137
202
  include(selector: string): this;
138
203
  /**
@@ -173,7 +238,8 @@ export class A11yCoreBuilder {
173
238
  /**
174
239
  * Where analyze() sends each scan gap instead of console.warn: called once
175
240
  * per gap, with the result of the frame it came from, and once per scan
176
- * for the internals-hook note (tell them apart by `kind`). `() => {}`
241
+ * for each of the internals-hook and listener-hook notes (tell them apart
242
+ * by `kind`). `() => {}`
177
243
  * silences them, `null` goes back to console.warn. A later call replaces it.
178
244
  */
179
245
  logger(fn: ((entry: ScanGap | ScanNote, result: A11yCoreResult) => void) | null): this;
@@ -190,8 +256,30 @@ export class A11yCoreBuilder {
190
256
  reportOnly(outcomes: Outcome | Outcome[]): this;
191
257
  /** Opt in to also scanning every sub-frame on the page (including cross-origin iframes). */
192
258
  frames(enabled?: boolean): this;
259
+ /**
260
+ * Also scan the page under each condition after scanning it as it is
261
+ * (@surea11y/binding-base 1.6.0): a color scheme, a viewport width, or
262
+ * both. analyze() returns one merged result: a rule's outcome is its worst
263
+ * across the scans, each occurrence lists the `conditions` it appeared
264
+ * under, and `conditionRuns` gives each scan's environment. The viewport
265
+ * and scheme are put back afterwards. Not combined with frames(true) yet.
266
+ */
267
+ conditions(list: ReadonlyArray<ScanCondition> | null): this;
193
268
  /** Opt in to resolving each fail/cantTell occurrence's selector to a live ElementHandle. */
194
269
  elementRef(enabled?: boolean): this;
270
+ /**
271
+ * Opt in to a picture of each element the scan flags, on its occurrences'
272
+ * `screenshot` field: a Buffer, or a file in `dir`. `false` turns them
273
+ * off. Throws a TypeError with code 'INVALID_ENGINE_OPTIONS' for an option
274
+ * it can't use.
275
+ */
276
+ screenshots(options?: ScreenshotOptions | boolean): this;
277
+ /**
278
+ * Fetch, from Node, the style sheets the page can't read (another origin's)
279
+ * and give core their text, so checks that read the CSS can check them. On
280
+ * by default; needs @surea11y/core 1.14.0 or later.
281
+ */
282
+ fetchStyleSheets(enabled?: boolean): this;
195
283
  /** The rules this scan will run, worked out in Node with no page (@surea11y/core 1.12.0 and later). */
196
284
  plannedChecks(): PlannedCheck[];
197
285
  /** The criteria this scan will report in rulesResults, worked out in Node with no page. */
@@ -213,15 +301,35 @@ export class A11yCoreBuilder {
213
301
  * `expect(results.checksResults, formatFailures(results)).toEqual([])`.
214
302
  * Given the whole result, it also lists what the scan left out
215
303
  * (getScanGaps()) and ends with the @surea11y/core release that produced
216
- * it. Throws a TypeError for a frames(true) result: format `topFrame` and
217
- * each frame on its own. Deliberately framework-agnostic -- no dependency
218
- * on any particular `expect` implementation.
304
+ * it. Occurrences are listed in the order a review takes: failures, then
305
+ * questions that likely fail, likely pass, and are open, each question
306
+ * with its lean. `outcomes` narrows by outcome or review group,
307
+ * `howToCheck: true` adds each question's steps. Throws a TypeError for a
308
+ * frames(true) result: format `topFrame` and each frame on its own.
309
+ * Deliberately framework-agnostic -- no dependency on any particular
310
+ * `expect` implementation.
219
311
  */
220
312
  export function formatFailures(
221
313
  input: A11yCoreResult | ReadonlyArray<CheckResult>,
222
- opts?: { outcomes?: Outcome[] }
314
+ opts?: { outcomes?: Array<Outcome | ReviewGroup>; howToCheck?: boolean; failOnSeverity?: Severity }
223
315
  ): string;
224
316
 
317
+ /** The four severities, least to most severe (@surea11y/binding-base 1.6.0 and later). */
318
+ export const SEVERITIES: ReadonlyArray<Severity>;
319
+
320
+ /**
321
+ * The failing rule results that should fail a test: every `fail`, or with
322
+ * `failOnSeverity` only those whose severity is that level or above, as
323
+ * `surea11y scan --fail-on-severity` counts them. `fail` keeps its meaning;
324
+ * the level only picks which failures stop the test. Throws a TypeError for
325
+ * a level that is not a severity. From @surea11y/binding-base 1.6.0.
326
+ */
327
+ export function getGatingFailures(
328
+ input: A11yCoreResult | ReadonlyArray<CheckResult>,
329
+ opts?: { failOnSeverity?: Severity }
330
+ ): CheckResult[];
331
+
332
+
225
333
  /**
226
334
  * What a scan result says it left out, which its checksResults alone would
227
335
  * pass over as clean: an include() scope that matched no element
@@ -237,8 +345,17 @@ export type { ScanGap, OccurrenceLocation } from '@surea11y/binding-base';
237
345
 
238
346
  /**
239
347
  * How the page was scanned, which a gap doesn't cover: `forced-colors` when
240
- * the page was shown in forced colors, and `internals-hook` when the scan
241
- * asked about web components it could have read with the internals hook.
348
+ * the page was shown in forced colors, `internals-hook` when the scan
349
+ * asked about web components it could have read with the internals hook,
350
+ * and `listener-hook` when it asked about click or pointer handlers whose
351
+ * keyboard equivalent the listener hook would have let it see.
242
352
  */
243
353
  export { getScanNotes } from '@surea11y/binding-base';
244
354
  export type { ScanNote } from '@surea11y/binding-base';
355
+
356
+ /** A condition to scan the page under with .conditions(). */
357
+ export interface ScanCondition {
358
+ colorScheme?: 'light' | 'dark';
359
+ /** The viewport's width in CSS pixels; its height is kept. */
360
+ width?: number;
361
+ }
@@ -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,
@@ -114,6 +116,19 @@ const findOccurrenceElement = eval(`(args) => {
114
116
  * const [firstFail] = results.checksResults.filter(r => r.outcome === 'fail');
115
117
  * await firstFail.occurrences[0].elementHandle.screenshot({ path: 'flagged.png' });
116
118
  *
119
+ * Or let the scan take a picture of each element it flags, with
120
+ * `.screenshots()` (@surea11y/binding-base's, see its README): each
121
+ * occurrence gets a `screenshot` field, the picture (a Buffer, or a file in
122
+ * `dir`) or why there is none. The element is scrolled into view and marked
123
+ * with a box drawn over the page, and the page is put back afterwards; in
124
+ * every frame with `.frames(true)`, including cross-origin ones:
125
+ *
126
+ * const results = await new A11yCoreBuilder({ page })
127
+ * .screenshots({ dir: 'a11y-shots', padding: 16 })
128
+ * .analyze();
129
+ * // results.checksResults[i].occurrences[j].screenshot
130
+ * // -> { path: 'a11y-shots/element-3f9a1c07.png', box: { x, y, width, height } }
131
+ *
117
132
  * Register your own rule(s) for just this scan with
118
133
  * `.withCustomRules([...])` (@surea11y/core's `engineOptions.customRules`
119
134
  * escape hatch -- see ../core/docs/ENGINE_OPTIONS.md). Pass a real,
@@ -142,8 +157,8 @@ const findOccurrenceElement = eval(`(args) => {
142
157
  * top of the first scan's scope rather than replacing it (intentional for
143
158
  * "call include() several times for one scan" -- see above -- but a footgun
144
159
  * if you hold one instance across multiple assertions).
145
- * reportOnly()/frames()/elementRef() are the exception: each call replaces
146
- * the previous value rather than merging with it.
160
+ * reportOnly()/frames()/elementRef()/screenshots() are the exception: each
161
+ * call replaces the previous value rather than merging with it.
147
162
  */
148
163
  class A11yCoreBuilder extends A11yCoreBuilderBase {
149
164
  /**
@@ -163,6 +178,53 @@ class A11yCoreBuilder extends A11yCoreBuilderBase {
163
178
  return pageOrContext.addInitScript({ content: internalsHookScript() });
164
179
  }
165
180
 
181
+ /**
182
+ * Installs @surea11y/core's opt-in listener hook, so the keyboard rules
183
+ * see the event listeners the page adds from script (`addEventListener`,
184
+ * `el.onclick = fn`), which no page script can list. Without it a
185
+ * `<div role="button">` given a click listener from script goes
186
+ * unjudged. Takes a Page, or a BrowserContext to cover every page it
187
+ * opens. Call it before page.goto(), as installInternalsHook(). Needs
188
+ * @surea11y/core 1.14.0 or later. Resolves when the script is added.
189
+ * @param {import('playwright').Page | import('playwright').BrowserContext} pageOrContext
190
+ */
191
+ static installListenerHook(pageOrContext) {
192
+ return installHook(pageOrContext, 'installListenerHook', 'listenerHookScript');
193
+ }
194
+
195
+ /**
196
+ * Installs @surea11y/core's opt-in live-region hook, which records what
197
+ * the page's live regions are given while it runs: the scan then asks
198
+ * about a region added with its text already in it, and
199
+ * A11yCoreBuilder.announcements(page) returns what the page made
200
+ * available to announce. Takes a Page, or a BrowserContext to cover every
201
+ * page it opens. Call it before page.goto(), as installInternalsHook().
202
+ * Needs @surea11y/core 1.14.0 or later.
203
+ * @param {import('playwright').Page | import('playwright').BrowserContext} pageOrContext
204
+ */
205
+ static installLiveRegionHook(pageOrContext) {
206
+ return installHook(pageOrContext, 'installLiveRegionHook', 'liveRegionHookScript');
207
+ }
208
+
209
+ /**
210
+ * What `page`'s live regions were given since it loaded, as the
211
+ * live-region hook recorded it, in order: `[{ text, politeness, time,
212
+ * order, behindModal, selector }]`, each region named by its selector (and
213
+ * `shadowHostSelectors` inside a shadow root; null for a region that has
214
+ * since left the page). null where installLiveRegionHook() wasn't called
215
+ * before the page loaded. What the page made available to announce, not
216
+ * what a screen reader said. A text given to a region behind an open
217
+ * modal dialog, which assistive technology did not get, is listed only
218
+ * with `{ includeBehindModal: true }`, marked `behindModal`. Needs
219
+ * @surea11y/core 1.14.0 or later.
220
+ * @param {import('playwright').Page} page
221
+ * @param {{ includeBehindModal?: boolean }} [options]
222
+ * @returns {Promise<Array<object>|null>}
223
+ */
224
+ static announcements(page, options) {
225
+ return new A11yCoreBuilder({ page })._announcementsIn(page, options);
226
+ }
227
+
166
228
  /**
167
229
  * @param {{ page: import('playwright').Page, url?: string }} opts
168
230
  * `page` must already be navigated to and settled at the URL to scan --
@@ -198,16 +260,33 @@ class A11yCoreBuilder extends A11yCoreBuilderBase {
198
260
  const runInFrame = async (frameOrPage, frameContextSelector) => {
199
261
  const frameUrl = this._url || (typeof frameOrPage.url === 'function' ? frameOrPage.url() : null);
200
262
  if (packScript) await frameOrPage.evaluate(packScript);
263
+ // The text of the style sheets the frame can't read, fetched from Node
264
+ // (binding-base 1.6.0 and core 1.14.0; nothing with older ones).
265
+ const frameEngineOptions =
266
+ typeof this._styleSheetEngineOptions === 'function'
267
+ ? await this._styleSheetEngineOptions(frameOrPage, engineOptions)
268
+ : engineOptions;
201
269
  const result = rethrowEngineError(await frameOrPage.evaluate(scanInPage, {
202
270
  url: frameUrl,
203
271
  contextSelector: frameContextSelector,
204
- engineOptions,
272
+ engineOptions: frameEngineOptions,
205
273
  runOnly
206
274
  }));
207
275
  this._warnScanGaps(result, '@surea11y/playwright');
276
+ // Right after the frame's scan, before reportOnly(): nothing unless
277
+ // .screenshots() was called.
278
+ if (this._screenshots) await this._screenshotFrame(frameOrPage, result);
208
279
  return this._elementRef ? this._attachElementRefs(frameOrPage, result) : result;
209
280
  };
210
281
 
282
+ // .conditions() (binding-base 1.6.0): the page as it is, then under each
283
+ // condition, merged into one result.
284
+ if (this._conditions) {
285
+ return this._applyReportOnly(
286
+ await this._scanUnderConditions(() => runInFrame(this._page, contextSelector), this._conditionDriver())
287
+ );
288
+ }
289
+
211
290
  if (!this._scanFrames) {
212
291
  return this._applyReportOnly(await runInFrame(this._page, contextSelector));
213
292
  }
@@ -243,6 +322,51 @@ class A11yCoreBuilder extends A11yCoreBuilderBase {
243
322
  return { topFrame, frames };
244
323
  }
245
324
 
325
+ /**
326
+ * The driver steps .conditions() scans need: the viewport's width with
327
+ * page.setViewportSize() (its height kept) and the color scheme with
328
+ * page.emulateMedia(). Each condition sets both, from the page as it was,
329
+ * so one condition's width or scheme doesn't carry into the next; at the
330
+ * end the viewport goes back, and if a condition set a scheme, the page
331
+ * is left in the scheme it had before (a scheme emulated by the caller, or
332
+ * the system's). The scheme is set back by name, not cleared with null:
333
+ * WebKit keeps a dark emulation that null should clear.
334
+ */
335
+ _conditionDriver() {
336
+ const page = this._page;
337
+ let schemeSet = false;
338
+ let viewport = null;
339
+ // The scheme a condition without one goes back to.
340
+ let baseScheme = 'light';
341
+ return {
342
+ save: async () => {
343
+ const before = await page.evaluate(() => ({
344
+ width: innerWidth,
345
+ height: innerHeight,
346
+ dark: matchMedia('(prefers-color-scheme: dark)').matches
347
+ }));
348
+ viewport = page.viewportSize() || { width: before.width, height: before.height };
349
+ baseScheme = before.dark ? 'dark' : 'light';
350
+ return { viewport };
351
+ },
352
+ apply: async (condition) => {
353
+ await page.setViewportSize({ width: condition.width || viewport.width, height: viewport.height });
354
+ if (condition.colorScheme) {
355
+ await page.emulateMedia({ colorScheme: condition.colorScheme });
356
+ schemeSet = true;
357
+ } else if (schemeSet) {
358
+ await page.emulateMedia({ colorScheme: baseScheme });
359
+ schemeSet = false;
360
+ }
361
+ },
362
+ restore: async (state) => {
363
+ if (!state) return;
364
+ await page.setViewportSize(state.viewport);
365
+ if (schemeSet) await page.emulateMedia({ colorScheme: baseScheme });
366
+ }
367
+ };
368
+ }
369
+
246
370
  /**
247
371
  * Resolves each occurrence to a live ElementHandle, scoped to
248
372
  * frameOrPage's own document (a Playwright Page and Frame both expose the
@@ -266,6 +390,59 @@ class A11yCoreBuilder extends A11yCoreBuilderBase {
266
390
  return result;
267
391
  }
268
392
 
393
+ /**
394
+ * binding-base's screenshots step for one scanned frame (or the page),
395
+ * with the <iframe>s leading to it: each frame's frameElement(), a handle
396
+ * in its parent, disposed afterwards.
397
+ */
398
+ async _screenshotFrame(frameOrPage, result) {
399
+ const framePath = [];
400
+ const parentOf = (f) => (typeof f.parentFrame === 'function' ? f.parentFrame() : null);
401
+ for (let f = frameOrPage; parentOf(f); f = parentOf(f)) {
402
+ // null when the frame detached after its scan: binding-base fails
403
+ // that frame's pictures.
404
+ const iframe = await f.frameElement().catch(() => null);
405
+ framePath.unshift({ frame: parentOf(f), iframe });
406
+ }
407
+ try {
408
+ await this._captureScreenshots(result, frameOrPage, framePath);
409
+ } finally {
410
+ await Promise.all(framePath.map((step) => (step.iframe ? step.iframe.dispose().catch(() => {}) : null)));
411
+ }
412
+ }
413
+
414
+ /**
415
+ * For binding-base's screenshots step: runs `fn(...args)` in the frame.
416
+ * Playwright's evaluate() takes one argument, so the arguments go as one
417
+ * array (an element handle inside it arrives as the element) and are
418
+ * spread in the page.
419
+ */
420
+ /**
421
+ * For binding-base's style sheet step: fetch with the page's own request
422
+ * API, which carries its cookies, in the shape of fetch().
423
+ */
424
+ get _styleSheetFetch() {
425
+ const request = this._page && typeof this._page.request === 'object' ? this._page.request : null;
426
+ if (!request || typeof request.get !== 'function') return null;
427
+ return async (url) => {
428
+ const res = await request.get(url, { timeout: 5000 });
429
+ return { ok: res.ok(), text: () => res.text() };
430
+ };
431
+ }
432
+
433
+ _evaluateInFrame(frameOrPage, fn, args) {
434
+ // eslint-disable-next-line no-new-func
435
+ return frameOrPage.evaluate(new Function('args', 'return (' + fn.toString() + ')(...args)'), args);
436
+ }
437
+
438
+ /**
439
+ * For binding-base's screenshots step: a PNG of `box`, CSS pixels in the
440
+ * viewport, which is what Playwright's clip is relative to.
441
+ */
442
+ _captureBox(box) {
443
+ return this._page.screenshot({ clip: { x: box.x, y: box.y, width: box.width, height: box.height } });
444
+ }
445
+
269
446
  async _findElement(frameOrPage, occurrence) {
270
447
  const handle = await frameOrPage.evaluateHandle(findOccurrenceElement, {
271
448
  selector: occurrence.selector,
@@ -277,4 +454,17 @@ class A11yCoreBuilder extends A11yCoreBuilderBase {
277
454
  }
278
455
  }
279
456
 
457
+ // One of core's hook scripts (1.14.0 and later for the listener and
458
+ // live-region hooks), added as an init script, which runs before the page's
459
+ // own scripts.
460
+ function installHook(pageOrContext, method, scriptName) {
461
+ if (!pageOrContext || typeof pageOrContext.addInitScript !== 'function') {
462
+ throw new TypeError(`A11yCoreBuilder.${method}() requires a Playwright Page or BrowserContext (with an .addInitScript() method).`);
463
+ }
464
+ if (typeof core[scriptName] !== 'function') {
465
+ throw new Error(`A11yCoreBuilder.${method}() needs @surea11y/core 1.14.0 or later, which has ${scriptName}().`);
466
+ }
467
+ return pageOrContext.addInitScript({ content: core[scriptName]() });
468
+ }
469
+
280
470
  module.exports = { A11yCoreBuilder };
package/src/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  'use strict';
2
2
 
3
- const { EngineError, getScanGaps, getScanNotes, formatOccurrenceLocation } = require('@surea11y/binding-base');
3
+ const { EngineError, getScanGaps, getScanNotes, formatOccurrenceLocation, getGatingFailures, SEVERITIES } = require('@surea11y/binding-base');
4
4
  const { A11yCoreBuilder } = require('./A11yCoreBuilder');
5
5
  const { formatFailures } = require('./formatFailures');
6
6
 
7
- module.exports = { A11yCoreBuilder, EngineError, formatFailures, formatOccurrenceLocation, getScanGaps, getScanNotes };
7
+ module.exports = { A11yCoreBuilder, EngineError, formatFailures, formatOccurrenceLocation, getScanGaps, getScanNotes, getGatingFailures, SEVERITIES };