@surea11y/playwright 1.0.2 → 1.2.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
 
@@ -35,14 +35,57 @@ 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.10.0"`): 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
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.
41
43
 
44
+ 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
+
42
46
  `.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
47
 
44
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.
45
49
 
50
+ ### When `.include()` matches nothing, or doesn't parse
51
+
52
+ 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:
53
+
54
+ ```js
55
+ const { A11yCoreBuilder, getScanGaps } = require('@surea11y/playwright');
56
+
57
+ const results = await new A11yCoreBuilder({ page }).include('#main').analyze();
58
+ const gaps = getScanGaps(results);
59
+ // [{ kind: 'context-not-found', selectors: ['#main'],
60
+ // message: 'Nothing was scanned: the scan scope matched no element ("#main").' }]
61
+ ```
62
+
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`).
64
+
65
+ `.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
+
67
+ ### Errors from the engine
68
+
69
+ When the engine refuses its input, `.analyze()` rejects with an `EngineError` (exported from this package) carrying the engine's `code`:
70
+
71
+ - `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
+ - `INVALID_CONTEXT_SELECTOR`: an `.include()` selector the browser can't parse; `err.selector` names it.
73
+
74
+ ```js
75
+ const { A11yCoreBuilder, EngineError } = require('@surea11y/playwright');
76
+
77
+ try {
78
+ await new A11yCoreBuilder({ page }).withTags(['wcag2.2aa']).analyze();
79
+ } catch (err) {
80
+ if (err instanceof EngineError && err.code === 'INVALID_RUN_ONLY') {
81
+ // runOnly.tags: no tag named "wcag2.2aa".
82
+ }
83
+ throw err;
84
+ }
85
+ ```
86
+
87
+ Any other error (a closed page, a navigation during the scan) rejects as it always has.
88
+
46
89
  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
90
 
48
91
  ### Using it as an E2E accessibility gate
@@ -58,15 +101,17 @@ test('page has no accessibility violations', async ({ page }) => {
58
101
 
59
102
  const results = await new A11yCoreBuilder({ page }).reportOnly(['fail']).analyze();
60
103
 
61
- expect(results.checksResults, formatFailures(results.checksResults)).toEqual([]);
104
+ expect(results.checksResults, formatFailures(results)).toEqual([]);
62
105
  });
63
106
  ```
64
107
 
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([])`.
109
+
65
110
  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
111
 
67
112
  ### Readable console/CI output on failure
68
113
 
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:
114
+ `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
115
 
71
116
  ```
72
117
  Error: 1) button-name-present (serious): This button has no accessible name.
@@ -75,9 +120,15 @@ Error: 1) button-name-present (serious): This button has no accessible name.
75
120
  2) img-alt-present (serious): Missing alt attribute on <img>.
76
121
  at html > body > img
77
122
  Add an alt attribute (use alt="" only for decorative images).
123
+
124
+ Part of the scan scope was not scanned: no element matched "#sidebar".
125
+
126
+ Scanned with @surea11y/core 1.10.0.
78
127
  ```
79
128
 
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.
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.
130
+
131
+ ...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
132
 
82
133
  ### Scanning every frame, including cross-origin iframes
83
134
 
@@ -92,6 +143,10 @@ for (const frame of results.frames) {
92
143
 
93
144
  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
145
 
146
+ `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
+
148
+ `.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
+
95
150
  ### Trimming the result to just violations
96
151
 
97
152
  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:
@@ -118,7 +173,7 @@ await failing.occurrences[0].elementHandle.screenshot({ path: 'flagged.png' });
118
173
  await failing.occurrences[0].elementHandle.click();
119
174
  ```
120
175
 
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.
176
+ 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
177
 
123
178
  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
179
 
@@ -141,7 +196,7 @@ const results = await new A11yCoreBuilder({ page })
141
196
  .analyze();
142
197
  ```
143
198
 
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.
199
+ 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
200
 
146
201
  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
202
 
@@ -154,15 +209,24 @@ const results = await new A11yCoreBuilder({ page })
154
209
 
155
210
  **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
211
 
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.)
212
+ 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`.)
158
213
 
159
214
  ### Element addressing beyond a CSS selector
160
215
 
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.
216
+ 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
217
 
163
218
  ## TypeScript
