@dimassetoid/septum-mcp 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (129) hide show
  1. package/README.md +38 -55
  2. package/package.json +7 -5
  3. package/src/cli/commands/check.ts +14 -10
  4. package/src/cli/commands/hook.ts +41 -6
  5. package/src/cli/commands/init.ts +10 -1
  6. package/src/cli/commands/stats.ts +33 -0
  7. package/src/cli/commands/sync-progress.ts +71 -0
  8. package/src/cli/commands/sync.ts +32 -4
  9. package/src/cli/index.ts +7 -0
  10. package/src/cli/templates/hooks.ts +3 -14
  11. package/src/cli/templates/skill.ts +17 -10
  12. package/src/core/boundary/audit.ts +383 -0
  13. package/src/core/boundary/evaluator.ts +251 -114
  14. package/src/core/boundary/staged-auditor.ts +147 -55
  15. package/src/core/config/domain-ownership.ts +6 -4
  16. package/src/core/config/domain-registration.ts +141 -0
  17. package/src/core/config/loader.ts +1 -25
  18. package/src/core/config/schema.ts +24 -36
  19. package/src/core/database/client.ts +2 -0
  20. package/src/core/database/repositories/dependency.repository.ts +334 -572
  21. package/src/core/database/repositories/domain.repository.ts +2 -1
  22. package/src/core/database/repositories/file.repository.ts +10 -0
  23. package/src/core/database/repositories/symbol.repository.ts +97 -398
  24. package/src/core/database/repository.ts +68 -9
  25. package/src/core/database/schema.ts +26 -0
  26. package/src/core/discovery/declarative-routes.ts +69 -0
  27. package/src/core/discovery/framework-detector.ts +149 -0
  28. package/src/core/discovery/navigation.ts +222 -58
  29. package/src/core/discovery/topology-detector.ts +93 -168
  30. package/src/core/errors.ts +19 -0
  31. package/src/core/ingestion/pipeline.ts +287 -88
  32. package/src/core/parser/extractors/base.ts +11 -3
  33. package/src/core/parser/extractors/csharp.ts +2 -2
  34. package/src/core/parser/extractors/django-routing.ts +163 -0
  35. package/src/core/parser/extractors/django-semantic.ts +397 -481
  36. package/src/core/parser/extractors/elysia-semantic.ts +172 -475
  37. package/src/core/parser/extractors/express-semantic.ts +195 -383
  38. package/src/core/parser/extractors/fastapi-semantic.ts +178 -361
  39. package/src/core/parser/extractors/fastify-semantic.ts +216 -717
  40. package/src/core/parser/extractors/flask-semantic.ts +89 -352
  41. package/src/core/parser/extractors/go-routing.ts +344 -0
  42. package/src/core/parser/extractors/go-semantic.ts +205 -562
  43. package/src/core/parser/extractors/go.ts +6 -3
  44. package/src/core/parser/extractors/graphql-entrypoint.ts +146 -0
  45. package/src/core/parser/extractors/hono-semantic.ts +132 -509
  46. package/src/core/parser/extractors/java.ts +2 -2
  47. package/src/core/parser/extractors/laravel-routing.ts +263 -0
  48. package/src/core/parser/extractors/laravel-semantic.ts +143 -335
  49. package/src/core/parser/extractors/manifest-helpers.ts +64 -0
  50. package/src/core/parser/extractors/mcp-cli-dispatch.ts +268 -0
  51. package/src/core/parser/extractors/mcp-cli-semantic.ts +82 -333
  52. package/src/core/parser/extractors/nestjs-semantic.ts +238 -494
  53. package/src/core/parser/extractors/nextjs-semantic.ts +164 -0
  54. package/src/core/parser/extractors/php-ast-helpers.ts +51 -0
  55. package/src/core/parser/extractors/php.ts +1 -1
  56. package/src/core/parser/extractors/python-route-ast.ts +249 -0
  57. package/src/core/parser/extractors/python.ts +5 -9
  58. package/src/core/parser/extractors/registry.ts +2 -0
  59. package/src/core/parser/extractors/route-prefixes.ts +43 -0
  60. package/src/core/parser/extractors/ruby.ts +2 -2
  61. package/src/core/parser/extractors/rust.ts +4 -4
  62. package/src/core/parser/extractors/symfony-routing.ts +114 -0
  63. package/src/core/parser/extractors/symfony-semantic.ts +72 -226
  64. package/src/core/parser/extractors/typescript-bindings.ts +333 -0
  65. package/src/core/parser/extractors/typescript-compiler-fallback.ts +380 -0
  66. package/src/core/parser/extractors/typescript-fallback.ts +207 -0
  67. package/src/core/parser/extractors/typescript-route-context.ts +58 -0
  68. package/src/core/parser/extractors/typescript.ts +23 -216
  69. package/src/core/parser/language-capabilities.ts +1 -1
  70. package/src/core/parser/schema/providers/laravel-migration-provider.ts +4 -1
  71. package/src/core/parser/wasm-loader.ts +6 -2
  72. package/src/core/resolver/ast-method-tracer.ts +230 -0
  73. package/src/core/resolver/call-graph-helpers.ts +72 -0
  74. package/src/core/resolver/call-graph-tracer.ts +169 -414
  75. package/src/core/resolver/dependency-analysis.ts +593 -0
  76. package/src/core/resolver/import-candidates.ts +120 -0
  77. package/src/core/resolver/import-evidence.ts +88 -0
  78. package/src/core/resolver/import-resolver.ts +60 -7
  79. package/src/core/resolver/interpretation-inputs.ts +60 -2
  80. package/src/core/resolver/languages/python.ts +31 -13
  81. package/src/core/resolver/languages/shared.ts +4 -1
  82. package/src/core/resolver/module-resolver.ts +10 -3
  83. package/src/core/resolver/path-resolver.ts +6 -3
  84. package/src/core/resolver/polyglot-slice-tracer.ts +197 -0
  85. package/src/core/resolver/slice-catalog.ts +21 -6
  86. package/src/core/resolver/slice-format.ts +13 -0
  87. package/src/core/resolver/slice-selection.ts +237 -0
  88. package/src/core/resolver/symbol-impact.ts +104 -8
  89. package/src/core/resolver/symbol-locator.ts +82 -15
  90. package/src/core/resolver/vertical-slice-tracer.ts +31 -230
  91. package/src/core/resources/ignore.ts +0 -1
  92. package/src/core/resources/limits.ts +2 -1
  93. package/src/core/resources/work-queue.ts +167 -4
  94. package/src/core/retrieval/context-page.ts +11 -4
  95. package/src/core/retrieval/context.ts +363 -226
  96. package/src/{mcp/tools/get-symbol.ts → core/retrieval/source-context.ts} +145 -96
  97. package/src/core/retrieval/symbol-details.ts +453 -0
  98. package/src/core/retrieval/symbol-evidence.ts +3 -3
  99. package/src/core/retrieval/typescript-references.ts +38 -7
  100. package/src/core/retrieval/universal-context.ts +182 -0
  101. package/src/core/telemetry/summary.ts +114 -0
  102. package/src/core/telemetry/telemetry.ts +192 -49
  103. package/src/mcp/formatters/compact-text.ts +439 -0
  104. package/src/mcp/resources-and-prompts.ts +253 -0
  105. package/src/mcp/schemas/boundary.ts +145 -0
  106. package/src/mcp/schemas/map.ts +250 -0
  107. package/src/mcp/schemas/shared.ts +52 -0
  108. package/src/mcp/schemas/slice.ts +60 -0
  109. package/src/mcp/schemas/symbol.ts +268 -0
  110. package/src/mcp/schemas.ts +5 -746
  111. package/src/mcp/server.ts +269 -429
  112. package/src/mcp/tool-catalog.ts +331 -0
  113. package/src/mcp/tools/boundary.ts +68 -3
  114. package/src/mcp/tools/map.ts +104 -4
  115. package/src/mcp/tools/slice.ts +101 -3
  116. package/src/mcp/tools/symbol.ts +469 -17
  117. package/src/mcp/ui/app-client.ts +899 -0
  118. package/src/mcp/ui/app.html +478 -0
  119. package/src/mcp/workflow-playbooks.ts +181 -0
  120. package/src/mcp/workspace-boundary.ts +50 -0
  121. package/src/mcp/workspace-manager.ts +88 -15
  122. package/src/mcp/workspace-watcher.ts +30 -11
  123. package/src/types/index.ts +12 -0
  124. package/src/mcp/tools/check-boundary.ts +0 -382
  125. package/src/mcp/tools/get-domain-catalog.ts +0 -39
  126. package/src/mcp/tools/get-symbol-impact.ts +0 -104
  127. package/src/mcp/tools/locate-symbol.ts +0 -236
  128. package/src/mcp/tools/register-domain.ts +0 -113
  129. package/src/mcp/tools/trace-vertical-slice.ts +0 -106
