@surea11y/playwright 1.4.2 → 1.6.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
@@ -9,7 +9,7 @@ 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 the binding as a regular dependency, so a project that doesn't list it still works. List it in your own `package.json` too, as the line above does: your project and the binding then share one copy, so whatever you do with core directly, writing a SARIF log or an HTML report (`@surea11y/core/sarif`, `/report`), reading the rule catalogue or keeping a baseline, reads results with the same core that produced them. When your core can't match the binding's range, as with a linked checkout (`file:../core`) or a fork, add `"overrides": { "@surea11y/core": "$@surea11y/core" }` beside it.
12
+ `@surea11y/core` 1.15.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
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
 
@@ -39,7 +39,7 @@ await browser.close();
39
39
 
40
40
  `results` is `@surea11y/core`'s own native result shape — see its [`OUTPUT_SCHEMA.md`](https://github.com/SureA11y/core/blob/main/docs/OUTPUT_SCHEMA.md) — not the `violations`/`passes`/`incomplete`/`inapplicable` shape used by other popular accessibility testing tools. The builder's *method names* are modeled on common conventions in this space for migration familiarity; the richer result schema is kept as-is.
41
41
 
42
- Every result says which `@surea11y/core` release produced it, in `results.engine.version` (for example `"1.12.0"`): quote it in a bug report, and compare it when two runs disagree. From 1.4.0 this package needs `@surea11y/core` 1.12.0 or later; see [What changes with `@surea11y/core` 1.12](#what-changes-with-surea11ycore-112).
42
+ Every result says which `@surea11y/core` release produced it, in `results.engine.version` (for example `"1.12.0"`): quote it in a bug report, and compare it when two runs disagree. From 1.6.0 this package needs `@surea11y/core` 1.15.0 or later, and from 1.5.0 it needed 1.14.0 or later; see [What changes with `@surea11y/core` 1.15](#what-changes-with-surea11ycore-115) and [What changes with `@surea11y/core` 1.14](#what-changes-with-surea11ycore-114).
43
43
 
44
44
  Also see `examples/basic-scan.js` for a runnable script (`npm run example -- <url>`).
45
45
 
@@ -99,7 +99,7 @@ const gaps = getScanGaps(results);
99
99
  // message: 'Nothing was scanned: the scan scope matched no element ("#main").' }]
100
100
  ```
101
101
 
102
- Each gap has a `kind`: `'context-not-found'` (nothing was scanned), `'context-partly-not-found'` (some of several selectors matched nothing), `'custom-rule-skipped'` (a custom rule the engine could not run, one per rule, from `results.skippedCustomRules`; one you excluded yourself with `.disableRules()` is not a gap), or `'pack-skipped'` (a pack that did not run, one per pack, from `results.skippedPacks`; see [Scanning with packs](#scanning-with-packs-standards-checklists-and-your-own-rules)).
102
+ Each gap has a `kind`: `'context-not-found'` (nothing was scanned), `'context-partly-not-found'` (some of several selectors matched nothing), `'custom-rule-skipped'` (a custom rule the engine could not run, one per rule, from `results.skippedCustomRules`; one you excluded yourself with `.disableRules()` is not a gap), `'pack-skipped'` (a pack that did not run, one per pack, from `results.skippedPacks`; see [Scanning with packs](#scanning-with-packs-standards-checklists-and-your-own-rules)), or `'profile-not-run'` (a profile a scan of several did not run, one per profile, from `results.engine.profilesNotRun`; `@surea11y/core` 1.15 and later).
103
103
 
104
104
  `.analyze()` also prints each gap with `console.warn`, once per scanned frame, prefixed with the frame's URL, for example `@surea11y/playwright (https://example.com/): Nothing was scanned: the scan scope matched no element ("#main").` The engine warns too, but in the page's console, which a Playwright run doesn't show. The warning doesn't fail anything: to fail a test on a gap, assert on `getScanGaps(results)` as below.
105
105
 
@@ -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
 
@@ -159,13 +159,27 @@ test('page has no accessibility violations', async ({ page }) => {
159
159
  });
160
160
  ```
161
161
 
162
- To also fail when the scan left something out (an `.include()` that matched nothing, a custom rule or a pack that didn't run), assert on `getScanGaps(results)` too: `expect(getScanGaps(results), formatFailures(results)).toEqual([])`.
162
+ To also fail when the scan left something out (an `.include()` that matched nothing, a custom rule, a pack or a profile that didn't run), assert on `getScanGaps(results)` too: `expect(getScanGaps(results), formatFailures(results)).toEqual([])`.
163
163
 
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.
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, and one gating a page on a pack's checklist.
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.
165
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
 
@@ -195,7 +209,7 @@ for (const frame of results.frames) {
195
209
  }
196
210
  ```
197
211
 
198
- Unlike script-injection-based accessibility tools (which need a `postMessage`-based protocol to reach cross-origin iframes, since they're injected as a plain `<script>` fully subject to the browser's same-origin policy), this needs no extra engine support at all — Playwright drives every frame via CDP at the automation-process level, so cross-origin `frame.evaluate()` already just works. Default off, so plain `.analyze()` is unaffected unless you opt in.
212
+ Unlike script-injection-based accessibility tools (which need a `postMessage`-based protocol to reach cross-origin iframes, since they're injected as a plain `<script>` fully subject to the browser's same-origin policy), this needs no extra engine support at all — Playwright drives every frame from the automation process, through its own browser protocol, so cross-origin `frame.evaluate()` already just works. Default off, so plain `.analyze()` is unaffected unless you opt in.
199
213
 
200
214
  `results.frames` is a flat list of every sub-frame, however deeply nested. A frame that couldn't be scanned (it detached or navigated away mid-scan, or is sandboxed against scripts) is an entry `{ url, error }` instead of a result, so check for `error` before reading `checksResults`.
201
215
 
@@ -209,7 +223,9 @@ const results = await new A11yCoreBuilder({ page }).frames(true).analyze();
209
223
  fs.writeFileSync('a11y.sarif', renderSarifReport(results));
210
224
  ```
211
225
 
212
- `.include()` scopes the top frame only: each sub-frame is scanned whole, as `@surea11y/core`'s own `runa11yCoreAcrossFrames` does. (A sub-frame rarely holds the element the top frame's selector names, and since core 1.10.0 a selector that matches nothing scans nothing.) `.exclude()` applies in every frame. An `EngineError` (above) rejects the whole scan, since the top frame is scanned first with the same rule and tag lists.
226
+ `.include()` scopes the top frame only: each sub-frame inside its roots is scanned whole, as `@surea11y/core`'s own `runa11yCoreAcrossFrames` does. (A sub-frame rarely holds the element the top frame's selector names, and since core 1.10.0 a selector that matches nothing scans nothing.) `.exclude()` applies in every frame. An `EngineError` (above) rejects the whole scan, since the top frame is scanned first with the same rule and tag lists.
227
+
228
+ Which frames are scanned, and how, also follows `runa11yCoreAcrossFrames` (`@surea11y/binding-base` 1.7.0 and later). A frame the page doesn't show, or that an open modal dialog covers, unless `.options({ includeHiddenElements: true })`, a frame in content `.exclude()` leaves out, a frame of the top page outside the `.include()` roots, a frame in a shadow root with `.options({ includeShadowDom: false })`, and a frame whose document shows nothing (an empty `about:blank`) are left out of `results.frames`, with the frames inside them. A frame under `aria-hidden="true"` is scanned as aria-hidden content, where names and roles don't apply and contrast, focus and keyboard still do, and one under `inert` only for how it looks; a frame inside one is read the same way (`@surea11y/core` 1.15 and later). The elements around a frame are read through slots and shadow hosts, as the accessibility tree reads them. Each sub-frame's result is named by its own `url`; a `url` given to the constructor names the top frame only.
213
229
 
214
230
  ### Trimming the result to just violations
215
231
 
@@ -274,6 +290,46 @@ first.occurrences[0].screenshot;
274
290
 
275
291
  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.
276
292
 
293
+ ### Findings that need review: leans and how to check
294
+
295
+ 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:
296
+
297
+ - **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).
298
+ - **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.
299
+
300
+ `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:
301
+
302
+ ```
303
+ 2) heading-order (minor, likely fails): This heading jumps from level 1 to level 3, skipping a level.
304
+ at html > body > main > h3
305
+ 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.
306
+ Why it likely fails: The heading skips a level after the one before it.
307
+ How to check:
308
+ 1. Find the heading the report names and note its level and the previous heading's level (from the report or the Accessibility pane).
309
+ ...
310
+ ```
311
+
312
+ 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:
313
+
314
+ ```js
315
+ const { test, expect } = require('@playwright/test');
316
+ const { leaningFailures } = require('@surea11y/core');
317
+ const { A11yCoreBuilder, formatFailures } = require('@surea11y/playwright');
318
+
319
+ test('no failures, and no questions that likely fail', async ({ page }) => {
320
+ await page.goto('https://example.com/');
321
+
322
+ const results = await new A11yCoreBuilder({ page }).analyze();
323
+ const failures = results.checksResults.filter((r) => r.outcome === 'fail');
324
+ expect(
325
+ [...failures, ...leaningFailures(results)],
326
+ formatFailures(results, { outcomes: ['fail', 'leanFail'] })
327
+ ).toEqual([]);
328
+ });
329
+ ```
330
+
331
+ 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.
332
+
277
333
  ### Web components: the internals hook
278
334
 
279
335
  Many web components keep their `ElementInternals` in a private field and name themselves, set their states or give themselves a role through it:
@@ -311,6 +367,57 @@ With it, the checkbox above passes, an unnamed component that attaches internals
311
367
  - **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.
312
368
  - **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'`.
313
369
 
370
+ ### Click handlers added from script: the listener hook
371
+
372
+ Most pages add their click handlers from script, where no page script can list them afterwards:
373
+
374
+ ```html
375
+ <div class="save" role="button" tabindex="0">Save</div>
376
+ <script>
377
+ document.querySelector('.save').addEventListener('click', save);
378
+ </script>
379
+ ```
380
+
381
+ 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:
382
+
383
+ ```js
384
+ const context = await browser.newContext();
385
+ await A11yCoreBuilder.installListenerHook(context); // before any page navigates
386
+ const page = await context.newPage();
387
+ await page.goto('https://example.com/');
388
+
389
+ const results = await new A11yCoreBuilder({ page }).analyze();
390
+ results.engine.environment.listenerHook; // 'early'
391
+ ```
392
+
393
+ With `@playwright/test`, install it in a `beforeEach` on the `context` fixture, or on `page` before the test navigates.
394
+
395
+ 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.
396
+
397
+ ### Live regions: the live-region hook and announcements()
398
+
399
+ `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:
400
+
401
+ ```js
402
+ const { test, expect } = require('@playwright/test');
403
+ const { A11yCoreBuilder } = require('@surea11y/playwright');
404
+
405
+ test.beforeEach(async ({ context }) => {
406
+ await A11yCoreBuilder.installLiveRegionHook(context); // before the test navigates
407
+ });
408
+
409
+ test('saving says so', async ({ page }) => {
410
+ await page.goto('https://example.com/settings');
411
+ await page.getByRole('button', { name: 'Save' }).click();
412
+
413
+ const said = await A11yCoreBuilder.announcements(page);
414
+ // [{ text: 'Saved', politeness: 'polite', time: 1234.5, order: 7, behindModal: false, selector: '#status' }]
415
+ expect(said.map((a) => a.text)).toContain('Saved');
416
+ });
417
+ ```
418
+
419
+ 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).
420
+
314
421
  ### Forced colors
315
422
 
316
423
  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:
@@ -323,6 +430,24 @@ results.engine.environment.forcedColors; // 'active'
323
430
 
324
431
  `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.
325
432
 
433
+ ### Dark mode and phone width: scans under conditions
434
+
435
+ 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:
436
+
437
+ ```js
438
+ const results = await new A11yCoreBuilder({ page })
439
+ .conditions([{ colorScheme: 'dark' }, { width: 320 }, { colorScheme: 'dark', width: 320 }])
440
+ .analyze();
441
+ ```
442
+
443
+ 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.
444
+
445
+ - A rule's outcome is its worst across the scans, so a contrast failure only in dark mode fails the rule.
446
+ - 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`.
447
+ - `results.conditionRuns` lists each scan's condition and `engine.environment`.
448
+
449
+ 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.
450
+
326
451
  ### Registering a custom rule at runtime
327
452
 
328
453
  `@surea11y/core` supports registering additional rules per-scan via `engineOptions.customRules`. Use `.withCustomRules()` to register one:
@@ -403,23 +528,75 @@ results.engine.profile; // 'acme-web-2026'
403
528
  results.rulesResults.filter((r) => r.meta && r.meta.standard === 'Acme web policy');
404
529
  ```
405
530
 
531
+ **Several profiles at once.** `.options({ profile })` also takes a list, a pack's profile beside WCAG's or another pack's (`@surea11y/core` 1.15 and later). Each profile judges the page as it would alone, and the result reads as one profile with the rules of all, in the top frame and in each frame with `.frames(true)`:
532
+
533
+ ```js
534
+ const waiAria = require('@surea11y/pack-wai-aria');
535
+
536
+ const results = await new A11yCoreBuilder({ page })
537
+ .withPacks(waiAria)
538
+ .options({ profile: ['wcag22-aa', 'wai-aria-1.2'] })
539
+ .analyze();
540
+
541
+ results.engine.profiles; // ['wcag22-aa', 'wai-aria-1.2']
542
+ // A rule both run is one check: its outcome is the worst, and its verdicts
543
+ // say what each profile makes of it.
544
+ results.checksResults.find((c) => c.ruleId === 'aria-allowed-attr').verdicts;
545
+ ```
546
+
547
+ A profile that didn't run is in `results.engine.profilesNotRun`, with why, and `getScanGaps()` reports it as `'profile-not-run'`. Core's [`OUTPUT_SCHEMA.md`](https://github.com/SureA11y/core/blob/main/docs/OUTPUT_SCHEMA.md#several-profiles) has the whole result.
548
+
406
549
  A pack's own rules appear in `checksResults` like core's, with ids that start with its namespace (`acme-no-autoplay`). Without its profile, a pack's rules run only when selected, with `.withRules()` or by a tag. `@surea11y/core`'s HTML, SARIF and JUnit reports show a standard's or a checklist's items in a section of their own. Pass an array, or call `.withPacks()` again, to scan with several packs.
407
550
 
408
551
  **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.
409
552
 
410
553
  **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.
411
554
 
555
+ ### Style sheets from another origin
556
+
557
+ 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; 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:
558
+
559
+ ```js
560
+ await new A11yCoreBuilder({ page }).fetchStyleSheets(false).analyze();
561
+ ```
562
+
412
563
  ### Element addressing beyond a CSS selector
413
564
 
414
565
  Every occurrence already carries `selector` and (with `.elementRef(true)`, above) a live `ElementHandle`. For an element inside a shadow tree, `selector` holds inside its shadow root, and `shadowHostSelectors` lists the shadow hosts that lead there, outermost first, each resolved in the tree that holds it. 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.
415
566
 
416
567
  ## TypeScript
417
568
 
418
- `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()`, `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.
569
+ `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`, and one for `'profile-not-run'`, which carries `profile`. `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.
570
+
571
+ ## What changes with `@surea11y/core` 1.15
572
+
573
+ With `@surea11y/core` 1.15.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):
574
+
575
+ - **WCAG fails only where WCAG fails.** Where only WAI-ARIA or the HTML content model is broken (an attribute the role doesn't support, an unnamed grid or dialog, a heading in a list), the ARIA and HTML structure rules now ask (`cantTell`, uncertainty `spec-only`) instead of failing. The findings keep their reason codes, so baselines still match, and a gate on `fail` no longer fails on them.
576
+ - **Frames are read as the browser reads them.** A framed document is no page of its own, so its title, language, viewport and landmark rules are `notApplicable`; a frame under `aria-hidden` or `inert` is read as such, one behind an open modal dialog is left out, and one in a shadow root is read through its host ([more](#scanning-every-frame-including-cross-origin-iframes)).
577
+ - **Several profiles at once.** `.options({ profile: ['wcag22-aa', 'wai-aria-1.2'] })`, with the packs that bring them, judges the page by each; a profile that can't run is a `profile-not-run` gap ([more](#scanning-with-packs-standards-checklists-and-your-own-rules)).
578
+ - **A picture in the state the finding was made in.** A `text-spacing-content-loss` finding is also pictured with the spacing applied ([more](#a-picture-of-each-failing-element)).
579
+ - **How to check by hand.** Core's procedures say how a person assesses each criterion, and its HTML report lists what a scan leaves to a person.
580
+ - **Roles follow WAI-ARIA more closely:** `role="text"` names no role, and an image with a presentational role and a global ARIA attribute keeps its role, so it fails without `alt`.
581
+
582
+ ## What changes with `@surea11y/core` 1.14
583
+
584
+ 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):
585
+
586
+ - **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.
587
+ - **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.
588
+ - **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).
589
+ - **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`.
590
+ - **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.
591
+ - **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).
592
+ - **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.
593
+ - **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.
594
+ - **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.
595
+ - **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).
419
596
 
420
597
  ## What changes with `@surea11y/core` 1.12
421
598
 
422
- This release needs `@surea11y/core` 1.12.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):
599
+ From 1.4.0 this package needs `@surea11y/core` 1.12.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):
423
600
 
424
601
  - **An empty heading now fails an unscoped scan.** `empty-heading` used to ask about a heading with no accessible name; it now fails it. It's a best practice, so it runs in a scan that selects nothing and with `.withBestPractices()`, not under `.withWcag()`, tags or a profile. A gate on a page with `<h2></h2>` that asserted no failures now fails: fix the heading, or scan a WCAG target.
425
602
  - **Scans that pick rules report their criteria.** `.withRules('img-alt-present')`, a non-WCAG tag or `.withBestPractices()` now fill `rulesResults` with the WCAG criteria those rules belong to, where it was empty. A criterion whose other rules weren't selected is `cantTell` (`reasonCode` `composite.rollup.cantTell.notSelectedChild`), and each check's `rollupIds` names the criteria it was added for. `.wcagLevel()` keeps those criteria to a level.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@surea11y/playwright",
3
- "version": "1.4.2",
3
+ "version": "1.6.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.5.0",
50
- "@surea11y/core": "^1.12.0"
49
+ "@surea11y/binding-base": "^1.7.0",
50
+ "@surea11y/core": "^1.15.0"
51
51
  },
52
52
  "peerDependencies": {
53
53
  "playwright": ">=1.0.0"
@@ -1,4 +1,4 @@
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
@@ -25,7 +25,9 @@ import type {
25
25
  Margin,
26
26
  MarginDeclaration,
27
27
  ContextMatch,
28
- CompositeResult
28
+ CompositeResult,
29
+ Lean,
30
+ HowToCheck
29
31
  } from '@surea11y/core';
30
32
 
31
33
  export type {
@@ -44,7 +46,9 @@ export type {
44
46
  Margin,
45
47
  MarginDeclaration,
46
48
  ContextMatch,
47
- CompositeResult
49
+ CompositeResult,
50
+ Lean,
51
+ HowToCheck
48
52
  };
49
53
 
50
54
  /**
@@ -67,9 +71,13 @@ export type {
67
71
  ScreenshotOptions,
68
72
  ScreenshotSkip,
69
73
  ScreenshotBox,
70
- OccurrenceScreenshot
74
+ OccurrenceScreenshot,
75
+ LocatedAnnouncement,
76
+ ReviewGroup
71
77
  } from '@surea11y/binding-base';
72
78
  import type {
79
+ LocatedAnnouncement,
80
+ ReviewGroup,
73
81
  PackLike,
74
82
  WcagVersion,
75
83
  WcagLevelInput,
@@ -87,6 +95,8 @@ export type CheckResultMeta = Core.RuleMeta;
87
95
  export type CompositeResultDetails = Core.CompositeResult['data']['details'];
88
96
 
89
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[];
90
100
  /**
91
101
  * Only present when `.elementRef(true)` was used. `null` when this
92
102
  * occurrence has no single resolvable target element (e.g. `selector` was
@@ -107,6 +117,8 @@ export interface CheckResult extends Omit<Core.CheckResult, 'occurrences'> {
107
117
 
108
118
  /** surea11y's native top-level result shape -- see docs/OUTPUT_SCHEMA.md. */
109
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 }>;
110
122
  checksResults: CheckResult[];
111
123
  }
112
124
 
@@ -162,6 +174,30 @@ export class A11yCoreBuilder {
162
174
  */
163
175
  static installInternalsHook(pageOrContext: Page | BrowserContext): Promise<void>;
164
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
+
165
201
  /** Scope the scan to one region. Call multiple times for a multi-region union. */
166
202
  include(selector: string): this;
167
203
  /**
@@ -175,7 +211,7 @@ export class A11yCoreBuilder {
175
211
  withTags(tags: string | string[]): this;
176
212
  /** Never run rules carrying any of these tags (applied after withTags). */
177
213
  disableTags(tags: string | string[]): this;
178
- /** Only run these specific rule IDs (accepts with or without the prefix). */
214
+ /** Only run these specific rule IDs (accepts with or without the `a11ycore-` prefix). */
179
215
  withRules(ruleIds: string | string[]): this;
180
216
  /** Never run these specific rule IDs (applied after withRules). */
181
217
  disableRules(ruleIds: string | string[]): this;
@@ -202,7 +238,8 @@ export class A11yCoreBuilder {
202
238
  /**
203
239
  * Where analyze() sends each scan gap instead of console.warn: called once
204
240
  * per gap, with the result of the frame it came from, and once per scan
205
- * 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`). `() => {}`
206
243
  * silences them, `null` goes back to console.warn. A later call replaces it.
207
244
  */
208
245
  logger(fn: ((entry: ScanGap | ScanNote, result: A11yCoreResult) => void) | null): this;
@@ -219,6 +256,15 @@ export class A11yCoreBuilder {
219
256
  reportOnly(outcomes: Outcome | Outcome[]): this;
220
257
  /** Opt in to also scanning every sub-frame on the page (including cross-origin iframes). */
221
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;
222
268
  /** Opt in to resolving each fail/cantTell occurrence's selector to a live ElementHandle. */
223
269
  elementRef(enabled?: boolean): this;
224
270
  /**
@@ -228,6 +274,12 @@ export class A11yCoreBuilder {
228
274
  * it can't use.
229
275
  */
230
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;
231
283
  /** The rules this scan will run, worked out in Node with no page (@surea11y/core 1.12.0 and later). */
232
284
  plannedChecks(): PlannedCheck[];
233
285
  /** The criteria this scan will report in rulesResults, worked out in Node with no page. */
@@ -249,22 +301,43 @@ export class A11yCoreBuilder {
249
301
  * `expect(results.checksResults, formatFailures(results)).toEqual([])`.
250
302
  * Given the whole result, it also lists what the scan left out
251
303
  * (getScanGaps()) and ends with the @surea11y/core release that produced
252
- * it. Throws a TypeError for a frames(true) result: format `topFrame` and
253
- * each frame on its own. Deliberately framework-agnostic -- no dependency
254
- * 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.
255
311
  */
256
312
  export function formatFailures(
257
313
  input: A11yCoreResult | ReadonlyArray<CheckResult>,
258
- opts?: { outcomes?: Outcome[] }
314
+ opts?: { outcomes?: Array<Outcome | ReviewGroup>; howToCheck?: boolean; failOnSeverity?: Severity }
259
315
  ): string;
260
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
+
261
333
  /**
262
334
  * What a scan result says it left out, which its checksResults alone would
263
335
  * pass over as clean: an include() scope that matched no element
264
336
  * (`context-not-found`, nothing was scanned), some include() selectors that
265
337
  * matched nothing (`context-partly-not-found`), each custom rule that did
266
- * not run (`custom-rule-skipped`), and each pack that did not run
267
- * (`pack-skipped`). Each gap has a `message`. Throws a
338
+ * not run (`custom-rule-skipped`), each pack that did not run
339
+ * (`pack-skipped`), and each profile a scan of several did not run
340
+ * (`profile-not-run`). Each gap has a `message`. Throws a
268
341
  * TypeError for a frames(true) result: call it on `topFrame` and on each
269
342
  * scanned frame.
270
343
  */
@@ -273,8 +346,19 @@ export type { ScanGap, OccurrenceLocation } from '@surea11y/binding-base';
273
346
 
274
347
  /**
275
348
  * How the page was scanned, which a gap doesn't cover: `forced-colors` when
276
- * the page was shown in forced colors, and `internals-hook` when the scan
277
- * asked about web components it could have read with the internals hook.
349
+ * the page was shown in forced colors, `internals-hook` when the scan
350
+ * asked about web components it could have read with the internals hook,
351
+ * `listener-hook` when it asked about click or pointer handlers whose
352
+ * keyboard equivalent the listener hook would have let it see, and
353
+ * `live-region-hook` when it judged live regions the live-region hook would
354
+ * have let it see.
278
355
  */
279
356
  export { getScanNotes } from '@surea11y/binding-base';
280
357
  export type { ScanNote } from '@surea11y/binding-base';
358
+
359
+ /** A condition to scan the page under with .conditions(). */
360
+ export interface ScanCondition {
361
+ colorScheme?: 'light' | 'dark';
362
+ /** The viewport's width in CSS pixels; its height is kept. */
363
+ width?: number;
364
+ }
@@ -1,12 +1,26 @@
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;
6
+ const bindingBase = require('@surea11y/binding-base');
4
7
  const {
5
8
  A11yCoreBuilderBase,
6
9
  createInPageScan,
7
10
  rethrowEngineError,
8
- queryOccurrenceElement
9
- } = require('@surea11y/binding-base');
11
+ queryOccurrenceElement,
12
+ // How .frames(true) reads each frame (binding-base 1.7 and later).
13
+ readFrameElement,
14
+ isFrameDocumentEmpty,
15
+ frameReadingOptions
16
+ } = bindingBase;
17
+ const frameEngineOptions = bindingBase.frameEngineOptions || ((engineOptions) => engineOptions);
18
+ // What a frame is under, with what the frames around it are under
19
+ // (binding-base 1.7 and later; aria-hidden and inert alike).
20
+ const inheritFrameReading = bindingBase.inheritFrameReading || ((above, reading) => ({
21
+ ariaHidden: !!((above && above.ariaHidden) || (reading && reading.ariaHidden)),
22
+ inert: !!((above && above.inert) || (reading && reading.inert))
23
+ }));
10
24
 
11
25
  // Playwright's page.evaluate(fn, arg) (and frame.evaluate(fn, arg), same
12
26
  // signature) only accepts ONE arg value -- page.evaluate(fn, a, b, c, d)
@@ -80,10 +94,11 @@ const findOccurrenceElement = eval(`(args) => {
80
94
  * // results.topFrame -- same shape as the single-frame case above
81
95
  * // results.frames -- array of the same native result shape, one per sub-frame
82
96
  *
83
- * include() scopes the top frame only; every sub-frame is scanned whole.
97
+ * include() scopes the top frame only; every sub-frame inside its roots is
98
+ * scanned whole, and a hidden, excluded or empty frame is left out.
84
99
  *
85
100
  * Unlike script-injection-based accessibility engines (which need a
86
- * postMessage-based protocol, runPartial/finishRun, to reach cross-origin
101
+ * postMessage-based protocol to reach cross-origin
87
102
  * iframes, since they're injected as a plain <script> and are fully subject
88
103
  * to the browser's same-origin policy), this doesn't need any @surea11y/core
89
104
  * engine support: Playwright
@@ -176,6 +191,53 @@ class A11yCoreBuilder extends A11yCoreBuilderBase {
176
191
  return pageOrContext.addInitScript({ content: internalsHookScript() });
177
192
  }
178
193
 
194
+ /**
195
+ * Installs @surea11y/core's opt-in listener hook, so the keyboard rules
196
+ * see the event listeners the page adds from script (`addEventListener`,
197
+ * `el.onclick = fn`), which no page script can list. Without it a
198
+ * `<div role="button">` given a click listener from script goes
199
+ * unjudged. Takes a Page, or a BrowserContext to cover every page it
200
+ * opens. Call it before page.goto(), as installInternalsHook(). Needs
201
+ * @surea11y/core 1.14.0 or later. Resolves when the script is added.
202
+ * @param {import('playwright').Page | import('playwright').BrowserContext} pageOrContext
203
+ */
204
+ static installListenerHook(pageOrContext) {
205
+ return installHook(pageOrContext, 'installListenerHook', 'listenerHookScript');
206
+ }
207
+
208
+ /**
209
+ * Installs @surea11y/core's opt-in live-region hook, which records what
210
+ * the page's live regions are given while it runs: the scan then asks
211
+ * about a region added with its text already in it, and
212
+ * A11yCoreBuilder.announcements(page) returns what the page made
213
+ * available to announce. Takes a Page, or a BrowserContext to cover every
214
+ * page it opens. Call it before page.goto(), as installInternalsHook().
215
+ * Needs @surea11y/core 1.14.0 or later.
216
+ * @param {import('playwright').Page | import('playwright').BrowserContext} pageOrContext
217
+ */
218
+ static installLiveRegionHook(pageOrContext) {
219
+ return installHook(pageOrContext, 'installLiveRegionHook', 'liveRegionHookScript');
220
+ }
221
+
222
+ /**
223
+ * What `page`'s live regions were given since it loaded, as the
224
+ * live-region hook recorded it, in order: `[{ text, politeness, time,
225
+ * order, behindModal, selector }]`, each region named by its selector (and
226
+ * `shadowHostSelectors` inside a shadow root; null for a region that has
227
+ * since left the page). null where installLiveRegionHook() wasn't called
228
+ * before the page loaded. What the page made available to announce, not
229
+ * what a screen reader said. A text given to a region behind an open
230
+ * modal dialog, which assistive technology did not get, is listed only
231
+ * with `{ includeBehindModal: true }`, marked `behindModal`. Needs
232
+ * @surea11y/core 1.14.0 or later.
233
+ * @param {import('playwright').Page} page
234
+ * @param {{ includeBehindModal?: boolean }} [options]
235
+ * @returns {Promise<Array<object>|null>}
236
+ */
237
+ static announcements(page, options) {
238
+ return new A11yCoreBuilder({ page })._announcementsIn(page, options);
239
+ }
240
+
179
241
  /**
180
242
  * @param {{ page: import('playwright').Page, url?: string }} opts
181
243
  * `page` must already be navigated to and settled at the URL to scan --
@@ -208,13 +270,23 @@ class A11yCoreBuilder extends A11yCoreBuilderBase {
208
270
 
209
271
  // A Playwright Page and a Frame both expose the same .evaluate(fn, arg)
210
272
  // and .url() shape, so this works unchanged for either.
211
- const runInFrame = async (frameOrPage, frameContextSelector) => {
212
- const frameUrl = this._url || (typeof frameOrPage.url === 'function' ? frameOrPage.url() : null);
273
+ // url() names the top page only; a frame is named by its own address.
274
+ const top = this._page.mainFrame ? this._page.mainFrame() : null;
275
+ const runInFrame = async (frameOrPage, frameContextSelector, frameOptions = engineOptions) => {
276
+ const isTop = frameOrPage === this._page || frameOrPage === top;
277
+ const ownUrl = typeof frameOrPage.url === 'function' ? frameOrPage.url() : null;
278
+ const frameUrl = isTop ? this._url || ownUrl : ownUrl;
213
279
  if (packScript) await frameOrPage.evaluate(packScript);
280
+ // The text of the style sheets the frame can't read, fetched from Node
281
+ // (binding-base 1.6.0 and core 1.14.0; nothing with older ones).
282
+ const scanOptions =
283
+ typeof this._styleSheetEngineOptions === 'function'
284
+ ? await this._styleSheetEngineOptions(frameOrPage, frameOptions)
285
+ : frameOptions;
214
286
  const result = rethrowEngineError(await frameOrPage.evaluate(scanInPage, {
215
287
  url: frameUrl,
216
288
  contextSelector: frameContextSelector,
217
- engineOptions,
289
+ engineOptions: scanOptions,
218
290
  runOnly
219
291
  }));
220
292
  this._warnScanGaps(result, '@surea11y/playwright');
@@ -224,6 +296,14 @@ class A11yCoreBuilder extends A11yCoreBuilderBase {
224
296
  return this._elementRef ? this._attachElementRefs(frameOrPage, result) : result;
225
297
  };
226
298
 
299
+ // .conditions() (binding-base 1.6.0): the page as it is, then under each
300
+ // condition, merged into one result.
301
+ if (this._conditions) {
302
+ return this._applyReportOnly(
303
+ await this._scanUnderConditions(() => runInFrame(this._page, contextSelector), this._conditionDriver())
304
+ );
305
+ }
306
+
227
307
  if (!this._scanFrames) {
228
308
  return this._applyReportOnly(await runInFrame(this._page, contextSelector));
229
309
  }
@@ -241,10 +321,22 @@ class A11yCoreBuilder extends A11yCoreBuilderBase {
241
321
  // passing the top frame's selector on would leave out every frame that
242
322
  // doesn't happen to contain the same element (before 1.10.0 such a frame
243
323
  // was silently scanned whole). exclude() still applies in every frame.
324
+ // Each frame read as core's own scan across frames reads it
325
+ // (binding-base's frames helpers, 1.7 and later): one the page doesn't
326
+ // show, that is excluded or outside include()'s roots, or that shows
327
+ // nothing is left out; one under aria-hidden is scanned as aria-hidden.
328
+ // A frame inside one inherits how it is read.
329
+ const readings = new Map();
330
+ const readingOf = (frame) => {
331
+ if (!readings.has(frame)) readings.set(frame, this._readFrame(frame, mainFrame, readingOf, engineOptions, contextSelector));
332
+ return readings.get(frame);
333
+ };
244
334
  const frames = [];
245
335
  for (const frame of subFrames) {
246
336
  try {
247
- frames.push(this._applyReportOnly(await runInFrame(frame, null)));
337
+ const reading = await readingOf(frame);
338
+ if (reading.skipped) continue;
339
+ frames.push(this._applyReportOnly(await runInFrame(frame, null, frameEngineOptions(engineOptions, reading))));
248
340
  } catch (e) {
249
341
  // A frame can detach/navigate away mid-scan, or be a sandboxed
250
342
  // frame the browser blocks scripting in -- don't let one bad frame
@@ -259,6 +351,74 @@ class A11yCoreBuilder extends A11yCoreBuilderBase {
259
351
  return { topFrame, frames };
260
352
  }
261
353
 
354
+ /**
355
+ * How a sub-frame is read: `{ skipped }`, `{ ariaHidden }` or `{}`, from
356
+ * its element in its parent frame and its own document, as core's scan
357
+ * across frames reads it. Without binding-base's frames helpers, every
358
+ * frame is scanned as before.
359
+ */
360
+ async _readFrame(frame, mainFrame, readingOf, engineOptions, contextSelector) {
361
+ if (typeof readFrameElement !== 'function') return {};
362
+ const parent = frame.parentFrame && frame.parentFrame();
363
+ const above = parent && parent !== mainFrame ? await readingOf(parent) : {};
364
+ if (above.skipped) return above;
365
+ let own = {};
366
+ try {
367
+ const handle = await frame.frameElement();
368
+ own = await handle.evaluate(readFrameElement, frameReadingOptions(engineOptions, contextSelector, parent === mainFrame));
369
+ await handle.dispose().catch(() => {});
370
+ if (!own.skipped && (await frame.evaluate(isFrameDocumentEmpty))) own = { skipped: 'empty' };
371
+ } catch (e) {
372
+ own = {};
373
+ }
374
+ return own.skipped ? own : inheritFrameReading(above, own);
375
+ }
376
+
377
+ /**
378
+ * The driver steps .conditions() scans need: the viewport's width with
379
+ * page.setViewportSize() (its height kept) and the color scheme with
380
+ * page.emulateMedia(). Each condition sets both, from the page as it was,
381
+ * so one condition's width or scheme doesn't carry into the next; at the
382
+ * end the viewport goes back, and if a condition set a scheme, the page
383
+ * is left in the scheme it had before (a scheme emulated by the caller, or
384
+ * the system's). The scheme is set back by name, not cleared with null:
385
+ * WebKit keeps a dark emulation that null should clear.
386
+ */
387
+ _conditionDriver() {
388
+ const page = this._page;
389
+ let schemeSet = false;
390
+ let viewport = null;
391
+ // The scheme a condition without one goes back to.
392
+ let baseScheme = 'light';
393
+ return {
394
+ save: async () => {
395
+ const before = await page.evaluate(() => ({
396
+ width: innerWidth,
397
+ height: innerHeight,
398
+ dark: matchMedia('(prefers-color-scheme: dark)').matches
399
+ }));
400
+ viewport = page.viewportSize() || { width: before.width, height: before.height };
401
+ baseScheme = before.dark ? 'dark' : 'light';
402
+ return { viewport };
403
+ },
404
+ apply: async (condition) => {
405
+ await page.setViewportSize({ width: condition.width || viewport.width, height: viewport.height });
406
+ if (condition.colorScheme) {
407
+ await page.emulateMedia({ colorScheme: condition.colorScheme });
408
+ schemeSet = true;
409
+ } else if (schemeSet) {
410
+ await page.emulateMedia({ colorScheme: baseScheme });
411
+ schemeSet = false;
412
+ }
413
+ },
414
+ restore: async (state) => {
415
+ if (!state) return;
416
+ await page.setViewportSize(state.viewport);
417
+ if (schemeSet) await page.emulateMedia({ colorScheme: baseScheme });
418
+ }
419
+ };
420
+ }
421
+
262
422
  /**
263
423
  * Resolves each occurrence to a live ElementHandle, scoped to
264
424
  * frameOrPage's own document (a Playwright Page and Frame both expose the
@@ -309,6 +469,19 @@ class A11yCoreBuilder extends A11yCoreBuilderBase {
309
469
  * array (an element handle inside it arrives as the element) and are
310
470
  * spread in the page.
311
471
  */
472
+ /**
473
+ * For binding-base's style sheet step: fetch with the page's own request
474
+ * API, which carries its cookies, in the shape of fetch().
475
+ */
476
+ get _styleSheetFetch() {
477
+ const request = this._page && typeof this._page.request === 'object' ? this._page.request : null;
478
+ if (!request || typeof request.get !== 'function') return null;
479
+ return async (url) => {
480
+ const res = await request.get(url, { timeout: 5000 });
481
+ return { ok: res.ok(), text: () => res.text() };
482
+ };
483
+ }
484
+
312
485
  _evaluateInFrame(frameOrPage, fn, args) {
313
486
  // eslint-disable-next-line no-new-func
314
487
  return frameOrPage.evaluate(new Function('args', 'return (' + fn.toString() + ')(...args)'), args);
@@ -333,4 +506,17 @@ class A11yCoreBuilder extends A11yCoreBuilderBase {
333
506
  }
334
507
  }
335
508
 
509
+ // One of core's hook scripts (1.14.0 and later for the listener and
510
+ // live-region hooks), added as an init script, which runs before the page's
511
+ // own scripts.
512
+ function installHook(pageOrContext, method, scriptName) {
513
+ if (!pageOrContext || typeof pageOrContext.addInitScript !== 'function') {
514
+ throw new TypeError(`A11yCoreBuilder.${method}() requires a Playwright Page or BrowserContext (with an .addInitScript() method).`);
515
+ }
516
+ if (typeof core[scriptName] !== 'function') {
517
+ throw new Error(`A11yCoreBuilder.${method}() needs @surea11y/core 1.14.0 or later, which has ${scriptName}().`);
518
+ }
519
+ return pageOrContext.addInitScript({ content: core[scriptName]() });
520
+ }
521
+
336
522
  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 };