164
219
 
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.
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.
221
+
222
+ ## Rule changes in `@surea11y/core` 1.10.0
223
+
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):
225
+
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.
166
230
 
167
231
  ## Building another framework binding?
168
232
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@surea11y/playwright",
3
- "version": "1.0.2",
3
+ "version": "1.2.0",
4
4
  "description": "Playwright binding for surea11y -- scan real, live-rendered pages for accessibility issues.",
5
5
  "keywords": [
6
6
  "accessibility",
@@ -39,14 +39,16 @@
39
39
  "LICENSE"
40
40
  ],
41
41
  "dependencies": {
42
- "@surea11y/core": "^1.1.0",
43
- "@surea11y/binding-base": "^1.1.0"
42
+ "@surea11y/binding-base": "^1.2.0",
43
+ "@surea11y/core": "^1.10.0"
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.61.1",
51
+ "typescript": "^5.9.3"
50
52
  },
51
53
  "scripts": {
52
54
  "test": "node --test tests/*.test.js",
@@ -1,128 +1,81 @@
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
- export interface EngineInfo {
16
- tag: string;
17
- schemaVersion: string;
18
- }
19
-
20
- export interface NormativeMapping {
21
- standard: string;
22
- version: string;
23
- requirement: string;
24
- title: string;
25
- conformanceLevel: string;
26
- }
27
-
28
- export interface CheckResultMeta {
29
- ruleId: string;
30
- ruleInterfaceVersion: string;
31
- ruleVersion: string;
32
- normative: boolean;
33
- atomic: boolean;
34
- category: Category;
35
- normativeMappings: NormativeMapping[];
36
- standard: string | null;
37
- applicability: string;
38
- expectation: string;
39
- references: string[];
40
- requirements: Record<string, unknown> | null;
41
- mappings: Record<string, unknown> | null;
42
- }
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) or `INVALID_CONTEXT_SELECTOR` (an include()
53
+ * selector the browser can't parse; `selector` names it).
54
+ */
55
+ export { EngineError } from '@surea11y/binding-base';
56
+ export type { EngineErrorCode } from '@surea11y/binding-base';
43
57
 
44
- export interface VisibilityFilter {
45
- targetSet: string;
46
- accEligible: boolean | null;
47
- reasons: string[];
48
- }
58
+ export type Category = Core.RuleMeta['category'];
59
+ export type LocaleResolutionReason = Core.LocaleResolution['reason'];
60
+ export type CheckResultMeta = Core.RuleMeta;
61
+ export type CompositeResultDetails = Core.CompositeResult['data']['details'];
49
62
 
50
- export interface Occurrence {
51
- selector: string;
52
- html: string;
53
- structuralPath: number[] | null;
54
- summary: string;
55
- hint: string;
56
- i18n: { summaryKey: string; hintKey: string; params: Record<string, unknown> } | null;
57
- data: {
58
- visibilityFilter?: VisibilityFilter;
59
- details?: Record<string, unknown>;
60
- };
63
+ export interface Occurrence extends Core.Occurrence {
61
64
  /**
62
65
  * Only present when `.elementRef(true)` was used. `null` when this
63
66
  * occurrence has no single resolvable target element (e.g. `selector` was
64
- * `""`) -- see A11yCoreBuilder#elementRef.
67
+ * `""`, or a shadow host on the way is gone) -- see A11yCoreBuilder#elementRef.
65
68
  */
66
69
  elementHandle?: ElementHandle | null;
67
70
  }
68
71
 
69
- export interface CheckResult {
70
- ruleId: string;
71
- outcome: Outcome;
72
- outcomeNormalized: OutcomeNormalized;
73
- severity: Severity;
74
- confidence: Confidence;
75
- type: RuleType;
72
+ export interface CheckResult extends Omit<Core.CheckResult, 'occurrences'> {
76
73
  occurrences: Occurrence[];
77
- title: string;
78
- description: string;
79
- i18n: { titleKey: string; descriptionKey: string } | null;
80
- meta: CheckResultMeta;
81
- engineOptions: Record<string, unknown>;
82
- schemaVersion: string;
83
- /** Present only if the rule threw, or the manual-fail-to-cantTell coercion fired. */
84
- error?: string;
85
- }
86
-
87
- export interface CompositeResultDetails {
88
- reasonCode: string;
89
- checksIds: string[];
90
- contributors: Array<{ testId: string; outcome: string; severity: string | null }>;
91
- metrics: {
92
- failCount: number;
93
- cantTellCount: number;
94
- notApplicableCount: number;
95
- passCount: number;
96
- missingCount: number;
97
- };
98
- }
99
-
100
- export interface CompositeResult {
101
- ruleId: string;
102
- outcome: Outcome;
103
- severity: Severity;
104
- confidence: Confidence;
105
- type: RuleType;
106
- title: string;
107
- description: string;
108
- meta: CheckResultMeta;
109
- engineOptions: Record<string, unknown>;
110
- schemaVersion: string;
111
- /** Always empty -- composites are rollups, not element-level findings. */
112
- occurrences: [];
113
- data: { details: CompositeResultDetails };
114
74
  }
115
75
 
116
76
  /** surea11y's native top-level result shape -- see docs/OUTPUT_SCHEMA.md. */
117
- export interface A11yCoreResult {
118
- engine: EngineInfo;
119
- url: string | null;
120
- title: string | null;
121
- timestamp: string | null;
122
- perfStats: Record<string, unknown> | null;
123
- contextSelector: string | string[] | null;
77
+ export interface A11yCoreResult extends Omit<Core.ScanResult, 'checksResults'> {
124
78
  checksResults: CheckResult[];
125
- rulesResults: CompositeResult[];
126
79
  }
127
80
 
128
81
  /** A sub-frame that couldn't be scanned (detached, navigated away, or sandboxed). */
@@ -196,16 +149,39 @@ export class A11yCoreBuilder {
196
149
  /** Opt in to resolving each fail/cantTell occurrence's selector to a live ElementHandle. */
197
150
  elementRef(enabled?: boolean): this;
198
151
 
199
- /** Runs the scan. Returns { topFrame, frames } instead of a single result when .frames(true) was used. */
152
+ /**
153
+ * Runs the scan. Returns { topFrame, frames } instead of a single result
154
+ * when .frames(true) was used. Rejects with an EngineError when the engine
155
+ * refuses the rule/tag lists or an include() selector.
156
+ */
200
157
  analyze(): Promise<A11yCoreResult | A11yCoreMultiFrameResult>;
201
158
  }
202
159
 
203
160
  /**
204
- * Formats a checksResults array into a short, human-readable block -- one
205
- * entry per occurrence, not per rule. Meant for an assertion library's
206
- * failure-message parameter, e.g.
207
- * `expect(results.checksResults, formatFailures(results.checksResults)).toEqual([])`.
208
- * Deliberately framework-agnostic -- no dependency on any particular
209
- * `expect` implementation.
161
+ * Formats a scan result, or its checksResults array, into a short,
162
+ * human-readable block -- one entry per occurrence, not per rule, located
163
+ * through its shadow hosts (`host >>> selector`). Meant for an assertion
164
+ * library's failure-message parameter, e.g.
165
+ * `expect(results.checksResults, formatFailures(results)).toEqual([])`.
166
+ * Given the whole result, it also lists what the scan left out
167
+ * (getScanGaps()) and ends with the @surea11y/core release that produced
168
+ * it. Throws a TypeError for a frames(true) result: format `topFrame` and
169
+ * each frame on its own. Deliberately framework-agnostic -- no dependency
170
+ * on any particular `expect` implementation.
171
+ */
172
+ export function formatFailures(
173
+ input: A11yCoreResult | ReadonlyArray<CheckResult>,
174
+ opts?: { outcomes?: Outcome[] }
175
+ ): string;
176
+
177
+ /**
178
+ * What a scan result says it left out, which its checksResults alone would
179
+ * pass over as clean: an include() scope that matched no element
180
+ * (`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
183
+ * TypeError for a frames(true) result: call it on `topFrame` and on each
184
+ * scanned frame.
210
185
  */
211
- export function formatFailures(checksResults: CheckResult[], opts?: { outcomes?: Outcome[] }): string;
186
+ export { getScanGaps, formatOccurrenceLocation } from '@surea11y/binding-base';
187
+ 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,53 @@ 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
176
 
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);
146
-
147
177
  // A Playwright Page and a Frame both expose the same .evaluate(fn, arg)
148
178
  // and .url() shape, so this works unchanged for either.
149
- const runInFrame = async (frameOrPage) => {
179
+ const runInFrame = async (frameOrPage, frameContextSelector) => {
150
180
  const frameUrl = this._url || (typeof frameOrPage.url === 'function' ? frameOrPage.url() : null);
151
- const result = await frameOrPage.evaluate(wrapperFn, {
181
+ const result = rethrowEngineError(await frameOrPage.evaluate(scanInPage, {
152
182
  url: frameUrl,
153
- contextSelector,
183
+ contextSelector: frameContextSelector,
154
184
  engineOptions,
155
185
  runOnly
156
- });
186
+ }));
187
+ this._warnScanGaps(result);
157
188
  return this._elementRef ? this._attachElementRefs(frameOrPage, result) : result;
158
189
  };
159
190
 
160
191
  if (!this._scanFrames) {
161
- return this._applyReportOnly(await runInFrame(this._page));
192
+ return this._applyReportOnly(await runInFrame(this._page, contextSelector));
162
193
  }
163
194
 
164
195
  const mainFrame = this._page.mainFrame();
165
- const topFrame = this._applyReportOnly(await runInFrame(mainFrame));
196
+ const topFrame = this._applyReportOnly(await runInFrame(mainFrame, contextSelector));
166
197
 
167
198
  // page.frames() includes the main frame itself -- exclude it here since
168
199
  // it's already covered by topFrame above, so callers don't have to
169
200
  // de-duplicate it themselves out of the frames array.
170
201
  const subFrames = this._page.frames().filter((f) => f !== mainFrame);
202
+ // include() scopes the top frame only: each sub-frame is scanned whole,
203
+ // as core's own runa11yCoreAcrossFrames does. Since @surea11y/core
204
+ // 1.10.0 a contextSelector that matches nothing scans nothing, so
205
+ // passing the top frame's selector on would leave out every frame that
206
+ // doesn't happen to contain the same element (before 1.10.0 such a frame
207
+ // was silently scanned whole). exclude() still applies in every frame.
171
208
  const frames = [];
172
209
  for (const frame of subFrames) {
173
210
  try {
174
- frames.push(this._applyReportOnly(await runInFrame(frame)));
211
+ frames.push(this._applyReportOnly(await runInFrame(frame, null)));
175
212
  } catch (e) {
176
213
  // A frame can detach/navigate away mid-scan, or be a sandboxed
177
214
  // frame the browser blocks scripting in -- don't let one bad frame
@@ -187,11 +224,11 @@ class A11yCoreBuilder extends A11yCoreBuilderBase {
187
224
  }
188
225
 
189
226
  /**
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.
227
+ * Resolves each occurrence to a live ElementHandle, scoped to
228
+ * frameOrPage's own document (a Playwright Page and Frame both expose the
229
+ * same .evaluateHandle(fn, arg) shape), through its shadow hosts when it
230
+ * has `shadowHostSelectors`. Mutates and returns the same result object
231
+ * -- it's a fresh object from this scan, not shared external state.
195
232
  */
196
233
  async _attachElementRefs(frameOrPage, result) {
197
234
  if (!Array.isArray(result.checksResults)) return result;
@@ -203,11 +240,42 @@ class A11yCoreBuilder extends A11yCoreBuilderBase {
203
240
  // rules) can carry "" -- not every occurrence resolves to one element,
204
241
  // so leave elementHandle null rather than passing "" to .$() (which
205
242
  // throws, it's not a valid CSS selector).
206
- occurrence.elementHandle = occurrence.selector ? await frameOrPage.$(occurrence.selector) : null;
243
+ occurrence.elementHandle = occurrence.selector ? await this._findElement(frameOrPage, occurrence) : null;
207
244
  }
208
245
  }
209
246
  return result;
210
247
  }
248
+
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
+ async _findElement(frameOrPage, occurrence) {
271
+ const handle = await frameOrPage.evaluateHandle(findOccurrenceElement, {
272
+ selector: occurrence.selector,
273
+ shadowHostSelectors: occurrence.shadowHostSelectors || null
274
+ });
275
+ const element = handle.asElement();
276
+ if (!element) await handle.dispose();
277
+ return element;
278
+ }
211
279
  }
212
280
 
213
281
  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 };