sniff-qa 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. package/LICENSE +172 -0
  2. package/README.md +581 -0
  3. package/dist/accessibility-UNJB57T6.js +93 -0
  4. package/dist/accessibility-UNJB57T6.js.map +1 -0
  5. package/dist/anthropic-api-MRDZ7BJA.js +33 -0
  6. package/dist/anthropic-api-MRDZ7BJA.js.map +1 -0
  7. package/dist/chunk-623BAIU2.js +73 -0
  8. package/dist/chunk-623BAIU2.js.map +1 -0
  9. package/dist/chunk-CBDOJUXB.js +157 -0
  10. package/dist/chunk-CBDOJUXB.js.map +1 -0
  11. package/dist/chunk-IXDUD2UG.js +14 -0
  12. package/dist/chunk-IXDUD2UG.js.map +1 -0
  13. package/dist/chunk-MMISGY2Q.js +52 -0
  14. package/dist/chunk-MMISGY2Q.js.map +1 -0
  15. package/dist/chunk-ZM6MGWO4.js +49 -0
  16. package/dist/chunk-ZM6MGWO4.js.map +1 -0
  17. package/dist/ci-2MVD2ISE.js +52 -0
  18. package/dist/ci-2MVD2ISE.js.map +1 -0
  19. package/dist/claude-code-F722EIIC.js +42 -0
  20. package/dist/claude-code-F722EIIC.js.map +1 -0
  21. package/dist/claude-exploration-provider-QJH6IPYU.js +126 -0
  22. package/dist/claude-exploration-provider-QJH6IPYU.js.map +1 -0
  23. package/dist/cli/index.d.ts +1 -0
  24. package/dist/cli/index.js +72 -0
  25. package/dist/cli/index.js.map +1 -0
  26. package/dist/cross-reference-MHNPSLEN.js +218 -0
  27. package/dist/cross-reference-MHNPSLEN.js.map +1 -0
  28. package/dist/element-extractor-OZTFBVKZ.js +250 -0
  29. package/dist/element-extractor-OZTFBVKZ.js.map +1 -0
  30. package/dist/errors-RFEOR527.js +7 -0
  31. package/dist/errors-RFEOR527.js.map +1 -0
  32. package/dist/flakiness-OVC7KGN2.js +11 -0
  33. package/dist/flakiness-OVC7KGN2.js.map +1 -0
  34. package/dist/formatter-HC3LT3VH.js +146 -0
  35. package/dist/formatter-HC3LT3VH.js.map +1 -0
  36. package/dist/framework-detector-ISSM2Q2I.js +95 -0
  37. package/dist/framework-detector-ISSM2Q2I.js.map +1 -0
  38. package/dist/generator-OZY3HMJW.js +7 -0
  39. package/dist/generator-OZY3HMJW.js.map +1 -0
  40. package/dist/index.d.ts +212 -0
  41. package/dist/index.js +13 -0
  42. package/dist/index.js.map +1 -0
  43. package/dist/init-75MMIW4A.js +66 -0
  44. package/dist/init-75MMIW4A.js.map +1 -0
  45. package/dist/json-YDWEB33Q.js +8 -0
  46. package/dist/json-YDWEB33Q.js.map +1 -0
  47. package/dist/junit-GL44ATRR.js +52 -0
  48. package/dist/junit-GL44ATRR.js.map +1 -0
  49. package/dist/loader-QII5CZSX.js +161 -0
  50. package/dist/loader-QII5CZSX.js.map +1 -0
  51. package/dist/mcp/server.d.ts +3 -0
  52. package/dist/mcp/server.js +171 -0
  53. package/dist/mcp/server.js.map +1 -0
  54. package/dist/model-SRPWXU63.js +92 -0
  55. package/dist/model-SRPWXU63.js.map +1 -0
  56. package/dist/page-hooks-DOZWXF7Z.js +13 -0
  57. package/dist/page-hooks-DOZWXF7Z.js.map +1 -0
  58. package/dist/page-state-extractor-GYYLYRFR.js +75 -0
  59. package/dist/page-state-extractor-GYYLYRFR.js.map +1 -0
  60. package/dist/performance-FBUGBRB3.js +134 -0
  61. package/dist/performance-FBUGBRB3.js.map +1 -0
  62. package/dist/persistence-RHUFBQAY.js +86 -0
  63. package/dist/persistence-RHUFBQAY.js.map +1 -0
  64. package/dist/prompt-builder-D3FBH534.js +53 -0
  65. package/dist/prompt-builder-D3FBH534.js.map +1 -0
  66. package/dist/provider-7IHXYR6V.js +13 -0
  67. package/dist/provider-7IHXYR6V.js.map +1 -0
  68. package/dist/registry-NB5CZB6W.js +43 -0
  69. package/dist/registry-NB5CZB6W.js.map +1 -0
  70. package/dist/repo-analyzer-4OURSITY.js +49 -0
  71. package/dist/repo-analyzer-4OURSITY.js.map +1 -0
  72. package/dist/report-E2JZMQED.js +61 -0
  73. package/dist/report-E2JZMQED.js.map +1 -0
  74. package/dist/response-parser-PUGNWF7S.js +46 -0
  75. package/dist/response-parser-PUGNWF7S.js.map +1 -0
  76. package/dist/route-discoverer-QBZCRQLJ.js +304 -0
  77. package/dist/route-discoverer-QBZCRQLJ.js.map +1 -0
  78. package/dist/runner-MS2SNTMR.js +153 -0
  79. package/dist/runner-MS2SNTMR.js.map +1 -0
  80. package/dist/runner-Z4I2YVVM.js +237 -0
  81. package/dist/runner-Z4I2YVVM.js.map +1 -0
  82. package/dist/source-D5KLH46F.js +896 -0
  83. package/dist/source-D5KLH46F.js.map +1 -0
  84. package/dist/unified-CQU7PSNJ.js +275 -0
  85. package/dist/unified-CQU7PSNJ.js.map +1 -0
  86. package/dist/update-baselines-MDTCFO2U.js +71 -0
  87. package/dist/update-baselines-MDTCFO2U.js.map +1 -0
  88. package/dist/visual-ZSQPDE7A.js +125 -0
  89. package/dist/visual-ZSQPDE7A.js.map +1 -0
  90. package/dist/workflow-template-3KFPCVIC.js +119 -0
  91. package/dist/workflow-template-3KFPCVIC.js.map +1 -0
  92. package/package.json +95 -0
