@vibecheckai/cli 3.2.4 → 3.2.6

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 (123) hide show
  1. package/bin/.generated +25 -25
  2. package/bin/dev/run-v2-torture.js +30 -30
  3. package/bin/runners/lib/__tests__/entitlements-v2.test.js +295 -295
  4. package/bin/runners/lib/api-client.js +269 -0
  5. package/bin/runners/lib/auth-truth.js +193 -193
  6. package/bin/runners/lib/backup.js +62 -62
  7. package/bin/runners/lib/billing.js +107 -107
  8. package/bin/runners/lib/claims.js +118 -118
  9. package/bin/runners/lib/cli-ui.js +540 -540
  10. package/bin/runners/lib/contracts/auth-contract.js +202 -202
  11. package/bin/runners/lib/contracts/env-contract.js +181 -181
  12. package/bin/runners/lib/contracts/external-contract.js +206 -206
  13. package/bin/runners/lib/contracts/guard.js +168 -168
  14. package/bin/runners/lib/contracts/index.js +89 -89
  15. package/bin/runners/lib/contracts/plan-validator.js +311 -311
  16. package/bin/runners/lib/contracts/route-contract.js +199 -199
  17. package/bin/runners/lib/contracts.js +804 -804
  18. package/bin/runners/lib/detect.js +89 -89
  19. package/bin/runners/lib/doctor/autofix.js +254 -254
  20. package/bin/runners/lib/doctor/index.js +37 -37
  21. package/bin/runners/lib/doctor/modules/dependencies.js +325 -325
  22. package/bin/runners/lib/doctor/modules/index.js +46 -46
  23. package/bin/runners/lib/doctor/modules/network.js +250 -250
  24. package/bin/runners/lib/doctor/modules/project.js +312 -312
  25. package/bin/runners/lib/doctor/modules/runtime.js +224 -224
  26. package/bin/runners/lib/doctor/modules/security.js +348 -348
  27. package/bin/runners/lib/doctor/modules/system.js +213 -213
  28. package/bin/runners/lib/doctor/modules/vibecheck.js +394 -394
  29. package/bin/runners/lib/doctor/reporter.js +262 -262
  30. package/bin/runners/lib/doctor/service.js +262 -262
  31. package/bin/runners/lib/doctor/types.js +113 -113
  32. package/bin/runners/lib/doctor/ui.js +263 -263
  33. package/bin/runners/lib/doctor-v2.js +608 -608
  34. package/bin/runners/lib/drift.js +425 -425
  35. package/bin/runners/lib/enforcement.js +72 -72
  36. package/bin/runners/lib/enterprise-detect.js +603 -603
  37. package/bin/runners/lib/enterprise-init.js +942 -942
  38. package/bin/runners/lib/env-resolver.js +417 -417
  39. package/bin/runners/lib/env-template.js +66 -66
  40. package/bin/runners/lib/env.js +189 -189
  41. package/bin/runners/lib/extractors/client-calls.js +990 -990
  42. package/bin/runners/lib/extractors/fastify-route-dump.js +573 -573
  43. package/bin/runners/lib/extractors/fastify-routes.js +426 -426
  44. package/bin/runners/lib/extractors/index.js +363 -363
  45. package/bin/runners/lib/extractors/next-routes.js +524 -524
  46. package/bin/runners/lib/extractors/proof-graph.js +431 -431
  47. package/bin/runners/lib/extractors/route-matcher.js +451 -451
  48. package/bin/runners/lib/extractors/truthpack-v2.js +377 -377
  49. package/bin/runners/lib/extractors/ui-bindings.js +547 -547
  50. package/bin/runners/lib/findings-schema.js +281 -281
  51. package/bin/runners/lib/firewall-prompt.js +50 -50
  52. package/bin/runners/lib/graph/graph-builder.js +265 -265
  53. package/bin/runners/lib/graph/html-renderer.js +413 -413
  54. package/bin/runners/lib/graph/index.js +32 -32
  55. package/bin/runners/lib/graph/runtime-collector.js +215 -215
  56. package/bin/runners/lib/graph/static-extractor.js +518 -518
  57. package/bin/runners/lib/html-report.js +650 -650
  58. package/bin/runners/lib/llm.js +75 -75
  59. package/bin/runners/lib/meter.js +61 -61
  60. package/bin/runners/lib/missions/evidence.js +126 -126
  61. package/bin/runners/lib/patch.js +40 -40
  62. package/bin/runners/lib/permissions/auth-model.js +213 -213
  63. package/bin/runners/lib/permissions/idor-prover.js +205 -205
  64. package/bin/runners/lib/permissions/index.js +45 -45
  65. package/bin/runners/lib/permissions/matrix-builder.js +198 -198
  66. package/bin/runners/lib/pkgjson.js +28 -28
  67. package/bin/runners/lib/policy.js +295 -295
  68. package/bin/runners/lib/preflight.js +142 -142
  69. package/bin/runners/lib/reality/correlation-detectors.js +359 -359
  70. package/bin/runners/lib/reality/index.js +318 -318
  71. package/bin/runners/lib/reality/request-hashing.js +416 -416
  72. package/bin/runners/lib/reality/request-mapper.js +453 -453
  73. package/bin/runners/lib/reality/safety-rails.js +463 -463
  74. package/bin/runners/lib/reality/semantic-snapshot.js +408 -408
  75. package/bin/runners/lib/reality/toast-detector.js +393 -393
  76. package/bin/runners/lib/reality-findings.js +84 -84
  77. package/bin/runners/lib/receipts.js +179 -179
  78. package/bin/runners/lib/redact.js +29 -29
  79. package/bin/runners/lib/replay/capsule-manager.js +154 -154
  80. package/bin/runners/lib/replay/index.js +263 -263
  81. package/bin/runners/lib/replay/player.js +348 -348
  82. package/bin/runners/lib/replay/recorder.js +331 -331
  83. package/bin/runners/lib/report.js +135 -135
  84. package/bin/runners/lib/route-detection.js +1140 -1140
  85. package/bin/runners/lib/sandbox/index.js +59 -59
  86. package/bin/runners/lib/sandbox/proof-chain.js +399 -399
  87. package/bin/runners/lib/sandbox/sandbox-runner.js +205 -205
  88. package/bin/runners/lib/sandbox/worktree.js +174 -174
  89. package/bin/runners/lib/schema-validator.js +350 -350
  90. package/bin/runners/lib/schemas/contracts.schema.json +160 -160
  91. package/bin/runners/lib/schemas/finding.schema.json +100 -100
  92. package/bin/runners/lib/schemas/mission-pack.schema.json +206 -206
  93. package/bin/runners/lib/schemas/proof-graph.schema.json +176 -176
  94. package/bin/runners/lib/schemas/reality-report.schema.json +162 -162
  95. package/bin/runners/lib/schemas/share-pack.schema.json +180 -180
  96. package/bin/runners/lib/schemas/ship-report.schema.json +117 -117
  97. package/bin/runners/lib/schemas/truthpack-v2.schema.json +303 -303
  98. package/bin/runners/lib/schemas/validator.js +438 -438
  99. package/bin/runners/lib/score-history.js +282 -282
  100. package/bin/runners/lib/share-pack.js +239 -239
  101. package/bin/runners/lib/snippets.js +67 -67
  102. package/bin/runners/lib/upsell.js +510 -510
  103. package/bin/runners/lib/usage.js +153 -153
  104. package/bin/runners/lib/validate-patch.js +156 -156
  105. package/bin/runners/lib/verdict-engine.js +628 -628
  106. package/bin/runners/reality/engine.js +917 -917
  107. package/bin/runners/reality/flows.js +122 -122
  108. package/bin/runners/reality/report.js +378 -378
  109. package/bin/runners/reality/session.js +193 -193
  110. package/bin/runners/runAgent.d.ts +5 -0
  111. package/bin/runners/runFirewall.d.ts +5 -0
  112. package/bin/runners/runFirewallHook.d.ts +5 -0
  113. package/bin/runners/runGuard.js +168 -168
  114. package/bin/runners/runScan.js +82 -0
  115. package/bin/runners/runTruth.d.ts +5 -0
  116. package/bin/vibecheck.js +45 -20
  117. package/mcp-server/index.js +85 -0
  118. package/mcp-server/lib/api-client.js +269 -0
  119. package/mcp-server/package.json +1 -1
  120. package/mcp-server/tier-auth.js +173 -113
  121. package/mcp-server/tools/index.js +72 -72
  122. package/mcp-server/vibecheck-mcp-server-3.2.0.tgz +0 -0
  123. package/package.json +1 -1
