@ashishjain15491/tapcheck 0.0.0-stage → 0.1.1

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.
Files changed (47) hide show
  1. package/CHANGELOG.md +87 -0
  2. package/LICENSE +21 -0
  3. package/README.md +190 -2
  4. package/dist/auth.d.ts +5 -0
  5. package/dist/auth.js +100 -0
  6. package/dist/browser.d.ts +143 -0
  7. package/dist/browser.js +237 -0
  8. package/dist/cli.d.ts +2 -0
  9. package/dist/cli.js +321 -0
  10. package/dist/config.d.ts +169 -0
  11. package/dist/config.js +369 -0
  12. package/dist/coverage.d.ts +17 -0
  13. package/dist/coverage.js +56 -0
  14. package/dist/flow.d.ts +193 -0
  15. package/dist/flow.js +512 -0
  16. package/dist/jev.d.ts +48 -0
  17. package/dist/jev.js +89 -0
  18. package/dist/parts.d.ts +65 -0
  19. package/dist/parts.js +157 -0
  20. package/dist/questions.d.ts +66 -0
  21. package/dist/questions.js +203 -0
  22. package/dist/report.d.ts +29 -0
  23. package/dist/report.js +59 -0
  24. package/dist/routes.d.ts +18 -0
  25. package/dist/routes.js +54 -0
  26. package/dist/stub.d.ts +51 -0
  27. package/dist/stub.js +244 -0
  28. package/dist/suites/a11y.d.ts +3 -0
  29. package/dist/suites/a11y.js +73 -0
  30. package/dist/suites/audit.d.ts +2 -0
  31. package/dist/suites/audit.js +440 -0
  32. package/dist/suites/code.d.ts +10 -0
  33. package/dist/suites/code.js +48 -0
  34. package/dist/suites/contract.d.ts +5 -0
  35. package/dist/suites/contract.js +79 -0
  36. package/dist/suites/crawl.d.ts +2 -0
  37. package/dist/suites/crawl.js +135 -0
  38. package/dist/suites/interact.d.ts +2 -0
  39. package/dist/suites/interact.js +319 -0
  40. package/dist/suites/security.d.ts +12 -0
  41. package/dist/suites/security.js +134 -0
  42. package/dist/suites/usability.d.ts +3 -0
  43. package/dist/suites/usability.js +205 -0
  44. package/dist/suites/ux.d.ts +6 -0
  45. package/dist/suites/ux.js +183 -0
  46. package/package.json +61 -5
  47. package/schema/tapcheck.schema.json +368 -0
