-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathrouterResolver.ts
More file actions
269 lines (245 loc) · 7.27 KB
/
Copy pathrouterResolver.ts
File metadata and controls
269 lines (245 loc) · 7.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
import { existsSync } from "node:fs"
import { isAbsolute, join } from "node:path"
import { log } from "../utils/logger"
import { analyzeFile } from "./analyzer"
import { resolveNamedImport, resolveRouterFromInit } from "./importResolver"
import type { FileAnalysis, RouterInfo, RouterNode } from "./internal"
import type { Parser } from "./parser"
export type { RouterNode }
/**
* Finds the main FastAPI app or APIRouter in the list of routers.
* If targetVariable is specified, only returns the router with that variable name.
* Otherwise, prioritizes FastAPI apps over APIRouters.
*/
function findAppRouter(
routers: RouterInfo[],
targetVariable?: string,
): RouterInfo | undefined {
if (targetVariable) {
return routers.find((r) => r.variableName === targetVariable)
}
return (
routers.find((r) => r.type === "FastAPI") ??
routers.find((r) => r.type === "APIRouter")
)
}
/**
* Builds a router graph starting from the given entry file.
* If targetVariable is specified, only that specific app/router will be used.
*/
export function buildRouterGraph(
entryFile: string,
parser: Parser,
projectRoot: string,
targetVariable?: string,
): RouterNode | null {
return buildRouterGraphInternal(
entryFile,
parser,
projectRoot,
new Set(),
targetVariable,
)
}
/**
* Internal recursive function to build the router graph.
*/
function buildRouterGraphInternal(
entryFile: string,
parser: Parser,
projectRoot: string,
visited: Set<string>,
targetVariable?: string,
): RouterNode | null {
// Resolve the full path of the entry file if necessary
let resolvedEntryFile = entryFile
if (!existsSync(resolvedEntryFile) && !isAbsolute(entryFile)) {
resolvedEntryFile = join(projectRoot, entryFile)
}
if (!existsSync(resolvedEntryFile)) {
log(`File not found: "${entryFile}"`)
return null
}
// Prevent infinite recursion on circular imports
if (visited.has(resolvedEntryFile)) {
log(`Skipping already visited file: "${resolvedEntryFile}"`)
return null
}
visited.add(resolvedEntryFile)
// Analyze the entry file
let analysis = analyzeFile(resolvedEntryFile, parser)
if (!analysis) {
log(`Failed to analyze file: "${resolvedEntryFile}"`)
return null
}
log(
`Analyzed "${resolvedEntryFile}": ${analysis.routes.length} routes, ${analysis.routers.length} routers, ${analysis.includeRouters.length} include_router calls`,
)
// Find FastAPI instantiation (filter by targetVariable if specified)
let appRouter = findAppRouter(analysis.routers, targetVariable)
// If no FastAPI/APIRouter found and this is an __init__.py, check for re-exports
if (!appRouter && resolvedEntryFile.endsWith("__init__.py")) {
const actualRouterFile = resolveRouterFromInit(
resolvedEntryFile,
projectRoot,
parser,
)
if (actualRouterFile && !visited.has(actualRouterFile)) {
visited.add(actualRouterFile)
const actualAnalysis = analyzeFile(actualRouterFile, parser)
if (actualAnalysis) {
const actualRouter = findAppRouter(actualAnalysis.routers)
if (actualRouter) {
analysis = actualAnalysis
appRouter = actualRouter
resolvedEntryFile = actualRouterFile
}
}
}
}
if (!appRouter || !analysis) {
return null
}
// Find all routers included in the app
// Only include routes that belong directly to the app (not to local APIRouters)
const appRoutes = analysis.routes.filter(
(r) => r.owner === appRouter.variableName,
)
const rootRouter: RouterNode = {
filePath: resolvedEntryFile,
variableName: appRouter.variableName,
type: appRouter.type,
prefix: appRouter.prefix,
tags: appRouter.tags,
line: appRouter.line,
column: appRouter.column,
routes: appRoutes.map((r) => ({
method: r.method,
path: r.path,
function: r.function,
line: r.line,
column: r.column,
})),
children: [],
}
// Process include_router calls to find child routers
for (const include of analysis.includeRouters) {
log(
`Resolving include_router: ${include.router} (prefix: ${include.prefix || "none"})`,
)
const childRouter = resolveRouterReference(
include.router,
analysis,
resolvedEntryFile,
projectRoot,
parser,
visited,
)
if (childRouter) {
// Merge tags from include_router call with the router's own tags
if (include.tags.length > 0) {
childRouter.tags = [...new Set([...childRouter.tags, ...include.tags])]
}
rootRouter.children.push({
router: childRouter,
prefix: include.prefix,
tags: include.tags,
})
}
}
// Process mount() calls for subapps
for (const mount of analysis.mounts) {
const childRouter = resolveRouterReference(
mount.app,
analysis,
resolvedEntryFile,
projectRoot,
parser,
visited,
)
if (childRouter) {
rootRouter.children.push({
router: childRouter,
prefix: mount.path,
tags: [],
})
}
}
return rootRouter
}
/**
* Resolves a router/app reference to its RouterNode.
* Used for include_router and mount calls.
*/
function resolveRouterReference(
reference: string,
analysis: FileAnalysis,
currentFile: string,
projectRoot: string,
parser: Parser,
visited: Set<string>,
): RouterNode | null {
const parts = reference.split(".")
const moduleName = parts[0]
// First, check if this is a local router defined in the same file
const localRouter = analysis.routers.find(
(r) => r.variableName === moduleName && r.type === "APIRouter",
)
if (localRouter) {
// Filter routes that belong to this router (decorated with @router.method)
const routerRoutes = analysis.routes.filter((r) => r.owner === moduleName)
return {
filePath: currentFile,
variableName: localRouter.variableName,
type: localRouter.type,
prefix: localRouter.prefix,
tags: localRouter.tags,
line: localRouter.line,
column: localRouter.column,
routes: routerRoutes.map((r) => ({
method: r.method,
path: r.path,
function: r.function,
line: r.line,
column: r.column,
})),
children: [],
}
}
// Otherwise, look for an imported router
const matchingImport = analysis.imports.find((imp) =>
imp.names.includes(moduleName),
)
if (!matchingImport) {
log(`No import found for router reference: ${reference}`)
return null
}
// Find the original import name (in case moduleName is an alias)
// e.g., "from .api_tokens import router as api_tokens_router"
// moduleName = "api_tokens_router", originalName = "router"
const namedImport = matchingImport.namedImports.find(
(ni) => (ni.alias ?? ni.name) === moduleName,
)
const originalName = namedImport?.name ?? moduleName
const importedFilePath = resolveNamedImport(
{
modulePath: matchingImport.modulePath,
names: [originalName],
isRelative: matchingImport.isRelative,
relativeDots: matchingImport.relativeDots,
},
currentFile,
projectRoot,
parser,
)
if (!importedFilePath) {
log(`Could not resolve import: ${matchingImport.modulePath}`)
return null
}
return buildRouterGraphInternal(
importedFilePath,
parser,
projectRoot,
visited,
)
}