@surea11y/playwright 1.1.0 → 1.3.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/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
- `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`.
12
+ `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).
13
13
 
14
14
  ## Usage
15
15
 
@@ -24,7 +24,7 @@ await page.goto('https://example.com/');
24
24
  const results = await new A11yCoreBuilder({ page })
25
25
  .include('#main') // optional -- call multiple times for multi-region scans
26
26
  .exclude('.cookie-banner') // optional
27
- .withTags(['wcag2a', 'wcag2aa'])
27
+ .withWcag('2.2', 'AA') // the rules for WCAG 2.2's A and AA criteria
28
28
  .disableRules(['meta-refresh-no-exceptions'])
29
29
  .options({ contrast: { mode: 'auditorAssist' } })
30
30
  .analyze();
@@ -35,13 +35,60 @@ await browser.close();
35
35
 
36
36
  `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.
37
37
 
38
+ Every result says which `@surea11y/core` release produced it, in `results.engine.version` (for example `"1.11.1"`): quote it in a bug report, and compare it when two runs disagree.
39
+
38
40
  Also see `examples/basic-scan.js` for a runnable script (`npm run example -- <url>`).
39
41
 
40
- `withTags()`/`disableRules()` above have counterparts: `.withRules([...])` (only run these specific rule IDs) and `.disableTags([...])` (never run rules carrying any of these tags). All four compose the same way similar allow/deny-list options do in other accessibility testing tools, with one non-obvious rule worth knowing: a "disable" always wins over a "with" on the same ID/tag (e.g. `.withRules(['a']).disableRules(['a'])` drops `'a'` entirely), and combining `.withRules()` **and** `.withTags()` together requires a rule to satisfy *both* (`@surea11y/core`'s default `includeMode: 'and'`), not either one.
42
+ `.withWcag(version, level)` selects by conformance target: `.withWcag('2.2', 'AA')` runs the rules for WCAG 2.2's Level A and AA criteria, by the level each criterion has in that version (4.1.1 Parsing, which 2.2 removed, is part of a `'2.1'` target and not of a `'2.2'` one). `.withBestPractices()` adds the rules that name no WCAG criterion, such as `region` and `heading-order`; on its own it runs only those. `.withRules()` and `.withTags()` add to a target's rules, and the disable methods apply after. A version other than `'2.0'`, `'2.1'` or `'2.2'`, or a level other than `'A'`, `'AA'` or `'AAA'`, throws a `TypeError` with `code: 'INVALID_RUN_ONLY'` at the call. Both need `@surea11y/core` 1.11 or later.
43
+
44
+ `withTags()`/`disableRules()` have counterparts: `.withRules([...])` (only run these specific rule IDs) and `.disableTags([...])` (never run rules carrying any of these tags). All four compose the same way similar allow/deny-list options do in other accessibility testing tools, with one non-obvious rule worth knowing: a "disable" always wins over a "with" on the same ID/tag (e.g. `.withRules(['a']).disableRules(['a'])` drops `'a'` entirely), and combining `.withRules()` **and** `.withTags()` together requires a rule to satisfy *both* (`@surea11y/core`'s default `includeMode: 'and'`), not either one.
45
+
46
+ The four take a string or an array of strings. `undefined` (a missing config value) or an empty string throws a `TypeError` with `code: 'INVALID_RUN_ONLY'` at the call. A rule ID or tag the engine doesn't know is ignored, with a warning in the page's console, as long as another one in the list is known; when none is, `.analyze()` rejects with an `EngineError` (below), so a typo such as `.withTags(['wcag2.2aa'])` can't run no rules and pass.
41
47
 
42
48
  `.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.
43
49
 
44
- **Create one builder per scan.** `A11yCoreBuilder` is a mutable object with no reset between `.analyze()` calls — `include()`/`exclude()`/`withRules()`/`disableRules()`/`withTags()`/`disableTags()`/`options()`/`withCustomRules()` 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()` are the exception: each call replaces the previous value instead of merging with it.
50
+ **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()` are the exception: each call replaces the previous value instead of merging with it.
51
+
52
+ ### When `.include()` matches nothing, or doesn't parse
53
+
54
+ An `.include()` selector that matches no element scans nothing: every rule reports `notApplicable`, and `results.contextMatch` says so (`{ elementCount: 0, unmatchedSelectors: ['#main'] }`). With several `.include()` calls, the ones that match are scanned and the others are listed in `unmatchedSelectors`. Without `.include()`, `contextMatch` is `null`. (Before `@surea11y/core` 1.10.0 such a selector fell back to the whole page, so a typo scanned everything.) Since a scan of nothing has no failures, a gate on `checksResults` alone would pass; `getScanGaps(results)` lists what a scan left out, and `formatFailures(results)` (below) prints it:
55
+
56
+ ```js
57
+ const { A11yCoreBuilder, getScanGaps } = require('@surea11y/playwright');
58
+
59
+ const results = await new A11yCoreBuilder({ page }).include('#main').analyze();
60
+ const gaps = getScanGaps(results);
61
+ // [{ kind: 'context-not-found', selectors: ['#main'],
62
+ // message: 'Nothing was scanned: the scan scope matched no element ("#main").' }]
63
+ ```
64
+
65
+ 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`), 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)).
66
+
67
+ `.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.
68
+
69
+ ### Errors from the engine
70
+
71
+ When the engine refuses its input, `.analyze()` rejects with an `EngineError` (exported from this package) carrying the engine's `code`:
72
+
73
+ - `INVALID_RUN_ONLY`: none of the rule IDs given to `.withRules()`, or none of the tags given to `.withTags()`, is one the engine knows.
74
+ - `INVALID_CONTEXT_SELECTOR`: an `.include()` selector the browser can't parse; `err.selector` names it.
75
+ - `INVALID_ENGINE_OPTIONS`: with `.options({ strictOptions: true })`, an option the engine doesn't read or a value it can't use. The message names each, with the closest known option (`lcoale`: did you mean `locale`?). Without `strictOptions`, a likely typo is only warned about in the page's console.
76
+ - `PAGE_BUILTINS_BROKEN`: the page's own scripts broke a JavaScript built-in the engine relies on (`Array.prototype.filter`, `Map`, `JSON.stringify`, ...), so no result it gave could be trusted. The message names each one.
77
+
78
+ ```js
79
+ const { A11yCoreBuilder, EngineError } = require('@surea11y/playwright');
80
+
81
+ try {
82
+ await new A11yCoreBuilder({ page }).withTags(['wcag2.2aa']).analyze();
83
+ } catch (err) {
84
+ if (err instanceof EngineError && err.code === 'INVALID_RUN_ONLY') {
85
+ // runOnly.tags: no tag named "wcag2.2aa".
86
+ }
87
+ throw err;
88
+ }
89
+ ```
90
+
91
+ Any other error (a closed page, a navigation during the scan) rejects as it always has.
45
92
 
46
93
  This binding works against all three Playwright engines, not just Chromium — verified with real Firefox and WebKit runs, see `tests/cross-browser.test.js`.
47
94
 
@@ -58,26 +105,34 @@ test('page has no accessibility violations', async ({ page }) => {
58
105
 
59
106
  const results = await new A11yCoreBuilder({ page }).reportOnly(['fail']).analyze();
60
107
 
61
- expect(results.checksResults, formatFailures(results.checksResults)).toEqual([]);
108
+ expect(results.checksResults, formatFailures(results)).toEqual([]);
62
109
  });
63
110
  ```
