routecall-audit 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 routecall-audit contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,335 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
1
+ # routecall-audit
2
+
3
+ **Find broken API calls in your Next.js application before they reach production.**
4
+
5
+ `routecall-audit` is a lightweight CLI tool that checks frontend API requests against your Next.js API routes. It helps identify missing endpoints, unsupported HTTP methods, and unused API routes without starting your development server.
6
+
7
+ Built for Next.js developers who want to catch API integration mistakes early.
8
+
9
+ ## Features
10
+
11
+ - **Missing route detection** — Find API requests that reference routes that don't exist.
12
+ - **HTTP method validation** — Detect requests using unsupported methods.
13
+ - **Fetch and Axios support** — Analyze common API calls automatically.
14
+ - **Dynamic route support** — Understand Next.js dynamic API paths.
15
+ - **Unused route reporting** — Identify routes without detected frontend references.
16
+ - **CI/CD integration** — Run API checks as part of your development workflow.
17
+ - **JSON output** — Generate machine-readable reports.
18
+ - **Zero runtime dependencies** — No extra packages required.
19
+
20
+ ## Installation
21
+
22
+ Install as a development dependency:
23
+
24
+ ```bash
25
+ npm install --save-dev routecall-audit
26
+ ```
27
+
28
+ **Requirements:** Node.js 20 or later.
29
+
30
+ You can also run it directly using npx:
31
+
32
+ ```bash
33
+ npx routecall-audit .
34
+ ```
35
+
36
+ ## Quick Start
37
+
38
+ Open your Next.js project directory and run:
39
+
40
+ ```bash
41
+ npx routecall-audit .
42
+ ```
43
+
44
+ The tool scans your project, discovers local API routes, and compares them against supported frontend API calls.
45
+
46
+ ### Example
47
+
48
+ Suppose your Next.js project contains:
49
+
50
+ ```text
51
+ src/
52
+ ├── app/
53
+ │ └── api/
54
+ │ └── users/
55
+ │ ├── route.ts
56
+ │ └── [id]/
57
+ │ └── route.ts
58
+ └── components/
59
+ └── UserList.tsx
60
+ ```
61
+
62
+ Your frontend makes these requests:
63
+
64
+ ```typescript
65
+ fetch('/api/users');
66
+
67
+ fetch('/api/payments');
68
+
69
+ axios.delete('/api/users/123');
70
+ ```
71
+
72
+ However:
73
+
74
+ - `/api/users` exists.
75
+ - `/api/payments` does not exist.
76
+ - `/api/users/[id]` only supports GET requests.
77
+
78
+ Running the audit reports the detected problems:
79
+
80
+ ```text
81
+ FAIL MISSING_ROUTE
82
+ GET /api/payments has no matching local Next.js API route
83
+
84
+ FAIL METHOD_MISMATCH
85
+ DELETE /api/users/123 is not handled by
86
+ src/app/api/users/[id]/route.ts (GET, HEAD, OPTIONS)
87
+ ```
88
+
89
+ This makes it easier to identify API integration problems without manually checking every request.
90
+
91
+ ## CLI Commands
92
+
93
+ ### Check API routes
94
+
95
+ ```bash
96
+ npx routecall-audit .
97
+ ```
98
+
99
+ Scans the current project and reports detected API issues.
100
+
101
+ ### Check another project
102
+
103
+ ```bash
104
+ npx routecall-audit ./my-nextjs-app
105
+ ```
106
+
107
+ ### Generate a JSON report
108
+
109
+ ```bash
110
+ npx routecall-audit . --json
111
+ ```
112
+
113
+ Useful for automation, scripts, and custom reporting.
114
+
115
+ ### Report unused API routes
116
+
117
+ ```bash
118
+ npx routecall-audit . --report-unused
119
+ ```
120
+
121
+ Lists API routes that have no detected frontend references.
122
+
123
+ Note that some routes may intentionally be used by mobile applications, external services, or other clients.
124
+
125
+ ### Fail when unused routes are detected
126
+
127
+ ```bash
128
+ npx routecall-audit . --fail-on-unused
129
+ ```
130
+
131
+ Useful for projects that require every local API route to have a detected frontend reference.
132
+
133
+ ## Next.js Integration
134
+
135
+ Add a script to your project's `package.json`:
136
+
137
+ ```json
138
+ {
139
+ "scripts": {
140
+ "check:api": "routecall-audit ."
141
+ }
142
+ }
143
+ ```
144
+
145
+ Run the audit with:
146
+
147
+ ```bash
148
+ npm run check:api
149
+ ```
150
+
151
+ ### Run checks before building
152
+
153
+ You can also integrate the audit into your build process:
154
+
155
+ ```json
156
+ {
157
+ "scripts": {
158
+ "check:api": "routecall-audit .",
159
+ "prebuild": "npm run check:api"
160
+ }
161
+ }
162
+ ```
163
+
164
+ Now running `npm run build` will first execute the API audit.
165
+
166
+ Only enable this build check after confirming that your project's API call patterns are supported.
167
+
168
+ ## Supported API Routes
169
+
170
+ The tool supports both Next.js routing systems.
171
+
172
+ ### App Router
173
+
174
+ ```text
175
+ app/api/users/route.ts
176
+ app/api/users/[id]/route.ts
177
+ src/app/api/products/route.ts
178
+ ```
179
+
180
+ Recognized HTTP methods:
181
+
182
+ `GET` · `POST` · `PUT` · `PATCH` · `DELETE` · `HEAD` · `OPTIONS`
183
+
184
+ ### Pages Router
185
+
186
+ ```text
187
+ pages/api/users.ts
188
+ pages/api/products/[id].ts
189
+ src/pages/api/auth/login.ts
190
+ ```
191
+
192
+ Pages Router endpoints are detected, but their individual HTTP method conditions are not validated.
193
+
194
+ ### Dynamic Routes
195
+
196
+ Common Next.js dynamic routes are supported:
197
+
198
+ ```text
199
+ [id]
200
+ [...slug]
201
+ [[...slug]]
202
+ ```
203
+
204
+ For example:
205
+
206
+ ```text
207
+ app/api/users/[id]/route.ts
208
+ ```
209
+
210
+ Matches a frontend request such as:
211
+
212
+ ```javascript
213
+ fetch('/api/users/123');
214
+ ```
215
+
216
+ ## Supported API Calls
217
+
218
+ ### Fetch API
219
+
220
+ ```javascript
221
+ fetch('/api/users');
222
+
223
+ fetch('/api/users/123');
224
+
225
+ fetch('/api/users', {
226
+ method: 'POST'
227
+ });
228
+ ```
229
+
230
+ ### Axios
231
+
232
+ ```javascript
233
+ axios.get('/api/users');
234
+
235
+ axios.post('/api/users', data);
236
+
237
+ axios.put('/api/users/123', data);
238
+
239
+ axios.patch('/api/users/123', data);
240
+
241
+ axios.delete('/api/users/123');
242
+ ```
243
+
244
+ Simple template-literal URLs are also supported:
245
+
246
+ ```javascript
247
+ fetch(`/api/users/${userId}`);
248
+ ```
249
+
250
+ ## Programmatic Usage
251
+
252
+ You can use `routecall-audit` directly in Node.js applications.
253
+
254
+ ```javascript
255
+ import { scanProject } from 'routecall-audit';
256
+
257
+ const report = scanProject(process.cwd());
258
+
259
+ console.log(report.stats);
260
+
261
+ for (const issue of report.issues) {
262
+ console.log(
263
+ issue.code,
264
+ issue.file,
265
+ issue.line,
266
+ issue.message
267
+ );
268
+ }
269
+ ```
270
+
271
+ TypeScript declarations are included.
272
+
273
+ ## CI/CD Integration
274
+
275
+ You can run the package in GitHub Actions or another CI/CD environment.
276
+
277
+ Example GitHub Actions workflow:
278
+
279
+ ```yaml
280
+ name: API Route Audit
281
+
282
+ on:
283
+ push:
284
+ pull_request:
285
+
286
+ jobs:
287
+ audit:
288
+ runs-on: ubuntu-latest
289
+
290
+ steps:
291
+ - uses: actions/checkout@v4
292
+
293
+ - uses: actions/setup-node@v4
294
+ with:
295
+ node-version: 20
296
+
297
+ - run: npm ci
298
+
299
+ - run: npx routecall-audit .
300
+ ```
301
+
302
+ This checks supported API calls whenever the workflow runs.
303
+
304
+ ### Exit Codes
305
+
306
+ | Code | Meaning |
307
+ |---|---|
308
+ | `0` | Audit completed successfully |
309
+ | `1` | API issues detected |
310
+ | `2` | An error prevented the audit |
311
+
312
+
313
+ ## Contributing
314
+
315
+ Contributions, bug reports, and feature suggestions are welcome.
316
+
317
+ To work on the package locally:
318
+
319
+ ```bash
320
+ git clone https://github.com/HarshanaLK/routecall-audit.git
321
+
322
+ cd routecall-audit
323
+
324
+ npm install
325
+
326
+ npm test
327
+ ```
328
+
329
+ If you encounter an issue or have an improvement in mind, open a GitHub issue or submit a pull request.
330
+
331
+ ## License
332
+
333
+ MIT License.
334
+
335
+ See the `LICENSE` file for details.
@@ -0,0 +1,77 @@
1
+ #!/usr/bin/env node
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { scanProject } from '../src/index.js';
6
+
7
+ const args = process.argv.slice(2);
8
+ const pkgPath = new URL('../package.json', import.meta.url);
9
+ const version = JSON.parse(fs.readFileSync(fileURLToPath(pkgPath), 'utf8')).version;
10
+ const usage = `routecall-audit v${version}
11
+
12
+ Usage: routecall-audit [project-dir] [options]
13
+
14
+ Options:
15
+ --json Print JSON report (good for CI integration)
16
+ --report-unused List API routes with no detected local callers
17
+ --fail-on-unused Fail when unused routes exist (also reports them)
18
+ --help, -h Show help
19
+ --version, -v Show version
20
+
21
+ Exit codes: 0 = no issues, 1 = audit issues, 2 = invalid usage / runtime error.
22
+
23
+ Notes: only local /api fetch(...) and axios.get/post/etc. calls are inspected.
24
+ This is static analysis, not a guarantee of runtime API correctness.`;
25
+
26
+ function cli() {
27
+ if (args.includes('--help') || args.includes('-h')) {
28
+ console.log(usage);
29
+ return 0;
30
+ }
31
+ if (args.includes('--version') || args.includes('-v')) {
32
+ console.log(version);
33
+ return 0;
34
+ }
35
+ const flags = new Set(['--json', '--report-unused', '--fail-on-unused']);
36
+ const positionals = [];
37
+ for (const arg of args) {
38
+ if (arg.startsWith('-') && !flags.has(arg)) {
39
+ console.error(`Unknown option: ${arg}\n\n${usage}`);
40
+ return 2;
41
+ }
42
+ if (!arg.startsWith('-')) positionals.push(arg);
43
+ }
44
+ if (positionals.length > 1) {
45
+ console.error(`Expected at most one project directory.\n\n${usage}`);
46
+ return 2;
47
+ }
48
+ const report = scanProject(positionals[0] ?? process.cwd());
49
+ const wantUnused = args.includes('--report-unused') || args.includes('--fail-on-unused');
50
+ if (args.includes('--json')) {
51
+ console.log(JSON.stringify(report, null, 2));
52
+ } else {
53
+ console.log(`\nroutecall-audit — ${path.resolve(report.root)}`);
54
+ console.log(`${report.stats.filesScanned} source files | ${report.stats.routesFound} API routes | ${report.stats.callsFound} calls`);
55
+ if (!report.issues.length) console.log('PASS: no detectable API route mismatches.');
56
+ for (const issue of report.issues) {
57
+ console.log(`FAIL ${issue.code} ${issue.file}:${issue.line}`);
58
+ console.log(` ${issue.message}`);
59
+ }
60
+ if (wantUnused && report.unusedRoutes.length) {
61
+ console.log('\nUnused local API routes (these might be called externally):');
62
+ for (const route of report.unusedRoutes) console.log(` ${route.path} (${route.file})`);
63
+ }
64
+ if (report.skippedCalls) {
65
+ console.log(`Skipped ${report.skippedCalls} calls that could not be checked statically.`);
66
+ }
67
+ console.log('');
68
+ }
69
+ return (report.issues.length || (args.includes('--fail-on-unused') && report.unusedRoutes.length)) ? 1 : 0;
70
+ }
71
+
72
+ try {
73
+ process.exitCode = cli();
74
+ } catch (error) {
75
+ console.error(`routecall-audit: ${error.message}`);
76
+ process.exitCode = 2;
77
+ }
package/package.json CHANGED
@@ -1,6 +1,47 @@
1
- {
2
- "name": "routecall-audit",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
1
+ {
2
+ "name": "routecall-audit",
3
+ "version": "0.1.1",
4
+ "description": "Offline static audit of Next.js API route handlers against frontend fetch and Axios calls",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "engines": {
8
+ "node": ">=20"
9
+ },
10
+ "bin": {
11
+ "routecall-audit": "./bin/routecall-audit.js"
12
+ },
13
+ "main": "./src/index.js",
14
+ "types": "./src/index.d.ts",
15
+ "exports": {
16
+ ".": {
17
+ "types": "./src/index.d.ts",
18
+ "import": "./src/index.js"
19
+ }
20
+ },
21
+ "files": [
22
+ "bin/",
23
+ "src/",
24
+ "README.md",
25
+ "LICENSE"
26
+ ],
27
+ "scripts": {
28
+ "test": "node --test",
29
+ "audit:example": "node bin/routecall-audit.js examples/next-app",
30
+ "audit:example:json": "node bin/routecall-audit.js examples/next-app --json",
31
+ "pack:check": "npm pack --dry-run"
32
+ },
33
+ "keywords": [
34
+ "nextjs",
35
+ "api",
36
+ "static-analysis",
37
+ "routes",
38
+ "fetch",
39
+ "axios",
40
+ "cli",
41
+ "ci",
42
+ "developer-tools"
43
+ ],
44
+ "publishConfig": {
45
+ "access": "public"
46
+ }
47
+ }
package/src/index.d.ts ADDED
@@ -0,0 +1,37 @@
1
+ export type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'HEAD' | 'OPTIONS';
2
+ export type Route = {
3
+ path: string;
4
+ file: string;
5
+ methods: string[];
6
+ router: 'app' | 'pages';
7
+ };
8
+ export type ApiCall = {
9
+ method: HttpMethod;
10
+ url: string;
11
+ file: string;
12
+ line: number;
13
+ client: 'fetch' | 'axios';
14
+ };
15
+ export type AuditIssue = ApiCall & {
16
+ code: 'MISSING_ROUTE' | 'METHOD_MISMATCH';
17
+ message: string;
18
+ routeFile?: string;
19
+ };
20
+ export type AuditReport = {
21
+ root: string;
22
+ routes: Route[];
23
+ calls: ApiCall[];
24
+ issues: AuditIssue[];
25
+ unusedRoutes: Route[];
26
+ skippedCalls: number;
27
+ stats: {
28
+ filesScanned: number;
29
+ routesFound: number;
30
+ callsFound: number;
31
+ issuesFound: number;
32
+ unusedRoutes: number;
33
+ skippedCalls: number;
34
+ };
35
+ };
36
+ /** Run a conservative, offline audit of local /api fetch and axios calls against Next.js API routes. */
37
+ export declare function scanProject(root?: string): AuditReport;
package/src/index.js ADDED
@@ -0,0 +1,271 @@
1
+ /**
2
+ * routecall-audit: a conservative, offline checker for Next.js API routes.
3
+ * It only reports confidently identified local API calls. No code executes.
4
+ */
5
+ import fs from 'node:fs';
6
+ import path from 'node:path';
7
+
8
+ const SOURCE_EXT = /\.(?:[cm]?[jt]sx?)$/i;
9
+ const NEXT_ROUTE_EXT = /\.(?:[cm]?[jt]sx?)$/i;
10
+ const IGNORED_DIRS = new Set([
11
+ '.git', '.next', '.nuxt', '.output', '.turbo', '.vercel', 'node_modules',
12
+ 'dist', 'build', 'coverage', 'out', 'test', 'tests', '__tests__',
13
+ 'e2e', 'cypress', 'playwright', '.storybook'
14
+ ]);
15
+ const METHODS = new Set(['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS']);
16
+ const MAX_SOURCE_BYTES = 1024 * 1024;
17
+
18
+ function walk(root) {
19
+ const found = [];
20
+ function visit(current) {
21
+ for (const entry of fs.readdirSync(current, { withFileTypes: true })) {
22
+ if (entry.isSymbolicLink()) continue;
23
+ const full = path.join(current, entry.name);
24
+ if (entry.isDirectory()) {
25
+ if (!IGNORED_DIRS.has(entry.name)) visit(full);
26
+ } else if (entry.isFile() && SOURCE_EXT.test(entry.name) &&
27
+ !entry.name.endsWith('.d.ts') && fs.statSync(full).size <= MAX_SOURCE_BYTES) {
28
+ found.push(full);
29
+ }
30
+ }
31
+ }
32
+ visit(root);
33
+ return found.sort();
34
+ }
35
+
36
+ function toPosix(file) {
37
+ return file.split(path.sep).join('/');
38
+ }
39
+
40
+ function routeSegments(relativeFile) {
41
+ const parts = toPosix(relativeFile).split('/');
42
+ let start = -1;
43
+ let mode = '';
44
+ if (parts[0] === 'src' && (parts[1] === 'app' || parts[1] === 'pages')) {
45
+ start = 2;
46
+ mode = parts[1];
47
+ } else if (parts[0] === 'app' || parts[0] === 'pages') {
48
+ start = 1;
49
+ mode = parts[0];
50
+ }
51
+ if (start === -1) return null;
52
+
53
+ const filename = parts.at(-1);
54
+ let segments;
55
+ if (mode === 'app' && /^route\.[cm]?[jt]sx?$/i.test(filename)) {
56
+ segments = parts.slice(start, -1).filter((seg) => !/^\(.*\)$/.test(seg) && !seg.startsWith('@'));
57
+ } else if (mode === 'pages' && parts[start] === 'api' && NEXT_ROUTE_EXT.test(filename) &&
58
+ !/^_/.test(filename)) {
59
+ segments = parts.slice(start);
60
+ segments[segments.length - 1] = filename.replace(NEXT_ROUTE_EXT, '');
61
+ if (segments.at(-1) === 'index') segments.pop();
62
+ } else {
63
+ return null;
64
+ }
65
+ if (segments[0] !== 'api') return null;
66
+ return { mode, routePath: '/' + segments.join('/') };
67
+ }
68
+
69
+ function appRouteMethods(source) {
70
+ const methods = new Set();
71
+ // App Router: export function GET(), export async function POST(),
72
+ // export const PUT = async ..., export { GET, POST }.
73
+ const direct = /\bexport\s+(?:(?:default|declare)\s+)?(?:async\s+)?(?:function|const|let)\s+(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)\b/g;
74
+ for (const match of source.matchAll(direct)) methods.add(match[1]);
75
+ const namedExports = /\bexport\s*\{([^}]+)\}/g;
76
+ for (const match of source.matchAll(namedExports)) {
77
+ for (const entry of match[1].split(',')) {
78
+ const exportedName = entry.trim().split(/\s+as\s+/i).at(-1)?.trim();
79
+ if (METHODS.has(exportedName)) methods.add(exportedName);
80
+ }
81
+ }
82
+ // Next.js supplies HEAD for GET and auto-implements OPTIONS.
83
+ if (methods.has('GET')) methods.add('HEAD');
84
+ if (methods.size) methods.add('OPTIONS');
85
+ return [...methods].sort();
86
+ }
87
+
88
+ function discoverRoutes(files, root) {
89
+ const routes = [];
90
+ for (const file of files) {
91
+ const relative = toPosix(path.relative(root, file));
92
+ const info = routeSegments(relative);
93
+ if (!info) continue;
94
+ const source = fs.readFileSync(file, 'utf8');
95
+ const methods = info.mode === 'pages' ? ['*'] : appRouteMethods(source);
96
+ routes.push({ path: info.routePath, file: relative, methods, router: info.mode });
97
+ }
98
+ return routes.sort((a, b) => a.path.localeCompare(b.path) || a.file.localeCompare(b.file));
99
+ }
100
+
101
+ /**
102
+ * Extract a balanced JS invocation, ignoring parentheses inside quoted strings.
103
+ * Deliberately conservative: an incomplete call is skipped.
104
+ */
105
+ function invocationBody(text, openIndex) {
106
+ let depth = 0;
107
+ let quote = null;
108
+ let escaped = false;
109
+ for (let i = openIndex; i < text.length; i++) {
110
+ const char = text[i];
111
+ if (quote !== null) {
112
+ if (escaped) escaped = false;
113
+ else if (char === '\\') escaped = true;
114
+ else if (char === quote) quote = null;
115
+ continue;
116
+ }
117
+ if (char === '"' || char === "'" || char === '`') {
118
+ quote = char;
119
+ } else if (char === '(') {
120
+ depth++;
121
+ } else if (char === ')') {
122
+ depth--;
123
+ if (depth === 0) return text.slice(openIndex + 1, i);
124
+ }
125
+ }
126
+ return null;
127
+ }
128
+
129
+ function literalFirstArgument(body) {
130
+ const trimmed = body.trimStart();
131
+ const quote = trimmed[0];
132
+ if (quote !== '"' && quote !== "'" && quote !== '`') return null;
133
+ let escaped = false;
134
+ for (let i = 1; i < trimmed.length; i++) {
135
+ const ch = trimmed[i];
136
+ if (escaped) { escaped = false; continue; }
137
+ if (ch === '\\') { escaped = true; continue; }
138
+ if (ch === quote) {
139
+ const rest = trimmed.slice(i + 1).trimStart();
140
+ if (rest && !rest.startsWith(',')) return null;
141
+ return { rawUrl: trimmed.slice(1, i), rest, quote };
142
+ }
143
+ }
144
+ return null;
145
+ }
146
+
147
+ function normalizeCallPath(rawUrl, quote) {
148
+ let pathname = rawUrl;
149
+ if (quote === '`') {
150
+ // Accept one interpolated expression per entire path segment.
151
+ pathname = pathname.replace(/\$\{[^{}]*\}/g, '__dynamic__');
152
+ if (pathname.includes('${')) return null;
153
+ }
154
+ if (!pathname.startsWith('/api') || (pathname.length > 4 && !['/', '?', '#'].includes(pathname[4]))) return null;
155
+ pathname = pathname.split(/[?#]/, 1)[0].replace(/\/+$/, '') || '/';
156
+ if (!pathname.split('/').every((segment) => !segment.includes('__dynamic__') || segment === '__dynamic__')) return null;
157
+ if (pathname.includes('\\')) return null;
158
+ return pathname;
159
+ }
160
+
161
+ function fetchMethod(rest) {
162
+ if (!rest) return 'GET';
163
+ const match = rest.match(/\bmethod\s*:\s*(['"`])([A-Za-z]+)\1/);
164
+ if (match) return match[2].toUpperCase();
165
+ // If the HTTP method is computed we must not guess GET.
166
+ if (/\bmethod\b/.test(rest)) return null;
167
+ return 'GET';
168
+ }
169
+
170
+ function sourceLine(text, offset) {
171
+ return text.slice(0, offset).split('\n').length;
172
+ }
173
+
174
+ function collectCalls(files, root) {
175
+ const calls = [];
176
+ let skippedCalls = 0;
177
+ for (const file of files) {
178
+ const relative = toPosix(path.relative(root, file));
179
+ const source = fs.readFileSync(file, 'utf8');
180
+ // axios and global fetch only. No user-controlled modules execute.
181
+ const pattern = /\b(fetch|axios\s*\.\s*(?:get|post|put|patch|delete|head|options))\s*\(/g;
182
+ for (const match of source.matchAll(pattern)) {
183
+ const open = match.index + match[0].length - 1;
184
+ const body = invocationBody(source, open);
185
+ if (body === null) { skippedCalls++; continue; }
186
+ const arg = literalFirstArgument(body);
187
+ if (!arg) { skippedCalls++; continue; }
188
+ const url = normalizeCallPath(arg.rawUrl, arg.quote);
189
+ if (!url) { skippedCalls++; continue; }
190
+ const method = match[1].startsWith('axios')
191
+ ? match[1].split('.').at(-1).trim().toUpperCase()
192
+ : fetchMethod(arg.rest);
193
+ if (!method || !METHODS.has(method)) { skippedCalls++; continue; }
194
+ calls.push({ method, url, file: relative, line: sourceLine(source, match.index),
195
+ client: match[1].startsWith('axios') ? 'axios' : 'fetch' });
196
+ }
197
+ }
198
+ return { calls, skippedCalls };
199
+ }
200
+
201
+ function matchesRoute(patternPath, actualPath) {
202
+ const expected = patternPath.split('/').filter(Boolean);
203
+ const actual = actualPath.split('/').filter(Boolean);
204
+ function matches(i, j) {
205
+ if (i === expected.length) return j === actual.length;
206
+ const segment = expected[i];
207
+ if (/^\[\[\.\.\.[^\]]+\]\]$/.test(segment)) {
208
+ if (i === expected.length - 1) return true;
209
+ for (let k = j; k <= actual.length; k++) if (matches(i + 1, k)) return true;
210
+ return false;
211
+ }
212
+ if (/^\[\.\.\.[^\]]+\]$/.test(segment)) {
213
+ if (i === expected.length - 1) return j < actual.length;
214
+ for (let k = j + 1; k <= actual.length; k++) if (matches(i + 1, k)) return true;
215
+ return false;
216
+ }
217
+ if (j >= actual.length) return false;
218
+ if (segment === actual[j] || /^\[[^\]]+\]$/.test(segment)) return matches(i + 1, j + 1);
219
+ return false;
220
+ }
221
+ return matches(0, 0);
222
+ }
223
+
224
+ function specificity(patternPath) {
225
+ return patternPath.split('/').filter(Boolean).reduce((score, seg) => {
226
+ if (/^\[\[\.\.\./.test(seg)) return score + 1;
227
+ if (/^\[\.\.\./.test(seg)) return score + 2;
228
+ if (/^\[/.test(seg)) return score + 10;
229
+ return score + 100;
230
+ }, 0);
231
+ }
232
+
233
+ /**
234
+ * Scan a Next.js project without installing its dependencies or running its code.
235
+ * @param {string} root project folder (defaults to current working directory)
236
+ * @returns {AuditReport} routes, calls, issues, unusedRoutes, stats
237
+ */
238
+ export function scanProject(root = process.cwd()) {
239
+ const absolute = path.resolve(root);
240
+ if (!fs.existsSync(absolute) || !fs.statSync(absolute).isDirectory()) {
241
+ throw new Error(`Project directory does not exist: ${absolute}`);
242
+ }
243
+ const files = walk(absolute);
244
+ const routes = discoverRoutes(files, absolute);
245
+ const { calls, skippedCalls } = collectCalls(files, absolute);
246
+ const issues = [];
247
+ const used = new Set();
248
+ for (const call of calls) {
249
+ const matches = routes.filter((route) => matchesRoute(route.path, call.url))
250
+ .sort((a, b) => specificity(b.path) - specificity(a.path));
251
+ const best = matches[0];
252
+ if (!best) {
253
+ issues.push({ code: 'MISSING_ROUTE', ...call,
254
+ message: `${call.method} ${call.url} has no matching local Next.js API route` });
255
+ continue;
256
+ }
257
+ used.add(best.file);
258
+ // An app route with no recognizable methods is skipped rather than assumed broken.
259
+ if (best.methods.length && !best.methods.includes('*') && !best.methods.includes(call.method)) {
260
+ issues.push({ code: 'METHOD_MISMATCH', ...call, routeFile: best.file,
261
+ message: `${call.method} ${call.url} is not handled by ${best.file} (${best.methods.join(', ')})` });
262
+ }
263
+ }
264
+ const unusedRoutes = routes.filter((route) => !used.has(route.file));
265
+ return {
266
+ root: absolute, routes, calls, issues, unusedRoutes, skippedCalls,
267
+ stats: { filesScanned: files.length, routesFound: routes.length,
268
+ callsFound: calls.length, issuesFound: issues.length,
269
+ unusedRoutes: unusedRoutes.length, skippedCalls }
270
+ };
271
+ }