feat: wire up framework route extraction (#89)

* docs: add framework extract wiring plan

* feat(resolution): replace extractNodes with extract() returning nodes and references

* feat(resolution): add getApplicableFrameworks helper for per-language dispatch

* feat(django): emit route nodes and route->view references in extract()

* feat(flask,fastapi): emit route nodes and route->handler references

* feat(express): emit route nodes and route->handler references

* feat(laravel): emit route nodes and route->handler references

* feat(rails): emit route nodes and route->handler references

* feat(spring): emit route nodes and route->handler references

* feat(go): emit route nodes and route->handler references

* feat(rust): emit route nodes and route->handler references

* feat(aspnet): emit route nodes and route->handler references

* feat(swift,vapor): emit route nodes and route->handler references

* chore(react,svelte): migrate resolvers to extract() interface

* feat(extraction): run framework extractors after tree-sitter parse

* docs: document framework route extraction

* feat(strip-comments): add per-language comment stripper for framework extractors

Replaces comment characters and string-literal contents with spaces (not
removal) so source offsets stay valid for downstream regex match index ->
line number conversion. Handles Python triple-quoted docstrings, Ruby
=begin/=end, Rust nested block comments, and the standard //, #, /* */
forms across the supported languages.

This is consumed by framework extract() methods in a follow-up commit so
that commented-out / docstring routing examples don't surface as phantom
route nodes in the graph.

* feat(frameworks): strip comments before regex extraction (prevents phantom routes)

Pipes the per-language stripCommentsForRegex helper into every framework
extract() that scans raw source: django/flask/fastapi (python.ts),
express, laravel, rails, spring, go, rust, aspnet, vapor, plus
swiftui/uikit struct extraction in swift.ts.

Without this, examples like:

    # path('/admin/', AdminPanel.as_view())
    """ path('/users/', UserListView.as_view()) """
    urlpatterns = [path('/real/', RealView.as_view())]

produced 3 phantom route nodes. Now only the real one is extracted.

Each framework gets a regression test in __tests__/frameworks.test.ts
asserting that line-, block-, docstring- and (where relevant)
heredoc-style commented-out routes do not surface as nodes.

---------

Co-authored-by: Colby McHenry <me@colbymchenry.com>
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
timomeara
2026-05-07 22:03:33 -05:00
committed by GitHub
co-authored by Colby McHenry Claude Opus 4.7
parent 5ab81746e8
commit 74327814ee
23 changed files with 3080 additions and 719 deletions
+78 -82
View File
@@ -6,9 +6,11 @@
import { Node } from '../../types';
import { FrameworkResolver, UnresolvedRef, ResolvedRef, ResolutionContext } from '../types';
import { stripCommentsForRegex } from '../strip-comments';
export const aspnetResolver: FrameworkResolver = {
name: 'aspnet',
languages: ['csharp'],
detect(context: ResolutionContext): boolean {
// Check for .csproj files with ASP.NET references
@@ -114,91 +116,26 @@ export const aspnetResolver: FrameworkResolver = {
return null;
},
extractNodes(filePath: string, content: string): Node[] {
extract(filePath, content) {
if (!filePath.endsWith('.cs')) return { nodes: [], references: [] };
const nodes: Node[] = [];
const references: UnresolvedRef[] = [];
const now = Date.now();
const safe = stripCommentsForRegex(content, 'csharp');
// Extract route attributes
// [HttpGet("path")], [HttpPost("path")], [Route("path")]
const routePatterns = [
/\[(Http(Get|Post|Put|Patch|Delete))\s*\(\s*["']([^"']+)["']\s*\)\]/g,
/\[(Http(Get|Post|Put|Patch|Delete))\s*\]/g,
/\[Route\s*\(\s*["']([^"']+)["']\s*\)\]/g,
];
// [HttpGet("path")], [HttpPost("path")], etc.
const attrRegex = /\[(HttpGet|HttpPost|HttpPut|HttpPatch|HttpDelete)\s*\(\s*"([^"]+)"\s*\)\]/g;
let match: RegExpExecArray | null;
while ((match = attrRegex.exec(safe)) !== null) {
const [, verb, routePath] = match;
const method = verb!.replace(/^Http/, '').toUpperCase();
const line = safe.slice(0, match.index).split('\n').length;
for (const pattern of routePatterns) {
let match;
while ((match = pattern.exec(content)) !== null) {
const line = content.slice(0, match.index).split('\n').length;
if (pattern.source.includes('Http')) {
if (match[3]) {
// HttpGet("path") style
const [, , method, path] = match;
nodes.push({
id: `route:${filePath}:${method!.toUpperCase()}:${path}:${line}`,
kind: 'route',
name: `${method!.toUpperCase()} ${path}`,
qualifiedName: `${filePath}::${method!.toUpperCase()}:${path}`,
filePath,
startLine: line,
endLine: line,
startColumn: 0,
endColumn: match[0].length,
language: 'csharp',
updatedAt: now,
});
} else if (match[2]) {
// HttpGet style without path
const [, , method] = match;
nodes.push({
id: `route:${filePath}:${method!.toUpperCase()}:${line}`,
kind: 'route',
name: `${method!.toUpperCase()}`,
qualifiedName: `${filePath}::${method!.toUpperCase()}`,
filePath,
startLine: line,
endLine: line,
startColumn: 0,
endColumn: match[0].length,
language: 'csharp',
updatedAt: now,
});
}
} else {
// [Route("path")] style
const [, path] = match;
nodes.push({
id: `route:${filePath}:ROUTE:${path}:${line}`,
kind: 'route',
name: `ROUTE ${path}`,
qualifiedName: `${filePath}::ROUTE:${path}`,
filePath,
startLine: line,
endLine: line,
startColumn: 0,
endColumn: match[0].length,
language: 'csharp',
updatedAt: now,
});
}
}
}
// Extract minimal API routes (ASP.NET Core 6+)
// app.MapGet("/path", ...), app.MapPost("/path", ...)
const minimalApiPattern = /\.Map(Get|Post|Put|Patch|Delete)\s*\(\s*["']([^"']+)["']/g;
let match;
while ((match = minimalApiPattern.exec(content)) !== null) {
const [, method, path] = match;
const line = content.slice(0, match.index).split('\n').length;
nodes.push({
id: `route:${filePath}:${method!.toUpperCase()}:${path}:${line}`,
const routeNode: Node = {
id: `route:${filePath}:${line}:${method}:${routePath}`,
kind: 'route',
name: `${method!.toUpperCase()} ${path}`,
qualifiedName: `${filePath}::${method!.toUpperCase()}:${path}`,
name: `${method} ${routePath}`,
qualifiedName: `${filePath}::route:${routePath}`,
filePath,
startLine: line,
endLine: line,
@@ -206,13 +143,72 @@ export const aspnetResolver: FrameworkResolver = {
endColumn: match[0].length,
language: 'csharp',
updatedAt: now,
});
};
nodes.push(routeNode);
// Capture the next method declaration
const tail = safe.slice(match.index + match[0].length);
const methodMatch = tail.match(/(?:public|private|protected|internal)\s+[\w<>,\s\[\]]+?\s+(\w+)\s*\(/);
if (methodMatch) {
references.push({
fromNodeId: routeNode.id,
referenceName: methodMatch[1]!,
referenceKind: 'references',
line,
column: 0,
filePath,
language: 'csharp',
});
}
}
return nodes;
// Minimal APIs: app.MapGet("/path", handler)
const minimalRegex = /\.Map(Get|Post|Put|Patch|Delete)\s*\(\s*"([^"]+)"\s*,\s*([^,)]+)/g;
while ((match = minimalRegex.exec(safe)) !== null) {
const [, verb, routePath, handlerExpr] = match;
const method = verb!.toUpperCase();
const line = safe.slice(0, match.index).split('\n').length;
const routeNode: Node = {
id: `route:${filePath}:${line}:${method}:${routePath}`,
kind: 'route',
name: `${method} ${routePath}`,
qualifiedName: `${filePath}::route:${routePath}`,
filePath,
startLine: line,
endLine: line,
startColumn: 0,
endColumn: match[0].length,
language: 'csharp',
updatedAt: now,
};
nodes.push(routeNode);
const handlerName = extractCSharpTailIdent(handlerExpr!);
if (handlerName) {
references.push({
fromNodeId: routeNode.id,
referenceName: handlerName,
referenceKind: 'references',
line,
column: 0,
filePath,
language: 'csharp',
});
}
}
return { nodes, references };
},
};
/** Extract last identifier from an expression like `MyService.Handler` or `Handler`. */
function extractCSharpTailIdent(expr: string): string | null {
const cleaned = expr.trim().replace(/\s+/g, '');
const m = cleaned.match(/(?:\.|^)([A-Za-z_][A-Za-z0-9_]*)$/);
return m ? m[1]! : null;
}
// Directory patterns
const CONTROLLER_DIRS = ['/Controllers/'];
const SERVICE_DIRS = ['/Services/', '/Service/', '/Application/'];
+46 -31
View File
@@ -6,9 +6,17 @@
import { Node } from '../../types';
import { FrameworkResolver, UnresolvedRef, ResolvedRef, ResolutionContext } from '../types';
import { stripCommentsForRegex } from '../strip-comments';
function extractTailIdent(expr: string): string | null {
const cleaned = expr.replace(/\s+/g, '').replace(/\(\)$/, '');
const m = cleaned.match(/(?:\.|^)([A-Za-z_][A-Za-z0-9_]*)$/);
return m ? m[1]! : null;
}
export const expressResolver: FrameworkResolver = {
name: 'express',
languages: ['javascript', 'typescript'],
detect(context: ResolutionContext): boolean {
// Check for Express in package.json
@@ -90,44 +98,51 @@ export const expressResolver: FrameworkResolver = {
return null;
},
extractNodes(filePath: string, content: string): Node[] {
extract(filePath, content) {
if (!/\.(m?js|tsx?|cjs)$/.test(filePath)) return { nodes: [], references: [] };
const nodes: Node[] = [];
const references: UnresolvedRef[] = [];
const now = Date.now();
// Extract route definitions
// app.get('/path', handler) or router.get('/path', handler)
const routePatterns = [
/(app|router)\.(get|post|put|patch|delete|all|use)\(\s*['"]([^'"]+)['"]/g,
];
for (const pattern of routePatterns) {
let match;
while ((match = pattern.exec(content)) !== null) {
const [, _obj, method, path] = match;
const line = content.slice(0, match.index).split('\n').length;
// Skip middleware use() without paths
if (method === 'use' && !path?.startsWith('/')) {
continue;
}
nodes.push({
id: `route:${filePath}:${method!.toUpperCase()}:${path}:${line}`,
kind: 'route',
name: `${method!.toUpperCase()} ${path}`,
qualifiedName: `${filePath}::${method!.toUpperCase()}:${path}`,
const lang = detectLanguage(filePath);
const safe = stripCommentsForRegex(content, lang);
// (app|router).METHOD('/path', handler-expr)
const regex = /\b(app|router)\.(get|post|put|patch|delete|all|use)\s*\(\s*['"]([^'"]+)['"]\s*,\s*([^)]+)\)/g;
let match: RegExpExecArray | null;
while ((match = regex.exec(safe)) !== null) {
const [, _obj, method, routePath, handlers] = match;
if (method === 'use' && !routePath!.startsWith('/')) continue;
const line = safe.slice(0, match.index).split('\n').length;
const routeNode: Node = {
id: `route:${filePath}:${line}:${method!.toUpperCase()}:${routePath}`,
kind: 'route',
name: `${method!.toUpperCase()} ${routePath}`,
qualifiedName: `${filePath}::${method!.toUpperCase()}:${routePath}`,
filePath,
startLine: line,
endLine: line,
startColumn: 0,
endColumn: match[0].length,
language: detectLanguage(filePath),
updatedAt: now,
};
nodes.push(routeNode);
// Handler is the LAST comma-separated argument; earlier ones are middleware.
const parts = handlers!.split(',').map((s) => s.trim()).filter(Boolean);
const last = parts[parts.length - 1];
const handlerName = last ? extractTailIdent(last) : null;
if (handlerName) {
references.push({
fromNodeId: routeNode.id,
referenceName: handlerName,
referenceKind: 'references',
line,
column: 0,
filePath,
startLine: line,
endLine: line,
startColumn: 0,
endColumn: match[0].length,
language: detectLanguage(filePath),
updatedAt: now,
});
}
}
return nodes;
return { nodes, references };
},
};
+44 -83
View File
@@ -6,9 +6,11 @@
import { Node } from '../../types';
import { FrameworkResolver, UnresolvedRef, ResolvedRef, ResolutionContext } from '../types';
import { stripCommentsForRegex } from '../strip-comments';
export const goResolver: FrameworkResolver = {
name: 'go',
languages: ['go'],
detect(context: ResolutionContext): boolean {
// Check for go.mod file (Go modules)
@@ -78,24 +80,30 @@ export const goResolver: FrameworkResolver = {
return null;
},
extractNodes(filePath: string, content: string): Node[] {
extract(filePath, content) {
if (!filePath.endsWith('.go')) return { nodes: [], references: [] };
const nodes: Node[] = [];
const references: UnresolvedRef[] = [];
const now = Date.now();
const safe = stripCommentsForRegex(content, 'go');
// Extract Gin routes
// r.GET("/path", handler), router.POST("/path", handler), etc.
const ginRoutePattern = /\.\s*(GET|POST|PUT|PATCH|DELETE|OPTIONS|HEAD)\s*\(\s*["']([^"']+)["']/g;
// (router|r|mux|app).METHOD("/path", handler)
// Handles Gin (GET/POST/...), Chi (Get/Post/...), net/http (HandleFunc/Handle).
const routeRegex = /\b(?:router|r|mux|app|e)\.(GET|POST|PUT|PATCH|DELETE|OPTIONS|HEAD|Get|Post|Put|Patch|Delete|Handle|HandleFunc)\s*\(\s*"([^"]+)"\s*,\s*([^)]+)\)/g;
let match: RegExpExecArray | null;
while ((match = routeRegex.exec(safe)) !== null) {
const [, rawMethod, routePath, handlerExpr] = match;
const line = safe.slice(0, match.index).split('\n').length;
const method =
rawMethod === 'Handle' || rawMethod === 'HandleFunc'
? 'ANY'
: rawMethod!.toUpperCase();
let match;
while ((match = ginRoutePattern.exec(content)) !== null) {
const [, method, path] = match;
const line = content.slice(0, match.index).split('\n').length;
nodes.push({
id: `route:${filePath}:${method}:${path}:${line}`,
const routeNode: Node = {
id: `route:${filePath}:${line}:${method}:${routePath}`,
kind: 'route',
name: `${method} ${path}`,
qualifiedName: `${filePath}::${method}:${path}`,
name: `${method} ${routePath}`,
qualifiedName: `${filePath}::route:${routePath}`,
filePath,
startLine: line,
endLine: line,
@@ -103,81 +111,34 @@ export const goResolver: FrameworkResolver = {
endColumn: match[0].length,
language: 'go',
updatedAt: now,
});
};
nodes.push(routeNode);
const handlerName = extractGoTailIdent(handlerExpr!);
if (handlerName) {
references.push({
fromNodeId: routeNode.id,
referenceName: handlerName,
referenceKind: 'references',
line,
column: 0,
filePath,
language: 'go',
});
}
}
// Extract Echo routes
// e.GET("/path", handler)
const echoRoutePattern = /e\.\s*(GET|POST|PUT|PATCH|DELETE)\s*\(\s*["']([^"']+)["']/g;
while ((match = echoRoutePattern.exec(content)) !== null) {
const [, method, path] = match;
const line = content.slice(0, match.index).split('\n').length;
nodes.push({
id: `route:${filePath}:${method}:${path}:${line}`,
kind: 'route',
name: `${method} ${path}`,
qualifiedName: `${filePath}::${method}:${path}`,
filePath,
startLine: line,
endLine: line,
startColumn: 0,
endColumn: match[0].length,
language: 'go',
updatedAt: now,
});
}
// Extract Chi routes
// r.Get("/path", handler), r.Post("/path", handler)
const chiRoutePattern = /r\.\s*(Get|Post|Put|Patch|Delete)\s*\(\s*["']([^"']+)["']/g;
while ((match = chiRoutePattern.exec(content)) !== null) {
const [, method, path] = match;
const line = content.slice(0, match.index).split('\n').length;
nodes.push({
id: `route:${filePath}:${method!.toUpperCase()}:${path}:${line}`,
kind: 'route',
name: `${method!.toUpperCase()} ${path}`,
qualifiedName: `${filePath}::${method!.toUpperCase()}:${path}`,
filePath,
startLine: line,
endLine: line,
startColumn: 0,
endColumn: match[0].length,
language: 'go',
updatedAt: now,
});
}
// Extract standard library http.HandleFunc
const httpHandlePattern = /http\.HandleFunc\s*\(\s*["']([^"']+)["']/g;
while ((match = httpHandlePattern.exec(content)) !== null) {
const [, path] = match;
const line = content.slice(0, match.index).split('\n').length;
nodes.push({
id: `route:${filePath}:ANY:${path}:${line}`,
kind: 'route',
name: `ANY ${path}`,
qualifiedName: `${filePath}::ANY:${path}`,
filePath,
startLine: line,
endLine: line,
startColumn: 0,
endColumn: match[0].length,
language: 'go',
updatedAt: now,
});
}
return nodes;
return { nodes, references };
},
};
/** Extract the last identifier from an expression like `pkg.Sub.handler` or `handler`. */
function extractGoTailIdent(expr: string): string | null {
const cleaned = expr.trim().replace(/\s+/g, '').replace(/\(\)$/, '');
const m = cleaned.match(/(?:\.|^)([A-Za-z_][A-Za-z0-9_]*)$/);
return m ? m[1]! : null;
}
// Directory patterns for framework resolution
const HANDLER_DIRS = ['handler', 'handlers', 'api', 'routes', 'controller', 'controllers'];
const SERVICE_DIRS = ['service', 'services', 'repository', 'store', 'pkg'];
+14
View File
@@ -5,6 +5,7 @@
*/
import { FrameworkResolver, ResolutionContext } from '../types';
import type { Language } from '../../types';
import { laravelResolver } from './laravel';
import { expressResolver } from './express';
import { reactResolver } from './react';
@@ -76,6 +77,19 @@ export function detectFrameworks(context: ResolutionContext): FrameworkResolver[
});
}
/**
* Filter a list of detected frameworks down to ones that apply to a given language.
* Frameworks without an explicit `languages` list are treated as universal.
*/
export function getApplicableFrameworks(
detected: FrameworkResolver[],
language: Language
): FrameworkResolver[] {
return detected.filter(
(fw) => !fw.languages || fw.languages.includes(language)
);
}
/**
* Register a custom framework resolver
*/
+37 -44
View File
@@ -6,9 +6,11 @@
import { Node } from '../../types';
import { FrameworkResolver, UnresolvedRef, ResolvedRef, ResolutionContext } from '../types';
import { stripCommentsForRegex } from '../strip-comments';
export const springResolver: FrameworkResolver = {
name: 'spring',
languages: ['java'],
detect(context: ResolutionContext): boolean {
// Check for pom.xml with Spring
@@ -116,63 +118,54 @@ export const springResolver: FrameworkResolver = {
return null;
},
extractNodes(filePath: string, content: string): Node[] {
extract(filePath, content) {
if (!filePath.endsWith('.java')) return { nodes: [], references: [] };
const nodes: Node[] = [];
const references: UnresolvedRef[] = [];
const now = Date.now();
const safe = stripCommentsForRegex(content, 'java');
// Extract REST endpoints
// @GetMapping("/path"), @PostMapping("/path"), etc.
const mappingPatterns = [
/@(Get|Post|Put|Patch|Delete|Request)Mapping\s*\(\s*(?:value\s*=\s*)?["']([^"']+)["']/g,
/@(Get|Post|Put|Patch|Delete|Request)Mapping\s*\(\s*(?:path\s*=\s*)?["']([^"']+)["']/g,
];
// @GetMapping("/path"), @PostMapping(value = "/path"), @RequestMapping("/path")
const mappingRegex = /@(GetMapping|PostMapping|PutMapping|PatchMapping|DeleteMapping|RequestMapping)\s*\(\s*(?:value\s*=\s*|path\s*=\s*)?["']([^"']+)["'][^)]*\)/g;
let match: RegExpExecArray | null;
while ((match = mappingRegex.exec(safe)) !== null) {
const [, mappingName, routePath] = match;
const line = safe.slice(0, match.index).split('\n').length;
const method =
mappingName === 'RequestMapping' ? 'ANY' : mappingName!.replace(/Mapping$/, '').toUpperCase();
for (const pattern of mappingPatterns) {
let match;
while ((match = pattern.exec(content)) !== null) {
const [, mappingType, path] = match;
const line = content.slice(0, match.index).split('\n').length;
const method = mappingType === 'Request' ? 'ANY' : mappingType!.toUpperCase();
nodes.push({
id: `route:${filePath}:${method}:${path}:${line}`,
kind: 'route',
name: `${method} ${path}`,
qualifiedName: `${filePath}::${method}:${path}`,
filePath,
startLine: line,
endLine: line,
startColumn: 0,
endColumn: match[0].length,
language: 'java',
updatedAt: now,
});
}
}
// Extract class-level @RequestMapping for base path
const baseMappingMatch = content.match(/@RequestMapping\s*\(\s*["']([^"']+)["']\s*\)/);
if (baseMappingMatch) {
const [, basePath] = baseMappingMatch;
const line = content.slice(0, baseMappingMatch.index).split('\n').length;
nodes.push({
id: `route:${filePath}:BASE:${basePath}:${line}`,
const routeNode: Node = {
id: `route:${filePath}:${line}:${method}:${routePath}`,
kind: 'route',
name: `BASE ${basePath}`,
qualifiedName: `${filePath}::BASE:${basePath}`,
name: `${method} ${routePath}`,
qualifiedName: `${filePath}::route:${routePath}`,
filePath,
startLine: line,
endLine: line,
startColumn: 0,
endColumn: baseMappingMatch[0].length,
endColumn: match[0].length,
language: 'java',
updatedAt: now,
});
};
nodes.push(routeNode);
// Look for the next public/private/protected method after the annotation
const tail = safe.slice(match.index + match[0].length);
const methodMatch = tail.match(/\b(?:public|private|protected)\s+[^;{]*?\s+(\w+)\s*\(/);
if (methodMatch) {
references.push({
fromNodeId: routeNode.id,
referenceName: methodMatch[1]!,
referenceKind: 'references',
line,
column: 0,
filePath,
language: 'java',
});
}
}
return nodes;
return { nodes, references };
},
};
+97 -43
View File
@@ -6,6 +6,7 @@
import { Node } from '../../types';
import { FrameworkResolver, UnresolvedRef, ResolvedRef, ResolutionContext } from '../types';
import { stripCommentsForRegex } from '../strip-comments';
/**
* Laravel facade mappings to underlying classes
@@ -36,6 +37,7 @@ export const FACADE_MAPPINGS: Record<string, string> = {
export const laravelResolver: FrameworkResolver = {
name: 'laravel',
languages: ['php'],
detect(context: ResolutionContext): boolean {
// Check for artisan file (Laravel signature)
@@ -90,63 +92,115 @@ export const laravelResolver: FrameworkResolver = {
return null;
},
extractNodes(filePath: string, content: string): Node[] {
extract(filePath, content) {
if (!filePath.endsWith('.php')) return { nodes: [], references: [] };
const nodes: Node[] = [];
const references: UnresolvedRef[] = [];
const now = Date.now();
const safe = stripCommentsForRegex(content, 'php');
// Extract route definitions
const routePatterns = [
// Route::get('/path', ...)
/Route::(get|post|put|patch|delete|options|any)\(\s*['"]([^'"]+)['"]/g,
// Route::resource('name', ...)
/Route::resource\(\s*['"]([^'"]+)['"]/g,
// Route::apiResource('name', ...)
/Route::apiResource\(\s*['"]([^'"]+)['"]/g,
];
// Route::METHOD('/path', handler-expr)
// handler-expr can be: [Class::class, 'method'] | 'Controller@method' | Closure | Class::class
const routeRegex = /Route::(get|post|put|patch|delete|options|any)\s*\(\s*['"]([^'"]+)['"]\s*,\s*([^)]+)\)/g;
let match: RegExpExecArray | null;
while ((match = routeRegex.exec(safe)) !== null) {
const [, method, routePath, handlerExpr] = match;
const line = safe.slice(0, match.index).split('\n').length;
const upper = method!.toUpperCase();
const routeNode: Node = {
id: `route:${filePath}:${line}:${upper}:${routePath}`,
kind: 'route',
name: `${upper} ${routePath}`,
qualifiedName: `${filePath}::route:${routePath}`,
filePath,
startLine: line,
endLine: line,
startColumn: 0,
endColumn: match[0].length,
language: 'php',
updatedAt: now,
};
nodes.push(routeNode);
for (const pattern of routePatterns) {
let match;
while ((match = pattern.exec(content)) !== null) {
if (pattern.source.includes('resource')) {
const [, resourceName] = match;
const line = content.slice(0, match.index).split('\n').length;
nodes.push({
id: `route:${filePath}:resource:${resourceName}:${line}`,
kind: 'route',
name: `resource:${resourceName}`,
qualifiedName: `${filePath}::resource:${resourceName}`,
const handlerName = extractLaravelHandler(handlerExpr!);
if (handlerName) {
references.push({
fromNodeId: routeNode.id,
referenceName: handlerName,
referenceKind: 'references',
line,
column: 0,
filePath,
language: 'php',
});
}
}
// Route::resource('name', Controller::class) / Route::apiResource('name', Controller::class)
const resourceRegex = /Route::(resource|apiResource)\s*\(\s*['"]([^'"]+)['"]\s*(?:,\s*([^)]+))?\)/g;
while ((match = resourceRegex.exec(safe)) !== null) {
const [, _fn, resourceName, handlerExpr] = match;
const line = safe.slice(0, match.index).split('\n').length;
const routeNode: Node = {
id: `route:${filePath}:${line}:RESOURCE:${resourceName}`,
kind: 'route',
name: `resource:${resourceName}`,
qualifiedName: `${filePath}::route:${resourceName}`,
filePath,
startLine: line,
endLine: line,
startColumn: 0,
endColumn: match[0].length,
language: 'php',
updatedAt: now,
};
nodes.push(routeNode);
if (handlerExpr) {
const controllerName = extractLaravelHandler(handlerExpr);
if (controllerName) {
references.push({
fromNodeId: routeNode.id,
referenceName: controllerName,
referenceKind: 'imports',
line,
column: 0,
filePath,
startLine: line,
endLine: line,
startColumn: 0,
endColumn: match[0].length,
language: 'php',
updatedAt: now,
});
} else {
const [, method, path] = match;
const line = content.slice(0, match.index).split('\n').length;
nodes.push({
id: `route:${filePath}:${method!.toUpperCase()}:${path}:${line}`,
kind: 'route',
name: `${method!.toUpperCase()} ${path}`,
qualifiedName: `${filePath}::${method!.toUpperCase()}:${path}`,
filePath,
startLine: line,
endLine: line,
startColumn: 0,
endColumn: match[0].length,
language: 'php',
updatedAt: now,
});
}
}
}
return nodes;
return { nodes, references };
},
};
/**
* Parse a Laravel route handler expression and return the symbol to link.
* - `[Class::class, 'method']` -> `method`
* - `'Controller@method'` -> `method`
* - `Class::class` -> `Class`
* - anything else (closure etc) -> null
*/
function extractLaravelHandler(expr: string): string | null {
const trimmed = expr.trim();
// [Class::class, 'method'] — grab the string literal
const tupleMatch = trimmed.match(/^\[\s*[^,]+,\s*['"]([^'"]+)['"]\s*\]/);
if (tupleMatch) return tupleMatch[1]!;
// 'Controller@method'
const atMatch = trimmed.match(/^['"]([^'"@]+)@([^'"]+)['"]$/);
if (atMatch) return atMatch[2]!;
// Controller::class
const classMatch = trimmed.match(/^([A-Za-z_][A-Za-z0-9_]*)::class/);
if (classMatch) return classMatch[1]!;
return null;
}
/**
* Resolve a Model::method() call
*/
+190 -207
View File
@@ -5,173 +5,62 @@
*/
import { Node } from '../../types';
import { FrameworkResolver, UnresolvedRef, ResolvedRef, ResolutionContext } from '../types';
import { FrameworkResolver, UnresolvedRef, ResolutionContext, FrameworkExtractionResult } from '../types';
import { stripCommentsForRegex } from '../strip-comments';
export const djangoResolver: FrameworkResolver = {
name: 'django',
languages: ['python'],
detect(context: ResolutionContext): boolean {
// Check for Django in requirements.txt or setup.py
detect(context) {
const requirements = context.readFile('requirements.txt');
if (requirements && requirements.includes('django')) {
return true;
}
if (requirements && requirements.toLowerCase().includes('django')) return true;
const setup = context.readFile('setup.py');
if (setup && setup.includes('django')) {
return true;
}
if (setup && setup.toLowerCase().includes('django')) return true;
const pyproject = context.readFile('pyproject.toml');
if (pyproject && pyproject.includes('django')) {
return true;
}
// Check for manage.py (Django signature)
if (pyproject && pyproject.toLowerCase().includes('django')) return true;
return context.fileExists('manage.py');
},
resolve(ref: UnresolvedRef, context: ResolutionContext): ResolvedRef | null {
// Pattern 1: Model references
resolve(ref, context) {
if (ref.referenceName.endsWith('Model') || /^[A-Z][a-z]+$/.test(ref.referenceName)) {
const result = resolveByNameAndKind(ref.referenceName, CLASS_KINDS, MODEL_DIRS, context);
if (result) {
return {
original: ref,
targetNodeId: result,
confidence: 0.8,
resolvedBy: 'framework',
};
}
if (result) return { original: ref, targetNodeId: result, confidence: 0.8, resolvedBy: 'framework' };
}
// Pattern 2: View references
if (ref.referenceName.endsWith('View') || ref.referenceName.endsWith('ViewSet')) {
const result = resolveByNameAndKind(ref.referenceName, VIEW_KINDS, VIEW_DIRS, context);
if (result) {
return {
original: ref,
targetNodeId: result,
confidence: 0.8,
resolvedBy: 'framework',
};
}
if (result) return { original: ref, targetNodeId: result, confidence: 0.8, resolvedBy: 'framework' };
}
// Pattern 3: Form references
if (ref.referenceName.endsWith('Form')) {
const result = resolveByNameAndKind(ref.referenceName, CLASS_KINDS, FORM_DIRS, context);
if (result) {
return {
original: ref,
targetNodeId: result,
confidence: 0.8,
resolvedBy: 'framework',
};
}
if (result) return { original: ref, targetNodeId: result, confidence: 0.8, resolvedBy: 'framework' };
}
return null;
},
extractNodes(filePath: string, content: string): Node[] {
extract(filePath, content) {
if (!filePath.endsWith('.py')) return { nodes: [], references: [] };
const nodes: Node[] = [];
const references: UnresolvedRef[] = [];
const now = Date.now();
const safe = stripCommentsForRegex(content, 'python');
// Extract URL patterns
// path('route/', view, name='name')
const urlPatterns = [
/path\s*\(\s*['"]([^'"]+)['"],\s*(\w+)/g,
/url\s*\(\s*r?['"]([^'"]+)['"],\s*(\w+)/g,
];
// path('url', handler, name=...) / re_path(r'...', handler) / url(r'...', handler)
// Capture groups: 1=function name, 2=url string, 3=handler expr
// Handler expr may contain one balanced () pair (e.g. View.as_view(), include('x.y'))
const routeRegex = /\b(path|re_path|url)\s*\(\s*r?['"]([^'"]+)['"]\s*,\s*([\w.]+(?:\s*\([^)]*\))?)/g;
for (const pattern of urlPatterns) {
let match;
while ((match = pattern.exec(content)) !== null) {
const [, urlPath] = match;
const line = content.slice(0, match.index).split('\n').length;
let match: RegExpExecArray | null;
while ((match = routeRegex.exec(safe)) !== null) {
const [, _fn, urlPath, handlerExpr] = match;
const line = safe.slice(0, match.index).split('\n').length;
nodes.push({
id: `route:${filePath}:${urlPath}:${line}`,
kind: 'route',
name: urlPath!,
qualifiedName: `${filePath}::route:${urlPath}`,
filePath,
startLine: line,
endLine: line,
startColumn: 0,
endColumn: match[0].length,
language: 'python',
updatedAt: now,
});
}
}
return nodes;
},
};
export const flaskResolver: FrameworkResolver = {
name: 'flask',
detect(context: ResolutionContext): boolean {
const requirements = context.readFile('requirements.txt');
if (requirements && (requirements.includes('flask') || requirements.includes('Flask'))) {
return true;
}
const pyproject = context.readFile('pyproject.toml');
if (pyproject && pyproject.includes('flask')) {
return true;
}
// Check for Flask app pattern in common files
const appFiles = ['app.py', 'application.py', 'main.py', '__init__.py'];
for (const file of appFiles) {
const content = context.readFile(file);
if (content && content.includes('Flask(__name__)')) {
return true;
}
}
return false;
},
resolve(ref: UnresolvedRef, context: ResolutionContext): ResolvedRef | null {
// Pattern 1: Blueprint references
if (ref.referenceName.endsWith('_bp') || ref.referenceName.endsWith('_blueprint')) {
const result = resolveByNameAndKind(ref.referenceName, VARIABLE_KINDS, [], context);
if (result) {
return {
original: ref,
targetNodeId: result,
confidence: 0.8,
resolvedBy: 'framework',
};
}
}
return null;
},
extractNodes(filePath: string, content: string): Node[] {
const nodes: Node[] = [];
const now = Date.now();
// Extract Flask route decorators
// @app.route('/path') or @blueprint.route('/path')
const routePattern = /@(\w+)\.route\s*\(\s*['"]([^'"]+)['"]/g;
let match;
while ((match = routePattern.exec(content)) !== null) {
const [, _appOrBp, routePath] = match;
const line = content.slice(0, match.index).split('\n').length;
nodes.push({
id: `route:${filePath}:${routePath}:${line}`,
const routeNode: Node = {
id: `route:${filePath}:${line}:${urlPath}`,
kind: 'route',
name: `${routePath}`,
qualifiedName: `${filePath}::route:${routePath}`,
name: urlPath!,
qualifiedName: `${filePath}::route:${urlPath}`,
filePath,
startLine: line,
endLine: line,
@@ -179,101 +68,195 @@ export const flaskResolver: FrameworkResolver = {
endColumn: match[0].length,
language: 'python',
updatedAt: now,
});
};
nodes.push(routeNode);
const handler = handlerExpr!.trim();
const target = resolveHandlerName(handler);
if (target) {
references.push({
fromNodeId: routeNode.id,
referenceName: target.name,
referenceKind: target.kind,
line,
column: 0,
filePath,
language: 'python',
});
}
}
return nodes;
return { nodes, references };
},
};
/**
* Parse a Django URL handler expression and return the symbol/module to link.
* Returns null for shapes we can't confidently link (e.g. lambdas).
*/
function resolveHandlerName(expr: string): { name: string; kind: 'references' | 'imports' } | null {
// include('module.path')
const includeMatch = expr.match(/^include\s*\(\s*['"]([^'"]+)['"]/);
if (includeMatch) return { name: includeMatch[1]!, kind: 'imports' };
// Strip trailing .as_view(...) or .as_view()
let head = expr.replace(/\.as_view\s*\([^)]*\)\s*$/, '');
// Drop any other trailing method call
head = head.replace(/\.\w+\s*\([^)]*\)\s*$/, '');
const dotted = head.split('.').filter(Boolean);
if (dotted.length === 0) return null;
const last = dotted[dotted.length - 1]!;
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(last)) return null;
return { name: last, kind: 'references' };
}
export const flaskResolver: FrameworkResolver = {
name: 'flask',
languages: ['python'],
detect(context) {
const requirements = context.readFile('requirements.txt');
if (requirements && /\bflask\b/i.test(requirements)) return true;
const pyproject = context.readFile('pyproject.toml');
if (pyproject && /\bflask\b/i.test(pyproject)) return true;
for (const file of ['app.py', 'application.py', 'main.py', '__init__.py']) {
const content = context.readFile(file);
if (content && content.includes('Flask(__name__)')) return true;
}
return false;
},
resolve(ref, context) {
if (ref.referenceName.endsWith('_bp') || ref.referenceName.endsWith('_blueprint')) {
const result = resolveByNameAndKind(ref.referenceName, VARIABLE_KINDS, [], context);
if (result) return { original: ref, targetNodeId: result, confidence: 0.8, resolvedBy: 'framework' };
}
return null;
},
extract(filePath, content) {
if (!filePath.endsWith('.py')) return { nodes: [], references: [] };
return extractDecoratorRoutes(filePath, stripCommentsForRegex(content, 'python'), {
// Flask: @x.route('/path', methods=[...])
decoratorRegex: /@(\w+)\.route\s*\(\s*['"]([^'"]+)['"](?:\s*,\s*methods\s*=\s*\[([^\]]+)\])?\s*\)\s*\n\s*(?:async\s+)?def\s+(\w+)/g,
defaultMethod: 'GET',
methodFromGroup: 3,
pathGroup: 2,
handlerGroup: 4,
language: 'python',
});
},
};
export const fastapiResolver: FrameworkResolver = {
name: 'fastapi',
languages: ['python'],
detect(context: ResolutionContext): boolean {
detect(context) {
const requirements = context.readFile('requirements.txt');
if (requirements && requirements.includes('fastapi')) {
return true;
}
if (requirements && /\bfastapi\b/i.test(requirements)) return true;
const pyproject = context.readFile('pyproject.toml');
if (pyproject && pyproject.includes('fastapi')) {
return true;
}
// Check for FastAPI app pattern
const appFiles = ['app.py', 'main.py', 'api.py'];
for (const file of appFiles) {
if (pyproject && /\bfastapi\b/i.test(pyproject)) return true;
for (const file of ['app.py', 'main.py', 'api.py']) {
const content = context.readFile(file);
if (content && content.includes('FastAPI()')) {
return true;
}
if (content && content.includes('FastAPI(')) return true;
}
return false;
},
resolve(ref: UnresolvedRef, context: ResolutionContext): ResolvedRef | null {
// Pattern 1: Router references
resolve(ref, context) {
if (ref.referenceName.endsWith('_router') || ref.referenceName === 'router') {
const result = resolveByNameAndKind(ref.referenceName, VARIABLE_KINDS, ROUTER_DIRS, context);
if (result) {
return {
original: ref,
targetNodeId: result,
confidence: 0.8,
resolvedBy: 'framework',
};
}
if (result) return { original: ref, targetNodeId: result, confidence: 0.8, resolvedBy: 'framework' };
}
// Pattern 2: Dependency references
if (ref.referenceName.startsWith('get_') || ref.referenceName.startsWith('Depends')) {
const result = resolveByNameAndKind(ref.referenceName, FUNCTION_KINDS, DEP_DIRS, context);
if (result) {
return {
original: ref,
targetNodeId: result,
confidence: 0.75,
resolvedBy: 'framework',
};
}
if (result) return { original: ref, targetNodeId: result, confidence: 0.75, resolvedBy: 'framework' };
}
return null;
},
extractNodes(filePath: string, content: string): Node[] {
const nodes: Node[] = [];
const now = Date.now();
// Extract FastAPI route decorators
// @app.get('/path') or @router.post('/path')
const routePattern = /@(\w+)\.(get|post|put|patch|delete|options|head)\s*\(\s*['"]([^'"]+)['"]/g;
let match;
while ((match = routePattern.exec(content)) !== null) {
const [, _appOrRouter, method, routePath] = match;
const line = content.slice(0, match.index).split('\n').length;
nodes.push({
id: `route:${filePath}:${method!.toUpperCase()}:${routePath}:${line}`,
kind: 'route',
name: `${method!.toUpperCase()} ${routePath}`,
qualifiedName: `${filePath}::${method!.toUpperCase()}:${routePath}`,
filePath,
startLine: line,
endLine: line,
startColumn: 0,
endColumn: match[0].length,
language: 'python',
updatedAt: now,
});
}
return nodes;
extract(filePath, content) {
if (!filePath.endsWith('.py')) return { nodes: [], references: [] };
return extractDecoratorRoutes(filePath, stripCommentsForRegex(content, 'python'), {
// FastAPI: @x.METHOD('/path') -> handler on the next def line
decoratorRegex: /@(\w+)\.(get|post|put|patch|delete|options|head)\s*\(\s*['"]([^'"]+)['"]/g,
defaultMethod: '',
methodGroup: 2,
pathGroup: 3,
findHandler: true,
language: 'python',
});
},
};
interface DecoratorRouteOpts {
decoratorRegex: RegExp;
defaultMethod: string;
methodGroup?: number;
methodFromGroup?: number; // methods=[...] list
pathGroup: number;
handlerGroup?: number;
findHandler?: boolean;
language: 'python';
}
function extractDecoratorRoutes(filePath: string, content: string, opts: DecoratorRouteOpts): FrameworkExtractionResult {
const nodes: Node[] = [];
const references: UnresolvedRef[] = [];
const now = Date.now();
let match: RegExpExecArray | null;
while ((match = opts.decoratorRegex.exec(content)) !== null) {
const routePath = match[opts.pathGroup];
let method = opts.defaultMethod;
if (opts.methodGroup && match[opts.methodGroup]) {
method = match[opts.methodGroup]!.toUpperCase();
} else if (opts.methodFromGroup && match[opts.methodFromGroup]) {
const m = match[opts.methodFromGroup]!.match(/['"]([A-Z]+)['"]/i);
if (m) method = m[1]!.toUpperCase();
}
const line = content.slice(0, match.index).split('\n').length;
const name = method ? `${method} ${routePath}` : routePath!;
const routeNode: Node = {
id: `route:${filePath}:${line}:${method}:${routePath}`,
kind: 'route',
name,
qualifiedName: `${filePath}::${method}:${routePath}`,
filePath,
startLine: line,
endLine: line,
startColumn: 0,
endColumn: match[0].length,
language: opts.language,
updatedAt: now,
};
nodes.push(routeNode);
let handlerName: string | undefined;
if (opts.handlerGroup && match[opts.handlerGroup]) {
handlerName = match[opts.handlerGroup];
} else if (opts.findHandler) {
const tail = content.slice(match.index + match[0].length);
const defMatch = tail.match(/\n\s*(?:async\s+)?def\s+(\w+)/);
if (defMatch) handlerName = defMatch[1];
}
if (handlerName) {
references.push({
fromNodeId: routeNode.id,
referenceName: handlerName,
referenceKind: 'references',
line,
column: 0,
filePath,
language: 'python',
});
}
}
return { nodes, references };
}
// Directory patterns
const MODEL_DIRS = ['models', 'app/models', 'src/models'];
const VIEW_DIRS = ['views', 'app/views', 'src/views', 'api/views'];
+3 -2
View File
@@ -9,6 +9,7 @@ import { FrameworkResolver, UnresolvedRef, ResolvedRef, ResolutionContext } from
export const reactResolver: FrameworkResolver = {
name: 'react',
languages: ['javascript', 'typescript'],
detect(context: ResolutionContext): boolean {
// Check for React in package.json
@@ -73,7 +74,7 @@ export const reactResolver: FrameworkResolver = {
return null;
},
extractNodes(filePath: string, content: string): Node[] {
extract(filePath, content) {
const nodes: Node[] = [];
const now = Date.now();
@@ -168,7 +169,7 @@ export const reactResolver: FrameworkResolver = {
}
}
return nodes;
return { nodes, references: [] };
},
};
+38 -92
View File
@@ -6,9 +6,11 @@
import { Node } from '../../types';
import { FrameworkResolver, UnresolvedRef, ResolvedRef, ResolutionContext } from '../types';
import { stripCommentsForRegex } from '../strip-comments';
export const railsResolver: FrameworkResolver = {
name: 'rails',
languages: ['ruby'],
detect(context: ResolutionContext): boolean {
// Check for Gemfile with rails
@@ -85,104 +87,48 @@ export const railsResolver: FrameworkResolver = {
return null;
},
extractNodes(filePath: string, content: string): Node[] {
extract(filePath, content) {
if (!filePath.endsWith('.rb')) return { nodes: [], references: [] };
const nodes: Node[] = [];
const references: UnresolvedRef[] = [];
const now = Date.now();
const safe = stripCommentsForRegex(content, 'ruby');
// Extract route definitions from config/routes.rb
if (filePath.includes('routes.rb')) {
// get/post/put/patch/delete 'path'
const routePatterns = [
/(get|post|put|patch|delete)\s+['"]([^'"]+)['"]/g,
/resources?\s+:(\w+)/g,
/root\s+['"]([^'"]+)['"]/g,
/root\s+to:\s*['"]([^'"]+)['"]/g,
];
// get/post/put/patch/delete/match '/path', to: 'controller#action'
// Also: get '/path' => 'controller#action'
const routeRegex = /\b(get|post|put|patch|delete|match)\s+['"]([^'"]+)['"]\s*(?:,\s*to:\s*|=>\s*)['"]([^#'"]+)#([^'"]+)['"]/g;
let match: RegExpExecArray | null;
while ((match = routeRegex.exec(safe)) !== null) {
const [, method, routePath, _controller, action] = match;
const line = safe.slice(0, match.index).split('\n').length;
const upper = method!.toUpperCase();
const routeNode: Node = {
id: `route:${filePath}:${line}:${upper}:${routePath}`,
kind: 'route',
name: `${upper} ${routePath}`,
qualifiedName: `${filePath}::route:${routePath}`,
filePath,
startLine: line,
endLine: line,
startColumn: 0,
endColumn: match[0].length,
language: 'ruby',
updatedAt: now,
};
nodes.push(routeNode);
for (const pattern of routePatterns) {
let match;
while ((match = pattern.exec(content)) !== null) {
const line = content.slice(0, match.index).split('\n').length;
if (pattern.source.includes('resources')) {
const [, resourceName] = match;
nodes.push({
id: `route:${filePath}:resource:${resourceName}:${line}`,
kind: 'route',
name: `resource:${resourceName}`,
qualifiedName: `${filePath}::resource:${resourceName}`,
filePath,
startLine: line,
endLine: line,
startColumn: 0,
endColumn: match[0].length,
language: 'ruby',
updatedAt: now,
});
} else if (pattern.source.includes('root')) {
const [, target] = match;
nodes.push({
id: `route:${filePath}:root:${line}`,
kind: 'route',
name: `/ -> ${target}`,
qualifiedName: `${filePath}::root`,
filePath,
startLine: line,
endLine: line,
startColumn: 0,
endColumn: match[0].length,
language: 'ruby',
updatedAt: now,
});
} else {
const [, method, path] = match;
nodes.push({
id: `route:${filePath}:${method!.toUpperCase()}:${path}:${line}`,
kind: 'route',
name: `${method!.toUpperCase()} ${path}`,
qualifiedName: `${filePath}::${method!.toUpperCase()}:${path}`,
filePath,
startLine: line,
endLine: line,
startColumn: 0,
endColumn: match[0].length,
language: 'ruby',
updatedAt: now,
});
}
}
}
references.push({
fromNodeId: routeNode.id,
referenceName: action!,
referenceKind: 'references',
line,
column: 0,
filePath,
language: 'ruby',
});
}
// Extract controller actions
if (filePath.includes('controllers/') && filePath.endsWith('.rb')) {
const actionPattern = /def\s+(\w+)/g;
let match;
while ((match = actionPattern.exec(content)) !== null) {
const [, actionName] = match;
const line = content.slice(0, match.index).split('\n').length;
// Skip private methods and common Rails callbacks
const privateMethods = ['initialize', 'set_', 'before_', 'after_'];
if (!privateMethods.some((p) => actionName!.startsWith(p))) {
nodes.push({
id: `action:${filePath}:${actionName}:${line}`,
kind: 'method',
name: actionName!,
qualifiedName: `${filePath}::${actionName}`,
filePath,
startLine: line,
endLine: line,
startColumn: 0,
endColumn: match[0].length,
language: 'ruby',
updatedAt: now,
});
}
}
}
return nodes;
return { nodes, references };
},
};
+51 -48
View File
@@ -6,9 +6,11 @@
import { Node } from '../../types';
import { FrameworkResolver, UnresolvedRef, ResolvedRef, ResolutionContext } from '../types';
import { stripCommentsForRegex } from '../strip-comments';
export const rustResolver: FrameworkResolver = {
name: 'rust',
languages: ['rust'],
detect(context: ResolutionContext): boolean {
// Check for Cargo.toml (Rust project signature)
@@ -71,24 +73,27 @@ export const rustResolver: FrameworkResolver = {
return null;
},
extractNodes(filePath: string, content: string): Node[] {
extract(filePath, content) {
if (!filePath.endsWith('.rs')) return { nodes: [], references: [] };
const nodes: Node[] = [];
const references: UnresolvedRef[] = [];
const now = Date.now();
const safe = stripCommentsForRegex(content, 'rust');
// Extract Actix-web routes
// #[get("/path")], #[post("/path")], etc.
const actixRoutePattern = /#\[(get|post|put|patch|delete)\s*\(\s*["']([^"']+)["']/g;
// Actix-web / Rocket attribute: #[get("/path")] fn handler(..)
// Capture the method, path, and the fn identifier that follows.
const attrRegex = /#\[(get|post|put|patch|delete|head|options)\s*\(\s*["']([^"']+)["'][^\]]*\)\]/g;
let match: RegExpExecArray | null;
while ((match = attrRegex.exec(safe)) !== null) {
const [, method, routePath] = match;
const line = safe.slice(0, match.index).split('\n').length;
const upper = method!.toUpperCase();
let match;
while ((match = actixRoutePattern.exec(content)) !== null) {
const [, method, path] = match;
const line = content.slice(0, match.index).split('\n').length;
nodes.push({
id: `route:${filePath}:${method!.toUpperCase()}:${path}:${line}`,
const routeNode: Node = {
id: `route:${filePath}:${line}:${upper}:${routePath}`,
kind: 'route',
name: `${method!.toUpperCase()} ${path}`,
qualifiedName: `${filePath}::${method!.toUpperCase()}:${path}`,
name: `${upper} ${routePath}`,
qualifiedName: `${filePath}::route:${routePath}`,
filePath,
startLine: line,
endLine: line,
@@ -96,49 +101,36 @@ export const rustResolver: FrameworkResolver = {
endColumn: match[0].length,
language: 'rust',
updatedAt: now,
});
}
};
nodes.push(routeNode);
// Extract Rocket routes
// #[get("/path")], #[post("/path", ...)]
const rocketRoutePattern = /#\[(get|post|put|patch|delete|head|options)\s*\(\s*["']([^"']+)["']/g;
while ((match = rocketRoutePattern.exec(content)) !== null) {
const [, method, path] = match;
const line = content.slice(0, match.index).split('\n').length;
// Avoid duplicates from actix pattern
const routeId = `route:${filePath}:${method!.toUpperCase()}:${path}:${line}`;
if (!nodes.some((n) => n.id === routeId)) {
nodes.push({
id: routeId,
kind: 'route',
name: `${method!.toUpperCase()} ${path}`,
qualifiedName: `${filePath}::${method!.toUpperCase()}:${path}`,
const tail = safe.slice(match.index + match[0].length);
const fnMatch = tail.match(/\n\s*(?:pub\s+)?(?:async\s+)?fn\s+(\w+)/);
if (fnMatch) {
references.push({
fromNodeId: routeNode.id,
referenceName: fnMatch[1]!,
referenceKind: 'references',
line,
column: 0,
filePath,
startLine: line,
endLine: line,
startColumn: 0,
endColumn: match[0].length,
language: 'rust',
updatedAt: now,
});
}
}
// Extract Axum routes (method chaining style)
// .route("/path", get(handler))
const axumRoutePattern = /\.route\s*\(\s*["']([^"']+)["']\s*,\s*(get|post|put|patch|delete)/g;
// Axum: .route("/path", get(handler))
const axumRegex = /\.route\s*\(\s*"([^"]+)"\s*,\s*(get|post|put|patch|delete)\s*\(\s*(\w+)/g;
while ((match = axumRegex.exec(safe)) !== null) {
const [, routePath, method, handler] = match;
const line = safe.slice(0, match.index).split('\n').length;
const upper = method!.toUpperCase();
while ((match = axumRoutePattern.exec(content)) !== null) {
const [, path, method] = match;
const line = content.slice(0, match.index).split('\n').length;
nodes.push({
id: `route:${filePath}:${method!.toUpperCase()}:${path}:${line}`,
const routeNode: Node = {
id: `route:${filePath}:${line}:${upper}:${routePath}`,
kind: 'route',
name: `${method!.toUpperCase()} ${path}`,
qualifiedName: `${filePath}::${method!.toUpperCase()}:${path}`,
name: `${upper} ${routePath}`,
qualifiedName: `${filePath}::route:${routePath}`,
filePath,
startLine: line,
endLine: line,
@@ -146,10 +138,21 @@ export const rustResolver: FrameworkResolver = {
endColumn: match[0].length,
language: 'rust',
updatedAt: now,
};
nodes.push(routeNode);
references.push({
fromNodeId: routeNode.id,
referenceName: handler!,
referenceKind: 'references',
line,
column: 0,
filePath,
language: 'rust',
});
}
return nodes;
return { nodes, references };
},
};
+3 -2
View File
@@ -44,6 +44,7 @@ const SVELTEKIT_MODULE_PREFIXES = [
export const svelteResolver: FrameworkResolver = {
name: 'svelte',
languages: ['svelte'],
detect(context: ResolutionContext): boolean {
// Check for svelte or @sveltejs/kit in package.json
@@ -144,7 +145,7 @@ export const svelteResolver: FrameworkResolver = {
return null;
},
extractNodes(filePath: string, _content: string): Node[] {
extract(filePath, _content) {
const nodes: Node[] = [];
const now = Date.now();
@@ -174,7 +175,7 @@ export const svelteResolver: FrameworkResolver = {
}
}
return nodes;
return { nodes, references: [] };
},
};
+55 -53
View File
@@ -6,9 +6,11 @@
import { Node } from '../../types';
import { FrameworkResolver, UnresolvedRef, ResolvedRef, ResolutionContext } from '../types';
import { stripCommentsForRegex } from '../strip-comments';
export const swiftUIResolver: FrameworkResolver = {
name: 'swiftui',
languages: ['swift'],
detect(context: ResolutionContext): boolean {
// Check for SwiftUI imports in Swift files
@@ -75,18 +77,20 @@ export const swiftUIResolver: FrameworkResolver = {
return null;
},
extractNodes(filePath: string, content: string): Node[] {
extract(filePath, content) {
if (!filePath.endsWith('.swift')) return { nodes: [], references: [] };
const nodes: Node[] = [];
const now = Date.now();
const safe = stripCommentsForRegex(content, 'swift');
// Extract SwiftUI View structs
// struct ContentView: View { ... }
const viewPattern = /struct\s+(\w+)\s*:\s*(?:\w+\s*,\s*)*View/g;
let match;
while ((match = viewPattern.exec(content)) !== null) {
let match: RegExpExecArray | null;
while ((match = viewPattern.exec(safe)) !== null) {
const [, viewName] = match;
const line = content.slice(0, match.index).split('\n').length;
const line = safe.slice(0, match.index).split('\n').length;
nodes.push({
id: `view:${filePath}:${viewName}:${line}`,
@@ -106,9 +110,9 @@ export const swiftUIResolver: FrameworkResolver = {
// Extract @main App entry point
const appPattern = /@main\s+struct\s+(\w+)\s*:\s*App/g;
while ((match = appPattern.exec(content)) !== null) {
while ((match = appPattern.exec(safe)) !== null) {
const [, appName] = match;
const line = content.slice(0, match.index).split('\n').length;
const line = safe.slice(0, match.index).split('\n').length;
nodes.push({
id: `app:${filePath}:${appName}:${line}`,
@@ -125,12 +129,13 @@ export const swiftUIResolver: FrameworkResolver = {
});
}
return nodes;
return { nodes, references: [] };
},
};
export const uikitResolver: FrameworkResolver = {
name: 'uikit',
languages: ['swift'],
detect(context: ResolutionContext): boolean {
const allFiles = context.getAllFiles();
@@ -206,17 +211,19 @@ export const uikitResolver: FrameworkResolver = {
return null;
},
extractNodes(filePath: string, content: string): Node[] {
extract(filePath, content) {
if (!filePath.endsWith('.swift')) return { nodes: [], references: [] };
const nodes: Node[] = [];
const now = Date.now();
const safe = stripCommentsForRegex(content, 'swift');
// Extract UIViewController subclasses
const vcPattern = /class\s+(\w+)\s*:\s*(?:\w+\s*,\s*)*UIViewController/g;
let match;
while ((match = vcPattern.exec(content)) !== null) {
let match: RegExpExecArray | null;
while ((match = vcPattern.exec(safe)) !== null) {
const [, vcName] = match;
const line = content.slice(0, match.index).split('\n').length;
const line = safe.slice(0, match.index).split('\n').length;
nodes.push({
id: `viewcontroller:${filePath}:${vcName}:${line}`,
@@ -236,9 +243,9 @@ export const uikitResolver: FrameworkResolver = {
// Extract UIView subclasses
const viewPattern = /class\s+(\w+)\s*:\s*(?:\w+\s*,\s*)*UIView[^C]/g;
while ((match = viewPattern.exec(content)) !== null) {
while ((match = viewPattern.exec(safe)) !== null) {
const [, viewName] = match;
const line = content.slice(0, match.index).split('\n').length;
const line = safe.slice(0, match.index).split('\n').length;
nodes.push({
id: `uiview:${filePath}:${viewName}:${line}`,
@@ -255,12 +262,13 @@ export const uikitResolver: FrameworkResolver = {
});
}
return nodes;
return { nodes, references: [] };
},
};
export const vaporResolver: FrameworkResolver = {
name: 'vapor',
languages: ['swift'],
detect(context: ResolutionContext): boolean {
// Check for Package.swift with Vapor dependency
@@ -326,24 +334,26 @@ export const vaporResolver: FrameworkResolver = {
return null;
},
extractNodes(filePath: string, content: string): Node[] {
extract(filePath, content) {
if (!filePath.endsWith('.swift')) return { nodes: [], references: [] };
const nodes: Node[] = [];
const references: UnresolvedRef[] = [];
const now = Date.now();
const safe = stripCommentsForRegex(content, 'swift');
// Extract Vapor routes
// app.get("path") { ... }, app.post("path") { ... }
const routePattern = /\.(get|post|put|patch|delete)\s*\(\s*["']([^"']+)["']/g;
// Vapor: (app|router|routes).METHOD("path", use: handler)
const routeRegex = /\b(?:app|router|routes)\.(get|post|put|patch|delete)\s*\(\s*"([^"]+)"\s*,\s*use:\s*([A-Za-z_][A-Za-z0-9_.]*)/g;
let match: RegExpExecArray | null;
while ((match = routeRegex.exec(safe)) !== null) {
const [, method, routePath, handlerExpr] = match;
const line = safe.slice(0, match.index).split('\n').length;
const upper = method!.toUpperCase();
let match;
while ((match = routePattern.exec(content)) !== null) {
const [, method, path] = match;
const line = content.slice(0, match.index).split('\n').length;
nodes.push({
id: `route:${filePath}:${method!.toUpperCase()}:${path}:${line}`,
const routeNode: Node = {
id: `route:${filePath}:${line}:${upper}:${routePath}`,
kind: 'route',
name: `${method!.toUpperCase()} ${path}`,
qualifiedName: `${filePath}::${method!.toUpperCase()}:${path}`,
name: `${upper} ${routePath}`,
qualifiedName: `${filePath}::route:${routePath}`,
filePath,
startLine: line,
endLine: line,
@@ -351,34 +361,26 @@ export const vaporResolver: FrameworkResolver = {
endColumn: match[0].length,
language: 'swift',
updatedAt: now,
});
};
nodes.push(routeNode);
// Last segment of dotted path (e.g. UserController.list -> list)
const parts = handlerExpr!.split('.');
const handlerName = parts[parts.length - 1];
if (handlerName) {
references.push({
fromNodeId: routeNode.id,
referenceName: handlerName,
referenceKind: 'references',
line,
column: 0,
filePath,
language: 'swift',
});
}
}
// Extract grouped routes
// app.grouped("api").get("users") { ... }
const groupedRoutePattern = /\.grouped\s*\(\s*["']([^"']+)["']\s*\)\s*\.(get|post|put|patch|delete)\s*\(\s*["']([^"']+)["']/g;
while ((match = groupedRoutePattern.exec(content)) !== null) {
const [, prefix, method, path] = match;
const line = content.slice(0, match.index).split('\n').length;
const fullPath = `${prefix}/${path}`;
nodes.push({
id: `route:${filePath}:${method!.toUpperCase()}:${fullPath}:${line}`,
kind: 'route',
name: `${method!.toUpperCase()} /${fullPath}`,
qualifiedName: `${filePath}::${method!.toUpperCase()}:${fullPath}`,
filePath,
startLine: line,
endLine: line,
startColumn: 0,
endColumn: match[0].length,
language: 'swift',
updatedAt: now,
});
}
return nodes;
return { nodes, references };
},
};
+2 -2
View File
@@ -187,7 +187,7 @@ export const vueResolver: FrameworkResolver = {
return null;
},
extractNodes(filePath: string, _content: string): Node[] {
extract(filePath: string, _content: string) {
const nodes: Node[] = [];
const now = Date.now();
@@ -260,7 +260,7 @@ export const vueResolver: FrameworkResolver = {
});
}
return nodes;
return { nodes, references: [] };
},
};