64
111
 
112
+ 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([])`.
113
+
65
114
  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.
66
115
 
67
116
  ### Readable console/CI output on failure
68
117
 
69
- `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(checksResults)` 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:
118
+ `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:
70
119
 
71
120
  ```
72
121
  Error: 1) button-name-present (serious): This button has no accessible name.
73
- at html > body > button
74
- Provide visible button text or a programmatic accessible-name mechanism (for example aria-label) so assistive technologies can identify the button.
75
- 2) img-alt-present (serious): Missing alt attribute on <img>.
76
- at html > body > img
77
- Add an alt attribute (use alt="" only for decorative images).
122
+ at main > button
123
+ Give the button visible text, or name it with aria-label, so screen reader users know what it does.
124
+ 2) img-alt-present (serious): This <img> has no alt attribute.
125
+ at main > img
126
+ Add an alt attribute that says what the image shows, or alt="" if the image is purely decorative.
127
+
128
+ Part of the scan scope was not scanned: no element matched "#sidebar".
129
+
130
+ Scanned with @surea11y/core 1.11.1.
78
131
  ```
79
132
 
80
- ...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 only two that ever carry occurrences); pass `{ outcomes: [...] }` to narrow further. A thrown rule (`occurrences: []`, `error` set) is still surfaced using its `error` message rather than silently dropped.
133
+ 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 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.
134
+
135
+ ...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.
81
136
 
82
137
  ### Scanning every frame, including cross-origin iframes
83
138
 
@@ -92,6 +147,20 @@ for (const frame of results.frames) {
92
147
 
93
148
  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.
94
149
 
150
+ `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`.
151
+
152
+ `@surea11y/core`'s reporters take this result as it is (core 1.11.1 and later): `renderSarifReport(results)`, `renderJunitReport(results)`, `renderHtmlReport(results)` and the baseline functions report every frame's findings, and a frame that couldn't be scanned as not scanned, so it never reads as a pass.
153
+
154
+ ```js
155
+ const fs = require('node:fs');
156
+ const { renderSarifReport } = require('@surea11y/core/sarif');
157
+
158
+ const results = await new A11yCoreBuilder({ page }).frames(true).analyze();
159
+ fs.writeFileSync('a11y.sarif', renderSarifReport(results));
160
+ ```
161
+
162
+ `.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.
163
+
95
164
  ### Trimming the result to just violations
96
165
 
97
166
  By default `analyze()` returns every rule's outcome, including `pass`/`notApplicable` — `@surea11y/core`'s own deliberate "not a violations-only list" design. Use `.reportOnly()` to post-filter down to only the outcomes you care about:
@@ -106,6 +175,8 @@ console.log(results.checksResults); // only fail/cantTell entries, pass/notAppli
106
175
 
107
176
  Valid outcome values are `'pass'`, `'fail'`, `'cantTell'`, `'notApplicable'`. This is pure binding-layer filtering — the engine itself still computes every rule; nothing about the scan itself changes. Combines with `.frames(true)`: the filter is applied to `results.topFrame` and each entry of `results.frames` independently.
108
177
 
178
+ A result trimmed this way is no longer the whole scan to `@surea11y/core`'s reporters: JUnit counts one test per rule it finds, and EARL makes one assertion per rule. To keep a result small and still hand it to them, ask the engine for a compact one instead, with `.options({ output: { detail: 'findings' } })`: a rule that passed or did not apply keeps only its outcome, and every reporter reads it as the full result. An empty page's result goes from about 236 KB to 80 KB.
179
+
109
180
  ### Getting a live element handle, not just a selector string
110
181
 
111
182
  By default each occurrence carries a CSS selector + HTML snippet, not a live reference to the element. Opt in to a real Playwright `ElementHandle` with `.elementRef(true)`:
@@ -118,7 +189,7 @@ await failing.occurrences[0].elementHandle.screenshot({ path: 'flagged.png' });
118
189
  await failing.occurrences[0].elementHandle.click();
119
190
  ```
120
191
 
121
- This resolves `occurrence.selector` to an `ElementHandle` (via `page.$()`/`frame.$()`) instead of leaving you to re-resolve a possibly-stale selector string yourself. Default off — resolving a handle per occurrence is a real page query per occurrence, so it costs more than a plain `.analyze()`. Combines with `.frames(true)`: each frame's occurrences resolve against that frame's own document. Not every occurrence has one target element — a page-wide finding (some `manual`/`cantTell` rules) can carry `selector: ""`, in which case `occurrence.elementHandle` is `null` rather than a handle.
192
+ This resolves each occurrence to an `ElementHandle` in its own frame instead of leaving you to re-resolve a possibly-stale selector string yourself. An occurrence inside a shadow tree is found through its `shadowHostSelectors` (below), so the handle is the flagged element even when a plain `page.$(occurrence.selector)` would match another one elsewhere on the page. Default off — resolving a handle per occurrence is a real page query per occurrence, so it costs more than a plain `.analyze()`. Combines with `.frames(true)`: each frame's occurrences resolve against that frame's own document. Not every occurrence has one target element — a page-wide finding (some `manual`/`cantTell` rules) can carry `selector: ""`, in which case `occurrence.elementHandle` is `null` rather than a handle; so is an occurrence whose element (or a shadow host on the way to it) is gone by the time it is resolved.
122
193
 
123
194
  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).
