routescope 0.0.0-stage → 0.1.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.
- package/LICENSE +21 -0
- package/README.md +214 -2
- package/bin/routescope.js +7 -0
- package/package.json +66 -4
- package/src/analyzer.js +138 -0
- package/src/cli.js +86 -0
- package/src/config.js +71 -0
- package/src/index.js +6 -0
- package/src/parser.js +207 -0
- package/src/reporters.js +161 -0
- package/src/resolver.js +175 -0
- package/src/scanner.js +57 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Your Name
|
|
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,215 @@
|
|
|
1
|
-
#
|
|
1
|
+
# RouteScope
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Discover, document and audit **Express** API routes from your terminal.
|
|
4
|
+
|
|
5
|
+
RouteScope statically analyses a JavaScript Express codebase, resolves nested router
|
|
6
|
+
mounts into their real, fully-qualified paths, and reports duplicate routes,
|
|
7
|
+
potentially unprotected endpoints, and routers it could not link to an app entry
|
|
8
|
+
point. Output is available as a terminal table, JSON, Markdown, or a Mermaid
|
|
9
|
+
diagram.
|
|
10
|
+
|
|
11
|
+
```text
|
|
12
|
+
$ routescope scan ./my-express-app
|
|
13
|
+
|
|
14
|
+
ROUTESCOPE ANALYSIS
|
|
15
|
+
|
|
16
|
+
GET / [unprotected]
|
|
17
|
+
GET /api/users [unprotected]
|
|
18
|
+
POST /api/users
|
|
19
|
+
GET /api/users/:id
|
|
20
|
+
PATCH /api/users/:id
|
|
21
|
+
DELETE /api/users/:id [unprotected]
|
|
22
|
+
GET /api/users/:userId [unprotected]
|
|
23
|
+
GET /health
|
|
24
|
+
|
|
25
|
+
Total Routes: 8
|
|
26
|
+
Files: 4 · Protected: 3 · Unprotected: 4 · Duplicates: 1
|
|
27
|
+
|
|
28
|
+
Warnings:
|
|
29
|
+
⚠ GET /api/users/:id
|
|
30
|
+
GET /api/users/:id collides with 1 other route(s) of the same shape
|
|
31
|
+
at src/routes/users.js:8
|
|
32
|
+
at src/routes/users.js:11
|
|
33
|
+
⚠ DELETE /api/users/:id
|
|
34
|
+
No recognized authentication middleware
|
|
35
|
+
at src/routes/users.js:10
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
## Why
|
|
39
|
+
|
|
40
|
+
Finding `app.get(...)` is easy. Understanding that
|
|
41
|
+
|
|
42
|
+
```js
|
|
43
|
+
// src/app.js
|
|
44
|
+
app.use('/api/users', usersRouter);
|
|
45
|
+
|
|
46
|
+
// src/routes/users.js
|
|
47
|
+
router.get('/:id', requireAuth, getUser);
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
exposes `GET /api/users/:id` — not `GET /:id` — is the hard part. RouteScope
|
|
51
|
+
builds a small mount graph, joins prefixes, and propagates authentication
|
|
52
|
+
middleware down the graph.
|
|
53
|
+
|
|
54
|
+
## Install
|
|
55
|
+
|
|
56
|
+
```bash
|
|
57
|
+
npm install --save-dev routescope
|
|
58
|
+
# or run it without installing
|
|
59
|
+
npx routescope scan .
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
Requires Node.js 20 or newer.
|
|
63
|
+
|
|
64
|
+
## Usage
|
|
65
|
+
|
|
66
|
+
```bash
|
|
67
|
+
routescope scan [dir] [options]
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
| Option | Description |
|
|
71
|
+
| ----------------------- | --------------------------------------------------------------------- |
|
|
72
|
+
| `-f, --format <format>` | `table` (default), `json`, `markdown` / `md`, `mermaid` |
|
|
73
|
+
| `-o, --output <file>` | Write the report to a file instead of stdout |
|
|
74
|
+
| `--include <glob>` | Additional glob of files to scan (repeatable) |
|
|
75
|
+
| `--ignore <glob>` | Glob of files to ignore (repeatable) |
|
|
76
|
+
| `--entry <file>` | Scan a single entry file |
|
|
77
|
+
| `-c, --config <file>` | Path to a config file |
|
|
78
|
+
| `--fail-on <level>` | Exit with code 1 on `warning` or `error` findings (`none` by default) |
|
|
79
|
+
| `--no-color` | Disable coloured output |
|
|
80
|
+
| `--verbose` | Show file and line for every route |
|
|
81
|
+
| `--quiet` | Suppress the spinner |
|
|
82
|
+
|
|
83
|
+
Examples:
|
|
84
|
+
|
|
85
|
+
```bash
|
|
86
|
+
# A shareable route table in a Markdown doc
|
|
87
|
+
routescope scan --format markdown --output docs/API.md
|
|
88
|
+
|
|
89
|
+
# A diagram GitHub renders natively
|
|
90
|
+
routescope scan --format mermaid --output docs/api-architecture.mmd
|
|
91
|
+
|
|
92
|
+
# Machine-readable output
|
|
93
|
+
routescope scan --format json --output routes.json
|
|
94
|
+
|
|
95
|
+
# Use findings in CI
|
|
96
|
+
routescope scan --fail-on warning
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
Reports go to **stdout**; the spinner and errors go to **stderr**, so
|
|
100
|
+
`routescope scan --format json > routes.json` always produces valid JSON.
|
|
101
|
+
|
|
102
|
+
### Exit codes
|
|
103
|
+
|
|
104
|
+
| Code | Meaning |
|
|
105
|
+
| ---- | ---------------------------------------------------------------- |
|
|
106
|
+
| `0` | Scan completed, no findings at or above the `--fail-on` level |
|
|
107
|
+
| `1` | Findings at or above the `--fail-on` level |
|
|
108
|
+
| `2` | The tool itself failed (parse error, bad config, unknown format) |
|
|
109
|
+
|
|
110
|
+
## Configuration
|
|
111
|
+
|
|
112
|
+
Create `routescope.config.js` (or `.mjs` in a CommonJS project) at the project
|
|
113
|
+
root. Every field is optional.
|
|
114
|
+
|
|
115
|
+
```js
|
|
116
|
+
export default {
|
|
117
|
+
include: ['src/**/*.{js,mjs,cjs}'],
|
|
118
|
+
ignore: ['**/node_modules/**', '**/*.test.js'],
|
|
119
|
+
entry: null,
|
|
120
|
+
authPatterns: ['^ensureTenant$'],
|
|
121
|
+
publicRoutes: ['/health', '/auth/login', '/webhooks/*'],
|
|
122
|
+
warnOnGet: false,
|
|
123
|
+
};
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
| Field | Default | Purpose |
|
|
127
|
+
| -------------- | ---------------------------------------------------- | ------------------------------------------------------- |
|
|
128
|
+
| `include` | `['**/*.{js,mjs,cjs}']` | Glob(s) of files to parse |
|
|
129
|
+
| `ignore` | node_modules, dist, build, coverage, tests, fixtures | Globs to skip |
|
|
130
|
+
| `entry` | `null` | Analyse only one entry file |
|
|
131
|
+
| `authPatterns` | `[]` | Extra regular expressions that identify auth middleware |
|
|
132
|
+
| `publicRoutes` | `/health`, `/auth/login`, … | Intentionally public paths (`*` suffix supported) |
|
|
133
|
+
| `warnOnGet` | `false` | Also flag unprotected GET routes |
|
|
134
|
+
|
|
135
|
+
## What gets reported
|
|
136
|
+
|
|
137
|
+
- **Fully-qualified paths** — nested mounts are composed (`/api` + `/users` + `/:id`).
|
|
138
|
+
- **Duplicate routes** — `DUPLICATE_ROUTE` (error) for the same method + path
|
|
139
|
+
registered twice, and `DUPLICATE_ROUTE_SHAPE` (warning) for collisions such as
|
|
140
|
+
`/:id` vs `/:userId`, where Express keeps only the first handler.
|
|
141
|
+
- **Unprotected endpoints** — write methods and sensitive paths (`/admin`,
|
|
142
|
+
`/internal`, `/private`, `/manage`) without recognised auth middleware.
|
|
143
|
+
- **Unreachable routes** — info-level findings for routers that no entry point
|
|
144
|
+
mounts.
|
|
145
|
+
- **Parse errors** — one unparsable file does not abort the scan.
|
|
146
|
+
|
|
147
|
+
## Library usage
|
|
148
|
+
|
|
149
|
+
```js
|
|
150
|
+
import { scanProject, renderReport } from 'routescope';
|
|
151
|
+
|
|
152
|
+
const result = await scanProject({ cwd: './my-app' });
|
|
153
|
+
console.log(result.summary.totalRoutes);
|
|
154
|
+
console.log(renderReport(result, { format: 'markdown' }));
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
`result` contains `routes`, `warnings`, `duplicates`, `parseErrors`, and a
|
|
158
|
+
`summary` with per-method counts.
|
|
159
|
+
|
|
160
|
+
## How it works
|
|
161
|
+
|
|
162
|
+
```text
|
|
163
|
+
discover → parse → resolve → analyse → render
|
|
164
|
+
fast-glob acorn mount graph warnings reporters
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
| Module | Responsibility |
|
|
168
|
+
| ------------------ | ------------------------------------------------------- |
|
|
169
|
+
| `src/config.js` | Defaults, config loading, auth-name matcher |
|
|
170
|
+
| `src/parser.js` | One file → routes, `use()` calls, imports, router names |
|
|
171
|
+
| `src/resolver.js` | Mount graph → fully-qualified routes + inherited auth |
|
|
172
|
+
| `src/analyzer.js` | Duplicates, unprotected routes, summary |
|
|
173
|
+
| `src/reporters.js` | Result → table / JSON / Markdown / Mermaid |
|
|
174
|
+
| `src/scanner.js` | Orchestrates the pipeline |
|
|
175
|
+
| `src/cli.js` | Commander + Ora + file output |
|
|
176
|
+
|
|
177
|
+
## Heuristics and limitations
|
|
178
|
+
|
|
179
|
+
- Authentication detection is **heuristic**. It recognises names like
|
|
180
|
+
`requireAuth`, `ensureLoggedIn`, `verifyJwt`, `passport.authenticate`, and
|
|
181
|
+
`apiKey`, and can be extended with `authPatterns`. Always review findings.
|
|
182
|
+
- Only static string paths are reported. Computed paths such as
|
|
183
|
+
`'/users/' + id` are ignored rather than guessed.
|
|
184
|
+
- Dynamic mounts (`app.use('/api', buildRouter())`) and router factories are not
|
|
185
|
+
resolved. Assign the router to a variable and export it for best results.
|
|
186
|
+
- Files with several routers use the declared router (or the single route owner)
|
|
187
|
+
as the entry router. Unusual factory patterns are reported as unreachable.
|
|
188
|
+
- Route arrays and `app.use('/x', router1, router2)` chains are not expanded.
|
|
189
|
+
- TypeScript is not parsed out of the box; point `include` at compiled JavaScript.
|
|
190
|
+
|
|
191
|
+
## Development
|
|
192
|
+
|
|
193
|
+
```bash
|
|
194
|
+
npm install
|
|
195
|
+
npm test # Vitest
|
|
196
|
+
npm run coverage # V8 coverage
|
|
197
|
+
npm run lint # ESLint flat config
|
|
198
|
+
npm run format # Prettier write
|
|
199
|
+
npm run format:check # Prettier check (CI)
|
|
200
|
+
npm run scan # Run the CLI against the bundled fixtures
|
|
201
|
+
```
|
|
202
|
+
|
|
203
|
+
Inspection helpers:
|
|
204
|
+
|
|
205
|
+
```bash
|
|
206
|
+
node scripts/inspect-parser.js test/fixtures/basic-app/src/routes/users.js
|
|
207
|
+
node scripts/inspect-routes.js test/fixtures/basic-app
|
|
208
|
+
```
|
|
209
|
+
|
|
210
|
+
The GitHub Actions workflows run lint, format check, and coverage on Node 20, 22,
|
|
211
|
+
and 24, and publish tagged releases with npm provenance.
|
|
212
|
+
|
|
213
|
+
## License
|
|
214
|
+
|
|
215
|
+
MIT
|
package/package.json
CHANGED
|
@@ -1,6 +1,68 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "routescope",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Discover, document and audit Express API routes from your terminal.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"bin": {
|
|
7
|
+
"routescope": "bin/routescope.js"
|
|
8
|
+
},
|
|
9
|
+
"main": "./src/index.js",
|
|
10
|
+
"exports": {
|
|
11
|
+
".": "./src/index.js"
|
|
12
|
+
},
|
|
13
|
+
"files": [
|
|
14
|
+
"bin",
|
|
15
|
+
"src",
|
|
16
|
+
"README.md",
|
|
17
|
+
"LICENSE"
|
|
18
|
+
],
|
|
19
|
+
"engines": {
|
|
20
|
+
"node": ">=20"
|
|
21
|
+
},
|
|
22
|
+
"scripts": {
|
|
23
|
+
"scan": "node bin/routescope.js scan test/fixtures/basic-app",
|
|
24
|
+
"test": "vitest run",
|
|
25
|
+
"test:watch": "vitest",
|
|
26
|
+
"coverage": "vitest run --coverage",
|
|
27
|
+
"lint": "eslint .",
|
|
28
|
+
"lint:fix": "eslint . --fix",
|
|
29
|
+
"format": "prettier --write .",
|
|
30
|
+
"format:check": "prettier --check ."
|
|
31
|
+
},
|
|
32
|
+
"keywords": [
|
|
33
|
+
"express",
|
|
34
|
+
"routes",
|
|
35
|
+
"api",
|
|
36
|
+
"cli",
|
|
37
|
+
"documentation",
|
|
38
|
+
"ast",
|
|
39
|
+
"acorn"
|
|
40
|
+
],
|
|
41
|
+
"license": "MIT",
|
|
42
|
+
"repository": {
|
|
43
|
+
"type": "git",
|
|
44
|
+
"url": "git+https://github.com/rehat2007/route_scope.git"
|
|
45
|
+
},
|
|
46
|
+
"homepage": "https://github.com/rehat2007/route_scope#readme",
|
|
47
|
+
"bugs": {
|
|
48
|
+
"url": "https://github.com/rehat2007/route_scope/issues"
|
|
49
|
+
},
|
|
50
|
+
"dependencies": {
|
|
51
|
+
"acorn": "^8.19.0",
|
|
52
|
+
"chalk": "^5.6.2",
|
|
53
|
+
"commander": "^13.1.0",
|
|
54
|
+
"fast-glob": "^3.3.3",
|
|
55
|
+
"ora": "^8.2.0"
|
|
56
|
+
},
|
|
57
|
+
"devDependencies": {
|
|
58
|
+
"@eslint/js": "^10.0.1",
|
|
59
|
+
"@vitest/coverage-v8": "^3.2.7",
|
|
60
|
+
"eslint": "^10.16.0",
|
|
61
|
+
"globals": "^17.14.0",
|
|
62
|
+
"prettier": "^3.10.1",
|
|
63
|
+
"vitest": "^3.2.7"
|
|
64
|
+
},
|
|
65
|
+
"overrides": {
|
|
66
|
+
"rollup": "npm:@rollup/wasm-node@^4.69.2"
|
|
67
|
+
}
|
|
68
|
+
}
|
package/src/analyzer.js
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
import { buildAuthMatcher } from './config.js';
|
|
2
|
+
|
|
3
|
+
const WRITE_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE']);
|
|
4
|
+
const METHOD_ORDER = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS', 'ALL'];
|
|
5
|
+
const SENSITIVE_PATH = /^\/(admin|internal|private|manage)\b/i;
|
|
6
|
+
|
|
7
|
+
function shape(path) {
|
|
8
|
+
return path
|
|
9
|
+
.split('/')
|
|
10
|
+
.map((segment) => (segment.startsWith(':') ? ':param' : segment))
|
|
11
|
+
.join('/');
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function isPublicRoute(path, publicRoutes) {
|
|
15
|
+
return publicRoutes.some((entry) =>
|
|
16
|
+
entry.endsWith('*') ? path.startsWith(entry.slice(0, -1)) : path === entry,
|
|
17
|
+
);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function pick(route) {
|
|
21
|
+
return {
|
|
22
|
+
method: route.method,
|
|
23
|
+
path: route.path,
|
|
24
|
+
file: route.file,
|
|
25
|
+
line: route.line,
|
|
26
|
+
protected: route.protected,
|
|
27
|
+
mounted: route.mounted,
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function analyze({ routes, files, config, parseErrors = [] }) {
|
|
32
|
+
const isAuth = buildAuthMatcher(config.authPatterns);
|
|
33
|
+
const publicRoutes = config.publicRoutes ?? [];
|
|
34
|
+
|
|
35
|
+
const enriched = routes.map((route) => ({
|
|
36
|
+
...route,
|
|
37
|
+
protected: route.protected || route.middlewares.some(isAuth),
|
|
38
|
+
public: isPublicRoute(route.path, publicRoutes),
|
|
39
|
+
}));
|
|
40
|
+
|
|
41
|
+
const warnings = [];
|
|
42
|
+
|
|
43
|
+
// 1. Exact duplicates and same-shape collisions (e.g. /:id vs /:userId).
|
|
44
|
+
const groups = new Map();
|
|
45
|
+
for (const route of enriched) {
|
|
46
|
+
const key = `${route.method} ${shape(route.path)}`;
|
|
47
|
+
if (!groups.has(key)) groups.set(key, []);
|
|
48
|
+
groups.get(key).push(route);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const duplicates = [];
|
|
52
|
+
for (const [key, group] of groups) {
|
|
53
|
+
if (group.length < 2) continue;
|
|
54
|
+
duplicates.push({ key, routes: group.map(pick) });
|
|
55
|
+
const identical = new Set(group.map((route) => route.path)).size === 1;
|
|
56
|
+
warnings.push({
|
|
57
|
+
code: identical ? 'DUPLICATE_ROUTE' : 'DUPLICATE_ROUTE_SHAPE',
|
|
58
|
+
severity: identical ? 'error' : 'warning',
|
|
59
|
+
message: identical
|
|
60
|
+
? `${group[0].method} ${group[0].path} is registered ${group.length} times`
|
|
61
|
+
: `${group[0].method} ${group[0].path} collides with ${group.length - 1} other route(s) of the same shape`,
|
|
62
|
+
route: pick(group[0]),
|
|
63
|
+
locations: group.map(pick),
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// 2. Unprotected sensitive endpoints (heuristic).
|
|
68
|
+
for (const route of enriched) {
|
|
69
|
+
if (route.protected || route.public) continue;
|
|
70
|
+
const sensitive = WRITE_METHODS.has(route.method) || SENSITIVE_PATH.test(route.path);
|
|
71
|
+
if (!sensitive && !config.warnOnGet) continue;
|
|
72
|
+
warnings.push({
|
|
73
|
+
code: 'UNPROTECTED_ROUTE',
|
|
74
|
+
severity: 'warning',
|
|
75
|
+
message: 'No recognized authentication middleware',
|
|
76
|
+
route: pick(route),
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// 3. Routes we could not attach to an app entry point.
|
|
81
|
+
const unreachable = enriched.filter((route) => !route.mounted);
|
|
82
|
+
if (unreachable.length) {
|
|
83
|
+
const byFile = new Map();
|
|
84
|
+
for (const route of unreachable) {
|
|
85
|
+
if (!byFile.has(route.file)) byFile.set(route.file, []);
|
|
86
|
+
byFile.get(route.file).push(route);
|
|
87
|
+
}
|
|
88
|
+
for (const fileRoutes of byFile.values()) {
|
|
89
|
+
warnings.push({
|
|
90
|
+
code: 'UNREACHABLE_ROUTE',
|
|
91
|
+
severity: 'info',
|
|
92
|
+
message: `${fileRoutes.length} route(s) could not be linked to an app entry point`,
|
|
93
|
+
locations: fileRoutes.map(pick),
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
enriched.sort(
|
|
99
|
+
(a, b) =>
|
|
100
|
+
a.path.localeCompare(b.path) ||
|
|
101
|
+
METHOD_ORDER.indexOf(a.method) - METHOD_ORDER.indexOf(b.method) ||
|
|
102
|
+
a.file.localeCompare(b.file),
|
|
103
|
+
);
|
|
104
|
+
|
|
105
|
+
const severityOrder = { error: 0, warning: 1, info: 2 };
|
|
106
|
+
warnings.sort(
|
|
107
|
+
(a, b) =>
|
|
108
|
+
severityOrder[a.severity] - severityOrder[b.severity] ||
|
|
109
|
+
(a.route?.path ?? '').localeCompare(b.route?.path ?? ''),
|
|
110
|
+
);
|
|
111
|
+
|
|
112
|
+
const byMethod = {};
|
|
113
|
+
for (const route of enriched) {
|
|
114
|
+
byMethod[route.method] = (byMethod[route.method] ?? 0) + 1;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
const warningCounts = { error: 0, warning: 0, info: 0 };
|
|
118
|
+
for (const warning of warnings) warningCounts[warning.severity] += 1;
|
|
119
|
+
|
|
120
|
+
return {
|
|
121
|
+
generatedAt: new Date().toISOString(),
|
|
122
|
+
root: config.cwd,
|
|
123
|
+
routes: enriched,
|
|
124
|
+
warnings,
|
|
125
|
+
duplicates,
|
|
126
|
+
parseErrors,
|
|
127
|
+
summary: {
|
|
128
|
+
files: files.length,
|
|
129
|
+
totalRoutes: enriched.length,
|
|
130
|
+
uniqueRoutes: new Set(enriched.map((route) => `${route.method} ${route.path}`)).size,
|
|
131
|
+
protectedRoutes: enriched.filter((route) => route.protected).length,
|
|
132
|
+
unprotectedRoutes: enriched.filter((route) => !route.protected && !route.public).length,
|
|
133
|
+
byMethod,
|
|
134
|
+
duplicates: duplicates.length,
|
|
135
|
+
warnings: warningCounts,
|
|
136
|
+
},
|
|
137
|
+
};
|
|
138
|
+
}
|
package/src/cli.js
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
import { mkdir, writeFile } from 'node:fs/promises';
|
|
3
|
+
import { dirname, resolve } from 'node:path';
|
|
4
|
+
import { Command, Option } from 'commander';
|
|
5
|
+
import chalk from 'chalk';
|
|
6
|
+
import ora from 'ora';
|
|
7
|
+
import { scanProject } from './scanner.js';
|
|
8
|
+
import { renderReport } from './reporters.js';
|
|
9
|
+
|
|
10
|
+
const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
|
|
11
|
+
|
|
12
|
+
function collect(value, previous) {
|
|
13
|
+
return [...previous, value];
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export async function run(argv = process.argv) {
|
|
17
|
+
const program = new Command();
|
|
18
|
+
|
|
19
|
+
program
|
|
20
|
+
.name('routescope')
|
|
21
|
+
.description('Discover, document and audit Express API routes.')
|
|
22
|
+
.version(pkg.version);
|
|
23
|
+
|
|
24
|
+
program
|
|
25
|
+
.command('scan')
|
|
26
|
+
.description('Scan a project for Express routes')
|
|
27
|
+
.argument('[dir]', 'project directory to scan', '.')
|
|
28
|
+
.option('-f, --format <format>', 'output format: table, json, markdown, mermaid', 'table')
|
|
29
|
+
.option('-o, --output <file>', 'write the report to a file instead of stdout')
|
|
30
|
+
.option('--include <glob>', 'additional glob of files to scan (repeatable)', collect, [])
|
|
31
|
+
.option('--ignore <glob>', 'glob of files to ignore (repeatable)', collect, [])
|
|
32
|
+
.option('--entry <file>', 'scan a single entry file')
|
|
33
|
+
.option('-c, --config <file>', 'path to a config file')
|
|
34
|
+
.addOption(
|
|
35
|
+
new Option('--fail-on <level>', 'exit with code 1 when this severity is found')
|
|
36
|
+
.choices(['none', 'warning', 'error'])
|
|
37
|
+
.default('none'),
|
|
38
|
+
)
|
|
39
|
+
.option('--no-color', 'disable colored output')
|
|
40
|
+
.option('--verbose', 'show file and line for every route')
|
|
41
|
+
.option('--quiet', 'suppress the spinner')
|
|
42
|
+
.action(async (dir, options) => {
|
|
43
|
+
const spinner = ora({
|
|
44
|
+
text: chalk.dim('Scanning for Express routes…'),
|
|
45
|
+
isEnabled: !options.quiet && Boolean(process.stdout.isTTY),
|
|
46
|
+
isSilent: options.quiet,
|
|
47
|
+
}).start();
|
|
48
|
+
|
|
49
|
+
try {
|
|
50
|
+
const result = await scanProject({
|
|
51
|
+
cwd: resolve(dir),
|
|
52
|
+
configPath: options.config,
|
|
53
|
+
include: options.include,
|
|
54
|
+
ignore: options.ignore,
|
|
55
|
+
entry: options.entry,
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
spinner.stop();
|
|
59
|
+
|
|
60
|
+
const report = renderReport(result, {
|
|
61
|
+
format: options.format,
|
|
62
|
+
color: options.color,
|
|
63
|
+
verbose: options.verbose,
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
if (options.output) {
|
|
67
|
+
const outputPath = resolve(options.output);
|
|
68
|
+
await mkdir(dirname(outputPath), { recursive: true });
|
|
69
|
+
await writeFile(outputPath, report, 'utf8');
|
|
70
|
+
console.log(`Report written to ${outputPath}`);
|
|
71
|
+
} else {
|
|
72
|
+
process.stdout.write(report);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const { error, warning } = result.summary.warnings;
|
|
76
|
+
if (options.failOn === 'error' && error > 0) process.exitCode = 1;
|
|
77
|
+
if (options.failOn === 'warning' && error + warning > 0) process.exitCode = 1;
|
|
78
|
+
} catch (error) {
|
|
79
|
+
spinner.fail('Scan failed');
|
|
80
|
+
console.error(error.stack ?? error.message);
|
|
81
|
+
process.exitCode = 2;
|
|
82
|
+
}
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
await program.parseAsync(argv);
|
|
86
|
+
}
|
package/src/config.js
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { existsSync } from 'node:fs';
|
|
2
|
+
import { join, resolve } from 'node:path';
|
|
3
|
+
import { pathToFileURL } from 'node:url';
|
|
4
|
+
|
|
5
|
+
export const DEFAULT_AUTH_HINT =
|
|
6
|
+
/(^|[^a-z0-9_])(require|ensure|verify|check|is|has|with)?_?(auth[a-z]*|loggedin|login|jwt|token|session|passport|api[_-]?key|permission|roles?|guard|protect)/i;
|
|
7
|
+
|
|
8
|
+
export const defaultConfig = {
|
|
9
|
+
include: ['**/*.{js,mjs,cjs}'],
|
|
10
|
+
ignore: [
|
|
11
|
+
'**/node_modules/**',
|
|
12
|
+
'**/dist/**',
|
|
13
|
+
'**/build/**',
|
|
14
|
+
'**/coverage/**',
|
|
15
|
+
'**/.git/**',
|
|
16
|
+
'**/*.{test,spec}.{js,mjs,cjs}',
|
|
17
|
+
'**/{test,tests,__tests__,fixtures}/**',
|
|
18
|
+
],
|
|
19
|
+
entry: null,
|
|
20
|
+
authPatterns: [],
|
|
21
|
+
publicRoutes: [
|
|
22
|
+
'/health',
|
|
23
|
+
'/healthz',
|
|
24
|
+
'/status',
|
|
25
|
+
'/auth/login',
|
|
26
|
+
'/auth/register',
|
|
27
|
+
'/auth/refresh',
|
|
28
|
+
],
|
|
29
|
+
warnOnGet: false,
|
|
30
|
+
output: { format: 'table', file: null },
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
export function buildAuthMatcher(extraPatterns = []) {
|
|
34
|
+
const extra = extraPatterns.map((pattern) => new RegExp(pattern, 'i'));
|
|
35
|
+
return (text) => {
|
|
36
|
+
if (!text || text.startsWith('<inline')) return false;
|
|
37
|
+
if (DEFAULT_AUTH_HINT.test(text)) return true;
|
|
38
|
+
return extra.some((regex) => regex.test(text));
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export async function loadConfig({ cwd = process.cwd(), configPath = null } = {}) {
|
|
43
|
+
const root = resolve(cwd);
|
|
44
|
+
let configFile = configPath ? resolve(root, configPath) : null;
|
|
45
|
+
|
|
46
|
+
if (!configFile) {
|
|
47
|
+
for (const name of ['routescope.config.js', 'routescope.config.mjs']) {
|
|
48
|
+
const candidate = join(root, name);
|
|
49
|
+
if (existsSync(candidate)) {
|
|
50
|
+
configFile = candidate;
|
|
51
|
+
break;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
let userConfig = {};
|
|
57
|
+
if (configFile) {
|
|
58
|
+
const module = await import(pathToFileURL(configFile).href);
|
|
59
|
+
userConfig = module.default ?? module;
|
|
60
|
+
if (typeof userConfig !== 'object' || userConfig === null) {
|
|
61
|
+
throw new TypeError('routescope.config.js must default-export an object');
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
return {
|
|
66
|
+
...defaultConfig,
|
|
67
|
+
...userConfig,
|
|
68
|
+
cwd: root,
|
|
69
|
+
configFile,
|
|
70
|
+
};
|
|
71
|
+
}
|
package/src/index.js
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export { scanProject } from './scanner.js';
|
|
2
|
+
export { loadConfig, defaultConfig, buildAuthMatcher } from './config.js';
|
|
3
|
+
export { parseFile, walk } from './parser.js';
|
|
4
|
+
export { resolveRoutes } from './resolver.js';
|
|
5
|
+
export { analyze } from './analyzer.js';
|
|
6
|
+
export { renderReport } from './reporters.js';
|
package/src/parser.js
ADDED
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
import { readFile } from 'node:fs/promises';
|
|
2
|
+
import { relative, sep } from 'node:path';
|
|
3
|
+
import { parse } from 'acorn';
|
|
4
|
+
|
|
5
|
+
export const HTTP_METHODS = new Set([
|
|
6
|
+
'get',
|
|
7
|
+
'post',
|
|
8
|
+
'put',
|
|
9
|
+
'patch',
|
|
10
|
+
'delete',
|
|
11
|
+
'options',
|
|
12
|
+
'head',
|
|
13
|
+
'all',
|
|
14
|
+
]);
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Minimal AST walker. Avoids an extra dependency and works with any Acorn AST.
|
|
18
|
+
*/
|
|
19
|
+
export function walk(node, visit) {
|
|
20
|
+
if (!node || typeof node.type !== 'string') return;
|
|
21
|
+
visit(node);
|
|
22
|
+
for (const key of Object.keys(node)) {
|
|
23
|
+
if (key === 'type' || key === 'start' || key === 'end' || key === 'loc') continue;
|
|
24
|
+
const value = node[key];
|
|
25
|
+
if (Array.isArray(value)) {
|
|
26
|
+
for (const child of value) {
|
|
27
|
+
if (child && typeof child.type === 'string') walk(child, visit);
|
|
28
|
+
}
|
|
29
|
+
} else if (value && typeof value.type === 'string') {
|
|
30
|
+
walk(value, visit);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function memberName(member) {
|
|
36
|
+
if (!member || member.type !== 'MemberExpression') return null;
|
|
37
|
+
if (!member.computed && member.property.type === 'Identifier') return member.property.name;
|
|
38
|
+
if (member.property.type === 'Literal' && typeof member.property.value === 'string') {
|
|
39
|
+
return member.property.value;
|
|
40
|
+
}
|
|
41
|
+
return null;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function stringValue(node) {
|
|
45
|
+
if (!node) return null;
|
|
46
|
+
if (node.type === 'Literal' && typeof node.value === 'string') return node.value;
|
|
47
|
+
if (node.type === 'TemplateLiteral' && node.expressions.length === 0) {
|
|
48
|
+
return node.quasis[0].value.cooked ?? '';
|
|
49
|
+
}
|
|
50
|
+
return null;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function isExpressCall(node) {
|
|
54
|
+
if (node?.type !== 'CallExpression') return false;
|
|
55
|
+
if (node.callee.type === 'Identifier' && node.callee.name === 'express') return true;
|
|
56
|
+
if (
|
|
57
|
+
node.callee.type === 'CallExpression' &&
|
|
58
|
+
node.callee.callee.type === 'Identifier' &&
|
|
59
|
+
node.callee.callee.name === 'require'
|
|
60
|
+
) {
|
|
61
|
+
return stringValue(node.callee.arguments[0]) === 'express';
|
|
62
|
+
}
|
|
63
|
+
return false;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function isRouterCall(node) {
|
|
67
|
+
if (node?.type !== 'CallExpression') return false;
|
|
68
|
+
if (node.callee.type === 'Identifier' && node.callee.name === 'Router') return true;
|
|
69
|
+
return memberName(node.callee) === 'Router';
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function parseSource(source, file) {
|
|
73
|
+
const base = { ecmaVersion: 'latest', locations: true, allowHashBang: true };
|
|
74
|
+
try {
|
|
75
|
+
return parse(source, { ...base, sourceType: 'module' });
|
|
76
|
+
} catch (moduleError) {
|
|
77
|
+
try {
|
|
78
|
+
return parse(source, {
|
|
79
|
+
...base,
|
|
80
|
+
sourceType: 'script',
|
|
81
|
+
allowReturnOutsideFunction: true,
|
|
82
|
+
});
|
|
83
|
+
} catch {
|
|
84
|
+
throw new Error(`Could not parse ${file}: ${moduleError.message}`);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function snippet(source, node) {
|
|
90
|
+
return source.slice(node.start, node.end).replace(/\s+/g, ' ').trim();
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function findRouteChain(node) {
|
|
94
|
+
let current = node;
|
|
95
|
+
while (current?.type === 'CallExpression' && current.callee.type === 'MemberExpression') {
|
|
96
|
+
if (memberName(current.callee) === 'route') return current;
|
|
97
|
+
current = current.callee.object;
|
|
98
|
+
}
|
|
99
|
+
return null;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function recordRoute(node, method, result, source) {
|
|
103
|
+
const owner = node.callee.object;
|
|
104
|
+
let routerName = owner.type === 'Identifier' ? owner.name : null;
|
|
105
|
+
let path = stringValue(node.arguments[0]);
|
|
106
|
+
let handlers = node.arguments.slice(1);
|
|
107
|
+
|
|
108
|
+
// app.route('/users').get(handler).post(handler)
|
|
109
|
+
if (path === null) {
|
|
110
|
+
const chain = findRouteChain(owner);
|
|
111
|
+
if (chain) {
|
|
112
|
+
path = stringValue(chain.arguments[0]);
|
|
113
|
+
const base = chain.callee.object;
|
|
114
|
+
if (base.type === 'Identifier') routerName = base.name;
|
|
115
|
+
handlers = node.arguments;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
if (path === null || !routerName) return;
|
|
120
|
+
|
|
121
|
+
result.routes.push({
|
|
122
|
+
method: method.toUpperCase(),
|
|
123
|
+
path,
|
|
124
|
+
router: routerName,
|
|
125
|
+
middlewares: handlers.map((handler) => snippet(source, handler)),
|
|
126
|
+
line: node.loc.start.line,
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function recordUse(node, result, source) {
|
|
131
|
+
const owner = node.callee.object;
|
|
132
|
+
if (owner.type !== 'Identifier') return;
|
|
133
|
+
|
|
134
|
+
const args = [...node.arguments];
|
|
135
|
+
let prefix = '';
|
|
136
|
+
if (args.length && stringValue(args[0]) !== null) {
|
|
137
|
+
prefix = stringValue(args[0]);
|
|
138
|
+
args.shift();
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
// The last identifier is normally the router; earlier ones are middleware.
|
|
142
|
+
const targetNode = [...args].reverse().find((arg) => arg.type === 'Identifier');
|
|
143
|
+
|
|
144
|
+
result.uses.push({
|
|
145
|
+
router: owner.name,
|
|
146
|
+
prefix,
|
|
147
|
+
target: targetNode?.name ?? null,
|
|
148
|
+
middleware: args.filter((arg) => arg !== targetNode).map((arg) => snippet(source, arg)),
|
|
149
|
+
line: node.loc.start.line,
|
|
150
|
+
});
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
export async function parseFile(file, { cwd } = {}) {
|
|
154
|
+
const source = await readFile(file, 'utf8');
|
|
155
|
+
const ast = parseSource(source, file);
|
|
156
|
+
const display = cwd ? relative(cwd, file).split(sep).join('/') : file;
|
|
157
|
+
|
|
158
|
+
const result = {
|
|
159
|
+
file,
|
|
160
|
+
display,
|
|
161
|
+
isApp: false,
|
|
162
|
+
appName: null,
|
|
163
|
+
imports: {},
|
|
164
|
+
routerNames: [],
|
|
165
|
+
routes: [],
|
|
166
|
+
uses: [],
|
|
167
|
+
};
|
|
168
|
+
|
|
169
|
+
walk(ast, (node) => {
|
|
170
|
+
if (node.type === 'ImportDeclaration') {
|
|
171
|
+
for (const specifier of node.specifiers) {
|
|
172
|
+
if (specifier.local?.type === 'Identifier' && node.source.type === 'Literal') {
|
|
173
|
+
result.imports[specifier.local.name] = node.source.value;
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
if (node.type === 'VariableDeclarator') {
|
|
180
|
+
if (node.id.type !== 'Identifier' || node.init?.type !== 'CallExpression') return;
|
|
181
|
+
const name = node.id.name;
|
|
182
|
+
if (isExpressCall(node.init)) {
|
|
183
|
+
result.isApp = true;
|
|
184
|
+
result.appName ??= name;
|
|
185
|
+
} else if (isRouterCall(node.init) && !result.routerNames.includes(name)) {
|
|
186
|
+
result.routerNames.push(name);
|
|
187
|
+
}
|
|
188
|
+
return;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
if (node.type !== 'CallExpression' || node.callee.type !== 'MemberExpression') return;
|
|
192
|
+
|
|
193
|
+
const name = memberName(node.callee);
|
|
194
|
+
if (!name) return;
|
|
195
|
+
const method = name.toLowerCase();
|
|
196
|
+
|
|
197
|
+
if (name === 'use') {
|
|
198
|
+
recordUse(node, result, source);
|
|
199
|
+
return;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
if (name !== method || !HTTP_METHODS.has(method)) return;
|
|
203
|
+
recordRoute(node, method, result, source);
|
|
204
|
+
});
|
|
205
|
+
|
|
206
|
+
return result;
|
|
207
|
+
}
|
package/src/reporters.js
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
import { Chalk } from 'chalk';
|
|
2
|
+
|
|
3
|
+
const METHOD_COLORS = {
|
|
4
|
+
GET: 'cyan',
|
|
5
|
+
POST: 'green',
|
|
6
|
+
PUT: 'yellow',
|
|
7
|
+
PATCH: 'magenta',
|
|
8
|
+
DELETE: 'red',
|
|
9
|
+
HEAD: 'gray',
|
|
10
|
+
OPTIONS: 'gray',
|
|
11
|
+
ALL: 'white',
|
|
12
|
+
};
|
|
13
|
+
|
|
14
|
+
const SEVERITY_ICON = { error: '✖', warning: '⚠', info: 'ℹ' };
|
|
15
|
+
|
|
16
|
+
function methodLabel(chalk, method) {
|
|
17
|
+
return chalk[METHOD_COLORS[method] ?? 'white'](method.padEnd(7));
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function routeTarget(warning) {
|
|
21
|
+
return warning.route ? `${warning.route.method} ${warning.route.path}` : warning.code;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function renderTable(result, { color = true, verbose = false } = {}) {
|
|
25
|
+
const chalk = new Chalk({ level: color ? 1 : 0 });
|
|
26
|
+
const lines = [chalk.bold('ROUTESCOPE ANALYSIS'), ''];
|
|
27
|
+
|
|
28
|
+
for (const route of result.routes) {
|
|
29
|
+
let line = `${methodLabel(chalk, route.method)} ${route.path}`;
|
|
30
|
+
if (verbose) line += chalk.dim(` ${route.file}:${route.line}`);
|
|
31
|
+
if (!route.protected && !route.public) line += chalk.yellow(' [unprotected]');
|
|
32
|
+
lines.push(line);
|
|
33
|
+
}
|
|
34
|
+
if (!result.routes.length) lines.push(chalk.dim('No routes found.'));
|
|
35
|
+
|
|
36
|
+
if (result.parseErrors.length) {
|
|
37
|
+
lines.push('', chalk.bold('Parse errors:'));
|
|
38
|
+
for (const error of result.parseErrors) {
|
|
39
|
+
lines.push(`${chalk.red('✖')} ${error.file}`, ` ${error.message}`);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
lines.push(
|
|
44
|
+
'',
|
|
45
|
+
chalk.bold(`Total Routes: ${result.summary.totalRoutes}`),
|
|
46
|
+
chalk.dim(
|
|
47
|
+
`Files: ${result.summary.files} · Protected: ${result.summary.protectedRoutes} · ` +
|
|
48
|
+
`Unprotected: ${result.summary.unprotectedRoutes} · Duplicates: ${result.summary.duplicates}`,
|
|
49
|
+
),
|
|
50
|
+
);
|
|
51
|
+
|
|
52
|
+
if (result.warnings.length) {
|
|
53
|
+
lines.push('', chalk.bold('Warnings:'));
|
|
54
|
+
for (const warning of result.warnings) {
|
|
55
|
+
const color =
|
|
56
|
+
warning.severity === 'error' ? 'red' : warning.severity === 'info' ? 'blue' : 'yellow';
|
|
57
|
+
lines.push(`${chalk[color](SEVERITY_ICON[warning.severity])} ${routeTarget(warning)}`);
|
|
58
|
+
lines.push(` ${warning.message}`);
|
|
59
|
+
const locations = warning.locations ?? (warning.route ? [warning.route] : []);
|
|
60
|
+
for (const location of locations) {
|
|
61
|
+
lines.push(chalk.dim(` at ${location.file}:${location.line}`));
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
return `${lines.join('\n')}\n`;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function escapeCell(value) {
|
|
70
|
+
return String(value).replace(/\|/g, '\\|');
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export function renderMarkdown(result) {
|
|
74
|
+
const lines = [
|
|
75
|
+
'# API Routes',
|
|
76
|
+
'',
|
|
77
|
+
`> Generated by [RouteScope](https://github.com/rehat2007/route_scope) on ${new Date(result.generatedAt).toUTCString()}`,
|
|
78
|
+
'',
|
|
79
|
+
`**${result.summary.totalRoutes} routes** across **${result.summary.files} files** — ` +
|
|
80
|
+
`${result.summary.protectedRoutes} protected, ${result.summary.unprotectedRoutes} unprotected.`,
|
|
81
|
+
'',
|
|
82
|
+
'| Method | Path | Auth | Source |',
|
|
83
|
+
'| --- | --- | --- | --- |',
|
|
84
|
+
];
|
|
85
|
+
|
|
86
|
+
for (const route of result.routes) {
|
|
87
|
+
const auth = route.protected ? '🔒' : route.public ? '🌐' : '⚠️';
|
|
88
|
+
lines.push(
|
|
89
|
+
`| ${route.method} | \`${escapeCell(route.path)}\` | ${auth} | \`${route.file}:${route.line}\` |`,
|
|
90
|
+
);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
lines.push('', '## Summary', '');
|
|
94
|
+
for (const [method, count] of Object.entries(result.summary.byMethod)) {
|
|
95
|
+
lines.push(`- **${method}**: ${count}`);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
if (result.warnings.length) {
|
|
99
|
+
lines.push('', '## Warnings', '');
|
|
100
|
+
for (const warning of result.warnings) {
|
|
101
|
+
const icon = warning.severity === 'error' ? '❌' : warning.severity === 'info' ? 'ℹ️' : '⚠️';
|
|
102
|
+
lines.push(`- ${icon} **${routeTarget(warning)}** — ${warning.message}`);
|
|
103
|
+
const locations = warning.locations ?? (warning.route ? [warning.route] : []);
|
|
104
|
+
for (const location of locations) {
|
|
105
|
+
lines.push(` - \`${location.file}:${location.line}\``);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
if (result.parseErrors.length) {
|
|
111
|
+
lines.push('', '## Parse errors', '');
|
|
112
|
+
for (const error of result.parseErrors) {
|
|
113
|
+
lines.push(`- **${error.file}** — ${error.message}`);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
return `${lines.join('\n')}\n`;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export function renderMermaid(result) {
|
|
121
|
+
const lines = ['flowchart LR'];
|
|
122
|
+
const fileIds = new Map();
|
|
123
|
+
|
|
124
|
+
const fileId = (file) => {
|
|
125
|
+
if (!fileIds.has(file)) {
|
|
126
|
+
const id = `f_${fileIds.size}`;
|
|
127
|
+
fileIds.set(file, id);
|
|
128
|
+
lines.push(` ${id}["${file}"]`);
|
|
129
|
+
}
|
|
130
|
+
return fileIds.get(file);
|
|
131
|
+
};
|
|
132
|
+
|
|
133
|
+
result.routes.forEach((route, index) => {
|
|
134
|
+
const id = `r${index}`;
|
|
135
|
+
const label = `${route.method} ${route.path}`.replace(/"/g, "'");
|
|
136
|
+
lines.push(` ${id}["${label}"]`);
|
|
137
|
+
lines.push(` ${fileId(route.file)} --> ${id}`);
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
return `${lines.join('\n')}\n`;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
export function renderJson(result) {
|
|
144
|
+
return `${JSON.stringify(result, null, 2)}\n`;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
const FORMATS = {
|
|
148
|
+
table: renderTable,
|
|
149
|
+
markdown: renderMarkdown,
|
|
150
|
+
md: renderMarkdown,
|
|
151
|
+
json: renderJson,
|
|
152
|
+
mermaid: renderMermaid,
|
|
153
|
+
};
|
|
154
|
+
|
|
155
|
+
export function renderReport(result, { format = 'table', color = true, verbose = false } = {}) {
|
|
156
|
+
const renderer = FORMATS[format];
|
|
157
|
+
if (!renderer) {
|
|
158
|
+
throw new Error(`Unknown format "${format}". Use one of: ${Object.keys(FORMATS).join(', ')}`);
|
|
159
|
+
}
|
|
160
|
+
return renderer(result, { color, verbose });
|
|
161
|
+
}
|
package/src/resolver.js
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
import { existsSync, statSync } from 'node:fs';
|
|
2
|
+
import { dirname, extname, join, resolve, sep } from 'node:path';
|
|
3
|
+
import { buildAuthMatcher } from './config.js';
|
|
4
|
+
|
|
5
|
+
const EXTENSIONS = ['.js', '.mjs', '.cjs', '.jsx'];
|
|
6
|
+
const INDEX_FILES = ['index.js', 'index.mjs', 'index.cjs'];
|
|
7
|
+
|
|
8
|
+
// fast-glob returns forward slashes, path.resolve returns native separators.
|
|
9
|
+
// Use one canonical form so file keys always match.
|
|
10
|
+
export function normalizePath(file) {
|
|
11
|
+
return file.split(sep).join('/');
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Turn a relative import specifier into an absolute file path, trying the
|
|
16
|
+
* usual extension and directory-index fallbacks.
|
|
17
|
+
*/
|
|
18
|
+
export function resolveSpecifier(fromFile, specifier) {
|
|
19
|
+
if (typeof specifier !== 'string' || !specifier.startsWith('.')) return null;
|
|
20
|
+
|
|
21
|
+
const base = resolve(dirname(fromFile), specifier);
|
|
22
|
+
const candidates = [];
|
|
23
|
+
if (extname(base)) candidates.push(base);
|
|
24
|
+
for (const extension of EXTENSIONS) candidates.push(base + extension);
|
|
25
|
+
for (const index of INDEX_FILES) candidates.push(join(base, index));
|
|
26
|
+
|
|
27
|
+
for (const candidate of candidates) {
|
|
28
|
+
try {
|
|
29
|
+
if (existsSync(candidate) && statSync(candidate).isFile()) return normalizePath(candidate);
|
|
30
|
+
} catch {
|
|
31
|
+
// Ignore unreadable paths and keep looking.
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
return null;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function joinPaths(prefix, path) {
|
|
38
|
+
const joined = `${prefix ?? ''}/${path ?? ''}`.replace(/\/+/g, '/');
|
|
39
|
+
if (joined.length > 1 && joined.endsWith('/')) return joined.slice(0, -1);
|
|
40
|
+
return joined || '/';
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function entryRouter(parsed) {
|
|
44
|
+
if (parsed.appName) return parsed.appName;
|
|
45
|
+
if (parsed.routerNames.length) return parsed.routerNames[0];
|
|
46
|
+
const owners = [...new Set(parsed.routes.map((route) => route.router))];
|
|
47
|
+
return owners.length === 1 ? owners[0] : null;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function resolveRoutes(parsedFiles, { authPatterns = [] } = {}) {
|
|
51
|
+
const isAuth = buildAuthMatcher(authPatterns);
|
|
52
|
+
for (const parsed of parsedFiles) parsed.file = normalizePath(parsed.file);
|
|
53
|
+
const byFile = new Map(parsedFiles.map((parsed) => [parsed.file, parsed]));
|
|
54
|
+
|
|
55
|
+
for (const parsed of parsedFiles) {
|
|
56
|
+
parsed.importFiles = {};
|
|
57
|
+
for (const [local, specifier] of Object.entries(parsed.imports)) {
|
|
58
|
+
const target = resolveSpecifier(parsed.file, specifier);
|
|
59
|
+
if (target && byFile.has(target)) parsed.importFiles[local] = target;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const looksLikeRouter = (file) => {
|
|
64
|
+
const parsed = byFile.get(file);
|
|
65
|
+
if (!parsed) return false;
|
|
66
|
+
return parsed.routes.length > 0 || parsed.routerNames.length > 0;
|
|
67
|
+
};
|
|
68
|
+
|
|
69
|
+
const mountTarget = (parsed, use) => {
|
|
70
|
+
if (!use.target) return null;
|
|
71
|
+
if (parsed.routerNames.includes(use.target)) return parsed.file;
|
|
72
|
+
const imported = parsed.importFiles[use.target];
|
|
73
|
+
if (imported && looksLikeRouter(imported)) return imported;
|
|
74
|
+
return null;
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
// Decide which `use()` calls are real mounts and which are plain middleware.
|
|
78
|
+
for (const parsed of parsedFiles) {
|
|
79
|
+
parsed.mounts = [];
|
|
80
|
+
parsed.middleware = {};
|
|
81
|
+
for (const use of parsed.uses) {
|
|
82
|
+
const targetFile = mountTarget(parsed, use);
|
|
83
|
+
if (targetFile) {
|
|
84
|
+
parsed.mounts.push({ ...use, targetFile });
|
|
85
|
+
} else {
|
|
86
|
+
(parsed.middleware[use.router] ??= []).push(
|
|
87
|
+
...use.middleware,
|
|
88
|
+
...(use.target ? [use.target] : []),
|
|
89
|
+
);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
const routes = [];
|
|
95
|
+
const visited = new Set();
|
|
96
|
+
|
|
97
|
+
const visit = (file, router, prefix, inheritedAuth, chain) => {
|
|
98
|
+
const parsed = byFile.get(file);
|
|
99
|
+
if (!parsed || !router) return;
|
|
100
|
+
|
|
101
|
+
const stateKey = `${file}|${router}`;
|
|
102
|
+
if (chain.has(stateKey)) return;
|
|
103
|
+
const nextChain = new Set(chain).add(stateKey);
|
|
104
|
+
visited.add(stateKey);
|
|
105
|
+
|
|
106
|
+
const protectedByUse = (parsed.middleware[router] ?? []).some(isAuth);
|
|
107
|
+
const auth = inheritedAuth || protectedByUse;
|
|
108
|
+
|
|
109
|
+
for (const route of parsed.routes) {
|
|
110
|
+
if (route.router !== router) continue;
|
|
111
|
+
routes.push({
|
|
112
|
+
method: route.method,
|
|
113
|
+
path: joinPaths(prefix, route.path),
|
|
114
|
+
file: parsed.display,
|
|
115
|
+
line: route.line,
|
|
116
|
+
middlewares: route.middlewares,
|
|
117
|
+
protected: auth || route.middlewares.some(isAuth),
|
|
118
|
+
mounted: true,
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
for (const mount of parsed.mounts) {
|
|
123
|
+
if (mount.router !== router) continue;
|
|
124
|
+
const child = byFile.get(mount.targetFile);
|
|
125
|
+
if (!child) continue;
|
|
126
|
+
const childRouter = entryRouter(child);
|
|
127
|
+
if (!childRouter) continue;
|
|
128
|
+
visit(
|
|
129
|
+
mount.targetFile,
|
|
130
|
+
childRouter,
|
|
131
|
+
joinPaths(prefix, mount.prefix),
|
|
132
|
+
auth || mount.middleware.some(isAuth),
|
|
133
|
+
nextChain,
|
|
134
|
+
);
|
|
135
|
+
}
|
|
136
|
+
};
|
|
137
|
+
|
|
138
|
+
const mountedFiles = new Set();
|
|
139
|
+
for (const parsed of parsedFiles) {
|
|
140
|
+
for (const mount of parsed.mounts) {
|
|
141
|
+
if (mount.targetFile !== parsed.file) mountedFiles.add(mount.targetFile);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
let roots = parsedFiles.filter((parsed) => parsed.isApp && !mountedFiles.has(parsed.file));
|
|
146
|
+
if (roots.length === 0) {
|
|
147
|
+
roots = parsedFiles.filter(
|
|
148
|
+
(parsed) => parsed.routes.length > 0 && !mountedFiles.has(parsed.file),
|
|
149
|
+
);
|
|
150
|
+
}
|
|
151
|
+
for (const root of roots) {
|
|
152
|
+
const router = entryRouter(root);
|
|
153
|
+
if (router) visit(root.file, router, '', false, new Set());
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// Routers that never got reached: report them instead of silently dropping them.
|
|
157
|
+
for (const parsed of parsedFiles) {
|
|
158
|
+
if (!parsed.routes.length) continue;
|
|
159
|
+
for (const route of parsed.routes) {
|
|
160
|
+
if (visited.has(`${parsed.file}|${route.router}`)) continue;
|
|
161
|
+
const auth = (parsed.middleware[route.router] ?? []).some(isAuth);
|
|
162
|
+
routes.push({
|
|
163
|
+
method: route.method,
|
|
164
|
+
path: joinPaths('', route.path),
|
|
165
|
+
file: parsed.display,
|
|
166
|
+
line: route.line,
|
|
167
|
+
middlewares: route.middlewares,
|
|
168
|
+
protected: auth || route.middlewares.some(isAuth),
|
|
169
|
+
mounted: false,
|
|
170
|
+
});
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
return routes;
|
|
175
|
+
}
|
package/src/scanner.js
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import fg from 'fast-glob';
|
|
2
|
+
import { relative, resolve, sep } from 'node:path';
|
|
3
|
+
import { loadConfig } from './config.js';
|
|
4
|
+
import { parseFile } from './parser.js';
|
|
5
|
+
import { resolveRoutes } from './resolver.js';
|
|
6
|
+
import { analyze } from './analyzer.js';
|
|
7
|
+
|
|
8
|
+
async function discoverFiles(config) {
|
|
9
|
+
if (config.entry) return [resolve(config.cwd, config.entry).split(sep).join('/')];
|
|
10
|
+
|
|
11
|
+
return fg(config.include, {
|
|
12
|
+
cwd: config.cwd,
|
|
13
|
+
ignore: config.ignore,
|
|
14
|
+
absolute: true,
|
|
15
|
+
onlyFiles: true,
|
|
16
|
+
followSymbolicLinks: false,
|
|
17
|
+
suppressErrors: true,
|
|
18
|
+
});
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export async function scanProject(options = {}) {
|
|
22
|
+
const config = await loadConfig(options);
|
|
23
|
+
|
|
24
|
+
if (options.include?.length) config.include = options.include;
|
|
25
|
+
if (options.ignore?.length) config.ignore = [...config.ignore, ...options.ignore];
|
|
26
|
+
if (options.entry) config.entry = options.entry;
|
|
27
|
+
|
|
28
|
+
const files = await discoverFiles(config);
|
|
29
|
+
|
|
30
|
+
const settled = await Promise.allSettled(
|
|
31
|
+
files.map((file) => parseFile(file, { cwd: config.cwd })),
|
|
32
|
+
);
|
|
33
|
+
|
|
34
|
+
const parsed = [];
|
|
35
|
+
const parseErrors = [];
|
|
36
|
+
settled.forEach((outcome, index) => {
|
|
37
|
+
if (outcome.status === 'fulfilled') {
|
|
38
|
+
parsed.push(outcome.value);
|
|
39
|
+
} else {
|
|
40
|
+
const file = files[index];
|
|
41
|
+
const relativePath = relative(config.cwd, file).split(sep).join('/');
|
|
42
|
+
parseErrors.push({
|
|
43
|
+
file: relativePath,
|
|
44
|
+
message: outcome.reason?.message ?? String(outcome.reason),
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
const routes = resolveRoutes(parsed, config);
|
|
50
|
+
|
|
51
|
+
return analyze({
|
|
52
|
+
routes,
|
|
53
|
+
files: parsed,
|
|
54
|
+
config,
|
|
55
|
+
parseErrors,
|
|
56
|
+
});
|
|
57
|
+
}
|