@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/dist/inpage.js ADDED
@@ -0,0 +1,3 @@
1
+ import { scan } from './scan.js';
2
+ const run = (options) => scan(document, options);
3
+ globalThis.__ngbA11yScan = run;
@@ -0,0 +1,38 @@
1
+ import type { A11yFinding } from '../scan.js';
2
+ /**
3
+ * Pure formatting for report-mode: grouping + Markdown/JSON serialization. Kept
4
+ * free of any Node or Playwright imports so the browser side (`report.ts`) can
5
+ * share `groupByComponent` without dragging headless code into the app bundle.
6
+ */
7
+ /** One scanned page/route and everything found on it. */
8
+ export interface PageReport {
9
+ /** Human label for the page, e.g. `Dashboard`. */
10
+ label: string;
11
+ /** The URL actually scanned. */
12
+ url: string;
13
+ findings: A11yFinding[];
14
+ /** Set when this route failed to scan; findings will be empty. */
15
+ error?: string;
16
+ }
17
+ /** A whole report-mode run across one or more pages. */
18
+ export interface ScanReport {
19
+ /** ISO timestamp of the run. */
20
+ generatedAt: string;
21
+ pages: PageReport[];
22
+ }
23
+ /**
24
+ * Group findings by the component that rendered them — the readable form the
25
+ * attribution makes possible ("♿ HeaderComponent — 2 issues" beats a list of
26
+ * CSS selectors). Insertion order is preserved so callers stay deterministic.
27
+ */
28
+ export declare function groupByComponent(findings: A11yFinding[]): Map<string, A11yFinding[]>;
29
+ /**
30
+ * Distinct axe rules vs. raw node-instances — the honest pair. A "54" headline
31
+ * is usually one rule firing dozens of times; distinct rules is the number that
32
+ * actually describes an app. Reports surface both so neither can mislead.
33
+ */
34
+ export declare function distinctRuleCount(findings: A11yFinding[]): number;
35
+ /** Serialize a report to JSON, with per-page and overall summary counts. */
36
+ export declare function toJson(report: ScanReport): string;
37
+ /** Render a human-readable Markdown report grouped by owning component. */
38
+ export declare function toMarkdown(report: ScanReport): string;
@@ -0,0 +1,108 @@
1
+ /**
2
+ * Group findings by the component that rendered them — the readable form the
3
+ * attribution makes possible ("♿ HeaderComponent — 2 issues" beats a list of
4
+ * CSS selectors). Insertion order is preserved so callers stay deterministic.
5
+ */
6
+ export function groupByComponent(findings) {
7
+ const byComponent = new Map();
8
+ for (const finding of findings) {
9
+ const key = finding.component ?? '(unknown component)';
10
+ const bucket = byComponent.get(key);
11
+ if (bucket)
12
+ bucket.push(finding);
13
+ else
14
+ byComponent.set(key, [finding]);
15
+ }
16
+ return byComponent;
17
+ }
18
+ /**
19
+ * Distinct axe rules vs. raw node-instances — the honest pair. A "54" headline
20
+ * is usually one rule firing dozens of times; distinct rules is the number that
21
+ * actually describes an app. Reports surface both so neither can mislead.
22
+ */
23
+ export function distinctRuleCount(findings) {
24
+ return new Set(findings.map((f) => f.id)).size;
25
+ }
26
+ const IMPACT_RANK = {
27
+ critical: 0,
28
+ serious: 1,
29
+ moderate: 2,
30
+ minor: 3,
31
+ };
32
+ function impactRank(impact) {
33
+ return impact ? (IMPACT_RANK[impact] ?? 4) : 4;
34
+ }
35
+ /** Serialize a report to JSON, with per-page and overall summary counts. */
36
+ export function toJson(report) {
37
+ const all = report.pages.flatMap((p) => p.findings);
38
+ return JSON.stringify({
39
+ generatedAt: report.generatedAt,
40
+ summary: {
41
+ pages: report.pages.length,
42
+ distinctRules: distinctRuleCount(all),
43
+ nodeInstances: all.length,
44
+ },
45
+ pages: report.pages.map((p) => ({
46
+ label: p.label,
47
+ url: p.url,
48
+ distinctRules: distinctRuleCount(p.findings),
49
+ nodeInstances: p.findings.length,
50
+ findings: p.findings,
51
+ })),
52
+ }, null, 2);
53
+ }
54
+ /** Render a human-readable Markdown report grouped by owning component. */
55
+ export function toMarkdown(report) {
56
+ const all = report.pages.flatMap((p) => p.findings);
57
+ const lines = [];
58
+ lines.push('# Accessibility report');
59
+ lines.push('');
60
+ lines.push(`_Generated ${report.generatedAt} · @ngbracket/a11y-devtools report-mode_`);
61
+ lines.push('');
62
+ // Summary table — distinct rules alongside raw node-instances, so the headline
63
+ // count can't be read as "how bad is it" on its own.
64
+ lines.push('## Summary');
65
+ lines.push('');
66
+ lines.push('| Page | Distinct rules | Node-instances | Components |');
67
+ lines.push('|---|---:|---:|---:|');
68
+ for (const page of report.pages) {
69
+ lines.push(`| ${page.label} | ${distinctRuleCount(page.findings)} | ${page.findings.length} | ${groupByComponent(page.findings).size} |`);
70
+ }
71
+ lines.push(`| **Total** | **${distinctRuleCount(all)}** | **${all.length}** | **${groupByComponent(all).size}** |`);
72
+ lines.push('');
73
+ for (const page of report.pages) {
74
+ lines.push(`## ${page.label} — \`${page.url}\``);
75
+ lines.push('');
76
+ if (page.error) {
77
+ lines.push(`⚠️ Scan failed: ${page.error}`);
78
+ lines.push('');
79
+ continue;
80
+ }
81
+ if (page.findings.length === 0) {
82
+ lines.push('No violations found. ✅');
83
+ lines.push('');
84
+ continue;
85
+ }
86
+ lines.push(`${page.findings.length} node-instance(s) across ${distinctRuleCount(page.findings)} distinct rule(s).`);
87
+ lines.push('');
88
+ const byComponent = [...groupByComponent(page.findings)].sort((a, b) => b[1].length - a[1].length);
89
+ for (const [component, items] of byComponent) {
90
+ lines.push(`### ♿ ${component} — ${items.length} issue(s)`);
91
+ lines.push('');
92
+ const sorted = [...items].sort((a, b) => impactRank(a.impact) - impactRank(b.impact));
93
+ for (const finding of sorted) {
94
+ // UI primitives the app component rendered through, e.g. an `<button
95
+ // nbButton>` shows as "via NbButtonComponent" under its app owner.
96
+ const ownerIndex = finding.component ? finding.componentPath.indexOf(finding.component) : -1;
97
+ const wrappers = ownerIndex > 0 ? finding.componentPath.slice(0, ownerIndex) : [];
98
+ const via = [...wrappers, ...finding.directives];
99
+ const suffix = via.length ? ` _(via ${via.join(', ')})_` : '';
100
+ lines.push(`- **${finding.impact ?? 'n/a'} · ${finding.id}**: ${finding.help}${suffix}`);
101
+ lines.push(` - \`${finding.target}\``);
102
+ lines.push(` - ${finding.helpUrl}`);
103
+ }
104
+ lines.push('');
105
+ }
106
+ }
107
+ return lines.join('\n');
108
+ }
@@ -0,0 +1,29 @@
1
+ import type { Page } from 'playwright';
2
+ import type { ScanReport } from './format.js';
3
+ export interface ScanPagesOptions {
4
+ /** Origin of the running dev server, e.g. `http://localhost:4200`. */
5
+ baseUrl: string;
6
+ /** Route paths to scan, resolved against `baseUrl`, e.g. `['/pages/dashboard']`. */
7
+ routes: string[];
8
+ /** Restrict axe to these tags, e.g. `['wcag22aa']`. Omit for the default ruleset. */
9
+ tags?: string[];
10
+ /** Quiet time (ms) after load before scanning, for SPA settle. Default 1500. */
11
+ waitMs?: number;
12
+ /** Optional human labels keyed by route path (falls back to the route). */
13
+ labels?: Record<string, string>;
14
+ /**
15
+ * Run once against `baseUrl` before scanning — e.g. dismiss a splash or pick a
16
+ * theme (ngx-admin gates its dashboard behind a theme picker). State that
17
+ * persists (localStorage/cookies) carries into the scanned routes.
18
+ */
19
+ setup?: (page: Page) => Promise<void>;
20
+ /** Launch a headed browser (for debugging). Default false (headless). */
21
+ headed?: boolean;
22
+ }
23
+ /**
24
+ * Drive a real headless browser over a running Angular **dev** build and return
25
+ * component-attributed findings per route. The scan runs *in the page* (via the
26
+ * injected in-page bundle), so `window.ng` is live and each violation is mapped
27
+ * to the component that rendered it — with no change to the target app.
28
+ */
29
+ export declare function scanPages(options: ScanPagesOptions): Promise<ScanReport>;
@@ -0,0 +1,65 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { dirname, resolve } from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ async function loadPlaywright() {
5
+ try {
6
+ return await import('playwright');
7
+ }
8
+ catch {
9
+ throw new Error('report-mode needs Playwright, which is an optional dependency. Install it with ' +
10
+ '`npm i -D playwright` and download a browser with `npx playwright install chromium`.');
11
+ }
12
+ }
13
+ /** Path to the built in-page IIFE, resolved relative to this compiled module. */
14
+ function inPageScriptPath() {
15
+ return resolve(dirname(fileURLToPath(import.meta.url)), '..', 'inpage.global.js');
16
+ }
17
+ /**
18
+ * Drive a real headless browser over a running Angular **dev** build and return
19
+ * component-attributed findings per route. The scan runs *in the page* (via the
20
+ * injected in-page bundle), so `window.ng` is live and each violation is mapped
21
+ * to the component that rendered it — with no change to the target app.
22
+ */
23
+ export async function scanPages(options) {
24
+ const { baseUrl, routes, tags, waitMs = 1500, labels = {}, setup, headed = false } = options;
25
+ const axeOptions = tags
26
+ ? { runOnly: { type: 'tag', values: tags } }
27
+ : undefined;
28
+ const inPageScript = readFileSync(inPageScriptPath(), 'utf8');
29
+ const { chromium } = await loadPlaywright();
30
+ const browser = await chromium.launch({ headless: !headed });
31
+ const pages = [];
32
+ try {
33
+ const context = await browser.newContext({ viewport: { width: 1280, height: 900 } });
34
+ const page = await context.newPage();
35
+ if (setup) {
36
+ await page.goto(baseUrl, { waitUntil: 'domcontentloaded' });
37
+ await setup(page);
38
+ }
39
+ for (const route of routes) {
40
+ const url = new URL(route, baseUrl).toString();
41
+ const label = labels[route] ?? route;
42
+ try {
43
+ // networkidle is the right settle signal for an SPA, but some apps keep a
44
+ // socket open and never reach it — fall back to a plain load.
45
+ await page.goto(url, { waitUntil: 'networkidle' }).catch(() => page.goto(url));
46
+ await page.waitForTimeout(waitMs);
47
+ await page.addScriptTag({ content: inPageScript });
48
+ const findings = (await page.evaluate((opts) => {
49
+ const w = window;
50
+ return w.__ngbA11yScan(opts);
51
+ }, axeOptions));
52
+ pages.push({ label, url: page.url(), findings });
53
+ }
54
+ catch (err) {
55
+ // One bad route shouldn't sink the whole run — record it and continue.
56
+ const message = err instanceof Error ? err.message : String(err);
57
+ pages.push({ label, url, findings: [], error: message });
58
+ }
59
+ }
60
+ }
61
+ finally {
62
+ await browser.close();
63
+ }
64
+ return { generatedAt: new Date().toISOString(), pages };
65
+ }
@@ -0,0 +1,2 @@
1
+ export { scanPages, type ScanPagesOptions } from './headless.js';
2
+ export { groupByComponent, distinctRuleCount, toJson, toMarkdown, type PageReport, type ScanReport, } from './format.js';
@@ -0,0 +1,2 @@
1
+ export { scanPages } from './headless.js';
2
+ export { groupByComponent, distinctRuleCount, toJson, toMarkdown, } from './format.js';
package/dist/report.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { groupByComponent } from './report/format.js';
1
2
  /**
2
3
  * Log findings grouped by the component that owns them — the readable form the
3
4
  * attribution makes possible ("♿ UserCardComponent — 2 issues" beats a list of
@@ -8,15 +9,7 @@ export function logFindings(findings, logger = console) {
8
9
  logger.info('♿ a11y-devtools: no violations found');
9
10
  return;
10
11
  }
11
- const byComponent = new Map();
12
- for (const finding of findings) {
13
- const key = finding.component ?? '(unknown component)';
14
- const bucket = byComponent.get(key);
15
- if (bucket)
16
- bucket.push(finding);
17
- else
18
- byComponent.set(key, [finding]);
19
- }
12
+ const byComponent = groupByComponent(findings);
20
13
  logger.info(`♿ a11y-devtools: ${findings.length} issue(s) across ${byComponent.size} component(s)`);
21
14
  for (const [component, items] of byComponent) {
22
15
  logger.groupCollapsed(`♿ ${component} — ${items.length} issue(s)`);
package/dist/scan.d.ts CHANGED
@@ -9,6 +9,8 @@ export interface A11yFinding {
9
9
  helpUrl: string;
10
10
  /** Owning component name, or null when attribution isn't available (prod). */