124
195
 
@@ -141,7 +212,7 @@ const results = await new A11yCoreBuilder({ page })
141
212
  .analyze();
142
213
  ```
143
214
 
144
- A custom rule descriptor is the same shape as one of `@surea11y/core`'s own internal rule modules (`{ id, meta, runInPage, applicability?, data? }`) — see its [`ENGINE_OPTIONS.md`](https://github.com/SureA11y/core/blob/main/docs/ENGINE_OPTIONS.md) for the full contract. Results appear in `checksResults` exactly like a built-in rule's, including automatic `selector`/`html`/`structuralPath` fill-in. Registered per-scan only (nothing persists between calls or shows up in any catalog listing), and a custom rule whose `id` collides with a built-in one overrides it for that scan.
215
+ A custom rule descriptor is the same shape as one of `@surea11y/core`'s own internal rule modules (`{ id, meta, runInPage, applicability?, data? }`) — see its [`ENGINE_OPTIONS.md`](https://github.com/SureA11y/core/blob/main/docs/ENGINE_OPTIONS.md) for the full contract. Results appear in `checksResults` exactly like a built-in rule's, including automatic `selector`/`html`/`structuralPath` fill-in. Registered per-scan only (nothing persists between calls or shows up in any catalog listing), and a custom rule whose `id` collides with a built-in one overrides it for that scan. A custom rule the engine can't run is listed in `results.skippedCustomRules` as `{ id, reason }`, and `getScanGaps()`/`formatFailures(results)` report it, instead of it looking like a rule that passed.
145
216
 
146
217
  Pass an array to register several at once, or call `.withCustomRules()` again to add more — like `.withRules()`/`.withTags()`, it accumulates rather than replacing what was already registered:
147
218
 
@@ -154,15 +225,52 @@ const results = await new A11yCoreBuilder({ page })
154
225
 
155
226
  **Why `.withCustomRules()` instead of the raw `.options({ customRules })` passthrough** (still supported, and composes with this method if you use both): `runInPage`/`applicability` must reach the page as a function-source *string*, not a live `Function` — a Playwright `page.evaluate()` argument crosses a JSON boundary that can't carry a live function reference, only a string `@surea11y/core` can reconstruct with `new Function` on the page side. Passing a raw live function via `.options()` directly would silently fail to serialize; `.withCustomRules()` calls `.toString()` on a live function for you, so you can write a normal function and not have to remember that constraint yourself. A string is still accepted as-is if you already have one.
156
227
 
157
- Invalid input (a missing/empty `id`, or a `runInPage`/`applicability` that's neither a function nor a non-empty string) throws immediately from `.withCustomRules()` itself, rather than surfacing later as a silently-skipped rule deep inside the page — easier to catch during development. (Note: a *raw* `.options({ customRules })` call bypasses this check entirely and defers to `@surea11y/core`'s own engine-side behavior, which silently skips an invalid descriptor rather than throwing.)
228
+ Invalid input (a missing/empty `id`, or a `runInPage`/`applicability` that's neither a function nor a non-empty string) throws immediately from `.withCustomRules()` itself, rather than surfacing later as a silently-skipped rule deep inside the page — easier to catch during development. (Note: a *raw* `.options({ customRules })` call bypasses this check entirely and defers to `@surea11y/core`'s own engine-side behavior, which skips an invalid descriptor rather than throwing, and lists it in `results.skippedCustomRules`.)
229
+
230
+ ### Scanning with packs: standards, checklists and your own rules
231
+
232
+ 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.
233
+
234
+ `.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 })`:
235
+
236
+ ```js
237
+ const acmePolicy = require('@acme/a11y-policy'); // a pack
238
+
239
+ const results = await new A11yCoreBuilder({ page })
240
+ .withPacks(acmePolicy)
241
+ .options({ profile: 'acme-web-2026' })
242
+ .analyze();
243
+
244
+ results.engine.packs; // ['@acme/a11y-policy@1.0.0']
245
+ results.engine.profile; // 'acme-web-2026'
246
+
247
+ // A checklist's items, each one result, beside core's WCAG rollups:
248
+ results.rulesResults.filter((r) => r.meta && r.meta.standard === 'Acme web policy');
249
+ ```
250
+
251
+ 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.
252
+
253
+ **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.
254
+
255
+ **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.
158
256
 
159
257
  ### Element addressing beyond a CSS selector
160
258
 
161
- Every occurrence already carries `selector` and (with `.elementRef(true)`, above) a live `ElementHandle`. It also carries `structuralPath` — a sibling-index path from the document root down to the flagged element (e.g. `[1, 0, 2]`) — a more robust identity than a selector string alone, since it survives some DOM changes a selector wouldn't (an id/class rename, for instance). No opt-in needed; it's already on every `fail`/`cantTell` occurrence today. See [`OUTPUT_SCHEMA.md`](https://github.com/SureA11y/core/blob/main/docs/OUTPUT_SCHEMA.md) for the full field description.
259
+ 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.
162
260
 
163
261
  ## TypeScript
164
262
 
165
- `src/A11yCoreBuilder.d.ts` (re-exported from `src/index.d.ts`, wired up via `package.json`'s `types` field) ships hand-written types for the whole builder API plus `@surea11y/core`'s native result shapes (`A11yCoreResult`, `CheckResult`, `Occurrence`, `CompositeResult`, etc.). `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.
263
+ `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` and `formatOccurrenceLocation()` are typed too, and so are `withWcag()` (`WcagVersion`, `WcagLevel`) 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.
264
+
265
+ ## What changes with `@surea11y/core` 1.11
266
+
267
+ The binding passes rule IDs, tags and options through to the engine, so these show in results without a change here (see core's [`CHANGELOG.md`](https://github.com/SureA11y/core/blob/main/CHANGELOG.md) for the full list):
268
+
269
+ - **Messages are reworded** in all five languages to say plainly what is wrong and what to do (`This <img> has no alt attribute.`). Message keys, rule IDs, reason codes and baselines are unchanged; a test that matches message text needs the new wording.
270
+ - **Contrast and target size measure what is on screen.** In a browser, the contrast rules check only text a reader can see, measure it against what is painted under it, and measure form field values and placeholders. `target-size-minimum` measures the area a pointer can hit, and exempts only links in a sentence. Expect new findings, and some old ones gone.
271
+ - **`aria-hidden-focus` maps to 4.1.2 only**, no longer to 2.4.7 Focus Visible, so `.withTags('wcag2aa')` alone no longer selects it.
272
+ - **A custom rule counts toward its WCAG criterion.** A `.withCustomRules()` rule with `meta.wcagSc` (or a WCAG `normativeMappings` entry) fails that criterion's rollup when it fails, and custom rules run after core's.
273
+ - **On/off options read as meant**: `.options({ perfStats: 'false' })` is off, where it was on. `.options({ strictOptions: true })` rejects any option the engine doesn't read (see [Errors from the engine](#errors-from-the-engine)).
166
274
 
167
275
  ## Building another framework binding?
168
276
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@surea11y/playwright",
3
- "version": "1.1.0",
3
+ "version": "1.3.0",
4
4
  "description": "Playwright binding for surea11y -- scan real, live-rendered pages for accessibility issues.",
5
5
  "keywords": [
6
6
  "accessibility",
@@ -39,18 +39,21 @@
39
39
  "LICENSE"
40
40
  ],
41
41
  "dependencies": {
42
- "@surea11y/binding-base": "^1.1.0",
43
- "@surea11y/core": "^1.5.0"
42
+ "@surea11y/binding-base": "^1.3.1",
43
+ "@surea11y/core": "^1.11.1"
44
44
  },
45
45
  "peerDependencies": {
46
46
  "playwright": ">=1.0.0"
47
47
  },
48
48
  "devDependencies": {
49
- "playwright": "^1.61.1"
49
+ "@types/node": "^20.19.43",
50
+ "playwright": "^1.64.0",
51
+ "typescript": "^7.0.2"
50
52
  },
51
53
  "scripts": {
52
54
  "test": "node --test tests/*.test.js",
53
55
  "example": "node examples/basic-scan.js",
54
- "example:e2e": "playwright test examples/playwright-test-example.spec.js"
56
+ "example:e2e": "playwright test examples/playwright-test-example.spec.js",
57
+ "example:pack": "node examples/scan-with-pack.js"
55
58
  }
56
59
  }
