sniff-qa 0.5.1 → 0.6.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 (33) hide show
  1. package/.claude-plugin/plugin.json +2 -2
  2. package/CHANGELOG.md +66 -0
  3. package/README.md +219 -347
  4. package/SECURITY.md +3 -3
  5. package/dist/chunk-LJYT4MD5.js +1246 -0
  6. package/dist/chunk-LJYT4MD5.js.map +1 -0
  7. package/dist/cli/index.js +41 -12
  8. package/dist/cli/index.js.map +1 -1
  9. package/dist/crawl-666NLYDC.js +11 -0
  10. package/dist/crawl-666NLYDC.js.map +1 -0
  11. package/dist/crawl-command-3OB4IUBU.js +54 -0
  12. package/dist/crawl-command-3OB4IUBU.js.map +1 -0
  13. package/dist/{discover-ENPRVN5A.js → discover-Q363YJ5X.js} +2 -2
  14. package/dist/{domain-UQ34YE4B.js → domain-NNL2PPRK.js} +1 -1
  15. package/dist/index.d.ts +94 -1
  16. package/dist/index.js +9 -1
  17. package/dist/index.js.map +1 -1
  18. package/dist/mcp/server.js +76 -6
  19. package/dist/mcp/server.js.map +1 -1
  20. package/dist/{model-X5J2JR5U.js → model-2DTSAX7T.js} +1 -1
  21. package/dist/{quality-run-6SXCN5CD.js → quality-run-LLBZZI7X.js} +2 -2
  22. package/dist/{repo-analyzer-4OURSITY.js → repo-analyzer-WK5WP7NT.js} +1 -1
  23. package/dist/{report-OAHSB56I.js → report-IKRVVIW4.js} +2 -2
  24. package/dist/{unified-SKXQQX3Y.js → unified-67Z6YA64.js} +4 -4
  25. package/package.json +3 -2
  26. package/skills/sniff/SKILL.md +20 -25
  27. /package/dist/{discover-ENPRVN5A.js.map → discover-Q363YJ5X.js.map} +0 -0
  28. /package/dist/{domain-UQ34YE4B.js.map → domain-NNL2PPRK.js.map} +0 -0
  29. /package/dist/{model-X5J2JR5U.js.map → model-2DTSAX7T.js.map} +0 -0
  30. /package/dist/{quality-run-6SXCN5CD.js.map → quality-run-LLBZZI7X.js.map} +0 -0
  31. /package/dist/{repo-analyzer-4OURSITY.js.map → repo-analyzer-WK5WP7NT.js.map} +0 -0
  32. /package/dist/{report-OAHSB56I.js.map → report-IKRVVIW4.js.map} +0 -0
  33. /package/dist/{unified-SKXQQX3Y.js.map → unified-67Z6YA64.js.map} +0 -0
