@surea11y/puppeteer 1.1.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -25,7 +25,7 @@ await page.goto('https://example.com/');
25
25
  const results = await new A11yCoreBuilder({ page })
26
26
  .include('#main') // optional -- call multiple times for multi-region scans
27
27
  .exclude('.cookie-banner') // optional
28
- .withTags(['wcag2a', 'wcag2aa'])
28
+ .withWcag('2.2', 'AA') // the rules for WCAG 2.2's A and AA criteria
29
29
  .disableRules(['meta-refresh-no-exceptions'])
30
30
  .options({ contrast: { mode: 'auditorAssist' } })
31
31
  .analyze();
@@ -34,15 +34,21 @@ console.log(results.checksResults.filter(r => r.outcome === 'fail'));
34
34
  await browser.close();
35
35
  ```
36
36
 
37
- `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
+ `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. `results.engine.version` names the `@surea11y/core` release that produced it (such as `"1.11.1"`); quote it in a bug report.
38
+
39
+ From 1.3.0 this package needs `@surea11y/core` 1.11.1 or later, which npm installs with it. Core's rules and messages change between its releases; see [What changes with `@surea11y/core` 1.11](#what-changes-with-surea11ycore-111) below and core's [changelog](https://github.com/SureA11y/core/blob/main/CHANGELOG.md).
38
40
 
39
41
  Also see `examples/basic-scan.js` for a runnable script (`npm run example -- <url>`).
40
42
 
41
- `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'` — see [`ENGINE_OPTIONS.md`](https://github.com/SureA11y/core/blob/main/docs/ENGINE_OPTIONS.md)), not either one.
43
+ `.withWcag(version, level)` selects by conformance target: `.withWcag('2.2', 'AA')` runs the rules for WCAG 2.2's Level A and AA criteria, by the level each criterion has in that version (4.1.1 Parsing, which 2.2 removed, is part of a `'2.1'` target and not of a `'2.2'` one). `.withBestPractices()` adds the rules that name no WCAG criterion, such as `region` and `heading-order`; on its own it runs only those. `.withRules()` and `.withTags()` add to a target's rules, and the disable methods apply after. A version other than `'2.0'`, `'2.1'` or `'2.2'`, or a level other than `'A'`, `'AA'` or `'AAA'`, throws a `TypeError` with `code: 'INVALID_RUN_ONLY'` at the call. Both need `@surea11y/core` 1.11 or later.
44
+
45
+ `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'` — see [`ENGINE_OPTIONS.md`](https://github.com/SureA11y/core/blob/main/docs/ENGINE_OPTIONS.md)), not either one.
46
+
47
+ Each of the four takes a string or an array of strings. Anything else, such as `undefined` from a missing config value or an empty string, throws a `TypeError` with `code: 'INVALID_RUN_ONLY'` at the call. A list that names nothing the engine knows (`.withRules(['img-alt-presnt'])`) makes `analyze()` reject instead; see [Errors](#errors).
42
48
 
43
49
  `.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.
44
50
 
45
- **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.
51
+ **Create one builder per scan.** `A11yCoreBuilder` is a mutable object with no reset between `.analyze()` calls — `include()`/`exclude()`/`withRules()`/`disableRules()`/`withTags()`/`disableTags()`/`options()`/`withCustomRules()`/`withPacks()` all push onto or merge into internal state that persists for the instance's lifetime. Calling one of them again before a second `.analyze()` call *accumulates* on top of the first scan's scope rather than replacing it (this is exactly what makes "call `.include()` several times for one scan," above, work — the same accumulation just also applies across separate scans if you reuse an instance). `.reportOnly()`/`.frames()`/`.elementRef()`/`.withWcag()`/`.withBestPractices()` are the exception: each call replaces the previous value instead of merging with it.
46
52
 
47
53
  This binding works against both browsers Puppeteer supports — Chrome (the default) and Firefox via `puppeteer.launch({ browser: 'firefox' })` — verified with a real Firefox run, see `tests/cross-browser.test.js`. There's no WebKit option; that's a Playwright-only engine.
48
54
 
@@ -52,7 +58,7 @@ The pattern above works unchanged inside a real test:
52
58
 
53
59
  ```js
54
60
  const puppeteer = require('puppeteer');
55
- const { A11yCoreBuilder, formatFailures } = require('@surea11y/puppeteer');
61
+ const { A11yCoreBuilder, formatFailures, getScanGaps } = require('@surea11y/puppeteer');
56
62
 
57
63
  const browser = await puppeteer.launch();
58
64
  const page = await browser.newPage();
@@ -60,25 +66,42 @@ await page.goto('https://example.com/');
60
66
 
61
67
  const results = await new A11yCoreBuilder({ page }).reportOnly(['fail']).analyze();
62
68
 
63
- assert.strictEqual(results.checksResults.length, 0, formatFailures(results.checksResults));
69
+ assert.ok(
70
+ results.checksResults.length === 0 && getScanGaps(results).length === 0,
71
+ formatFailures(results)
72
+ );
64
73
  ```
65
74
 
66
- See `examples/e2e-test-example.test.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. It uses `node:test` directly rather than a dedicated test-runner package: Puppeteer has no first-party test runner the way `@playwright/test` is the default for Playwright, and `node:test` is a zero-new-dependency choice that already matches this project's own test suite.
75
+ `getScanGaps(results)` lists what the scan left out, which `checksResults` alone would pass over as clean: an `.include()` scope that matched nothing (`kind: 'context-not-found'`; nothing was scanned, so every rule reports `notApplicable`), some of several `.include()` selectors that matched nothing (`'context-partly-not-found'`), each custom rule the engine did not run (`'custom-rule-skipped'`, with the engine's reason), and each pack the page did not run (`'pack-skipped'`, from `results.skippedPacks`; see [Scanning with packs](#scanning-with-packs-standards-checklists-and-your-own-rules)). Each gap has a `message`. Checking it is what keeps a mistyped scope from passing the gate. `analyze()` also prints each gap's message with `console.warn` (as `@surea11y/puppeteer (<frame url>): <message>`, once per scanned frame under `.frames(true)`), so a scan that left something out shows in the log even where nothing asserts on it.
76
+
77
+ See `examples/e2e-test-example.test.js` for a fuller, runnable version (`npm run example:e2e`) — one test proving real violations get caught (unlabeled button, missing `alt`), one proving a mistyped `.include()` scope is caught rather than passed, one proving a well-formed page passes cleanly, and one gating a page on a pack's checklist. It uses `node:test` directly rather than a dedicated test-runner package: Puppeteer has no first-party test runner the way `@playwright/test` is the default for Playwright, and `node:test` is a zero-new-dependency choice that already matches this project's own test suite.
67
78
 
68
79
  ### Readable console/CI output on failure
69
80
 
70
- A bare length/equality assertion 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:
81
+ A bare length/equality assertion 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/location/hint), followed by the result's scan gaps and the `@surea11y/core` release that produced it, that you hand to your assertion library's own failure-message parameter, as above. A real failure then prints:
71
82
 
72
83
  ```
73
- Error: 1) button-name-present (serious): This button has no accessible name.
84
+ AssertionError [ERR_ASSERTION]: 1) button-name-present (serious): This button has no accessible name.
74
85
  at html > body > button
75
- Provide visible button text or a programmatic accessible-name mechanism (for example aria-label) so assistive technologies can identify the button.
76
- 2) img-alt-present (serious): Missing alt attribute on <img>.
86
+ Give the button visible text, or name it with aria-label, so screen reader users know what it does.
87
+ 2) img-alt-present (serious): This <img> has no alt attribute.
77
88
  at html > body > img
78
- Add an alt attribute (use alt="" only for decorative images).
89
+ Add an alt attribute that says what the image shows, or alt="" if the image is purely decorative.
90
+
91
+ Scanned with @surea11y/core 1.11.1.
92
+ ```
93
+
94
+ and a scope that matched nothing prints:
95
+
96
+ ```
97
+ AssertionError [ERR_ASSERTION]: Nothing was scanned: the scan scope matched no element ("#main").
98
+
99
+ Scanned with @surea11y/core 1.11.1.
79
100
  ```
80
101
 
81
- Deliberately a plain function, not a custom `expect` matcher — no dependency on any particular assertion library, so it works the same with `node:assert`, 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 — see [`OUTPUT_SCHEMA.md`](https://github.com/SureA11y/core/blob/main/docs/OUTPUT_SCHEMA.md)) is still surfaced using its `error` message rather than silently dropped.
102
+ An element inside a shadow tree is located through its shadow hosts, as `my-app >>> my-card >>> img`; `formatOccurrenceLocation(occurrence)` gives that line on its own. Passing `results.checksResults` instead of `results` still works and lists the findings alone.
103
+
104
+ Deliberately a plain function, not a custom `expect` matcher — no dependency on any particular assertion library, so it works the same with `node:assert`, Jest, Vitest, or a hand-rolled `if`/`throw`. Defaults to `fail`/`cantTell` outcomes (the ones that report something found); pass `{ outcomes: [...] }` to narrow further. It throws a `TypeError` for the `{ topFrame, frames }` result of a `.frames(true)` scan: format `topFrame` and each frame on its own (below). A thrown rule (`occurrences: []`, `error` set — see [`OUTPUT_SCHEMA.md`](https://github.com/SureA11y/core/blob/main/docs/OUTPUT_SCHEMA.md)) is still surfaced using its `error` message rather than silently dropped.
82
105
 
83
106
  ### Scanning every frame, including cross-origin iframes
84
107
 
@@ -91,8 +114,28 @@ for (const frame of results.frames) {
91
114
  }
92
115
  ```
93
116
 
117
+ Format a `.frames(true)` result one frame at a time:
118
+
119
+ ```js
120
+ const messages = [results.topFrame, ...results.frames].map((frame) =>
121
+ 'error' in frame ? `${frame.url}: not scanned (${frame.error})` : formatFailures(frame)
122
+ );
123
+ ```
124
+
125
+ `.include()` scopes the top frame only: each sub-frame is scanned whole, as `@surea11y/core`'s own `runa11yCoreAcrossFrames` does. The selectors are written against the top document, and since core 1.10.0 a selector that matches nothing scans nothing, so passing them on would leave most frames unscanned. `.exclude()` and every other option apply in every frame. A sub-frame that can't be scanned (detached, navigated away, sandboxed) becomes a `{ url, error }` entry; an [engine error](#errors) rejects the whole `analyze()` from the top frame instead, since it would fail in every frame.
126
+
94
127
  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 `@surea11y/core` engine support at all — Puppeteer drives every frame via CDP at the automation-process level, so cross-origin `frame.evaluate()` already just works. Verified against a real cross-origin page (`example.org` embedded in an unrelated origin) — see `tests/builder.test.js`. Default off, so plain `.analyze()` is unaffected unless you opt in.
95
128
 
129
+ `@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.
130
+
131
+ ```js
132
+ const fs = require('node:fs');
133
+ const { renderSarifReport } = require('@surea11y/core/sarif');
134
+
135
+ const results = await new A11yCoreBuilder({ page }).frames(true).analyze();
136
+ fs.writeFileSync('a11y.sarif', renderSarifReport(results));
137
+ ```
138
+
96
139
  ### Trimming the result to just violations
97
140
 
98
141
  By default `analyze()` returns every rule's outcome, including `pass`/`notApplicable` — `@surea11y/core`'s own deliberate "not a violations-only list" design (see [`OUTPUT_SCHEMA.md`](https://github.com/SureA11y/core/blob/main/docs/OUTPUT_SCHEMA.md)). Use `.reportOnly()` to post-filter down to only the outcomes you care about:
@@ -107,6 +150,8 @@ console.log(results.checksResults); // only fail/cantTell entries, pass/notAppli
107
150
 
108
151
  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.
109
152
 
153
+ 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 238 KB to 82 KB.
154
+
110
155
  ### Getting a live element handle, not just a selector string
111
156
 
112
157
  By default each occurrence carries a CSS selector + HTML snippet, not a live reference to the element. Opt in to a real Puppeteer `ElementHandle` with `.elementRef(true)`:
@@ -119,7 +164,7 @@ await failing.occurrences[0].elementHandle.screenshot({ path: 'flagged.png' });
119
164
  await failing.occurrences[0].elementHandle.click();
120
165
  ```
121
166
 
122
- 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.
167
+ This resolves the occurrence to an `ElementHandle` instead of leaving you to re-resolve a possibly-stale selector string yourself. An occurrence inside a shadow tree carries `shadowHostSelectors` (the shadow hosts leading to it, outermost first), and its `selector` holds only inside the last host's shadow root, so `page.$(occurrence.selector)` would find another element or none; `.elementRef(true)` goes through the hosts and finds the right one. `elementHandle` is `null` when the element is no longer in 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.
123
168
 
124
169
  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 [Puppeteer's own `ElementHandle` guidance](https://pptr.dev/api/puppeteer.elementhandle).
125
170
 
@@ -155,15 +200,76 @@ const results = await new A11yCoreBuilder({ page })
155
200
 
156
201
  **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 Puppeteer `page.evaluate()` argument crosses a serialization 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.
157
202
 
158
- 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.)
203
+ 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 skipped rule deep inside the page — easier to catch during development. A *raw* `.options({ customRules })` call bypasses this check and defers to `@surea11y/core`, which skips a descriptor it can't use without throwing. The result lists each one in `skippedCustomRules` as `{ id, reason }`, and `getScanGaps()`/`formatFailures(results)` report it, so a rule that did not run doesn't look like one that passed.
204
+
205
+ ### Scanning with packs: standards, checklists and your own rules
206
+
207
+ 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.
208
+
209
+ `.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 })`:
210
+
211
+ ```js
212
+ const acmePolicy = require('@acme/a11y-policy'); // a pack
213
+
214
+ const results = await new A11yCoreBuilder({ page })
215
+ .withPacks(acmePolicy)
216
+ .options({ profile: 'acme-web-2026' })
217
+ .analyze();
218
+
219
+ results.engine.packs; // ['@acme/a11y-policy@1.0.0']
220
+ results.engine.profile; // 'acme-web-2026'
221
+
222
+ // A checklist's items, each one result, beside core's WCAG rollups:
223
+ results.rulesResults.filter((r) => r.meta && r.meta.standard === 'Acme web policy');
224
+ ```
225
+
226
+ 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.
227
+
228
+ **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/e2e-test-example.test.js`](./examples/e2e-test-example.test.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.
229
+
230
+ **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.
159
231
 
160
232
  ### Element addressing beyond a CSS selector
161
233
 
162
234
  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.
163
235
 
236
+ ## Errors
237
+
238
+ `analyze()` rejects with an `EngineError` (exported from this package) when `@surea11y/core` can't use what it was given. Its `code` says why:
239
+
240
+ - `'INVALID_RUN_ONLY'`: a `.withRules()`/`.withTags()` list in which no value names a rule or a tag the engine knows, such as a misspelled rule ID. A value that names nothing beside ones that do is ignored, with a `console.warn` in the page.
241
+ - `'INVALID_CONTEXT_SELECTOR'`: an `.include()` selector the browser can't parse. `error.selector` is that selector.
242
+ - `'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.
243
+ - `'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.
244
+
245
+ ```js
246
+ const { A11yCoreBuilder, EngineError } = require('@surea11y/puppeteer');
247
+
248
+ try {
249
+ await new A11yCoreBuilder({ page }).withRules(['img-alt-presnt']).analyze();
250
+ } catch (e) {
251
+ if (e instanceof EngineError && e.code === 'INVALID_RUN_ONLY') {
252
+ // e.message: 'runOnly.includeRuleIds: no rule named "img-alt-presnt".'
253
+ }
254
+ throw e;
255
+ }
256
+ ```
257
+
258
+ `page.evaluate()` keeps only an error's message; the binding brings the `code` back. Any other error in the page rejects `analyze()` as Puppeteer reports it. An `.include()` that parses but matches nothing is not an error: see `getScanGaps()` [above](#using-it-as-an-e2e-accessibility-gate).
259
+
164
260
  ## TypeScript
165
261
 
166
- `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.), mirrored from [`OUTPUT_SCHEMA.md`](https://github.com/SureA11y/core/blob/main/docs/OUTPUT_SCHEMA.md). `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. `puppeteer` is a `peerDependencies` entry (not just `devDependencies`) since the class's `page` argument and `Occurrence#elementHandle` both come from it — consumers need their own `puppeteer` install for the types to resolve, same as they already do to construct a `Page` in the first place.
262
+ `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 plus `@surea11y/core`'s native result shapes (`A11yCoreResult`, `CheckResult`, `Occurrence`, `CompositeResult`, etc.). The result shapes are `@surea11y/core`'s own types (its `ScanResult` and the rest), with `elementHandle` added to an occurrence, so they follow the engine: `engine.version`, `contextMatch`, `skippedCustomRules`, `shadowHostSelectors` and `margin` are all declared. `EngineError`, `ScanGap` and `EngineErrorCode` come from `@surea11y/binding-base`, and so do the types of `withWcag()` (`WcagVersion`, `WcagLevel`) and `withPacks()`, which takes a pack made with `definePack` (`PackLike`). Code that handles every `ScanGap` kind it knows and treats the rest in an `else` branch needs a branch for `'pack-skipped'`, which carries `pack` rather than `selectors`. `analyze()` is typed `Promise<A11yCoreResult | A11yCoreMultiFrameResult>` — narrow on `'topFrame' in results` (or cast, if you already know which mode you called) to get the specific shape back, since a fluent builder can't statically track that `.frames(true)` was called earlier in the chain. `puppeteer` is a `peerDependencies` entry (not just `devDependencies`) since the class's `page` argument and `Occurrence#elementHandle` both come from it — consumers need their own `puppeteer` install for the types to resolve, same as they already do to construct a `Page` in the first place.
263
+
264
+ ## What changes with `@surea11y/core` 1.11
265
+
266
+ 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):
267
+
268
+ - **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.
269
+ - **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.
270
+ - **`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.
271
+ - **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.
272
+ - **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](#errors)).
167
273
 
168
274
  ## Relationship to `@surea11y/playwright`
169
275
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@surea11y/puppeteer",
3
- "version": "1.1.0",
3
+ "version": "1.3.0",
4
4
  "description": "Puppeteer binding for surea11y -- scan real, live-rendered pages for accessibility issues.",
5
5
  "keywords": [
6
6
  "accessibility",
@@ -39,18 +39,21 @@
39
39
  "LICENSE"
40
40
  ],
41
41
  "dependencies": {
42
- "@surea11y/binding-base": "^1.1.0",
43
- "@surea11y/core": "^1.5.0"
42
+ "@surea11y/binding-base": "^1.3.1",
43
+ "@surea11y/core": "^1.11.1"
44
44
  },
45
45
  "peerDependencies": {
46
46
  "puppeteer": ">=22.0.0"
47
47
  },
48
48
  "devDependencies": {
49
- "puppeteer": "^25.3.0"
49
+ "@types/node": "^20.19.43",
50
+ "puppeteer": "^25.13.0",
51
+ "typescript": "^7.0.2"
50
52
  },
51
53
  "scripts": {
52
54
  "test": "node --test tests/*.test.js",
53
55
  "example": "node examples/basic-scan.js",
54
- "example:e2e": "node --test examples/e2e-test-example.test.js"
56
+ "example:e2e": "node --test examples/e2e-test-example.test.js",
57
+ "example:pack": "node examples/scan-with-pack.js"
55
58
  }
56
59
  }
@@ -1,145 +1,70 @@
1
1
  import type { Page, ElementHandle } from 'puppeteer';
2
-
3
- // See surea11y's docs/OUTPUT_SCHEMA.md -- this file mirrors that document's
4
- // shapes exactly (plus the elementHandle field this binding adds on top when
5
- // .elementRef(true) is used). Keep in sync with that doc, not the other way
6
- // around -- it's the source of truth for what the engine actually returns.
7
-
8
- export type Outcome = 'pass' | 'fail' | 'cantTell' | 'notApplicable';
9
- export type OutcomeNormalized = 'pass' | 'fail' | 'cantTell' | 'inapplicable';
10
- export type Severity = 'minor' | 'moderate' | 'serious' | 'critical';
11
- export type Confidence = 'high' | 'medium' | 'low';
12
- export type RuleType = 'automatic' | 'manual';
13
- export type Category = 'perceivable' | 'operable' | 'understandable' | 'robust' | null;
14
-
15
- // The reason set is open: core can add a value in a minor release, so the
16
- // union stays assignable from any string rather than going stale.
17
- export type LocaleResolutionReason =
18
- | 'ok'
19
- | 'primary-subtag'
20
- | 'dictionary-not-loaded'
21
- | 'unknown-locale'
22
- | 'partial-dictionary'
23
- | (string & {});
24
-
25
- export interface LocaleResolution {
26
- requested: string;
27
- resolved: string;
28
- reason: LocaleResolutionReason;
29
- }
30
-
31
- export interface EngineInfo {
32
- tag: string;
33
- schemaVersion: string;
34
- locale: LocaleResolution;
35
- }
36
-
37
- export interface NormativeMapping {
38
- standard: string;
39
- version: string;
40
- requirement: string;
41
- title: string;
42
- conformanceLevel: string;
43
- }
44
-
45
- export interface CheckResultMeta {
46
- ruleId: string;
47
- ruleInterfaceVersion: string;
48
- ruleVersion: string;
49
- normative: boolean;
50
- atomic: boolean;
51
- category: Category;
52
- normativeMappings: NormativeMapping[];
53
- standard: string | null;
54
- applicability: string;
55
- expectation: string;
56
- references: string[];
57
- requirements: Record<string, unknown> | null;
58
- mappings: Record<string, unknown> | null;
59
- }
60
-
61
- export interface VisibilityFilter {
62
- targetSet: string;
63
- accEligible: boolean | null;
64
- reasons: string[];
65
- }
66
-
67
- export interface Occurrence {
68
- selector: string;
69
- html: string;
70
- structuralPath: number[] | null;
71
- summary: string;
72
- hint: string;
73
- i18n: { summaryKey: string; hintKey: string; params: Record<string, unknown> } | null;
74
- data: {
75
- visibilityFilter?: VisibilityFilter;
76
- details?: Record<string, unknown>;
77
- };
2
+ import type * as Core from '@surea11y/core';
3
+
4
+ // The result shapes are @surea11y/core's own types (shipped since core
5
+ // 1.9.0, checked there against real scan results), re-exported under the
6
+ // names this file has always used. The binding adds `elementHandle` to an
7
+ // occurrence when .elementRef(true) is used, and the { topFrame, frames }
8
+ // shape of a .frames(true) scan. See core's docs/OUTPUT_SCHEMA.md for what
9
+ // each field means.
10
+
11
+ export type {
12
+ Outcome,
13
+ OutcomeNormalized,
14
+ Severity,
15
+ Confidence,
16
+ RuleType,
17
+ LocaleResolution,
18
+ EngineInfo,
19
+ RenderingEnvironment,
20
+ NormativeMapping,
21
+ VisibilityFilter,
22
+ Uncertainty,
23
+ Margin,
24
+ ContextMatch,
25
+ CompositeResult
26
+ } from '@surea11y/core';
27
+
28
+ // Re-exported from @surea11y/binding-base with the functions src/index.js
29
+ // re-exports from it.
30
+ export {
31
+ formatFailures,
32
+ getScanGaps,
33
+ formatOccurrenceLocation,
34
+ EngineError
35
+ } from '@surea11y/binding-base';
36
+ export type {
37
+ ScanGap,
38
+ EngineErrorCode,
39
+ OccurrenceLocation,
40
+ PackLike,
41
+ WcagVersion,
42
+ WcagLevel
43
+ } from '@surea11y/binding-base';
44
+ import type { PackLike, WcagVersion, WcagLevel } from '@surea11y/binding-base';
45
+
46
+ export type Category = Core.RuleMeta['category'];
47
+ export type LocaleResolutionReason = Core.LocaleResolution['reason'];
48
+ export type CheckResultMeta = Core.RuleMeta;
49
+ export type CompositeResultDetails = Core.CompositeResult['data']['details'];
50
+
51
+ export interface Occurrence extends Core.Occurrence {
78
52
  /**
79
53
  * Only present when `.elementRef(true)` was used. `null` when this
80
54
  * occurrence has no single resolvable target element (e.g. `selector` was
81
- * `""`) -- see A11yCoreBuilder#elementRef.
55
+ * `""`), or the element is no longer in the page -- see
56
+ * A11yCoreBuilder#elementRef.
82
57
  */
83
58
  elementHandle?: ElementHandle | null;
84
59
  }
85
60
 
86
- export interface CheckResult {
87
- ruleId: string;
88
- outcome: Outcome;
89
- outcomeNormalized: OutcomeNormalized;
90
- severity: Severity;
91
- confidence: Confidence;
92
- type: RuleType;
61
+ export interface CheckResult extends Omit<Core.CheckResult, 'occurrences'> {
93
62
  occurrences: Occurrence[];
94
- title: string;
95
- description: string;
96
- i18n: { titleKey: string; descriptionKey: string } | null;
97
- meta: CheckResultMeta;
98
- engineOptions: Record<string, unknown>;
99
- schemaVersion: string;
100
- /** Present only if the rule threw, or the manual-fail-to-cantTell coercion fired. */
101
- error?: string;
102
- }
103
-
104
- export interface CompositeResultDetails {
105
- reasonCode: string;
106
- checksIds: string[];
107
- contributors: Array<{ testId: string; outcome: string; severity: string | null }>;
108
- metrics: {
109
- failCount: number;
110
- cantTellCount: number;
111
- notApplicableCount: number;
112
- passCount: number;
113
- missingCount: number;
114
- };
115
- }
116
-
117
- export interface CompositeResult {
118
- ruleId: string;
119
- outcome: Outcome;
120
- severity: Severity;
121
- confidence: Confidence;
122
- type: RuleType;
123
- title: string;
124
- description: string;
125
- meta: CheckResultMeta;
126
- engineOptions: Record<string, unknown>;
127
- schemaVersion: string;
128
- /** Always empty -- composites are rollups, not element-level findings. */
129
- occurrences: [];
130
- data: { details: CompositeResultDetails };
131
63
  }
132
64
 
133
65
  /** surea11y's native top-level result shape -- see docs/OUTPUT_SCHEMA.md. */
134
- export interface A11yCoreResult {
135
- engine: EngineInfo;
136
- url: string | null;
137
- title: string | null;
138
- timestamp: string | null;
139
- perfStats: Record<string, unknown> | null;
140
- contextSelector: string | string[] | null;
66
+ export interface A11yCoreResult extends Omit<Core.ScanResult, 'checksResults'> {
141
67
  checksResults: CheckResult[];
142
- rulesResults: CompositeResult[];
143
68
  }
144
69
 
145
70
  /** A sub-frame that couldn't be scanned (detached, navigated away, or sandboxed). */
@@ -169,8 +94,8 @@ export interface CustomRuleDescriptor {
169
94
  title?: string;
170
95
  description?: string;
171
96
  tags?: string[];
172
- defaultSeverity?: Severity;
173
- defaultConfidence?: Confidence;
97
+ defaultSeverity?: Core.Severity;
98
+ defaultConfidence?: Core.Confidence;
174
99
  [key: string]: unknown;
175
100
  };
176
101
  runInPage: ((ctx: unknown) => unknown) | string;
@@ -198,31 +123,44 @@ export class A11yCoreBuilder {
198
123
  withTags(tags: string | string[]): this;
199
124
  /** Never run rules carrying any of these tags (applied after withTags). */
200
125
  disableTags(tags: string | string[]): this;
201
- /** Only run these specific rule IDs (accepts with or without the prefix). */
126
+ /** Only run these specific rule IDs (accepts with or without the `a11ycore-` prefix). */
202
127
  withRules(ruleIds: string | string[]): this;
203
128
  /** Never run these specific rule IDs (applied after withRules). */
204
129
  disableRules(ruleIds: string | string[]): this;
130
+ /**
131
+ * Run the rules for a WCAG conformance target: `withWcag('2.2', 'AA')`
132
+ * runs those of WCAG 2.2's A and AA criteria. withTags()/withRules() add
133
+ * to them. A later call replaces the target.
134
+ */
135
+ withWcag(version: WcagVersion | 2.0 | 2.1 | 2.2, level?: WcagLevel): this;
136
+ /** Also run the best-practice rules, those that name no WCAG criterion. */
137
+ withBestPractices(enabled?: boolean): this;
205
138
  /** Merge arbitrary engineOptions (locale, contrast.mode, policyContract, ...). */
206
139
  options(partialEngineOptions: Record<string, unknown>): this;
207
140
  /** Register one or more custom rules for just this scan. Call multiple times to accumulate. */
208
141
  withCustomRules(rules: CustomRuleDescriptor | CustomRuleDescriptor[]): this;
142
+ /**
143
+ * Packs from `@surea11y/core/pack` (core 1.11 or later): registered in each
144
+ * frame before the scan, and named in `engineOptions.packs`.
145
+ */
146
+ withPacks(packs: PackLike | PackLike[]): this;
209
147
  /** Post-filter checksResults down to only the given outcomes. */
210
- reportOnly(outcomes: Outcome | Outcome[]): this;
148
+ reportOnly(outcomes: Core.Outcome | Core.Outcome[]): this;
211
149
  /** Opt in to also scanning every sub-frame on the page (including cross-origin iframes). */
212
150
  frames(enabled?: boolean): this;
213
151
  /** Opt in to resolving each fail/cantTell occurrence's selector to a live ElementHandle. */
214
152
  elementRef(enabled?: boolean): this;
215
153
 
216
- /** Runs the scan. Returns { topFrame, frames } instead of a single result when .frames(true) was used. */
154
+ /**
155
+ * Runs the scan. Returns { topFrame, frames } instead of a single result
156
+ * when .frames(true) was used; include() then scopes the top frame only,
157
+ * and each sub-frame is scanned whole. Rejects with an EngineError for
158
+ * input the engine cannot use, with its `code`: 'INVALID_RUN_ONLY'
159
+ * (withRules()/withTags() named no rule or tag it knows),
160
+ * 'INVALID_CONTEXT_SELECTOR' (an include() selector the browser can't
161
+ * parse), 'INVALID_ENGINE_OPTIONS' (an option `strictOptions: true`
162
+ * rejects) or 'PAGE_BUILTINS_BROKEN' (the page's scripts broke a
163
+ * JavaScript built-in the engine relies on).
164
+ */
217
165
  analyze(): Promise<A11yCoreResult | A11yCoreMultiFrameResult>;
218
166
  }
219
-
220
- /**
221
- * Formats a checksResults array into a short, human-readable block -- one
222
- * entry per occurrence, not per rule. Meant for an assertion library's
223
- * failure-message parameter, e.g.
224
- * `assert.strictEqual(results.checksResults.length, 0, formatFailures(results.checksResults))`.
225
- * Deliberately framework-agnostic -- no dependency on any particular
226
- * `expect` implementation.
227
- */
228
- export function formatFailures(checksResults: CheckResult[], opts?: { outcomes?: Outcome[] }): string;
@@ -1,7 +1,18 @@
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
+ // core's scan, wrapped so an engine error keeps its `code` across
13
+ // page.evaluate(), which keeps only an error's message. Built once; it is
14
+ // self-contained, so Puppeteer serializes it as it did runa11yCoreInPage.
15
+ const inPageScan = createInPageScan(runa11yCoreInPage);
5
16
 
6
17
  /**
7
18
  * Puppeteer binding for surea11y -- scans a real, already-rendered page.
@@ -123,6 +134,9 @@ class A11yCoreBuilder extends A11yCoreBuilderBase {
123
134
  */
124
135
  async analyze() {
125
136
  const { contextSelector, engineOptions, runOnly } = this._buildEngineArgs();
137
+ // The script that registers withPacks()'s packs in a frame, which the
138
+ // scan names in engineOptions.packs; null without packs.
139
+ const packScript = this._packScript();
126
140
 
127
141
  // Unlike Playwright's page.evaluate(fn, arg), which only accepts a
128
142
  // SINGLE argument (forcing a hand-built single-arg wrapper there --
@@ -131,22 +145,30 @@ class A11yCoreBuilder extends A11yCoreBuilderBase {
131
145
  // variadic: evaluate<Params extends unknown[], Func>(pageFunction: Func
132
146
  // | string, ...args: Params) (confirmed against a real Puppeteer 25.x
133
147
  // install's own puppeteer-core/lib/types.d.ts, on the shared abstract
134
- // Realm class both Page and Frame implement). That means
135
- // runa11yCoreInPage's own 4 positional args can be passed straight
136
- // through with no wrapper/eval() trick needed -- see
137
- // ../core/docs/INTEGRATION.md for the documented example this mirrors.
138
- const runInFrame = async (frameOrPage) => {
148
+ // Realm class both Page and Frame implement). That means the scan's
149
+ // own 4 positional args can be passed straight through with no
150
+ // wrapper/eval() trick needed -- see ../core/docs/INTEGRATION.md for
151
+ // the documented example this mirrors.
152
+ //
153
+ // An engine error (INVALID_RUN_ONLY, INVALID_CONTEXT_SELECTOR) comes
154
+ // back as a plain object and is thrown here as an EngineError with its
155
+ // `code`; any other error in the page rejects evaluate() as before.
156
+ const runInFrame = async (frameOrPage, frameContextSelector) => {
139
157
  const frameUrl = this._url || (typeof frameOrPage.url === 'function' ? frameOrPage.url() : null);
140
- const result = await frameOrPage.evaluate(runa11yCoreInPage, frameUrl, contextSelector, engineOptions, runOnly);
158
+ if (packScript) await frameOrPage.evaluate(packScript);
159
+ const result = rethrowEngineError(
160
+ await frameOrPage.evaluate(inPageScan, frameUrl, frameContextSelector, engineOptions, runOnly)
161
+ );
162
+ warnScanGaps(result);
141
163
  return this._elementRef ? this._attachElementRefs(frameOrPage, result) : result;
142
164
  };
143
165
 
144
166
  if (!this._scanFrames) {
145
- return this._applyReportOnly(await runInFrame(this._page));
167
+ return this._applyReportOnly(await runInFrame(this._page, contextSelector));
146
168
  }
147
169
 
148
170
  const mainFrame = this._page.mainFrame();
149
- const topFrame = this._applyReportOnly(await runInFrame(mainFrame));
171
+ const topFrame = this._applyReportOnly(await runInFrame(mainFrame, contextSelector));
150
172
 
151
173
  // page.frames() includes the main frame itself -- exclude it here since
152
174
  // it's already covered by topFrame above, so callers don't have to
@@ -155,7 +177,12 @@ class A11yCoreBuilder extends A11yCoreBuilderBase {
155
177
  const frames = [];
156
178
  for (const frame of subFrames) {
157
179
  try {
158
- frames.push(this._applyReportOnly(await runInFrame(frame)));
180
+ // include() scopes the top frame only: each sub-frame is scanned
181
+ // whole, as core's own runa11yCoreAcrossFrames does. The selectors
182
+ // were written against the top document, and since core 1.10.0 a
183
+ // selector that matches nothing scans nothing, so passing them on
184
+ // would leave most frames unscanned.
185
+ frames.push(this._applyReportOnly(await runInFrame(frame, null)));
159
186
  } catch (e) {
160
187
  // A frame can detach/navigate away mid-scan, or be a sandboxed
161
188
  // frame the browser blocks scripting in -- don't let one bad frame
@@ -171,9 +198,12 @@ class A11yCoreBuilder extends A11yCoreBuilderBase {
171
198
  }
172
199
 
173
200
  /**
174
- * Resolves occurrence.selector to a live ElementHandle for every
175
- * fail/cantTell occurrence, scoped to frameOrPage's own document (a
176
- * Puppeteer Page and Frame both expose the same .$(selector) shape).
201
+ * Resolves each fail/cantTell occurrence to a live ElementHandle, scoped
202
+ * to frameOrPage's own document (a Puppeteer Page and Frame both expose
203
+ * evaluateHandle()). An occurrence inside a shadow tree is found through
204
+ * its `shadowHostSelectors` (core 1.10.0 and later): its `selector` holds
205
+ * only inside the last host's shadow root, so `frameOrPage.$(selector)`
206
+ * would find another element, or none.
177
207
  * Mutates and returns the same result object -- it's a fresh object from
178
208
  * this scan, not shared external state.
179
209
  */
@@ -185,13 +215,38 @@ class A11yCoreBuilder extends A11yCoreBuilderBase {
185
215
  // Most occurrences carry a concrete element selector, but a page-wide
186
216
  // finding with no single target element (e.g. some `manual`/cantTell
187
217
  // rules) can carry "" -- not every occurrence resolves to one element,
188
- // so leave elementHandle null rather than passing "" to .$() (which
189
- // throws, it's not a valid CSS selector).
190
- occurrence.elementHandle = occurrence.selector ? await frameOrPage.$(occurrence.selector) : null;
218
+ // so leave elementHandle null without a round trip to the page.
219
+ occurrence.elementHandle = occurrence.selector
220
+ ? await resolveElementHandle(frameOrPage, occurrence)
221
+ : null;
191
222
  }
192
223
  }
193
224
  return result;
194
225
  }
195
226
  }
196
227
 
228
+ // Says on the console what the scan left out (an include() scope that
229
+ // matched nothing, a custom rule the engine did not run), one line per gap,
230
+ // so a scan that skipped something does not pass unnoticed as clean. Once
231
+ // per scanned frame; the gaps also stay readable through getScanGaps().
232
+ function warnScanGaps(result) {
233
+ for (const gap of getScanGaps(result)) {
234
+ const where = result.url ? ` (${result.url})` : '';
235
+ console.warn(`@surea11y/puppeteer${where}: ${gap.message}`);
236
+ }
237
+ }
238
+
239
+ // The occurrence's element as an ElementHandle, or null when it is gone (or
240
+ // a shadow host on the way is). A handle to null is disposed, not leaked.
241
+ async function resolveElementHandle(frameOrPage, occurrence) {
242
+ const handle = await frameOrPage.evaluateHandle(
243
+ queryOccurrenceElement,
244
+ occurrence.selector,
245
+ occurrence.shadowHostSelectors || null
246
+ );
247
+ const element = handle.asElement();
248
+ if (!element) await handle.dispose();
249
+ return element;
250
+ }
251
+
197
252
  module.exports = { A11yCoreBuilder };
package/src/index.js CHANGED
@@ -3,4 +3,10 @@
3
3
  const { A11yCoreBuilder } = require('./A11yCoreBuilder');
4
4
  const { formatFailures } = require('./formatFailures');
5
5
 
6
- module.exports = { A11yCoreBuilder, formatFailures };
6
+ // Re-exported from @surea11y/binding-base, as formatFailures is, so a test
7
+ // needs only this package: what a result says it left out, an occurrence's
8
+ // location as text, and the error analyze() throws for input the engine
9
+ // cannot use.
10
+ const { getScanGaps, formatOccurrenceLocation, EngineError } = require('@surea11y/binding-base');
11
+
12
+ module.exports = { A11yCoreBuilder, formatFailures, getScanGaps, formatOccurrenceLocation, EngineError };