@surea11y/playwright 1.2.0 → 1.4.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,6 +9,10 @@ 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
+ `@surea11y/core` 1.12.0 or later comes with it as a peer dependency, as Playwright does: npm 7 and later, and pnpm 8 and later, install it for you, so the line above is all you need. With Yarn 1 or npm 6, which don't install peers, add `@surea11y/core` to that line.
13
+
14
+ Being a peer means your project and this binding share one copy of core. That matters as soon as your project uses core directly, to write a SARIF log or an HTML report (`@surea11y/core/sarif`, `/report`), read the rule catalogue, or keep a baseline: those read results with the same core that produced them, so a report never labels a finding with another release's rules. It holds when you bring your own core too: a linked checkout (`file:../core`), a monorepo, a fork, or a pinned release. Before 1.4.0, core was a regular dependency, and a project whose core differed from the binding's got a second copy without a word; such a project needed `"overrides": { "@surea11y/core": "$@surea11y/core" }` in its `package.json`, which it can now drop.
15
+
12
16
  `npm test` (in this repo) only needs Chromium. The cross-browser regression tests in `tests/cross-browser.test.js` (proving this works against Firefox/WebKit too, not just Chromium) additionally need `npx playwright install firefox webkit`. `npm test` also compiles `tests/types/usage.ts` with TypeScript against the shipped types (`typescript` is a dev dependency only).
13
17
 
14
18
  ## Usage
@@ -24,7 +28,7 @@ await page.goto('https://example.com/');
24
28
  const results = await new A11yCoreBuilder({ page })
25
29
  .include('#main') // optional -- call multiple times for multi-region scans
26
30
  .exclude('.cookie-banner') // optional
27
- .withTags(['wcag2a', 'wcag2aa'])
31
+ .withWcag('2.2', 'AA') // the rules for WCAG 2.2's A and AA criteria
28
32
  .disableRules(['meta-refresh-no-exceptions'])
29
33
  .options({ contrast: { mode: 'auditorAssist' } })
30
34
  .analyze();
@@ -35,17 +39,52 @@ await browser.close();
35
39
 
36
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.
37
41
 
38
- Every result says which `@surea11y/core` release produced it, in `results.engine.version` (for example `"1.10.0"`): quote it in a bug report, and compare it when two runs disagree.
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).
39
43
 
40
44
  Also see `examples/basic-scan.js` for a runnable script (`npm run example -- <url>`).
41
45
 
