@pavanyn/docugen 1.0.1 → 1.0.3

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 (76) hide show
  1. package/README.md +54 -2
  2. package/dist/analysis/findings.d.ts.map +1 -1
  3. package/dist/analysis/findings.js +4 -3
  4. package/dist/analysis/findings.js.map +1 -1
  5. package/dist/changes/schema.d.ts +2 -2
  6. package/dist/commands/doctor.d.ts +2 -0
  7. package/dist/commands/doctor.d.ts.map +1 -1
  8. package/dist/commands/doctor.js +11 -4
  9. package/dist/commands/doctor.js.map +1 -1
  10. package/dist/commands/extract.js +29 -4
  11. package/dist/commands/extract.js.map +1 -1
  12. package/dist/detect/ownership.d.ts +8 -0
  13. package/dist/detect/ownership.d.ts.map +1 -0
  14. package/dist/detect/ownership.js +18 -0
  15. package/dist/detect/ownership.js.map +1 -0
  16. package/dist/extract/config/index.d.ts.map +1 -1
  17. package/dist/extract/config/index.js +52 -14
  18. package/dist/extract/config/index.js.map +1 -1
  19. package/dist/extract/endpoints/express.d.ts +23 -8
  20. package/dist/extract/endpoints/express.d.ts.map +1 -1
  21. package/dist/extract/endpoints/express.js +277 -263
  22. package/dist/extract/endpoints/express.js.map +1 -1
  23. package/dist/extract/endpoints/index.d.ts +9 -0
  24. package/dist/extract/endpoints/index.d.ts.map +1 -1
  25. package/dist/extract/endpoints/index.js +79 -37
  26. package/dist/extract/endpoints/index.js.map +1 -1
  27. package/dist/extract/endpoints/openapi.d.ts +6 -23
  28. package/dist/extract/endpoints/openapi.d.ts.map +1 -1
  29. package/dist/extract/endpoints/openapi.js +202 -88
  30. package/dist/extract/endpoints/openapi.js.map +1 -1
  31. package/dist/extract/endpoints/static-string.d.ts +26 -0
  32. package/dist/extract/endpoints/static-string.d.ts.map +1 -0
  33. package/dist/extract/endpoints/static-string.js +180 -0
  34. package/dist/extract/endpoints/static-string.js.map +1 -0
  35. package/dist/extract/schema/index.d.ts.map +1 -1
  36. package/dist/extract/schema/index.js +45 -6
  37. package/dist/extract/schema/index.js.map +1 -1
  38. package/dist/extract/types.d.ts +2 -0
  39. package/dist/extract/types.d.ts.map +1 -1
  40. package/dist/extract/types.js.map +1 -1
  41. package/dist/features/schema.d.ts +4 -4
  42. package/dist/graph/from-extraction.d.ts.map +1 -1
  43. package/dist/graph/from-extraction.js +27 -8
  44. package/dist/graph/from-extraction.js.map +1 -1
  45. package/dist/index.d.ts +2 -2
  46. package/dist/index.d.ts.map +1 -1
  47. package/dist/index.js +1 -1
  48. package/dist/index.js.map +1 -1
  49. package/dist/pipeline.d.ts.map +1 -1
  50. package/dist/pipeline.js +1 -0
  51. package/dist/pipeline.js.map +1 -1
  52. package/dist/plans/schema.d.ts +4 -4
  53. package/dist/privacy/redact.d.ts +4 -0
  54. package/dist/privacy/redact.d.ts.map +1 -1
  55. package/dist/privacy/redact.js +28 -1
  56. package/dist/privacy/redact.js.map +1 -1
  57. package/dist/render/index.d.ts.map +1 -1
  58. package/dist/render/index.js +3 -1
  59. package/dist/render/index.js.map +1 -1
  60. package/dist/render/pages/api.d.ts.map +1 -1
  61. package/dist/render/pages/api.js +43 -35
  62. package/dist/render/pages/api.js.map +1 -1
  63. package/dist/render/pages/config.d.ts.map +1 -1
  64. package/dist/render/pages/config.js +10 -2
  65. package/dist/render/pages/config.js.map +1 -1
  66. package/dist/render/pages/schema.d.ts +3 -1
  67. package/dist/render/pages/schema.d.ts.map +1 -1
  68. package/dist/render/pages/schema.js +14 -3
  69. package/dist/render/pages/schema.js.map +1 -1
  70. package/dist/types/entries.d.ts +21 -1
  71. package/dist/types/entries.d.ts.map +1 -1
  72. package/dist/util/git.d.ts +14 -0
  73. package/dist/util/git.d.ts.map +1 -1
  74. package/dist/util/git.js +55 -7
  75. package/dist/util/git.js.map +1 -1
  76. package/package.json +1 -1
@@ -5,77 +5,43 @@ import { toPosix } from '../../util/paths.js';
5
5
  import { readModuleBindings, resolveSymbolToFile } from '../../util/modules.js';
6
6
  import { loadPathAliases } from '../../util/tsconfig.js';
7
7
  import { literalString, parseSourceFile, positionOf, ts, walk } from '../../util/ts-ast.js';
8
+ import { compareStrings } from '../../util/sort.js';
9
+ import { redactSecrets } from '../../privacy/redact.js';
8
10
  import { joinPath, paramsOf } from './paths.js';