@@ -0,0 +1,164 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import ts from "typescript";
4
+ import type { ExecutionChainNode } from "../../../types/index.ts";
5
+ import { probeSourcePath, readOptionalSourceFile } from "../../resources/source-files.ts";
6
+ import { listSourceFiles, type SourceInventory } from "../../resources/source-inventory.ts";
7
+ import type { SemanticSliceExtractor, VerticalSliceCandidate } from "./semantic-extractor.interface.ts";
8
+ import { lineOf, TypeScriptBindings } from "./typescript-bindings.ts";
9
+
10
+ const NEXTJS_HTTP_METHODS = new Set(["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "HEAD"]);
11
+
12
+ /** Converts an App Router `.../app/.../route.ts` relative path into a normalized URI. */
13
+ export function nextAppRouteFileToUri(relPath: string): string | null {
14
+ const norm = relPath.replace(/\\/g, "/").replace(/^\.\//, "");
15
+ const match = norm.match(/(?:^|.*\/)app\/(?:(.+)\/)?route\.[cm]?[jt]sx?$/i);
16
+ if (!match) return null;
17
+ const rawSegments = (match[1] ?? "").split("/").filter(Boolean);
18
+ const uriSegments: string[] = [];
19
+ for (const seg of rawSegments) {
20
+ // Next.js route groups `(group)` do not appear in URL paths.
21
+ if (/^\([^)]+\)$/.test(seg)) continue;
22
+ const catchAll = seg.match(/^\[\.\.\.([^\]]+)\]$/);
23
+ if (catchAll) {
24
+ uriSegments.push(`*${catchAll[1]}`);
25
+ continue;
26
+ }
27
+ const optCatchAll = seg.match(/^\[\[\.\.\.([^\]]+)\]\]$/);
28
+ if (optCatchAll) {
29
+ uriSegments.push(`*${optCatchAll[1]}`);
30
+ continue;
31
+ }
32
+ const dynamicSeg = seg.match(/^\[([^\]]+)\]$/);
33
+ if (dynamicSeg) {
34
+ uriSegments.push(`:${dynamicSeg[1]}`);
35
+ continue;
36
+ }
37
+ uriSegments.push(seg);
38
+ }
39
+ return "/" + uriSegments.join("/");
40
+ }
41
+
42
+ export class NextJsSemanticExtractor implements SemanticSliceExtractor {
43
+ public readonly id = "nextjs";
44
+ public readonly name = "Next.js App Router Semantic Extractor";
45
+
46
+ public canHandle(projectRoot: string, framework?: string): boolean {
47
+ if (framework === "nextjs") return true;
48
+ const hasNextInPkg = (manifestFile: string): boolean => {
49
+ if (probeSourcePath(manifestFile) !== "file") return false;
50
+ const manifest = readOptionalSourceFile(manifestFile, "utf-8");
51
+ if (!manifest) return false;
52
+ try {
53
+ const pkg = JSON.parse(manifest);
54
+ return !!(pkg.dependencies?.next || pkg.devDependencies?.next);
55
+ } catch {
56
+ return false;
57
+ }
58
+ };
59
+ if (hasNextInPkg(path.join(projectRoot, "package.json"))) return true;
60
+ for (const group of ["apps", "packages"]) {
61
+ const groupDir = path.join(projectRoot, group);
62
+ if (probeSourcePath(groupDir) === "directory") {
63
+ try {
64
+ for (const entry of fs.readdirSync(groupDir, { withFileTypes: true })) {
65
+ if (entry.isDirectory() && hasNextInPkg(path.join(groupDir, entry.name, "package.json"))) {
66
+ return true;
67
+ }
68
+ }
69
+ } catch {
70
+ // Ignore unreadable directories
71
+ }
72
+ }
73
+ }
74
+ return false;
75
+ }
76
+
77
+ public async extractSlices(
78
+ projectRoot: string,
79
+ domainId?: number,
80
+ signal?: AbortSignal,
81
+ inventory?: SourceInventory
82
+ ): Promise<VerticalSliceCandidate[]> {
83
+ const root = path.resolve(projectRoot);
84
+ const allTsFiles = listSourceFiles(root, /\.[cm]?[jt]sx?$/, inventory).filter((f) => !/\.d\.[cm]?ts$/.test(f));
85
+ const routeFiles = allTsFiles.filter((f) => /(?:^|\/)app\/(?:.+\/)?route\.[cm]?[jt]sx?$/i.test(f));
86
+ if (routeFiles.length === 0) return [];
87
+
88
+ const bindings = new TypeScriptBindings(root, new Set(allTsFiles), signal);
89
+ const slices: VerticalSliceCandidate[] = [];
90
+
91
+ for (const file of routeFiles) {
92
+ signal?.throwIfAborted();
93
+ const relFile = path.relative(root, file).replace(/\\/g, "/");
94
+ const uri = nextAppRouteFileToUri(relFile);
95
+ if (!uri) continue;
96
+
97
+ const unit = bindings.load(file);
98
+ if (!unit) continue;
99
+
100
+ const exportedHandlers: Array<{ method: string; node: ts.Node; line: number }> = [];
101
+ for (const stmt of unit.source.statements) {
102
+ const mods = ts.canHaveModifiers(stmt) ? ts.getModifiers(stmt) : undefined;
103
+ const isExported = Boolean(mods?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword));
104
+ if (!isExported) continue;
105
+
106
+ if (ts.isFunctionDeclaration(stmt) && stmt.name && NEXTJS_HTTP_METHODS.has(stmt.name.text)) {
107
+ exportedHandlers.push({ method: stmt.name.text, node: stmt, line: lineOf(stmt) });
108
+ } else if (ts.isVariableStatement(stmt)) {
109
+ for (const decl of stmt.declarationList.declarations) {
110
+ if (ts.isIdentifier(decl.name) && NEXTJS_HTTP_METHODS.has(decl.name.text) && decl.initializer) {
111
+ const handler = bindings.handler(decl.initializer);
112
+ exportedHandlers.push({
113
+ method: decl.name.text,
114
+ node: handler?.node ?? decl.initializer,
115
+ line: handler ? lineOf(handler.node) : lineOf(decl),
116
+ });
117
+ }
118
+ }
119
+ }
120
+ }
121
+
122
+ if (exportedHandlers.length === 0) continue;
123
+
124
+ const controllerClass = path.basename(path.dirname(relFile)) || "Route";
125
+ for (const entry of exportedHandlers) {
126
+ const chain: ExecutionChainNode[] = [
127
+ {
128
+ stage: "ingress",
129
+ symbol: `${entry.method} ${uri}`,
130
+ file: relFile,
131
+ line: entry.line,
132
+ description: "Next.js App Router Route Handler",
133
+ relationship: { kind: "declares", derivation: "source", reason: "Next.js App Router export" },
134
+ },
135
+ {
136
+ stage: "controller",
137
+ symbol: `${controllerClass}::${entry.method}`,
138
+ file: relFile,
139
+ line: entry.line,
140
+ description: `Next.js ${entry.method} Handler`,
141
+ relationship: { kind: "route_binding", derivation: "source", reason: "Next.js App Router handler" },
142
+ },
143
+ ];
144
+
145
+ slices.push({
146
+ domain_id: domainId ?? null,
147
+ feature_key: `nextjs.${controllerClass.toLowerCase()}.${entry.method.toLowerCase()}`,
148
+ http_method: entry.method,
149
+ route_uri: uri,
150
+ route_name: `${controllerClass}.${entry.method}`,
151
+ controller_class: controllerClass,
152
+ action_name: entry.method,
153
+ controller_file: relFile,
154
+ controller_line: entry.line,
155
+ architecture_style: "mvc",
156
+ entry_kind: "http_route",
157
+ execution_chain_json: JSON.stringify(chain),
158
+ });
159
+ }
160
+ }
161
+
162
+ return slices;
163
+ }
164
+ }
@@ -0,0 +1,51 @@
1
+ import type Parser from "web-tree-sitter";
2
+
3
+ type Node = Parser.SyntaxNode;
4
+
5
+ export function children(node?: Node | null): Node[] {
6
+ return node?.namedChildren.filter(child => child.type !== "comment") ?? [];
7
+ }
8
+
9
+ export function literal(node?: Node): string | undefined {
10
+ if (node?.type === "string") return node.text.slice(1, -1).replace(/\\([\\'])/g, "$1");
11
+ if (node?.type === "encapsed_string" && children(node).every(child => child.type === "string_content")) {
12
+ const value = node.text.slice(1, -1);
13
+ if (!value.includes("\\")) return value;
14
+ }
15
+ return undefined;
16
+ }
17
+
18
+ export function phpSections(root: Node): Array<{ namespace: string; statements: Node[] }> {
19
+ const sections = [{ namespace: "", statements: [] as Node[] }];
20
+ for (const node of children(root)) {
21
+ if (node.type !== "namespace_definition") {
22
+ sections.at(-1)!.statements.push(node);
23
+ continue;
24
+ }
25
+ const namespace = node.childForFieldName("name")?.text ?? "";
26
+ const body = node.childForFieldName("body");
27
+ sections.push({ namespace, statements: children(body) });
28
+ if (body) sections.push({ namespace: "", statements: [] });
29
+ }
30
+ return sections;
31
+ }
32
+
33
+ export function importsFor(statements: Node[]): Map<string, string | null> {
34
+ const imports = new Map<string, string | null>();
35
+ for (const node of statements) {
36
+ if (node.type !== "namespace_use_declaration" || /^use\s+(?:function|const)\b/i.test(node.text)) continue;
37
+ const group = children(node).find(child => child.type === "namespace_use_group");
38
+ const prefix = group ? children(node).find(child => child.type === "namespace_name")?.text : undefined;
39
+ for (const clause of group ? children(group) : children(node)) {
40
+ if (!["namespace_use_clause", "namespace_use_group_clause"].includes(clause.type) ||
41
+ /^(?:function|const)\s/i.test(clause.text)) continue;
42
+ const targetNode = children(clause).find(child => ["name", "qualified_name", "namespace_name"].includes(child.type));
43
+ if (!targetNode) continue;
44
+ const target = [prefix, targetNode.text].filter(Boolean).join("\\").replace(/^\\/, "");
45
+ const alias = children(clause).find(child => child.type === "namespace_aliasing_clause");
46
+ const key = (alias?.namedChild(0)?.text ?? target.split("\\").at(-1)!).toLowerCase();
47
+ imports.set(key, imports.has(key) ? null : target);
48
+ }
49
+ }
50
+ return imports;
51
+ }
@@ -369,7 +369,7 @@ export class PHPExtractor implements CodeExtractor {
369
369
  };
370
370
  const lineStart = node.startPosition.row + 1;
371
371
  const lineEnd = Math.max(lineStart, node.endPosition.row + 1);
372
- const headerLine = getNodeHeader(node);
372
+ const headerLine = getNodeHeader(node, content);
373
373
 
374
374
  symbols.push({
375
375
  name: containerName,
@@ -0,0 +1,249 @@
1
+ import type Parser from "web-tree-sitter";
2
+ import type { ImportResolver } from "../../resolver/import-resolver.ts";
3
+ import { readPythonStaticString } from "../static-string.ts";
4
+
5
+ type Node = Parser.SyntaxNode;
6
+ export type PythonImport = { module: string; symbol?: string; qualifiedRoot?: string };
7
+
8
+ export function pythonImports(statement: Node): Array<[string, PythonImport]> {
9
+ const from = statement.type === "import_from_statement";
10
+ if (!from && statement.type !== "import_statement") return [];
11
+ const source = statement.childForFieldName("module_name");
12
+ return statement.namedChildren.flatMap((child): Array<[string, PythonImport]> => {
13
+ if (child.id === source?.id) return [];
14
+ const name = child.type === "aliased_import" ? child.childForFieldName("name") : child;
15
+ if (name?.type !== "dotted_name") return [];
16
+ const alias = child.childForFieldName("alias")?.text;
17
+ if (from && source) return [[alias ?? name.text, { module: source.text, symbol: name.text }]];
18
+ const head = name.text.split(".")[0]!;
19
+ return [[alias ?? head, { module: name.text, qualifiedRoot: alias ? undefined : name.text }]];
20
+ });
21
+ }
22
+
23
+ export function pythonImportMember(module: string, symbol: string): string {
24
+ return module.endsWith(".") ? module + symbol : module + "." + symbol;
25
+ }
26
+
27
+ export function pythonCallArgument(call: Node, name: string, position?: number): Node | undefined {
28
+ const args = call.childForFieldName("arguments")?.namedChildren.filter(child => child.type !== "comment") ?? [];
29
+ const keyword = args.find(child => child.type === "keyword_argument" && child.childForFieldName("name")?.text === name);
30
+ if (keyword) return keyword.childForFieldName("value") ?? undefined;
31
+ const argument = position === undefined ? undefined : args[position];
32
+ if (!argument || ["keyword_argument", "list_splat", "dictionary_splat"].includes(argument.type)) return undefined;
33
+ return argument;
34
+ }
35
+
36
+ /** Resolve the imported spelling of a dotted identifier. Calls provide no binding evidence. */
37
+ export function pythonImportedName(name: string, imports: ReadonlyMap<string, PythonImport>): string | undefined {
38
+ const [head, ...tail] = name.split(".");
39
+ const binding = imports.get(head!);
40
+ if (!binding) return undefined;
41
+ if (binding.qualifiedRoot) {
42
+ return name === binding.qualifiedRoot || name.startsWith(binding.qualifiedRoot + ".") ? name : undefined;
43
+ }
44
+ const module = binding.symbol ? pythonImportMember(binding.module, binding.symbol) : binding.module;
45
+ return [module, ...tail].join(".");
46
+ }
47
+
48
+ export function pythonCallUsesUnpacking(call: Node): boolean {
49
+ return call.childForFieldName("arguments")?.namedChildren.some(
50
+ child => child.type === "list_splat" || child.type === "dictionary_splat",
51
+ ) ?? false;
52
+ }
53
+
54
+ export function pythonLiteralMethods(methods: Node): string[] | undefined {
55
+ if (!["list", "tuple", "set"].includes(methods.type)) return undefined;
56
+ const values = methods.namedChildren.filter(child => child.type !== "comment").map(readPythonStaticString);
57
+ if (!values.every((value): value is string => value !== undefined && /^[a-z]+$/i.test(value))) return undefined;
58
+ return [...new Set(values.map(value => value.toUpperCase()))];
59
+ }
60
+
61
+ export type PythonRouterTarget = { key: string } | { module: string; symbol: string };
62
+ type RouterNames = Map<string, string>;
63
+
64
+ export function pythonImportedMember(
65
+ expression: string,
66
+ imports: ReadonlyMap<string, PythonImport>,
67
+ ): { module: string; symbol: string } | undefined {
68
+ const binding = imports.get(expression);
69
+ if (binding?.symbol) return { module: binding.module, symbol: binding.symbol };
70
+ const imported = pythonImportedName(expression, imports);
71
+ const split = imported?.lastIndexOf(".") ?? -1;
72
+ if (imported && split > 0) return { module: imported.slice(0, split), symbol: imported.slice(split + 1) };
73
+ return undefined;
74
+ }
75
+
76
+ export function resolvePythonRouterTarget(
77
+ target: PythonRouterTarget,
78
+ source: string,
79
+ resolver: ImportResolver,
80
+ exportedRouters: ReadonlyMap<string, RouterNames>,
81
+ ): string | undefined {
82
+ if ("key" in target) return target.key;
83
+ const module = resolver.resolve(target.module, source);
84
+ if (module.status !== "resolved") return undefined;
85
+ const candidates = module.targets.flatMap(item => item.files)
86
+ .map(file => exportedRouters.get(file)?.get(target.symbol)).filter((key): key is string => !!key);
87
+ return candidates.length === 1 ? candidates[0] : undefined;
88
+ }
89
+
90
+ type RouterCall = {
91
+ key: string;
92
+ receiver: string;
93
+ method: string;
94
+ call: Node;
95
+ line: number;
96
+ };
97
+
98
+ interface PythonRouteVisitor {
99
+ constructorCall: (key: string, name: string, constructor: string, call: Node) => boolean;
100
+ routerCall: (call: RouterCall, targets: {
101
+ router: (expression: string) => PythonRouterTarget | undefined;
102
+ function: (expression: string) => Node | undefined;
103
+ }) => void;
104
+ decorator: (call: RouterCall, handler: Node) => void;
105
+ }
106
+
107
+ export function visitPythonRouterModule(root: Node, file: string, visitor: PythonRouteVisitor, signal?: AbortSignal) {
108
+ const imports = new Map<string, PythonImport>();
109
+ const routers: RouterNames = new Map();
110
+ const functions = new Map<string, Node>();
111
+ const bound = new Set<string>();
112
+ const unbind = (name: string) => {
113
+ bound.add(name);
114
+ routers.delete(name);
115
+ functions.delete(name);
116
+ imports.delete(name);
117
+ };
118
+
119
+ const routerTarget = (expression: string): PythonRouterTarget | undefined => {
120
+ const local = routers.get(expression);
121
+ if (local) return { key: local };
122
+ return pythonImportedMember(expression, imports);
123
+ };
124
+
125
+ const callOnRouter = (call: Node | null, line: number): RouterCall | undefined => {
126
+ if (call?.type !== "call" || call.hasError) return undefined;
127
+ const attr = call.childForFieldName("function");
128
+ if (attr?.type !== "attribute") return undefined;
129
+ const receiver = attr.childForFieldName("object")?.text ?? "";
130
+ const key = routers.get(receiver);
131
+ const method = attr.childForFieldName("attribute")?.text;
132
+ if (key && method) return { key, receiver, method, call, line };
133
+ return undefined;
134
+ };
135
+
136
+ for (const statement of root.namedChildren) {
137
+ signal?.throwIfAborted();
138
+ for (const [name, binding] of pythonImports(statement)) {
139
+ unbind(name);
140
+ imports.set(name, binding);
141
+ }
142
+
143
+ const expression = statement.type === "expression_statement" ? statement.namedChild(0) : null;
144
+ if (expression?.type === "assignment") {
145
+ const left = expression.childForFieldName("left");
146
+ const right = expression.childForFieldName("right");
147
+ if (left?.type !== "identifier" || !right) continue;
148
+ const router = routers.get(right.text);
149
+ const handler = functions.get(right.text);
150
+ const importAlias = imports.get(right.text);
151
+ const callee = right.childForFieldName("function")?.text ?? "";
152
+ const constructor = pythonImportedName(callee, imports) ?? (!callee.includes(".") && !bound.has(callee) ? callee : "");
153
+ unbind(left.text);
154
+ if (router) routers.set(left.text, router);
155
+ if (handler) functions.set(left.text, handler);
156
+ if (importAlias) imports.set(left.text, importAlias);
157
+ if (right.type !== "call" || right.hasError || !constructor) continue;
158
+ const key = file + "#" + left.text + "@" + left.startIndex;
159
+ if (visitor.constructorCall(key, left.text, constructor, right)) routers.set(left.text, key);
160
+ }
161
+
162
+ if (expression?.type === "call") {
163
+ const registration = callOnRouter(expression, expression.startPosition.row + 1);
164
+ if (registration) visitor.routerCall(registration, { router: routerTarget, function: name => functions.get(name) });
165
+ }
166
+
167
+ const definition = statement.type === "decorated_definition" ? statement.childForFieldName("definition") : statement;
168
+ if (definition?.type !== "function_definition" && definition?.type !== "class_definition") continue;
169
+ const name = definition.childForFieldName("name")?.text;
170
+ if (!name) continue;
171
+ if (definition.type === "function_definition" && !definition.hasError) {
172
+ for (const decorator of statement.namedChildren.filter(child => child.type === "decorator")) {
173
+ const registration = callOnRouter(decorator.namedChild(0), decorator.startPosition.row + 1);
174
+ if (registration) visitor.decorator(registration, definition);
175
+ }
176
+ unbind(name);
177
+ functions.set(name, definition);
178
+ } else unbind(name);
179
+ }
180
+ return { imports, routers };
181
+ }
182
+
183
+ export interface UnwrappedPythonView {
184
+ node: Node;
185
+ methods?: string[];
186
+ }
187
+
188
+ function isAsViewCall(node: Node): boolean {
189
+ if (node.type !== "call") return false;
190
+ const fn = node.childForFieldName("function");
191
+ return fn?.type === "attribute" && fn.childForFieldName("attribute")?.text === "as_view";
192
+ }
193
+
194
+ function decoratorMethodConstraint(
195
+ fnNode: Node | null,
196
+ callee: (name: string) => string,
197
+ ): string[] | undefined {
198
+ if (!fnNode) return undefined;
199
+ if (fnNode.type === "call") {
200
+ const innerName = callee(fnNode.childForFieldName("function")?.text ?? "");
201
+ if (/^(?:django\.views\.decorators\.http\.)?require_http_methods$/.test(innerName)) {
202
+ const arg = pythonCallArgument(fnNode, "request_method_list", 0);
203
+ return arg ? pythonLiteralMethods(arg) : undefined;
204
+ }
205
+ return undefined;
206
+ }
207
+ const qualified = callee(fnNode.text);
208
+ if (/^(?:django\.views\.decorators\.http\.)?require_GET$/.test(qualified)) return ["GET"];
209
+ if (/^(?:django\.views\.decorators\.http\.)?require_POST$/.test(qualified)) return ["POST"];
210
+ if (/^(?:django\.views\.decorators\.http\.)?require_safe$/.test(qualified)) return ["GET", "HEAD"];
211
+ return undefined;
212
+ }
213
+
214
+ /**
215
+ * Unwraps decorator/middleware wrapper calls (e.g. `csrf_exempt(View.as_view(...))`,
216
+ * `login_required(fn)`, `cache_page(60)(View.as_view(...))`) to the underlying view expression.
217
+ */
218
+ export function unwrapPythonCallWrapper(
219
+ viewNode: Node,
220
+ callee: (name: string) => string = (name) => name,
221
+ ): UnwrappedPythonView {
222
+ let current = viewNode;
223
+ let methods: string[] | undefined;
224
+
225
+ for (let depth = 0; depth < 8; depth++) {
226
+ if (current.type === "parenthesized_expression") {
227
+ const inner = current.namedChildren.find((c) => c.type !== "comment");
228
+ if (!inner) break;
229
+ current = inner;
230
+ continue;
231
+ }
232
+ if (current.type !== "call" || isAsViewCall(current) || pythonCallUsesUnpacking(current)) {
233
+ break;
234
+ }
235
+ const args = current.childForFieldName("arguments")?.namedChildren.filter((c) => c.type !== "comment") ?? [];
236
+ if (args.length !== 1) break;
237
+ const innerArg = args[0]!;
238
+ if (!["identifier", "attribute", "call", "parenthesized_expression"].includes(innerArg.type)) {
239
+ break;
240
+ }
241
+ const constraint = decoratorMethodConstraint(current.childForFieldName("function"), callee);
242
+ if (constraint) {
243
+ methods = methods ? methods.filter((m) => constraint.includes(m)) : constraint;
244
+ }
245
+ current = innerArg;
246
+ }
247
+
248
+ return { node: current, methods };
249
+ }
@@ -290,7 +290,7 @@ export class PythonExtractor implements CodeExtractor {
290
290
  ? "protected"
291
291
  : "public";
292
292
 
293
- const extractImports = (node: Parser.SyntaxNode): void => {
293
+ for (const node of rootNode.descendantsOfType(["import_statement", "import_from_statement"])) {
294
294
  if (node.type === "import_from_statement") {
295
295
  const modNode =
296
296
  node.childForFieldName("module_name") ??
@@ -322,7 +322,7 @@ export class PythonExtractor implements CodeExtractor {
322
322
  ...(importedSymbols.length > 0 ? { imported_symbols: Array.from(new Set(importedSymbols)) } : {}),
323
323
  });
324
324
  }
325
- return;
325
+ continue;
326
326
  }
327
327
 
328
328
  if (node.type === "import_statement") {
@@ -355,12 +355,8 @@ export class PythonExtractor implements CodeExtractor {
355
355
  }
356
356
  }
357
357
  }
358
- return;
359
358
  }
360
-
361
- for (const child of node.namedChildren) extractImports(child);
362
- };
363
- extractImports(rootNode);
359
+ }
364
360
 
365
361
  const processNode = (node: Parser.SyntaxNode, currentClass: string | null, pendingDecorators?: string[]): void => {
366
362
  if (node.type === "decorated_definition") {
@@ -387,7 +383,7 @@ export class PythonExtractor implements CodeExtractor {
387
383
  const qualifiedName = currentClass ? `${currentClass}::${className}` : className;
388
384
  const lineStart = node.startPosition.row + 1;
389
385
  const lineEnd = Math.max(lineStart, node.endPosition.row + 1);
390
- const headerLine = getNodeHeader(node).replace(/:$/, "").trim();
386
+ const headerLine = getNodeHeader(node, content).replace(/:$/, "").trim();
391
387
  const baseSignature = headerLine || `class ${className}`;
392
388
  const signature = pendingDecorators?.length ? `${pendingDecorators.join("\n")}\n${baseSignature}` : baseSignature;
393
389
 
@@ -423,7 +419,7 @@ export class PythonExtractor implements CodeExtractor {
423
419
  const isProperty = pendingDecorators?.some((d) => d === "@property");
424
420
  const lineStart = node.startPosition.row + 1;
425
421
  const lineEnd = Math.max(lineStart, node.endPosition.row + 1);
426
- const headerLine = getNodeHeader(node).replace(/:$/, "").trim();
422
+ const headerLine = getNodeHeader(node, content).replace(/:$/, "").trim();
427
423
  const baseSignature = headerLine || `def ${funcName}()`;
428
424
  const signature = pendingDecorators?.length ? `${pendingDecorators.join("\n")}\n${baseSignature}` : baseSignature;
429
425
  const nestingDepth = calculateAstControlFlowNesting(
@@ -14,6 +14,7 @@ import { ExpressSemanticExtractor } from "./express-semantic.ts";
14
14
  import { FastifySemanticExtractor } from "./fastify-semantic.ts";
15
15
  import { HonoSemanticExtractor } from "./hono-semantic.ts";
16
16
  import { ElysiaSemanticExtractor } from "./elysia-semantic.ts";
17
+ import { NextJsSemanticExtractor } from "./nextjs-semantic.ts";
17
18
  import { scanSourceFiles, type SourceInventory } from "../../resources/source-inventory.ts";
18
19
  import { shouldIgnoreSourcePath } from "../../resources/ignore.ts";
19
20
 
@@ -34,6 +35,7 @@ export class SemanticSliceExtractorRegistry {
34
35
  new FastifySemanticExtractor(),
35
36
  new HonoSemanticExtractor(),
36
37
  new ElysiaSemanticExtractor(),
38
+ new NextJsSemanticExtractor(),
37
39
  new FastApiSemanticExtractor(),
38
40
  new DjangoSemanticExtractor(),
39
41
  new FlaskSemanticExtractor(),
@@ -0,0 +1,43 @@
1
+ /** Accumulate all mount paths at each router before propagating them to descendants. */
2
+ export function composeMountPrefixes<Key>(
3
+ roots: ReadonlyMap<Key, string | undefined>,
4
+ mounts: ReadonlyArray<{ parent: Key; child: Key; prefix: string | undefined }>,
5
+ signal?: AbortSignal,
6
+ ): Map<Key, Set<string>> {
7
+ const children = new Map<Key, typeof mounts[number][]>();
8
+ const incoming = new Map<Key, number>();
9
+ for (const mount of mounts) {
10
+ const edges = children.get(mount.parent) ?? [];
11
+ edges.push(mount);
12
+ children.set(mount.parent, edges);
13
+ incoming.set(mount.child, (incoming.get(mount.child) ?? 0) + 1);
14
+ }
15
+
16
+ const prefixes = new Map<Key, Set<string>>();
17
+ const queue: Key[] = [];
18
+ for (const [key, prefix] of roots) {
19
+ if (incoming.has(key)) continue;
20
+ queue.push(key);
21
+ prefixes.set(key, new Set(prefix === undefined ? [] : [prefix]));
22
+ }
23
+ for (let index = 0; index < queue.length; index++) {
24
+ signal?.throwIfAborted();
25
+ const parent = queue[index]!;
26
+ for (const edge of children.get(parent) ?? []) {
27
+ const paths = prefixes.get(edge.child) ?? new Set<string>();
28
+ if (edge.prefix !== undefined) {
29
+ for (const path of prefixes.get(parent) ?? []) {
30
+ signal?.throwIfAborted();
31
+ paths.add(path + edge.prefix);
32
+ }
33
+ }
34
+ prefixes.set(edge.child, paths);
35
+ const remaining = incoming.get(edge.child)! - 1;
36
+ incoming.set(edge.child, remaining);
37
+ if (!remaining) queue.push(edge.child);
38
+ }
39
+ }
40
+ // Cycles (and routes depending on them) have no complete registration path.
41
+ for (const [key, remaining] of incoming) if (remaining) prefixes.delete(key);
42
+ return prefixes;
43
+ }
@@ -110,7 +110,7 @@ export class RubyExtractor implements CodeExtractor {
110
110
  const fullName = scopeName ? `${scopeName}::${baseName}` : baseName;
111
111
  const lineStart = child.startPosition.row + 1;
112
112
  const lineEnd = Math.max(lineStart, child.endPosition.row + 1);
113
- const headerLine = getNodeHeader(child);
113
+ const headerLine = getNodeHeader(child, content);
114
114
  const kind = child.type === "class" ? "class" : "interface";
115
115
 
116
116
  symbols.push({
@@ -145,7 +145,7 @@ export class RubyExtractor implements CodeExtractor {
145
145
  : methodName;
146
146
  const lineStart = child.startPosition.row + 1;
147
147
  const lineEnd = Math.max(lineStart, child.endPosition.row + 1);
148
- const headerLine = getNodeHeader(child);
148
+ const headerLine = getNodeHeader(child, content);
149
149
  const nestingDepth = calculateAstControlFlowNesting(
150
150
  child,
151
151
  RUBY_CONTROL_FLOW_NODES,
@@ -115,7 +115,7 @@ export class RustExtractor implements CodeExtractor {
115
115
  const fnName = nameNode.text;
116
116
  const lineStart = node.startPosition.row + 1;
117
117
  const lineEnd = Math.max(lineStart, node.endPosition.row + 1);
118
- const headerLine = getNodeHeader(node);
118
+ const headerLine = getNodeHeader(node, content);
119
119
  const nestingDepth = calculateAstControlFlowNesting(
120
120
  node,
121
121
  RUST_CONTROL_FLOW_NODES,
@@ -144,7 +144,7 @@ export class RustExtractor implements CodeExtractor {
144
144
  const structName = nameNode.text;
145
145
  const lineStart = node.startPosition.row + 1;
146
146
  const lineEnd = Math.max(lineStart, node.endPosition.row + 1);
147
- const headerLine = getNodeHeader(node);
147
+ const headerLine = getNodeHeader(node, content);
148
148
 
149
149
  symbols.push({
150
150
  name: qualify(structName),
@@ -168,7 +168,7 @@ export class RustExtractor implements CodeExtractor {
168
168
  const enumName = nameNode.text;
169
169
  const lineStart = node.startPosition.row + 1;
170
170
  const lineEnd = Math.max(lineStart, node.endPosition.row + 1);
171
- const headerLine = getNodeHeader(node);
171
+ const headerLine = getNodeHeader(node, content);
172
172
 
173
173
  symbols.push({
174
174
  name: qualify(enumName),
@@ -192,7 +192,7 @@ export class RustExtractor implements CodeExtractor {
192
192
  const traitName = nameNode.text;
193
193
  const lineStart = node.startPosition.row + 1;
194
194
  const lineEnd = Math.max(lineStart, node.endPosition.row + 1);
195
- const headerLine = getNodeHeader(node);
195
+ const headerLine = getNodeHeader(node, content);
196
196
 
197
197
  symbols.push({
198
198
  name: qualify(traitName),