42
- `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.
46
+ `.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. The level is read in any case (`'aa'` is `'AA'`). 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.
47
+
48
+ `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, unless you ask for that with `.includeMode('or')` (below).
49
+
50
+ `.includeMode(mode)` decides how `.withRules()` and `.withTags()` combine when both are given: `'and'`, the default, runs only the rules that match both, and `'or'` runs those that match either. That's what lets a scan say "this area, plus these checks". A team that owns a design system's form components, say, can run every rule about forms and the contrast check too, in one scan:
51
+
52
+ ```js
53
+ const results = await new A11yCoreBuilder({ page })
54
+ .withTags('forms')
55
+ .withRules('contrast-computable')
56
+ .includeMode('or') // every forms rule, plus the contrast check
57
+ .analyze();
58
+ ```
59
+
60
+ Without `.includeMode('or')`, the same lines run no rule at all, since `contrast-computable` isn't tagged `forms`, and a scan of no rules looks clean. The same goes for a WCAG level tag beside a best practice: `.withTags('wcag2a').withRules('region')` runs nothing, and with `'or'` runs the `wcag2a` rules plus `region`. On its own, with no other selection, it changes nothing. A value other than `'and'` or `'or'` throws a `TypeError` with `code: 'INVALID_RUN_ONLY'` at the call. A `.withWcag()` target doesn't need it: its rules are always added to what tags and rules select.
61
+
62
+ `.wcagLevel(level)` sets the WCAG level of the criteria a scan reports, without changing which rules run: criteria above it are left out of `results.rulesResults`, while every selected rule still runs and reports in `results.checksResults`. It's what lets a scan that names a few checks say it is meant as WCAG AA. A team that gates each pull request on colour contrast alone, say, runs one check, which covers both 1.4.3 (AA) and 1.4.6 (AAA):
63
+
64
+ ```js
65
+ const results = await new A11yCoreBuilder({ page })
66
+ .withRules('contrast-computable')
67
+ .wcagLevel('AA') // report 1.4.3, not the AAA 1.4.6
68
+ .analyze();
69
+ ```
70
+
71
+ Without `.wcagLevel('AA')`, that scan reports 1.4.6 as well, so a site that meets AA can show a failing AAA criterion it never aimed for. With it, the scan reports 1.4.3 alone, and `results.engine.wcagLevel` says `'AA'`. A `.withWcag()` target already implies its level; `.wcagLevel()` is for selections that don't, and wins when both are given, as it does over a level given through `.options()`. `'A'`, `'AA'` or `'AAA'` in any case is accepted. Anything else throws a `TypeError` with `code: 'INVALID_ENGINE_OPTIONS'` at the call, and `null` clears it. Needs `@surea11y/core` 1.12.0 or later.
72
+
73
+ `.plannedChecks()` and `.plannedCriteria()` say what a scan *will* check before you run it: the rules it runs (entries with `ruleId`) and the criteria it reports in `rulesResults` (entries with `id`), worked out in Node from the same selection and options, with no page. Use them to record what a run covered next to its result, or to catch a selection that runs nothing, which would otherwise look like a clean scan:
74
+
75
+ ```js
76
+ const builder = new A11yCoreBuilder({ page }).withTags('forms').withRules('contrast-computable');
77
+ if (builder.plannedChecks().length === 0) {
78
+ throw new Error('This selection runs no rule. Did you mean .includeMode("or")?');
79
+ }
80
+ const results = await builder.analyze();
81
+ ```
43
82
 
44
83
  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.
45
84
 
46
85
  `.exclude(selector)` above excludes globally. Pass a second argument to scope it to specific rule IDs instead: `.exclude('.mat-select', { rules: ['aria-required-children'] })` skips `.mat-select` for that rule only — every other rule still sees it. Global and rule-scoped `.exclude()` calls compose freely.
47
86
 
48
- **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.
87
+ **Create one builder per scan.** `A11yCoreBuilder` is a mutable object with no reset between `.analyze()` calls — `include()`/`exclude()`/`withRules()`/`disableRules()`/`withTags()`/`disableTags()`/`options()`/`withCustomRules()`/`withPacks()` all push onto or merge into internal state that persists for the instance's lifetime. Calling one of them again before a second `.analyze()` call *accumulates* on top of the first scan's scope rather than replacing it (this is exactly what makes "call `.include()` several times for one scan," above, work — the same accumulation just also applies across separate scans if you reuse an instance). `.reportOnly()`/`.frames()`/`.elementRef()`/`.withWcag()`/`.withBestPractices()`/`.includeMode()`/`.wcagLevel()`/`.logger()` are the exception: each call replaces the previous value instead of merging with it.
49
88
 
50
89
  ### When `.include()` matches nothing, or doesn't parse
51
90
 
@@ -60,16 +99,31 @@ const gaps = getScanGaps(results);
60
99
  // message: 'Nothing was scanned: the scan scope matched no element ("#main").' }]
61
100
  ```
62
101
 
63
- Each gap has a `kind`: `'context-not-found'` (nothing was scanned), `'context-partly-not-found'` (some of several selectors matched nothing), or `'custom-rule-skipped'` (a custom rule the engine could not run, one per rule, from `results.skippedCustomRules`).
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)).
64
103
 
65
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.
66
105
 
106
+ That warning is the right default for a test run. A project that already handles gaps itself can take them over with `.logger(fn)`: `fn(gap, result)` is called once per gap, with the gap as `getScanGaps()` gives it and the result of the frame it came from, instead of `console.warn`. A scanning service that shows gaps to its users, say, can send them once to its own structured log, rather than also printing a loose line on the server's console for every scan:
107
+
108
+ ```js
109
+ const results = await new A11yCoreBuilder({ page })
110
+ .include('#checkout')
111
+ .logger((gap, frame) => log.warn({ url: frame.url, kind: gap.kind }, gap.message))
112
+ .analyze();
113
+ ```
114
+
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
+
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).
118
+
67
119
  ### Errors from the engine
68
120
 
69
121
  When the engine refuses its input, `.analyze()` rejects with an `EngineError` (exported from this package) carrying the engine's `code`:
70
122
 
71
123
  - `INVALID_RUN_ONLY`: none of the rule IDs given to `.withRules()`, or none of the tags given to `.withTags()`, is one the engine knows.
72
124
  - `INVALID_CONTEXT_SELECTOR`: an `.include()` selector the browser can't parse; `err.selector` names it.
125
+ - `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.
126
+ - `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.
73
127
 
74
128
  ```js
75
129
  const { A11yCoreBuilder, EngineError } = require('@surea11y/playwright');
@@ -105,7 +159,7 @@ test('page has no accessibility violations', async ({ page }) => {
105
159
  });
106
160
  ```
107
161
 
