Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
194 changes: 157 additions & 37 deletions src/detectors/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1759,6 +1759,7 @@ async function resolveRoutePrefixes(
// This handles multi-level routing: app.ts → routes.ts → auth.ts
// mountEdges: targetFile → { prefix, mountedBy }
const mountEdges = new Map<string, { prefix: string; mountedBy: string }>();
const fileInternalPrefixes = new Map<string, string>();

const sourceFiles = files.filter(f => f.match(/\.(ts|js|mjs|cjs|py)$/));

Expand All @@ -1770,8 +1771,8 @@ async function resolveRoutePrefixes(
const dir = rel.includes("/") ? rel.split("/").slice(0, -1).join("/") : "";

if (file.endsWith(".py")) {
if (content.includes("include_router")) {
parsePythonMountsToGraph(content, dir, files, project, mountEdges, rel);
if (content.includes("include_router") || content.includes("APIRouter")) {
parsePythonMountsToGraph(content, dir, files, project, mountEdges, fileInternalPrefixes, rel);
}
} else {
if (content.includes(".route(") || content.includes(".use(")) {
Expand All @@ -1780,7 +1781,7 @@ async function resolveRoutePrefixes(
}
}

if (mountEdges.size === 0) return routes;
if (mountEdges.size === 0 && fileInternalPrefixes.size === 0) return routes;

// Resolve full prefix for each file by walking up the mount graph.
// Handles chaining: if app.ts mounts routes.ts at /api, and routes.ts
Expand All @@ -1806,12 +1807,14 @@ async function resolveRoutePrefixes(

return routes.map(route => {
const routeFile = route.file.replace(/\\/g, "/");
const prefix = resolveFullPrefix(routeFile, new Set());
const parentPrefix = resolveFullPrefix(routeFile, new Set());
const selfPrefix = fileInternalPrefixes.get(routeFile) || "";
const prefix = (parentPrefix + selfPrefix).replace(/\/\//g, "/");
if (!prefix || prefix === "/") return route;
// Don't double-prefix if path already starts with it
if (route.path.startsWith(prefix + "/") || route.path === prefix) return route;
const base = prefix.replace(/\/$/, "");
const newPath = route.path === "/" ? base : base + route.path;
const newPath = route.path === "/" ? (base || "/") : (base + (route.path.startsWith("/") ? route.path : `/${route.path}`));
return { ...route, path: newPath };
});
}
Expand Down Expand Up @@ -1903,59 +1906,176 @@ function resolveJSImport(
return null;
}

function resolvePythonModuleFile(
modStr: string,
entryDir: string,
files: string[],
project: ProjectInfo
): string | null {
let modPath = "";
if (modStr.startsWith(".")) {
let leadingDots = 0;
while (modStr[leadingDots] === ".") leadingDots++;
const remainder = modStr.slice(leadingDots).replace(/\./g, "/");

const dirParts = entryDir ? entryDir.split("/") : [];
const upLevels = leadingDots - 1;
if (upLevels > dirParts.length) return null;
const baseParts = dirParts.slice(0, dirParts.length - upLevels);
modPath = remainder
? (baseParts.length ? `${baseParts.join("/")}/${remainder}` : remainder)
: baseParts.join("/");
} else {
modPath = modStr.replace(/\./g, "/");
}

const candidates = [
`${modPath}.py`,
`${modPath}/__init__.py`,
];

for (const cand of candidates) {
const hit = files.find(f => {
const rel = f.replace(/\\/g, "/");
return rel === cand || rel.endsWith(`/${cand}`);
});
if (hit) return relative(project.root, hit).replace(/\\/g, "/");
}

return null;
}

function resolvePythonPrefix(expr: string, stringVars: Map<string, string>): string {
if (!expr) return "";
const trimmed = expr.trim();
const litMatch = trimmed.match(/^['"](.*?)['"]$/);
if (litMatch) return litMatch[1];

const fMatch = trimmed.match(/^f['"](.*?)['"]$/);
if (fMatch) {
return fMatch[1].replace(/\{([A-Za-z_]\w*)\}/g, (_, varName) => {
return stringVars.get(varName) ?? "";
});
}

if (trimmed.includes("+")) {
const parts = trimmed.split("+").map(p => resolvePythonPrefix(p.trim(), stringVars));
return parts.join("");
}

if (stringVars.has(trimmed)) {
return stringVars.get(trimmed)!;
}

return "";
}

/** Python/FastAPI: scan for APIRouter(prefix=...) + include_router() chains */
function parsePythonMountsToGraph(
content: string,
_entryDir: string,
entryDir: string,
files: string[],
project: ProjectInfo,
mountEdges: Map<string, { prefix: string; mountedBy: string }>,
fileInternalPrefixes: Map<string, string>,
sourceFile: string
): void {
// Step 1: Build alias map: "auth_router" → "backend/routes/auth.py"
// from routes.auth import router as auth_router
const aliasRe = /from\s+([\w.]+)\s+import\s+router\s+as\s+(\w+)/g;
const aliasMap = new Map<string, string>(); // alias → source file
// Step 1: Collect string constants (e.g. API_V1_PREFIX: Final[str] = '/api/v1')
const stringVars = new Map<string, string>();
const varAssignRe = /^\s*([A-Za-z_]\w*)(?:\s*:\s*[^=\n]+)?\s*=\s*(['"])(.*?)\2\s*$/gm;
let vm;
while ((vm = varAssignRe.exec(content)) !== null) {
stringVars.set(vm[1], vm[3]);
}

// Step 2: Build alias map: symbol/module name → source file
const aliasMap = new Map<string, string>();

// from <module> import <symbols>
const fromImportRe = /from\s+([\w.]+)\s+import\s+([^#\n]+)/g;
let m;
while ((m = aliasRe.exec(content)) !== null) {
while ((m = fromImportRe.exec(content)) !== null) {
const moduleDots = m[1];
const alias = m[2];
const modPath = moduleDots.replace(/\./g, "/");
const hit = files.find(f => {
const rel = f.replace(/\\/g, "/");
return rel.endsWith(`/${modPath}.py`) || rel.endsWith(`${modPath}.py`);
});
if (hit) aliasMap.set(alias, relative(project.root, hit).replace(/\\/g, "/"));
const importedPart = m[2];
for (const item of importedPart.split(",")) {
const trimmed = item.trim();
if (!trimmed) continue;
const [symbol, alias] = trimmed.split(/\s+as\s+/);
const name = (alias || symbol).trim();
if (!name || !/^\w+$/.test(name)) continue;

// 1. Try treating symbol as a submodule/file: moduleDots.symbol
const fullMod = `${moduleDots}.${symbol.trim()}`;
const hitDirect = resolvePythonModuleFile(fullMod, entryDir, files, project);
if (hitDirect) {
aliasMap.set(name, hitDirect);
continue;
}

// 2. Try treating moduleDots as the file (e.g. from routes.auth import router)
const hitParent = resolvePythonModuleFile(moduleDots, entryDir, files, project);
if (hitParent) {
aliasMap.set(name, hitParent);
}
}
}

// Also handle: from routes.auth import router (no alias)
const noAliasRe = /from\s+([\w.]+)\s+import\s+router(?!\s+as)\b/g;
while ((m = noAliasRe.exec(content)) !== null) {
const modPath = m[1].replace(/\./g, "/");
const hit = files.find(f => f.replace(/\\/g, "/").endsWith(`${modPath}.py`));
if (hit) aliasMap.set("router", relative(project.root, hit).replace(/\\/g, "/"));
// import <module> [as <alias>]
const directImportRe = /import\s+([\w.]+)(?:\s+as\s+(\w+))?/g;
while ((m = directImportRe.exec(content)) !== null) {
const fullMod = m[1];
const alias = m[2] || fullMod.split(".").pop()!;
const hit = resolvePythonModuleFile(fullMod, entryDir, files, project);
if (hit) aliasMap.set(alias, hit);
}

// Step 2: Find APIRouter with prefix: api_router = APIRouter(prefix="/api")
const prefixRouterRe = /(\w+)\s*=\s*APIRouter\s*\([^)]*prefix\s*=\s*['"]([^'"]+)['"]/g;
const routerPrefixes = new Map<string, string>(); // varName → prefix
// Step 3: Find APIRouter definitions with prefix:
// router = APIRouter(prefix="/api")
// consumer_router = r = APIRouter()
const prefixRouterRe = /([A-Za-z_]\w*(?:\s*=\s*[A-Za-z_]\w*)*)\s*=\s*APIRouter\s*\(([\s\S]*?)\)/g;
const routerPrefixes = new Map<string, string>();
while ((m = prefixRouterRe.exec(content)) !== null) {
routerPrefixes.set(m[1], m[2]);
const varsPart = m[1];
const argsPart = m[2];
const pMatch = argsPart.match(/prefix\s*=\s*(f?['"][^'"]*['"]|[A-Za-z_]\w*(?:\s*\+\s*(?:f?['"][^'"]*['"]|[A-Za-z_]\w*))*)/);
const prefix = pMatch ? resolvePythonPrefix(pMatch[1], stringVars) : "";

for (const v of varsPart.split("=")) {
const varName = v.trim();
if (varName && /^\w+$/.test(varName)) {
routerPrefixes.set(varName, prefix);
}
}

if (prefix && !fileInternalPrefixes.has(sourceFile)) {
fileInternalPrefixes.set(sourceFile, prefix);
}
}

// Step 3: Chain include_router calls:
// api_router.include_router(auth_router)
// api_router.include_router(cv_router, prefix="/cv")
const includeRe = /(\w+)\s*\.\s*include_router\s*\(\s*(\w+)(?:[^)]*prefix\s*=\s*['"]([^'"]+)['"])?\s*\)/g;
// Step 4: Chain include_router calls:
// app.include_router(consumer.consumer_router, prefix=f"{API_V1_PREFIX}/consumer")
// r.include_router(post_notification.router)
const includeRe = /([A-Za-z_]\w*)\s*\.\s*include_router\s*\(([\s\S]*?)\)/g;
while ((m = includeRe.exec(content)) !== null) {
const parentVar = m[1];
const childVar = m[2];
const extraPrefix = m[3] || "";
const body = m[2];

const firstArgMatch = body.match(/^\s*([A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*)/);
if (!firstArgMatch) continue;
const routerExpr = firstArgMatch[1];

const prefixMatch = body.match(/prefix\s*=\s*(f?['"][^'"]*['"]|[A-Za-z_]\w*(?:\s*\+\s*(?:f?['"][^'"]*['"]|[A-Za-z_]\w*))*)/);
const extraPrefix = prefixMatch ? resolvePythonPrefix(prefixMatch[1], stringVars) : "";
const parentPrefix = routerPrefixes.get(parentVar) || "";
const fullPrefix = parentPrefix + extraPrefix;
const fullPrefix = (parentPrefix + extraPrefix).replace(/\/\//g, "/");

const targetFile = aliasMap.get(childVar);
if (targetFile && fullPrefix && !mountEdges.has(targetFile)) {
// Resolve target file from routerExpr:
const targetFile =
aliasMap.get(routerExpr) ||
aliasMap.get(routerExpr.split(".")[0]) ||
aliasMap.get(routerExpr.split(".").pop()!);

if (targetFile && !mountEdges.has(targetFile)) {
mountEdges.set(targetFile, { prefix: fullPrefix, mountedBy: sourceFile });
}
}
Expand Down
37 changes: 37 additions & 0 deletions tests/detectors.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,43 @@ def create_user():
assert.ok(routes.some((r: any) => r.method === "GET" && r.path === "/users"));
});

it("resolves nested FastAPI router prefixes and include_router cascades (issue #55)", async () => {
const dir = await writeFixture("fastapi-cascade-prefixes", {
"requirements.txt": "fastapi\nuvicorn\n",
"main.py": `from backend.routers.v1 import consumer

API_V1_PREFIX: Final[str] = '/api/v1'

app.include_router(
consumer.consumer_router,
prefix=f"{API_V1_PREFIX}/consumer",
)
`,
"backend/routers/v1/consumer/__init__.py": `from fastapi import APIRouter
from backend.routers.v1.consumer import post_notification

consumer_router = r = APIRouter()

r.include_router(post_notification.router)
`,
"backend/routers/v1/consumer/post_notification.py": `from fastapi import APIRouter, status

router = APIRouter()

@router.post('/notification', status_code=status.HTTP_201_CREATED)
def post_notification():
return {"status": "ok"}
`
});
const project = await mods.detectProject(dir);
const files = await mods.collectFiles(dir);
const routes = await mods.detectRoutes(files, project);
assert.ok(
routes.some((r: any) => r.method === "POST" && r.path === "/api/v1/consumer/notification"),
`Expected POST /api/v1/consumer/notification, got: ${routes.map((r: any) => `${r.method} ${r.path}`).join(", ")}`
);
});

it("detects Django URL patterns", async () => {
const dir = await writeFixture("django-app", {
"requirements.txt": "django\n",
Expand Down