@ngbracket/a11y-devtools 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,43 @@
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.4.0
7
+
8
+ ### Added
9
+
10
+ - **Report mode** — a headless, CI-friendly way to scan a whole running app. A new
11
+ `./report` export (`scanPages`, `toMarkdown`, `toJson`) and a `ngbr-a11y-report`
12
+ CLI drive a headless browser over your dev server, inject the same
13
+ component-attributed scan, and write a Markdown + JSON report grouped by owning
14
+ component. No change to the app under test.
15
+ - `--fail-on <impact>` exits non-zero on findings at/above a severity, for CI gates.
16
+ - A `setup` hook (programmatic API) handles apps gated behind a login or theme picker.
17
+ - Reports surface **distinct rules vs. raw node-instances**.
18
+ - `A11yFinding.componentPath` — the full ownership chain from the flagged node to
19
+ the root, nearest first.
20
+ - Exported `resolveComponentPath` and `appComponentFromPath`.
21
+
22
+ ### Changed
23
+
24
+ - **Attribution now reports the nearest _app-owned_ component.** Violations on a
25
+ third-party UI primitive (Nebular `Nb*`, Angular Material `Mat*`, CDK
26
+ `Cdk*`/`Mdc*`) are attributed to the app component that placed them — where the
27
+ fix lives — instead of the library component. A component library you author
28
+ (`Ngbr*`) is intentionally not skipped. This changes `finding.component` (and the
29
+ console/overlay grouping) for such cases; the primitive is preserved in
30
+ `componentPath` and shown as `(via …)` in the report.
31
+
32
+ ### Packaging
33
+
34
+ - Playwright is an **optional peer dependency** (not auto-installed) — install it
35
+ only if you use report mode. The base package stays weightless; axe-core still
36
+ never reaches your app bundle (enforced by the prod-weight guard, now extended to
37
+ keep report-mode code out of the browser entry).
38
+
39
+ ## 0.3.0
40
+
41
+ - Scoped ruleset via `tags`; documented WCAG coverage.
42
+ - Component + directive/`hostDirectives` attribution, axe scan, grouped console
43
+ reporter, dev-only provider, in-app overlay, CI prod-weight guard.
package/README.md CHANGED
@@ -92,6 +92,57 @@ const raw = await scan(document.body); // findings only
92
92
  argument (`scan(root, { runOnly: … })`) for finer control than the provider's
93
93
  `tags`.
94
94
 
95
+ ## Report mode (headless, CI-friendly)
96
+
97
+ The provider is for while you're developing a page. **Report mode** turns the same
98
+ engine on a whole running app from the outside: it drives a headless browser over
99
+ your **dev** server, injects the same component-attributed scan, and writes a
100
+ report grouped by owning component — with no change to the app under test. It needs
101
+ a dev build, because that's what publishes `window.ng` for attribution; against a
102
+ production build, attribution falls back to `(unknown component)`.
103
+
104
+ Report mode is opt-in and needs Playwright, an **optional peer** you install
105
+ yourself (so the base package stays weightless):
106
+
107
+ ```bash
108
+ npm i -D playwright
109
+ npx playwright install chromium
110
+ ```
111
+
112
+ Start your app (`ng serve`), then point the CLI at it:
113
+
114
+ ```bash
115
+ # writes a11y.md and a11y.json
116
+ npx ngbr-a11y-report --base http://localhost:4200 --route / --route /dashboard --out a11y
117
+
118
+ # CI gate: exit non-zero on any serious/critical finding
119
+ npx ngbr-a11y-report --base http://localhost:4200 --route / --fail-on serious
120
+ ```
121
+
122
+ For apps gated behind a login or theme picker, use the programmatic API with a
123
+ `setup` hook (run once before the routes are scanned):
124
+
125
+ ```ts
126
+ import { scanPages, toMarkdown } from '@ngbracket/a11y-devtools/report';
127
+
128
+ const report = await scanPages({
129
+ baseUrl: 'http://localhost:4200',
130
+ routes: ['/pages/dashboard'],
131
+ setup: async (page) => {
132
+ await page.goto('http://localhost:4200/login');
133
+ await page.fill('#email', 'demo@example.com');
134
+ await page.click('button[type=submit]');
135
+ },
136
+ });
137
+ console.log(toMarkdown(report));
138
+ ```
139
+
140
+ The report leads with a summary of **distinct rules vs. raw node-instances** (a
141
+ "54" is usually one rule firing dozens of times), then lists findings under each
142
+ owning component. When a flagged control is itself a third-party UI primitive
143
+ (e.g. `<button nbButton>`), attribution walks past the primitive to the app
144
+ component that placed it and notes the primitive as `(via …)`.
145
+
95
146
  ## What it checks (and what it can't)