108
- To also fail when the scan left something out (an `.include()` that matched nothing, a custom rule 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 or a pack that didn't run), assert on `getScanGaps(results)` too: `expect(getScanGaps(results), formatFailures(results)).toEqual([])`.
109
163
 
110
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.
111
165
 
@@ -115,18 +169,18 @@ See `examples/playwright-test-example.spec.js` for a fuller, runnable version (`
115
169
 
116
170
  ```
117
171
  Error: 1) button-name-present (serious): This button has no accessible name.
118
- at html > body > button
119
- Provide visible button text or a programmatic accessible-name mechanism (for example aria-label) so assistive technologies can identify the button.
120
- 2) img-alt-present (serious): Missing alt attribute on <img>.
121
- at html > body > img
122
- Add an alt attribute (use alt="" only for decorative images).
172
+ at main > button
173
+ Give the button visible text, or name it with aria-label, so screen reader users know what it does.
174
+ 2) img-alt-present (serious): This <img> has no alt attribute.
175
+ at main > img
176
+ Add an alt attribute that says what the image shows, or alt="" if the image is purely decorative.
123
177
 
124
178
  Part of the scan scope was not scanned: no element matched "#sidebar".
125
179
 
126
- Scanned with @surea11y/core 1.10.0.
180
+ Scanned with @surea11y/core 1.12.0.
127
181
  ```
128
182
 
129
- 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.
183
+ 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.
130
184
 
131
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.
132
186
 
@@ -145,6 +199,16 @@ Unlike script-injection-based accessibility tools (which need a `postMessage`-ba
145
199
 
146
200
  `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`.
147
201
 
202
+ `@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.
203
+
204
+ ```js
205
+ const fs = require('node:fs');
206
+ const { renderSarifReport } = require('@surea11y/core/sarif');
207
+
208
+ const results = await new A11yCoreBuilder({ page }).frames(true).analyze();
209
+ fs.writeFileSync('a11y.sarif', renderSarifReport(results));
210
+ ```
211
+
148
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.
149
213
 
150
214
  ### Trimming the result to just violations
@@ -161,6 +225,8 @@ console.log(results.checksResults); // only fail/cantTell entries, pass/notAppli
161
225
 
162
226
  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.
163
227
 
228
+ 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.
229
+
164
230
  ### Getting a live element handle, not just a selector string
165
231
 
166
232
  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)`:
@@ -177,6 +243,55 @@ This resolves each occurrence to an `ElementHandle` in its own frame instead of
177
243
 
178
244
  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).
179
245
 
246
+ ### Web components: the internals hook
247
+
248
+ Many web components keep their `ElementInternals` in a private field and name themselves, set their states or give themselves a role through it:
249
+
250
+ ```js
251
+ class SubscribeCheckbox extends HTMLElement {
252
+ #internals = this.attachInternals();
253
+ constructor() {
254
+ super();
255
+ this.#internals.ariaLabel = 'Subscribe';
256
+ this.#internals.ariaChecked = 'false';
257
+ }
258
+ }
259
+ ```
260
+
261
+ The browser exposes that name, but no page script can read it back, so by default the scan asks about such a component (`cantTell`) instead of judging it. A component that's a `switch` only through `this.#internals.role` isn't even asked about: the scan doesn't see its role, so it isn't checked at all.
262
+
263
+ `A11yCoreBuilder.installInternalsHook(pageOrContext)` installs `@surea11y/core`'s opt-in hook, which records each component's internals for the scan to read. Call it **before** `page.goto()`, on the page, or on its browser context to cover every page the context opens:
264
+
265
+ ```js
266
+ const context = await browser.newContext();
267
+ await A11yCoreBuilder.installInternalsHook(context); // before any page navigates
268
+ const page = await context.newPage();
269
+ await page.goto('https://example.com/');
270
+
271
+ const results = await new A11yCoreBuilder({ page }).analyze();
272
+ results.engine.environment.internalsHook; // 'early': the hook ran before the page's scripts
273
+ ```
274
+
275
+ With `@playwright/test`, install it in a `beforeEach` on the `context` fixture, or on `page` before the test navigates.
276
+
277
+ With it, the checkbox above passes, an unnamed component that attaches internals fails like any unnamed control, and the switch is checked as a switch, so it fails without a name. Playwright runs init scripts (`addInitScript()`) before the page's own scripts in every frame, and again after each navigation, so one call covers a page or context for its lifetime. It works in Chromium, Firefox and WebKit.
278
+
279
+ - **Before the page loads.** On a page that's already loaded, the call has no effect until the next navigation (a reload will do), and the result has no `internalsHook`.
280
+ - **For test and audit runs.** The hook wraps `HTMLElement.prototype.attachInternals` (components get the same internals back), adds a stack frame to errors thrown through it, and keeps its record under a global symbol, where any script on the page can read every component's internals. That's why it's opt-in.
281
+ - **Without it**, `.analyze()` says so once per scan when it asked about such components (`1 custom element was asked about because the scan could not read...`), and `getScanNotes()` gives that note as `kind: 'internals-hook'`.
282
+
283
+ ### Forced colors
284
+
285
+ 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:
286
+
287
+ ```js
288
+ await page.emulateMedia({ forcedColors: 'active' });
289
+ const results = await new A11yCoreBuilder({ page }).analyze();
290
+ results.engine.environment.forcedColors; // 'active'
291
+ ```
292
+
293
+ `browser.newContext({ forcedColors: 'active' })` does the same for a whole context, and `@playwright/test` takes it as a `use` option. The contrast rules still measure the page's own colors under forced colors, since WCAG judges contrast in those, so results match a scan with forced colors off; a contrast finding the engine couldn't measure that way carries `details.forcedColors: true`. When forced colors were active, `formatFailures()` adds a line saying so, since it's easy to miss on a CI agent with high contrast turned on.
294
+
180
295
  ### Registering a custom rule at runtime