@@ -1,524 +1,524 @@
1
- /**
2
- * Next.js Route Extractor v2
3
- *
4
- * Spec-compliant extraction for App Router + Pages Router API routes.
5
- * Handles dynamic segments, route groups, catch-alls, and method detection.
6
- *
7
- * Canonical path format:
8
- * - Static: /api/billing/portal
9
- * - Params: /api/users/{id}
10
- * - Catch-all: /api/files/{*path}
11
- * - Optional catch-all: /api/blog/{*slug?}
12
- */
13
-
14
- "use strict";
15
-
16
- const fs = require("fs");
17
- const path = require("path");
18
- const fg = require("fast-glob");
19
- const crypto = require("crypto");
20
-
21
- const NEXT_HTTP_METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "HEAD"];
22
-
23
- /**
24
- * Detect Next.js mode and roots
25
- */
26
- function detectNextMode(projectRoot) {
27
- const result = {
28
- present: false,
29
- router: "unknown",
30
- appDir: null,
31
- pagesDir: null,
32
- middlewareFile: null,
33
- basePath: "",
34
- trailingSlash: false,
35
- rewrites: [],
36
- };
37
-
38
- // Check for Next.js presence
39
- const pkgPath = path.join(projectRoot, "package.json");
40
- if (fs.existsSync(pkgPath)) {
41
- try {
42
- const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf8"));
43
- if (pkg.dependencies?.next || pkg.devDependencies?.next) {
44
- result.present = true;
45
- }
46
- } catch {}
47
- }
48
-
49
- // Check for next.config
50
- const configFiles = ["next.config.js", "next.config.mjs", "next.config.ts"];
51
- for (const configFile of configFiles) {
52
- const configPath = path.join(projectRoot, configFile);
53
- if (fs.existsSync(configPath)) {
54
- result.present = true;
55
- parseNextConfig(configPath, result);
56
- break;
57
- }
58
- }
59
-
60
- // Check for app/ and pages/ directories
61
- const appDir = path.join(projectRoot, "app");
62
- const srcAppDir = path.join(projectRoot, "src", "app");
63
- const pagesDir = path.join(projectRoot, "pages");
64
- const srcPagesDir = path.join(projectRoot, "src", "pages");
65
-
66
- if (fs.existsSync(appDir)) {
67
- result.appDir = appDir;
68
- result.present = true;
69
- } else if (fs.existsSync(srcAppDir)) {
70
- result.appDir = srcAppDir;
71
- result.present = true;
72
- }
73
-
74
- if (fs.existsSync(pagesDir)) {
75
- result.pagesDir = pagesDir;
76
- result.present = true;
77
- } else if (fs.existsSync(srcPagesDir)) {
78
- result.pagesDir = srcPagesDir;
79
- result.present = true;
80
- }
81
-
82
- // Determine router mode
83
- if (result.appDir && result.pagesDir) {
84
- result.router = "mixed";
85
- } else if (result.appDir) {
86
- result.router = "app";
87
- } else if (result.pagesDir) {
88
- result.router = "pages";
89
- }
90
-
91
- // Find middleware
92
- const middlewareLocations = [
93
- path.join(projectRoot, "middleware.ts"),
94
- path.join(projectRoot, "middleware.js"),
95
- path.join(projectRoot, "src", "middleware.ts"),
96
- path.join(projectRoot, "src", "middleware.js"),
97
- ];
98
- for (const loc of middlewareLocations) {
99
- if (fs.existsSync(loc)) {
100
- result.middlewareFile = loc;
101
- break;
102
- }
103
- }
104
-
105
- return result;
106
- }
107
-
108
- /**
109
- * Parse next.config for basePath, trailingSlash, rewrites
110
- */
111
- function parseNextConfig(configPath, result) {
112
- try {
113
- const content = fs.readFileSync(configPath, "utf8");
114
-
115
- // Extract basePath
116
- const basePathMatch = content.match(/basePath\s*:\s*['"`]([^'"`]+)['"`]/);
117
- if (basePathMatch) {
118
- result.basePath = basePathMatch[1];
119
- }
120
-
121
- // Extract trailingSlash
122
- if (/trailingSlash\s*:\s*true/.test(content)) {
123
- result.trailingSlash = true;
124
- }
125
-
126
- // Extract rewrites (basic pattern matching)
127
- const rewriteMatches = content.matchAll(/source\s*:\s*['"`]([^'"`]+)['"`][\s\S]*?destination\s*:\s*['"`]([^'"`]+)['"`]/g);
128
- for (const match of rewriteMatches) {
129
- result.rewrites.push({
130
- source: match[1],
131
- destination: match[2],
132
- isExternal: match[2].startsWith("http"),
133
- });
134
- }
135
- } catch {}
136
- }
137
-
138
- /**
139
- * Extract App Router API routes from app/api directory
140
- */
141
- function extractAppRouterRoutes(appDir, projectRoot) {
142
- const routes = [];
143
-
144
- if (!appDir || !fs.existsSync(appDir)) return routes;
145
-
146
- // Find all route handlers
147
- const pattern = path.join(appDir, "api", "**", "route.{js,jsx,ts,tsx}").replace(/\\/g, "/");
148
- const files = fg.sync(pattern, { onlyFiles: true, absolute: true });
149
-
150
- for (const file of files) {
151
- const route = extractAppRouteHandler(file, appDir, projectRoot);
152
- if (route) {
153
- routes.push(route);
154
- }
155
- }
156
-
157
- return routes;
158
- }
159
-
160
- /**
161
- * Extract a single App Router route handler
162
- */
163
- function extractAppRouteHandler(file, appDir, projectRoot) {
164
- const content = fs.readFileSync(file, "utf8");
165
- const relPath = path.relative(appDir, file).replace(/\\/g, "/");
166
-
167
- // Build canonical path from file path
168
- // Strip api/ prefix and route.* suffix
169
- let urlPath = relPath
170
- .replace(/^api\//, "/api/")
171
- .replace(/\/route\.(js|jsx|ts|tsx)$/, "")
172
- .replace(/^\/api/, "/api"); // Ensure /api prefix
173
-
174
- // Handle special segments
175
- urlPath = convertNextPathToCanonical(urlPath);
176
-
177
- // Extract HTTP methods from exports
178
- const methods = extractExportedMethods(content);
179
- const confidence = methods.length > 0 && !methods.includes("UNKNOWN") ? "high" : "low";
180
-
181
- // Build evidence
182
- const evidence = [];
183
- for (const method of methods) {
184
- const methodMatch = content.match(new RegExp(`export\\s+(async\\s+)?function\\s+${method}|export\\s+const\\s+${method}\\s*=`, "m"));
185
- if (methodMatch) {
186
- const lineNum = content.substring(0, methodMatch.index).split("\n").length;
187
- evidence.push({
188
- id: `E_${crypto.randomBytes(4).toString("hex").toUpperCase()}`,
189
- kind: "file",
190
- reason: `${method} handler export`,
191
- file: path.relative(projectRoot, file).replace(/\\/g, "/"),
192
- lines: `${lineNum}-${lineNum + 5}`,
193
- snippetHash: hashSnippet(methodMatch[0]),
194
- });
195
- }
196
- }
197
-
198
- // If no methods found, add generic evidence
199
- if (evidence.length === 0) {
200
- evidence.push({
201
- id: `E_${crypto.randomBytes(4).toString("hex").toUpperCase()}`,
202
- kind: "file",
203
- reason: "Route handler file",
204
- file: path.relative(projectRoot, file).replace(/\\/g, "/"),
205
- lines: "1-10",
206
- });
207
- }
208
-
209
- return {
210
- id: `R_NEXT_APP_${hashPath(urlPath)}`,
211
- kind: "next_route_handler",
212
- methods: methods.length > 0 ? methods : ["UNKNOWN"],
213
- rawPath: relPath,
214
- path: urlPath,
215
- canonicalPath: urlPath,
216
- authRequired: "unknown",
217
- confidence,
218
- handler: {
219
- file: path.relative(projectRoot, file).replace(/\\/g, "/"),
220
- export: methods[0] || "handler",
221
- },
222
- evidence,
223
- };
224
- }
225
-
226
- /**
227
- * Extract Pages Router API routes (pages/api/**)
228
- */
229
- function extractPagesRouterRoutes(pagesDir, projectRoot) {
230
- const routes = [];
231
-
232
- if (!pagesDir || !fs.existsSync(pagesDir)) return routes;
233
-
234
- const apiDir = path.join(pagesDir, "api");
235
- if (!fs.existsSync(apiDir)) return routes;
236
-
237
- // Find all API files
238
- const pattern = path.join(apiDir, "**", "*.{js,jsx,ts,tsx}").replace(/\\/g, "/");
239
- const files = fg.sync(pattern, { onlyFiles: true, absolute: true });
240
-
241
- for (const file of files) {
242
- const route = extractPagesApiHandler(file, pagesDir, projectRoot);
243
- if (route) {
244
- routes.push(route);
245
- }
246
- }
247
-
248
- return routes;
249
- }
250
-
251
- /**
252
- * Extract a single Pages API handler
253
- */
254
- function extractPagesApiHandler(file, pagesDir, projectRoot) {
255
- const content = fs.readFileSync(file, "utf8");
256
- const relPath = path.relative(pagesDir, file).replace(/\\/g, "/");
257
-
258
- // Build URL path
259
- let urlPath = "/" + relPath
260
- .replace(/^api\//, "api/")
261
- .replace(/\.(js|jsx|ts|tsx)$/, "")
262
- .replace(/\/index$/, "");
263
-
264
- // Ensure /api prefix
265
- if (!urlPath.startsWith("/api")) {
266
- urlPath = "/api" + urlPath;
267
- }
268
-
269
- // Convert dynamic segments
270
- urlPath = convertNextPathToCanonical(urlPath);
271
-
272
- // Extract methods from req.method checks
273
- const methods = extractReqMethodChecks(content);
274
- const confidence = methods.length > 0 && !methods.includes("UNKNOWN") ? "medium" : "low";
275
-
276
- // Build evidence
277
- const evidence = [{
278
- id: `E_${crypto.randomBytes(4).toString("hex").toUpperCase()}`,
279
- kind: "file",
280
- reason: "Pages API handler",
281
- file: path.relative(projectRoot, file).replace(/\\/g, "/"),
282
- lines: "1-20",
283
- }];
284
-
285
- // Add evidence for method checks
286
- const methodCheckMatch = content.match(/req\.method\s*===?\s*['"`](\w+)['"`]/);
287
- if (methodCheckMatch) {
288
- const lineNum = content.substring(0, methodCheckMatch.index).split("\n").length;
289
- evidence.push({
290
- id: `E_${crypto.randomBytes(4).toString("hex").toUpperCase()}`,
291
- kind: "file",
292
- reason: "Method check",
293
- file: path.relative(projectRoot, file).replace(/\\/g, "/"),
294
- lines: `${lineNum}-${lineNum}`,
295
- snippetHash: hashSnippet(methodCheckMatch[0]),
296
- });
297
- }
298
-
299
- return {
300
- id: `R_NEXT_PAGES_${hashPath(urlPath)}`,
301
- kind: "next_pages_api",
302
- methods: methods.length > 0 ? methods : ["UNKNOWN"],
303
- rawPath: relPath,
304
- path: urlPath,
305
- canonicalPath: urlPath,
306
- authRequired: "unknown",
307
- confidence,
308
- handler: {
309
- file: path.relative(projectRoot, file).replace(/\\/g, "/"),
310
- export: "default",
311
- },
312
- evidence,
313
- };
314
- }
315
-
316
- /**
317
- * Convert Next.js path segments to canonical format
318
- * [id] → {id}
319
- * [...slug] → {*slug}
320
- * [[...slug]] → {*slug?}
321
- * (group) → removed
322
- */
323
- function convertNextPathToCanonical(urlPath) {
324
- return urlPath
325
- // Remove route groups (parentheses)
326
- .replace(/\/\([^)]+\)/g, "")
327
- // Remove parallel routes (@)
328
- .replace(/\/@[^/]+/g, "")
329
- // Optional catch-all [[...slug]]
330
- .replace(/\[\[\.\.\.([^\]]+)\]\]/g, "{*$1?}")
331
- // Catch-all [...slug]
332
- .replace(/\[\.\.\.([^\]]+)\]/g, "{*$1}")
333
- // Dynamic segment [id]
334
- .replace(/\[([^\]]+)\]/g, "{$1}")
335
- // Clean up double slashes
336
- .replace(/\/+/g, "/")
337
- // Remove trailing slash except root
338
- .replace(/(.)\/$/, "$1");
339
- }
340
-
341
- /**
342
- * Extract exported HTTP methods from App Router file
343
- */
344
- function extractExportedMethods(content) {
345
- const methods = [];
346
-
347
- for (const method of NEXT_HTTP_METHODS) {
348
- // export async function GET
349
- // export function GET
350
- // export const GET =
351
- const patterns = [
352
- new RegExp(`export\\s+async\\s+function\\s+${method}\\s*\\(`, "m"),
353
- new RegExp(`export\\s+function\\s+${method}\\s*\\(`, "m"),
354
- new RegExp(`export\\s+const\\s+${method}\\s*=`, "m"),
355
- ];
356
-
357
- for (const pattern of patterns) {
358
- if (pattern.test(content)) {
359
- methods.push(method);
360
- break;
361
- }
362
- }
363
- }
364
-
365
- return methods;
366
- }
367
-
368
- /**
369
- * Extract methods from req.method checks in Pages API
370
- */
371
- function extractReqMethodChecks(content) {
372
- const methods = new Set();
373
-
374
- // Match patterns like: req.method === "POST" or req.method === 'GET'
375
- const matches = content.matchAll(/req\.method\s*===?\s*['"`](\w+)['"`]/g);
376
- for (const match of matches) {
377
- const method = match[1].toUpperCase();
378
- if (NEXT_HTTP_METHODS.includes(method)) {
379
- methods.add(method);
380
- }
381
- }
382
-
383
- // Match switch case patterns
384
- const caseMatches = content.matchAll(/case\s*['"`](\w+)['"`]\s*:/g);
385
- for (const match of caseMatches) {
386
- const method = match[1].toUpperCase();
387
- if (NEXT_HTTP_METHODS.includes(method)) {
388
- methods.add(method);
389
- }
390
- }
391
-
392
- return [...methods];
393
- }
394
-
395
- /**
396
- * Extract middleware matchers for auth hints
397
- */
398
- function extractMiddlewareMatchers(middlewareFile, projectRoot) {
399
- const result = {
400
- matchers: [],
401
- protectedHints: [],
402
- };
403
-
404
- if (!middlewareFile || !fs.existsSync(middlewareFile)) return result;
405
-
406
- const content = fs.readFileSync(middlewareFile, "utf8");
407
-
408
- // Extract config.matcher
409
- const matcherMatch = content.match(/export\s+const\s+config\s*=\s*\{[^}]*matcher\s*:\s*(\[[^\]]+\]|['"`][^'"`]+['"`])/s);
410
- if (matcherMatch) {
411
- const matcherValue = matcherMatch[1];
412
-
413
- // Parse array
414
- if (matcherValue.startsWith("[")) {
415
- const patterns = matcherValue.matchAll(/['"`]([^'"`]+)['"`]/g);
416
- for (const p of patterns) {
417
- result.matchers.push(p[1]);
418
- }
419
- } else {
420
- // Single string
421
- const singleMatch = matcherValue.match(/['"`]([^'"`]+)['"`]/);
422
- if (singleMatch) {
423
- result.matchers.push(singleMatch[1]);
424
- }
425
- }
426
- }
427
-
428
- // Detect auth signals (protected hints)
429
- const authSignals = [
430
- /getToken\s*\(/,
431
- /getServerSession\s*\(/,
432
- /auth\s*\(\s*\)/,
433
- /cookies\(\)\.get\s*\(/,
434
- /NextResponse\.redirect.*login/i,
435
- /clerk/i,
436
- /supabase.*auth/i,
437
- ];
438
-
439
- for (const signal of authSignals) {
440
- if (signal.test(content)) {
441
- result.protectedHints.push({
442
- signal: signal.toString(),
443
- file: path.relative(projectRoot, middlewareFile).replace(/\\/g, "/"),
444
- });
445
- }
446
- }
447
-
448
- return result;
449
- }
450
-
451
- /**
452
- * Main extraction function
453
- */
454
- function extractNextRoutes(projectRoot) {
455
- const mode = detectNextMode(projectRoot);
456
-
457
- if (!mode.present) {
458
- return {
459
- present: false,
460
- router: "unknown",
461
- routes: [],
462
- middleware: { matchers: [], protectedHints: [] },
463
- };
464
- }
465
-
466
- const routes = [];
467
-
468
- // Extract App Router routes
469
- if (mode.appDir) {
470
- const appRoutes = extractAppRouterRoutes(mode.appDir, projectRoot);
471
- routes.push(...appRoutes);
472
- }
473
-
474
- // Extract Pages Router routes
475
- if (mode.pagesDir) {
476
- const pagesRoutes = extractPagesRouterRoutes(mode.pagesDir, projectRoot);
477
- routes.push(...pagesRoutes);
478
- }
479
-
480
- // Apply basePath to all routes
481
- if (mode.basePath) {
482
- for (const route of routes) {
483
- route.path = mode.basePath + route.path;
484
- route.canonicalPath = mode.basePath + route.canonicalPath;
485
- }
486
- }
487
-
488
- // Extract middleware
489
- const middleware = extractMiddlewareMatchers(mode.middlewareFile, projectRoot);
490
-
491
- return {
492
- present: true,
493
- router: mode.router,
494
- appDir: mode.appDir ? path.relative(projectRoot, mode.appDir) : null,
495
- pagesDir: mode.pagesDir ? path.relative(projectRoot, mode.pagesDir) : null,
496
- basePath: mode.basePath,
497
- trailingSlash: mode.trailingSlash,
498
- rewrites: mode.rewrites,
499
- middlewareFile: mode.middlewareFile ? path.relative(projectRoot, mode.middlewareFile) : null,
500
- routes,
501
- middleware,
502
- };
503
- }
504
-
505
- // Helpers
506
- function hashSnippet(text) {
507
- return `sha256:${crypto.createHash("sha256").update(text).digest("hex")}`;
508
- }
509
-
510
- function hashPath(urlPath) {
511
- return crypto.createHash("sha256").update(urlPath).digest("hex").slice(0, 12).toUpperCase();
512
- }
513
-
514
- module.exports = {
515
- detectNextMode,
516
- extractNextRoutes,
517
- extractAppRouterRoutes,
518
- extractPagesRouterRoutes,
519
- extractMiddlewareMatchers,
520
- convertNextPathToCanonical,
521
- extractExportedMethods,
522
- extractReqMethodChecks,
523
- NEXT_HTTP_METHODS,
524
- };
1
+ /**
2
+ * Next.js Route Extractor v2
3
+ *
4
+ * Spec-compliant extraction for App Router + Pages Router API routes.
5
+ * Handles dynamic segments, route groups, catch-alls, and method detection.
6
+ *
7
+ * Canonical path format:
8
+ * - Static: /api/billing/portal
9
+ * - Params: /api/users/{id}
10
+ * - Catch-all: /api/files/{*path}
11
+ * - Optional catch-all: /api/blog/{*slug?}
12
+ */
13
+
14
+ "use strict";
15
+
16
+ const fs = require("fs");
17
+ const path = require("path");
18
+ const fg = require("fast-glob");
19
+ const crypto = require("crypto");
20
+
21
+ const NEXT_HTTP_METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "HEAD"];
22
+
23
+ /**
24
+ * Detect Next.js mode and roots
25
+ */
26
+ function detectNextMode(projectRoot) {
27
+ const result = {
28
+ present: false,
29
+ router: "unknown",
30
+ appDir: null,
31
+ pagesDir: null,
32
+ middlewareFile: null,
33
+ basePath: "",
34
+ trailingSlash: false,
35
+ rewrites: [],
36
+ };
37
+
38
+ // Check for Next.js presence
39
+ const pkgPath = path.join(projectRoot, "package.json");
40
+ if (fs.existsSync(pkgPath)) {
41
+ try {
42
+ const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf8"));
43
+ if (pkg.dependencies?.next || pkg.devDependencies?.next) {
44
+ result.present = true;
45
+ }
46
+ } catch {}
47
+ }
48
+
49
+ // Check for next.config
50
+ const configFiles = ["next.config.js", "next.config.mjs", "next.config.ts"];
51
+ for (const configFile of configFiles) {
52
+ const configPath = path.join(projectRoot, configFile);
53
+ if (fs.existsSync(configPath)) {
54
+ result.present = true;
55
+ parseNextConfig(configPath, result);
56
+ break;
57
+ }
58
+ }
59
+
60
+ // Check for app/ and pages/ directories
61
+ const appDir = path.join(projectRoot, "app");
62
+ const srcAppDir = path.join(projectRoot, "src", "app");
63
+ const pagesDir = path.join(projectRoot, "pages");
64
+ const srcPagesDir = path.join(projectRoot, "src", "pages");
65
+
66
+ if (fs.existsSync(appDir)) {
67
+ result.appDir = appDir;
68
+ result.present = true;
69
+ } else if (fs.existsSync(srcAppDir)) {
70
+ result.appDir = srcAppDir;
71
+ result.present = true;
72
+ }
73
+
74
+ if (fs.existsSync(pagesDir)) {
75
+ result.pagesDir = pagesDir;
76
+ result.present = true;
77
+ } else if (fs.existsSync(srcPagesDir)) {
78
+ result.pagesDir = srcPagesDir;
79
+ result.present = true;
80
+ }
81
+
82
+ // Determine router mode
83
+ if (result.appDir && result.pagesDir) {
84
+ result.router = "mixed";
85
+ } else if (result.appDir) {
86
+ result.router = "app";
87
+ } else if (result.pagesDir) {
88
+ result.router = "pages";
89
+ }
90
+
91
+ // Find middleware
92
+ const middlewareLocations = [
93
+ path.join(projectRoot, "middleware.ts"),
94
+ path.join(projectRoot, "middleware.js"),
95
+ path.join(projectRoot, "src", "middleware.ts"),
96
+ path.join(projectRoot, "src", "middleware.js"),
97
+ ];
98
+ for (const loc of middlewareLocations) {
99
+ if (fs.existsSync(loc)) {
100
+ result.middlewareFile = loc;
101
+ break;
102
+ }
103
+ }
104
+
105
+ return result;
106
+ }
107
+
108
+ /**
109
+ * Parse next.config for basePath, trailingSlash, rewrites
110
+ */
111
+ function parseNextConfig(configPath, result) {
112
+ try {
113
+ const content = fs.readFileSync(configPath, "utf8");
114
+
115
+ // Extract basePath
116
+ const basePathMatch = content.match(/basePath\s*:\s*['"`]([^'"`]+)['"`]/);
117
+ if (basePathMatch) {
118
+ result.basePath = basePathMatch[1];
119
+ }
120
+
121
+ // Extract trailingSlash
122
+ if (/trailingSlash\s*:\s*true/.test(content)) {
123
+ result.trailingSlash = true;
124
+ }
125
+
126
+ // Extract rewrites (basic pattern matching)
127
+ const rewriteMatches = content.matchAll(/source\s*:\s*['"`]([^'"`]+)['"`][\s\S]*?destination\s*:\s*['"`]([^'"`]+)['"`]/g);
128
+ for (const match of rewriteMatches) {
129
+ result.rewrites.push({
130
+ source: match[1],
131
+ destination: match[2],
132
+ isExternal: match[2].startsWith("http"),
133
+ });
134
+ }
135
+ } catch {}
136
+ }
137
+
138
+ /**
139
+ * Extract App Router API routes from app/api directory
140
+ */
141
+ function extractAppRouterRoutes(appDir, projectRoot) {
142
+ const routes = [];
143
+
144
+ if (!appDir || !fs.existsSync(appDir)) return routes;
145
+
146
+ // Find all route handlers
147
+ const pattern = path.join(appDir, "api", "**", "route.{js,jsx,ts,tsx}").replace(/\\/g, "/");
148
+ const files = fg.sync(pattern, { onlyFiles: true, absolute: true });
149
+
150
+ for (const file of files) {
151
+ const route = extractAppRouteHandler(file, appDir, projectRoot);
152
+ if (route) {
153
+ routes.push(route);
154
+ }
155
+ }
156
+
157
+ return routes;
158
+ }
159
+
160
+ /**
161
+ * Extract a single App Router route handler
162
+ */
163
+ function extractAppRouteHandler(file, appDir, projectRoot) {
164
+ const content = fs.readFileSync(file, "utf8");
165
+ const relPath = path.relative(appDir, file).replace(/\\/g, "/");
166
+
167
+ // Build canonical path from file path
168
+ // Strip api/ prefix and route.* suffix
169
+ let urlPath = relPath
170
+ .replace(/^api\//, "/api/")
171
+ .replace(/\/route\.(js|jsx|ts|tsx)$/, "")
172
+ .replace(/^\/api/, "/api"); // Ensure /api prefix
173
+
174
+ // Handle special segments
175
+ urlPath = convertNextPathToCanonical(urlPath);
176
+
177
+ // Extract HTTP methods from exports
178
+ const methods = extractExportedMethods(content);
179
+ const confidence = methods.length > 0 && !methods.includes("UNKNOWN") ? "high" : "low";
180
+
181
+ // Build evidence
182
+ const evidence = [];
183
+ for (const method of methods) {
184
+ const methodMatch = content.match(new RegExp(`export\\s+(async\\s+)?function\\s+${method}|export\\s+const\\s+${method}\\s*=`, "m"));
185
+ if (methodMatch) {
186
+ const lineNum = content.substring(0, methodMatch.index).split("\n").length;
187
+ evidence.push({
188
+ id: `E_${crypto.randomBytes(4).toString("hex").toUpperCase()}`,
189
+ kind: "file",
190
+ reason: `${method} handler export`,
191
+ file: path.relative(projectRoot, file).replace(/\\/g, "/"),
192
+ lines: `${lineNum}-${lineNum + 5}`,
193
+ snippetHash: hashSnippet(methodMatch[0]),
194
+ });
195
+ }
196
+ }
197
+
198
+ // If no methods found, add generic evidence
199
+ if (evidence.length === 0) {
200
+ evidence.push({
201
+ id: `E_${crypto.randomBytes(4).toString("hex").toUpperCase()}`,
202
+ kind: "file",
203
+ reason: "Route handler file",
204
+ file: path.relative(projectRoot, file).replace(/\\/g, "/"),
205
+ lines: "1-10",
206
+ });
207
+ }
208
+
209
+ return {
210
+ id: `R_NEXT_APP_${hashPath(urlPath)}`,
211
+ kind: "next_route_handler",
212
+ methods: methods.length > 0 ? methods : ["UNKNOWN"],
213
+ rawPath: relPath,
214
+ path: urlPath,
215
+ canonicalPath: urlPath,
216
+ authRequired: "unknown",
217
+ confidence,
218
+ handler: {
219
+ file: path.relative(projectRoot, file).replace(/\\/g, "/"),
220
+ export: methods[0] || "handler",
221
+ },
222
+ evidence,
223
+ };
224
+ }
225
+
226
+ /**
227
+ * Extract Pages Router API routes (pages/api/**)
228
+ */
229
+ function extractPagesRouterRoutes(pagesDir, projectRoot) {
230
+ const routes = [];
231
+
232
+ if (!pagesDir || !fs.existsSync(pagesDir)) return routes;
233
+
234
+ const apiDir = path.join(pagesDir, "api");
235
+ if (!fs.existsSync(apiDir)) return routes;
236
+
237
+ // Find all API files
238
+ const pattern = path.join(apiDir, "**", "*.{js,jsx,ts,tsx}").replace(/\\/g, "/");
239
+ const files = fg.sync(pattern, { onlyFiles: true, absolute: true });
240
+
241
+ for (const file of files) {
242
+ const route = extractPagesApiHandler(file, pagesDir, projectRoot);
243
+ if (route) {
244
+ routes.push(route);
245
+ }
246
+ }
247
+
248
+ return routes;
249
+ }
250
+
251
+ /**
252
+ * Extract a single Pages API handler
253
+ */
254
+ function extractPagesApiHandler(file, pagesDir, projectRoot) {
255
+ const content = fs.readFileSync(file, "utf8");
256
+ const relPath = path.relative(pagesDir, file).replace(/\\/g, "/");
257
+
258
+ // Build URL path
259
+ let urlPath = "/" + relPath
260
+ .replace(/^api\//, "api/")
261
+ .replace(/\.(js|jsx|ts|tsx)$/, "")
262
+ .replace(/\/index$/, "");
263
+
264
+ // Ensure /api prefix
265
+ if (!urlPath.startsWith("/api")) {
266
+ urlPath = "/api" + urlPath;
267
+ }
268
+
269
+ // Convert dynamic segments
270
+ urlPath = convertNextPathToCanonical(urlPath);
271
+
272
+ // Extract methods from req.method checks
273
+ const methods = extractReqMethodChecks(content);
274
+ const confidence = methods.length > 0 && !methods.includes("UNKNOWN") ? "medium" : "low";
275
+
276
+ // Build evidence
277
+ const evidence = [{
278
+ id: `E_${crypto.randomBytes(4).toString("hex").toUpperCase()}`,
279
+ kind: "file",
280
+ reason: "Pages API handler",
281
+ file: path.relative(projectRoot, file).replace(/\\/g, "/"),
282
+ lines: "1-20",
283
+ }];
284
+
285
+ // Add evidence for method checks
286
+ const methodCheckMatch = content.match(/req\.method\s*===?\s*['"`](\w+)['"`]/);
287
+ if (methodCheckMatch) {
288
+ const lineNum = content.substring(0, methodCheckMatch.index).split("\n").length;
289
+ evidence.push({
290
+ id: `E_${crypto.randomBytes(4).toString("hex").toUpperCase()}`,
291
+ kind: "file",
292
+ reason: "Method check",
293
+ file: path.relative(projectRoot, file).replace(/\\/g, "/"),
294
+ lines: `${lineNum}-${lineNum}`,
295
+ snippetHash: hashSnippet(methodCheckMatch[0]),
296
+ });
297
+ }
298
+
299
+ return {
300
+ id: `R_NEXT_PAGES_${hashPath(urlPath)}`,
301
+ kind: "next_pages_api",
302
+ methods: methods.length > 0 ? methods : ["UNKNOWN"],
303
+ rawPath: relPath,
304
+ path: urlPath,
305
+ canonicalPath: urlPath,
306
+ authRequired: "unknown",
307
+ confidence,
308
+ handler: {
309
+ file: path.relative(projectRoot, file).replace(/\\/g, "/"),
310
+ export: "default",
311
+ },
312
+ evidence,
313
+ };
314
+ }
315
+
316
+ /**
317
+ * Convert Next.js path segments to canonical format
318
+ * [id] → {id}
319
+ * [...slug] → {*slug}
320
+ * [[...slug]] → {*slug?}
321
+ * (group) → removed
322
+ */
323
+ function convertNextPathToCanonical(urlPath) {
324
+ return urlPath
325
+ // Remove route groups (parentheses)
326
+ .replace(/\/\([^)]+\)/g, "")
327
+ // Remove parallel routes (@)
328
+ .replace(/\/@[^/]+/g, "")
329
+ // Optional catch-all [[...slug]]
330
+ .replace(/\[\[\.\.\.([^\]]+)\]\]/g, "{*$1?}")
331
+ // Catch-all [...slug]
332
+ .replace(/\[\.\.\.([^\]]+)\]/g, "{*$1}")
333
+ // Dynamic segment [id]
334
+ .replace(/\[([^\]]+)\]/g, "{$1}")
335
+ // Clean up double slashes
336
+ .replace(/\/+/g, "/")
337
+ // Remove trailing slash except root
338
+ .replace(/(.)\/$/, "$1");
339
+ }
340
+
341
+ /**
342
+ * Extract exported HTTP methods from App Router file
343
+ */
344
+ function extractExportedMethods(content) {
345
+ const methods = [];
346
+
347
+ for (const method of NEXT_HTTP_METHODS) {
348
+ // export async function GET
349
+ // export function GET
350
+ // export const GET =
351
+ const patterns = [
352
+ new RegExp(`export\\s+async\\s+function\\s+${method}\\s*\\(`, "m"),
353
+ new RegExp(`export\\s+function\\s+${method}\\s*\\(`, "m"),
354
+ new RegExp(`export\\s+const\\s+${method}\\s*=`, "m"),
355
+ ];
356
+
357
+ for (const pattern of patterns) {
358
+ if (pattern.test(content)) {
359
+ methods.push(method);
360
+ break;
361
+ }
362
+ }
363
+ }
364
+
365
+ return methods;
366
+ }
367
+
368
+ /**
369
+ * Extract methods from req.method checks in Pages API
370
+ */
371
+ function extractReqMethodChecks(content) {
372
+ const methods = new Set();
373
+
374
+ // Match patterns like: req.method === "POST" or req.method === 'GET'
375
+ const matches = content.matchAll(/req\.method\s*===?\s*['"`](\w+)['"`]/g);
376
+ for (const match of matches) {
377
+ const method = match[1].toUpperCase();
378
+ if (NEXT_HTTP_METHODS.includes(method)) {
379
+ methods.add(method);
380
+ }
381
+ }
382
+
383
+ // Match switch case patterns
384
+ const caseMatches = content.matchAll(/case\s*['"`](\w+)['"`]\s*:/g);
385
+ for (const match of caseMatches) {
386
+ const method = match[1].toUpperCase();
387
+ if (NEXT_HTTP_METHODS.includes(method)) {
388
+ methods.add(method);
389
+ }
390
+ }
391
+
392
+ return [...methods];
393
+ }
394
+
395
+ /**
396
+ * Extract middleware matchers for auth hints
397
+ */
398
+ function extractMiddlewareMatchers(middlewareFile, projectRoot) {
399
+ const result = {
400
+ matchers: [],
401
+ protectedHints: [],
402
+ };
403
+
404
+ if (!middlewareFile || !fs.existsSync(middlewareFile)) return result;
405
+
406
+ const content = fs.readFileSync(middlewareFile, "utf8");
407
+
408
+ // Extract config.matcher
409
+ const matcherMatch = content.match(/export\s+const\s+config\s*=\s*\{[^}]*matcher\s*:\s*(\[[^\]]+\]|['"`][^'"`]+['"`])/s);
410
+ if (matcherMatch) {
411
+ const matcherValue = matcherMatch[1];
412
+
413
+ // Parse array
414
+ if (matcherValue.startsWith("[")) {
415
+ const patterns = matcherValue.matchAll(/['"`]([^'"`]+)['"`]/g);
416
+ for (const p of patterns) {
417
+ result.matchers.push(p[1]);
418
+ }
419
+ } else {
420
+ // Single string
421
+ const singleMatch = matcherValue.match(/['"`]([^'"`]+)['"`]/);
422
+ if (singleMatch) {
423
+ result.matchers.push(singleMatch[1]);
424
+ }
425
+ }
426
+ }
427
+
428
+ // Detect auth signals (protected hints)
429
+ const authSignals = [
430
+ /getToken\s*\(/,
431
+ /getServerSession\s*\(/,
432
+ /auth\s*\(\s*\)/,
433
+ /cookies\(\)\.get\s*\(/,
434
+ /NextResponse\.redirect.*login/i,
435
+ /clerk/i,
436
+ /supabase.*auth/i,
437
+ ];
438
+
439
+ for (const signal of authSignals) {
440
+ if (signal.test(content)) {
441
+ result.protectedHints.push({
442
+ signal: signal.toString(),
443
+ file: path.relative(projectRoot, middlewareFile).replace(/\\/g, "/"),
444
+ });
445
+ }
446
+ }
447
+
448
+ return result;
449
+ }
450
+
451
+ /**
452
+ * Main extraction function
453
+ */
454
+ function extractNextRoutes(projectRoot) {
455
+ const mode = detectNextMode(projectRoot);
456
+
457
+ if (!mode.present) {
458
+ return {
459
+ present: false,
460
+ router: "unknown",
461
+ routes: [],
462
+ middleware: { matchers: [], protectedHints: [] },
463
+ };
464
+ }
465
+
466
+ const routes = [];
467
+
468
+ // Extract App Router routes
469
+ if (mode.appDir) {
470
+ const appRoutes = extractAppRouterRoutes(mode.appDir, projectRoot);
471
+ routes.push(...appRoutes);
472
+ }
473
+
474
+ // Extract Pages Router routes
475
+ if (mode.pagesDir) {
476
+ const pagesRoutes = extractPagesRouterRoutes(mode.pagesDir, projectRoot);
477
+ routes.push(...pagesRoutes);
478
+ }
479
+
480
+ // Apply basePath to all routes
481
+ if (mode.basePath) {
482
+ for (const route of routes) {
483
+ route.path = mode.basePath + route.path;
484
+ route.canonicalPath = mode.basePath + route.canonicalPath;
485
+ }
486
+ }
487
+
488
+ // Extract middleware
489
+ const middleware = extractMiddlewareMatchers(mode.middlewareFile, projectRoot);
490
+
491
+ return {
492
+ present: true,
493
+ router: mode.router,
494
+ appDir: mode.appDir ? path.relative(projectRoot, mode.appDir) : null,
495
+ pagesDir: mode.pagesDir ? path.relative(projectRoot, mode.pagesDir) : null,
496
+ basePath: mode.basePath,
497
+ trailingSlash: mode.trailingSlash,
498
+ rewrites: mode.rewrites,
499
+ middlewareFile: mode.middlewareFile ? path.relative(projectRoot, mode.middlewareFile) : null,
500
+ routes,
501
+ middleware,
502
+ };
503
+ }
504
+
505
+ // Helpers
506
+ function hashSnippet(text) {
507
+ return `sha256:${crypto.createHash("sha256").update(text).digest("hex")}`;
508
+ }
509
+
510
+ function hashPath(urlPath) {
511
+ return crypto.createHash("sha256").update(urlPath).digest("hex").slice(0, 12).toUpperCase();
512
+ }
513
+
514
+ module.exports = {
515
+ detectNextMode,
516
+ extractNextRoutes,
517
+ extractAppRouterRoutes,
518
+ extractPagesRouterRoutes,
519
+ extractMiddlewareMatchers,
520
+ convertNextPathToCanonical,
521
+ extractExportedMethods,
522
+ extractReqMethodChecks,
523
+ NEXT_HTTP_METHODS,
524
+ };