@ngbracket/a11y-devtools 0.12.3 → 0.13.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 CHANGED
@@ -3,6 +3,21 @@
3
3
  All notable changes to `@ngbracket/a11y-devtools` are documented here.
4
4
  This project adheres to [Semantic Versioning](https://semver.org/).
5
5
 
6
+ ## 0.13.0
7
+
8
+ ### Added
9
+
10
+ - **Report mode can start your dev server.** `--serve "<command>"` runs the
11
+ command (for example `--serve "npx ng serve"`), waits until `--base` answers,
12
+ scans, then stops the server and everything it started — even on Ctrl+C or a
13
+ cancelled CI job. `--base` defaults to `http://localhost:4200` with `--serve`.
14
+ If something already answers at `--base`, that server is scanned and nothing is
15
+ started, so the same command works locally with `ng serve` already running.
16
+ `--serve-timeout <seconds>` (default 180) sets how long to wait. If the command
17
+ exits early or never answers, the CLI exits with code `2` and prints the last
18
+ lines of its output. From code: `startDevServer()` and `isServing()` from
19
+ `@ngbracket/a11y-devtools/report`.
20
+
6
21
  ## 0.12.3
7
22
 
8
23
  ### Changed
package/README.md CHANGED
@@ -59,10 +59,10 @@ finding highlights labelled with their owning component (including the ngbr/*
59
59
  keyboard findings), and the focus-follow accessibility-tree panel showing the
60
60
  focused button's computed role, name and states.](./demo/keyboard-layer-2026-09.png)
61
61
 
62
- In CI, against a running `ng serve`:
62
+ In CI (`--serve` starts `ng serve`, waits for it, and stops it after the scan):
63
63
 
64
64
  ```bash
65
- npx ngbr-a11y-report --base http://localhost:4200 --route / --route /settings \
65
+ npx ngbr-a11y-report --serve "npx ng serve" --route / --route /settings \
66
66
  --keyboard --baseline a11y-baseline.json --fail-on serious --out a11y --format all
67
67
  ```
68
68
 
@@ -4,6 +4,7 @@ import {
4
4
  diffAgainstBaseline,
5
5
  parseBaseline,
6
6
  scanPages,
7
+ startDevServer,
7
8
  toHtml,
8
9
  toJson,
9
10
  toMarkdown,
@@ -13,9 +14,16 @@ const USAGE = `ngbr-a11y-report — component-attributed a11y scan of a running
13
14
 
14
15
  Usage:
15
16
  ngbr-a11y-report --base <url> --route <path> [--route <path> ...] [options]
17
+ ngbr-a11y-report --serve "<command>" --route <path> [...] [options]
16
18
 
17
19
  Options:
18
- --base <url> Origin of the running dev server (e.g. http://localhost:4200)
20
+ --base <url> Origin of the running dev server (e.g. http://localhost:4200).
21
+ With --serve, defaults to http://localhost:4200
22
+ --serve <command> Start the dev server with this command, wait until --base
23
+ answers, scan, then stop it — e.g. --serve "npx ng serve".
24
+ If --base already answers, that server is used as-is
25
+ --serve-timeout <s>
26
+ Seconds to wait for --serve to answer (default 180)
19
27
  --route <path> Route to scan; repeat for multiple routes
20
28
  --tags <list> Comma-separated axe tags to scope the ruleset (e.g. wcag22aa,best-practice)
21
29
  --out <prefix> Write <prefix>.md / .json / .html (default: print Markdown to stdout)
@@ -63,6 +71,8 @@ function parseArgs(argv) {
63
71
  const next = () => argv[++i];
64
72
  switch (arg) {
65
73
  case '--base': opts.base = next(); break;
74
+ case '--serve': opts.serve = next(); break;
75
+ case '--serve-timeout': opts.serveTimeout = Number(next()); break;
66
76
  case '--route': opts.routes.push(next()); break;
67
77
  case '--tags': opts.tags = next().split(',').map((s) => s.trim()).filter(Boolean); break;
68
78
  case '--out': opts.out = next(); break;
@@ -88,6 +98,7 @@ function parseArgs(argv) {
88
98
  }
89
99
 
90
100
  const opts = parseArgs(process.argv.slice(2));
101
+ if (opts.serve && !opts.base) opts.base = 'http://localhost:4200';
91
102
 
92
103
  if (opts.help || !opts.base || opts.routes.length === 0) {
93
104
  process.stderr.write(USAGE);
@@ -129,19 +140,52 @@ if (opts.baseline) {
129
140
  }
130
141
  }
131
142
 
132
- const report = await scanPages({
133
- baseUrl: opts.base,
134
- routes: opts.routes,
135
- tags: opts.tags,
136
- waitMs: opts.wait,
137
- headed: opts.headed,
138
- frameworkPrefixes: opts.frameworkPrefixes,
139
- keyboard: opts.keyboard,
140
- focusTraps: opts.focusTraps,
141
- colorScheme: opts.colorScheme,
142
- darkClass: opts.darkClass,
143
- darkAttribute,
144
- });
143
+ if (opts.serveTimeout !== undefined && !(opts.serveTimeout > 0)) {
144
+ process.stderr.write('Invalid --serve-timeout (use a number of seconds, e.g. 300)\n');
145
+ process.exit(2);
146
+ }
147
+
148
+ let server;
149
+ if (opts.serve) {
150
+ process.stderr.write(`Starting dev server: ${opts.serve}\n`);
151
+ try {
152
+ server = await startDevServer({
153
+ command: opts.serve,
154
+ url: opts.base,
155
+ timeoutMs: opts.serveTimeout === undefined ? undefined : opts.serveTimeout * 1000,
156
+ });
157
+ } catch (err) {
158
+ process.stderr.write(`${err.message}\n`);
159
+ process.exit(2);
160
+ }
161
+ process.stderr.write(
162
+ server.reused
163
+ ? `${opts.base} is already serving; scanning that (nothing started).\n`
164
+ : `Dev server is up at ${opts.base}.\n`,
165
+ );
166
+ }
167
+
168
+ let report;
169
+ try {
170
+ report = await scanPages({
171
+ baseUrl: opts.base,
172
+ routes: opts.routes,
173
+ tags: opts.tags,
174
+ waitMs: opts.wait,
175
+ headed: opts.headed,
176
+ frameworkPrefixes: opts.frameworkPrefixes,
177
+ keyboard: opts.keyboard,
178
+ focusTraps: opts.focusTraps,
179
+ colorScheme: opts.colorScheme,
180
+ darkClass: opts.darkClass,
181
+ darkAttribute,
182
+ });
183
+ } finally {
184
+ if (server && !server.reused) {
185
+ await server.stop();
186
+ process.stderr.write('Stopped the dev server.\n');
187
+ }
188
+ }
145
189
 
146
190
  const allFindings = report.pages.flatMap((p) => p.findings);
147
191
  process.stderr.write(
@@ -2,3 +2,4 @@ export { scanPages, type ColorScheme, type ScanPagesOptions, type ThemeContext,
2
2
  export { groupByComponent, distinctRuleCount, toJson, toMarkdown, DARK_ONLY_NOTE, type PageReport, type ScanReport, } from './format.js';
3
3
  export { toHtml } from './html.js';
4
4
  export { diffAgainstBaseline, findingKey, findingsNotIn, parseBaseline, type BaselineDiff, type BaselineReport, type NewFinding, } from './baseline.js';
5
+ export { isServing, startDevServer, type DevServer, type DevServerOptions } from './serve.js';
@@ -2,3 +2,4 @@ export { scanPages, } from './headless.js';
2
2
  export { groupByComponent, distinctRuleCount, toJson, toMarkdown, DARK_ONLY_NOTE, } from './format.js';
3
3
  export { toHtml } from './html.js';
4
4
  export { diffAgainstBaseline, findingKey, findingsNotIn, parseBaseline, } from './baseline.js';
5
+ export { isServing, startDevServer } from './serve.js';
@@ -0,0 +1,33 @@
1
+ export interface DevServerOptions {
2
+ /** Shell command that starts the dev server, e.g. `npx ng serve admin --port 4300`. */
3
+ command: string;
4
+ /** URL to poll until the server answers, e.g. `http://localhost:4300`. */
5
+ url: string;
6
+ /** Give up if the server hasn't answered after this long (ms). Default 180000. */
7
+ timeoutMs?: number;
8
+ /**
9
+ * If something already answers at `url`, scan that and start nothing.
10
+ * Default true — handy locally when `ng serve` is already running.
11
+ */
12
+ reuseExisting?: boolean;
13
+ /** Working directory for the command. Default `process.cwd()`. */
14
+ cwd?: string;
15
+ /** Called with each line the command prints (stdout and stderr). */
16
+ onOutput?: (line: string) => void;
17
+ }
18
+ export interface DevServer {
19
+ /** True when an already-running server was reused and nothing was started. */
20
+ reused: boolean;
21
+ /** Stop the server (and everything it spawned). Safe to call more than once. */
22
+ stop(): Promise<void>;
23
+ }
24
+ /** True when something at `url` answers with a non-5xx response. */
25
+ export declare function isServing(url: string): Promise<boolean>;
26
+ /**
27
+ * Start a dev server and resolve once `url` answers — for report mode in CI,
28
+ * where nothing is running yet. Rejects (after stopping the process) if the
29
+ * command exits first or `timeoutMs` passes; the error includes the last lines
30
+ * of its output. Always `stop()` the result when the scan is done. Until then,
31
+ * SIGINT/SIGTERM stop the server before the process ends.
32
+ */
33
+ export declare function startDevServer(options: DevServerOptions): Promise<DevServer>;
@@ -0,0 +1,117 @@
1
+ import { spawn } from 'node:child_process';
2
+ /** Lines of dev-server output kept for the error message when it fails to start. */
3
+ const OUTPUT_TAIL = 30;
4
+ const POLL_MS = 500;
5
+ /** True when something at `url` answers with a non-5xx response. */
6
+ export async function isServing(url) {
7
+ try {
8
+ const res = await fetch(url, { signal: AbortSignal.timeout(2000), redirect: 'manual' });
9
+ await res.body?.cancel();
10
+ return res.status < 500;
11
+ }
12
+ catch {
13
+ return false;
14
+ }
15
+ }
16
+ /**
17
+ * Start a dev server and resolve once `url` answers — for report mode in CI,
18
+ * where nothing is running yet. Rejects (after stopping the process) if the
19
+ * command exits first or `timeoutMs` passes; the error includes the last lines
20
+ * of its output. Always `stop()` the result when the scan is done. Until then,
21
+ * SIGINT/SIGTERM stop the server before the process ends.
22
+ */
23
+ export async function startDevServer(options) {
24
+ const { command, url, timeoutMs = 180_000, reuseExisting = true } = options;
25
+ if (await isServing(url)) {
26
+ if (reuseExisting)
27
+ return { reused: true, stop: async () => { } };
28
+ throw new Error(`Something is already serving ${url}; stop it or use a different port.`);
29
+ }
30
+ // A process group of its own (POSIX), so stop() also ends what the shell spawned.
31
+ const child = spawn(command, {
32
+ cwd: options.cwd,
33
+ shell: true,
34
+ detached: process.platform !== 'win32',
35
+ stdio: ['ignore', 'pipe', 'pipe'],
36
+ });
37
+ const tail = [];
38
+ const collect = (chunk) => {
39
+ for (const line of chunk.toString().split(/\r?\n/)) {
40
+ if (!line.trim())
41
+ continue;
42
+ options.onOutput?.(line);
43
+ tail.push(line);
44
+ if (tail.length > OUTPUT_TAIL)
45
+ tail.shift();
46
+ }
47
+ };
48
+ child.stdout?.on('data', collect);
49
+ child.stderr?.on('data', collect);
50
+ let exitCode;
51
+ const exited = new Promise((done) => {
52
+ child.once('exit', (code, signal) => {
53
+ exitCode = code ?? (signal ? -1 : null);
54
+ done();
55
+ });
56
+ child.once('error', (err) => {
57
+ tail.push(err.message);
58
+ exitCode = -1;
59
+ done();
60
+ });
61
+ });
62
+ // The server is in its own process group, so Ctrl+C (or a cancelled CI job)
63
+ // doesn't reach it. Until stop(), pass those signals on, then re-raise them;
64
+ // if the process exits some other way, kill it synchronously.
65
+ const onSignal = (signal) => {
66
+ void stop().then(() => process.kill(process.pid, signal));
67
+ };
68
+ const onExit = () => killTree(child, 'SIGKILL');
69
+ process.once('SIGINT', onSignal);
70
+ process.once('SIGTERM', onSignal);
71
+ process.once('exit', onExit);
72
+ let stopped = false;
73
+ const stop = async () => {
74
+ if (stopped)
75
+ return;
76
+ stopped = true;
77
+ process.off('SIGINT', onSignal);
78
+ process.off('SIGTERM', onSignal);
79
+ process.off('exit', onExit);
80
+ if (exitCode === undefined) {
81
+ killTree(child, 'SIGTERM');
82
+ const forced = setTimeout(() => killTree(child, 'SIGKILL'), 5000);
83
+ await exited;
84
+ clearTimeout(forced);
85
+ }
86
+ };
87
+ const withOutput = (message) => new Error(tail.length ? `${message}\nLast output:\n ${tail.join('\n ')}` : message);
88
+ const deadline = Date.now() + timeoutMs;
89
+ while (true) {
90
+ if (exitCode !== undefined) {
91
+ await stop();
92
+ throw withOutput(`Dev server command exited (code ${exitCode}) before ${url} answered: ${command}`);
93
+ }
94
+ if (await isServing(url))
95
+ return { reused: false, stop };
96
+ if (Date.now() >= deadline) {
97
+ await stop();
98
+ throw withOutput(`Dev server didn't answer at ${url} within ${Math.round(timeoutMs / 1000)}s: ${command}`);
99
+ }
100
+ await Promise.race([exited, new Promise((r) => setTimeout(r, POLL_MS))]);
101
+ }
102
+ }
103
+ function killTree(child, signal) {
104
+ if (child.pid === undefined)
105
+ return;
106
+ try {
107
+ if (process.platform === 'win32') {
108
+ spawn('taskkill', ['/pid', String(child.pid), '/T', '/F'], { stdio: 'ignore' });
109
+ }
110
+ else {
111
+ process.kill(-child.pid, signal);
112
+ }
113
+ }
114
+ catch {
115
+ // Already gone.
116
+ }
117
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ngbracket/a11y-devtools",
3
- "version": "0.12.3",
3
+ "version": "0.13.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",