181
296
 
182
297
  `@surea11y/core` supports registering additional rules per-scan via `engineOptions.customRules`. Use `.withCustomRules()` to register one:
@@ -209,24 +324,85 @@ const results = await new A11yCoreBuilder({ page })
209
324
 
210
325
  **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.
211
326
 
327
+ A custom rule you turn off for one scan (`.withCustomRules(rules).disableRules('org-banner-text')`) is listed in `skippedCustomRules` with `excluded: true` and isn't a scan gap, so it isn't warned about (core 1.12.0 and later).
328
+
212
329
  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`.)
213
330
 
331
+ ### Checking against EN 301 549
332
+
333
+ EN 301 549, the standard the European Accessibility Act refers to, restates WCAG's Level A and AA criteria in its chapter 9. `.options({ profile })` runs the rules for its version, and each finding carries its EN 301 549 clause beside its WCAG criterion, in `meta.normativeMappings` (WCAG 1.1.1 is clause 9.1.1.1):
334
+
335
+ ```js
336
+ // EN 301 549 V4.1.1 (WCAG 2.2 A and AA); 'en301549-v3.2.1' for V3.2.1 (WCAG 2.1 A and AA)
337
+ const results = await new A11yCoreBuilder({ page })
338
+ .options({ profile: 'en301549-v4.1.1' })
339
+ .analyze();
340
+
341
+ results.engine.profile; // 'en301549-v4.1.1'
342
+ ```
343
+
344
+ `.withWcag()`, `.withRules()` and `.withTags()` select rules instead of a profile, so leave them out when scanning with one. As with any target, a scan with no failures means no rule found a violation, not that the page conforms: most criteria need a person to check them. A profile name core doesn't know is not an error: the scan runs without it, core warns in the page's console, and `results.engine.profile` is left out.
345
+
346
+ ### Scanning with packs: standards, checklists and your own rules
347
+
348
+ A pack brings rules, variants of core's rules, a standard or a checklist, and their profiles and messages, from a package of its own: a national standard such as RGAA, or your organisation's accessibility policy. `@surea11y/core` runs a pack as it runs its own rules and standards, so its results, rollups and report entries look like core's. Packs need `@surea11y/core` 1.11.1 or later.
349
+
350
+ `.withPacks()` registers packs in the page, and in every frame with `.frames(true)`, before the scan; a pack's profile is chosen with `.options({ profile })`:
351
+
352
+ ```js
353
+ const acmePolicy = require('@acme/a11y-policy'); // a pack
354
+
355
+ const results = await new A11yCoreBuilder({ page })
356
+ .withPacks(acmePolicy)
357
+ .options({ profile: 'acme-web-2026' })
358
+ .analyze();
359
+
360
+ results.engine.packs; // ['@acme/a11y-policy@1.0.0']
361
+ results.engine.profile; // 'acme-web-2026'
362
+
363
+ // A checklist's items, each one result, beside core's WCAG rollups:
364
+ results.rulesResults.filter((r) => r.meta && r.meta.standard === 'Acme web policy');
365
+ ```
366
+
367
+ 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.
368
+
369
+ **Writing a pack.** A pack is an object made with `definePack` from `@surea11y/core/pack`. [`examples/acme-policy-pack.js`](./examples/acme-policy-pack.js) is a small one: a house rule, a checklist profile (WCAG 2.2 A and AA, `region`, and the house rule) and two checklist items. `npm run example:pack` scans a page with it, and [`examples/playwright-test-example.spec.js`](./examples/playwright-test-example.spec.js) uses it as a test gate. For a pack of your own, `npx surea11y-pack new <folder>` (from `@surea11y/core`) writes a package that works as generated, with its tests, docs and lint; core's [`PACKS.md`](https://github.com/SureA11y/core/blob/main/docs/PACKS.md) is the guide.
370
+
371
+ **When a pack doesn't run.** `.withPacks()` builds the page's script with the `@surea11y/core` this binding loads, and checks each pack as it does: `.analyze()` throws before scanning for a pack that core can't run, such as one whose `core` range leaves out the installed core, or whose profile names a rule that doesn't exist. A pack the page then doesn't run (one named with a raw `.options({ packs })` and never registered, or a page running another core version, when two copies of core are installed) is listed in `results.skippedPacks` with the reason. `getScanGaps()` reports that as `'pack-skipped'`, and `.analyze()` warns about it, so a test gate that asserts on `getScanGaps(results)` fails rather than passing with the pack's checks never run. Install the pack beside the binding, so npm resolves one core for both.
372
+
214
373
  ### Element addressing beyond a CSS selector
215
374
 
216
375
  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.
217
376
 
218
377
  ## TypeScript
219
378
 
220
- `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. `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.
379
+ `src/A11yCoreBuilder.d.ts` (re-exported from `src/index.d.ts`, wired up via `package.json`'s `types` field) ships types for the whole builder API and the result (`A11yCoreResult`, `CheckResult`, `Occurrence`, `CompositeResult`, etc.). The result types are built on the ones `@surea11y/core` ships, so they carry every field the engine returns (`engine.version`, `engine.environment`, `contextMatch`, `skippedCustomRules`, `shadowHostSelectors`, `margin`, ...); this package adds `elementHandle` and the `.frames(true)` shape. `EngineError`/`EngineErrorCode`, `getScanGaps()`/`ScanGap`, `getScanNotes()`/`ScanNote` and `formatOccurrenceLocation()` are typed too, and so are `withWcag()` and `wcagLevel()` (`WcagVersion`, `WcagLevelInput`), `plannedChecks()`/`plannedCriteria()` (`PlannedCheck`, `PlannedCriterion`), the static `installInternalsHook()`, and `withPacks()`, which takes a pack made with `definePack` (`PackLike`). Code that handles every `ScanGap` kind it knows and treats the rest in an `else` branch needs a branch for `'pack-skipped'`, which carries `pack` rather than `selectors`. `analyze()` is typed `Promise<A11yCoreResult | A11yCoreMultiFrameResult>` — narrow on `'topFrame' in results` (or cast, if you already know which mode you called) to get the specific shape back, since a fluent builder can't statically track that `.frames(true)` was called earlier in the chain. `playwright` is a `peerDependencies` entry (not just `devDependencies`) since the class's `page` argument and `Occurrence#elementHandle` both come from it — consumers need their own `playwright` install for the types to resolve, same as they already do to construct a `Page` in the first place.
380
+
381
+ ## What changes with `@surea11y/core` 1.12
382
+
383
+ 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):
384
+
385
+ - **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.
386
+ - **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.
387
+ - **Four rules count towards more criteria**, as W3C's ACT rules map them: `input-image-alt-present` adds 4.1.2, `aria-roles-valid` 1.3.1, `link-name-present` 2.4.9 (AAA), and `meta-refresh-timing-absent` 2.2.4 and 3.2.5 (AAA). The findings don't change; the 1.3.1 and 4.1.2 rollups can now fail where they passed.
388
+ - **Unnamed custom elements are questions.** A defined custom element with no visible name may name itself through `ElementInternals`, so it's `cantTell` (`name_internals`) where it used to fail. [`installInternalsHook()`](#web-components-the-internals-hook) lets the engine decide.
389
+ - **`engine.wcagLevel`** records the level a scan was gated by, and [`.wcagLevel()`](#usage) sets it.
390
+ - **`engine.environment.forcedColors`** records whether the page was in [forced colors](#forced-colors).
391
+ - **A custom rule you exclude** isn't a scan gap any more, so `.disableRules()` of one prints no warning.
392
+ - **Rule IDs in another case select their rule**: `.withRules('IMG-ALT-PRESENT')` used to throw `INVALID_RUN_ONLY` or be ignored.
393
+ - **`runOnly.optInTags` on its own throws** `INVALID_RUN_ONLY`; it was accepted and did nothing. Opt-in rules are unlocked with `.options({ optInRules })`.
394
+ - **A finding in a shadow tree is located through its hosts**, as `#card >>> img`, in core's HTML report, SARIF, JUnit and baselines, as `formatFailures()` already did.
395
+ - **An inline `policyContract`** with an unknown value in `allowedOutcomes` or `allowedConfidence` drops that value with a warning, where it turned every check into `cantTell`.
221
396
 
222
- ## Rule changes in `@surea11y/core` 1.10.0
397
+ ## What changes with `@surea11y/core` 1.11
223
398
 
224
- The binding passes rule IDs and tags 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):
399
+ 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):
225
400
 