@@ -0,0 +1,896 @@
1
+ // src/scanners/source/index.ts
2
+ import fg2 from "fast-glob";
3
+ import { readFile as readFile3, access as access2 } from "fs/promises";
4
+ import { dirname as dirname3, join as join2, relative as relative2 } from "path";
5
+ import { performance } from "perf_hooks";
6
+
7
+ // src/scanners/source/rules/placeholder.ts
8
+ var placeholderRules = [
9
+ {
10
+ id: "placeholder-lorem",
11
+ severity: "high",
12
+ description: "Lorem ipsum placeholder text detected",
13
+ pattern: /lorem\s+ipsum/i,
14
+ include: ["**/*.{ts,tsx,js,jsx,html,css}"]
15
+ },
16
+ {
17
+ id: "placeholder-todo",
18
+ severity: "medium",
19
+ description: "TODO comment found",
20
+ pattern: /\bTODO\b/,
21
+ include: ["**/*.{ts,tsx,js,jsx}"]
22
+ },
23
+ {
24
+ id: "placeholder-fixme",
25
+ severity: "high",
26
+ description: "FIXME comment found",
27
+ pattern: /\bFIXME\b/,
28
+ include: ["**/*.{ts,tsx,js,jsx}"]
29
+ },
30
+ {
31
+ id: "placeholder-tbd",
32
+ severity: "medium",
33
+ description: "TBD placeholder found",
34
+ pattern: /\bTBD\b/,
35
+ include: ["**/*.{ts,tsx,js,jsx}"]
36
+ }
37
+ ];
38
+
39
+ // src/scanners/source/rules/debug.ts
40
+ var debugRules = [
41
+ {
42
+ id: "debug-console-log",
43
+ severity: "medium",
44
+ description: "Console logging statement detected",
45
+ pattern: /\bconsole\.(log|debug|info)\b/,
46
+ include: ["**/*.{ts,tsx,js,jsx}"],
47
+ exclude: ["**/*.test.*", "**/*.spec.*"]
48
+ },
49
+ {
50
+ id: "debug-debugger",
51
+ severity: "high",
52
+ description: "Debugger statement detected",
53
+ pattern: /\bdebugger\b/,
54
+ include: ["**/*.{ts,tsx,js,jsx}"]
55
+ }
56
+ ];
57
+
58
+ // src/scanners/source/rules/hardcoded.ts
59
+ var hardcodedRules = [
60
+ {
61
+ id: "hardcoded-localhost",
62
+ severity: "medium",
63
+ description: "Hardcoded localhost URL detected",
64
+ pattern: /https?:\/\/localhost[:/]/,
65
+ include: ["**/*.{ts,tsx,js,jsx}"],
66
+ exclude: ["**/*.test.*", "**/*.spec.*", "**/*.config.*"]
67
+ },
68
+ {
69
+ id: "hardcoded-127",
70
+ severity: "medium",
71
+ description: "Hardcoded 127.0.0.1 URL detected",
72
+ pattern: /https?:\/\/127\.0\.0\.1[:/]/,
73
+ include: ["**/*.{ts,tsx,js,jsx}"],
74
+ exclude: ["**/*.test.*", "**/*.spec.*", "**/*.config.*"]
75
+ }
76
+ ];
77
+
78
+ // src/scanners/source/rules/imports.ts
79
+ var importRules = [
80
+ {
81
+ id: "broken-import",
82
+ severity: "medium",
83
+ description: "Potentially broken relative import",
84
+ pattern: /from\s+['"]\.\.?\//,
85
+ include: ["**/*.{ts,tsx,js,jsx}"]
86
+ }
87
+ ];
88
+
89
+ // src/scanners/source/rules/dead-links.ts
90
+ import { readFile, access } from "fs/promises";
91
+ import { dirname, join, resolve, extname } from "path";
92
+ var defaultDeadLinkConfig = {
93
+ checkExternal: true,
94
+ timeout: 5e3,
95
+ retries: 2,
96
+ ignorePatterns: [],
97
+ followRedirects: true,
98
+ maxConcurrent: 10
99
+ };
100
+ var MD_LINK_RE = /(?<!!)\[(?:[^\]]*)\]\(([^)]+)\)/g;
101
+ var HTML_ATTR_RE = /(?:href|src|action)=["']([^"']+)["']/gi;
102
+ var JSX_ATTR_RE = /(?:href|src|action)=\{["'`]([^"'`]+)["'`]\}/gi;
103
+ var PLAIN_URL_RE = /https?:\/\/[^\s)"'`>\]]+/g;
104
+ var LINK_FILE_EXTENSIONS = /* @__PURE__ */ new Set([
105
+ ".md",
106
+ ".mdx",
107
+ ".html",
108
+ ".htm",
109
+ ".jsx",
110
+ ".tsx",
111
+ ".js",
112
+ ".ts",
113
+ ".vue",
114
+ ".svelte",
115
+ ".astro"
116
+ ]);
117
+ var SKIP_PATTERNS = [
118
+ /^\{\{/,
119
+ // template variables {{ }}
120
+ /^\$\{/,
121
+ // template literals ${ }
122
+ /^mailto:/i,
123
+ /^tel:/i,
124
+ /^javascript:/i,
125
+ /^data:/i,
126
+ /^#$/,
127
+ // bare hash
128
+ /^\/\//
129
+ // protocol-relative (ambiguous)
130
+ ];
131
+ function classifyLink(url) {
132
+ if (SKIP_PATTERNS.some((p) => p.test(url))) return "skip";
133
+ if (url.startsWith("#")) return "anchor";
134
+ if (/^https?:\/\//i.test(url)) return "external";
135
+ return "internal";
136
+ }
137
+ function extractLinks(content, filePath) {
138
+ const ext = extname(filePath).toLowerCase();
139
+ if (!LINK_FILE_EXTENSIONS.has(ext)) return [];
140
+ const lines = content.split("\n");
141
+ const links = [];
142
+ const seen = /* @__PURE__ */ new Set();
143
+ for (let lineIdx = 0; lineIdx < lines.length; lineIdx++) {
144
+ const line = lines[lineIdx];
145
+ const patterns = [MD_LINK_RE, HTML_ATTR_RE, JSX_ATTR_RE, PLAIN_URL_RE];
146
+ for (const pattern of patterns) {
147
+ const re = new RegExp(pattern.source, pattern.flags);
148
+ let match;
149
+ while ((match = re.exec(line)) !== null) {
150
+ const url = (match[1] ?? match[0]).trim();
151
+ if (!url) continue;
152
+ const dedupeKey = `${lineIdx}:${url}`;
153
+ if (seen.has(dedupeKey)) continue;
154
+ seen.add(dedupeKey);
155
+ const type = classifyLink(url);
156
+ if (type === "skip") continue;
157
+ links.push({
158
+ url,
159
+ line: lineIdx + 1,
160
+ column: (match.index ?? 0) + 1,
161
+ snippet: line.trim(),
162
+ type
163
+ });
164
+ }
165
+ }
166
+ }
167
+ return links;
168
+ }
169
+ async function fileExists(filePath) {
170
+ try {
171
+ await access(filePath);
172
+ return true;
173
+ } catch {
174
+ return false;
175
+ }
176
+ }
177
+ async function validateInternalLink(url, fromFile, rootDir) {
178
+ const [pathPart, anchor] = url.split("#");
179
+ if (!pathPart) {
180
+ return { valid: true };
181
+ }
182
+ const resolved = pathPart.startsWith("/") ? join(rootDir, pathPart) : resolve(dirname(fromFile), pathPart);
183
+ if (await fileExists(resolved)) {
184
+ if (anchor) {
185
+ return validateAnchor(resolved, anchor);
186
+ }
187
+ return { valid: true };
188
+ }
189
+ const extensions = [".md", ".mdx", ".html", ".htm", ".tsx", ".ts", ".jsx", ".js"];
190
+ for (const ext of extensions) {
191
+ if (await fileExists(resolved + ext)) return { valid: true };
192
+ }
193
+ for (const idx of ["index.md", "index.html", "index.tsx", "index.ts", "README.md"]) {
194
+ if (await fileExists(join(resolved, idx))) return { valid: true };
195
+ }
196
+ return { valid: false, reason: `File not found: ${pathPart}` };
197
+ }
198
+ async function validateAnchor(filePath, anchor) {
199
+ try {
200
+ const content = await readFile(filePath, "utf-8");
201
+ const normalizedAnchor = anchor.toLowerCase();
202
+ const headingRe = /^#{1,6}\s+(.+)$/gm;
203
+ let match;
204
+ while ((match = headingRe.exec(content)) !== null) {
205
+ const slug = match[1].toLowerCase().replace(/[^\w\s-]/g, "").replace(/\s+/g, "-").replace(/-+/g, "-").trim();
206
+ if (slug === normalizedAnchor) return { valid: true };
207
+ }
208
+ const idRe = /id=["']([^"']+)["']/gi;
209
+ while ((match = idRe.exec(content)) !== null) {
210
+ if (match[1].toLowerCase() === normalizedAnchor) return { valid: true };
211
+ }
212
+ const nameRe = /name=["']([^"']+)["']/gi;
213
+ while ((match = nameRe.exec(content)) !== null) {
214
+ if (match[1].toLowerCase() === normalizedAnchor) return { valid: true };
215
+ }
216
+ return { valid: false, reason: `Anchor #${anchor} not found in ${filePath}` };
217
+ } catch {
218
+ return { valid: true };
219
+ }
220
+ }
221
+ async function validateExternalLink(url, config) {
222
+ let lastError;
223
+ for (let attempt = 0; attempt <= config.retries; attempt++) {
224
+ try {
225
+ const controller = new AbortController();
226
+ const timer = setTimeout(() => controller.abort(), config.timeout);
227
+ const response = await fetch(url, {
228
+ method: "HEAD",
229
+ signal: controller.signal,
230
+ redirect: config.followRedirects ? "follow" : "manual",
231
+ headers: {
232
+ "User-Agent": "sniff-qa/0.2.0 (link-checker)"
233
+ }
234
+ });
235
+ clearTimeout(timer);
236
+ if (response.ok) {
237
+ return { valid: true, status: response.status };
238
+ }
239
+ if (response.status === 405 || response.status === 403) {
240
+ const getController = new AbortController();
241
+ const getTimer = setTimeout(() => getController.abort(), config.timeout);
242
+ const getResponse = await fetch(url, {
243
+ method: "GET",
244
+ signal: getController.signal,
245
+ redirect: config.followRedirects ? "follow" : "manual",
246
+ headers: {
247
+ "User-Agent": "sniff-qa/0.2.0 (link-checker)"
248
+ }
249
+ });
250
+ clearTimeout(getTimer);
251
+ if (getResponse.ok) {
252
+ return { valid: true, status: getResponse.status };
253
+ }
254
+ return {
255
+ valid: false,
256
+ status: getResponse.status,
257
+ reason: `HTTP ${getResponse.status}`
258
+ };
259
+ }
260
+ return {
261
+ valid: false,
262
+ status: response.status,
263
+ reason: `HTTP ${response.status}`
264
+ };
265
+ } catch (err) {
266
+ if (err instanceof DOMException && err.name === "AbortError") {
267
+ lastError = `Timeout after ${config.timeout}ms`;
268
+ } else if (err instanceof Error) {
269
+ lastError = err.message;
270
+ } else {
271
+ lastError = "Unknown error";
272
+ }
273
+ }
274
+ }
275
+ return { valid: false, reason: lastError ?? "Request failed" };
276
+ }
277
+ function getSeverity(link, reason) {
278
+ if (link.type === "internal") return "high";
279
+ if (link.type === "anchor") return "medium";
280
+ if (reason?.includes("HTTP 404") || reason?.includes("HTTP 410")) return "medium";
281
+ if (reason?.includes("Timeout")) return "low";
282
+ return "medium";
283
+ }
284
+ async function scanFileForDeadLinks(filePath, relPath, content, rootDir, config) {
285
+ const links = extractLinks(content, filePath);
286
+ if (links.length === 0) return [];
287
+ const findings = [];
288
+ const shouldIgnore = (url) => config.ignorePatterns.some((pattern) => {
289
+ try {
290
+ return new RegExp(pattern).test(url);
291
+ } catch {
292
+ return url.includes(pattern);
293
+ }
294
+ });
295
+ const internalLinks = links.filter((l) => l.type === "internal" || l.type === "anchor");
296
+ for (const link of internalLinks) {
297
+ if (shouldIgnore(link.url)) continue;
298
+ if (link.type === "anchor") {
299
+ const result2 = await validateAnchor(filePath, link.url.slice(1));
300
+ if (!result2.valid) {
301
+ findings.push({
302
+ ruleId: "dead-link-anchor",
303
+ severity: getSeverity(link, result2.reason),
304
+ message: result2.reason ?? `Broken anchor: ${link.url}`,
305
+ filePath: relPath,
306
+ line: link.line,
307
+ column: link.column,
308
+ snippet: link.snippet
309
+ });
310
+ }
311
+ continue;
312
+ }
313
+ const result = await validateInternalLink(link.url, filePath, rootDir);
314
+ if (!result.valid) {
315
+ findings.push({
316
+ ruleId: "dead-link-internal",
317
+ severity: getSeverity(link, result.reason),
318
+ message: result.reason ?? `Broken internal link: ${link.url}`,
319
+ filePath: relPath,
320
+ line: link.line,
321
+ column: link.column,
322
+ snippet: link.snippet
323
+ });
324
+ }
325
+ }
326
+ if (config.checkExternal) {
327
+ const externalLinks = links.filter((l) => l.type === "external" && !shouldIgnore(l.url));
328
+ const uniqueUrls = /* @__PURE__ */ new Map();
329
+ for (const link of externalLinks) {
330
+ const existing = uniqueUrls.get(link.url);
331
+ if (existing) {
332
+ existing.push(link);
333
+ } else {
334
+ uniqueUrls.set(link.url, [link]);
335
+ }
336
+ }
337
+ const entries = [...uniqueUrls.entries()];
338
+ for (let i = 0; i < entries.length; i += config.maxConcurrent) {
339
+ const batch = entries.slice(i, i + config.maxConcurrent);
340
+ const results = await Promise.all(
341
+ batch.map(async ([url, occurrences]) => {
342
+ const result = await validateExternalLink(url, config);
343
+ return { url, occurrences, result };
344
+ })
345
+ );
346
+ for (const { occurrences, result } of results) {
347
+ if (!result.valid) {
348
+ const link = occurrences[0];
349
+ findings.push({
350
+ ruleId: "dead-link-external",
351
+ severity: getSeverity(link, result.reason),
352
+ message: result.reason ?? `Broken external link: ${link.url}`,
353
+ filePath: relPath,
354
+ line: link.line,
355
+ column: link.column,
356
+ snippet: link.snippet
357
+ });
358
+ }
359
+ }
360
+ }
361
+ }
362
+ return findings;
363
+ }
364
+
365
+ // src/scanners/source/rules/api-endpoints.ts
366
+ import { readFile as readFile2 } from "fs/promises";
367
+ import { basename, relative } from "path";
368
+ import fg from "fast-glob";
369
+ var defaultApiEndpointsConfig = {
370
+ enabled: true,
371
+ checkErrorHandling: true,
372
+ checkValidation: true,
373
+ checkAuth: true,
374
+ checkSecrets: true,
375
+ frameworks: []
376
+ };
377
+ var EXPRESS_ROUTE_RE = /\b(?:app|router|server|fastify)\.(get|post|put|delete|patch|all|options|head)\s*\(\s*['"`]([^'"`]+)['"`]/gi;
378
+ var HONO_ROUTE_RE = /\bnew\s+Hono\b/;
379
+ var TRPC_ROUTER_RE = /\b(\w+)\s*:\s*(?:publicProcedure|protectedProcedure|procedure)\s*\.\s*(query|mutation|subscription)\b/gi;
380
+ var GRAPHQL_TYPE_RE = /\btype\s+(Query|Mutation|Subscription)\s*\{([^}]+)\}/gs;
381
+ var GRAPHQL_FIELD_RE = /^\s*(\w+)/gm;
382
+ var FILE_ROUTE_PATTERNS = [
383
+ // Next.js App Router: app/**/route.ts
384
+ {
385
+ framework: "nextjs-app",
386
+ glob: "**/app/**/route.{ts,tsx,js,jsx}",
387
+ extractRoute: (filePath, rootDir) => {
388
+ const rel = relative(rootDir, filePath);
389
+ const match = rel.match(/app\/(.+)\/route\.\w+$/);
390
+ if (!match) return null;
391
+ const routePath = "/" + match[1].replace(/\[\.{3}(\w+)\]/g, ":$1*").replace(/\[(\w+)\]/g, ":$1");
392
+ return { method: "ALL", path: routePath };
393
+ }
394
+ },
395
+ // Next.js Pages Router: pages/api/**/*.ts
396
+ {
397
+ framework: "nextjs-pages",
398
+ glob: "**/pages/api/**/*.{ts,tsx,js,jsx}",
399
+ extractRoute: (filePath, rootDir) => {
400
+ const rel = relative(rootDir, filePath);
401
+ const match = rel.match(/pages\/api\/(.+)\.\w+$/);
402
+ if (!match) return null;
403
+ let routePath = "/api/" + match[1].replace(/\[\.{3}(\w+)\]/g, ":$1*").replace(/\[(\w+)\]/g, ":$1");
404
+ if (routePath.endsWith("/index")) {
405
+ routePath = routePath.replace(/\/index$/, "");
406
+ }
407
+ return { method: "ALL", path: routePath || "/api" };
408
+ }
409
+ },
410
+ // SvelteKit: routes/**/+server.ts
411
+ {
412
+ framework: "sveltekit",
413
+ glob: "**/routes/**/+server.{ts,js}",
414
+ extractRoute: (filePath, rootDir) => {
415
+ const rel = relative(rootDir, filePath);
416
+ const match = rel.match(/routes\/(.+)\/\+server\.\w+$/);
417
+ if (!match) return null;
418
+ const routePath = "/" + match[1].replace(/\[\.{3}(\w+)\]/g, ":$1*").replace(/\[(\w+)\]/g, ":$1");
419
+ return { method: "ALL", path: routePath };
420
+ }
421
+ }
422
+ ];
423
+ var VALIDATION_PATTERNS = [
424
+ /\bzod\b/,
425
+ /\b(?:z\.object|z\.string|z\.number)\b/,
426
+ /\bjoi\b/,
427
+ /\bJoi\./,
428
+ /\byup\b/,
429
+ /\byup\./,
430
+ /\bvalidate\b/i,
431
+ /\bvalidator\b/i,
432
+ /\bclass-validator\b/,
433
+ /\bIsString\b/,
434
+ /\bIsNumber\b/,
435
+ /\bsuperStruct\b/,
436
+ /\bvalibot\b/,
437
+ /\bparsedBody\b/i,
438
+ /\bparseBody\b/i
439
+ ];
440
+ var AUTH_PATTERNS = [
441
+ /\bauth\b/i,
442
+ /\bauthenticate\b/i,
443
+ /\bauthorize\b/i,
444
+ /\bisAuthenticated\b/,
445
+ /\brequireAuth\b/i,
446
+ /\bpassport\b/i,
447
+ /\bjwt\b/i,
448
+ /\bbearer\b/i,
449
+ /\bsession\b/i,
450
+ /\bmiddleware\b/i,
451
+ /\bprotectedProcedure\b/,
452
+ /\bwithAuth\b/i,
453
+ /\bgetServerSession\b/,
454
+ /\buseSession\b/
455
+ ];
456
+ var ERROR_HANDLING_PATTERNS = [
457
+ /\btry\s*\{/,
458
+ /\bcatch\s*\(/,
459
+ /\.catch\(/,
460
+ /\berrorHandler\b/i,
461
+ /\bnext\s*\(\s*(?:err|error|new\s+Error)\b/,
462
+ /\bthrow\b/
463
+ ];
464
+ var SECRET_PATTERNS = [
465
+ { re: /(?:api[_-]?key|apikey)\s*[:=]\s*['"`][A-Za-z0-9_\-]{16,}['"`]/i, label: "API key" },
466
+ { re: /(?:secret|password|passwd|pwd)\s*[:=]\s*['"`][^'"`]{8,}['"`]/i, label: "secret/password" },
467
+ { re: /(?:token)\s*[:=]\s*['"`][A-Za-z0-9_\-]{16,}['"`]/i, label: "token" },
468
+ { re: /(?:bearer)\s+[A-Za-z0-9_\-\.]{20,}/i, label: "bearer token" },
469
+ { re: /(?:sk_live|pk_live|sk_test|pk_test)_[A-Za-z0-9]{10,}/i, label: "Stripe key" },
470
+ { re: /(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{20,}/i, label: "GitHub token" }
471
+ ];
472
+ function checkEndpointIssues(content, endpoint, config) {
473
+ const issues = [];
474
+ const lines = content.split("\n");
475
+ const startLine = Math.max(0, endpoint.line - 2);
476
+ const endLine = Math.min(lines.length, endpoint.line + 50);
477
+ const routeBlock = lines.slice(startLine, endLine).join("\n");
478
+ if (config.checkErrorHandling) {
479
+ const hasErrorHandling = ERROR_HANDLING_PATTERNS.some((p) => p.test(routeBlock));
480
+ if (!hasErrorHandling) {
481
+ issues.push({
482
+ ruleId: "api-no-error-handling",
483
+ severity: "medium",
484
+ message: `Endpoint ${endpoint.method} ${endpoint.path} has no error handling (no try/catch or error middleware)`,
485
+ filePath: endpoint.filePath,
486
+ line: endpoint.line,
487
+ column: 1,
488
+ snippet: lines[endpoint.line - 1]?.trim() ?? ""
489
+ });
490
+ }
491
+ }
492
+ if (config.checkValidation) {
493
+ const mutationMethods = ["POST", "PUT", "PATCH", "MUTATION", "ALL"];
494
+ if (mutationMethods.includes(endpoint.method.toUpperCase())) {
495
+ const hasValidation = VALIDATION_PATTERNS.some((p) => p.test(routeBlock));
496
+ if (!hasValidation) {
497
+ issues.push({
498
+ ruleId: "api-no-validation",
499
+ severity: "medium",
500
+ message: `Endpoint ${endpoint.method} ${endpoint.path} has no input validation`,
501
+ filePath: endpoint.filePath,
502
+ line: endpoint.line,
503
+ column: 1,
504
+ snippet: lines[endpoint.line - 1]?.trim() ?? ""
505
+ });
506
+ }
507
+ }
508
+ }
509
+ if (config.checkAuth) {
510
+ const publicPaths = ["/health", "/ping", "/status", "/favicon", "/robots.txt", "/sitemap"];
511
+ const isLikelyPublic = publicPaths.some((p) => endpoint.path.includes(p)) || endpoint.path === "/" || endpoint.method === "OPTIONS";
512
+ if (!isLikelyPublic) {
513
+ const hasAuth = AUTH_PATTERNS.some((p) => p.test(routeBlock));
514
+ if (!hasAuth) {
515
+ issues.push({
516
+ ruleId: "api-no-auth",
517
+ severity: "low",
518
+ message: `Endpoint ${endpoint.method} ${endpoint.path} has no visible auth middleware`,
519
+ filePath: endpoint.filePath,
520
+ line: endpoint.line,
521
+ column: 1,
522
+ snippet: lines[endpoint.line - 1]?.trim() ?? ""
523
+ });
524
+ }
525
+ }
526
+ }
527
+ if (config.checkSecrets) {
528
+ for (let i = startLine; i < endLine; i++) {
529
+ const line = lines[i];
530
+ for (const { re, label } of SECRET_PATTERNS) {
531
+ if (re.test(line)) {
532
+ issues.push({
533
+ ruleId: "api-hardcoded-secret",
534
+ severity: "critical",
535
+ message: `Hardcoded ${label} detected in route handler for ${endpoint.method} ${endpoint.path}`,
536
+ filePath: endpoint.filePath,
537
+ line: i + 1,
538
+ column: 1,
539
+ snippet: line.trim()
540
+ });
541
+ }
542
+ }
543
+ }
544
+ }
545
+ return issues;
546
+ }
547
+ function extractInlineEndpoints(content, relPath) {
548
+ const endpoints = [];
549
+ const lines = content.split("\n");
550
+ for (let lineIdx = 0; lineIdx < lines.length; lineIdx++) {
551
+ const line = lines[lineIdx];
552
+ const re = new RegExp(EXPRESS_ROUTE_RE.source, EXPRESS_ROUTE_RE.flags);
553
+ let match;
554
+ while ((match = re.exec(line)) !== null) {
555
+ const method = match[1].toUpperCase();
556
+ const path = match[2];
557
+ let framework = "express";
558
+ if (HONO_ROUTE_RE.test(content)) framework = "hono";
559
+ else if (/\bfastify\b/i.test(content)) framework = "fastify";
560
+ endpoints.push({
561
+ method,
562
+ path,
563
+ framework,
564
+ filePath: relPath,
565
+ line: lineIdx + 1,
566
+ snippet: line.trim()
567
+ });
568
+ }
569
+ }
570
+ for (let lineIdx = 0; lineIdx < lines.length; lineIdx++) {
571
+ const line = lines[lineIdx];
572
+ const re = new RegExp(TRPC_ROUTER_RE.source, TRPC_ROUTER_RE.flags);
573
+ let match;
574
+ while ((match = re.exec(line)) !== null) {
575
+ endpoints.push({
576
+ method: match[2].toUpperCase(),
577
+ path: match[1],
578
+ framework: "trpc",
579
+ filePath: relPath,
580
+ line: lineIdx + 1,
581
+ snippet: line.trim()
582
+ });
583
+ }
584
+ }
585
+ const gqlRe = new RegExp(GRAPHQL_TYPE_RE.source, GRAPHQL_TYPE_RE.flags);
586
+ let gqlMatch;
587
+ while ((gqlMatch = gqlRe.exec(content)) !== null) {
588
+ const typeName = gqlMatch[1];
589
+ const body = gqlMatch[2];
590
+ const fieldRe = new RegExp(GRAPHQL_FIELD_RE.source, GRAPHQL_FIELD_RE.flags);
591
+ let fieldMatch;
592
+ while ((fieldMatch = fieldRe.exec(body)) !== null) {
593
+ const fieldName = fieldMatch[1];
594
+ if (!fieldName || fieldName.startsWith("#")) continue;
595
+ const beforeField = content.indexOf(fieldName);
596
+ const lineNum = beforeField >= 0 ? content.slice(0, beforeField).split("\n").length : 1;
597
+ endpoints.push({
598
+ method: typeName.toUpperCase(),
599
+ path: fieldName,
600
+ framework: "graphql",
601
+ filePath: relPath,
602
+ line: lineNum,
603
+ snippet: fieldName
604
+ });
605
+ }
606
+ }
607
+ return endpoints;
608
+ }
609
+ function extractExportedHandlers(content, relPath, framework) {
610
+ const endpoints = [];
611
+ const lines = content.split("\n");
612
+ const EXPORT_HANDLER_RE = /export\s+(?:async\s+)?function\s+(GET|POST|PUT|DELETE|PATCH|HEAD|OPTIONS)\b/g;
613
+ for (let lineIdx = 0; lineIdx < lines.length; lineIdx++) {
614
+ const line = lines[lineIdx];
615
+ const re = new RegExp(EXPORT_HANDLER_RE.source, EXPORT_HANDLER_RE.flags);
616
+ let match;
617
+ while ((match = re.exec(line)) !== null) {
618
+ endpoints.push({
619
+ method: match[1],
620
+ path: relPath,
621
+ framework,
622
+ filePath: relPath,
623
+ line: lineIdx + 1,
624
+ snippet: line.trim()
625
+ });
626
+ }
627
+ }
628
+ const EXPORT_CONST_RE = /export\s+const\s+(GET|POST|PUT|DELETE|PATCH|HEAD|OPTIONS)\s*=/g;
629
+ for (let lineIdx = 0; lineIdx < lines.length; lineIdx++) {
630
+ const line = lines[lineIdx];
631
+ const re = new RegExp(EXPORT_CONST_RE.source, EXPORT_CONST_RE.flags);
632
+ let match;
633
+ while ((match = re.exec(line)) !== null) {
634
+ endpoints.push({
635
+ method: match[1],
636
+ path: relPath,
637
+ framework,
638
+ filePath: relPath,
639
+ line: lineIdx + 1,
640
+ snippet: line.trim()
641
+ });
642
+ }
643
+ }
644
+ return endpoints;
645
+ }
646
+ async function scanForApiEndpoints(rootDir, config, exclude) {
647
+ const allEndpoints = [];
648
+ const allFindings = [];
649
+ for (const pattern of FILE_ROUTE_PATTERNS) {
650
+ if (config.frameworks.length > 0 && !config.frameworks.includes(pattern.framework)) {
651
+ continue;
652
+ }
653
+ const files = await fg(pattern.glob, {
654
+ cwd: rootDir,
655
+ ignore: exclude,
656
+ absolute: true
657
+ });
658
+ for (const filePath of files) {
659
+ const routeInfo = pattern.extractRoute(filePath, rootDir);
660
+ if (!routeInfo) continue;
661
+ const content = await readFile2(filePath, "utf-8");
662
+ const relPath = relative(rootDir, filePath);
663
+ const handlers = extractExportedHandlers(content, relPath, pattern.framework);
664
+ if (handlers.length > 0) {
665
+ for (const handler of handlers) {
666
+ handler.path = routeInfo.path;
667
+ allEndpoints.push(handler);
668
+ const issues = checkEndpointIssues(content, handler, config);
669
+ allFindings.push(...issues);
670
+ }
671
+ } else {
672
+ const endpoint = {
673
+ method: routeInfo.method,
674
+ path: routeInfo.path,
675
+ framework: pattern.framework,
676
+ filePath: relPath,
677
+ line: 1,
678
+ snippet: basename(filePath)
679
+ };
680
+ allEndpoints.push(endpoint);
681
+ const issues = checkEndpointIssues(content, endpoint, config);
682
+ allFindings.push(...issues);
683
+ }
684
+ }
685
+ }
686
+ const sourceGlobs = ["**/*.{ts,tsx,js,jsx}"];
687
+ const sourceFiles = await fg(sourceGlobs, {
688
+ cwd: rootDir,
689
+ ignore: [...exclude, "**/node_modules/**", "**/*.test.*", "**/*.spec.*"],
690
+ absolute: true
691
+ });
692
+ for (const filePath of sourceFiles) {
693
+ const content = await readFile2(filePath, "utf-8");
694
+ const relPath = relative(rootDir, filePath);
695
+ const endpoints = extractInlineEndpoints(content, relPath);
696
+ for (const endpoint of endpoints) {
697
+ if (config.frameworks.length > 0 && !config.frameworks.includes(endpoint.framework)) {
698
+ continue;
699
+ }
700
+ allEndpoints.push(endpoint);
701
+ const issues = checkEndpointIssues(content, endpoint, config);
702
+ allFindings.push(...issues);
703
+ }
704
+ }
705
+ if (allEndpoints.length > 0) {
706
+ const byFramework = /* @__PURE__ */ new Map();
707
+ for (const ep of allEndpoints) {
708
+ byFramework.set(ep.framework, (byFramework.get(ep.framework) ?? 0) + 1);
709
+ }
710
+ const summary = [...byFramework.entries()].map(([fw, count]) => `${fw}: ${count}`).join(", ");
711
+ allFindings.push({
712
+ ruleId: "api-endpoints-discovered",
713
+ severity: "info",
714
+ message: `Discovered ${allEndpoints.length} API endpoints (${summary})`,
715
+ filePath: "",
716
+ line: 0,
717
+ column: 0,
718
+ snippet: ""
719
+ });
720
+ }
721
+ return { endpoints: allEndpoints, findings: allFindings };
722
+ }
723
+
724
+ // src/scanners/source/rules/index.ts
725
+ var allRules = [
726
+ ...placeholderRules,
727
+ ...debugRules,
728
+ ...hardcodedRules,
729
+ ...importRules
730
+ ];
731
+
732
+ // src/scanners/source/index.ts
733
+ var IMPORT_PATH_RE = /from\s+['"](\.\.?\/[^'"]+)['"]/;
734
+ var RESOLVE_EXTENSIONS = [".ts", ".tsx", ".js", ".jsx"];
735
+ var INDEX_FILES = RESOLVE_EXTENSIONS.map((ext) => `index${ext}`);
736
+ async function fileExists2(filePath) {
737
+ try {
738
+ await access2(filePath);
739
+ return true;
740
+ } catch {
741
+ return false;
742
+ }
743
+ }
744
+ async function resolveImportExists(importPath, fromDir) {
745
+ const resolved = join2(fromDir, importPath);
746
+ if (await fileExists2(resolved)) return true;
747
+ if (resolved.endsWith(".js") || resolved.endsWith(".jsx")) {
748
+ const withoutExt = resolved.replace(/\.jsx?$/, "");
749
+ for (const ext of RESOLVE_EXTENSIONS) {
750
+ if (await fileExists2(withoutExt + ext)) return true;
751
+ }
752
+ }
753
+ for (const ext of RESOLVE_EXTENSIONS) {
754
+ if (await fileExists2(resolved + ext)) return true;
755
+ }
756
+ for (const indexFile of INDEX_FILES) {
757
+ if (await fileExists2(join2(resolved, indexFile))) return true;
758
+ }
759
+ return false;
760
+ }
761
+ var SourceScanner = class {
762
+ name = "source";
763
+ async scan(ctx) {
764
+ const start = performance.now();
765
+ const enabledRules = this.resolveRules(ctx);
766
+ const includePatterns = /* @__PURE__ */ new Set();
767
+ for (const rule of enabledRules) {
768
+ if (rule.include) {
769
+ for (const pattern of rule.include) {
770
+ includePatterns.add(pattern);
771
+ }
772
+ }
773
+ }
774
+ const globs = includePatterns.size > 0 ? [...includePatterns] : ctx.config.include;
775
+ const files = await fg2(globs, {
776
+ cwd: ctx.rootDir,
777
+ ignore: ctx.config.exclude,
778
+ absolute: true
779
+ });
780
+ const findings = [];
781
+ for (let i = 0; i < files.length; i += 50) {
782
+ const batch = files.slice(i, i + 50);
783
+ const batchResults = await Promise.all(
784
+ batch.map(
785
+ (filePath) => this.scanFile(filePath, enabledRules, ctx.rootDir)
786
+ )
787
+ );
788
+ for (const result of batchResults) {
789
+ findings.push(...result);
790
+ }
791
+ }
792
+ const deadLinksEnabled = ctx.config.rules["dead-link-internal"] !== "off" && ctx.config.rules["dead-link-internal"] !== false;
793
+ if (deadLinksEnabled) {
794
+ const dlConfig = {
795
+ ...defaultDeadLinkConfig,
796
+ ...ctx.config.deadLinks
797
+ };
798
+ const linkGlobs = ["**/*.{md,mdx,html,htm,jsx,tsx,js,ts,vue,svelte,astro}"];
799
+ const linkFiles = await fg2(linkGlobs, {
800
+ cwd: ctx.rootDir,
801
+ ignore: ctx.config.exclude,
802
+ absolute: true
803
+ });
804
+ for (let i = 0; i < linkFiles.length; i += 50) {
805
+ const batch = linkFiles.slice(i, i + 50);
806
+ const batchResults = await Promise.all(
807
+ batch.map(async (filePath) => {
808
+ const content = await readFile3(filePath, "utf-8");
809
+ const relPath = relative2(ctx.rootDir, filePath);
810
+ return scanFileForDeadLinks(filePath, relPath, content, ctx.rootDir, dlConfig);
811
+ })
812
+ );
813
+ for (const result of batchResults) {
814
+ findings.push(...result);
815
+ }
816
+ }
817
+ }
818
+ const apiEnabled = ctx.config.rules["api-endpoints-discovered"] !== "off" && ctx.config.rules["api-endpoints-discovered"] !== false;
819
+ if (apiEnabled) {
820
+ const apiConfig = {
821
+ ...defaultApiEndpointsConfig,
822
+ ...ctx.config.apiEndpoints
823
+ };
824
+ if (apiConfig.enabled) {
825
+ const { findings: apiFindings } = await scanForApiEndpoints(
826
+ ctx.rootDir,
827
+ apiConfig,
828
+ ctx.config.exclude
829
+ );
830
+ findings.push(...apiFindings);
831
+ }
832
+ }
833
+ return {
834
+ scanner: this.name,
835
+ findings,
836
+ duration: performance.now() - start
837
+ };
838
+ }
839
+ resolveRules(ctx) {
840
+ return allRules.filter((rule) => {
841
+ const config = ctx.config.rules[rule.id];
842
+ return config !== "off" && config !== false;
843
+ });
844
+ }
845
+ async scanFile(filePath, rules, rootDir) {
846
+ const findings = [];
847
+ const content = await readFile3(filePath, "utf-8");
848
+ const lines = content.split("\n");
849
+ const relPath = relative2(rootDir, filePath);
850
+ const applicableRules = rules.filter((rule) => {
851
+ if (rule.exclude) {
852
+ if (rule.exclude.some((pattern) => matchSimpleGlob(relPath, pattern))) {
853
+ return false;
854
+ }
855
+ }
856
+ return true;
857
+ });
858
+ for (let lineIdx = 0; lineIdx < lines.length; lineIdx++) {
859
+ const line = lines[lineIdx];
860
+ for (const rule of applicableRules) {
861
+ const re = new RegExp(rule.pattern.source, rule.pattern.flags);
862
+ const match = re.exec(line);
863
+ if (!match) continue;
864
+ if (rule.id === "broken-import") {
865
+ const importMatch = IMPORT_PATH_RE.exec(line);
866
+ if (importMatch) {
867
+ const importPath = importMatch[1];
868
+ const fileDir = dirname3(filePath);
869
+ const exists = await resolveImportExists(importPath, fileDir);
870
+ if (exists) continue;
871
+ } else {
872
+ continue;
873
+ }
874
+ }
875
+ findings.push({
876
+ ruleId: rule.id,
877
+ severity: rule.severity,
878
+ message: rule.description,
879
+ filePath: relPath,
880
+ line: lineIdx + 1,
881
+ column: (match.index ?? 0) + 1,
882
+ snippet: line.trim()
883
+ });
884
+ }
885
+ }
886
+ return findings;
887
+ }
888
+ };
889
+ function matchSimpleGlob(filePath, pattern) {
890
+ const regexStr = pattern.replace(/\./g, "\\.").replace(/\*\*/g, "<<<GLOBSTAR>>>").replace(/\*/g, "[^/]*").replace(/<<<GLOBSTAR>>>/g, ".*");
891
+ return new RegExp(`^${regexStr}$`).test(filePath);
892
+ }
893
+ export {
894
+ SourceScanner
895
+ };
896
+ //# sourceMappingURL=source-D5KLH46F.js.map