11
11
  component: string | null;
12
+ /** Owning components from the flagged node up to the root, nearest first; [] in prod. */
13
+ componentPath: string[];
12
14
  /** Directives on the flagged node (incl. hostDirectives); [] when none/unavailable. */
13
15
  directives: string[];
14
16
  /** CSS selector axe reported for the node. */
package/dist/scan.js CHANGED
@@ -1,4 +1,4 @@
1
- import { resolveDirectiveNames, resolveOwningComponentName } from './attribution.js';
1
+ import { appComponentFromPath, resolveComponentPath, resolveDirectiveNames } from './attribution.js';
2
2
  import { OVERLAY_EXCLUDE_SELECTOR } from './overlay.js';
3
3
  // axe-core is a singleton and throws if a run starts while another is in flight.
4
4
  // Chain runs so overlapping callers (e.g. rapid rescans) serialize safely.
@@ -31,12 +31,14 @@ async function runAxeOnce(root, options) {
31
31
  catch {
32
32
  element = null;
33
33
  }
34
+ const componentPath = element ? resolveComponentPath(element) : [];
34
35
  findings.push({
35
36
  id: violation.id,
36
37
  impact: (violation.impact ?? null),
37
38
  help: violation.help,
38
39
  helpUrl: violation.helpUrl,
39
- component: element ? resolveOwningComponentName(element) : null,
40
+ component: appComponentFromPath(componentPath),
41
+ componentPath,
40
42
  directives: element ? resolveDirectiveNames(element) : [],
41
43
  target,
42
44
  html: node.html,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ngbracket/a11y-devtools",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "description": "Dev-only in-app accessibility auditing for Angular that maps each axe violation back to the component that rendered it — the attribution React overlay tools can't do.",
5
5
  "license": "MIT",
6
6
  "author": "Duncan Faulkner",
@@ -30,16 +30,25 @@
30
30
  "types": "./dist/index.d.ts",
31
31
  "import": "./dist/index.js"
32
32
  },
33
+ "./report": {
34
+ "types": "./dist/report/index.d.ts",
35
+ "import": "./dist/report/index.js"
36
+ },
33
37
  "./package.json": "./package.json"
34
38
  },
39
+ "bin": {
40
+ "ngbr-a11y-report": "bin/ngbr-a11y-report.mjs"
41
+ },
35
42
  "files": [
36
- "dist"
43
+ "dist",
44
+ "bin",
45
+ "CHANGELOG.md"
37
46
  ],
38
47
  "engines": {
39
48
  "node": "^20.19.0 || ^22.12.0 || >=24.0.0"
40
49
  },
41
50
  "scripts": {
42
- "build": "tsc -p tsconfig.json",
51
+ "build": "tsc -p tsconfig.json && node scripts/build-inpage.mjs",
43
52
  "test": "vitest run",
44
53
  "test:watch": "vitest",
45
54
  "demo:console": "vitest run --config vitest.demo.config.ts --disableConsoleIntercept",
@@ -50,9 +59,17 @@
50
59
  },
51
60
  "peerDependencies": {
52
61
  "@angular/core": ">=18.0.0",
53
- "rxjs": ">=7.0.0"
62
+ "rxjs": ">=7.0.0",
63
+ "playwright": ">=1.40.0"
64
+ },
65
+ "peerDependenciesMeta": {
66
+ "playwright": {
67
+ "optional": true
68
+ }
54
69
  },
55
70
  "devDependencies": {
71
+ "esbuild": "^0.28.2",
72
+ "playwright": "^1.40.0",
56
73
  "@analogjs/vite-plugin-angular": "^2.7.2",
57
74
  "@analogjs/vitest-angular": "^2.7.2",
58
75
  "@angular/build": "^22.1.7",