@@ -1,145 +1,84 @@
1
1
  import type { Page, ElementHandle } from 'playwright';
2
+ import type * as Core from '@surea11y/core';
3
+
4
+ // The result shapes are @surea11y/core's own types (shipped with it since
5
+ // 1.9.0, and checked there against real scan results), so they follow the
6
+ // engine instead of a copy of its docs. This file only adds what the
7
+ // binding puts on top: `elementHandle` on an occurrence with
8
+ // .elementRef(true), and the { topFrame, frames } shape of .frames(true).
9
+ // Every name this file exported before is still exported.
10
+
11
+ import type {
12
+ Outcome,
13
+ OutcomeNormalized,
14
+ Severity,
15
+ Confidence,
16
+ RuleType,
17
+ LocaleResolution,
18
+ RenderingEnvironment,
19
+ EngineInfo,
20
+ NormativeMapping,
21
+ VisibilityFilter,
22
+ Uncertainty,
23
+ UncertaintyCode,
24
+ Margin,
25
+ MarginDeclaration,
26
+ ContextMatch,
27
+ CompositeResult
28
+ } from '@surea11y/core';
29
+
30
+ export type {
31
+ Outcome,
32
+ OutcomeNormalized,
33
+ Severity,
34
+ Confidence,
35
+ RuleType,
36
+ LocaleResolution,
37
+ RenderingEnvironment,
38
+ EngineInfo,
39
+ NormativeMapping,
40
+ VisibilityFilter,
41
+ Uncertainty,
42
+ UncertaintyCode,
43
+ Margin,
44
+ MarginDeclaration,
45
+ ContextMatch,
46
+ CompositeResult
47
+ };
2
48
 
