@ngbracket/a11y-devtools 0.3.0 → 0.5.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/CHANGELOG.md ADDED
@@ -0,0 +1,59 @@
1
+ # Changelog
2
+
3
+ All notable changes to `@ngbracket/a11y-devtools` are documented here.
4
+ This project adheres to [Semantic Versioning](https://semver.org/).
5
+
6
+ ## 0.5.0
7
+
8
+ ### Added
9
+
10
+ - **Configurable framework prefixes.** The component-name prefixes attribution
11
+ walks past (third-party UI primitives) are now configurable instead of a
12
+ hardcoded `Nb`/`Mat`/`Cdk`/`Mdc` list:
13
+ - `provideA11yDevtools({ frameworkPrefixes })`, `runA11yScan(root, { frameworkPrefixes })`,
14
+ `scan(root, axe, { frameworkPrefixes })`, and `scanPages({ frameworkPrefixes })`.
15
+ - CLI: `--framework-prefixes Nb,Mat,Nz,Clr,Ion` and `--no-skip-primitives`.
16
+ - Pass `[]` (or `--no-skip-primitives`) to attribute to the **immediate** owner —
17
+ e.g. when scanning a component library's *own* code, so it blames the library
18
+ component rather than a demo wrapper.
19
+ - Exported `DEFAULT_FRAMEWORK_PREFIXES` (spread it to extend: `[...DEFAULT_FRAMEWORK_PREFIXES, 'Nz']`)
20
+ and the `ScanOptions` type.
21
+
22
+ ## 0.4.0
23
+
24
+ ### Added
25
+
26
+ - **Report mode** — a headless, CI-friendly way to scan a whole running app. A new
27
+ `./report` export (`scanPages`, `toMarkdown`, `toJson`) and a `ngbr-a11y-report`
28
+ CLI drive a headless browser over your dev server, inject the same
29
+ component-attributed scan, and write a Markdown + JSON report grouped by owning
30
+ component. No change to the app under test.
31
+ - `--fail-on <impact>` exits non-zero on findings at/above a severity, for CI gates.
32
+ - A `setup` hook (programmatic API) handles apps gated behind a login or theme picker.
33
+ - Reports surface **distinct rules vs. raw node-instances**.
34
+ - `A11yFinding.componentPath` — the full ownership chain from the flagged node to
35
+ the root, nearest first.
36
+ - Exported `resolveComponentPath` and `appComponentFromPath`.
37
+
38
+ ### Changed
39
+
40
+ - **Attribution now reports the nearest _app-owned_ component.** Violations on a
41
+ third-party UI primitive (Nebular `Nb*`, Angular Material `Mat*`, CDK
42
+ `Cdk*`/`Mdc*`) are attributed to the app component that placed them — where the
43
+ fix lives — instead of the library component. A component library you author
44
+ (`Ngbr*`) is intentionally not skipped. This changes `finding.component` (and the
45
+ console/overlay grouping) for such cases; the primitive is preserved in
46
+ `componentPath` and shown as `(via …)` in the report.
47
+
48
+ ### Packaging
49
+
50
+ - Playwright is an **optional peer dependency** (not auto-installed) — install it
51
+ only if you use report mode. The base package stays weightless; axe-core still
52
+ never reaches your app bundle (enforced by the prod-weight guard, now extended to
53
+ keep report-mode code out of the browser entry).
54
+
55
+ ## 0.3.0
56
+
57
+ - Scoped ruleset via `tags`; documented WCAG coverage.
58
+ - Component + directive/`hostDirectives` attribution, axe scan, grouped console
59
+ reporter, dev-only provider, in-app overlay, CI prod-weight guard.
package/README.md CHANGED
@@ -62,9 +62,18 @@ provideA11yDevtools({
62
62
  overlay: true, // in-app visual highlights over flagged nodes; default false
63
63
  debounceMs: 500, // quiet window after stabilization before scanning
64
64
  tags: ['wcag22aa'], // scope the ruleset; default = axe-core's full ruleset
65
+ frameworkPrefixes: ['Nb', 'Mat', 'Cdk', 'Mdc'], // UI primitives to attribute past (default)
65
66
  });
66
67
  ```
67
68
 
69
+ **Framework prefixes.** Attribution walks *past* third-party UI primitives to the app
70
+ component that placed them — a `<button nbButton>` with no name is blamed on your
71
+ `HeaderComponent`, not `NbButtonComponent`. The default list is `Nb`/`Mat`/`Cdk`/`Mdc`;
72
+ override `frameworkPrefixes` to add others (e.g. `['Nb','Mat','Nz','Clr','Ion']` — spread
73
+ `DEFAULT_FRAMEWORK_PREFIXES` to extend), or pass `[]` to attribute to the **immediate**
74
+ owner (useful when auditing a component library's *own* code). The same option is available
75
+ on `scan`, `runA11yScan`, `scanPages`, and the CLI (`--framework-prefixes` / `--no-skip-primitives`).
76
+
68
77
  Findings are grouped by owning component, led by a summary line, and each node's
69
78
  directives are shown inline:
70
79
 
@@ -92,6 +101,57 @@ const raw = await scan(document.body); // findings only
92
101
  argument (`scan(root, { runOnly: … })`) for finer control than the provider's
93
102
  `tags`.
94
103
 
104
+ ## Report mode (headless, CI-friendly)
105
+
106
+ The provider is for while you're developing a page. **Report mode** turns the same
107
+ engine on a whole running app from the outside: it drives a headless browser over
108
+ your **dev** server, injects the same component-attributed scan, and writes a
109
+ report grouped by owning component — with no change to the app under test. It needs
110
+ a dev build, because that's what publishes `window.ng` for attribution; against a
111
+ production build, attribution falls back to `(unknown component)`.
112
+
113
+ Report mode is opt-in and needs Playwright, an **optional peer** you install
114
+ yourself (so the base package stays weightless):
115
+
116
+ ```bash
117
+ npm i -D playwright
118
+ npx playwright install chromium
119
+ ```
120
+
121
+ Start your app (`ng serve`), then point the CLI at it:
122
+
123
+ ```bash
124
+ # writes a11y.md and a11y.json
125
+ npx ngbr-a11y-report --base http://localhost:4200 --route / --route /dashboard --out a11y
126
+
127
+ # CI gate: exit non-zero on any serious/critical finding
128
+ npx ngbr-a11y-report --base http://localhost:4200 --route / --fail-on serious
129
+ ```
130
+
131
+ For apps gated behind a login or theme picker, use the programmatic API with a
132
+ `setup` hook (run once before the routes are scanned):
133
+
134
+ ```ts
135
+ import { scanPages, toMarkdown } from '@ngbracket/a11y-devtools/report';
136
+
137
+ const report = await scanPages({
138
+ baseUrl: 'http://localhost:4200',
139
+ routes: ['/pages/dashboard'],
140
+ setup: async (page) => {
141
+ await page.goto('http://localhost:4200/login');
142
+ await page.fill('#email', 'demo@example.com');
143
+ await page.click('button[type=submit]');
144
+ },
145
+ });
146
+ console.log(toMarkdown(report));
147
+ ```
148
+
149
+ The report leads with a summary of **distinct rules vs. raw node-instances** (a
150
+ "54" is usually one rule firing dozens of times), then lists findings under each
151
+ owning component. When a flagged control is itself a third-party UI primitive
152
+ (e.g. `<button nbButton>`), attribution walks past the primitive to the app
153
+ component that placed it and notes the primitive as `(via …)`.
154
+
95
155
  ## What it checks (and what it can't)
96
156
 
97
157
  Under the hood this is [axe-core](https://github.com/dequelabs/axe-core) — the
@@ -131,7 +191,11 @@ npm run build # tsc -> dist/ (ESM + .d.ts)
131
191
 
132
192
  ## Roadmap
133
193
 
194
+ - Configurable framework-primitive prefixes (PrimeNG, Clarity, Ionic, …).
195
+ - HTML report + baseline/diff mode for CI.
134
196
  - Per-component filtering and a violation-count badge.
135
197
 
136
- Done: component attribution · directive / `hostDirectives` attribution · axe scan ·
137
- grouped console reporter · dev-only provider · in-app overlay · CI prod-weight guard.
198
+ Done: component attribution (nearest app-owned, walking past UI primitives) ·
199
+ directive / `hostDirectives` attribution · axe scan · grouped console reporter ·
200
+ dev-only provider · in-app overlay · headless report mode (CLI + `./report`) ·
201
+ CI prod-weight guard.
@@ -0,0 +1,110 @@
1
+ #!/usr/bin/env node
2
+ import { writeFileSync } from 'node:fs';
3
+ import { scanPages, toJson, toMarkdown } from '../dist/report/index.js';
4
+
5
+ const USAGE = `ngbr-a11y-report — component-attributed a11y scan of a running Angular dev build
6
+
7
+ Usage:
8
+ ngbr-a11y-report --base <url> --route <path> [--route <path> ...] [options]
9
+
10
+ Options:
11
+ --base <url> Origin of the running dev server (e.g. http://localhost:4200)
12
+ --route <path> Route to scan; repeat for multiple routes
13
+ --tags <list> Comma-separated axe tags to scope the ruleset (e.g. wcag22aa,best-practice)
14
+ --out <prefix> Write <prefix>.md / <prefix>.json (default: print Markdown to stdout)
15
+ --format <fmt> md | json | both (default: both when --out is set)
16
+ --wait <ms> Settle time after load before scanning (default 1500)
17
+ --fail-on <impact> Exit non-zero if any finding is at/above impact
18
+ (minor | moderate | serious | critical) — for CI gating
19
+ --framework-prefixes <list>
20
+ Comma-separated component-name prefixes to treat as
21
+ third-party UI primitives to walk past during attribution
22
+ (default: Nb,Mat,Cdk,Mdc). e.g. Nb,Mat,Nz,Clr,Ion
23
+ --no-skip-primitives
24
+ Attribute to the immediate owner (skip nothing) — use when
25
+ scanning a component library's own code
26
+ --headed Launch a visible browser (debugging)
27
+ -h, --help Show this help
28
+ `;
29
+
30
+ const IMPACT_RANK = { minor: 1, moderate: 2, serious: 3, critical: 4 };
31
+
32
+ function parseArgs(argv) {
33
+ const opts = { routes: [], format: 'both' };
34
+ for (let i = 0; i < argv.length; i++) {
35
+ const arg = argv[i];
36
+ const next = () => argv[++i];
37
+ switch (arg) {
38
+ case '--base': opts.base = next(); break;
39
+ case '--route': opts.routes.push(next()); break;
40
+ case '--tags': opts.tags = next().split(',').map((s) => s.trim()).filter(Boolean); break;
41
+ case '--out': opts.out = next(); break;
42
+ case '--format': opts.format = next(); break;
43
+ case '--wait': opts.wait = Number(next()); break;
44
+ case '--fail-on': opts.failOn = next(); break;
45
+ case '--framework-prefixes':
46
+ opts.frameworkPrefixes = next().split(',').map((s) => s.trim()).filter(Boolean);
47
+ break;
48
+ case '--no-skip-primitives': opts.frameworkPrefixes = []; break;
49
+ case '--headed': opts.headed = true; break;
50
+ case '-h': case '--help': opts.help = true; break;
51
+ default: console.error(`Unknown argument: ${arg}\n`); opts.help = true;
52
+ }
53
+ }
54
+ return opts;
55
+ }
56
+
57
+ const opts = parseArgs(process.argv.slice(2));
58
+
59
+ if (opts.help || !opts.base || opts.routes.length === 0) {
60
+ process.stderr.write(USAGE);
61
+ process.exit(opts.help ? 0 : 1);
62
+ }
63
+
64
+ const report = await scanPages({
65
+ baseUrl: opts.base,
66
+ routes: opts.routes,
67
+ tags: opts.tags,
68
+ waitMs: opts.wait,
69
+ headed: opts.headed,
70
+ frameworkPrefixes: opts.frameworkPrefixes,
71
+ });
72
+
73
+ const allFindings = report.pages.flatMap((p) => p.findings);
74
+ process.stderr.write(
75
+ `Scanned ${report.pages.length} route(s) · ${allFindings.length} node-instance(s).\n`,
76
+ );
77
+ if (allFindings.length > 0 && allFindings.every((f) => f.component === null)) {
78
+ process.stderr.write(
79
+ 'Note: no component attribution (window.ng absent) — is this a production build? Report mode names components only against a dev build.\n',
80
+ );
81
+ }
82
+
83
+ if (!opts.out) {
84
+ process.stdout.write(toMarkdown(report) + '\n');
85
+ } else {
86
+ const format = opts.format ?? 'both';
87
+ if (format === 'md' || format === 'both') {
88
+ writeFileSync(`${opts.out}.md`, toMarkdown(report));
89
+ process.stderr.write(`Wrote ${opts.out}.md\n`);
90
+ }
91
+ if (format === 'json' || format === 'both') {
92
+ writeFileSync(`${opts.out}.json`, toJson(report));
93
+ process.stderr.write(`Wrote ${opts.out}.json\n`);
94
+ }
95
+ }
96
+
97
+ if (opts.failOn) {
98
+ const threshold = IMPACT_RANK[opts.failOn];
99
+ if (!threshold) {
100
+ process.stderr.write(`Invalid --fail-on "${opts.failOn}" (use minor|moderate|serious|critical)\n`);
101
+ process.exit(2);
102
+ }
103
+ const worst = report.pages
104
+ .flatMap((p) => p.findings)
105
+ .reduce((max, f) => Math.max(max, IMPACT_RANK[f.impact] ?? 0), 0);
106
+ if (worst >= threshold) {
107
+ process.stderr.write(`Failing: found violation(s) at or above "${opts.failOn}".\n`);
108
+ process.exit(1);
109
+ }
110
+ }
@@ -16,7 +16,37 @@ export interface NgDebugGlobal {
16
16
  getDirectives(element: Element | object): unknown[];
17
17
  }
18
18
  export declare function ngDebug(): NgDebugGlobal | undefined;
19
- export declare function resolveOwningComponentName(node: Element): string | null;
19
+ /**
20
+ * Default component-name prefixes treated as third-party UI primitives (Nebular
21
+ * `Nb*`, Angular Material `Mat*`, CDK `Cdk*`/`Mdc*`) whose violations are fixed
22
+ * where the primitive is *used*, not inside the library — e.g. `<button nbButton>`
23
+ * with no name is fixed in the component that placed it, not in Nebular.
24
+ * Attribution walks past these to the app component. A component library you
25
+ * author (e.g. `Ngbr*`) is deliberately absent: a bug in a component you ship is
26
+ * fixed in that component. Override with the `frameworkPrefixes` option — add
27
+ * `Nz`/`Clr`/`Ion`/`Tui` for other libraries, or pass `[]` to disable walking
28
+ * (attribute to the immediate owner) when scanning a library's own code.
29
+ */
30
+ export declare const DEFAULT_FRAMEWORK_PREFIXES: readonly string[];
31
+ /**
32
+ * The chain of owning components from the flagged node up to the root, nearest
33
+ * first and de-duplicated. Built by walking DOM ancestors and asking Angular's
34
+ * debug API who owns each, so a control that is itself a library primitive still
35
+ * reveals the app component that placed it. Empty when the global is absent (prod).
36
+ */
37
+ export declare function resolveComponentPath(node: Element): string[];
38
+ /**
39
+ * The component to blame from an ownership path: the nearest one the app owns,
40
+ * walking past third-party UI primitives. Pass `frameworkPrefixes: []` to skip
41
+ * nothing and return the immediate owner.
42
+ */
43
+ export declare function appComponentFromPath(path: string[], frameworkPrefixes?: readonly string[]): string | null;
44
+ /**
45
+ * The owning component name for a flagged node — the nearest component the app
46
+ * author actually owns (walking past third-party UI primitives to where the fix
47
+ * lives). Null when the debug global is absent (prod).
48
+ */
49
+ export declare function resolveOwningComponentName(node: Element, frameworkPrefixes?: readonly string[]): string | null;
20
50
  /**
21
51
  * Names of the directives applied directly to `node`, including those attached
22
52
  * via `hostDirectives` — the runtime-only a11y cases the static lint plugin
@@ -15,12 +15,79 @@ function nameOf(instance) {
15
15
  return null;
16
16
  return cleanName(instance.constructor.name ?? null);
17
17
  }
18
- export function resolveOwningComponentName(node) {
18
+ /**
19
+ * Default component-name prefixes treated as third-party UI primitives (Nebular
20
+ * `Nb*`, Angular Material `Mat*`, CDK `Cdk*`/`Mdc*`) whose violations are fixed
21
+ * where the primitive is *used*, not inside the library — e.g. `<button nbButton>`
22
+ * with no name is fixed in the component that placed it, not in Nebular.
23
+ * Attribution walks past these to the app component. A component library you
24
+ * author (e.g. `Ngbr*`) is deliberately absent: a bug in a component you ship is
25
+ * fixed in that component. Override with the `frameworkPrefixes` option — add
26
+ * `Nz`/`Clr`/`Ion`/`Tui` for other libraries, or pass `[]` to disable walking
27
+ * (attribute to the immediate owner) when scanning a library's own code.
28
+ */
29
+ export const DEFAULT_FRAMEWORK_PREFIXES = ['Nb', 'Mat', 'Cdk', 'Mdc'];
30
+ /**
31
+ * True when `name` starts with one of `prefixes` at a CamelCase boundary, so
32
+ * `MatCard` matches Material but `MatchList` does not. An empty prefix list
33
+ * matches nothing — nothing is treated as a primitive.
34
+ */
35
+ function isPrimitiveComponent(name, prefixes) {
36
+ for (const prefix of prefixes) {
37
+ if (!prefix || name.length <= prefix.length || !name.startsWith(prefix))
38
+ continue;
39
+ const next = name.charCodeAt(prefix.length);
40
+ if (next >= 65 && next <= 90)
41
+ return true; // next char is A–Z
42
+ }
43
+ return false;
44
+ }
45
+ /**
46
+ * The chain of owning components from the flagged node up to the root, nearest
47
+ * first and de-duplicated. Built by walking DOM ancestors and asking Angular's
48
+ * debug API who owns each, so a control that is itself a library primitive still
49
+ * reveals the app component that placed it. Empty when the global is absent (prod).
50
+ */
51
+ export function resolveComponentPath(node) {
19
52
  const ng = ngDebug();
20
- if (!ng)
21
- return null;
22
- const component = ng.getComponent(node) ?? ng.getOwningComponent(node);
23
- return nameOf(component);
53
+ // A production build can leave a partial `ng` global (present but without the
54
+ // debug helpers). Treat a missing/!function owner-resolver as "no attribution"
55
+ // rather than throwing mid-scan.
56
+ if (!ng || typeof ng.getOwningComponent !== 'function')
57
+ return [];
58
+ const getComponent = typeof ng.getComponent === 'function' ? ng.getComponent.bind(ng) : null;
59
+ const path = [];
60
+ let el = node;
61
+ while (el) {
62
+ let owner = null;
63
+ try {
64
+ owner = getComponent?.(el) ?? ng.getOwningComponent(el);
65
+ }
66
+ catch {
67
+ owner = null; // node isn't part of a live view
68
+ }
69
+ const name = nameOf(owner);
70
+ if (name && name !== path[path.length - 1])
71
+ path.push(name);
72
+ el = el.parentElement;
73
+ }
74
+ return path;
75
+ }
76
+ /**
77
+ * The component to blame from an ownership path: the nearest one the app owns,
78
+ * walking past third-party UI primitives. Pass `frameworkPrefixes: []` to skip
79
+ * nothing and return the immediate owner.
80
+ */
81
+ export function appComponentFromPath(path, frameworkPrefixes = DEFAULT_FRAMEWORK_PREFIXES) {
82
+ return path.find((name) => !isPrimitiveComponent(name, frameworkPrefixes)) ?? path[0] ?? null;
83
+ }
84
+ /**
85
+ * The owning component name for a flagged node — the nearest component the app
86
+ * author actually owns (walking past third-party UI primitives to where the fix
87
+ * lives). Null when the debug global is absent (prod).
88
+ */
89
+ export function resolveOwningComponentName(node, frameworkPrefixes = DEFAULT_FRAMEWORK_PREFIXES) {
90
+ return appComponentFromPath(resolveComponentPath(node), frameworkPrefixes);
24
91
  }
25
92
  /**
26
93
  * Names of the directives applied directly to `node`, including those attached
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  export { provideA11yDevtools, type A11yDevtoolsOptions } from './provider.js';
2
2
  export { runA11yScan, type RunOptions } from './runner.js';
3
- export { scan, type A11yFinding, type Impact } from './scan.js';
3
+ export { scan, type A11yFinding, type Impact, type ScanOptions } from './scan.js';
4
4
  export { logFindings, type Logger } from './report.js';
5
- export { resolveOwningComponentName, ngDebug, type NgDebugGlobal } from './attribution.js';
5
+ export { resolveOwningComponentName, resolveComponentPath, appComponentFromPath, DEFAULT_FRAMEWORK_PREFIXES, ngDebug, type NgDebugGlobal, } from './attribution.js';
6
6
  export { createOverlay, OVERLAY_ATTR, OVERLAY_EXCLUDE_SELECTOR, type A11yOverlay, type OverlayOptions, } from './overlay.js';
package/dist/index.js CHANGED
@@ -2,5 +2,5 @@ export { provideA11yDevtools } from './provider.js';
2
2
  export { runA11yScan } from './runner.js';
3
3
  export { scan } from './scan.js';
4
4
  export { logFindings } from './report.js';
5
- export { resolveOwningComponentName, ngDebug } from './attribution.js';
5
+ export { resolveOwningComponentName, resolveComponentPath, appComponentFromPath, DEFAULT_FRAMEWORK_PREFIXES, ngDebug, } from './attribution.js';
6
6
  export { createOverlay, OVERLAY_ATTR, OVERLAY_EXCLUDE_SELECTOR, } from './overlay.js';
@@ -0,0 +1,12 @@
1
+ import type { RunOptions as AxeRunOptions } from 'axe-core';
2
+ import { type A11yFinding, type ScanOptions } from './scan.js';
3
+ /**
4
+ * The browser-injected half of report-mode. A headless driver injects the built
5
+ * IIFE (`dist/inpage.global.js`) into a running **dev** page and calls this
6
+ * global; because it runs *in the page*, `window.ng` is live and `scan()`
7
+ * attributes each violation to its owning component — no change to the target app.
8
+ *
9
+ * This entry is deliberately NOT re-exported from `index.ts`: it bundles axe-core
10
+ * and must never reach a consumer's application bundle.
11
+ */
12
+ export type InPageScan = (options?: AxeRunOptions, scanOptions?: ScanOptions) => Promise<A11yFinding[]>;