@@ -0,0 +1,169 @@
1
+ export type Screen = {
2
+ name: string;
3
+ path?: string;
4
+ from?: string;
5
+ link?: string;
6
+ suffix?: string;
7
+ purpose?: string;
8
+ };
9
+ export type Login = {
10
+ none: true;
11
+ } | {
12
+ manual: string;
13
+ } | {
14
+ form: {
15
+ url: string;
16
+ fields: Record<string, string>;
17
+ submit?: string;
18
+ totp?: {
19
+ field: string;
20
+ secret: string;
21
+ };
22
+ };
23
+ } | {
24
+ command: string;
25
+ };
26
+ /** A usability task: start at `from`, try to reach the screen `done` describes in about `optimal` clicks; `text` is what a person would type on the way. */
27
+ export type Task = {
28
+ name: string;
29
+ from: string;
30
+ goal: string;
31
+ done: string;
32
+ notDone: string;
33
+ optimal: number;
34
+ text?: string;
35
+ };
36
+ /** Every suite that runs once per side, in run order. */
37
+ export declare const SUITES: readonly ['crawl', 'contract', 'security', 'a11y', 'interact', 'audit', 'ux', 'usability'];
38
+ /** The suite names `changes` can key on: the suites, plus the side-less `code` part and the custom flows. A part name
39
+ * (a11y-customer, flow-checkout) is a key too; the CLI checks those once the flows are loaded. */
40
+ export declare const CHANGE_KEYS: string[];
41
+ /** A command from the project's own toolchain: exit 0 passes; `warn` makes a non-zero exit a warning. `timeout` in seconds. */
42
+ export type Gate = {
43
+ name: string;
44
+ run: string;
45
+ timeout: number;
46
+ warn: boolean;
47
+ };
48
+ /** One canned answer of the stub server (src/stub.ts). `path` is a glob, or a regular expression when it starts with ^. */
49
+ export type StubRule = {
50
+ host?: string;
51
+ method?: string;
52
+ path?: string;
53
+ status: number;
54
+ json?: unknown;
55
+ body?: string;
56
+ file?: string;
57
+ headers: Record<string, string>;
58
+ delayMs: number;
59
+ };
60
+ /** One answer of the stub's DNS server. An MX value is "<priority> <host>" or just the host (priority 10). */
61
+ export declare const DNS_TYPES: readonly ['A', 'AAAA', 'MX', 'TXT', 'CNAME', 'NS'];
62
+ export type DnsRecord = {
63
+ name: string;
64
+ type: (typeof DNS_TYPES)[number];
65
+ values: string[];
66
+ };
67
+ export type Csrf = {
68
+ method: string;
69
+ path: string;
70
+ expect: number;
71
+ };
72
+ /** `csrf`: this side's own CSRF probe, in place of security.csrf (another host often has other routes). */
73
+ export type Side = {
74
+ name: string;
75
+ baseUrl: string;
76
+ login: Login;
77
+ screens: Screen[];
78
+ tasks: Task[];
79
+ csrf?: Csrf;
80
+ };
81
+ export type Config = {
82
+ root: string;
83
+ baseUrl: string;
84
+ app: {
85
+ start?: string;
86
+ stop?: string;
87
+ reset?: string;
88
+ resetWhen: string[];
89
+ ready: string;
90
+ timeout: number;
91
+ allowRemoteReset: boolean;
92
+ };
93
+ sides: Side[];
94
+ loginPaths: RegExp;
95
+ crawl: {
96
+ max: number;
97
+ skip: RegExp;
98
+ };
99
+ interact: {
100
+ max: number;
101
+ submit: boolean;
102
+ };
103
+ audit: {
104
+ max: number;
105
+ skip?: RegExp;
106
+ };
107
+ design?: {
108
+ colors?: string[];
109
+ fonts?: string[];
110
+ radii?: number[];
111
+ spacing?: number[];
112
+ };
113
+ security: {
114
+ csrf?: Csrf;
115
+ allowedHosts: string[];
116
+ publicWrites?: RegExp;
117
+ };
118
+ viewports: {
119
+ name: string;
120
+ width: number;
121
+ height: number;
122
+ mobile: boolean;
123
+ }[];
124
+ out: string;
125
+ audience: string;
126
+ jev: {
127
+ budget: number;
128
+ headers: Record<string, string>;
129
+ };
130
+ i18n: {
131
+ keys?: string;
132
+ };
133
+ changes: Record<string, string[]>;
134
+ gates: Gate[];
135
+ routes?: string;
136
+ stub?: {
137
+ port: number;
138
+ rules: StubRule[];
139
+ dns?: {
140
+ port: number;
141
+ records: DnsRecord[];
142
+ defaultA?: string;
143
+ };
144
+ };
145
+ coverage: {
146
+ file: string;
147
+ reasons: {
148
+ match: RegExp;
149
+ why: string;
150
+ }[];
151
+ };
152
+ flows: string[];
153
+ parallel: number;
154
+ mail: {
155
+ mailpit?: string;
156
+ };
157
+ browser: {
158
+ args: string[];
159
+ };
160
+ };
161
+ /** Replaces $NAME and ${NAME} in every string with the environment's value; a missing variable is an error. */
162
+ export declare function expand(v: unknown, at?: string): any;
163
+ /** A record value as the stub can encode it: an address for A and AAAA, [priority] host for MX, any text otherwise. */
164
+ export declare const dnsValue: (type: string, x: unknown) => boolean;
165
+ /** Checks a parsed (and expanded) config object and fills in the defaults. `root` is the config file's folder. */
166
+ export declare function check(raw: any, root?: string): Config;
167
+ export declare function load(file?: string): Config;
168
+ /** Hosts a reset may run against without allowRemoteReset: this machine, *.localhost and *.test. */
169
+ export declare const isLocal: (u: string) => boolean;
package/dist/config.js ADDED
@@ -0,0 +1,369 @@
1
+ /*
2
+ * tapcheck.yml: load, fill in $VARS from the environment, check, and apply defaults. Every check names the field and
3
+ * says what it should be, so a wrong config fails before any browser starts.
4
+ */
5
+ import { existsSync, readFileSync } from 'node:fs';
6
+ import { isIPv4, isIPv6 } from 'node:net';
7
+ import { dirname, resolve } from 'node:path';
8
+ import { parse } from 'yaml';
9
+ /** Every suite that runs once per side, in run order. */
10
+ export const SUITES = ['crawl', 'contract', 'security', 'a11y', 'interact', 'audit', 'ux', 'usability'];
11
+ /** The suite names `changes` can key on: the suites, plus the side-less `code` part and the custom flows. A part name
12
+ * (a11y-customer, flow-checkout) is a key too; the CLI checks those once the flows are loaded. */
13
+ export const CHANGE_KEYS = [...SUITES, 'code', 'flow'];
14
+ /** One answer of the stub's DNS server. An MX value is "<priority> <host>" or just the host (priority 10). */
15
+ export const DNS_TYPES = ['A', 'AAAA', 'MX', 'TXT', 'CNAME', 'NS'];
16
+ const DEFAULT_SKIP = '/(logout|log-out|sign-?out|delete|destroy|remove|export|download|impersonat|unsubscribe)|\\.(csv|pdf|zip|png|jpe?g|gif|svg|webp|ico|xlsx?)$';
17
+ const DEFAULT_VIEWPORTS = [
18
+ { name: 'desktop', width: 1440, height: 900, mobile: false },
19
+ { name: 'mobile', width: 390, height: 844, mobile: true },
20
+ ];
21
+ /** Replaces $NAME and ${NAME} in every string with the environment's value; a missing variable is an error. */
22
+ export function expand(v, at = '') {
23
+ if (typeof v === 'string') {
24
+ return v.replace(/\$\{([A-Z_][A-Z0-9_]*)\}|\$([A-Z_][A-Z0-9_]*)/g, (_m, a, b) => {
25
+ const name = a ?? b;
26
+ if (process.env[name] === undefined)
27
+ throw new Error(`tapcheck.yml: ${at}: environment variable ${name} is not set`);
28
+ return process.env[name];
29
+ });
30
+ }
31
+ if (Array.isArray(v))
32
+ return v.map((x, i) => expand(x, `${at}[${i}]`));
33
+ if (v && typeof v === 'object')
34
+ return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, expand(x, at ? `${at}.${k}` : k)]));
35
+ return v;
36
+ }
37
+ function fail(field, want) {
38
+ throw new Error(`tapcheck.yml: ${field} ${want}`);
39
+ }
40
+ const str = (v, field, optional = false) => {
41
+ if (v === undefined && optional)
42
+ return undefined;
43
+ if (typeof v !== 'string' || !v.trim())
44
+ fail(field, 'must be a non-empty string');
45
+ return v;
46
+ };
47
+ const regex = (v, field, fallback) => {
48
+ const s = str(v ?? fallback, field);
49
+ try {
50
+ return new RegExp(s, 'i');
51
+ }
52
+ catch (e) {
53
+ fail(field, `is not a valid regular expression: ${e.message}`);
54
+ }
55
+ };
56
+ const url = (v, field) => {
57
+ const s = str(v, field);
58
+ if (!/^https?:\/\/[^/]+/.test(s))
59
+ fail(field, `must be an http(s) URL, got "${s}"`);
60
+ return s.replace(/\/$/, '');
61
+ };
62
+ function login(v, field) {
63
+ if (v === undefined || v === 'none')
64
+ return { none: true };
65
+ if (v === 'manual')
66
+ return { manual: '/login' };
67
+ if (!v || typeof v !== 'object')
68
+ fail(field, 'must be none, manual, or one of {manual: <path>}, {form: …}, {command: …}');
69
+ const o = v;
70
+ const keys = Object.keys(o);
71
+ if (keys.length !== 1)
72
+ fail(field, `must have exactly one of manual, form, command (got ${keys.join(', ') || 'none'})`);
73
+ if ('manual' in o)
74
+ return { manual: str(o.manual, `${field}.manual`) };
75
+ if ('command' in o)
76
+ return { command: str(o.command, `${field}.command`) };
77
+ if ('form' in o) {
78
+ const f = o.form ?? {};
79
+ if (!f.fields || typeof f.fields !== 'object' || !Object.keys(f.fields).length)
80
+ fail(`${field}.form.fields`, 'must map at least one field to its value');
81
+ for (const [k, x] of Object.entries(f.fields))
82
+ str(x, `${field}.form.fields.${k}`);
83
+ const totp = f.totp === undefined ? undefined : { field: str(f.totp.field, `${field}.form.totp.field`), secret: str(f.totp.secret, `${field}.form.totp.secret`) };
84
+ return { form: { url: str(f.url, `${field}.form.url`), fields: f.fields, submit: str(f.submit, `${field}.form.submit`, true), totp } };
85
+ }
86
+ fail(field, `has an unknown kind "${keys[0]}" (use manual, form or command)`);
87
+ }
88
+ function csrfOf(v, field) {
89
+ if (v === undefined)
90
+ return undefined;
91
+ if (!v || typeof v !== 'object')
92
+ fail(field, 'must be {method?, path, expect}');
93
+ if (!Number.isInteger(v.expect))
94
+ fail(`${field}.expect`, 'must be the HTTP status the app answers with (e.g. 403 or 419)');
95
+ return { method: (str(v.method ?? 'POST', `${field}.method`)).toUpperCase(), path: str(v.path, `${field}.path`), expect: v.expect };
96
+ }
97
+ function screens(v, field) {
98
+ if (v === undefined)
99
+ return [];
100
+ if (!Array.isArray(v))
101
+ fail(field, 'must be a list of screens');
102
+ return v.map((s, i) => {
103
+ const at = `${field}[${i}]`;
104
+ if (!s || typeof s !== 'object')
105
+ fail(at, 'must be {name, path} or {name, from, link}');
106
+ const name = str(s.name, `${at}.name`);
107
+ if (!s.path && !(s.from && s.link))
108
+ fail(at, 'needs a path, or from + link');
109
+ if (s.link)
110
+ regex(s.link, `${at}.link`, '');
111
+ return { name, path: str(s.path, `${at}.path`, true), from: str(s.from, `${at}.from`, true), link: str(s.link, `${at}.link`, true),
112
+ suffix: str(s.suffix, `${at}.suffix`, true), purpose: str(s.purpose, `${at}.purpose`, true) };
113
+ });
114
+ }
115
+ function tasks(v, field) {
116
+ if (v === undefined)
117
+ return [];
118
+ if (!Array.isArray(v))
119
+ fail(field, 'must be a list of tasks');
120
+ return v.map((t, i) => {
121
+ const at = `${field}[${i}]`;
122
+ if (!t || typeof t !== 'object')
123
+ fail(at, 'must be {name, from, goal, done, notDone, optimal}');
124
+ if (!Number.isInteger(t.optimal) || t.optimal < 1)
125
+ fail(`${at}.optimal`, 'must be the fewest clicks that reach the goal (a whole number above 0)');
126
+ return { name: str(t.name, `${at}.name`), from: str(t.from, `${at}.from`), goal: str(t.goal, `${at}.goal`), done: str(t.done, `${at}.done`),
127
+ notDone: str(t.notDone, `${at}.notDone`), optimal: t.optimal, text: str(t.text, `${at}.text`, true) };
128
+ });
129
+ }
130
+ function gates(v) {
131
+ if (v === undefined)
132
+ return [];
133
+ if (!Array.isArray(v))
134
+ fail('gates', 'must be a list of {name, run, timeout?, warn?}');
135
+ return v.map((g, i) => {
136
+ const at = `gates[${i}]`;
137
+ if (!g || typeof g !== 'object')
138
+ fail(at, 'must be {name, run, timeout?, warn?}');
139
+ const timeout = g.timeout ?? 600;
140
+ if (typeof timeout !== 'number' || timeout <= 0)
141
+ fail(`${at}.timeout`, 'must be a positive number of seconds');
142
+ return { name: str(g.name, `${at}.name`), run: str(g.run, `${at}.run`), timeout, warn: g.warn === true };
143
+ });
144
+ }
145
+ function stub(v, root) {
146
+ if (v === undefined)
147
+ return undefined;
148
+ if (!v || typeof v !== 'object' || Array.isArray(v))
149
+ fail('stub', 'must be {port?, rules?, dns?}');
150
+ const port = v.port ?? 8766;
151
+ if (!Number.isInteger(port) || port < 1 || port > 65535)
152
+ fail('stub.port', 'must be a port number (1–65535)');
153
+ if (v.rules !== undefined && !Array.isArray(v.rules))
154
+ fail('stub.rules', 'must be a list of {host?, method?, path?, status?, json? | body? | file?, headers?, delayMs?}');
155
+ const rules = (v.rules ?? []).map((r, i) => {
156
+ const at = `stub.rules[${i}]`;
157
+ if (!r || typeof r !== 'object')
158
+ fail(at, 'must be {host?, method?, path?, status?, json? | body? | file?, headers?, delayMs?}');
159
+ const status = r.status ?? 200, delayMs = r.delayMs ?? 0, headers = r.headers ?? {};
160
+ if (!Number.isInteger(status) || status < 100 || status > 599)
161
+ fail(`${at}.status`, 'must be an HTTP status (100–599)');
162
+ if (typeof delayMs !== 'number' || delayMs < 0)
163
+ fail(`${at}.delayMs`, 'must be a number of milliseconds, 0 or more');
164
+ if (typeof headers !== 'object' || Array.isArray(headers))
165
+ fail(`${at}.headers`, 'must map header names to values');
166
+ if (['json', 'body', 'file'].filter((k) => r[k] !== undefined).length > 1)
167
+ fail(at, 'takes one of json, body or file');
168
+ const path = str(r.path, `${at}.path`, true);
169
+ if (path?.startsWith('^'))
170
+ regex(path, `${at}.path`, '');
171
+ const file = str(r.file, `${at}.file`, true);
172
+ if (file && !existsSync(resolve(root, file)))
173
+ fail(`${at}.file`, `is not a file next to tapcheck.yml: ${file}`);
174
+ return { host: str(r.host, `${at}.host`, true)?.toLowerCase(), method: str(r.method, `${at}.method`, true)?.toUpperCase(), path, status, json: r.json,
175
+ body: r.body === undefined ? undefined : String(r.body), file, headers, delayMs };
176
+ });
177
+ return { port, rules, dns: dns(v.dns) };
178
+ }
179
+ /** A record value as the stub can encode it: an address for A and AAAA, [priority] host for MX, any text otherwise. */
180
+ export const dnsValue = (type, x) => typeof x === 'string' && !!x.trim()
181
+ && (type === 'A' ? isIPv4(x) : type === 'AAAA' ? isIPv6(x) && !x.includes('.') : type === 'MX' ? /^(\d+\s+)?\S+$/.test(x) : true);
182
+ function dns(v) {
183
+ if (v === undefined)
184
+ return undefined;
185
+ if (!v || typeof v !== 'object' || Array.isArray(v))
186
+ fail('stub.dns', 'must be {port?, records?, defaultA?}');
187
+ const port = v.port ?? 8767;
188
+ if (!Number.isInteger(port) || port < 1 || port > 65535)
189
+ fail('stub.dns.port', 'must be a port number (1–65535)');
190
+ if (v.records !== undefined && !Array.isArray(v.records))
191
+ fail('stub.dns.records', 'must be a list of {name, type, values}');
192
+ const records = (v.records ?? []).map((r, i) => {
193
+ const at = `stub.dns.records[${i}]`;
194
+ if (!r || typeof r !== 'object')
195
+ fail(at, 'must be {name, type, values}');
196
+ const type = String(r.type ?? '').toUpperCase();
197
+ if (!DNS_TYPES.includes(type))
198
+ fail(`${at}.type`, `must be one of ${DNS_TYPES.join(', ')}`);
199
+ if (!Array.isArray(r.values) || !r.values.length)
200
+ fail(`${at}.values`, 'must be a list with at least one value');
201
+ r.values.forEach((x, j) => dnsValue(type, x) || fail(`${at}.values[${j}]`, type === 'A' ? 'must be an IPv4 address' : type === 'AAAA' ? 'must be an IPv6 address (hex groups only)' : type === 'MX' ? 'must be a mail host, or "<priority> <host>"' : 'must be a non-empty string'));
202
+ return { name: str(r.name, `${at}.name`).toLowerCase().replace(/\.$/, ''), type, values: r.values };
203
+ });
204
+ if (v.defaultA !== undefined && !dnsValue('A', v.defaultA))
205
+ fail('stub.dns.defaultA', 'must be an IPv4 address');
206
+ return { port, records, defaultA: v.defaultA };
207
+ }
208
+ function coverage(v) {
209
+ if (v !== undefined && (!v || typeof v !== 'object' || Array.isArray(v)))
210
+ fail('coverage', 'must be {file?, reasons?}');
211
+ if (v?.reasons !== undefined && !Array.isArray(v.reasons))
212
+ fail('coverage.reasons', 'must be a list of {match, why}');
213
+ return { file: str(v?.file ?? 'COVERAGE.md', 'coverage.file'), reasons: (v?.reasons ?? []).map((r, i) => {
214
+ if (!r || typeof r !== 'object')
215
+ fail(`coverage.reasons[${i}]`, 'must be {match, why}');
216
+ return { match: regex(r.match, `coverage.reasons[${i}].match`, ''), why: str(r.why, `coverage.reasons[${i}].why`) };
217
+ }) };
218
+ }
219
+ function design(v) {
220
+ if (v === undefined)
221
+ return undefined;
222
+ if (!v || typeof v !== 'object' || Array.isArray(v))
223
+ fail('design', 'must be {colors?, fonts?, radii?, spacing?}');
224
+ const list = (key, ok, want) => {
225
+ if (v[key] === undefined)
226
+ return undefined;
227
+ if (!Array.isArray(v[key]))
228
+ fail(`design.${key}`, 'must be a list');
229
+ v[key].forEach((x, i) => ok(x) || fail(`design.${key}[${i}]`, want));
230
+ return v[key];
231
+ };
232
+ const px = (x) => typeof x === 'number' && x >= 0;
233
+ return { colors: list('colors', (x) => typeof x === 'string' && /^#([0-9a-f]{3}|[0-9a-f]{6})$/i.test(x), 'must be a hex colour in quotes, such as "#1f2937"'),
234
+ fonts: list('fonts', (x) => typeof x === 'string' && !!x.trim(), 'must be a font family name'),
235
+ radii: list('radii', px, 'must be a number of pixels, 0 or more'), spacing: list('spacing', px, 'must be a number of pixels, 0 or more') };
236
+ }
237
+ /** Checks a parsed (and expanded) config object and fills in the defaults. `root` is the config file's folder. */
238
+ export function check(raw, root = process.cwd()) {
239
+ if (!raw || typeof raw !== 'object')
240
+ fail('', 'must be a YAML mapping');
241
+ const baseUrl = url(raw.baseUrl, 'baseUrl');
242
+ const a = raw.app ?? {};
243
+ const timeout = a.timeout ?? 120;
244
+ if (typeof timeout !== 'number' || timeout <= 0)
245
+ fail('app.timeout', 'must be a positive number of seconds');
246
+ const resetWhen = a.resetWhen ?? [];
247
+ if (!Array.isArray(resetWhen))
248
+ fail('app.resetWhen', 'must be a list of globs, e.g. ["database/**"]');
249
+ resetWhen.forEach((g, i) => str(g, `app.resetWhen[${i}]`));
250
+ if (resetWhen.length && !a.reset)
251
+ fail('app.resetWhen', 'needs app.reset: the command it runs');
252
+ const app = { start: str(a.start, 'app.start', true), stop: str(a.stop, 'app.stop', true), reset: str(a.reset, 'app.reset', true), resetWhen,
253
+ ready: str(a.ready ?? '/', 'app.ready'), timeout, allowRemoteReset: a.allowRemoteReset === true };
254
+ // screens and tasks: a list (every side) or a map of side → list.
255
+ const byside = (key, side) => (Array.isArray(raw[key]) ? raw[key] : raw[key]?.[side]);
256
+ const at = (key, side) => (Array.isArray(raw[key]) ? key : `${key}.${side}`);
257
+ const sideDefs = raw.sides ?? { public: {} };
258
+ if (typeof sideDefs !== 'object' || Array.isArray(sideDefs) || !Object.keys(sideDefs).length)
259
+ fail('sides', 'must map each side name to {login, baseUrl?, csrf?}');
260
+ const sides = Object.entries(sideDefs).map(([name, s]) => {
261
+ if (!/^[a-z][a-z0-9-]*$/.test(name))
262
+ fail(`sides.${name}`, 'name must be lowercase letters, digits and dashes');
263
+ // Side names are tags too (ONLY=<side>), so they can't reuse a suite or kind tag.
264
+ if ([...CHANGE_KEYS, 'jev', 'measured'].includes(name))
265
+ fail(`sides.${name}`, `name can't be a suite or tag name (${[...CHANGE_KEYS, 'jev', 'measured'].join(', ')})`);
266
+ return { name, baseUrl: s?.baseUrl ? url(s.baseUrl, `sides.${name}.baseUrl`) : baseUrl, login: login(s?.login, `sides.${name}.login`), csrf: csrfOf(s?.csrf, `sides.${name}.csrf`),
267
+ screens: screens(byside('screens', name), at('screens', name)), tasks: tasks(byside('tasks', name), at('tasks', name)) };
268
+ });
269
+ for (const key of ['screens', 'tasks']) {
270
+ if (!raw[key] || Array.isArray(raw[key]))
271
+ continue;
272
+ if (typeof raw[key] !== 'object')
273
+ fail(key, `must be a list, or map each side to a list`);
274
+ for (const k of Object.keys(raw[key]))
275
+ if (!sides.some((s) => s.name === k))
276
+ fail(`${key}.${k}`, `names a side that isn't in sides (${sides.map((s) => s.name).join(', ')})`);
277
+ }
278
+ const c = raw.crawl ?? {};
279
+ const max = c.max ?? 60;
280
+ if (!Number.isInteger(max) || max < 1)
281
+ fail('crawl.max', 'must be a whole number above 0');
282
+ const it = raw.interact ?? {}, au = raw.audit ?? {};
283
+ if (typeof it !== 'object' || Array.isArray(it))
284
+ fail('interact', 'must be {max?, submit?}');
285
+ const interactMax = it.max ?? 40;
286
+ if (!Number.isInteger(interactMax) || interactMax < 1)
287
+ fail('interact.max', 'must be a whole number above 0');
288
+ if (it.submit !== undefined && typeof it.submit !== 'boolean')
289
+ fail('interact.submit', 'must be true or false');
290
+ if (typeof au !== 'object' || Array.isArray(au))
291
+ fail('audit', 'must be {max?, skip?}');
292
+ const auditMax = au.max ?? 0;
293
+ if (!Number.isInteger(auditMax) || auditMax < 0)
294
+ fail('audit.max', 'must be a whole number, 0 or more');
295
+ const s = raw.security ?? {};
296
+ const csrf = csrfOf(s.csrf, 'security.csrf');
297
+ const allowedHosts = s.allowedHosts ?? [];
298
+ if (!Array.isArray(allowedHosts))
299
+ fail('security.allowedHosts', 'must be a list of host names');
300
+ const viewports = raw.viewports ?? DEFAULT_VIEWPORTS;
301
+ if (!Array.isArray(viewports) || !viewports.length)
302
+ fail('viewports', 'must be a list of {name, width, height, mobile?}');
303
+ viewports.forEach((v, i) => {
304
+ if (!v?.name || !Number.isInteger(v.width) || !Number.isInteger(v.height))
305
+ fail(`viewports[${i}]`, 'needs name, width and height');
306
+ v.mobile = v.mobile === true;
307
+ });
308
+ const j = raw.jev ?? {};
309
+ if (typeof j !== 'object' || Array.isArray(j))
310
+ fail('jev', 'must be {budget?, headers?}');
311
+ const budget = process.env.JEV_BUDGET !== undefined ? Number(process.env.JEV_BUDGET) : j.budget ?? 1;
312
+ if (typeof budget !== 'number' || !(budget > 0))
313
+ fail(process.env.JEV_BUDGET !== undefined ? 'JEV_BUDGET (environment)' : 'jev.budget', 'must be a number of US dollars above 0');
314
+ const headers = j.headers ?? {};
315
+ if (typeof headers !== 'object' || Array.isArray(headers))
316
+ fail('jev.headers', 'must map header names to values');
317
+ for (const [k, x] of Object.entries(headers))
318
+ str(x, `jev.headers.${k}`);
319
+ if (raw.i18n !== undefined && (!raw.i18n || typeof raw.i18n !== 'object'))
320
+ fail('i18n', 'must be {keys: <command printing one translation key per line>}');
321
+ const changes = raw.changes ?? {};
322
+ if (!changes || typeof changes !== 'object' || Array.isArray(changes))
323
+ fail('changes', 'must map a suite name (or "*") to a list of globs');
324
+ for (const [k, globs] of Object.entries(changes)) {
325
+ if (k !== '*' && !CHANGE_KEYS.includes(k) && !(k.startsWith('flow-') || CHANGE_KEYS.some((x) => k.startsWith(`${x}-`)))) {
326
+ fail(`changes.${k}`, `names a suite that doesn't exist (use "*", a part name such as flow-<name> or a11y-<side>, or one of ${CHANGE_KEYS.join(', ')})`);
327
+ }
328
+ if (!Array.isArray(globs) || !globs.length)
329
+ fail(`changes.${k}`, 'must be a list of globs, e.g. ["src/**"]');
330
+ globs.forEach((g, i) => str(g, `changes.${k}[${i}]`));
331
+ }
332
+ const parallel = process.env.PARALLEL !== undefined && process.env.PARALLEL !== '' ? Number(process.env.PARALLEL) : raw.parallel ?? 1;
333
+ if (!Number.isInteger(parallel) || parallel < 1 || parallel > 32)
334
+ fail(process.env.PARALLEL ? 'PARALLEL (environment)' : 'parallel', 'must be a whole number from 1 to 32');
335
+ const flows = raw.flows === undefined ? [] : Array.isArray(raw.flows) ? raw.flows : [raw.flows];
336
+ flows.forEach((g, i) => str(g, Array.isArray(raw.flows) ? `flows[${i}]` : 'flows'));
337
+ if (raw.mail !== undefined && (!raw.mail || typeof raw.mail !== 'object'))
338
+ fail('mail', 'must be {mailpit: <the address of Mailpit\'s web page>}');
339
+ const args = raw.browser?.args ?? [];
340
+ if ((raw.browser !== undefined && (!raw.browser || typeof raw.browser !== 'object' || Array.isArray(raw.browser))) || !Array.isArray(args) || args.some((a) => typeof a !== 'string' || !a.startsWith('--')))
341
+ fail('browser', 'must be {args: ["--a-chromium-switch", …]}');
342
+ return { root, baseUrl, app, sides, changes, browser: { args }, gates: gates(raw.gates), routes: str(raw.routes, 'routes', true), stub: stub(raw.stub, root), coverage: coverage(raw.coverage), flows, parallel,
343
+ mail: { mailpit: raw.mail?.mailpit === undefined ? undefined : url(raw.mail.mailpit, 'mail.mailpit') }, audience: str(raw.audience ?? 'a first-time visitor', 'audience'), jev: { budget, headers },
344
+ i18n: { keys: str(raw.i18n?.keys, 'i18n.keys', true) }, loginPaths: regex(raw.loginPaths, 'loginPaths', '/(login|sign-?in|two-factor|2fa)(/|$)'),
345
+ crawl: { max, skip: regex(c.skip, 'crawl.skip', DEFAULT_SKIP) }, interact: { max: interactMax, submit: it.submit === true },
346
+ audit: { max: auditMax, skip: au.skip === undefined ? undefined : regex(au.skip, 'audit.skip', '') }, design: design(raw.design), security: { csrf, allowedHosts, publicWrites: s.publicWrites === undefined ? undefined : regex(s.publicWrites, 'security.publicWrites', '') }, viewports, out: str(raw.out ?? '.tapcheck', 'out') };
347
+ }
348
+ export function load(file = 'tapcheck.yml') {
349
+ if (!existsSync(file))
350
+ throw new Error(`No ${file} here. Write one (see examples/) or let the tapcheck-setup skill write it.`);
351
+ let raw;
352
+ try {
353
+ raw = parse(readFileSync(file, 'utf8'));
354
+ }
355
+ catch (e) {
356
+ throw new Error(`${file} is not valid YAML: ${e.message}`);
357
+ }
358
+ // The stub's address is known before anything starts, so tapcheck.yml itself can use $TAPCHECK_STUB_URL (in app.start, say).
359
+ if (raw?.stub)
360
+ process.env.TAPCHECK_STUB_URL = `http://127.0.0.1:${raw.stub.port ?? 8766}`;
361
+ if (raw?.stub?.dns)
362
+ process.env.TAPCHECK_DNS = `127.0.0.1:${raw.stub.dns.port ?? 8767}`; // the stub's DNS server, as host:port
363
+ return check(expand(raw), dirname(resolve(file)));
364
+ }
365
+ /** Hosts a reset may run against without allowRemoteReset: this machine, *.localhost and *.test. */
366
+ export const isLocal = (u) => {
367
+ const h = new URL(u).hostname;
368
+ return ['localhost', '127.0.0.1', '[::1]', '::1'].includes(h) || h.endsWith('.localhost') || h.endsWith('.test');
369
+ };
@@ -0,0 +1,17 @@
1
+ import type { Reach } from './browser.ts';
2
+ import type { Config } from './config.ts';
3
+ import { type Route } from './routes.ts';
4
+ /** The hits of every run under `out`, newest run first, and how many runs had any. */
5
+ export declare function hits(out: string): {
6
+ all: Reach[];
7
+ runs: number;
8
+ };
9
+ /** The coverage map as Markdown, and its counts. `reasons` are matched against "GET /path", "dialog <name>" and "table <headers>: <control>". */
10
+ export declare function coverage(all: Reach[], runs: number, routes: Route[], reasons: Config['coverage']['reasons']): {
11
+ md: string;
12
+ summary: string;
13
+ total: number;
14
+ covered: number;
15
+ excused: number;
16
+ gaps: string[];
17
+ };
@@ -0,0 +1,56 @@
1
+ /*
2
+ * The coverage map across runs (COVERAGE=1). Coverage is observed, not claimed: every run writes <side dir>/hits.json,
3
+ * what each part touched (every request the app answered, the dialogs and table controls interact exercised, and for a
4
+ * flow the step that did it). This merges the hits of every run folder under `out`, so parts run one at a time still
5
+ * add up, into one Markdown file: each route of the `routes` command with the parts that reached it, or GAP (with the
6
+ * reason, when `coverage.reasons` gives one), then the dialogs and table controls seen. Without a `routes` command there
7
+ * is nothing to measure against, so it lists what was reached.
8
+ */
9
+ import { existsSync, readdirSync, readFileSync } from 'node:fs';
10
+ import { matcher } from './routes.js';
11
+ /** The hits of every run under `out`, newest run first, and how many runs had any. */
12
+ export function hits(out) {
13
+ const runs = (existsSync(out) ? readdirSync(out) : []).filter((d) => d.startsWith('run-')).sort().reverse()
14
+ .map((d) => readdirSync(`${out}/${d}`, { withFileTypes: true }).filter((e) => e.isDirectory() && existsSync(`${out}/${d}/${e.name}/hits.json`))
15
+ .flatMap((e) => JSON.parse(readFileSync(`${out}/${d}/${e.name}/hits.json`, 'utf8'))))
16
+ .filter((h) => h.length);
17
+ return { all: runs.flat(), runs: runs.length };
18
+ }
19
+ /** The coverage map as Markdown, and its counts. `reasons` are matched against "GET /path", "dialog <name>" and "table <headers>: <control>". */
20
+ export function coverage(all, runs, routes, reasons) {
21
+ const cell = (s) => s.replace(/\|/g, '\\|').replace(/\s+/g, ' ');
22
+ const by = (ok) => [...new Set(all.filter((h) => ok(h.what)).map((h) => (h.step ? `${h.part}: ${h.step}` : h.part)))];
23
+ const who = (w) => cell(w.slice(0, 2).join(', ') + (w.length > 2 ? ` (+${w.length - 2})` : ''));
24
+ const kind = (prefix) => [...new Set(all.filter((h) => h.what.startsWith(prefix)).map((h) => h.what))].sort().map((what) => `| ${cell(what.slice(prefix.length))} | ${who(by((w) => w === what))} |`);
25
+ const out = [], gaps = [];
26
+ let covered = 0, excused = 0;
27
+ if (routes.length) {
28
+ out.push('## Routes', '', '| Route | Reached by |', '|---|---|');
29
+ for (const key of [...new Set(routes.map((r) => `${r.method} ${r.path}`))].sort((a, b) => a.split(' ')[1].localeCompare(b.split(' ')[1]) || a.localeCompare(b))) {
30
+ const [method, path] = key.split(' '), re = matcher(path);
31
+ const w = by((what) => what.startsWith(`${method} `) && re.test(what.slice(method.length + 1)));
32
+ const why = w.length ? undefined : reasons.find((r) => r.match.test(key))?.why;
33
+ if (w.length)
34
+ covered++;
35
+ else if (why)
36
+ excused++;
37
+ else
38
+ gaps.push(key);
39
+ out.push(`| \`${cell(key)}\` | ${w.length ? who(w) : why ? `GAP: ${cell(why)}` : '**GAP**'} |`);
40
+ }
41
+ }
42
+ else {
43
+ const reached = kind('').filter((row) => /^\| [A-Z]+ \//.test(row));
44
+ out.push('## Reached', '', 'tapcheck.yml has no `routes` command, so there is no route list to find gaps in. These requests were answered:', '', '| Request | Reached by |', '|---|---|', ...reached);
45
+ }
46
+ for (const [prefix, title, head] of [['dialog ', 'Dialogs', 'Dialog'], ['table ', 'Table controls', 'Table: control']]) {
47
+ const rows = kind(prefix);
48
+ if (rows.length)
49
+ out.push('', `## ${title}`, '', `| ${head} | Reached by |`, '|---|---|', ...rows);
50
+ }
51
+ const total = covered + excused + gaps.length;
52
+ const summary = routes.length ? `${total} routes: ${covered} reached, ${excused} left out on purpose, ${gaps.length} GAP` : `${new Set(all.map((h) => h.what)).size} things reached (no route list)`;
53
+ const md = ['# Coverage map', '', 'Written by `COVERAGE=1 tapcheck` from the hits.json of every run. Do not edit by hand: run more parts, then write it again.', '',
54
+ `**${summary}.** Runs merged: ${runs}.`, '', ...out, ''].join('\n');
55
+ return { md, summary, total, covered, excused, gaps };
56
+ }