3
- // See surea11y's docs/OUTPUT_SCHEMA.md -- this file mirrors that document's
4
- // shapes exactly (plus the elementHandle field this binding adds on top when
5
- // .elementRef(true) is used). Keep in sync with that doc, not the other way
6
- // around -- it's the source of truth for what the engine actually returns.
7
-
8
- export type Outcome = 'pass' | 'fail' | 'cantTell' | 'notApplicable';
9
- export type OutcomeNormalized = 'pass' | 'fail' | 'cantTell' | 'inapplicable';
10
- export type Severity = 'minor' | 'moderate' | 'serious' | 'critical';
11
- export type Confidence = 'high' | 'medium' | 'low';
12
- export type RuleType = 'automatic' | 'manual';
13
- export type Category = 'perceivable' | 'operable' | 'understandable' | 'robust' | null;
14
-
15
- // The reason set is open: core can add a value in a minor release, so the
16
- // union stays assignable from any string rather than going stale.
17
- export type LocaleResolutionReason =
18
- | 'ok'
19
- | 'primary-subtag'
20
- | 'dictionary-not-loaded'
21
- | 'unknown-locale'
22
- | 'partial-dictionary'
23
- | (string & {});
24
-
25
- export interface LocaleResolution {
26
- requested: string;
27
- resolved: string;
28
- reason: LocaleResolutionReason;
29
- }
30
-
31
- export interface EngineInfo {
32
- tag: string;
33
- schemaVersion: string;
34
- locale: LocaleResolution;
35
- }
36
-
37
- export interface NormativeMapping {
38
- standard: string;
39
- version: string;
40
- requirement: string;
41
- title: string;
42
- conformanceLevel: string;
43
- }
44
-
45
- export interface CheckResultMeta {
46
- ruleId: string;
47
- ruleInterfaceVersion: string;
48
- ruleVersion: string;
49
- normative: boolean;
50
- atomic: boolean;
51
- category: Category;
52
- normativeMappings: NormativeMapping[];
53
- standard: string | null;
54
- applicability: string;
55
- expectation: string;
56
- references: string[];
57
- requirements: Record<string, unknown> | null;
58
- mappings: Record<string, unknown> | null;
59
- }
49
+ /**
50
+ * What analyze() rejects with when @surea11y/core refuses its input, with
51
+ * the engine's `code`: `INVALID_RUN_ONLY` (withRules()/withTags() named no
52
+ * rule or tag it knows), `INVALID_CONTEXT_SELECTOR` (an include() selector
53
+ * the browser can't parse; `selector` names it), `INVALID_ENGINE_OPTIONS`
54
+ * (an option `strictOptions: true` rejects) or `PAGE_BUILTINS_BROKEN` (the
55
+ * page's scripts broke a JavaScript built-in the engine relies on).
56
+ */
57
+ export { EngineError } from '@surea11y/binding-base';
58
+ export type { EngineErrorCode, PackLike, WcagVersion, WcagLevel } from '@surea11y/binding-base';
59
+ import type { PackLike, WcagVersion, WcagLevel } from '@surea11y/binding-base';
60
60
 
61
- export interface VisibilityFilter {
62
- targetSet: string;
63
- accEligible: boolean | null;
64
- reasons: string[];
65
- }
61
+ export type Category = Core.RuleMeta['category'];
62
+ export type LocaleResolutionReason = Core.LocaleResolution['reason'];
63
+ export type CheckResultMeta = Core.RuleMeta;
64
+ export type CompositeResultDetails = Core.CompositeResult['data']['details'];
66
65
 