96
147
 
97
148
  Under the hood this is [axe-core](https://github.com/dequelabs/axe-core) — the
@@ -131,7 +182,11 @@ npm run build # tsc -> dist/ (ESM + .d.ts)
131
182
 
132
183
  ## Roadmap
133
184
 
185
+ - Configurable framework-primitive prefixes (PrimeNG, Clarity, Ionic, …).
186
+ - HTML report + baseline/diff mode for CI.
134
187
  - Per-component filtering and a violation-count badge.
135
188
 
136
- Done: component attribution · directive / `hostDirectives` attribution · axe scan ·
137
- grouped console reporter · dev-only provider · in-app overlay · CI prod-weight guard.
189
+ Done: component attribution (nearest app-owned, walking past UI primitives) ·
190
+ directive / `hostDirectives` attribution · axe scan · grouped console reporter ·
191
+ dev-only provider · in-app overlay · headless report mode (CLI + `./report`) ·
192
+ CI prod-weight guard.
@@ -0,0 +1,98 @@
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
+ --headed Launch a visible browser (debugging)
20
+ -h, --help Show this help
21
+ `;
22
+
23
+ const IMPACT_RANK = { minor: 1, moderate: 2, serious: 3, critical: 4 };
24
+
25
+ function parseArgs(argv) {
26
+ const opts = { routes: [], format: 'both' };
27
+ for (let i = 0; i < argv.length; i++) {
28
+ const arg = argv[i];
29
+ const next = () => argv[++i];
30
+ switch (arg) {
31
+ case '--base': opts.base = next(); break;
32
+ case '--route': opts.routes.push(next()); break;
33
+ case '--tags': opts.tags = next().split(',').map((s) => s.trim()).filter(Boolean); break;
34
+ case '--out': opts.out = next(); break;
35
+ case '--format': opts.format = next(); break;
36
+ case '--wait': opts.wait = Number(next()); break;
37
+ case '--fail-on': opts.failOn = next(); break;
38
+ case '--headed': opts.headed = true; break;
39
+ case '-h': case '--help': opts.help = true; break;
40
+ default: console.error(`Unknown argument: ${arg}\n`); opts.help = true;
41
+ }
42
+ }
43
+ return opts;
44
+ }
45
+
46
+ const opts = parseArgs(process.argv.slice(2));
47
+
48
+ if (opts.help || !opts.base || opts.routes.length === 0) {
49
+ process.stderr.write(USAGE);
50
+ process.exit(opts.help ? 0 : 1);
51
+ }
52
+
53
+ const report = await scanPages({
54
+ baseUrl: opts.base,
55
+ routes: opts.routes,
56
+ tags: opts.tags,
57
+ waitMs: opts.wait,
58
+ headed: opts.headed,
59
+ });
60
+
61
+ const allFindings = report.pages.flatMap((p) => p.findings);
62
+ process.stderr.write(
63
+ `Scanned ${report.pages.length} route(s) · ${allFindings.length} node-instance(s).\n`,
64
+ );
65
+ if (allFindings.length > 0 && allFindings.every((f) => f.component === null)) {
66
+ process.stderr.write(
67
+ 'Note: no component attribution (window.ng absent) — is this a production build? Report mode names components only against a dev build.\n',
68
+ );
69
+ }
70
+
71
+ if (!opts.out) {
72
+ process.stdout.write(toMarkdown(report) + '\n');
73
+ } else {
74
+ const format = opts.format ?? 'both';
75
+ if (format === 'md' || format === 'both') {
76
+ writeFileSync(`${opts.out}.md`, toMarkdown(report));
77
+ process.stderr.write(`Wrote ${opts.out}.md\n`);
78
+ }
79
+ if (format === 'json' || format === 'both') {
80
+ writeFileSync(`${opts.out}.json`, toJson(report));
81
+ process.stderr.write(`Wrote ${opts.out}.json\n`);
82
+ }
83
+ }
84
+
85
+ if (opts.failOn) {
86
+ const threshold = IMPACT_RANK[opts.failOn];
87
+ if (!threshold) {
88
+ process.stderr.write(`Invalid --fail-on "${opts.failOn}" (use minor|moderate|serious|critical)\n`);
89
+ process.exit(2);
90
+ }
91
+ const worst = report.pages
92
+ .flatMap((p) => p.findings)
93
+ .reduce((max, f) => Math.max(max, IMPACT_RANK[f.impact] ?? 0), 0);
94
+ if (worst >= threshold) {
95
+ process.stderr.write(`Failing: found violation(s) at or above "${opts.failOn}".\n`);
96
+ process.exit(1);
97
+ }
98
+ }
@@ -16,6 +16,20 @@ export interface NgDebugGlobal {
16
16
  getDirectives(element: Element | object): unknown[];
17
17
  }
18
18
  export declare function ngDebug(): NgDebugGlobal | undefined;
19
+ /**
20
+ * The chain of owning components from the flagged node up to the root, nearest
21
+ * first and de-duplicated. Built by walking DOM ancestors and asking Angular's
22
+ * debug API who owns each, so a control that is itself a library primitive still
23
+ * reveals the app component that placed it. Empty when the global is absent (prod).
24
+ */
25
+ export declare function resolveComponentPath(node: Element): string[];
26
+ /** The component to blame from an ownership path: the nearest one the app owns. */
27
+ export declare function appComponentFromPath(path: string[]): string | null;
28
+ /**
29
+ * The owning component name for a flagged node — the nearest component the app
30
+ * author actually owns (walking past third-party UI primitives to where the fix
31
+ * lives). Null when the debug global is absent (prod).
32
+ */
19
33
  export declare function resolveOwningComponentName(node: Element): string | null;
20
34
  /**
21
35
  * Names of the directives applied directly to `node`, including those attached
@@ -15,12 +15,61 @@ function nameOf(instance) {
15
15
  return null;
16
16
  return cleanName(instance.constructor.name ?? null);
17
17
  }
18
- export function resolveOwningComponentName(node) {
18
+ /**
19
+ * Third-party UI-primitive components (Nebular `Nb*`, Angular Material `Mat*`,
20
+ * CDK `Cdk*`/`Mdc*`) whose violations are fixed where the primitive is *used*,
21
+ * not inside the library — e.g. `<button nbButton>` with no name is fixed in the
22
+ * component that placed it, not in Nebular. Attribution walks past these to the
23
+ * app component. Matched with a CamelCase boundary so `MatchListComponent` isn't
24
+ * mistaken for Material. A component library you author (e.g. `Ngbr*`) is
25
+ * deliberately absent: a bug in a component you ship is fixed in that component.
26
+ */
27
+ const PRIMITIVE_COMPONENT = /^(Nb|Mat|Cdk|Mdc)[A-Z]/;
28
+ function isPrimitiveComponent(name) {
29
+ return PRIMITIVE_COMPONENT.test(name);
30
+ }
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 function resolveComponentPath(node) {
19
38
  const ng = ngDebug();
20
- if (!ng)
21
- return null;
22
- const component = ng.getComponent(node) ?? ng.getOwningComponent(node);
23
- return nameOf(component);
39
+ // A production build can leave a partial `ng` global (present but without the
40
+ // debug helpers). Treat a missing/!function owner-resolver as "no attribution"
41
+ // rather than throwing mid-scan.
42
+ if (!ng || typeof ng.getOwningComponent !== 'function')
43
+ return [];
44
+ const getComponent = typeof ng.getComponent === 'function' ? ng.getComponent.bind(ng) : null;
45
+ const path = [];
46
+ let el = node;
47
+ while (el) {
48
+ let owner = null;
49
+ try {
50
+ owner = getComponent?.(el) ?? ng.getOwningComponent(el);
51
+ }
52
+ catch {
53
+ owner = null; // node isn't part of a live view
54
+ }
55
+ const name = nameOf(owner);
56
+ if (name && name !== path[path.length - 1])
57
+ path.push(name);
58
+ el = el.parentElement;
59
+ }
60
+ return path;
61
+ }
62
+ /** The component to blame from an ownership path: the nearest one the app owns. */
63
+ export function appComponentFromPath(path) {
64
+ return path.find((name) => !isPrimitiveComponent(name)) ?? path[0] ?? null;
65
+ }
66
+ /**
67
+ * The owning component name for a flagged node — the nearest component the app
68
+ * author actually owns (walking past third-party UI primitives to where the fix
69
+ * lives). Null when the debug global is absent (prod).
70
+ */
71
+ export function resolveOwningComponentName(node) {
72
+ return appComponentFromPath(resolveComponentPath(node));
24
73
  }
25
74
  /**
26
75
  * Names of the directives applied directly to `node`, including those attached
package/dist/index.d.ts CHANGED
@@ -2,5 +2,5 @@ export { provideA11yDevtools, type A11yDevtoolsOptions } from './provider.js';
2
2
  export { runA11yScan, type RunOptions } from './runner.js';
3
3
  export { scan, type A11yFinding, type Impact } 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, 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, 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 } 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) => Promise<A11yFinding[]>;