9
- /**
10
- * Express routes.
11
- *
12
- * The hard part is not finding `router.get(...)` — it is knowing what URL it
13
- * ends up at. A microservice typically declares its routes in one file and
14
- * mounts the whole router elsewhere with `app.use('/projects', projectRoutes)`,
15
- * often through a barrel re-export. Ignoring the mount documents every endpoint
16
- * at the wrong path, so mounts are resolved across files and a route whose
17
- * mount cannot be resolved is reported rather than published at a guessed URL.
18
- */
19
- const HTTP_METHODS = new Set([
20
- 'get',
21
- 'post',
22
- 'put',
23
- 'patch',
24
- 'delete',
25
- 'head',
26
- 'options',
27
- 'all',
28
- ]);
29
- /** Calls that produce a mountable Router. */
11
+ import { applicationScope, owningWorkspace } from '../../detect/ownership.js';
12
+ import { evaluateStaticString } from './static-string.js';
13
+ const HTTP_METHODS = new Set(['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'all']);
30
14
  const ROUTER_FACTORIES = new Set(['Router']);
31
- /** Calls that produce the application itself, which is never mounted. */
32
15
  const APP_FACTORIES = new Set(['express']);
33
- /**
34
- * Type names that prove a value is an Express app or router.
35
- *
36
- * The app frequently arrives as a function parameter rather than a local
37
- * assignment (`export default async (app: Application) => { app.use(...) }`),
38
- * and its type annotation is the precise signal for that — far safer than
39
- * guessing from the variable's name.
40
- */
41
16
  const ROUTER_TYPE_NAMES = new Set(['Router', 'IRouter', 'express.Router', 'e.Router']);
42
17
  const APP_TYPE_NAMES = new Set([
43
- 'Application',
44
- 'Express',
45
- 'express.Application',
46
- 'express.Express',
47
- 'e.Application',
48
- 'e.Express',
18
+ 'Application', 'Express', 'Express.Application', 'Express.Express',
19
+ 'express.Application', 'express.Express', 'e.Application', 'e.Express',
49
20
  ]);
50
21
  export async function extractExpressEndpoints(args) {
51
- const files = (await fg(['**/*.{ts,js,mjs}'], { cwd: args.root, ignore: [...args.exclude], onlyFiles: true }))
52
- .map(toPosix)
53
- .sort();
22
+ const files = (await fg(['**/*.{ts,js,mjs}'], {
23
+ cwd: args.root, ignore: [...args.exclude], onlyFiles: true,
24
+ })).map(toPosix).sort(compareStrings);
54
25
  const fileSet = new Set(files);
55
26
  const aliases = await loadPathAliases(args.root);
56
27
  const analyses = new Map();
57
- const bindingsCache = new Map();
58
- /**
59
- * Bindings for any file, parsed on demand.
60
- *
61
- * A re-export barrel declares no routes of its own, so it never reaches
62
- * `analyses` — but mount resolution passes straight through it. Loading
63
- * lazily keeps the common path cheap while still following the chain.
64
- */
65
- const loadBindings = async (file) => {
66
- if (bindingsCache.has(file))
67
- return bindingsCache.get(file);
68
- let bindings;
28
+ const moduleCache = new Map();
29
+ const loadModule = async (file) => {
30
+ if (moduleCache.has(file))
31
+ return moduleCache.get(file);
69
32
  try {
70
33
  const contents = await fs.readFile(path.join(args.root, file), 'utf8');
71
- bindings = readModuleBindings(parseSourceFile(file, contents));
34
+ const source = parseSourceFile(file, contents);
35
+ const module = { file, source, bindings: readModuleBindings(source) };
36
+ moduleCache.set(file, module);
37
+ return module;
72
38
  }
73
39
  catch {
74
- bindings = undefined;
40
+ moduleCache.set(file, undefined);
41
+ return undefined;
75
42
  }
76
- bindingsCache.set(file, bindings);
77
- return bindings;
78
43
  };
44
+ const loadBindings = async (file) => (await loadModule(file))?.bindings;
79
45
  for (const relative of files) {
80
46
  let contents;
81
47
  try {
@@ -84,29 +50,20 @@ export async function extractExpressEndpoints(args) {
84
50
  catch {
85
51
  continue;
86
52
  }
87
- // Cheap pre-filter; parsing every file in a large repo blows the budget.
88
- if (!/\b(?:Router|express)\s*\(|\.(?:get|post|put|patch|delete|use)\s*\(/.test(contents))
53
+ if (!/\b(?:Router|express)\s*\(|\.(?:get|post|put|patch|delete|head|options|all|use)\s*\(/.test(contents))
89
54
  continue;
90
55
  const analysis = analyseFile(relative, contents);
91
- bindingsCache.set(relative, analysis.bindings);
92
- if (analysis.registrations.length === 0 &&
93
- analysis.mounts.length === 0 &&
94
- analysis.unconfirmedRouters.length === 0) {
56
+ moduleCache.set(relative, analysis);
57
+ if (analysis.registrations.length === 0 && analysis.mounts.length === 0 && analysis.unconfirmedRouters.length === 0)
95
58
  continue;
96
- }
97
59
  analyses.set(relative, analysis);
98
60
  }
99
- // A file reaches `analyses` only with a registration, a mount, or a candidate
100
- // router in a file that imports express — so anything here is genuine
101
- // evidence. A repo where every router is unconfirmed still counts: producing
102
- // silence there would be the "empty output looks like a clean repo" failure.
103
61
  if (analyses.size === 0)
104
- return { entries: [], gaps: [], found: false };
105
- // Resolve every mount to the file that declares the router it points at, so
106
- // a registration can be given the prefix it actually runs under.
107
- const prefixesByRouter = new Map();
62
+ return { entries: [], gaps: [], found: false, sourceOwnership: [] };
63
+ const locationsByRouter = new Map();
108
64
  const mountEdges = new Map();
109
65
  const gaps = [];
66
+ const workspaces = args.workspaces ?? [{ dir: '', manifests: [] }];
110
67
  const routerKey = (file, variable) => `${file}\u0000${variable}`;
111
68
  const targetVariable = (resolved) => {
112
69
  const target = analyses.get(resolved.file);
@@ -124,30 +81,25 @@ export async function extractExpressEndpoints(args) {
124
81
  const binding = target.bindings.exports.get(resolved.exportedName);
125
82
  if (binding?.kind === 'local')
126
83
  return binding.localName;
127
- if (resolved.exportedName === 'default' && target.mounts.some((mount) => mount.routerVariable === '$default')) {
84
+ if (resolved.exportedName === 'default' && target.mounts.some((mount) => mount.routerVariable === '$default'))
128
85
  return '$default';
129
- }
130
86
  return resolved.exportedName;
131
87
  };
132
88
  for (const analysis of analyses.values()) {
133
89
  for (const mount of analysis.mounts) {
90
+ const evaluated = mount.prefixExpression === undefined
91
+ ? { value: mount.prefix, complete: true, original: mount.prefix }
92
+ : await evaluateStaticString({
93
+ module: analysis, expression: mount.prefixExpression, files: fileSet, aliases, loadModule,
94
+ });
134
95
  const resolved = await resolveSymbolToFile({
135
- fromFile: analysis.file,
136
- symbol: mount.symbol,
137
- loadBindings,
138
- files: fileSet,
139
- aliases,
96
+ fromFile: analysis.file, symbol: mount.symbol, loadBindings, files: fileSet, aliases,
140
97
  });
141
98
  if (resolved === undefined || !analyses.has(resolved.file)) {
142
- // A mount pointing at something docgen cannot follow — commonly a
143
- // third-party middleware rather than a local router. Only worth
144
- // reporting when it carries a path prefix that would change URLs.
145
- if (mount.prefix !== '' && mount.prefix !== '/') {
99
+ if (evaluated.value !== '' && evaluated.value !== '/') {
146
100
  gaps.push({
147
- extractor: 'endpoints',
148
- kind: 'mount-target-unresolved',
149
- message: `'${mount.symbol}' is mounted at '${mount.prefix}' but docgen could not resolve what it ` +
150
- 'refers to. Any routes it declares are documented without this prefix.',
101
+ extractor: 'endpoints', kind: 'mount-target-unresolved',
102
+ message: `'${mount.symbol}' is mounted at '${evaluated.value}' but docgen could not resolve what it refers to.`,
151
103
  source: { file: analysis.file, line: mount.line },
152
104
  });
153
105
  }
@@ -155,104 +107,133 @@ export async function extractExpressEndpoints(args) {
155
107
  }
156
108
  const from = routerKey(analysis.file, mount.routerVariable);
157
109
  const to = routerKey(resolved.file, targetVariable(resolved));
158
- const edges = mountEdges.get(from) ?? [];
159
- edges.push({ to, prefix: mount.prefix });
160
- mountEdges.set(from, edges);
110
+ mountEdges.set(from, [...(mountEdges.get(from) ?? []), {
111
+ to, prefix: evaluated.value, resolved: evaluated.complete,
112
+ ...(evaluated.complete ? {} : { original: redactSecrets(evaluated.original).text }),
113
+ sourceFile: analysis.file, line: mount.line, symbol: mount.symbol,
114
+ }]);
161
115
  }
162
116
  if (analysis.unconfirmedRouters.length > 0) {
163
117
  gaps.push({
164
- extractor: 'endpoints',
165
- kind: 'unconfirmed-router-variable',
166
- message: `${analysis.file} registers rooted paths on ${analysis.unconfirmedRouters.join(', ')}, which ` +
167
- 'docgen could not confirm is an Express app or router. Those routes are not documented — ' +
168
- 'annotate the variable with an Express type to have them picked up.',
118
+ extractor: 'endpoints', kind: 'unconfirmed-router-variable',
119
+ message: `${analysis.file} registers rooted paths on ${analysis.unconfirmedRouters.join(', ')}, which docgen could not confirm is an Express app or router. Those routes are not documented; annotate the variable with an Express type.`,
169
120
  source: { file: analysis.file },
170
121
  });
171
122
  }
172
123
  }
173
124
  const queue = [];
174
125
  for (const analysis of analyses.values()) {
175
- for (const variable of analysis.appVariables) {
176
- queue.push({ key: routerKey(analysis.file, variable), prefix: '' });
126
+ const workspace = owningWorkspace(analysis.file, workspaces);
127
+ for (const root of analysis.applicationRoots) {
128
+ queue.push({
129
+ key: routerKey(analysis.file, root.owner), prefix: '', resolved: true,
130
+ application: applicationScope(workspace, 'express', root.discriminator),
131
+ });
177
132
  }
178
133
  }
179
134
  const visited = new Set();
135
+ const unresolvedFindingKeys = new Set();
180
136
  while (queue.length > 0) {
181
137
  const current = queue.shift();
182
138
  if (current === undefined)
183
139
  continue;
184
- const visitKey = `${current.key}\u0000${current.prefix}`;
140
+ const visitKey = `${current.key}\u0000${current.application}\u0000${current.prefix}\u0000${current.resolved}`;
185
141
  if (visited.has(visitKey))
186
142
  continue;
187
143
  visited.add(visitKey);
188
- const bucket = prefixesByRouter.get(current.key) ?? new Set();
189
- bucket.add(current.prefix);
190
- prefixesByRouter.set(current.key, bucket);
144
+ const byApplication = locationsByRouter.get(current.key) ?? new Map();
145
+ const bucket = byApplication.get(current.application) ?? new Map();
146
+ bucket.set(`${current.prefix}\u0000${current.resolved}`, { prefix: current.prefix, resolved: current.resolved });
147
+ byApplication.set(current.application, bucket);
148
+ locationsByRouter.set(current.key, byApplication);
191
149
  for (const edge of mountEdges.get(current.key) ?? []) {
192
- queue.push({ key: edge.to, prefix: joinPath(current.prefix, edge.prefix) });
150
+ const prefix = joinPath(current.prefix, edge.prefix);
151
+ const resolved = current.resolved && edge.resolved;
152
+ if (!edge.resolved) {
153
+ const findingKey = `${edge.sourceFile}\u0000${edge.line}\u0000${edge.symbol}\u0000${current.application}\u0000${prefix}`;
154
+ if (!unresolvedFindingKeys.has(findingKey)) {
155
+ unresolvedFindingKeys.add(findingKey);
156
+ gaps.push({
157
+ extractor: 'endpoints', kind: 'mount-prefix-unresolved',
158
+ message: `Mount prefix expression '${edge.original ?? edge.prefix}' for router '${edge.symbol}' in application '${current.application}' was only partially resolvable; '${prefix}' is used as an explicit placeholder path.`,
159
+ source: { file: edge.sourceFile, line: edge.line },
160
+ });
161
+ }
162
+ }
163
+ queue.push({ key: edge.to, prefix, application: current.application, resolved });
193
164
  }
194
165
  }
195
166
  const entries = [];
196
167
  for (const analysis of analyses.values()) {
197
168
  if (analysis.registrations.length === 0)
198
169
  continue;
199
- const registrationPrefixes = new Map();
200
- for (const registration of analysis.registrations) {
201
- const prefixes = [...(prefixesByRouter.get(routerKey(analysis.file, registration.routerVariable)) ?? [])]
202
- .sort();
203
- registrationPrefixes.set(registration.routerVariable, prefixes);
204
- }
205
- if (declaresMountableRouter(analysis) &&
206
- [...new Set(analysis.registrations.map((registration) => registration.routerVariable))].some((variable) => (prefixesByRouter.get(routerKey(analysis.file, variable))?.size ?? 0) === 0)) {
207
- // Routes on a router nobody mounts have no determinable URL.
170
+ const mountedVariables = new Set(analysis.registrations
171
+ .map((registration) => registration.routerVariable)
172
+ .filter((variable) => (locationsByRouter.get(routerKey(analysis.file, variable))?.size ?? 0) > 0));
173
+ const unmountedVariables = new Set(analysis.registrations
174
+ .map((registration) => registration.routerVariable)
175
+ .filter((variable) => analysis.routerVariables.has(variable) && !mountedVariables.has(variable)));
176
+ if (unmountedVariables.size > 0) {
208
177
  gaps.push({
209
- extractor: 'endpoints',
210
- kind: 'router-not-mounted',
211
- message: `${analysis.file} declares routes on a router that docgen did not find mounted anywhere. ` +
212
- 'The paths shown are relative to wherever it is mounted, so they may be incomplete.',
178
+ extractor: 'endpoints', kind: 'router-not-mounted',
179
+ message: `${analysis.file} declares routes on a router that docgen did not find mounted anywhere. The paths shown are relative and may be incomplete.`,
213
180
  source: { file: analysis.file },
214
181
  });
215
182
  }
216
183
  for (const registration of analysis.registrations) {
217
- const prefixes = registrationPrefixes.get(registration.routerVariable) ?? [];
218
- const effectivePrefixes = prefixes.length === 0 ? [''] : prefixes;
219
- for (const prefix of effectivePrefixes) {
220
- const fullPath = joinPath(prefix, registration.path);
184
+ const locations = locationsByRouter.get(routerKey(analysis.file, registration.routerVariable)) ?? new Map();
185
+ const effective = locations.size === 0
186
+ ? [{ application: undefined, prefix: '', resolved: false }]
187
+ : [...locations.entries()].flatMap(([application, values]) => [...values.values()].map((value) => ({ application, ...value })))
188
+ .sort((a, b) => compareStrings(a.application ?? '', b.application ?? '') || compareStrings(a.prefix, b.prefix));
189
+ for (const location of effective) {
190
+ const fullPath = joinPath(location.prefix, registration.path);
191
+ const workspace = owningWorkspace(analysis.file, workspaces);
221
192
  entries.push({
222
193
  id: `endpoint:${registration.method}:${fullPath}`,
223
194
  source: { file: analysis.file, line: registration.line, column: registration.column },
224
- extractionMethod: 'ast',
225
- certainty: 'high',
226
- method: registration.method,
227
- path: fullPath,
228
- params: paramsOf(fullPath),
229
- handler: { file: analysis.file, line: registration.line },
195
+ extractionMethod: 'ast', certainty: 'high', method: registration.method, path: fullPath,
196
+ ...(args.workspaces !== undefined && args.workspaces.length > 1 ? { workspace } : {}),
197
+ ...(location.application === undefined
198
+ ? { finalPathResolved: false }
199
+ : { application: location.application, finalPathResolved: location.resolved }),
200
+ params: paramsOf(fullPath), handler: { file: analysis.file, line: registration.line },
230
201
  middleware: registration.middleware,
231
- ...(registration.requestShape === undefined
232
- ? {}
233
- : { requestShape: registration.requestShape }),
202
+ ...(registration.requestShape === undefined ? {} : { requestShape: registration.requestShape }),
234
203
  });
235
204
  }
236
205
  }
237
206
  }
238
- return { entries, gaps, found: true };
239
- }
240
- /**
241
- * Whether this file registers routes on a Router that something else must
242
- * mount. The application object is a root: it is never mounted, so an
243
- * unmounted-router warning about it would be a false alarm.
244
- */
245
- function declaresMountableRouter(analysis) {
246
- return analysis.registrations.some((registration) => analysis.routerVariables.has(registration.routerVariable));
207
+ const sourceOwnership = [];
208
+ for (const analysis of analyses.values()) {
209
+ const workspace = owningWorkspace(analysis.file, workspaces);
210
+ const applications = new Map();
211
+ const owners = new Set([
212
+ ...analysis.routerVariables,
213
+ ...analysis.applicationRoots.map((root) => root.owner),
214
+ ...analysis.registrations.map((registration) => registration.routerVariable),
215
+ ]);
216
+ for (const owner of owners) {
217
+ for (const [application, values] of locationsByRouter.get(routerKey(analysis.file, owner)) ?? []) {
218
+ for (const value of values.values()) {
219
+ const origin = analysis.routerVariables.has(owner) ? 'router' : 'application';
220
+ applications.set(`${application}\u0000${value.prefix}\u0000${value.resolved}\u0000${origin}`, {
221
+ application, prefix: value.prefix, finalPathResolved: value.resolved, origin,
222
+ });
223
+ }
224
+ }
225
+ }
226
+ sourceOwnership.push({
227
+ file: analysis.file, workspace,
228
+ applications: [...applications.values()].sort((a, b) => compareStrings(a.application, b.application) || compareStrings(a.prefix, b.prefix)),
229
+ });
230
+ }
231
+ return { entries, gaps: dedupeGaps(gaps), found: true, sourceOwnership };
247
232
  }
248
- /** The module symbol a mount refers to: `routes` or `routes.default`. */
249
233
  function mountedSymbolName(argument) {
250
234
  if (ts.isIdentifier(argument))
251
235
  return argument.text;
252
- if (ts.isPropertyAccessExpression(argument) &&
253
- ts.isIdentifier(argument.expression) &&
254
- ts.isIdentifier(argument.name) &&
255
- argument.name.text === 'default') {
236
+ if (ts.isPropertyAccessExpression(argument) && ts.isIdentifier(argument.expression) && argument.name.text === 'default') {
256
237
  return argument.expression.text;
257
238
  }
258
239
  return undefined;
@@ -262,180 +243,206 @@ export function analyseFile(file, contents) {
262
243
  const bindings = readModuleBindings(source);
263
244
  const importsExpress = [...bindings.imports.values()].some((binding) => binding.specifier === 'express');
264
245
  const routerVariables = new Set();
265
- const appVariables = new Set();
246
+ const appRoots = new Map();
247
+ const aliases = new Map();
266
248
  const registrations = [];
267
249
  const mounts = [];
268
250
  const unconfirmed = new Set();
269
- // `const router = Router()` / `express()` / `express.Router()`
251
+ const addAppRoot = (owner, discriminator = `${file}#${owner}`) => {
252
+ appRoots.set(owner, { owner, discriminator });
253
+ };
270
254
  walk(source, (node) => {
271
- if (!ts.isVariableDeclaration(node))
272
- return;
273
- if (!ts.isIdentifier(node.name))
274
- return;
275
- const initializer = node.initializer;
276
- if (initializer === undefined || !ts.isCallExpression(initializer))
277
- return;
278
- if (isRouterChain(initializer)) {
279
- routerVariables.add(node.name.text);
280
- return;
255
+ if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name)) {
256
+ const initializer = node.initializer;
257
+ if (initializer !== undefined && ts.isCallExpression(initializer)) {
258
+ if (isRouterChain(initializer))
259
+ routerVariables.add(node.name.text);
260
+ else {
261
+ const factory = factoryName(initializer);
262
+ if (factory !== undefined && ROUTER_FACTORIES.has(factory))
263
+ routerVariables.add(node.name.text);
264
+ else if (factory !== undefined && APP_FACTORIES.has(factory))
265
+ addAppRoot(node.name.text);
266
+ }
267
+ }
268
+ if (node.type !== undefined)
269
+ classifyTyped(node.name.text, node.type.getText(source), routerVariables, addAppRoot);
281
270
  }
282
- const callee = initializer.expression;
283
- const name = ts.isIdentifier(callee)
284
- ? callee.text
285
- : ts.isPropertyAccessExpression(callee) && ts.isIdentifier(callee.name)
286
- ? callee.name.text
287
- : undefined;
288
- if (name === undefined)
289
- return;
290
- if (ROUTER_FACTORIES.has(name))
291
- routerVariables.add(node.name.text);
292
- else if (APP_FACTORIES.has(name))
293
- appVariables.add(node.name.text);
294
- });
295
- walk(source, (node) => {
296
- if (ts.isExportAssignment(node) && node.isExportEquals !== true &&
297
- isRouterChain(node.expression)) {
298
- routerVariables.add('$default');
271
+ if (ts.isParameter(node) && ts.isIdentifier(node.name) && node.type !== undefined) {
272
+ classifyTyped(node.name.text, node.type.getText(source), routerVariables, addAppRoot);
299
273
  }
274
+ if (ts.isPropertyDeclaration(node) && isSimplePropertyName(node.name)) {
275
+ const className = enclosingClassName(node);
276
+ if (className === undefined)
277
+ return;
278
+ const owner = classOwner(className, node.name.text);
279
+ const typeText = node.type?.getText(source);
280
+ if (typeText !== undefined && APP_TYPE_NAMES.has(typeText))
281
+ addAppRoot(owner, `${file}#${className}.${node.name.text}`);
282
+ if (node.initializer !== undefined && ts.isCallExpression(node.initializer) && APP_FACTORIES.has(factoryName(node.initializer) ?? '')) {
283
+ addAppRoot(owner, `${file}#${className}.${node.name.text}`);
284
+ }
285
+ }
286
+ if (ts.isBinaryExpression(node) && node.operatorToken.kind === ts.SyntaxKind.EqualsToken) {
287
+ const owner = thisPropertyOwner(node.left);
288
+ if (owner !== undefined && ts.isCallExpression(node.right) && APP_FACTORIES.has(factoryName(node.right) ?? '')) {
289
+ const [className, property] = splitClassOwner(owner);
290
+ addAppRoot(owner, `${file}#${className}.${property}`);
291
+ }
292
+ }
293
+ if (ts.isExportAssignment(node) && node.isExportEquals !== true && isRouterChain(node.expression))
294
+ routerVariables.add('$default');
300
295
  });
301
- // Anything annotated as an Express app or router, however it arrived.
302
- walk(source, (node) => {
303
- const isTyped = (ts.isParameter(node) || ts.isVariableDeclaration(node)) &&
304
- ts.isIdentifier(node.name) &&
305
- node.type !== undefined;
306
- if (!isTyped)
307
- return;
308
- const declaration = node;
309
- const typeText = declaration.type?.getText(source);
310
- const name = declaration.name.text;
311
- if (typeText === undefined)
312
- return;
313
- if (ROUTER_TYPE_NAMES.has(typeText))
314
- routerVariables.add(name);
315
- else if (APP_TYPE_NAMES.has(typeText))
316
- appVariables.add(name);
317
- });
296
+ // Resolve harmless aliases such as `const server = this.app` before calls are
297
+ // inspected. Fixed-point iteration also handles alias-of-alias chains.
298
+ let changed = true;
299
+ while (changed) {
300
+ changed = false;
301
+ walk(source, (node) => {
302
+ if (!ts.isVariableDeclaration(node) || !ts.isIdentifier(node.name) || node.initializer === undefined)
303
+ return;
304
+ const target = expressionOwner(node.initializer, aliases);
305
+ if (target !== undefined && (appRoots.has(target) || routerVariables.has(target)) && aliases.get(node.name.text) !== target) {
306
+ aliases.set(node.name.text, target);
307
+ changed = true;
308
+ }
309
+ });
310
+ }
318
311
  walk(source, (node) => {
319
- if (!ts.isCallExpression(node))
312
+ if (!ts.isCallExpression(node) || !ts.isPropertyAccessExpression(node.expression))
320
313
  return;
321
314
  const callee = node.expression;
322
- if (!ts.isPropertyAccessExpression(callee) || !ts.isIdentifier(callee.name))
323
- return;
324
- const routerVariable = ts.isIdentifier(callee.expression)
325
- ? callee.expression.text
326
- : ownerOfChain(node);
315
+ const routerVariable = expressionOwner(callee.expression, aliases) ?? ownerOfChain(node);
327
316
  if (routerVariable === undefined)
328
317
  return;
329
318
  const methodName = callee.name.text.toLowerCase();
330
319
  const position = positionOf(source, node, file);
331
- // Only a variable known to hold a Router or app counts. Without this,
332
- // `req.get('User-Agent')` and `axios.post('http://...')` are read as route
333
- // registrations and published as endpoints that do not exist.
334
- if (!routerVariables.has(routerVariable) && !appVariables.has(routerVariable)) {
335
- // It may still be a router docgen could not confirm — an untyped JS
336
- // parameter, say. Recorded so the omission is visible rather than
337
- // silent, but never emitted as an endpoint.
338
- const first = node.arguments[0];
339
- const candidatePath = literalString(first);
340
- // Requiring express in the file keeps HTTP clients out: `axios.get('/api/x')`
341
- // in a React app is a request, not a route, and reporting it as an
342
- // unconfirmed router would claim the repo runs a server it does not.
343
- if (importsExpress &&
344
- (HTTP_METHODS.has(methodName) || methodName === 'use') &&
345
- candidatePath !== undefined &&
346
- candidatePath.startsWith('/')) {
320
+ if (!routerVariables.has(routerVariable) && !appRoots.has(routerVariable)) {
321
+ const candidatePath = literalString(node.arguments[0]);
322
+ if (importsExpress && (HTTP_METHODS.has(methodName) || methodName === 'use') && candidatePath?.startsWith('/') === true)
347
323
  unconfirmed.add(routerVariable);
348
- }
349
324
  return;
350
325
  }
351
326
  if (methodName === 'use') {
352
327
  const first = node.arguments[0];
353
- const literalPrefix = literalString(first);
354
- const hasPrefix = literalPrefix?.startsWith('/') === true;
355
- const prefix = hasPrefix ? literalPrefix : '';
328
+ const hasPrefix = first !== undefined && node.arguments.length > 1 && isPrefixExpression(first, source, bindings);
356
329
  const mounted = hasPrefix ? node.arguments.slice(1) : node.arguments;
357
330
  for (const argument of mounted) {
358
- // `app.use('/x', routes)` and the ESM/CJS interop form
359
- // `app.use('/x', routes.default)` both mount the same module.
360
331
  const symbol = mountedSymbolName(argument);
361
- if (symbol !== undefined) {
362
- mounts.push({ routerVariable, prefix, symbol, line: position.line ?? 1 });
363
- }
332
+ if (symbol !== undefined)
333
+ mounts.push({
334
+ routerVariable, prefix: hasPrefix ? literalString(first) ?? '' : '',
335
+ ...(hasPrefix && literalString(first) === undefined ? { prefixExpression: first } : {}),
336
+ symbol, line: position.line ?? 1,
337
+ });
364
338
  }
365
339
  return;
366
340
  }
367
341
  if (!HTTP_METHODS.has(methodName))
368
342
  return;
369
- const first = node.arguments[0];
370
- const routePath = literalString(first);
371
- if (routePath === undefined) {
372
- // A computed path cannot be resolved without running the module. Emitting
373
- // nothing here is deliberate: a wrong URL is worse than a missing one.
374
- return;
375
- }
376
- // Express route paths are rooted. A non-rooted string is something else —
377
- // a header name, an absolute URL passed to an HTTP client, an event name.
378
- if (!routePath.startsWith('/'))
343
+ const routePath = literalString(node.arguments[0]);
344
+ if (routePath === undefined || !routePath.startsWith('/'))
379
345
  return;
380
346
  const middleware = [];
381
347
  let requestShape;
382
- // In Express the final argument is the route handler; everything between
383
- // the path and it is middleware. Listing the handler as middleware would
384
- // misreport the auth chain, which is the field a reader most relies on.
385
348
  const handlerArguments = node.arguments.slice(1);
386
349
  const middlewareArguments = handlerArguments.length > 1 ? handlerArguments.slice(0, -1) : [];
387
350
  for (const argument of middlewareArguments) {
388
- if (ts.isIdentifier(argument)) {
351
+ if (ts.isIdentifier(argument))
389
352
  middleware.push(argument.text);
390
- continue;
391
- }
392
- if (ts.isCallExpression(argument) && ts.isIdentifier(argument.expression)) {
393
- const callName = argument.expression.text;
394
- middleware.push(`${callName}()`);
395
- // `validate(CreateOrderSchema)` names the request contract. The
396
- // validator library is not assumed — only that this argument is what
397
- // the route validates against.
398
- const shapeArgument = argument.arguments[0];
399
- if (requestShape === undefined && shapeArgument !== undefined && ts.isIdentifier(shapeArgument)) {
400
- requestShape = { name: shapeArgument.text, kind: 'validator-argument' };
353
+ else if (ts.isCallExpression(argument) && ts.isIdentifier(argument.expression)) {
354
+ middleware.push(`${argument.expression.text}()`);
355
+ const shape = argument.arguments[0];
356
+ if (requestShape === undefined && shape !== undefined && ts.isIdentifier(shape)) {
357
+ requestShape = { name: shape.text, kind: 'validator-argument' };
401
358
  }
402
359
  }
403
360
  }
404
361
  registrations.push({
405
- routerVariable,
406
- method: methodName.toUpperCase(),
407
- path: routePath,
408
- middleware,
409
- ...(requestShape === undefined ? {} : { requestShape }),
410
- line: position.line ?? 1,
411
- column: position.column ?? 1,
362
+ routerVariable, method: methodName.toUpperCase(), path: routePath, middleware,
363
+ ...(requestShape === undefined ? {} : { requestShape }), line: position.line ?? 1, column: position.column ?? 1,
412
364
  });
413
365
  });
414
366
  const defaultExport = bindings.exports.get('default');
415
367
  if (defaultExport?.kind === 'local' && routerVariables.has(defaultExport.localName)) {
416
368
  mounts.push({ routerVariable: '$default', prefix: '', symbol: defaultExport.localName, line: 1 });
417
369
  }
418
- for (const name of [...routerVariables, ...appVariables])
370
+ for (const name of [...routerVariables, ...appRoots.keys(), ...aliases.keys()])
419
371
  unconfirmed.delete(name);
420
372
  return {
421
- file,
422
- bindings,
423
- routerVariables,
424
- appVariables,
425
- registrations,
426
- mounts,
427
- unconfirmedRouters: [...unconfirmed].sort(),
373
+ file, source, bindings, routerVariables, applicationRoots: [...appRoots.values()].sort((a, b) => compareStrings(a.owner, b.owner)),
374
+ registrations, mounts, unconfirmedRouters: [...unconfirmed].sort(compareStrings),
428
375
  };
429
376
  }
377
+ function classifyTyped(name, typeText, routers, addApp) {
378
+ if (ROUTER_TYPE_NAMES.has(typeText))
379
+ routers.add(name);
380
+ else if (APP_TYPE_NAMES.has(typeText))
381
+ addApp(name);
382
+ }
383
+ function factoryName(call) {
384
+ const callee = call.expression;
385
+ return ts.isIdentifier(callee) ? callee.text
386
+ : ts.isPropertyAccessExpression(callee) ? callee.name.text
387
+ : undefined;
388
+ }
389
+ function classOwner(className, property) {
390
+ return `this:${className}:${property}`;
391
+ }
392
+ function splitClassOwner(owner) {
393
+ const [, className = 'Anonymous', property = 'app'] = owner.split(':');
394
+ return [className, property];
395
+ }
396
+ function enclosingClassName(node) {
397
+ let current = node;
398
+ while (current !== undefined) {
399
+ if ((ts.isClassDeclaration(current) || ts.isClassExpression(current)) && current.name !== undefined)
400
+ return current.name.text;
401
+ current = current.parent;
402
+ }
403
+ return undefined;
404
+ }
405
+ function thisPropertyOwner(node) {
406
+ if (!ts.isPropertyAccessExpression(node) || node.expression.kind !== ts.SyntaxKind.ThisKeyword)
407
+ return undefined;
408
+ const className = enclosingClassName(node);
409
+ return className === undefined ? undefined : classOwner(className, node.name.text);
410
+ }
411
+ function expressionOwner(expression, aliases) {
412
+ if (ts.isIdentifier(expression))
413
+ return aliases.get(expression.text) ?? expression.text;
414
+ return thisPropertyOwner(expression);
415
+ }
416
+ function isSimplePropertyName(name) {
417
+ return ts.isIdentifier(name) || ts.isStringLiteral(name);
418
+ }
419
+ function isPrefixExpression(expression, source, bindings) {
420
+ const literal = literalString(expression);
421
+ if (literal !== undefined)
422
+ return literal.startsWith('/');
423
+ if (ts.isTemplateExpression(expression) || ts.isBinaryExpression(expression) ||
424
+ ts.isPropertyAccessExpression(expression) || ts.isElementAccessExpression(expression) ||
425
+ ts.isCallExpression(expression) || ts.isParenthesizedExpression(expression))
426
+ return true;
427
+ if (!ts.isIdentifier(expression))
428
+ return false;
429
+ if (bindings.imports.has(expression.text))
430
+ return /(?:path|prefix|base|mount|url)$/i.test(expression.text);
431
+ let initializer;
432
+ walk(source, (node) => {
433
+ if (initializer !== undefined || !ts.isVariableDeclaration(node) || !ts.isIdentifier(node.name))
434
+ return;
435
+ if (node.name.text === expression.text)
436
+ initializer = node.initializer;
437
+ });
438
+ return initializer !== undefined;
439
+ }
430
440
  function isRouterChain(expression) {
431
441
  let current = expression;
432
- while (ts.isCallExpression(current) && ts.isPropertyAccessExpression(current.expression)) {
442
+ while (ts.isCallExpression(current) && ts.isPropertyAccessExpression(current.expression))
433
443
  current = current.expression.expression;
434
- }
435
- return ts.isCallExpression(current) &&
436
- ((ts.isIdentifier(current.expression) && ROUTER_FACTORIES.has(current.expression.text)) ||
437
- (ts.isPropertyAccessExpression(current.expression) &&
438
- ts.isIdentifier(current.expression.name) && ROUTER_FACTORIES.has(current.expression.name.text)));
444
+ return ts.isCallExpression(current) && ((ts.isIdentifier(current.expression) && ROUTER_FACTORIES.has(current.expression.text)) ||
445
+ (ts.isPropertyAccessExpression(current.expression) && ROUTER_FACTORIES.has(current.expression.name.text)));
439
446
  }
440
447
  function ownerOfChain(node) {
441
448
  let current = node;
@@ -451,4 +458,11 @@ function ownerOfChain(node) {
451
458
  }
452
459
  return undefined;
453
460
  }
461
+ function dedupeGaps(gaps) {
462
+ const unique = new Map();
463
+ for (const gap of gaps)
464
+ unique.set(`${gap.kind}\u0000${gap.source?.file ?? ''}\u0000${gap.source?.line ?? 0}\u0000${gap.message}`, gap);
465
+ return [...unique.values()].sort((a, b) => compareStrings(a.kind, b.kind) || compareStrings(a.source?.file ?? '', b.source?.file ?? '') ||
466
+ (a.source?.line ?? 0) - (b.source?.line ?? 0) || compareStrings(a.message, b.message));
467
+ }
454
468
  //# sourceMappingURL=express.js.map