fastqa-mcp 0.0.0-stage → 0.3.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.
package/dist/index.js ADDED
@@ -0,0 +1,267 @@
1
+ #!/usr/bin/env node
2
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
3
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
4
+ import { z } from 'zod';
5
+ import { Session } from './session.js';
6
+ import { runStep, bind, STEP_KINDS } from './runner.js';
7
+ import { saveFlow, loadFlow, listFlows, runSuite, exportFlow, FLOW_DIR } from './flows.js';
8
+ import { auditA11y, renderA11y } from './a11y.js';
9
+ import { promises as fs } from 'node:fs';
10
+ import path from 'node:path';
11
+ const VERSION = '0.3.1';
12
+ const session = new Session();
13
+ const text = (t) => ({ content: [{ type: 'text', text: t }] });
14
+ const stripHash = (u) => u.split('#')[0];
15
+ const MUTATING = /^(goto|click|dblclick|press|select|check|uncheck|fill|type)$/;
16
+ function evidenceSummary() {
17
+ const e = session.evidence;
18
+ const errs = e.pageErrors.length + e.console.filter((c) => c.startsWith('[error]')).length;
19
+ const parts = [];
20
+ if (errs)
21
+ parts.push(`${errs} JS error(s)`);
22
+ if (e.failedRequests.length)
23
+ parts.push(`${e.failedRequests.length} failed request(s)`);
24
+ return parts.length ? `\n⚠ ${parts.join(', ')} so far — call evidence for details` : '';
25
+ }
26
+ const server = new McpServer({ name: 'fastqa', version: VERSION });
27
+ server.registerTool('open', {
28
+ description: 'Open a URL in the QA browser and return a compact snapshot: one line per element, e.g. `e4 textbox "Email" [required]`. Shadow DOM content is inlined; iframes appear as indented `frame "…"` blocks. ' +
29
+ 'Refs (eN) can be used as targets in act. Starts recording a new tape for flow save.',
30
+ inputSchema: {
31
+ url: z.string().describe('URL to open'),
32
+ fresh: z.boolean().optional().describe('New isolated context (clears cookies/storage). Default false.'),
33
+ device: z.string().optional().describe('Emulate a device, e.g. "iPhone 13", "Pixel 7", "iPad Mini". "" = back to desktop.'),
34
+ },
35
+ }, async ({ url, fresh, device }) => {
36
+ const page = await session.ensure(!!fresh, device);
37
+ session.mark = Date.now();
38
+ const t0 = Date.now();
39
+ const r = await runStep(session, { do: 'goto', value: url });
40
+ session.tape = r.recorded ? [r.recorded] : [];
41
+ if (!r.ok)
42
+ return text(r.line);
43
+ await session.settle();
44
+ const snap = await session.snapshot();
45
+ session.lastLines = snap.items.map((i) => i.line);
46
+ return text(`${Session.render(snap)}\n(${Date.now() - t0}ms)${evidenceSummary()}`);
47
+ });
48
+ const StepSchema = z.object({
49
+ do: z.enum(STEP_KINDS),
50
+ target: z.string().optional().describe('ref "e5", visible text/label like "Log in" or "Email", or a selector: "#id", "css=..", "testid=..". expect_request: "POST /api/orders" or "/regex/". expect_no_errors: optional text to ignore.'),
51
+ value: z.string().optional().describe('text to fill, key to press, option to select, url, expected text/url (use /regex/ for regex). {{name}} reads env FASTQA_VAR_name so secrets never pass through the model. expect_request: status "200"/"2xx"/"<400". expect_no_errors: "strict" also fails on 4xx. expect_accessible: lowest failing impact, default "serious".'),
52
+ timeout: z.number().optional().describe('ms, default 5000'),
53
+ frame: z.string().optional().describe('only search inside this iframe (title, name, id or src fragment). Usually not needed: targets are searched in the page, shadow DOM and all iframes.'),
54
+ });
55
+ server.registerTool('act', {
56
+ description: 'Run MANY steps in ONE call (fill a whole form, submit, assert) — this is what makes fastqa fast. ' +
57
+ 'Targets resolve by ref, label, placeholder, role+name or text — also inside open shadow DOM and iframes — so you usually do not need a snapshot first. ' +
58
+ 'Stops at the first failing step and then returns a full snapshot so you can recover. ' +
59
+ 'Otherwise returns only what changed on the page (+ added / - removed lines). ' +
60
+ 'expect_* steps are QA assertions that poll until they pass or time out. expect_request checks an API call happened with the right status, ' +
61
+ 'expect_no_errors fails on JS errors / 5xx since the batch started, expect_accessible runs a WCAG check.',
62
+ inputSchema: {
63
+ steps: z.array(StepSchema).min(1).max(50),
64
+ snapshot: z.enum(['diff', 'full', 'none']).optional().describe('What to return after the steps. Default diff.'),
65
+ },
66
+ }, async ({ steps, snapshot = 'diff' }) => {
67
+ if (!session.page)
68
+ return text('No page open. Call open first.');
69
+ const t0 = Date.now();
70
+ const out = [];
71
+ let failed = false;
72
+ const urlBefore = session.page.url();
73
+ session.mark = Date.now();
74
+ for (const step of steps) {
75
+ const r = await runStep(session, bind(step, {}), step);
76
+ out.push(r.line);
77
+ if (!r.ok) {
78
+ failed = true;
79
+ break;
80
+ }
81
+ if (r.recorded)
82
+ session.tape.push(r.recorded);
83
+ if (MUTATING.test(step.do) && step.do !== 'fill' && step.do !== 'type')
84
+ await session.settle(1500);
85
+ }
86
+ await session.settle(1500);
87
+ const snap = await session.snapshot();
88
+ const lines = snap.items.map((i) => i.line);
89
+ let tail = '';
90
+ if (failed) {
91
+ let shot = '';
92
+ try {
93
+ const f = path.join(FLOW_DIR(), 'artifacts', `fail-${Date.now()}.jpg`);
94
+ await fs.mkdir(path.dirname(f), { recursive: true });
95
+ await session.page.screenshot({ path: f, type: 'jpeg', quality: 60 });
96
+ shot = `\nscreenshot saved: ${f}`;
97
+ }
98
+ catch { /* ignore */ }
99
+ tail = shot + '\n--- page now ---\n' + Session.render(snap);
100
+ }
101
+ else if (snapshot === 'full') {
102
+ tail = '\n--- page now ---\n' + Session.render(snap);
103
+ }
104
+ else if (snapshot === 'diff' && stripHash(snap.url) !== stripHash(urlBefore)) {
105
+ tail = '\n--- navigated, new page ---\n' + Session.render(snap); // a diff across pages is noise
106
+ }
107
+ else if (snapshot === 'diff') {
108
+ const { added, removed } = session.diff(lines);
109
+ const urlLine = `url: ${snap.url}`;
110
+ tail = '\n--- changes ---\n' + urlLine + '\n' +
111
+ (added.length || removed.length
112
+ ? [...removed.slice(0, 60).map((l) => '- ' + l), ...added.slice(0, 120).map((l) => '+ ' + l)].join('\n')
113
+ : '(no visible changes)');
114
+ }
115
+ session.lastLines = lines;
116
+ const head = failed
117
+ ? `FAILED at step ${out.length}/${steps.length} after ${Date.now() - t0}ms`
118
+ : `PASSED ${steps.length}/${steps.length} steps in ${Date.now() - t0}ms`;
119
+ return text(`${head}\n${out.join('\n')}${tail}${evidenceSummary()}`);
120
+ });
121
+ server.registerTool('snapshot', {
122
+ description: 'Compact page snapshot. mode=interactive (default): controls, headings, alerts. mode=full: also visible text. root=css to scope to part of the page.',
123
+ inputSchema: {
124
+ mode: z.enum(['interactive', 'full']).optional(),
125
+ root: z.string().optional(),
126
+ },
127
+ }, async ({ mode = 'interactive', root }) => {
128
+ if (!session.page)
129
+ return text('No page open. Call open first.');
130
+ const snap = await session.snapshot(mode, root);
131
+ if (!root && mode === 'interactive')
132
+ session.lastLines = snap.items.map((i) => i.line);
133
+ return text(Session.render(snap));
134
+ });
135
+ server.registerTool('screenshot', {
136
+ description: 'JPEG screenshot. Only use when layout/visuals matter — text snapshots are much cheaper.',
137
+ inputSchema: {
138
+ target: z.string().optional().describe('element to capture (ref/text/selector)'),
139
+ full_page: z.boolean().optional(),
140
+ },
141
+ }, async ({ target, full_page }) => {
142
+ if (!session.page)
143
+ return text('No page open. Call open first.');
144
+ const buf = target
145
+ ? await (await session.resolve(target, 'any')).loc.screenshot({ type: 'jpeg', quality: 60 })
146
+ : await session.page.screenshot({ type: 'jpeg', quality: 60, fullPage: !!full_page });
147
+ return { content: [{ type: 'image', data: buf.toString('base64'), mimeType: 'image/jpeg' }] };
148
+ });
149
+ server.registerTool('audit', {
150
+ description: 'Accessibility check (axe-core, WCAG 2.1 A/AA) of the current page and its iframes. Returns violations grouped by impact.',
151
+ inputSchema: {},
152
+ }, async () => {
153
+ if (!session.page)
154
+ return text('No page open. Call open first.');
155
+ const issues = await auditA11y(session.page, (f) => f.name() || f.url().split('?')[0]);
156
+ return text(renderA11y(issues));
157
+ });
158
+ server.registerTool('evidence', {
159
+ description: 'JS errors, console errors/warnings and failed HTTP requests (>=400) collected since the last call. Use for bug reports.',
160
+ inputSchema: {},
161
+ }, async () => {
162
+ const e = session.takeEvidence();
163
+ const sec = (h, a) => `${h} (${a.length})${a.length ? '\n ' + a.join('\n ') : ''}`;
164
+ return text([sec('page errors', e.pageErrors), sec('console', e.console), sec('failed requests', e.failedRequests)].join('\n'));
165
+ });
166
+ server.registerTool('flow', {
167
+ description: 'Record & replay without the model. start: begin a new recording tape. save: store the steps recorded since open/start as a named flow. ' +
168
+ 'run: replay a flow (or "*" for all) in an isolated context, no LLM calls, returns pass/fail per step. ' +
169
+ 'list / show: inspect flows. export: write a Playwright Test .spec.ts.',
170
+ inputSchema: {
171
+ action: z.enum(['start', 'save', 'run', 'list', 'show', 'export']),
172
+ name: z.string().optional(),
173
+ vars: z.record(z.string()).optional().describe('values for {{placeholders}} when running'),
174
+ dataset: z.string().optional().describe('run: CSV file (or name in .fastqa/data/) — the flow runs once per row, columns fill {{placeholders}}'),
175
+ },
176
+ }, async ({ action, name, vars, dataset }) => {
177
+ switch (action) {
178
+ case 'start': {
179
+ session.tape = session.page ? [{ do: 'goto', value: session.page.url(), code: `await page.goto(${JSON.stringify(session.page.url())});` }] : [];
180
+ return text(`Recording from ${session.page?.url() ?? '(no page)'}`);
181
+ }
182
+ case 'save': {
183
+ if (!name)
184
+ return text('name is required');
185
+ if (!session.tape.length)
186
+ return text('Nothing recorded yet.');
187
+ const p = await saveFlow(name, session.tape);
188
+ return text(`Saved ${session.tape.length} steps to ${p}`);
189
+ }
190
+ case 'list': {
191
+ const all = await listFlows();
192
+ return text(all.length ? all.join('\n') : 'No flows saved yet.');
193
+ }
194
+ case 'show': {
195
+ if (!name)
196
+ return text('name is required');
197
+ const f = await loadFlow(name);
198
+ return text(f.steps.map((s, i) => `${i + 1}. ${s.do}${s.target ? ' ' + JSON.stringify(s.target) : ''}${s.value !== undefined ? ' ' + JSON.stringify(s.value) : ''}${Array.isArray(s.frame) && s.frame.length ? ' @ ' + s.frame.join(' >> ') : ''}`).join('\n'));
199
+ }
200
+ case 'run': {
201
+ if (!name)
202
+ return text('name is required ("*" runs all)');
203
+ await session.ensure();
204
+ const names = name === '*' ? await listFlows() : [name];
205
+ const { runs, html, junit } = await runSuite(names, vars ?? {}, dataset, session);
206
+ const passed = runs.filter((r) => r.ok).length;
207
+ const report = runs.map((r) => `${r.ok ? 'PASS' : 'FAIL'} ${r.name} (${r.ms}ms)` + (r.ok ? '' : '\n' + r.lines.map((l) => ' ' + l).join('\n')) +
208
+ (r.shotFile ? `\n screenshot: ${r.shotFile}` : '') +
209
+ (r.evidence.length ? '\n evidence: ' + r.evidence.slice(0, 5).join(' | ') : ''));
210
+ return text(`${passed}/${runs.length} flows passed\n${report.join('\n')}\nreport: ${html}\njunit: ${junit}`);
211
+ }
212
+ case 'export': {
213
+ if (!name)
214
+ return text('name is required');
215
+ const { file, code } = await exportFlow(name);
216
+ return text(`Wrote ${file}\n\n${code}`);
217
+ }
218
+ }
219
+ });
220
+ server.registerTool('close', { description: 'Close the browser.', inputSchema: {} }, async () => {
221
+ await session.close();
222
+ return text('closed');
223
+ });
224
+ // ---- CLI: `fastqa-mcp run <flow|*>` replays flows with no model (for CI) ----
225
+ async function cli(args) {
226
+ const name = args[1] ?? '*';
227
+ const vars = {};
228
+ let dataset;
229
+ for (const a of args.slice(2)) {
230
+ const m = /^--var=(\w+)=(.*)$/.exec(a);
231
+ if (m)
232
+ vars[m[1]] = m[2];
233
+ const d = /^--data=(.+)$/.exec(a);
234
+ if (d)
235
+ dataset = d[1];
236
+ }
237
+ const names = name === '*' ? await listFlows() : [name];
238
+ if (!names.length) {
239
+ console.log('No flows found in ' + FLOW_DIR());
240
+ process.exit(2);
241
+ }
242
+ const { runs, html, junit } = await runSuite(names, vars, dataset);
243
+ for (const r of runs) {
244
+ console.log(`${r.ok ? 'PASS' : 'FAIL'} ${r.name} (${r.ms}ms)`);
245
+ if (!r.ok)
246
+ r.lines.forEach((l) => console.log(' ' + l));
247
+ r.evidence.slice(0, 5).forEach((e) => console.log(' evidence: ' + e));
248
+ }
249
+ const failed = runs.filter((r) => !r.ok).length;
250
+ console.log(`${runs.length - failed}/${runs.length} passed\nreport: ${html}\njunit: ${junit}`);
251
+ process.exit(failed ? 1 : 0);
252
+ }
253
+ const argv = process.argv.slice(2);
254
+ if (argv[0] === 'run') {
255
+ cli(argv).catch((e) => { console.error(e); process.exit(2); });
256
+ }
257
+ else if (argv[0] === '--version') {
258
+ console.log(VERSION);
259
+ }
260
+ else {
261
+ const transport = new StdioServerTransport();
262
+ await server.connect(transport);
263
+ const shutdown = async () => { await session.close(); process.exit(0); };
264
+ process.on('SIGINT', shutdown);
265
+ process.on('SIGTERM', shutdown);
266
+ process.stdin.on('close', shutdown);
267
+ }
package/dist/report.js ADDED
@@ -0,0 +1,48 @@
1
+ import { promises as fs } from 'node:fs';
2
+ import path from 'node:path';
3
+ const esc = (s) => s.replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
4
+ /** Writes reports/<stamp>.html (open in a browser) and reports/<stamp>.junit.xml (Jenkins "Publish JUnit test result report"). */
5
+ export async function writeReports(runs, dir) {
6
+ const stamp = new Date().toISOString().replace(/[:.]/g, '-');
7
+ const out = path.join(dir, 'reports');
8
+ await fs.mkdir(out, { recursive: true });
9
+ const passed = runs.filter((r) => r.ok).length;
10
+ const total = runs.reduce((a, r) => a + r.ms, 0);
11
+ const cards = runs.map((r) => `
12
+ <details class="run ${r.ok ? 'pass' : 'fail'}" ${r.ok ? '' : 'open'}>
13
+ <summary><b>${r.ok ? 'PASS' : 'FAIL'}</b> ${esc(r.name)} <span class="ms">${r.ms} ms</span></summary>
14
+ <ol>${r.lines.map((l) => `<li class="${l.includes('✗') ? 'bad' : ''}">${esc(l.replace(/^\s*\d+\.\s*/, ''))}</li>`).join('')}</ol>
15
+ ${r.evidence.length ? `<h4>Evidence</h4><ul class="ev">${r.evidence.map((e) => `<li>${esc(e)}</li>`).join('')}</ul>` : ''}
16
+ ${r.url ? `<p class="ms">Page at failure: ${esc(r.url)}</p>` : ''}
17
+ ${r.screenshot ? `<img alt="screenshot at failure" src="data:image/jpeg;base64,${r.screenshot}">` : ''}
18
+ </details>`).join('\n');
19
+ const html = `<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
20
+ <title>fastqa report — ${passed}/${runs.length} passed</title>
21
+ <style>
22
+ body{font:15px/1.5 system-ui,sans-serif;max-width:980px;margin:24px auto;padding:0 16px;color:#1d1d1f}
23
+ h1{font-size:22px;margin-bottom:4px}.sum{color:#555;margin-bottom:20px}
24
+ .bar{height:10px;border-radius:5px;background:#e33;overflow:hidden;margin:8px 0 20px}.bar i{display:block;height:100%;background:#2a2}
25
+ .run{border:1px solid #ddd;border-radius:10px;margin:10px 0;padding:8px 14px}.run.pass summary b{color:#1a7f37}.run.fail{border-color:#e33}.run.fail summary b{color:#c00}
26
+ summary{cursor:pointer}.ms{color:#777;font-size:13px}li.bad{color:#c00;font-weight:600}.ev li{font-family:ui-monospace,monospace;font-size:12px}
27
+ img{max-width:100%;border:1px solid #ccc;border-radius:6px;margin-top:8px}
28
+ </style></head><body>
29
+ <h1>fastqa test report</h1>
30
+ <div class="sum">${passed} of ${runs.length} passed · ${(total / 1000).toFixed(1)} s · ${new Date().toLocaleString()}</div>
31
+ <div class="bar"><i style="width:${runs.length ? (100 * passed) / runs.length : 0}%"></i></div>
32
+ ${cards}
33
+ </body></html>`;
34
+ const junit = `<?xml version="1.0" encoding="UTF-8"?>
35
+ <testsuite name="fastqa" tests="${runs.length}" failures="${runs.length - passed}" time="${(total / 1000).toFixed(3)}" timestamp="${new Date().toISOString()}">
36
+ ${runs.map((r) => ` <testcase classname="fastqa.flows" name="${esc(r.name)}" time="${(r.ms / 1000).toFixed(3)}">${r.ok ? '' : `
37
+ <failure message="${esc((r.lines.find((l) => l.includes('✗')) ?? 'failed').trim())}">${esc([...r.lines, ...r.evidence.map((e) => 'evidence: ' + e), r.shotFile ? 'screenshot: ' + r.shotFile : ''].join('\n'))}</failure>
38
+ `}</testcase>`).join('\n')}
39
+ </testsuite>
40
+ `;
41
+ const html_p = path.join(out, `${stamp}.html`);
42
+ const junit_p = path.join(out, `${stamp}.junit.xml`);
43
+ await fs.writeFile(html_p, html);
44
+ await fs.writeFile(junit_p, junit);
45
+ await fs.copyFile(html_p, path.join(out, 'latest.html'));
46
+ await fs.copyFile(junit_p, path.join(out, 'latest.junit.xml'));
47
+ return { html: html_p, junit: junit_p };
48
+ }
package/dist/runner.js ADDED
@@ -0,0 +1,289 @@
1
+ import { auditA11y } from './a11y.js';
2
+ import { Session, DEFAULT_TIMEOUT, sleep } from './session.js';
3
+ export const STEP_KINDS = [
4
+ 'goto', 'click', 'dblclick', 'hover', 'fill', 'type', 'press', 'select', 'check', 'uncheck', 'wait',
5
+ 'expect_text', 'expect_no_text', 'expect_url', 'expect_title', 'expect_value',
6
+ 'expect_visible', 'expect_hidden', 'expect_enabled', 'expect_disabled', 'expect_count',
7
+ 'expect_request', 'expect_no_errors', 'expect_accessible',
8
+ ];
9
+ const q = JSON.stringify;
10
+ async function poll(check, timeout, interval = 50) {
11
+ const end = Date.now() + timeout;
12
+ do {
13
+ try {
14
+ if (await check())
15
+ return true;
16
+ }
17
+ catch { /* retry */ }
18
+ await sleep(interval);
19
+ } while (Date.now() < end);
20
+ return false;
21
+ }
22
+ function matches(actual, expected) {
23
+ const m = /^\/(.+)\/([dgimsuy]*)$/.exec(expected); // "/api/login" is a path, "/api.*login/i" is a regex
24
+ if (m) {
25
+ try {
26
+ return new RegExp(m[1], m[2]).test(actual);
27
+ }
28
+ catch { /* not a valid regex: substring */ }
29
+ }
30
+ return actual.includes(expected);
31
+ }
32
+ function need(s, field) {
33
+ if (s[field] === undefined || s[field] === '')
34
+ throw new Error(`"${s.do}" needs "${field}"`);
35
+ return s[field];
36
+ }
37
+ export async function runStep(session, s, tmpl) {
38
+ // V(): how a value appears in exported code. Templated values ({{x}}) become env lookups, never literals.
39
+ const V = (bound) => (tmpl?.value && /\{\{\w+\}\}/.test(tmpl.value) ? envLiteral(tmpl.value) : q(bound));
40
+ const page = session.page;
41
+ const t0 = Date.now();
42
+ const timeout = s.timeout ?? DEFAULT_TIMEOUT;
43
+ const L = tmpl ?? s; // label uses the template so secrets bound from env never echo back to the model
44
+ const label = `${L.do}${L.target ? ' ' + q(L.target) : ''}${L.value !== undefined && L.do !== 'fill' && L.do !== 'type' ? ' ' + q(L.value) : L.value !== undefined ? ' ' + q(maskish(L)) : ''}`;
45
+ let recorded = { ...s };
46
+ try {
47
+ switch (s.do) {
48
+ case 'goto': {
49
+ const url = need(s, 'value');
50
+ await page.goto(url, { waitUntil: 'domcontentloaded', timeout: Math.max(timeout, 15000) });
51
+ recorded.code = `await page.goto(${q(url)});`;
52
+ break;
53
+ }
54
+ case 'click':
55
+ case 'dblclick':
56
+ case 'hover':
57
+ case 'check':
58
+ case 'uncheck': {
59
+ const r = await session.resolve(need(s, 'target'), 'click', timeout, s.frame);
60
+ if (s.do === 'click')
61
+ await r.loc.click({ timeout });
62
+ if (s.do === 'dblclick')
63
+ await r.loc.dblclick({ timeout });
64
+ if (s.do === 'hover')
65
+ await r.loc.hover({ timeout });
66
+ if (s.do === 'check')
67
+ await r.loc.check({ timeout });
68
+ if (s.do === 'uncheck')
69
+ await r.loc.uncheck({ timeout });
70
+ recorded = { ...s, target: r.record, frame: r.frame, code: `await ${r.code}.${s.do}();` };
71
+ break;
72
+ }
73
+ case 'fill':
74
+ case 'type':
75
+ case 'select': {
76
+ const value = s.value ?? '';
77
+ const r = await session.resolve(need(s, 'target'), 'fill', timeout, s.frame);
78
+ if (s.do === 'fill')
79
+ await r.loc.fill(value, { timeout });
80
+ if (s.do === 'type') {
81
+ await r.loc.click({ timeout });
82
+ await r.loc.pressSequentially(value, { delay: 10 });
83
+ }
84
+ if (s.do === 'select') {
85
+ try {
86
+ await r.loc.selectOption({ label: value }, { timeout: Math.min(timeout, 1500) });
87
+ }
88
+ catch {
89
+ await r.loc.selectOption(value, { timeout });
90
+ }
91
+ }
92
+ const method = s.do === 'select' ? 'selectOption' : s.do === 'type' ? 'pressSequentially' : 'fill';
93
+ recorded = { ...s, target: r.record, frame: r.frame, code: `await ${r.code}.${method}(${V(value)});` };
94
+ break;
95
+ }
96
+ case 'press': {
97
+ const key = need(s, 'value');
98
+ if (s.target) {
99
+ const r = await session.resolve(s.target, 'fill', timeout, s.frame);
100
+ await r.loc.press(key, { timeout });
101
+ recorded = { ...s, target: r.record, frame: r.frame, code: `await ${r.code}.press(${q(key)});` };
102
+ }
103
+ else {
104
+ await page.keyboard.press(key);
105
+ recorded.code = `await page.keyboard.press(${q(key)});`;
106
+ }
107
+ break;
108
+ }
109
+ case 'wait': {
110
+ if (s.target) {
111
+ const r = await session.resolve(s.target, 'any', timeout, s.frame);
112
+ await r.loc.waitFor({ state: 'visible', timeout });
113
+ recorded = { ...s, target: r.record, frame: r.frame, code: `await ${r.code}.waitFor();` };
114
+ }
115
+ else {
116
+ const ms = Math.min(Number(s.value || 500), 10000);
117
+ await sleep(ms);
118
+ recorded.code = `await page.waitForTimeout(${ms});`;
119
+ }
120
+ break;
121
+ }
122
+ case 'expect_text':
123
+ case 'expect_no_text': {
124
+ const text = need(s, 'value');
125
+ const want = s.do === 'expect_text';
126
+ let hitChain;
127
+ let sample = '';
128
+ const ok = await poll(async () => {
129
+ if (s.target) {
130
+ const r = await session.resolve(s.target, 'any', 500, s.frame);
131
+ sample = await r.loc.innerText({ timeout: 500 });
132
+ hitChain = r.frame;
133
+ return matches(sample, text) === want;
134
+ }
135
+ // whole page: main document + open shadow roots + every visible iframe
136
+ const texts = await session.deepTexts();
137
+ const frameFilter = s.frame ? new Set((await session.scopesFor(s.frame)).map((c) => c.join(' >> '))) : null;
138
+ const pool = frameFilter ? texts.filter((x) => frameFilter.has(x.chain.join(' >> '))) : texts;
139
+ sample = pool.map((x) => x.text).join(' | ');
140
+ const hit = pool.find((x) => matches(x.text, text));
141
+ hitChain = hit?.chain.length ? hit.chain : undefined;
142
+ return !!hit === want;
143
+ }, timeout);
144
+ if (!ok)
145
+ throw new Error(want ? `text ${q(text)} not found. Visible text starts: ${q(sample.slice(0, 300))}` : `text ${q(text)} is still present`);
146
+ const sc = Session.codePrefix(hitChain);
147
+ const tx = regexOrString(text);
148
+ recorded = { ...s, frame: hitChain ?? (Array.isArray(s.frame) ? s.frame : undefined) };
149
+ recorded.code = want
150
+ ? `await expect(${sc}.getByText(${tx}).first()).toBeVisible();`
151
+ : `await expect(${sc}.getByText(${tx})).toHaveCount(0);`;
152
+ break;
153
+ }
154
+ case 'expect_url': {
155
+ const v = need(s, 'value');
156
+ if (!(await poll(async () => matches(page.url(), v), timeout)))
157
+ throw new Error(`url is ${q(page.url())}, expected ${q(v)}`);
158
+ recorded.code = `await expect(page).toHaveURL(${isRe(v) ? v : 'new RegExp(' + q(escapeRe(v)) + ')'});`;
159
+ break;
160
+ }
161
+ case 'expect_title': {
162
+ const v = need(s, 'value');
163
+ if (!(await poll(async () => matches(await page.title(), v), timeout)))
164
+ throw new Error(`title is ${q(await page.title())}`);
165
+ recorded.code = `await expect(page).toHaveTitle(${isRe(v) ? v : 'new RegExp(' + q(escapeRe(v)) + ')'});`;
166
+ break;
167
+ }
168
+ case 'expect_value': {
169
+ const v = s.value ?? '';
170
+ const r = await session.resolve(need(s, 'target'), 'fill', timeout, s.frame);
171
+ let actual = '';
172
+ const ok = await poll(async () => { actual = await r.loc.inputValue({ timeout: 300 }); return matches(actual, v) || (v === '' && actual === ''); }, timeout);
173
+ if (!ok)
174
+ throw new Error(`value is ${q(actual)}, expected ${q(v)}`);
175
+ recorded = { ...s, target: r.record, frame: r.frame, code: `await expect(${r.code}).toHaveValue(${regexOrString(v)});` };
176
+ break;
177
+ }
178
+ case 'expect_visible':
179
+ case 'expect_enabled':
180
+ case 'expect_disabled': {
181
+ const r = await session.resolve(need(s, 'target'), 'any', timeout, s.frame);
182
+ if (s.do === 'expect_enabled' && !(await poll(() => r.loc.isEnabled(), timeout)))
183
+ throw new Error('element is disabled');
184
+ if (s.do === 'expect_disabled' && !(await poll(() => r.loc.isDisabled(), timeout)))
185
+ throw new Error('element is enabled');
186
+ const m = s.do === 'expect_visible' ? 'toBeVisible' : s.do === 'expect_enabled' ? 'toBeEnabled' : 'toBeDisabled';
187
+ recorded = { ...s, target: r.record, frame: r.frame, code: `await expect(${r.code}).${m}();` };
188
+ break;
189
+ }
190
+ case 'expect_hidden': {
191
+ const target = need(s, 'target');
192
+ const ok = await poll(async () => {
193
+ try {
194
+ const r = await session.resolve(target, 'any', 1, s.frame);
195
+ return !(await r.loc.isVisible());
196
+ }
197
+ catch {
198
+ return true;
199
+ }
200
+ }, timeout);
201
+ if (!ok)
202
+ throw new Error('element is still visible');
203
+ recorded.code = `// expect hidden: ${target}`;
204
+ break;
205
+ }
206
+ case 'expect_count': {
207
+ const sel = need(s, 'target');
208
+ const n = Number(need(s, 'value'));
209
+ const loc = page.locator(sel.replace(/^css=/, ''));
210
+ let c = -1;
211
+ if (!(await poll(async () => (c = await loc.count()) === n, timeout)))
212
+ throw new Error(`count is ${c}, expected ${n}`);
213
+ recorded.code = `await expect(page.locator(${q(sel.replace(/^css=/, ''))})).toHaveCount(${n});`;
214
+ break;
215
+ }
216
+ case 'expect_request': {
217
+ // target: "POST /api/orders" | "/api/orders" | "/regex/"; value: "200" | "2xx" | "<400" (default: < 400)
218
+ const spec = need(s, 'target').trim();
219
+ const m = /^(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)\s+(.+)$/i.exec(spec);
220
+ const method = m?.[1].toUpperCase();
221
+ const urlPart = m ? m[2] : spec;
222
+ const want = (s.value || '<400').trim();
223
+ const okStatus = (st) => /^\dxx$/i.test(want) ? Math.floor(st / 100) === Number(want[0]) :
224
+ /^<\d+$/.test(want) ? st > 0 && st < Number(want.slice(1)) :
225
+ st === Number(want);
226
+ let seen = [];
227
+ const ok = await poll(async () => {
228
+ const hits = session.since(session.mark).filter((e) => e.kind === 'http' && (!method || e.method === method) && matches(e.url, urlPart));
229
+ seen = hits.map((h) => `${h.status || 'FAILED'} ${h.method} ${h.url}`);
230
+ return hits.some((h) => okStatus(h.status));
231
+ }, timeout);
232
+ if (!ok)
233
+ throw new Error(seen.length ? `request seen but status not ${want}: ${seen.slice(-3).join(' ; ')}` : `no ${method ?? ''} request matching ${q(urlPart)} since this run started`);
234
+ recorded.code = `// expect_request ${spec} ${want} — checked by fastqa (wrap the triggering action in page.waitForResponse for a native assertion)`;
235
+ break;
236
+ }
237
+ case 'expect_no_errors': {
238
+ // JS exceptions, console.error, network failures and HTTP 5xx since this run started. value "strict" also counts 4xx.
239
+ const strict = /strict/i.test(s.value || '');
240
+ const ignore = s.target ? s.target : undefined;
241
+ const bad = session.since(session.mark).filter((e) => (e.kind !== 'http' || e.status === 0 || e.status >= (strict ? 400 : 500)) && !(ignore && matches(e.text, ignore)));
242
+ if (bad.length)
243
+ throw new Error(`${bad.length} error(s): ` + bad.slice(0, 4).map((e) => `${e.kind}: ${e.text.slice(0, 120)}`).join(' ; '));
244
+ recorded.code = `// expect_no_errors${strict ? ' strict' : ''} — checked by fastqa`;
245
+ break;
246
+ }
247
+ case 'expect_accessible': {
248
+ // value: lowest impact that fails the step: critical | serious (default) | moderate | minor
249
+ const levels = ['critical', 'serious', 'moderate', 'minor'];
250
+ const lim = levels.indexOf((s.value || 'serious').toLowerCase());
251
+ const issues = (await auditA11y(page, () => 'iframe')).filter((i) => levels.indexOf(i.impact) <= (lim < 0 ? 1 : lim));
252
+ if (issues.length)
253
+ throw new Error(`${issues.length} accessibility rule(s) violated: ` + issues.slice(0, 4).map((i) => `[${i.impact}] ${i.id} ×${i.count}`).join(', ') + ' — call audit for details');
254
+ recorded.code = `// expect_accessible ${s.value || 'serious'} — checked by fastqa (axe-core)`;
255
+ break;
256
+ }
257
+ default:
258
+ throw new Error(`Unknown step "${s.do}". Valid: ${STEP_KINDS.join(', ')}`);
259
+ }
260
+ if (recorded && tmpl?.value !== undefined)
261
+ recorded.value = tmpl.value;
262
+ return { ok: true, ms: Date.now() - t0, line: `✓ ${label} (${Date.now() - t0}ms)`, recorded };
263
+ }
264
+ catch (e) {
265
+ const msg = String(e?.message || e).split('\n')[0].replace(/^locator\.\w+: /, '');
266
+ return { ok: false, ms: Date.now() - t0, line: `✗ ${label} — ${msg}` };
267
+ }
268
+ }
269
+ function maskish(s) {
270
+ return /pass|pwd|secret|token/i.test(s.target || '') ? '•••' : s.value;
271
+ }
272
+ function envLiteral(t) {
273
+ return '`' + t.replace(/`/g, '\\`').replace(/\{\{(\w+)\}\}/g, (_, k) => '${process.env.FASTQA_VAR_' + k + ' ?? ""}') + '`';
274
+ }
275
+ const isRe = (v) => { const m = /^\/(.+)\/([dgimsuy]*)$/.exec(v); if (!m)
276
+ return false; try {
277
+ new RegExp(m[1], m[2]);
278
+ return true;
279
+ }
280
+ catch {
281
+ return false;
282
+ } };
283
+ function escapeRe(s) { return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); }
284
+ function regexOrString(v) { return isRe(v) ? v : q(v); }
285
+ /** Replace {{var}} placeholders. */
286
+ export function bind(step, vars) {
287
+ const sub = (x) => x?.replace(/\{\{(\w+)\}\}/g, (_, k) => (k in vars ? vars[k] : process.env[`FASTQA_VAR_${k}`] ?? `{{${k}}}`));
288
+ return { ...step, target: sub(step.target), value: sub(step.value) };
289
+ }