67
- export interface Occurrence {
68
- selector: string;
69
- html: string;
70
- structuralPath: number[] | null;
71
- summary: string;
72
- hint: string;
73
- i18n: { summaryKey: string; hintKey: string; params: Record<string, unknown> } | null;
74
- data: {
75
- visibilityFilter?: VisibilityFilter;
76
- details?: Record<string, unknown>;
77
- };
66
+ export interface Occurrence extends Core.Occurrence {
78
67
  /**
79
68
  * Only present when `.elementRef(true)` was used. `null` when this
80
69
  * occurrence has no single resolvable target element (e.g. `selector` was
81
- * `""`) -- see A11yCoreBuilder#elementRef.
70
+ * `""`, or a shadow host on the way is gone) -- see A11yCoreBuilder#elementRef.
82
71
  */
83
72
  elementHandle?: ElementHandle | null;
84
73
  }
85
74
 
86
- export interface CheckResult {
87
- ruleId: string;
88
- outcome: Outcome;
89
- outcomeNormalized: OutcomeNormalized;
90
- severity: Severity;
91
- confidence: Confidence;
92
- type: RuleType;
75
+ export interface CheckResult extends Omit<Core.CheckResult, 'occurrences'> {
93
76
  occurrences: Occurrence[];
94
- title: string;
95
- description: string;
96
- i18n: { titleKey: string; descriptionKey: string } | null;
97
- meta: CheckResultMeta;
98
- engineOptions: Record<string, unknown>;
99
- schemaVersion: string;
100
- /** Present only if the rule threw, or the manual-fail-to-cantTell coercion fired. */
101
- error?: string;
102
- }
103
-
104
- export interface CompositeResultDetails {
105
- reasonCode: string;
106
- checksIds: string[];
107
- contributors: Array<{ testId: string; outcome: string; severity: string | null }>;
108
- metrics: {
109
- failCount: number;
110
- cantTellCount: number;
111
- notApplicableCount: number;
112
- passCount: number;
113
- missingCount: number;
114
- };
115
- }
116
-
117
- export interface CompositeResult {
118
- ruleId: string;
119
- outcome: Outcome;
120
- severity: Severity;
121
- confidence: Confidence;
122
- type: RuleType;
123
- title: string;
124
- description: string;
125
- meta: CheckResultMeta;
126
- engineOptions: Record<string, unknown>;
127
- schemaVersion: string;
128
- /** Always empty -- composites are rollups, not element-level findings. */
129
- occurrences: [];
130
- data: { details: CompositeResultDetails };
131
77
  }
132
78
 
133
79
  /** surea11y's native top-level result shape -- see docs/OUTPUT_SCHEMA.md. */
134
- export interface A11yCoreResult {
135
- engine: EngineInfo;
136
- url: string | null;
137
- title: string | null;
138
- timestamp: string | null;
139
- perfStats: Record<string, unknown> | null;
140
- contextSelector: string | string[] | null;
80
+ export interface A11yCoreResult extends Omit<Core.ScanResult, 'checksResults'> {
141
81
  checksResults: CheckResult[];
142
- rulesResults: CompositeResult[];
143
82
  }
144
83
 
145
84
  /** A sub-frame that couldn't be scanned (detached, navigated away, or sandboxed). */
@@ -202,10 +141,23 @@ export class A11yCoreBuilder {
202
141
  withRules(ruleIds: string | string[]): this;
203
142
  /** Never run these specific rule IDs (applied after withRules). */
204
143
  disableRules(ruleIds: string | string[]): this;
144
+ /**
145
+ * Run the rules for a WCAG conformance target: `withWcag('2.2', 'AA')`
146
+ * runs those of WCAG 2.2's A and AA criteria. withTags()/withRules() add
147
+ * to them. A later call replaces the target.
148
+ */
149
+ withWcag(version: WcagVersion | 2.0 | 2.1 | 2.2, level?: WcagLevel): this;
150
+ /** Also run the best-practice rules, those that name no WCAG criterion. */
151
+ withBestPractices(enabled?: boolean): this;
205
152
  /** Merge arbitrary engineOptions (locale, contrast.mode, policyContract, ...). */
206
153
  options(partialEngineOptions: Record<string, unknown>): this;
207
154
  /** Register one or more custom rules for just this scan. Call multiple times to accumulate. */
208
155
  withCustomRules(rules: CustomRuleDescriptor | CustomRuleDescriptor[]): this;
156
+ /**
157
+ * Packs from `@surea11y/core/pack` (core 1.11 or later): registered in each
158
+ * frame before the scan, and named in `engineOptions.packs`.
159
+ */
160
+ withPacks(packs: PackLike | PackLike[]): this;
209
161
  /** Post-filter checksResults down to only the given outcomes. */
210
162
  reportOnly(outcomes: Outcome | Outcome[]): this;
211
163
  /** Opt in to also scanning every sub-frame on the page (including cross-origin iframes). */
@@ -213,16 +165,40 @@ export class A11yCoreBuilder {
213
165
  /** Opt in to resolving each fail/cantTell occurrence's selector to a live ElementHandle. */
214
166
  elementRef(enabled?: boolean): this;
215
167
 
216
- /** Runs the scan. Returns { topFrame, frames } instead of a single result when .frames(true) was used. */
168
+ /**
169
+ * Runs the scan. Returns { topFrame, frames } instead of a single result
170
+ * when .frames(true) was used. Rejects with an EngineError when the engine
171
+ * refuses its input (see EngineError).
172
+ */
217
173
  analyze(): Promise<A11yCoreResult | A11yCoreMultiFrameResult>;
218
174
  }
219
175
 
220
176
  /**
221
- * Formats a checksResults array into a short, human-readable block -- one
222
- * entry per occurrence, not per rule. Meant for an assertion library's
223
- * failure-message parameter, e.g.
224
- * `expect(results.checksResults, formatFailures(results.checksResults)).toEqual([])`.
225
- * Deliberately framework-agnostic -- no dependency on any particular
226
- * `expect` implementation.
177
+ * Formats a scan result, or its checksResults array, into a short,
178
+ * human-readable block -- one entry per occurrence, not per rule, located
179
+ * through its shadow hosts (`host >>> selector`). Meant for an assertion
180
+ * library's failure-message parameter, e.g.
181
+ * `expect(results.checksResults, formatFailures(results)).toEqual([])`.
182
+ * Given the whole result, it also lists what the scan left out
183
+ * (getScanGaps()) and ends with the @surea11y/core release that produced
184
+ * it. Throws a TypeError for a frames(true) result: format `topFrame` and
185
+ * each frame on its own. Deliberately framework-agnostic -- no dependency
186
+ * on any particular `expect` implementation.
187
+ */
188
+ export function formatFailures(
189
+ input: A11yCoreResult | ReadonlyArray<CheckResult>,
190
+ opts?: { outcomes?: Outcome[] }
191
+ ): string;
192
+
193
+ /**
194
+ * What a scan result says it left out, which its checksResults alone would
195
+ * pass over as clean: an include() scope that matched no element
196
+ * (`context-not-found`, nothing was scanned), some include() selectors that
197
+ * matched nothing (`context-partly-not-found`), each custom rule that did
198
+ * not run (`custom-rule-skipped`), and each pack that did not run
199
+ * (`pack-skipped`). Each gap has a `message`. Throws a
200
+ * TypeError for a frames(true) result: call it on `topFrame` and on each
201
+ * scanned frame.
227
202
  */
228
- export function formatFailures(checksResults: CheckResult[], opts?: { outcomes?: Outcome[] }): string;
203
+ export { getScanGaps, formatOccurrenceLocation } from '@surea11y/binding-base';
204
+ export type { ScanGap, OccurrenceLocation } from '@surea11y/binding-base';
@@ -1,7 +1,47 @@
1
1
  'use strict';
2
2
 
3
3
  const { runa11yCoreInPage } = require('@surea11y/core');
4
- const { A11yCoreBuilderBase } = require('@surea11y/binding-base');
4
+ const {
5
+ A11yCoreBuilderBase,
6
+ createInPageScan,
7
+ rethrowEngineError,
8
+ queryOccurrenceElement,
9
+ getScanGaps
10
+ } = require('@surea11y/binding-base');
11
+
12
+ // Playwright's page.evaluate(fn, arg) (and frame.evaluate(fn, arg), same
13
+ // signature) only accepts ONE arg value -- page.evaluate(fn, a, b, c, d)
14
+ // throws "Too many arguments. If you need to pass more than 1 argument to
15
+ // the function wrap them in an object." (confirmed against a real Playwright
16
+ // page -- see ../core/docs/INTEGRATION.md for the full story, including why
17
+ // this differs from Puppeteer's variadic form). The scan takes 4 positional
18
+ // args, so wrap it in a single-arg function that destructures one options
19
+ // object, embedding the scan's own source so the wrapper stays fully
20
+ // self-contained once serialized into the page (it has zero free vars of
21
+ // its own -- see ../core/docs/RULE_AUTHORING.md for why that matters).
22
+ //
23
+ // The scan is core's runa11yCoreInPage wrapped by createInPageScan(), which
24
+ // returns an engine error (INVALID_RUN_ONLY, INVALID_CONTEXT_SELECTOR) as a
25
+ // plain object instead of throwing it: page.evaluate() keeps a thrown
26
+ // error's message but drops its `code`. rethrowEngineError() below throws
27
+ // it again on this side as an EngineError with `code` (and `selector`).
28
+ const inPageScan = createInPageScan(runa11yCoreInPage);
29
+ // eslint-disable-next-line no-eval
30
+ const scanInPage = eval(`(args) => {
31
+ const inPageScan = ${inPageScan.toString()};
32
+ return inPageScan(args.url, args.contextSelector, args.engineOptions, args.runOnly);
33
+ }`);
34
+
35
+ // Finds an occurrence's element through its shadow hosts. Since
36
+ // @surea11y/core 1.10.0 an occurrence inside a shadow tree carries
37
+ // `shadowHostSelectors`, and its `selector` holds only inside the last
38
+ // host's shadow root, so frame.$(selector) finds another element or none.
39
+ // Same single-argument wrapping as scanInPage, for evaluateHandle().
40
+ // eslint-disable-next-line no-eval
41
+ const findOccurrenceElement = eval(`(args) => {
42
+ const queryOccurrenceElement = ${queryOccurrenceElement.toString()};
43
+ return queryOccurrenceElement(args.selector, args.shadowHostSelectors);
44
+ }`);
5
45
 
6
46
  /**
7
47
  * Playwright binding for surea11y -- scans a real, already-rendered page.
@@ -41,6 +81,8 @@ const { A11yCoreBuilderBase } = require('@surea11y/binding-base');
41
81
  * // results.topFrame -- same shape as the single-frame case above
42
82
  * // results.frames -- array of the same native result shape, one per sub-frame
43
83
  *
84
+ * include() scopes the top frame only; every sub-frame is scanned whole.
85
+ *
44
86
  * Unlike script-injection-based accessibility engines (which need a
45
87
  * postMessage-based protocol, runPartial/finishRun, to reach cross-origin
46
88
  * iframes, since they're injected as a plain <script> and are fully subject
@@ -120,58 +162,57 @@ class A11yCoreBuilder extends A11yCoreBuilderBase {
120
162
 
121
163
  /**
122
164
  * Runs the scan and returns @surea11y/core's native result object.
165
+ *
166
+ * Rejects with an `EngineError` (from @surea11y/binding-base) carrying
167
+ * the engine's `code` when the engine refuses the input:
168
+ * `INVALID_RUN_ONLY` when none of the rule IDs, or none of the tags, given
169
+ * to withRules()/withTags() is one it knows, and
170
+ * `INVALID_CONTEXT_SELECTOR` (with `selector`) for an include() selector
171
+ * the browser can't parse.
123
172
  * @returns {Promise<object>} see ../core/docs/OUTPUT_SCHEMA.md
124
173
  */
125
174
  async analyze() {
126
175
  const { contextSelector, engineOptions, runOnly } = this._buildEngineArgs();
127
-
128
- // Playwright's page.evaluate(fn, arg) (and frame.evaluate(fn, arg), same
129
- // signature) only accepts ONE arg value -- page.evaluate(fn, a, b, c, d)
130
- // throws "Too many arguments. If you need to pass more than 1 argument
131
- // to the function wrap them in an object." (confirmed against a real
132
- // Playwright page -- see ../core/docs/INTEGRATION.md for the
133
- // full story, including why this differs from Puppeteer's variadic
134
- // form). runa11yCoreInPage itself takes 4 positional args, so wrap it in
135
- // a single-arg function that destructures one options object, embedding
136
- // runa11yCoreInPage's own source via .toString() so the wrapper stays
137
- // fully self-contained once serialized into the page (it has zero free
138
- // vars of its own -- see ../core/docs/RULE_AUTHORING.md for why that
139
- // matters).
140
- const wrapperSource = `(args) => {
141
- const runa11yCoreInPage = ${runa11yCoreInPage.toString()};
142
- return runa11yCoreInPage(args.url, args.contextSelector, args.engineOptions, args.runOnly);
143
- }`;
144
- // eslint-disable-next-line no-eval
145
- const wrapperFn = eval(wrapperSource);
176
+ // The script that registers withPacks()'s packs in a frame, which the
177
+ // scan names in engineOptions.packs; null without packs.
178
+ const packScript = this._packScript();
146
179
 
147
180
  // A Playwright Page and a Frame both expose the same .evaluate(fn, arg)
148
181
  // and .url() shape, so this works unchanged for either.
149
- const runInFrame = async (frameOrPage) => {
182
+ const runInFrame = async (frameOrPage, frameContextSelector) => {
150
183
  const frameUrl = this._url || (typeof frameOrPage.url === 'function' ? frameOrPage.url() : null);
151
- const result = await frameOrPage.evaluate(wrapperFn, {
184
+ if (packScript) await frameOrPage.evaluate(packScript);
185
+ const result = rethrowEngineError(await frameOrPage.evaluate(scanInPage, {
152
186
  url: frameUrl,
153
- contextSelector,
187
+ contextSelector: frameContextSelector,
154
188
  engineOptions,
155
189
  runOnly
156
- });
190
+ }));
191
+ this._warnScanGaps(result);
157
192
  return this._elementRef ? this._attachElementRefs(frameOrPage, result) : result;
158
193
  };
159
194
 
160
195
  if (!this._scanFrames) {
161
- return this._applyReportOnly(await runInFrame(this._page));
196
+ return this._applyReportOnly(await runInFrame(this._page, contextSelector));
162
197
  }
163
198
 
164
199
  const mainFrame = this._page.mainFrame();
165
- const topFrame = this._applyReportOnly(await runInFrame(mainFrame));
200
+ const topFrame = this._applyReportOnly(await runInFrame(mainFrame, contextSelector));
166
201
 
167
202
  // page.frames() includes the main frame itself -- exclude it here since
168
203
  // it's already covered by topFrame above, so callers don't have to
169
204
  // de-duplicate it themselves out of the frames array.
170
205
  const subFrames = this._page.frames().filter((f) => f !== mainFrame);
206
+ // include() scopes the top frame only: each sub-frame is scanned whole,
207
+ // as core's own runa11yCoreAcrossFrames does. Since @surea11y/core
208
+ // 1.10.0 a contextSelector that matches nothing scans nothing, so
209
+ // passing the top frame's selector on would leave out every frame that
210
+ // doesn't happen to contain the same element (before 1.10.0 such a frame
211
+ // was silently scanned whole). exclude() still applies in every frame.
171
212
  const frames = [];
172
213
  for (const frame of subFrames) {
173
214
  try {
174
- frames.push(this._applyReportOnly(await runInFrame(frame)));
215
+ frames.push(this._applyReportOnly(await runInFrame(frame, null)));
175
216
  } catch (e) {
176
217
  // A frame can detach/navigate away mid-scan, or be a sandboxed
177
218
  // frame the browser blocks scripting in -- don't let one bad frame
@@ -187,11 +228,11 @@ class A11yCoreBuilder extends A11yCoreBuilderBase {
187
228
  }
188
229
 
189
230
  /**
190
- * Resolves occurrence.selector to a live ElementHandle for every
191
- * fail/cantTell occurrence, scoped to frameOrPage's own document (a
192
- * Playwright Page and Frame both expose the same .$(selector) shape).
193
- * Mutates and returns the same result object -- it's a fresh object from
194
- * this scan, not shared external state.
231
+ * Resolves each occurrence to a live ElementHandle, scoped to
232
+ * frameOrPage's own document (a Playwright Page and Frame both expose the
233
+ * same .evaluateHandle(fn, arg) shape), through its shadow hosts when it
234
+ * has `shadowHostSelectors`. Mutates and returns the same result object
235
+ * -- it's a fresh object from this scan, not shared external state.
195
236
  */
196
237
  async _attachElementRefs(frameOrPage, result) {
197
238
  if (!Array.isArray(result.checksResults)) return result;
@@ -203,11 +244,42 @@ class A11yCoreBuilder extends A11yCoreBuilderBase {
203
244
  // rules) can carry "" -- not every occurrence resolves to one element,
204
245
  // so leave elementHandle null rather than passing "" to .$() (which
205
246
  // throws, it's not a valid CSS selector).
206
- occurrence.elementHandle = occurrence.selector ? await frameOrPage.$(occurrence.selector) : null;
247
+ occurrence.elementHandle = occurrence.selector ? await this._findElement(frameOrPage, occurrence) : null;
207
248
  }
208
249
  }
209
250
  return result;
210
251
  }
252
+
253
+ /**
254
+ * Prints what the scan left out (getScanGaps(): an include() scope that
255
+ * matched nothing, a custom rule that did not run) with console.warn,
256
+ * once per scanned frame. @surea11y/core warns about these too, but in
257
+ * the page's console, which a Playwright run does not show; a result
258
+ * whose checksResults alone look clean would otherwise pass without a
259
+ * word.
260
+ */
261
+ _warnScanGaps(result) {
262
+ let gaps;
263
+ try {
264
+ gaps = getScanGaps(result);
265
+ } catch (e) {
266
+ return; // not a scan result; nothing to say about it here
267
+ }
268
+ const where = result.url ? ` (${result.url})` : '';
269
+ for (const gap of gaps) {
270
+ console.warn(`@surea11y/playwright${where}: ${gap.message}`);
271
+ }
272
+ }
273
+
274
+ async _findElement(frameOrPage, occurrence) {
275
+ const handle = await frameOrPage.evaluateHandle(findOccurrenceElement, {
276
+ selector: occurrence.selector,
277
+ shadowHostSelectors: occurrence.shadowHostSelectors || null
278
+ });
279
+ const element = handle.asElement();
280
+ if (!element) await handle.dispose();
281
+ return element;
282
+ }
211
283
  }
212
284
 
213
285
  module.exports = { A11yCoreBuilder };
@@ -5,7 +5,8 @@
5
5
  // ../binding-base/README.md for the full rationale. Kept as a
6
6
  // real file here (not just re-exporting straight from src/index.js) so
7
7
  // `require('@surea11y/playwright/src/formatFailures')` keeps working for
8
- // anyone importing the submodule path directly.
8
+ // anyone importing the submodule path directly. Takes a whole scan result
9
+ // as well as its checksResults (binding-base 1.2.0 and later).
9
10
  const { formatFailures } = require('@surea11y/binding-base');
10
11
 
11
12
  module.exports = { formatFailures };
package/src/index.js CHANGED
@@ -1,6 +1,7 @@
1
1
  'use strict';
2
2
 
3
+ const { EngineError, getScanGaps, formatOccurrenceLocation } = require('@surea11y/binding-base');
3
4
  const { A11yCoreBuilder } = require('./A11yCoreBuilder');
4
5
  const { formatFailures } = require('./formatFailures');
5
6
 
6
- module.exports = { A11yCoreBuilder, formatFailures };
7
+ module.exports = { A11yCoreBuilder, EngineError, formatFailures, formatOccurrenceLocation, getScanGaps };