@@ -0,0 +1,1246 @@
1
+ // src/crawl/engine.ts
2
+ import { join } from "path";
3
+ import { mkdir } from "fs/promises";
4
+
5
+ // src/crawl/noise.ts
6
+ function normalizeUrl(raw) {
7
+ try {
8
+ const u = new URL(raw);
9
+ u.hash = "";
10
+ u.hostname = u.hostname.toLowerCase();
11
+ let s = u.toString();
12
+ s = s.replace(/\/(?=$|\?)/, (m, off) => u.pathname === "/" ? m : "");
13
+ return s.replace(/\/$/, (m) => u.pathname === "/" ? m : "");
14
+ } catch {
15
+ return raw;
16
+ }
17
+ }
18
+ function sameOrigin(url, baseOrigin) {
19
+ try {
20
+ return new URL(url).origin === baseOrigin;
21
+ } catch {
22
+ return false;
23
+ }
24
+ }
25
+ var THIRD_PARTY_HOST = /(google-analytics|googletagmanager|doubleclick|google\.com\/(ads|pagead)|segment\.(io|com)|sentry\.io|hotjar|posthog|datadoghq|mixpanel|amplitude|fullstory|intercom|facebook\.(com|net)|connect\.facebook|fonts\.(googleapis|gstatic)|gstatic\.com|cloudflareinsights|newrelic|nr-data|bugsnag|launchdarkly|stripe\.com\/v\d)/i;
26
+ var PLUMBING_PATH = /(\/favicon\.ico|\.map(\?|$)|\/robots\.txt|\/sitemap\.xml|\/_next\/static\/.*\.js\.map|\/__nextjs|\/_next\/webpack-hmr|\/@vite\/|\/__vite_ping|\/@react-refresh|\/sockjs-node|\/_nuxt\/|\/__webpack_hmr|hot-update\.json|\/\.well-known\/)/i;
27
+ var ASSET_EXT = /\.(png|jpe?g|gif|svg|webp|avif|ico|css|js|mjs|woff2?|ttf|eot|map|json|webmanifest|mp4|webm|wasm)(\?|$)/i;
28
+ function isIgnorableRequest(url) {
29
+ return THIRD_PARTY_HOST.test(url) || PLUMBING_PATH.test(url);
30
+ }
31
+ function isExpectedAuthStatus(status) {
32
+ return status === 401 || status === 403;
33
+ }
34
+ function isEngineInducedFailure(errorText) {
35
+ if (!errorText) return false;
36
+ return /ERR_ABORTED|net::ERR_BLOCKED_BY_CLIENT|context (or browser )?(was )?closed|Target closed|frame was detached/i.test(
37
+ errorText
38
+ );
39
+ }
40
+ var CONSOLE_NOISE = /(Download the React DevTools|\[vite\]|\[HMR\]|\[webpack|Lighthouse|DevTools failed to load|source ?map|React Router Future Flag|was preloaded using link preload but not used|Slow network is detected|Tracking Prevention|net::ERR_|favicon|Failed to load resource)/i;
41
+ function isConsoleNoise(text) {
42
+ return CONSOLE_NOISE.test(text);
43
+ }
44
+ var PLACEHOLDER_PATTERNS = [
45
+ { id: "lorem", re: /\blorem ipsum\b/i, label: "Lorem ipsum placeholder text" },
46
+ { id: "todo", re: /\b(TODO|FIXME|TBD|XXX)\b[:\s]/, label: "TODO/FIXME placeholder note" },
47
+ { id: "test-email", re: /\b(test@test\.com|test@example\.com|user@example\.com|admin@admin\.com|foo@bar\.com)\b/i, label: "Test/placeholder email address" },
48
+ { id: "example-email", re: /\b[a-z0-9._%+-]+@example\.(com|org|net)\b/i, label: "example.com placeholder email" },
49
+ { id: "placeholder-phone", re: /\b(123[-.\s]?456[-.\s]?7890|555[-.\s]?555[-.\s]?5555|000[-.\s]?000[-.\s]?0000)\b/, label: "Placeholder phone number" },
50
+ { id: "lipsum-name", re: /\b(John Doe|Jane Doe|Lorem Ipsum)\b/, label: "Placeholder name" },
51
+ { id: "dummy", re: /\b(dummy (text|data|content)|placeholder (text|content)|your text here|insert .* here)\b/i, label: "Dummy/placeholder content" }
52
+ ];
53
+
54
+ // src/crawl/evidence.ts
55
+ var PageEvidence = class {
56
+ consoleErrors = [];
57
+ pageErrors = [];
58
+ /** Filtered HTTP>=400 responses (favicons/analytics/HMR removed). */
59
+ networkFailures = [];
60
+ /** Filtered request failures (engine-induced aborts removed). */
61
+ failedRequests = [];
62
+ /** All responses (used by detectors to reason about first-party fetches). */
63
+ responses = [];
64
+ baseOrigin;
65
+ attached = false;
66
+ constructor(baseOrigin) {
67
+ this.baseOrigin = baseOrigin;
68
+ }
69
+ attach(page) {
70
+ if (this.attached) return;
71
+ this.attached = true;
72
+ page.on("console", (msg) => {
73
+ if (msg.type() !== "error") return;
74
+ const text = msg.text();
75
+ if (isConsoleNoise(text)) return;
76
+ this.consoleErrors.push({ text, location: msg.location()?.url || page.url() });
77
+ });
78
+ page.on("pageerror", (err) => {
79
+ if (isConsoleNoise(err.message)) return;
80
+ this.pageErrors.push({ message: err.message, ...err.stack ? { stack: err.stack } : {} });
81
+ });
82
+ page.on("response", (res) => {
83
+ const url = res.url();
84
+ const status = res.status();
85
+ const ev = {
86
+ url,
87
+ status,
88
+ method: res.request().method(),
89
+ resourceType: res.request().resourceType(),
90
+ firstParty: sameOrigin(url, this.baseOrigin),
91
+ expectedAuth: isExpectedAuthStatus(status)
92
+ };
93
+ this.responses.push(ev);
94
+ if (status >= 400 && !isIgnorableRequest(url) && !ev.expectedAuth) {
95
+ this.networkFailures.push(ev);
96
+ }
97
+ });
98
+ page.on("requestfailed", (req) => {
99
+ const errorText = req.failure()?.errorText ?? "unknown error";
100
+ const url = req.url();
101
+ if (isEngineInducedFailure(errorText) || isIgnorableRequest(url)) return;
102
+ this.failedRequests.push({
103
+ url,
104
+ method: req.method(),
105
+ resourceType: req.resourceType(),
106
+ errorText,
107
+ firstParty: sameOrigin(url, this.baseOrigin)
108
+ });
109
+ });
110
+ }
111
+ reset() {
112
+ this.consoleErrors = [];
113
+ this.pageErrors = [];
114
+ this.networkFailures = [];
115
+ this.failedRequests = [];
116
+ this.responses = [];
117
+ }
118
+ /** First-party non-2xx XHR/fetch responses — the "failed API call" signal. */
119
+ firstPartyApiFailures() {
120
+ return this.networkFailures.filter(
121
+ (e) => e.firstParty && (e.resourceType === "xhr" || e.resourceType === "fetch")
122
+ );
123
+ }
124
+ consoleExcerpt(limit = 5) {
125
+ return [
126
+ ...this.pageErrors.map((e) => `Uncaught: ${e.message}`),
127
+ ...this.consoleErrors.map((e) => `console.error: ${e.text}`)
128
+ ].slice(0, limit);
129
+ }
130
+ networkExcerpt(limit = 5) {
131
+ return [
132
+ ...this.networkFailures.map((e) => `${e.method} ${e.url} -> ${e.status}`),
133
+ ...this.failedRequests.map((e) => `${e.method} ${e.url} -> FAILED (${e.errorText})`)
134
+ ].slice(0, limit);
135
+ }
136
+ };
137
+
138
+ // src/crawl/crawler.ts
139
+ async function extractLinks(page, baseOrigin) {
140
+ const hrefs = await page.evaluate(
141
+ () => Array.from(document.querySelectorAll("a[href]")).map((a) => a.href).filter(Boolean)
142
+ ).catch(() => []);
143
+ const internal = /* @__PURE__ */ new Set();
144
+ const external = /* @__PURE__ */ new Set();
145
+ for (const raw of hrefs) {
146
+ if (/^(mailto:|tel:|javascript:|#)/i.test(raw)) continue;
147
+ let abs;
148
+ try {
149
+ abs = new URL(raw, page.url()).toString();
150
+ } catch {
151
+ continue;
152
+ }
153
+ if (!/^https?:/i.test(abs)) continue;
154
+ const norm = normalizeUrl(abs);
155
+ if (sameOrigin(abs, baseOrigin)) internal.add(norm);
156
+ else external.add(norm);
157
+ }
158
+ return { internal: [...internal], external: [...external] };
159
+ }
160
+ function isCrawlable(url, baseOrigin) {
161
+ if (!sameOrigin(url, baseOrigin)) return false;
162
+ try {
163
+ const path = new URL(url).pathname;
164
+ if (ASSET_EXT.test(path)) return false;
165
+ if (path.startsWith("/api/")) return false;
166
+ } catch {
167
+ return false;
168
+ }
169
+ return true;
170
+ }
171
+ async function checkLinks(request, links, opts = { timeout: 1e4 }) {
172
+ const findings = [];
173
+ const seen = /* @__PURE__ */ new Set();
174
+ for (const link of links) {
175
+ if (seen.has(link.url)) continue;
176
+ seen.add(link.url);
177
+ let status = 0;
178
+ let errored = false;
179
+ let errText = "";
180
+ try {
181
+ const res = link.external ? await request.fetch(link.url, { method: "HEAD", timeout: opts.timeout, maxRedirects: 5 }) : await request.get(link.url, { timeout: opts.timeout, maxRedirects: 5 });
182
+ status = res.status();
183
+ if (link.external && status >= 400 && status !== 404) {
184
+ try {
185
+ const res2 = await request.get(link.url, { timeout: opts.timeout, maxRedirects: 5 });
186
+ status = res2.status();
187
+ } catch {
188
+ }
189
+ }
190
+ } catch (e) {
191
+ errored = true;
192
+ errText = e instanceof Error ? e.message : String(e);
193
+ }
194
+ if (errored || status >= 400) {
195
+ const detail = errored ? `request failed (${errText.split("\n")[0]})` : `HTTP ${status}`;
196
+ findings.push({
197
+ ruleId: link.external ? "links/broken-external" : "links/broken-internal",
198
+ issueClass: 2,
199
+ title: `Broken ${link.external ? "external" : "internal"} link: ${link.url} (${detail})`,
200
+ severity: link.external ? "medium" : "high",
201
+ confidence: "confirmed",
202
+ steps: [`On ${link.sourceRoute}, the link to ${link.url} ${errored ? "does not resolve" : `returns ${detail}`}`],
203
+ networkExcerpt: [`${link.url} -> ${errored ? "FAILED: " + errText.split("\n")[0] : status}`],
204
+ suggestedFix: link.external ? "Update or remove the dead external link." : "Fix the href or add the missing route; this internal link leads nowhere.",
205
+ dedupeKey: `link:${link.url}`
206
+ });
207
+ }
208
+ }
209
+ return findings;
210
+ }
211
+
212
+ // src/crawl/detectors/page-health.ts
213
+ var STACK_TRACE_RE = /(\bat\s+\w[\w.]*\s*\(.*:\d+:\d+\)|Cannot read propert(y|ies) of (undefined|null)|\bTypeError:|\bReferenceError:|Unhandled (Runtime )?Error|Application error: a (server|client)-side exception|Internal Server Error|Traceback \(most recent call last\))/;
214
+ var pageHealthDetector = async (ctx) => {
215
+ const findings = [];
216
+ if (ctx.navStatus !== null && ctx.navStatus >= 400) {
217
+ const isServer = ctx.navStatus >= 500;
218
+ findings.push({
219
+ ruleId: "route/broken-page",
220
+ issueClass: 1,
221
+ title: `Page returns HTTP ${ctx.navStatus}`,
222
+ severity: isServer ? "critical" : "high",
223
+ confidence: "confirmed",
224
+ steps: [`Navigate to ${ctx.route}`, `Server responded with HTTP ${ctx.navStatus}`],
225
+ suggestedFix: isServer ? "The route throws server-side. Check the server logs/handler for this path and return a valid page or a proper error page." : "The route is not found. Fix the link that points here, add the missing route, or return a helpful 404 page."
226
+ });
227
+ }
228
+ const dom = await ctx.page.evaluate(() => {
229
+ const body = document.body;
230
+ const text = (body?.innerText || "").trim();
231
+ const main = document.querySelector('main, [role="main"], #root, #app, #__next');
232
+ const mainText = (main?.textContent || "").trim();
233
+ const interactive = document.querySelectorAll('a[href], button, input, select, textarea, [role="button"]').length;
234
+ return { textLen: text.length, sample: text.slice(0, 400), mainText: mainText.length, interactive };
235
+ }).catch(() => null);
236
+ if (dom && (ctx.navStatus === null || ctx.navStatus < 400)) {
237
+ if (STACK_TRACE_RE.test(dom.sample)) {
238
+ findings.push({
239
+ ruleId: "route/crash-screen",
240
+ issueClass: 1,
241
+ title: "Raw error / stack trace shown to the user",
242
+ severity: "high",
243
+ confidence: "confirmed",
244
+ steps: [`Navigate to ${ctx.route}`, "The page renders a raw stack trace / crash screen"],
245
+ suggestedFix: "Catch the error and render a friendly error state; never expose stack traces to users.",
246
+ dedupeKey: "crash"
247
+ });
248
+ } else if (dom.textLen < 12 && dom.interactive === 0) {
249
+ findings.push({
250
+ ruleId: "route/blank-render",
251
+ issueClass: 1,
252
+ title: "Page renders blank (no visible content or controls)",
253
+ severity: "high",
254
+ confidence: "likely",
255
+ steps: [`Navigate to ${ctx.route}`, "The page loaded (HTTP 2xx) but rendered no visible content"],
256
+ suggestedFix: "A 200 response rendered an empty document \u2014 likely a client-side render crash or missing data. Check the console for errors and verify the page mounts.",
257
+ dedupeKey: "blank"
258
+ });
259
+ }
260
+ }
261
+ return findings;
262
+ };
263
+
264
+ // src/crawl/detectors/runtime-errors.ts
265
+ var runtimeErrorDetector = async (ctx) => {
266
+ const findings = [];
267
+ const { evidence } = ctx;
268
+ const seenExc = /* @__PURE__ */ new Set();
269
+ for (const err of evidence.pageErrors) {
270
+ const key = err.message.slice(0, 120);
271
+ if (seenExc.has(key)) continue;
272
+ seenExc.add(key);
273
+ findings.push({
274
+ ruleId: "js/uncaught-exception",
275
+ issueClass: 3,
276
+ title: `Uncaught exception: ${err.message.slice(0, 100)}`,
277
+ severity: "high",
278
+ confidence: "confirmed",
279
+ steps: [`Navigate to ${ctx.route}`, `An uncaught exception was thrown: ${err.message}`],
280
+ consoleExcerpt: [err.stack ? err.stack.split("\n").slice(0, 4).join("\n") : err.message],
281
+ suggestedFix: "Fix the thrown error; an uncaught exception can halt the rest of the page script (other features silently stop working).",
282
+ dedupeKey: key
283
+ });
284
+ }
285
+ const seenCon = /* @__PURE__ */ new Set();
286
+ for (const c of evidence.consoleErrors) {
287
+ const key = c.text.slice(0, 120);
288
+ if (seenCon.has(key)) continue;
289
+ seenCon.add(key);
290
+ findings.push({
291
+ ruleId: "console/error",
292
+ issueClass: 3,
293
+ title: `Console error: ${c.text.slice(0, 100)}`,
294
+ severity: "medium",
295
+ confidence: "likely",
296
+ steps: [`Navigate to ${ctx.route}`, `console.error logged: ${c.text}`],
297
+ consoleExcerpt: [c.text],
298
+ suggestedFix: "Investigate the logged error; console errors often mark a feature that failed silently.",
299
+ dedupeKey: key
300
+ });
301
+ }
302
+ const seenNet = /* @__PURE__ */ new Set();
303
+ for (const ev of evidence.firstPartyApiFailures()) {
304
+ const key = `${ev.method} ${ev.url}`;
305
+ if (seenNet.has(key)) continue;
306
+ seenNet.add(key);
307
+ const isServer = ev.status >= 500;
308
+ findings.push({
309
+ ruleId: "network/failed-request",
310
+ issueClass: 3,
311
+ title: `Failed request: ${ev.method} ${shortPath(ev.url)} \u2192 ${ev.status}`,
312
+ severity: isServer ? "high" : "medium",
313
+ confidence: "confirmed",
314
+ steps: [`Navigate to ${ctx.route}`, `The page requested ${ev.method} ${ev.url} which returned HTTP ${ev.status}`],
315
+ networkExcerpt: [`${ev.method} ${ev.url} -> ${ev.status}`],
316
+ suggestedFix: isServer ? "The API endpoint errors (5xx). Check the server handler; the page likely shows stale or missing data." : "The API call failed (4xx). Verify the endpoint URL and request shape.",
317
+ dedupeKey: key
318
+ });
319
+ }
320
+ return findings;
321
+ };
322
+ function shortPath(u) {
323
+ try {
324
+ return new URL(u).pathname;
325
+ } catch {
326
+ return u;
327
+ }
328
+ }
329
+
330
+ // src/crawl/detectors/content.ts
331
+ var contentDetector = async (ctx) => {
332
+ const findings = [];
333
+ const data = await ctx.page.evaluate(() => {
334
+ const visibleText = (document.body?.innerText || "").trim();
335
+ function isShown(el) {
336
+ const s = getComputedStyle(el);
337
+ return s.display !== "none" && s.visibility !== "hidden";
338
+ }
339
+ function nearbyText(el) {
340
+ const scope = el.closest("section, main, article, div, body") || el.parentElement || el;
341
+ return (scope.textContent || "").toLowerCase();
342
+ }
343
+ const EMPTY_HINT = /(no |empty|nothing|0 results|no results|you (have|don'?t)|once you|get started|add your first|haven'?t)/i;
344
+ const empties = [];
345
+ for (const table of Array.from(document.querySelectorAll("table"))) {
346
+ if (!isShown(table)) continue;
347
+ const headCols = table.querySelectorAll("thead th, thead td").length;
348
+ const bodyRows = table.querySelectorAll("tbody tr").length;
349
+ if (headCols >= 2 && bodyRows === 0) {
350
+ const heading = (table.closest("section, main, body")?.querySelector("h1,h2,h3")?.textContent || "").trim();
351
+ if (!EMPTY_HINT.test(nearbyText(table))) {
352
+ empties.push({ kind: "table", label: heading || "data table" });
353
+ }
354
+ }
355
+ }
356
+ for (const list of Array.from(document.querySelectorAll('ul[aria-label], ol[aria-label], [role="list"], [data-testid*="list" i], [class*="results" i]'))) {
357
+ if (!isShown(list)) continue;
358
+ const items = list.querySelectorAll('li, [role="listitem"], [class*="item" i]').length;
359
+ if (items === 0 && !EMPTY_HINT.test(nearbyText(list))) {
360
+ const label = (list.getAttribute("aria-label") || "").trim();
361
+ empties.push({ kind: "list", label: label || "list" });
362
+ }
363
+ }
364
+ return { visibleText, empties };
365
+ }).catch(() => null);
366
+ if (!data) return findings;
367
+ for (const e of data.empties) {
368
+ findings.push({
369
+ ruleId: "data/empty-collection",
370
+ issueClass: 4,
371
+ title: `Empty ${e.kind} with no empty-state ("${e.label}")`,
372
+ severity: "medium",
373
+ confidence: "likely",
374
+ steps: [`Navigate to ${ctx.route}`, `The "${e.label}" ${e.kind} rendered with zero rows/items and no empty-state message`],
375
+ suggestedFix: 'Either load the data or render a clear empty-state ("You have no orders yet"). A silently empty table reads as a bug.',
376
+ dedupeKey: `empty:${e.kind}:${e.label}`
377
+ });
378
+ }
379
+ for (const p of PLACEHOLDER_PATTERNS) {
380
+ const m = data.visibleText.match(p.re);
381
+ if (m) {
382
+ findings.push({
383
+ ruleId: "data/placeholder-content",
384
+ issueClass: 4,
385
+ title: `${p.label} visible in the page`,
386
+ severity: "medium",
387
+ confidence: "confirmed",
388
+ steps: [`Navigate to ${ctx.route}`, `Found placeholder/mock content: "${m[0]}"`],
389
+ suggestedFix: "Replace placeholder/mock data with real content (or guard it out of production builds).",
390
+ dedupeKey: `placeholder:${p.id}`
391
+ });
392
+ }
393
+ }
394
+ return findings;
395
+ };
396
+
397
+ // src/crawl/detectors/a11y.ts
398
+ function mapAxeImpact(impact) {
399
+ switch (impact) {
400
+ case "critical":
401
+ return "high";
402
+ case "serious":
403
+ return "high";
404
+ case "moderate":
405
+ return "medium";
406
+ case "minor":
407
+ return "low";
408
+ default:
409
+ return "medium";
410
+ }
411
+ }
412
+ function issueClassFor(axeId) {
413
+ return axeId === "target-size" ? 10 : 11;
414
+ }
415
+ var a11yDetector = async (ctx) => {
416
+ let AxeBuilder;
417
+ try {
418
+ ({ AxeBuilder } = await import("@axe-core/playwright"));
419
+ } catch {
420
+ return [];
421
+ }
422
+ let builder = new AxeBuilder({ page: ctx.page }).withTags(["wcag2a", "wcag2aa", "wcag21aa"]);
423
+ if (ctx.viewport === "mobile") {
424
+ builder = builder.withRules(["target-size"]);
425
+ }
426
+ let results;
427
+ try {
428
+ results = await builder.analyze();
429
+ } catch {
430
+ return [];
431
+ }
432
+ const findings = [];
433
+ const unlabeled = await ctx.page.evaluate(() => {
434
+ const TYPES = ["text", "email", "password", "tel", "search", "number", "url", ""];
435
+ const controls = Array.from(document.querySelectorAll("input, select, textarea"));
436
+ const out = [];
437
+ for (const c of controls) {
438
+ const type = (c.getAttribute("type") || "").toLowerCase();
439
+ if (c.tagName === "INPUT" && !TYPES.includes(type)) continue;
440
+ const s = getComputedStyle(c);
441
+ if (s.display === "none" || s.visibility === "hidden") continue;
442
+ const hasAria = c.getAttribute("aria-label") || c.getAttribute("aria-labelledby") || c.getAttribute("title");
443
+ const labelledBy = c.id ? document.querySelector(`label[for="${CSS.escape(c.id)}"]`) : null;
444
+ const wrapping = c.closest("label");
445
+ if (!hasAria && !labelledBy && !wrapping) {
446
+ out.push((c.getAttribute("name") || c.getAttribute("placeholder") || type || "field").slice(0, 30));
447
+ }
448
+ }
449
+ return out;
450
+ }).catch(() => []);
451
+ if (unlabeled.length > 0) {
452
+ findings.push({
453
+ ruleId: "a11y/label-missing",
454
+ issueClass: 11,
455
+ title: `Form control${unlabeled.length > 1 ? "s" : ""} without an accessible label (${unlabeled.length})`,
456
+ severity: "medium",
457
+ confidence: "confirmed",
458
+ steps: [`Navigate to ${ctx.route}`, `Found input(s) with no <label>, aria-label, or title: ${unlabeled.join(", ")}`],
459
+ suggestedFix: "Associate a <label for> (or aria-label) with every form control so screen readers and clicks on the label work.",
460
+ dedupeKey: "label-missing"
461
+ });
462
+ }
463
+ for (const v of results.violations) {
464
+ const nodeCount = v.nodes.length;
465
+ const sampleHtml = v.nodes.slice(0, 2).map((n) => n.html.slice(0, 120));
466
+ findings.push({
467
+ ruleId: `a11y/${v.id}`,
468
+ issueClass: issueClassFor(v.id),
469
+ title: `${v.help}${nodeCount > 1 ? ` (${nodeCount} elements)` : ""}`,
470
+ severity: mapAxeImpact(v.impact),
471
+ confidence: "confirmed",
472
+ steps: [
473
+ `Navigate to ${ctx.route}${ctx.viewport === "mobile" ? " (mobile viewport)" : ""}`,
474
+ `axe-core WCAG check "${v.id}" failed: ${v.description}`,
475
+ ...sampleHtml.map((h) => `element: ${h}`)
476
+ ],
477
+ suggestedFix: `${v.help}. See ${v.helpUrl}`,
478
+ dedupeKey: `a11y:${v.id}`
479
+ });
480
+ }
481
+ return findings;
482
+ };
483
+
484
+ // src/crawl/detectors/responsive.ts
485
+ var responsiveDetector = async (ctx) => {
486
+ if (ctx.viewport !== "mobile") return [];
487
+ const findings = [];
488
+ const tiny = await ctx.page.evaluate(() => {
489
+ const MIN = 24;
490
+ const controls = Array.from(
491
+ document.querySelectorAll('button, [role="button"], input[type="submit"], input[type="button"], a.btn, a.button')
492
+ );
493
+ const out = [];
494
+ for (const c of controls) {
495
+ const s = getComputedStyle(c);
496
+ if (s.display === "none" || s.visibility === "hidden") continue;
497
+ const r = c.getBoundingClientRect();
498
+ if (r.width === 0 || r.height === 0) continue;
499
+ if (r.width < MIN || r.height < MIN) {
500
+ out.push({ label: (c.textContent || c.getAttribute("aria-label") || c.tagName).trim().slice(0, 30), w: Math.round(r.width), h: Math.round(r.height) });
501
+ }
502
+ }
503
+ return out;
504
+ }).catch(() => []);
505
+ if (tiny.length > 0) {
506
+ const sample = tiny.slice(0, 4).map((t) => `"${t.label}" ${t.w}x${t.h}px`).join(", ");
507
+ findings.push({
508
+ ruleId: "responsive/tap-target-too-small",
509
+ issueClass: 10,
510
+ title: `Tap target${tiny.length > 1 ? "s" : ""} below 24x24px (${tiny.length})`,
511
+ severity: "low",
512
+ confidence: "likely",
513
+ steps: [`Navigate to ${ctx.route} at 375px (mobile) width`, `Found ${tiny.length} control(s) smaller than the 24x24px minimum: ${sample}`],
514
+ suggestedFix: "Give interactive controls at least a 24x24px (ideally 44x44px) touch area via padding/min-height.",
515
+ dedupeKey: "tap-target"
516
+ });
517
+ }
518
+ const overflow = await ctx.page.evaluate(() => {
519
+ const doc = document.documentElement;
520
+ const slack = 4;
521
+ const scrollW = doc.scrollWidth;
522
+ const clientW = doc.clientWidth;
523
+ if (scrollW <= clientW + slack) return null;
524
+ let worst = null;
525
+ for (const el of Array.from(document.body.querySelectorAll("*"))) {
526
+ const r = el.getBoundingClientRect();
527
+ if (r.width > clientW + slack && (!worst || r.width > worst.width)) {
528
+ const cls = el.className && typeof el.className === "string" ? "." + el.className.trim().split(/\s+/).join(".") : "";
529
+ worst = { tag: el.tagName.toLowerCase(), width: Math.round(r.width), desc: el.tagName.toLowerCase() + cls.slice(0, 60) };
530
+ }
531
+ }
532
+ return { scrollW, clientW, worst };
533
+ }).catch(() => null);
534
+ if (!overflow) return findings;
535
+ const culprit = overflow.worst ? ` Widest offender: <${overflow.worst.desc}> at ${overflow.worst.width}px.` : "";
536
+ findings.push({
537
+ ruleId: "responsive/horizontal-overflow",
538
+ issueClass: 10,
539
+ title: "Horizontal overflow at mobile width",
540
+ severity: "medium",
541
+ confidence: "confirmed",
542
+ steps: [
543
+ `Navigate to ${ctx.route} at 375px (mobile) width`,
544
+ `The document scrolls horizontally: content is ${overflow.scrollW}px wide in a ${overflow.clientW}px viewport.${culprit}`
545
+ ],
546
+ suggestedFix: "Constrain fixed-width elements (use max-width:100%, overflow-x handling, or responsive units) so the page fits the viewport.",
547
+ dedupeKey: "overflow"
548
+ });
549
+ return findings;
550
+ };
551
+
552
+ // src/crawl/detectors/forms.ts
553
+ var SUCCESS_RE = /(success|thank you|thanks|confirmed|order (placed|received)|received|we'?ll be in touch|check your email|submitted|saved|welcome)/i;
554
+ var SUBMIT_TEXT_RE = /(submit|create|sign ?up|register|continue|next|save|place order|pay|checkout|send|log ?in|sign ?in|subscribe|apply)/i;
555
+ async function snapshot(page) {
556
+ return page.evaluate((successSrc) => {
557
+ const re = new RegExp(successSrc, "i");
558
+ const text = document.body?.innerText || "";
559
+ const alerts = document.querySelectorAll('[role="alert"], [aria-live], .error, .invalid, .field-error, [class*="error" i]').length;
560
+ const invalidField = Array.from(document.querySelectorAll("input, select, textarea")).some(
561
+ (el) => el.validity && !el.validity.valid
562
+ );
563
+ return { url: location.href, textLen: text.length, alerts, invalidField, successText: re.test(text) };
564
+ }, SUCCESS_RE.source);
565
+ }
566
+ async function fillForm(page, formIdx, email) {
567
+ const form = page.locator("form").nth(formIdx);
568
+ const inputs = form.locator("input:visible, textarea:visible, select:visible");
569
+ const n = await inputs.count().catch(() => 0);
570
+ let filledAny = false;
571
+ for (let i = 0; i < n; i++) {
572
+ const el = inputs.nth(i);
573
+ const type = (await el.getAttribute("type").catch(() => "") || "").toLowerCase();
574
+ const name = (await el.getAttribute("name").catch(() => "") || "") + " " + (await el.getAttribute("placeholder").catch(() => "") || "");
575
+ try {
576
+ if (type === "checkbox" || type === "radio") {
577
+ await el.check({ timeout: 1e3 });
578
+ filledAny = true;
579
+ } else if (type === "email" || /email/i.test(name)) {
580
+ await el.fill(email, { timeout: 1e3 });
581
+ filledAny = true;
582
+ } else if (type === "password") {
583
+ await el.fill("Passw0rd!23", { timeout: 1e3 });
584
+ filledAny = true;
585
+ } else if (type === "tel" || /phone/i.test(name)) {
586
+ await el.fill("5551234567", { timeout: 1e3 });
587
+ filledAny = true;
588
+ } else if (type === "number") {
589
+ await el.fill("1", { timeout: 1e3 });
590
+ filledAny = true;
591
+ } else if (type === "" || type === "text" || type === "search" || el) {
592
+ await el.fill("QA Test 123", { timeout: 1e3 });
593
+ filledAny = true;
594
+ }
595
+ } catch {
596
+ }
597
+ }
598
+ return filledAny;
599
+ }
600
+ async function findSubmit(page, formIdx) {
601
+ const form = page.locator("form").nth(formIdx);
602
+ let btn = form.locator('button[type="submit"], input[type="submit"]').first();
603
+ if (await btn.count() === 0) {
604
+ const buttons = form.locator('button, [role="button"]');
605
+ const bn = await buttons.count();
606
+ for (let i = 0; i < bn; i++) {
607
+ const t = await buttons.nth(i).innerText().catch(() => "") || "";
608
+ if (SUBMIT_TEXT_RE.test(t)) {
609
+ btn = buttons.nth(i);
610
+ break;
611
+ }
612
+ if (i === bn - 1) btn = buttons.first();
613
+ }
614
+ }
615
+ return btn;
616
+ }
617
+ var formsDetector = async (ctx) => {
618
+ const findings = [];
619
+ const formCount = await ctx.page.locator("form").count().catch(() => 0);
620
+ if (formCount === 0) return findings;
621
+ const limit = Math.min(formCount, 2);
622
+ for (let f = 0; f < limit; f++) {
623
+ await ctx.freshNavigate();
624
+ const hasSubmit = await findSubmit(ctx.page, f).then((b) => b.count()).catch(() => 0) > 0;
625
+ if (!hasSubmit) continue;
626
+ await fillForm(ctx.page, f, "qa.tester@example.org");
627
+ const before = await snapshot(ctx.page);
628
+ let postRequest = false;
629
+ let anyRequest = false;
630
+ const onReq = (req) => {
631
+ anyRequest = true;
632
+ if (req.method() === "POST" || req.method() === "PUT" || req.method() === "PATCH") postRequest = true;
633
+ };
634
+ ctx.page.on("request", onReq);
635
+ const submit = await findSubmit(ctx.page, f);
636
+ await submit.click({ timeout: 2e3 }).catch(() => {
637
+ });
638
+ await ctx.page.waitForTimeout(1200);
639
+ ctx.page.off("request", onReq);
640
+ const after = await snapshot(ctx.page).catch(() => before);
641
+ const urlChanged = after.url !== before.url;
642
+ const domChanged = Math.abs(after.textLen - before.textLen) > 8;
643
+ const newAlert = after.alerts > before.alerts || after.invalidField;
644
+ const success = after.successText && !before.successText;
645
+ const observableEffect = urlChanged || domChanged || newAlert || success || anyRequest;
646
+ if (!observableEffect) {
647
+ findings.push({
648
+ ruleId: "form/submit-noop",
649
+ issueClass: 5,
650
+ title: "Submit button does nothing",
651
+ severity: "high",
652
+ confidence: "likely",
653
+ steps: [`Navigate to ${ctx.route}`, "Fill the form with valid values", "Click the submit button", "Nothing happens: no navigation, no request, no message, no visible change"],
654
+ suggestedFix: "Wire the submit handler (or form action). A dead submit button blocks the whole flow.",
655
+ dedupeKey: `submit-noop:${f}`
656
+ });
657
+ } else if (postRequest && !urlChanged && !domChanged && !success) {
658
+ findings.push({
659
+ ruleId: "async/no-success-feedback",
660
+ issueClass: 9,
661
+ title: "Form submits but shows no success feedback",
662
+ severity: "high",
663
+ confidence: "likely",
664
+ steps: [`Navigate to ${ctx.route}`, "Fill and submit the form", "A request was sent, but the UI shows no success message, redirect, or change"],
665
+ suggestedFix: "Render a clear success state (message/redirect) after the request resolves; users cannot tell if the action worked.",
666
+ needsOutOfBandVerification: true,
667
+ dedupeKey: `no-success:${f}`
668
+ });
669
+ }
670
+ const hasEmail = await ctx.page.locator("form").nth(f).locator('input[type="email"], input[name*="email" i], input[placeholder*="email" i]').count().catch(() => 0);
671
+ if (hasEmail > 0) {
672
+ await ctx.freshNavigate();
673
+ await fillForm(ctx.page, f, "notanemail");
674
+ const b2 = await snapshot(ctx.page);
675
+ const submit2 = await findSubmit(ctx.page, f);
676
+ await submit2.click({ timeout: 2e3 }).catch(() => {
677
+ });
678
+ await ctx.page.waitForTimeout(1e3);
679
+ const a2 = await snapshot(ctx.page).catch(() => b2);
680
+ const validationFired = a2.invalidField || a2.alerts > b2.alerts;
681
+ if (!validationFired) {
682
+ findings.push({
683
+ ruleId: "form/no-validation",
684
+ issueClass: 5,
685
+ title: "Invalid email accepted without validation",
686
+ severity: "medium",
687
+ confidence: "likely",
688
+ steps: [`Navigate to ${ctx.route}`, 'Enter an invalid email ("notanemail")', "Submit the form", "No validation error fires and the value is accepted"],
689
+ suggestedFix: 'Validate the email field (use type="email" or explicit validation) and show an inline error for invalid input.',
690
+ dedupeKey: `no-validation:${f}`
691
+ });
692
+ }
693
+ }
694
+ }
695
+ return findings;
696
+ };
697
+
698
+ // src/crawl/detectors/loading.ts
699
+ var ERROR_TEXT_RE = /(error|failed|failure|something went wrong|went wrong|try again|couldn'?t|could not|unable to|problem loading|retry)/i;
700
+ var loadingStateDetector = async (ctx) => {
701
+ const findings = [];
702
+ const spinnerSel = '[class*="spin" i],[class*="loading" i],[class*="loader" i],[class*="skeleton" i],[role="progressbar"],[aria-busy="true"]';
703
+ const stillSpinning = async () => ctx.page.evaluate((sel) => {
704
+ const els = Array.from(document.querySelectorAll(sel));
705
+ return els.some((el) => {
706
+ const s = getComputedStyle(el);
707
+ const r = el.getBoundingClientRect();
708
+ return s.display !== "none" && s.visibility !== "hidden" && s.opacity !== "0" && r.width > 0 && r.height > 0;
709
+ });
710
+ }, spinnerSel).catch(() => false);
711
+ if (await stillSpinning()) {
712
+ await ctx.page.waitForTimeout(2500);
713
+ if (await stillSpinning()) {
714
+ findings.push({
715
+ ruleId: "loading/stuck-spinner",
716
+ issueClass: 8,
717
+ title: "Loading spinner never resolves",
718
+ severity: "medium",
719
+ confidence: "likely",
720
+ steps: [`Navigate to ${ctx.route}`, "A loading indicator is still spinning after the page has had ample time to settle", "A request likely hung and the UI is stuck loading"],
721
+ suggestedFix: "Add a timeout/fallback for the pending request and resolve the loading state (render data, an empty state, or an error).",
722
+ networkExcerpt: ctx.evidence.networkExcerpt(),
723
+ dedupeKey: "stuck-spinner"
724
+ });
725
+ }
726
+ }
727
+ const apiFailures = ctx.evidence.firstPartyApiFailures();
728
+ if (apiFailures.length > 0) {
729
+ const hasErrorUi = await ctx.page.evaluate((src) => {
730
+ const re = new RegExp(src, "i");
731
+ const hasAlert = document.querySelector('[role="alert"]') !== null;
732
+ return hasAlert || re.test(document.body?.innerText || "");
733
+ }, ERROR_TEXT_RE.source).catch(() => true);
734
+ if (!hasErrorUi) {
735
+ const f = apiFailures[0];
736
+ findings.push({
737
+ ruleId: "state/missing-error-state",
738
+ issueClass: 8,
739
+ title: "Failed request shows no error state to the user",
740
+ severity: "medium",
741
+ confidence: "likely",
742
+ steps: [`Navigate to ${ctx.route}`, `A request failed (${f.method} ${f.url} \u2192 ${f.status})`, "The page shows no error message, retry, or fallback \u2014 the failure is silent"],
743
+ suggestedFix: "Render a visible error state when a request fails (message + retry), instead of swallowing the error.",
744
+ networkExcerpt: ctx.evidence.networkExcerpt(),
745
+ dedupeKey: "missing-error-state"
746
+ });
747
+ }
748
+ }
749
+ return findings;
750
+ };
751
+
752
+ // src/crawl/detectors/flow.ts
753
+ var FORWARD_RE = /\b(next|continue|forward|proceed|step\s?2|go on)\b/i;
754
+ var BACK_RE = /\b(back|previous|prev|go back)\b/i;
755
+ var FINISH_RE = /\b(finish|done|complete|submit|next|continue|confirm)\b/i;
756
+ var PRIMARY_ACTION_RE = /\b(checkout|buy now|buy|purchase|add to cart|place order|get started|sign\s?up|start free|book now|proceed to|continue to)\b/i;
757
+ var SENTINEL = "SNIFFSTATE12345";
758
+ var flowDetector = async (ctx) => {
759
+ const findings = [];
760
+ await ctx.freshNavigate();
761
+ const trackSel = await ctx.page.evaluate(() => {
762
+ const inputs = Array.from(document.querySelectorAll("input"));
763
+ const el = inputs.find((i) => {
764
+ const t = (i.type || "text").toLowerCase();
765
+ const s = getComputedStyle(i);
766
+ return ["text", "email", "search", "tel", ""].includes(t) && s.display !== "none" && s.visibility !== "hidden";
767
+ });
768
+ if (!el) return null;
769
+ if (el.id) return `#${CSS.escape(el.id)}`;
770
+ if (el.name) return `[name="${CSS.escape(el.name)}"]`;
771
+ return null;
772
+ }).catch(() => null);
773
+ const forward = ctx.page.locator('button:visible, a:visible, [role="button"]').filter({ hasText: FORWARD_RE }).first();
774
+ const hasForward = await forward.count().catch(() => 0) > 0;
775
+ if (trackSel && hasForward) {
776
+ await ctx.page.fill(trackSel, SENTINEL, { timeout: 1500 }).catch(() => {
777
+ });
778
+ await forward.click({ timeout: 2e3 }).catch(() => {
779
+ });
780
+ await ctx.page.waitForTimeout(800);
781
+ await ctx.page.locator('input[type="checkbox"]:visible').first().check({ timeout: 800 }).catch(() => {
782
+ });
783
+ const deadEnd = await ctx.page.evaluate((sources) => {
784
+ const [finishSrc, fwdSrc] = sources;
785
+ const finishRe = new RegExp(finishSrc, "i");
786
+ const fwdRe = new RegExp(fwdSrc, "i");
787
+ const ctrls = Array.from(document.querySelectorAll('button, a, [role="button"], input[type="submit"]'));
788
+ const visible = ctrls.filter((c) => {
789
+ const s = getComputedStyle(c);
790
+ const r = c.getBoundingClientRect();
791
+ return s.display !== "none" && s.visibility !== "hidden" && r.width > 0 && r.height > 0;
792
+ });
793
+ const forwardish = visible.filter((c) => finishRe.test(c.textContent || "") || fwdRe.test(c.textContent || ""));
794
+ if (forwardish.length === 0) return false;
795
+ const anyEnabled = forwardish.some((c) => !c.disabled && c.getAttribute("aria-disabled") !== "true");
796
+ return !anyEnabled;
797
+ }, [FINISH_RE.source, FORWARD_RE.source]).catch(() => false);
798
+ if (deadEnd) {
799
+ findings.push({
800
+ ruleId: "flow/dead-end",
801
+ issueClass: 7,
802
+ title: "Multi-step flow dead-ends (no enabled way forward)",
803
+ severity: "high",
804
+ confidence: "likely",
805
+ steps: [`Navigate to ${ctx.route}`, "Advance past the first step", "Fill the step inputs", "The only forward/finish control stays disabled \u2014 the flow cannot be completed"],
806
+ suggestedFix: "Enable the forward/finish control when the step is valid, or provide another way to complete the flow.",
807
+ dedupeKey: "dead-end"
808
+ });
809
+ }
810
+ const back = ctx.page.locator('button:visible, a:visible, [role="button"]').filter({ hasText: BACK_RE }).first();
811
+ if (await back.count().catch(() => 0) > 0) {
812
+ await back.click({ timeout: 2e3 }).catch(() => {
813
+ });
814
+ } else {
815
+ await ctx.page.goBack({ timeout: 3e3 }).catch(() => {
816
+ });
817
+ }
818
+ await ctx.page.waitForTimeout(700);
819
+ const restored = await ctx.page.locator(trackSel).inputValue({ timeout: 1500 }).catch(() => null);
820
+ if (restored !== null && restored !== SENTINEL) {
821
+ findings.push({
822
+ ruleId: "flow/state-loss",
823
+ issueClass: 6,
824
+ title: "Form state lost on back navigation",
825
+ severity: "high",
826
+ confidence: "likely",
827
+ steps: [`Navigate to ${ctx.route}`, `Enter a value in the first field`, "Advance to the next step", "Go back", "The value was wiped (state not preserved)"],
828
+ suggestedFix: "Preserve multi-step form state (keep it in state/store or restore it on back) so users do not lose their progress.",
829
+ dedupeKey: "state-loss"
830
+ });
831
+ }
832
+ }
833
+ await ctx.freshNavigate().catch(() => {
834
+ });
835
+ const buried = await ctx.page.evaluate((actionSrc) => {
836
+ const re = new RegExp(actionSrc, "i");
837
+ const els = Array.from(document.querySelectorAll("a[href]"));
838
+ const out = [];
839
+ for (const el of els) {
840
+ const text = (el.textContent || "").trim();
841
+ if (!text || !re.test(text)) continue;
842
+ const s = getComputedStyle(el);
843
+ const r = el.getBoundingClientRect();
844
+ const fontSize = parseFloat(s.fontSize) || 16;
845
+ const opacity = parseFloat(s.opacity);
846
+ const offscreen = r.right < 0 || r.bottom < 0 || r.left > (window.innerWidth || 1280);
847
+ let reason = "";
848
+ if (fontSize < 12) reason = `tiny font (${fontSize}px)`;
849
+ else if (!Number.isNaN(opacity) && opacity < 0.4) reason = `near-transparent (opacity ${opacity})`;
850
+ else if (r.width > 0 && r.width < 8) reason = "almost zero width";
851
+ else if (offscreen) reason = "positioned off-screen";
852
+ if (reason) out.push({ text: text.slice(0, 40), reason });
853
+ }
854
+ return out;
855
+ }, PRIMARY_ACTION_RE.source).catch(() => []);
856
+ for (const b of buried) {
857
+ findings.push({
858
+ ruleId: "flow/unclear-action",
859
+ issueClass: 12,
860
+ title: `Primary action "${b.text}" is hard to find`,
861
+ severity: "low",
862
+ confidence: "uncertain",
863
+ steps: [`Navigate to ${ctx.route}`, `The primary action "${b.text}" is rendered with low prominence: ${b.reason}`],
864
+ suggestedFix: "Give the primary action clear visual prominence (readable size, sufficient contrast, obvious placement).",
865
+ dedupeKey: `unclear:${b.text}`
866
+ });
867
+ }
868
+ return findings;
869
+ };
870
+
871
+ // src/crawl/engine.ts
872
+ var DESKTOP = { width: 1280, height: 800 };
873
+ var MOBILE = { width: 375, height: 812 };
874
+ var PASSIVE = [pageHealthDetector, runtimeErrorDetector, contentDetector];
875
+ var INTERACTION = [formsDetector, loadingStateDetector, flowDetector];
876
+ function routeOf(url) {
877
+ try {
878
+ return new URL(url).pathname.replace(/\/+$/, "") || "/";
879
+ } catch {
880
+ return url;
881
+ }
882
+ }
883
+ function safeName(s) {
884
+ return s.replace(/[^a-zA-Z0-9]/g, "_").slice(0, 60) || "root";
885
+ }
886
+ async function runCrawl(opts) {
887
+ const maxPages = opts.maxPages ?? 25;
888
+ const headless = opts.headless ?? true;
889
+ const includeMobile = opts.includeMobile ?? true;
890
+ const settleMs = opts.settleMs ?? 3500;
891
+ const linkTimeoutMs = opts.linkTimeoutMs ?? 1e4;
892
+ const log = opts.onProgress ?? (() => {
893
+ });
894
+ const startUrl = normalizeUrl(opts.startUrl);
895
+ const baseOrigin = new URL(startUrl).origin;
896
+ const startedAt = performance.now();
897
+ const outputDir = opts.outputDir ?? join(process.cwd(), "sniff-reports", "crawl");
898
+ await mkdir(outputDir, { recursive: true }).catch(() => {
899
+ });
900
+ const playwright = await import("playwright");
901
+ const browser = await playwright.chromium.launch({ headless });
902
+ const raw = [];
903
+ const visited = [];
904
+ const brokenRoutes = /* @__PURE__ */ new Set();
905
+ const linkRegistry = [];
906
+ const linkSeen = /* @__PURE__ */ new Set();
907
+ let linksChecked = 0;
908
+ try {
909
+ const context = await browser.newContext({ viewport: DESKTOP, ignoreHTTPSErrors: true });
910
+ const page = await context.newPage();
911
+ page.setDefaultTimeout(8e3);
912
+ const evidence = new PageEvidence(baseOrigin);
913
+ evidence.attach(page);
914
+ async function navigateAndSettle(url) {
915
+ evidence.reset();
916
+ let status = null;
917
+ try {
918
+ const resp = await page.goto(url, { waitUntil: "domcontentloaded", timeout: 15e3 });
919
+ status = resp ? resp.status() : null;
920
+ } catch (e) {
921
+ const msg = e instanceof Error ? e.message : String(e);
922
+ if (!isEngineInducedFailure(msg)) status = null;
923
+ }
924
+ await page.waitForLoadState("networkidle", { timeout: settleMs }).catch(() => {
925
+ });
926
+ return status;
927
+ }
928
+ const queue = [startUrl];
929
+ while (queue.length > 0 && visited.length < maxPages) {
930
+ const url = queue.shift();
931
+ if (visited.includes(url)) continue;
932
+ visited.push(url);
933
+ const route = routeOf(url);
934
+ log(`scan ${route}`);
935
+ const navStatus = await navigateAndSettle(url);
936
+ const ctx = {
937
+ page,
938
+ url,
939
+ route,
940
+ viewport: "desktop",
941
+ navStatus,
942
+ evidence,
943
+ baseOrigin,
944
+ freshNavigate: async () => {
945
+ await navigateAndSettle(url);
946
+ }
947
+ };
948
+ if (navStatus !== null && navStatus >= 400) {
949
+ brokenRoutes.add(route);
950
+ const bf = await pageHealthDetector(ctx).catch(() => []);
951
+ let bshot;
952
+ if (bf.length > 0) {
953
+ bshot = join(outputDir, `${safeName(route)}-desktop.png`);
954
+ await page.screenshot({ path: bshot, fullPage: false }).catch(() => {
955
+ bshot = void 0;
956
+ });
957
+ }
958
+ for (const f of bf) raw.push({ ...f, url, route, viewport: "desktop", ...bshot ? { screenshotPath: bshot } : {} });
959
+ continue;
960
+ }
961
+ const pageFindings = [];
962
+ for (const det of PASSIVE) {
963
+ try {
964
+ pageFindings.push(...await det(ctx));
965
+ } catch {
966
+ }
967
+ }
968
+ try {
969
+ pageFindings.push(...await a11yDetector(ctx));
970
+ } catch {
971
+ }
972
+ const links = await extractLinks(page, baseOrigin);
973
+ for (const l of [...links.internal.map((u) => ({ u, ext: false })), ...links.external.map((u) => ({ u, ext: true }))]) {
974
+ if (linkSeen.has(l.u)) continue;
975
+ linkSeen.add(l.u);
976
+ linkRegistry.push({ url: l.u, sourceRoute: route, external: l.ext });
977
+ }
978
+ for (const internal of links.internal) {
979
+ if (!visited.includes(internal) && !queue.includes(internal) && isCrawlable(internal, baseOrigin)) {
980
+ queue.push(internal);
981
+ }
982
+ }
983
+ for (const det of INTERACTION) {
984
+ try {
985
+ pageFindings.push(...await det(ctx));
986
+ } catch {
987
+ }
988
+ }
989
+ let shot;
990
+ if (pageFindings.length > 0) {
991
+ await navigateAndSettle(url);
992
+ shot = join(outputDir, `${safeName(route)}-desktop.png`);
993
+ await page.screenshot({ path: shot, fullPage: false }).catch(() => {
994
+ shot = void 0;
995
+ });
996
+ }
997
+ for (const f of pageFindings) {
998
+ raw.push({ ...f, url, route, viewport: "desktop", ...shot ? { screenshotPath: shot } : {} });
999
+ }
1000
+ }
1001
+ log(`checking ${linkRegistry.length} links`);
1002
+ const request = context.request;
1003
+ const linkFindings = await checkLinks(request, linkRegistry, { timeout: linkTimeoutMs });
1004
+ linksChecked = linkRegistry.length;
1005
+ for (const f of linkFindings) {
1006
+ const src = linkRegistry.find((l) => f.title.includes(l.url));
1007
+ const route = src?.sourceRoute ?? routeOf(startUrl);
1008
+ raw.push({ ...f, url: src?.url ?? startUrl, route, viewport: "desktop" });
1009
+ }
1010
+ await context.close();
1011
+ if (includeMobile && visited.length > 0) {
1012
+ const mctx = await browser.newContext({ viewport: MOBILE, ignoreHTTPSErrors: true });
1013
+ const mpage = await mctx.newPage();
1014
+ mpage.setDefaultTimeout(8e3);
1015
+ const mevidence = new PageEvidence(baseOrigin);
1016
+ mevidence.attach(mpage);
1017
+ for (const url of visited) {
1018
+ const route = routeOf(url);
1019
+ if (brokenRoutes.has(route)) continue;
1020
+ log(`mobile ${route}`);
1021
+ mevidence.reset();
1022
+ try {
1023
+ await mpage.goto(url, { waitUntil: "domcontentloaded", timeout: 15e3 });
1024
+ } catch {
1025
+ }
1026
+ await mpage.waitForLoadState("networkidle", { timeout: settleMs }).catch(() => {
1027
+ });
1028
+ const mc = {
1029
+ page: mpage,
1030
+ url,
1031
+ route,
1032
+ viewport: "mobile",
1033
+ navStatus: null,
1034
+ evidence: mevidence,
1035
+ baseOrigin,
1036
+ freshNavigate: async () => {
1037
+ try {
1038
+ await mpage.goto(url, { waitUntil: "domcontentloaded" });
1039
+ } catch {
1040
+ }
1041
+ }
1042
+ };
1043
+ const mf = [];
1044
+ try {
1045
+ mf.push(...await a11yDetector(mc));
1046
+ } catch {
1047
+ }
1048
+ try {
1049
+ mf.push(...await responsiveDetector(mc));
1050
+ } catch {
1051
+ }
1052
+ let shot;
1053
+ if (mf.length > 0) {
1054
+ shot = join(outputDir, `${safeName(route)}-mobile.png`);
1055
+ await mpage.screenshot({ path: shot, fullPage: false }).catch(() => {
1056
+ shot = void 0;
1057
+ });
1058
+ }
1059
+ for (const f of mf) raw.push({ ...f, url, route, viewport: "mobile", ...shot ? { screenshotPath: shot } : {} });
1060
+ }
1061
+ await mctx.close();
1062
+ }
1063
+ } finally {
1064
+ await browser.close();
1065
+ }
1066
+ const seen = /* @__PURE__ */ new Set();
1067
+ const findings = [];
1068
+ for (const r of raw) {
1069
+ const key = `${r.ruleId}|${r.route}|${r.dedupeKey ?? r.title}`;
1070
+ if (seen.has(key)) continue;
1071
+ seen.add(key);
1072
+ findings.push({
1073
+ ruleId: r.ruleId,
1074
+ issueClass: r.issueClass,
1075
+ title: r.title,
1076
+ severity: r.severity,
1077
+ confidence: r.confidence,
1078
+ reproduction: {
1079
+ url: r.url,
1080
+ route: r.route,
1081
+ steps: r.steps ?? [`Navigate to ${r.route}`],
1082
+ ...r.screenshotPath ? { screenshotPath: r.screenshotPath } : {},
1083
+ ...r.consoleExcerpt ? { consoleExcerpt: r.consoleExcerpt } : {},
1084
+ ...r.networkExcerpt ? { networkExcerpt: r.networkExcerpt } : {}
1085
+ },
1086
+ suggestedFix: r.suggestedFix,
1087
+ ...r.needsOutOfBandVerification ? { needsOutOfBandVerification: true } : {}
1088
+ });
1089
+ }
1090
+ findings.sort((a, b) => sevRank(b.severity) - sevRank(a.severity) || a.issueClass - b.issueClass);
1091
+ const bySeverity = {};
1092
+ const byConfidence = {};
1093
+ const byIssueClass = {};
1094
+ for (const f of findings) {
1095
+ bySeverity[f.severity] = (bySeverity[f.severity] ?? 0) + 1;
1096
+ byConfidence[f.confidence] = (byConfidence[f.confidence] ?? 0) + 1;
1097
+ byIssueClass[String(f.issueClass)] = (byIssueClass[String(f.issueClass)] ?? 0) + 1;
1098
+ }
1099
+ return {
1100
+ findings,
1101
+ stats: {
1102
+ pagesVisited: visited.length,
1103
+ linksChecked,
1104
+ durationMs: Math.round(performance.now() - startedAt),
1105
+ startUrl
1106
+ },
1107
+ routes: visited.map(routeOf),
1108
+ runAt: (/* @__PURE__ */ new Date()).toISOString(),
1109
+ summary: { total: findings.length, bySeverity, byConfidence, byIssueClass }
1110
+ };
1111
+ }
1112
+ function sevRank(s) {
1113
+ return { critical: 5, high: 4, medium: 3, low: 2, info: 1 }[s] ?? 0;
1114
+ }
1115
+
1116
+ // src/crawl/report-html.ts
1117
+ var SEV_ORDER = ["critical", "high", "medium", "low", "info"];
1118
+ var SEV_COLOR = {
1119
+ critical: "#ff5c7a",
1120
+ high: "#ff8a5c",
1121
+ medium: "#ffd166",
1122
+ low: "#6ee7b7",
1123
+ info: "#8ab4ff"
1124
+ };
1125
+ var CONF_COLOR = {
1126
+ confirmed: "#34d399",
1127
+ likely: "#fbbf24",
1128
+ uncertain: "#94a3b8"
1129
+ };
1130
+ function esc(s) {
1131
+ return String(s).replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
1132
+ }
1133
+ function findingCard(f) {
1134
+ const steps = f.reproduction.steps.map((s) => `<li>${esc(s)}</li>`).join("");
1135
+ const net = (f.reproduction.networkExcerpt ?? []).map((s) => `<code>${esc(s)}</code>`).join("");
1136
+ const con = (f.reproduction.consoleExcerpt ?? []).map((s) => `<code>${esc(s)}</code>`).join("");
1137
+ const shot = f.reproduction.screenshotPath ? `<a class="shot" href="${esc(f.reproduction.screenshotPath)}">screenshot</a>` : "";
1138
+ const oob = f.needsOutOfBandVerification ? `<p class="oob">\u26A0 Needs out-of-band verification (confirm the email/async job actually completed).</p>` : "";
1139
+ return `
1140
+ <article class="card" data-sev="${f.severity}">
1141
+ <header>
1142
+ <span class="sev" style="--c:${SEV_COLOR[f.severity] ?? "#888"}">${f.severity}</span>
1143
+ <span class="conf" style="--c:${CONF_COLOR[f.confidence] ?? "#888"}">${f.confidence}</span>
1144
+ <h3>${esc(f.title)}</h3>
1145
+ </header>
1146
+ <div class="meta"><span class="route">${esc(f.reproduction.route)}</span><span class="rule">${esc(f.ruleId)}</span></div>
1147
+ <details open><summary>Reproduction</summary><ol>${steps}</ol>${con ? `<div class="ex">${con}</div>` : ""}${net ? `<div class="ex">${net}</div>` : ""}${shot}</details>
1148
+ <p class="fix"><strong>Fix:</strong> ${esc(f.suggestedFix)}</p>
1149
+ ${oob}
1150
+ </article>`;
1151
+ }
1152
+ function renderHtmlReport(report, opts = {}) {
1153
+ const title = opts.title ?? "sniff report";
1154
+ const shown = report.findings;
1155
+ const counts = SEV_ORDER.map((s) => ({ s, n: report.summary.bySeverity[s] ?? 0 })).filter((x) => x.n > 0);
1156
+ const chips = counts.map((c) => `<span class="chip" style="--c:${SEV_COLOR[c.s]}">${c.n} ${c.s}</span>`).join("");
1157
+ const cards = shown.length ? SEV_ORDER.flatMap((sev) => shown.filter((f) => f.severity === sev)).map(findingCard).join("") : `<p class="empty">No issues found. \u2713</p>`;
1158
+ return `<!doctype html>
1159
+ <html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
1160
+ <title>${esc(title)}</title>
1161
+ <style>
1162
+ :root{color-scheme:dark}
1163
+ *{box-sizing:border-box}
1164
+ body{margin:0;background:#0b0e14;color:#e6e9ef;font:15px/1.55 system-ui,-apple-system,Segoe UI,Roboto,sans-serif}
1165
+ .wrap{max-width:860px;margin:0 auto;padding:32px 20px 80px}
1166
+ h1{font-size:24px;margin:0 0 4px} .sub{color:#8b93a7;margin:0 0 20px}
1167
+ .chips{display:flex;gap:8px;flex-wrap:wrap;margin:16px 0 28px}
1168
+ .chip{font-size:13px;padding:4px 10px;border-radius:999px;border:1px solid color-mix(in srgb,var(--c) 50%,transparent);color:var(--c);background:color-mix(in srgb,var(--c) 12%,transparent)}
1169
+ .stat{display:inline-block;margin-right:18px;color:#8b93a7;font-size:13px}
1170
+ .card{background:#11151f;border:1px solid #1e2533;border-radius:12px;padding:16px 18px;margin:14px 0}
1171
+ .card header{display:flex;align-items:center;gap:8px;flex-wrap:wrap}
1172
+ .card h3{font-size:16px;margin:6px 0 0;flex-basis:100%}
1173
+ .sev,.conf{font-size:11px;text-transform:uppercase;letter-spacing:.04em;font-weight:700;padding:3px 8px;border-radius:6px;color:var(--c);border:1px solid color-mix(in srgb,var(--c) 45%,transparent)}
1174
+ .meta{display:flex;gap:12px;margin:8px 0;font-size:13px}
1175
+ .route{color:#8ab4ff;font-family:ui-monospace,Menlo,monospace}
1176
+ .rule{color:#6b7280;font-family:ui-monospace,Menlo,monospace}
1177
+ details{margin:8px 0;border-top:1px solid #1e2533;padding-top:8px}
1178
+ summary{cursor:pointer;color:#aab2c5;font-size:13px}
1179
+ ol{margin:8px 0;padding-left:20px;color:#c7cdda}
1180
+ .ex{margin:6px 0;display:flex;flex-direction:column;gap:4px}
1181
+ code{background:#0b0e14;border:1px solid #1e2533;border-radius:6px;padding:4px 8px;font-size:12px;color:#9fb6e0;overflow-x:auto}
1182
+ .fix{margin:10px 0 0;color:#cbd5e1;font-size:14px}
1183
+ .oob{color:#fbbf24;font-size:13px;margin:8px 0 0}
1184
+ .shot{display:inline-block;margin-top:8px;color:#34d399;font-size:13px}
1185
+ .empty{color:#34d399;font-size:18px;text-align:center;padding:40px}
1186
+ footer{margin-top:40px;color:#5b6275;font-size:12px;text-align:center}
1187
+ </style></head>
1188
+ <body><div class="wrap">
1189
+ <h1>${esc(title)}</h1>
1190
+ <p class="sub">Autonomous QA scan of <code>${esc(report.stats.startUrl)}</code></p>
1191
+ <div>
1192
+ <span class="stat">${report.stats.pagesVisited} pages</span>
1193
+ <span class="stat">${report.stats.linksChecked} links checked</span>
1194
+ <span class="stat">${shown.length} findings</span>
1195
+ <span class="stat">${(report.stats.durationMs / 1e3).toFixed(1)}s</span>
1196
+ </div>
1197
+ <div class="chips">${chips || '<span class="chip" style="--c:#34d399">0 issues</span>'}</div>
1198
+ ${cards}
1199
+ <footer>Generated by sniff \xB7 ${esc(report.runAt)}</footer>
1200
+ </div></body></html>`;
1201
+ }
1202
+
1203
+ // src/crawl/index.ts
1204
+ var SEV_ORDER2 = ["critical", "high", "medium", "low", "info"];
1205
+ function formatReportText(report, opts = {}) {
1206
+ const shown = report.findings.filter((f) => opts.all || f.confidence !== "uncertain");
1207
+ const hidden = report.findings.length - shown.length;
1208
+ const lines = [];
1209
+ lines.push("");
1210
+ lines.push(` sniff crawl \u2014 ${report.stats.pagesVisited} pages, ${report.stats.linksChecked} links, ${(report.stats.durationMs / 1e3).toFixed(1)}s`);
1211
+ lines.push(` ${shown.length} finding${shown.length === 1 ? "" : "s"}${hidden > 0 ? ` (+${hidden} low-confidence hidden; use --all)` : ""}`);
1212
+ lines.push("");
1213
+ if (shown.length === 0) {
1214
+ lines.push(" No issues found. \u2713");
1215
+ lines.push("");
1216
+ return lines.join("\n");
1217
+ }
1218
+ const bySev = /* @__PURE__ */ new Map();
1219
+ for (const f of shown) {
1220
+ const arr = bySev.get(f.severity) ?? [];
1221
+ arr.push(f);
1222
+ bySev.set(f.severity, arr);
1223
+ }
1224
+ for (const sev of SEV_ORDER2) {
1225
+ const arr = bySev.get(sev);
1226
+ if (!arr || arr.length === 0) continue;
1227
+ lines.push(` ${sev.toUpperCase()} (${arr.length})`);
1228
+ for (const f of arr) {
1229
+ lines.push(` \u2022 [${f.confidence}] ${f.title}`);
1230
+ lines.push(` ${f.reproduction.route} (${f.ruleId})`);
1231
+ for (const s of f.reproduction.steps) lines.push(` - ${s}`);
1232
+ lines.push(` fix: ${f.suggestedFix}`);
1233
+ if (f.needsOutOfBandVerification) lines.push(` note: needs out-of-band verification (e.g. confirm the email/job actually completed)`);
1234
+ if (f.reproduction.screenshotPath) lines.push(` shot: ${f.reproduction.screenshotPath}`);
1235
+ lines.push("");
1236
+ }
1237
+ }
1238
+ return lines.join("\n");
1239
+ }
1240
+
1241
+ export {
1242
+ runCrawl,
1243
+ renderHtmlReport,
1244
+ formatReportText
1245
+ };
1246
+ //# sourceMappingURL=chunk-LJYT4MD5.js.map