226
- - `landmark-role-name-present` is new: an element with `role="region"` or `role="form"` and no accessible name (best practice, reported as `cantTell`).
227
- - `label-title-only` is deprecated, replaced by `form-control-programmatic-label-quality`, which reported the same fields. It now always reports `notApplicable`; its ID still resolves, so a `.withRules()` or `.disableRules()` list naming it keeps working until core 2.0.0.
228
- - Several `manual` rules, including the landmark rules, report `pass` when they checked something and found it fine, where they reported `notApplicable`. Under `.include()`, rules that compare elements across the page (`landmark-unique`, `heading-order`, `accesskeys`, ...) report `notApplicable`, since a scan of one region can't see the rest.
229
- - A rule that measures against a threshold (contrast, target size, text spacing) can carry `margin` on its result: how close the closest passing element came. It is never a finding.
401
+ - **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.
402
+ - **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.
403
+ - **`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.
404
+ - **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.
405
+ - **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)).
230
406
 
231
407
  ## Building another framework binding?
232
408
 
package/package.json CHANGED
@@ -1,16 +1,23 @@
1
1
  {
2
2
  "name": "@surea11y/playwright",
3
- "version": "1.2.0",
4
- "description": "Playwright binding for surea11y -- scan real, live-rendered pages for accessibility issues.",
3
+ "version": "1.4.0",
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",
7
7
  "a11y",
8
+ "a11y-testing",
8
9
  "wcag",
10
+ "wcag21",
9
11
  "wcag22",
12
+ "en301549",
13
+ "en-301-549",
14
+ "european-accessibility-act",
10
15
  "accessibility-testing",
11
16
  "playwright",
17
+ "playwright-test",
12
18
  "e2e",
13
19
  "e2e-testing",
20
+ "end-to-end",
14
21
  "audit",
15
22
  "aria",
16
23
  "surea11y"
@@ -39,20 +46,22 @@
39
46
  "LICENSE"
40
47
  ],
41
48
  "dependencies": {
42
- "@surea11y/binding-base": "^1.2.0",
43
- "@surea11y/core": "^1.10.0"
49
+ "@surea11y/binding-base": "^1.4.0"
44
50
  },
45
51
  "peerDependencies": {
52
+ "@surea11y/core": ">=1.12.0",
46
53
  "playwright": ">=1.0.0"
47
54
  },
48
55
  "devDependencies": {
56
+ "@surea11y/core": "^1.12.0",
49
57
  "@types/node": "^20.19.43",
50
- "playwright": "^1.61.1",
51
- "typescript": "^5.9.3"
58
+ "playwright": "^1.64.0",
59
+ "typescript": "^7.0.2"
52
60
  },
53
61
  "scripts": {
54
62
  "test": "node --test tests/*.test.js",
55
63
  "example": "node examples/basic-scan.js",
56
- "example:e2e": "playwright test examples/playwright-test-example.spec.js"
64
+ "example:e2e": "playwright test examples/playwright-test-example.spec.js",
65
+ "example:pack": "node examples/scan-with-pack.js"
57
66
  }
58
67
  }
@@ -1,4 +1,4 @@
1
- import type { Page, ElementHandle } from 'playwright';
1
+ import type { Page, BrowserContext, ElementHandle } 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
@@ -49,11 +49,14 @@ export type {
49
49
  /**
50
50
  * What analyze() rejects with when @surea11y/core refuses its input, with
51
51
  * the engine's `code`: `INVALID_RUN_ONLY` (withRules()/withTags() named no
52
- * rule or tag it knows) or `INVALID_CONTEXT_SELECTOR` (an include()
53
- * selector the browser can't parse; `selector` names it).
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).
54
56
  */
55
57
  export { EngineError } from '@surea11y/binding-base';
56
- export type { EngineErrorCode } from '@surea11y/binding-base';
58
+ export type { EngineErrorCode, PackLike, WcagVersion, WcagLevel, WcagLevelInput, PlannedCheck, PlannedCriterion } from '@surea11y/binding-base';
59
+ import type { PackLike, WcagVersion, WcagLevelInput, ScanGap, ScanNote, PlannedCheck, PlannedCriterion } from '@surea11y/binding-base';
57
60
 
58
61
  export type Category = Core.RuleMeta['category'];
59
62
  export type LocaleResolutionReason = Core.LocaleResolution['reason'];
@@ -121,6 +124,15 @@ export class A11yCoreBuilder {
121
124
  */
122
125
  constructor(opts: { page: Page; url?: string });
123
126
 
127
+ /**
128
+ * Installs @surea11y/core's opt-in internals hook on a Page, or on a
129
+ * BrowserContext for every page it opens, so a scan can read names,
130
+ * states and roles web components set through a private ElementInternals.
131
+ * Call it before page.goto(): it runs before the page's scripts in every
132
+ * frame and after each navigation.
133
+ */
134
+ static installInternalsHook(pageOrContext: Page | BrowserContext): Promise<void>;
135
+
124
136
  /** Scope the scan to one region. Call multiple times for a multi-region union. */
125
137
  include(selector: string): this;
126
138
  /**
@@ -138,21 +150,57 @@ export class A11yCoreBuilder {
138
150
  withRules(ruleIds: string | string[]): this;
139
151
  /** Never run these specific rule IDs (applied after withRules). */
140
152
  disableRules(ruleIds: string | string[]): this;
153
+ /**
154
+ * Run the rules for a WCAG conformance target: `withWcag('2.2', 'AA')`
155
+ * runs those of WCAG 2.2's A and AA criteria. withTags()/withRules() add
156
+ * to them. A later call replaces the target.
157
+ */
158
+ withWcag(version: WcagVersion | 2.0 | 2.1 | 2.2, level?: WcagLevelInput): this;
159
+ /** Also run the best-practice rules, those that name no WCAG criterion. */
160
+ withBestPractices(enabled?: boolean): this;
161
+ /**
162
+ * How withRules() and withTags() combine when both are given: 'and' (the
163
+ * default) runs the rules matching both, 'or' those matching either. A
164
+ * later call replaces the mode.
165
+ */
166
+ includeMode(mode: 'and' | 'or'): this;
167
+ /**
168
+ * The WCAG level of the criteria the scan reports, without changing which
169
+ * rules run: `.withRules('contrast-computable').wcagLevel('AA')` reports
170
+ * 1.4.3 and not 1.4.6. Any case; null clears it. A later call replaces it.
171
+ */
172
+ wcagLevel(level: WcagLevelInput | null): this;
173
+ /**
174
+ * Where analyze() sends each scan gap instead of console.warn: called once
175
+ * per gap, with the result of the frame it came from, and once per scan
176
+ * for the internals-hook note (tell them apart by `kind`). `() => {}`
177
+ * silences them, `null` goes back to console.warn. A later call replaces it.
178
+ */
179
+ logger(fn: ((entry: ScanGap | ScanNote, result: A11yCoreResult) => void) | null): this;
141
180
  /** Merge arbitrary engineOptions (locale, contrast.mode, policyContract, ...). */
142
181
  options(partialEngineOptions: Record<string, unknown>): this;
143
182
  /** Register one or more custom rules for just this scan. Call multiple times to accumulate. */
144
183
  withCustomRules(rules: CustomRuleDescriptor | CustomRuleDescriptor[]): this;
184
+ /**
185
+ * Packs from `@surea11y/core/pack` (core 1.11 or later): registered in each
186
+ * frame before the scan, and named in `engineOptions.packs`.
187
+ */
188
+ withPacks(packs: PackLike | PackLike[]): this;
145
189
  /** Post-filter checksResults down to only the given outcomes. */
146
190
  reportOnly(outcomes: Outcome | Outcome[]): this;
147
191
  /** Opt in to also scanning every sub-frame on the page (including cross-origin iframes). */
148
192
  frames(enabled?: boolean): this;
149
193
  /** Opt in to resolving each fail/cantTell occurrence's selector to a live ElementHandle. */
150
194
  elementRef(enabled?: boolean): this;
195
+ /** The rules this scan will run, worked out in Node with no page (@surea11y/core 1.12.0 and later). */
196
+ plannedChecks(): PlannedCheck[];
197
+ /** The criteria this scan will report in rulesResults, worked out in Node with no page. */
198
+ plannedCriteria(): PlannedCriterion[];
151
199
 
152
200
  /**
153
201
  * Runs the scan. Returns { topFrame, frames } instead of a single result
154
202
  * when .frames(true) was used. Rejects with an EngineError when the engine
155
- * refuses the rule/tag lists or an include() selector.
203
+ * refuses its input (see EngineError).
156
204
  */
157
205
  analyze(): Promise<A11yCoreResult | A11yCoreMultiFrameResult>;
158
206
  }
@@ -178,10 +226,19 @@ export function formatFailures(
178
226
  * What a scan result says it left out, which its checksResults alone would
179
227
  * pass over as clean: an include() scope that matched no element
180
228
  * (`context-not-found`, nothing was scanned), some include() selectors that
181
- * matched nothing (`context-partly-not-found`), and each custom rule that
182
- * did not run (`custom-rule-skipped`). Each gap has a `message`. Throws a
229
+ * matched nothing (`context-partly-not-found`), each custom rule that did
230
+ * not run (`custom-rule-skipped`), and each pack that did not run
231
+ * (`pack-skipped`). Each gap has a `message`. Throws a
183
232
  * TypeError for a frames(true) result: call it on `topFrame` and on each
184
233
  * scanned frame.
185
234
  */
186
235
  export { getScanGaps, formatOccurrenceLocation } from '@surea11y/binding-base';
187
236
  export type { ScanGap, OccurrenceLocation } from '@surea11y/binding-base';
237
+
238
+ /**
239
+ * How the page was scanned, which a gap doesn't cover: `forced-colors` when
240
+ * the page was shown in forced colors, and `internals-hook` when the scan
241
+ * asked about web components it could have read with the internals hook.
242
+ */
243
+ export { getScanNotes } from '@surea11y/binding-base';
244
+ export type { ScanNote } from '@surea11y/binding-base';
@@ -1,12 +1,11 @@
1
1
  'use strict';
2
2
 
3
- const { runa11yCoreInPage } = require('@surea11y/core');
3
+ const { runa11yCoreInPage, internalsHookScript } = require('@surea11y/core');
4
4
  const {
5
5
  A11yCoreBuilderBase,
6
6
  createInPageScan,
7
7
  rethrowEngineError,
8
- queryOccurrenceElement,
9
- getScanGaps
8
+ queryOccurrenceElement
10
9
  } = require('@surea11y/binding-base');
11
10
 
12
11
  // Playwright's page.evaluate(fn, arg) (and frame.evaluate(fn, arg), same
@@ -147,6 +146,23 @@ const findOccurrenceElement = eval(`(args) => {
147
146
  * the previous value rather than merging with it.
148
147
  */
149
148
  class A11yCoreBuilder extends A11yCoreBuilderBase {
149
+ /**
150
+ * Installs @surea11y/core's opt-in internals hook, so a scan can read the
151
+ * names, states and roles web components set through a private
152
+ * ElementInternals. Takes a Page, or a BrowserContext to cover every page
153
+ * it opens. Call it before page.goto(): Playwright runs init scripts
154
+ * before the page's own scripts in every frame, and again after each
155
+ * navigation (addInitScript()). The page already loaded when it is called
156
+ * doesn't get it until it navigates. Resolves when the script is added.
157
+ * @param {import('playwright').Page | import('playwright').BrowserContext} pageOrContext
158
+ */
159
+ static installInternalsHook(pageOrContext) {
160
+ if (!pageOrContext || typeof pageOrContext.addInitScript !== 'function') {
161
+ throw new TypeError('A11yCoreBuilder.installInternalsHook() requires a Playwright Page or BrowserContext (with an .addInitScript() method).');
162
+ }
163
+ return pageOrContext.addInitScript({ content: internalsHookScript() });
164
+ }
165
+
150
166
  /**
151
167
  * @param {{ page: import('playwright').Page, url?: string }} opts
152
168
  * `page` must already be navigated to and settled at the URL to scan --
@@ -173,18 +189,22 @@ class A11yCoreBuilder extends A11yCoreBuilderBase {
173
189
  */
174
190
  async analyze() {
175
191
  const { contextSelector, engineOptions, runOnly } = this._buildEngineArgs();
192
+ // The script that registers withPacks()'s packs in a frame, which the
193
+ // scan names in engineOptions.packs; null without packs.
194
+ const packScript = this._packScript();
176
195
 
177
196
  // A Playwright Page and a Frame both expose the same .evaluate(fn, arg)
178
197
  // and .url() shape, so this works unchanged for either.
179
198
  const runInFrame = async (frameOrPage, frameContextSelector) => {
180
199
  const frameUrl = this._url || (typeof frameOrPage.url === 'function' ? frameOrPage.url() : null);
200
+ if (packScript) await frameOrPage.evaluate(packScript);
181
201
  const result = rethrowEngineError(await frameOrPage.evaluate(scanInPage, {
182
202
  url: frameUrl,
183
203
  contextSelector: frameContextSelector,
184
204
  engineOptions,
185
205
  runOnly
186
206
  }));
187
- this._warnScanGaps(result);
207
+ this._warnScanGaps(result, '@surea11y/playwright');
188
208
  return this._elementRef ? this._attachElementRefs(frameOrPage, result) : result;
189
209
  };
190
210
 
@@ -246,27 +266,6 @@ class A11yCoreBuilder extends A11yCoreBuilderBase {
246
266
  return result;
247
267
  }
248
268
 
249
- /**
250
- * Prints what the scan left out (getScanGaps(): an include() scope that
251
- * matched nothing, a custom rule that did not run) with console.warn,
252
- * once per scanned frame. @surea11y/core warns about these too, but in
253
- * the page's console, which a Playwright run does not show; a result
254
- * whose checksResults alone look clean would otherwise pass without a
255
- * word.
256
- */
257
- _warnScanGaps(result) {
258
- let gaps;
259
- try {
260
- gaps = getScanGaps(result);
261
- } catch (e) {
262
- return; // not a scan result; nothing to say about it here
263
- }
264
- const where = result.url ? ` (${result.url})` : '';
265
- for (const gap of gaps) {
266
- console.warn(`@surea11y/playwright${where}: ${gap.message}`);
267
- }
268
- }
269
-
270
269
  async _findElement(frameOrPage, occurrence) {
271
270
  const handle = await frameOrPage.evaluateHandle(findOccurrenceElement, {
272
271
  selector: occurrence.selector,
package/src/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  'use strict';
2
2
 
3
- const { EngineError, getScanGaps, formatOccurrenceLocation } = require('@surea11y/binding-base');
3
+ const { EngineError, getScanGaps, getScanNotes, formatOccurrenceLocation } = 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 };
7
+ module.exports = { A11yCoreBuilder, EngineError, formatFailures, formatOccurrenceLocation, getScanGaps, getScanNotes };