@dimassetoid/septum-mcp 0.2.1 → 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 (161) hide show
  1. package/README.md +46 -45
  2. package/package.json +8 -6
  3. package/src/cli/commands/check.ts +41 -26
  4. package/src/cli/commands/hook.ts +77 -105
  5. package/src/cli/commands/init.ts +35 -9
  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 +35 -9
  9. package/src/cli/hook-payload.ts +43 -0
  10. package/src/cli/index.ts +15 -51
  11. package/src/cli/scaffold/harness-config.ts +48 -8
  12. package/src/cli/templates/hooks.ts +51 -27
  13. package/src/cli/templates/rules.ts +34 -49
  14. package/src/cli/templates/skill.ts +46 -35
  15. package/src/core/boundary/audit.ts +383 -0
  16. package/src/core/boundary/evaluator.ts +299 -178
  17. package/src/core/boundary/staged-auditor.ts +188 -34
  18. package/src/core/config/domain-ownership.ts +47 -0
  19. package/src/core/config/domain-registration.ts +141 -0
  20. package/src/core/config/loader.ts +82 -54
  21. package/src/core/config/schema.ts +24 -46
  22. package/src/core/database/client.ts +2 -0
  23. package/src/core/database/repositories/dependency.repository.ts +326 -543
  24. package/src/core/database/repositories/domain.repository.ts +48 -4
  25. package/src/core/database/repositories/file.repository.ts +10 -0
  26. package/src/core/database/repositories/symbol.repository.ts +97 -259
  27. package/src/core/database/repository.ts +138 -24
  28. package/src/core/database/schema.ts +28 -33
  29. package/src/core/discovery/declarative-routes.ts +69 -0
  30. package/src/core/discovery/framework-detector.ts +149 -0
  31. package/src/core/discovery/navigation.ts +269 -0
  32. package/src/core/discovery/topology-detector.ts +153 -170
  33. package/src/core/errors.ts +19 -0
  34. package/src/core/ingestion/pipeline.ts +378 -212
  35. package/src/core/parser/behavioral-analyzer.ts +26 -22
  36. package/src/core/parser/boundary-tracker.ts +15 -0
  37. package/src/core/parser/extractors/base.ts +16 -4
  38. package/src/core/parser/extractors/csharp.ts +9 -5
  39. package/src/core/parser/extractors/django-routing.ts +163 -0
  40. package/src/core/parser/extractors/django-semantic.ts +400 -516
  41. package/src/core/parser/extractors/elysia-semantic.ts +172 -496
  42. package/src/core/parser/extractors/express-semantic.ts +195 -398
  43. package/src/core/parser/extractors/fastapi-semantic.ts +182 -399
  44. package/src/core/parser/extractors/fastify-semantic.ts +216 -732
  45. package/src/core/parser/extractors/flask-semantic.ts +92 -388
  46. package/src/core/parser/extractors/go-routing.ts +344 -0
  47. package/src/core/parser/extractors/go-semantic.ts +210 -508
  48. package/src/core/parser/extractors/go.ts +6 -3
  49. package/src/core/parser/extractors/graphql-entrypoint.ts +146 -0
  50. package/src/core/parser/extractors/hono-semantic.ts +132 -530
  51. package/src/core/parser/extractors/java.ts +7 -5
  52. package/src/core/parser/extractors/laravel-routing.ts +263 -0
  53. package/src/core/parser/extractors/laravel-semantic.ts +169 -333
  54. package/src/core/parser/extractors/manifest-helpers.ts +64 -0
  55. package/src/core/parser/extractors/mcp-cli-dispatch.ts +268 -0
  56. package/src/core/parser/extractors/mcp-cli-semantic.ts +84 -336
  57. package/src/core/parser/extractors/nestjs-semantic.ts +238 -510
  58. package/src/core/parser/extractors/nextjs-semantic.ts +164 -0
  59. package/src/core/parser/extractors/php-ast-helpers.ts +51 -0
  60. package/src/core/parser/extractors/php.ts +17 -1
  61. package/src/core/parser/extractors/python-route-ast.ts +249 -0
  62. package/src/core/parser/extractors/python.ts +9 -8
  63. package/src/core/parser/extractors/registry.ts +28 -5
  64. package/src/core/parser/extractors/route-prefixes.ts +43 -0
  65. package/src/core/parser/extractors/ruby.ts +10 -7
  66. package/src/core/parser/extractors/rust.ts +35 -17
  67. package/src/core/parser/extractors/semantic-extractor.interface.ts +3 -1
  68. package/src/core/parser/extractors/symfony-routing.ts +114 -0
  69. package/src/core/parser/extractors/symfony-semantic.ts +75 -262
  70. package/src/core/parser/extractors/typescript-bindings.ts +333 -0
  71. package/src/core/parser/extractors/typescript-compiler-fallback.ts +380 -0
  72. package/src/core/parser/extractors/typescript-fallback.ts +207 -0
  73. package/src/core/parser/extractors/typescript-route-context.ts +58 -0
  74. package/src/core/parser/extractors/typescript.ts +36 -216
  75. package/src/core/parser/implementation-fingerprint.ts +97 -0
  76. package/src/core/parser/language-capabilities.ts +23 -7
  77. package/src/core/parser/schema/providers/laravel-migration-provider.ts +77 -51
  78. package/src/core/parser/schema/schema-provider-registry.ts +1 -3
  79. package/src/core/parser/schema/schema-provider.interface.ts +2 -1
  80. package/src/core/parser/semantic-revision.ts +3 -0
  81. package/src/core/parser/static-string.ts +51 -0
  82. package/src/core/parser/wasm-loader.ts +6 -2
  83. package/src/core/resolver/ast-method-tracer.ts +230 -0
  84. package/src/core/resolver/call-graph-helpers.ts +72 -0
  85. package/src/core/resolver/call-graph-tracer.ts +375 -311
  86. package/src/core/resolver/dependency-analysis.ts +593 -0
  87. package/src/core/resolver/import-candidates.ts +120 -0
  88. package/src/core/resolver/import-evidence.ts +88 -0
  89. package/src/core/resolver/import-resolver.ts +162 -181
  90. package/src/core/resolver/interpretation-inputs.ts +65 -0
  91. package/src/core/resolver/languages/go.ts +103 -0
  92. package/src/core/resolver/languages/managed.ts +200 -0
  93. package/src/core/resolver/languages/python.ts +133 -0
  94. package/src/core/resolver/languages/ruby.ts +40 -0
  95. package/src/core/resolver/languages/rust.ts +127 -0
  96. package/src/core/resolver/languages/shared.ts +74 -0
  97. package/src/core/resolver/module-resolver.ts +18 -7
  98. package/src/core/resolver/path-resolver.ts +6 -3
  99. package/src/core/resolver/polyglot-slice-tracer.ts +197 -0
  100. package/src/core/resolver/slice-catalog.ts +94 -0
  101. package/src/core/resolver/slice-format.ts +22 -0
  102. package/src/core/resolver/slice-selection.ts +237 -0
  103. package/src/core/resolver/symbol-impact.ts +477 -0
  104. package/src/core/resolver/symbol-locator.ts +82 -15
  105. package/src/core/resolver/vertical-slice-tracer.ts +57 -278
  106. package/src/core/resources/ignore.ts +21 -1
  107. package/src/core/resources/limits.ts +2 -1
  108. package/src/core/resources/source-files.ts +143 -20
  109. package/src/core/resources/source-inventory.ts +55 -0
  110. package/src/core/resources/work-queue.ts +167 -4
  111. package/src/core/retrieval/context-page.ts +116 -0
  112. package/src/core/retrieval/context.ts +457 -0
  113. package/src/core/retrieval/resolution-warnings.ts +21 -0
  114. package/src/core/retrieval/source-context.ts +448 -0
  115. package/src/core/retrieval/symbol-details.ts +453 -0
  116. package/src/core/retrieval/symbol-evidence.ts +97 -0
  117. package/src/core/retrieval/typescript-references.ts +293 -0
  118. package/src/core/retrieval/universal-context.ts +182 -0
  119. package/src/core/telemetry/summary.ts +114 -0
  120. package/src/core/telemetry/telemetry.ts +225 -37
  121. package/src/index.ts +0 -3
  122. package/src/mcp/formatters/compact-text.ts +439 -0
  123. package/src/mcp/resources-and-prompts.ts +253 -0
  124. package/src/mcp/schemas/boundary.ts +145 -0
  125. package/src/mcp/schemas/map.ts +250 -0
  126. package/src/mcp/schemas/shared.ts +52 -0
  127. package/src/mcp/schemas/slice.ts +60 -0
  128. package/src/mcp/schemas/symbol.ts +268 -0
  129. package/src/mcp/schemas.ts +5 -1105
  130. package/src/mcp/server.ts +263 -597
  131. package/src/mcp/tool-catalog.ts +331 -0
  132. package/src/mcp/tools/boundary.ts +69 -4
  133. package/src/mcp/tools/map.ts +126 -0
  134. package/src/mcp/tools/slice.ts +101 -3
  135. package/src/mcp/tools/symbol.ts +480 -26
  136. package/src/mcp/ui/app-client.ts +899 -0
  137. package/src/mcp/ui/app.html +478 -0
  138. package/src/mcp/workflow-playbooks.ts +181 -0
  139. package/src/mcp/workspace-boundary.ts +50 -0
  140. package/src/mcp/workspace-manager.ts +102 -18
  141. package/src/mcp/workspace-watcher.ts +38 -19
  142. package/src/types/index.ts +47 -53
  143. package/src/cli/commands/topology.ts +0 -161
  144. package/src/core/database/repositories/environment.repository.ts +0 -207
  145. package/src/core/parser/schema/providers/prisma-schema-provider.ts +0 -90
  146. package/src/core/session/session-manager.ts +0 -107
  147. package/src/core/topology/environment-detector.ts +0 -973
  148. package/src/core/topology/types.ts +0 -83
  149. package/src/mcp/tools/check-boundary.ts +0 -387
  150. package/src/mcp/tools/domain.ts +0 -40
  151. package/src/mcp/tools/feature.ts +0 -67
  152. package/src/mcp/tools/get-domain-catalog.ts +0 -226
  153. package/src/mcp/tools/get-environment-topology.ts +0 -138
  154. package/src/mcp/tools/get-feature-context.ts +0 -224
  155. package/src/mcp/tools/get-symbol-hotspots.ts +0 -54
  156. package/src/mcp/tools/get-symbol-impact.ts +0 -64
  157. package/src/mcp/tools/get-symbol.ts +0 -175
  158. package/src/mcp/tools/locate-symbol.ts +0 -196
  159. package/src/mcp/tools/register-domain.ts +0 -75
  160. package/src/mcp/tools/register-feature.ts +0 -110
  161. package/src/mcp/tools/trace-vertical-slice.ts +0 -80
@@ -1,51 +1,25 @@
1
- import type Parser from "web-tree-sitter";
2
- import { parseWithTreeSitter } from "../wasm-loader.ts";
3
- import { readOptionalSourceFile } from "../../resources/source-files.ts";
4
- import { isIgnoredDirectory } from "../../resources/ignore.ts";
5
- import { ImportResolver } from "../../resolver/import-resolver.ts";
6
- import * as fs from "node:fs";
7
1
  import * as path from "node:path";
2
+ import ts from "typescript";
3
+ import type { ExecutionChainNode } from "../../../types/index.ts";
4
+ import { listSourceFiles, type SourceInventory } from "../../resources/source-inventory.ts";
5
+ import { probeSourcePath, readOptionalSourceFile } from "../../resources/source-files.ts";
6
+ import { hasPackageJsonDependency } from "./manifest-helpers.ts";
8
7
  import type { SemanticSliceExtractor, VerticalSliceCandidate } from "./semantic-extractor.interface.ts";
9
-
10
- const ELYSIA_VERBS = new Set(["get", "post", "put", "patch", "delete", "all"]);
11
-
12
- interface ExtractedRoute {
13
- file: string;
14
- relPath: string;
15
- routerVar: string;
16
- httpMethods: string[];
17
- rawPath: string;
18
- validationSchema?: { symbol: string; file?: string; line?: number };
19
- handler: { symbol: string; line: number; node?: Parser.SyntaxNode };
20
- routeLine: number;
21
- }
22
-
23
- interface ExtractedMount {
24
- file: string;
25
- relPath: string;
26
- callerVar: string;
27
- prefix: string;
28
- targetVar: string;
29
- line: number;
30
- }
31
-
32
- function cleanLiteral(node: Parser.SyntaxNode | null | undefined): string | undefined {
33
- if (!node) return undefined;
34
- if (node.type === "string") {
35
- const raw = node.text.trim();
36
- return raw.replace(/^['"`]|['"`]$/g, "");
37
- }
38
- return undefined;
39
- }
40
-
41
- function normalizeRouteUri(prefix: string, rawPath: string): string {
42
- const p = (prefix ?? "").trim().replace(/\/+$/, "");
43
- let r = (rawPath ?? "").trim();
44
- if (!r.startsWith("/")) r = "/" + r;
45
- if (r === "/" && p.length > 0) return p;
46
- if (r === "/" && p.length === 0) return "/";
47
- const joined = `${p}${r}`;
48
- return joined.startsWith("/") ? joined : `/${joined}`;
8
+ import { lineOf, literal, objectMember, TypeScriptBindings, visitRouteCalls } from "./typescript-bindings.ts";
9
+ import { routeContext } from "./typescript-route-context.ts";
10
+
11
+ const verbs = new Set(["get", "post", "put", "patch", "delete", "head", "options", "connect", "trace", "all"]);
12
+ const instanceMethods = new Set([
13
+ ...verbs, "route", "use", "group", "guard", "decorate", "state", "derive", "resolve",
14
+ "model", "onRequest", "onBeforeHandle", "onAfterHandle", "onError",
15
+ ]);
16
+ type Expression = ts.Expression | ts.MethodDeclaration;
17
+ type Route = { method: string; uri: string; call: ts.CallExpression; handler: ts.Expression; schema?: Expression };
18
+ type Scope = { prefix: string | undefined; routes: Map<string, Route>; schema?: Expression };
19
+ type Frames = ReadonlyMap<ts.ParameterDeclaration, Scope>;
20
+
21
+ function leadingSlash(value: string): string {
22
+ return value && !value.startsWith("/") ? "/" + value : value;
49
23
  }
50
24
 
51
25
  export class ElysiaSemanticExtractor implements SemanticSliceExtractor {
@@ -54,485 +28,187 @@ export class ElysiaSemanticExtractor implements SemanticSliceExtractor {
54
28
 
55
29
  public canHandle(projectRoot: string, framework?: string): boolean {
56
30
  if (framework === "elysia") return true;
57
-
58
- const pkgPath = path.join(projectRoot, "package.json");
59
- if (fs.existsSync(pkgPath)) {
60
- try {
61
- const pkg = JSON.parse(readOptionalSourceFile(pkgPath, "utf-8"));
62
- const deps = { ...(pkg.dependencies || {}), ...(pkg.devDependencies || {}) };
63
- if (deps.elysia) return true;
64
- } catch {}
65
- }
66
-
67
- // Check entrypoint source code
31
+ if (hasPackageJsonDependency(projectRoot, ["elysia"])) return true;
68
32
  for (const entry of ["src/index.ts", "src/app.ts", "index.ts", "app.ts", "src/server.ts"]) {
69
- const full = path.join(projectRoot, entry);
70
- if (fs.existsSync(full)) {
71
- try {
72
- const content = readOptionalSourceFile(full, "utf-8");
73
- if (content.includes("from \"elysia\"") || content.includes("from 'elysia'") || content.includes("require(\"elysia\")")) {
74
- return true;
75
- }
76
- } catch {}
33
+ const file = path.join(projectRoot, entry);
34
+ if (probeSourcePath(file) === "file" && /(?:from\s*|require\(\s*)['"]elysia['"]/.test(readOptionalSourceFile(file))) {
35
+ return true;
77
36
  }
78
37
  }
79
-
80
38
  return false;
81
39
  }
82
40
 
83
41
  public async extractSlices(
84
42
  projectRoot: string,
85
43
  domainId?: number,
86
- signal?: AbortSignal
44
+ signal?: AbortSignal,
45
+ inventory?: SourceInventory,
87
46
  ): Promise<VerticalSliceCandidate[]> {
88
- const slices: VerticalSliceCandidate[] = [];
89
- const sourceFiles = this.findSourceFiles(projectRoot);
90
- const resolver = new ImportResolver(projectRoot);
91
-
92
- const allRoutes: ExtractedRoute[] = [];
93
- const allMounts: ExtractedMount[] = [];
94
- const fileImports = new Map<string, Map<string, string>>(); // relPath -> (ident -> targetRelPath)
95
-
96
- for (const file of sourceFiles) {
97
- if (signal?.aborted) throw new Error("semantic_extraction_cancelled");
98
- const relPath = path.relative(projectRoot, file).replace(/\\/g, "/");
99
- const content = readOptionalSourceFile(file, "utf-8");
100
- if (!content.trim()) continue;
101
-
102
- const fileData = await parseWithTreeSitter(
103
- "typescript",
104
- content,
105
- (rootNode) => this.extractFileAst(file, relPath, rootNode, resolver, projectRoot)
106
- );
107
-
108
- if (fileData) {
109
- allRoutes.push(...fileData.routes);
110
- allMounts.push(...fileData.mounts);
111
- if (fileData.resolvedImports.size > 0) {
112
- fileImports.set(relPath, fileData.resolvedImports);
113
- }
47
+ const root = path.resolve(projectRoot);
48
+ const files = listSourceFiles(root, /\.[cm]?[jt]sx?$/, inventory).filter(file => !/\.d\.[cm]?ts$/.test(file));
49
+ const bindings = new TypeScriptBindings(root, new Set(files), signal);
50
+ const scopes = new Map<ts.NewExpression, Scope>();
51
+ const mounted = new Set<Scope>();
52
+ const active = new Set<ts.FunctionLikeDeclaration>();
53
+ const fileOf = (node: ts.Node) => path.relative(root, node.getSourceFile().fileName).replace(/\\/g, "/");
54
+ const object = (expression?: ts.Expression) => {
55
+ const value = bindings.value(expression);
56
+ return value && ts.isObjectLiteralExpression(value) ? value : undefined;
57
+ };
58
+ const schemaFor = (expression?: ts.Expression): Expression | undefined => {
59
+ const opts = object(expression);
60
+ if (!opts) return undefined;
61
+ for (const field of ["body", "query", "params", "headers", "cookie", "response"]) {
62
+ const value = objectMember(opts, field);
63
+ if (value) return value;
114
64
  }
115
- }
116
-
117
- // Resolve Router Prefix Hierarchy
118
- const routerPrefixes = this.resolvePrefixHierarchy(allMounts, fileImports);
119
-
120
- // Build Vertical Slices (Level 0 – Level 5)
121
- for (const route of allRoutes) {
122
- const prefixes = routerPrefixes.get(`${route.relPath}#${route.routerVar}`) || [""];
123
-
124
- for (const prefix of prefixes) {
125
- for (const httpMethod of route.httpMethods) {
126
- const fullUri = normalizeRouteUri(prefix, route.rawPath);
127
- const actionSymbol = route.handler.symbol;
128
- const rootIdent = actionSymbol.includes(".") ? actionSymbol.split(".")[0] : actionSymbol;
129
- const imports = fileImports.get(route.relPath);
130
- const resolvedControllerFile = imports?.get(rootIdent) || route.relPath;
131
- const fileBase = path.basename(route.relPath).replace(/\.[^.]+$/, "");
132
- const controllerClass = actionSymbol.includes(".")
133
- ? actionSymbol.split(".")[0]
134
- : fileBase.charAt(0).toUpperCase() + fileBase.slice(1);
135
- const actionName = actionSymbol.includes(".") ? actionSymbol.split(".").pop()! : actionSymbol;
136
-
137
- const chain: Array<{ stage: string; symbol: string; file?: string; line?: number; description?: string }> = [
138
- {
139
- stage: "ingress",
140
- symbol: `${httpMethod} ${fullUri}`,
141
- file: route.relPath,
142
- line: route.routeLine,
143
- description: `Elysia Route: ${httpMethod} ${fullUri}`,
144
- },
145
- ];
146
-
147
- // L2: Validation Schema (TypeBox)
148
- if (route.validationSchema) {
149
- chain.push({
150
- stage: "validation",
151
- symbol: route.validationSchema.symbol,
152
- file: route.validationSchema.file || route.relPath,
153
- line: route.validationSchema.line,
154
- description: `Elysia TypeBox Schema: ${route.validationSchema.symbol}`,
155
- });
156
- }
157
-
158
- // L3: Controller Action
159
- chain.push({
160
- stage: "controller",
161
- symbol: actionSymbol,
162
- file: resolvedControllerFile,
163
- line: route.handler.line,
164
- description: `Elysia Action Handler`,
165
- });
166
-
167
- // L4–L5: Tracing Service & Persistence from handler or imported controller
168
- const scanFile = resolvedControllerFile !== route.relPath ? resolvedControllerFile : route.relPath;
169
- const fullScanPath = path.resolve(projectRoot, scanFile);
170
- const scanContent = readOptionalSourceFile(fullScanPath, "utf-8");
171
-
172
- if (scanContent) {
173
- // Check service calls: orderService.create(...) or OrderService.process(...)
174
- const sMatch = scanContent.match(/\b([a-zA-Z0-9_]+(?:Service|Usecase))\s*\.\s*([A-Za-z0-9_]+)\s*\(/i);
175
- let serviceFile: string | undefined;
176
- if (sMatch) {
177
- const svcIdent = sMatch[1];
178
- const svcMethod = sMatch[2];
179
- const imports = fileImports.get(scanFile);
180
- let svcImport = imports?.get(svcIdent);
181
- if (!svcImport && imports) {
182
- const pascal = svcIdent.charAt(0).toUpperCase() + svcIdent.slice(1);
183
- svcImport = imports.get(pascal);
184
- if (!svcImport) {
185
- const instMatch = scanContent.match(new RegExp(`\\b(?:const|let|var)\\s+${svcIdent}\\s*=\\s*new\\s+([a-zA-Z0-9_]+)`));
186
- if (instMatch) {
187
- svcImport = imports.get(instMatch[1]);
188
- }
189
- }
190
- }
191
- serviceFile = svcImport;
192
-
193
- chain.push({
194
- stage: "service",
195
- symbol: `${svcIdent}::${svcMethod}`,
196
- ...(serviceFile ? { file: serviceFile } : {}),
197
- description: `Elysia Service Call: ${svcIdent}::${svcMethod}`,
198
- });
199
- }
200
-
201
- // Check Prisma / Drizzle / TypeORM persistence in scanFile or serviceFile
202
- const filesToInspect = [fullScanPath];
203
- if (serviceFile) filesToInspect.push(path.resolve(projectRoot, serviceFile));
204
-
205
- for (const inspectPath of filesToInspect) {
206
- const contentToInspect = readOptionalSourceFile(inspectPath, "utf-8");
207
- if (!contentToInspect) continue;
208
-
209
- const prismaMatch = contentToInspect.match(/prisma\.([a-zA-Z0-9_]+)\.(?:find|create|update|delete|upsert)/);
210
- const drizzleMatch = contentToInspect.match(/db\.(?:insert|select|update|delete)\s*\(\s*([a-zA-Z0-9_]+)\s*\)/);
211
-
212
- const entityName =
213
- prismaMatch ? (prismaMatch[1].charAt(0).toUpperCase() + prismaMatch[1].slice(1)) :
214
- drizzleMatch ? (drizzleMatch[1].charAt(0).toUpperCase() + drizzleMatch[1].slice(1)) : undefined;
215
-
216
- if (entityName && !chain.some((n) => n.stage === "entity")) {
217
- const inspectRel = path.relative(projectRoot, inspectPath).replace(/\\/g, "/");
218
- const entImport = fileImports.get(inspectRel)?.get(entityName);
219
-
220
- chain.push({
221
- stage: "repository",
222
- symbol: `${entityName}Repository`,
223
- file: inspectRel,
224
- description: prismaMatch ? "Prisma ORM Client" : "Drizzle ORM Query",
225
- });
226
-
227
- chain.push({
228
- stage: "entity",
229
- symbol: entityName,
230
- ...(entImport ? { file: entImport } : { file: inspectRel }),
231
- description: "Database Entity / Schema Model",
232
- });
233
- }
234
- }
235
- }
65
+ return undefined;
66
+ };
236
67
 
237
- slices.push({
238
- domain_id: domainId ?? null,
239
- feature_key: `elysia.${controllerClass.toLowerCase()}.${actionName}`,
240
- http_method: httpMethod,
241
- route_uri: fullUri,
242
- route_name: `${controllerClass}.${actionName}`,
243
- controller_class: controllerClass,
244
- action_name: actionName,
245
- controller_file: resolvedControllerFile,
246
- controller_line: route.handler.line,
247
- architecture_style: "mvc",
248
- entry_kind: "http_route",
249
- execution_chain_json: JSON.stringify(chain),
250
- });
68
+ const instanceOf = (expression: ts.Expression, frames: Frames): Scope | undefined => {
69
+ const visited = new Set<ts.Node>();
70
+ let value = bindings.value(expression);
71
+ while (value && !visited.has(value)) {
72
+ visited.add(value);
73
+ if (ts.isIdentifier(value)) {
74
+ const declared = bindings.declaration(value);
75
+ return declared && ts.isParameter(declared) ? frames.get(declared) : undefined;
76
+ }
77
+ if (ts.isNewExpression(value)) {
78
+ const existing = scopes.get(value);
79
+ if (existing) return existing;
80
+ const type = bindings.packageBinding(value.expression);
81
+ if (type?.module !== "elysia" || type.name !== "Elysia" && type.name !== "default") return undefined;
82
+ const opts = object(value.arguments?.[0]);
83
+ const raw = opts && objectMember(opts, "prefix");
84
+ const dynamic = value.arguments?.length && (!opts || opts.properties.some(property =>
85
+ ts.isSpreadAssignment(property) || property.name && ts.isComputedPropertyName(property.name),
86
+ ));
87
+ const prefix = raw && !ts.isMethodDeclaration(raw) ? literal(raw) : raw || dynamic ? undefined : "";
88
+ const scope = { prefix: prefix === undefined ? undefined : leadingSlash(prefix), routes: new Map<string, Route>() };
89
+ scopes.set(value, scope);
90
+ return scope;
251
91
  }
92
+ if (!ts.isCallExpression(value) || value.questionDotToken || !ts.isPropertyAccessExpression(value.expression) ||
93
+ value.expression.questionDotToken || !instanceMethods.has(value.expression.name.text)) return undefined;
94
+ value = bindings.value(value.expression.expression);
252
95
  }
253
- }
254
-
255
- return slices;
256
- }
257
-
258
- private extractFileAst(
259
- file: string,
260
- relPath: string,
261
- rootNode: Parser.SyntaxNode,
262
- resolver: ImportResolver,
263
- _projectRoot: string
264
- ): {
265
- routes: ExtractedRoute[];
266
- mounts: ExtractedMount[];
267
- resolvedImports: Map<string, string>;
268
- } {
269
- const routes: ExtractedRoute[] = [];
270
- const mounts: ExtractedMount[] = [];
271
- const resolvedImports = new Map<string, string>();
96
+ return undefined;
97
+ };
272
98
 
273
- // 1. Collect import statements
274
- for (const child of rootNode.namedChildren) {
275
- if (child.type === "import_statement") {
276
- const sourceNode = child.childForFieldName("source");
277
- const specifier = cleanLiteral(sourceNode);
278
- if (!specifier) continue;
99
+ const put = (scope: Scope, route: Route) => scope.routes.set(route.method + "\0" + route.uri, route);
100
+ const copyRoutes = (parent: Scope, child: Scope, subpath: string) => {
101
+ if (parent.prefix === undefined || parent === child) return;
102
+ for (const route of child.routes.values()) {
103
+ signal?.throwIfAborted();
104
+ put(parent, { ...route, uri: parent.prefix + leadingSlash(subpath + route.uri) });
105
+ }
106
+ };
279
107
 
280
- const res = resolver.resolve(specifier, relPath);
281
- const targetFile = res.status === "resolved" && res.targets[0]?.files[0] ? res.targets[0].files[0] : undefined;
282
- if (!targetFile) continue;
108
+ const visitCallback = (callback: ts.Expression | undefined, scope: Scope, frames: Frames) => {
109
+ const handler = bindings.handler(callback)?.node;
110
+ if (!handler?.body || !handler.parameters[0] || active.has(handler)) return;
111
+ active.add(handler);
112
+ try {
113
+ const locals = new Map(frames).set(handler.parameters[0], scope);
114
+ visitRouteCalls(handler.body, call => readCall(call, locals));
115
+ } finally { active.delete(handler); }
116
+ };
283
117
 
284
- const importClause = child.namedChildren.find((c) => c.type === "import_clause");
285
- if (importClause) {
286
- for (const ic of importClause.namedChildren) {
287
- if (ic.type === "identifier") {
288
- resolvedImports.set(ic.text.trim(), targetFile);
289
- } else if (ic.type === "namespace_import") {
290
- const identNode = ic.namedChildren.find((n) => n.type === "identifier");
291
- if (identNode) resolvedImports.set(identNode.text.trim(), targetFile);
292
- } else if (ic.type === "named_imports") {
293
- for (const spec of ic.namedChildren) {
294
- if (spec.type === "import_specifier") {
295
- const alias = spec.childForFieldName("alias");
296
- const name = spec.childForFieldName("name") ?? spec.namedChildren[0];
297
- const ident = alias ? alias.text.trim() : name ? name.text.trim() : "";
298
- if (ident) resolvedImports.set(ident, targetFile);
299
- }
300
- }
301
- }
118
+ const readCall = (call: ts.CallExpression, frames: Frames) => {
119
+ signal?.throwIfAborted();
120
+ const member = call.expression;
121
+ if (call.questionDotToken || !ts.isPropertyAccessExpression(member) || member.questionDotToken) return;
122
+ const method = member.name.text;
123
+ if (!["use", "group", "route", "guard"].includes(method) && !verbs.has(method)) return;
124
+ const parent = instanceOf(member.expression, frames);
125
+ if (!parent) return;
126
+
127
+ if (method === "use") {
128
+ const use = (argument?: ts.Expression) => {
129
+ const value = bindings.value(argument);
130
+ if (!value) return;
131
+ if (ts.isArrayLiteralExpression(value)) {
132
+ for (const item of value.elements) if (!ts.isSpreadElement(item)) use(item);
133
+ return;
302
134
  }
303
- }
135
+ const plugin = instanceOf(value, frames);
136
+ if (plugin && plugin !== parent) {
137
+ mounted.add(plugin);
138
+ copyRoutes(parent, plugin, "");
139
+ } else if (!plugin) visitCallback(argument, parent, frames);
140
+ };
141
+ use(call.arguments[0]);
142
+ return;
304
143
  }
305
- }
306
-
307
- // 2. Walk call expressions for routes and sub-route mounts
308
- const walkCalls = (node: Parser.SyntaxNode): void => {
309
- if (node.type === "call_expression") {
310
- const fnNode = node.childForFieldName("function");
311
- if (fnNode && fnNode.type === "member_expression") {
312
- const objNode = fnNode.childForFieldName("object");
313
- const propNode = fnNode.childForFieldName("property");
314
- const argsNode = node.childForFieldName("arguments");
315
-
316
- if (objNode && propNode && argsNode) {
317
- const callerVar = objNode.text.trim();
318
- const methodName = propNode.text.trim();
319
- const lowerMethod = methodName.toLowerCase();
320
- const args = argsNode.namedChildren;
321
144
 
322
- // Route Mount / Plugin: app.use(subPlugin)
323
- if (lowerMethod === "use") {
324
- if (args.length >= 1 && args[0].type === "identifier") {
325
- mounts.push({
326
- file,
327
- relPath,
328
- callerVar,
329
- prefix: "",
330
- targetVar: args[0].text.trim(),
331
- line: node.startPosition.row + 1,
332
- });
333
- }
334
- } else if (lowerMethod === "group") {
335
- // Group scoping: app.group('/v1', (app) => ...)
336
- if (args.length >= 2) {
337
- const prefixLit = cleanLiteral(args[0]);
338
- const groupFn = args[1];
339
- if (prefixLit !== undefined && groupFn) {
340
- // Trace routes inside the group callback
341
- let scopedVar = callerVar;
342
- if (groupFn.type === "arrow_function" || groupFn.type === "function") {
343
- const paramsNode = groupFn.childForFieldName("parameters");
344
- if (paramsNode && paramsNode.namedChildren[0]) {
345
- scopedVar = paramsNode.namedChildren[0].text.trim();
346
- }
347
- }
348
- mounts.push({
349
- file,
350
- relPath,
351
- callerVar,
352
- prefix: prefixLit,
353
- targetVar: scopedVar,
354
- line: node.startPosition.row + 1,
355
- });
356
- }
357
- }
358
- } else if (ELYSIA_VERBS.has(lowerMethod)) {
359
- // Direct route: app.get('/path', handler, options) or app.post('/path', { body: ... }, handler)
360
- if (args.length >= 2) {
361
- const rawPath = cleanLiteral(args[0]);
362
- if (rawPath !== undefined) {
363
- let handlerNode: Parser.SyntaxNode | undefined;
364
- let optionsNode: Parser.SyntaxNode | undefined;
365
-
366
- for (let i = 1; i < args.length; i++) {
367
- const arg = args[i];
368
- if (arg.type === "object") {
369
- optionsNode = arg;
370
- } else if (
371
- arg.type === "identifier" ||
372
- arg.type === "member_expression" ||
373
- arg.type === "arrow_function" ||
374
- arg.type === "function" ||
375
- arg.type === "function_expression"
376
- ) {
377
- handlerNode = arg;
378
- }
379
- }
380
-
381
- if (!handlerNode && args.length >= 2) {
382
- handlerNode = args[1];
383
- }
384
-
385
- const validationSchema = this.extractValidationFromOptions(optionsNode, resolvedImports);
386
- const handler = this.extractSingleHandler(handlerNode || args[1]);
387
-
388
- routes.push({
389
- file,
390
- relPath,
391
- routerVar: callerVar,
392
- httpMethods: lowerMethod === "all" ? ["GET", "POST", "PUT", "DELETE"] : [lowerMethod.toUpperCase()],
393
- rawPath,
394
- validationSchema,
395
- handler,
396
- routeLine: node.startPosition.row + 1,
397
- });
398
- }
399
- }
400
- }
401
- }
145
+ if (method === "group" || method === "guard") {
146
+ if (method === "guard" && call.arguments.length < 2) {
147
+ parent.schema = schemaFor(call.arguments[0]) ?? parent.schema;
148
+ return;
402
149
  }
150
+ const threeArguments = method === "group" && call.arguments.length >= 3;
151
+ const sub = method === "group" ? literal(call.arguments[0]) : "";
152
+ const schema = schemaFor(threeArguments || method === "guard" ? call.arguments[method === "guard" ? 0 : 1] : undefined);
153
+ const child: Scope = { prefix: "", routes: new Map(), schema: schema ?? parent.schema };
154
+ visitCallback(call.arguments[threeArguments ? 2 : 1], child, frames);
155
+ if (sub !== undefined) copyRoutes(parent, child, sub);
156
+ return;
403
157
  }
404
158
 
405
- for (const child of node.namedChildren) {
406
- walkCalls(child);
407
- }
159
+ const rawMethod = method === "route" ? literal(call.arguments[0])?.toUpperCase() : method.toUpperCase();
160
+ if (!rawMethod || !/^[A-Z][A-Z0-9-]*$/.test(rawMethod) || parent.prefix === undefined) return;
161
+ const offset = method === "route" ? 1 : 0;
162
+ const local = literal(call.arguments[offset]);
163
+ const handler = call.arguments[offset + 1];
164
+ if (local === undefined || !handler) return;
165
+ put(parent, {
166
+ method: rawMethod === "ALL" ? "ANY" : rawMethod, uri: parent.prefix + leadingSlash(local),
167
+ call, handler, schema: schemaFor(call.arguments[offset + 2]) ?? parent.schema,
168
+ });
408
169
  };
409
170
 
410
- walkCalls(rootNode);
411
- return { routes, mounts, resolvedImports };
412
- }
171
+ const rootFrames: Frames = new Map();
172
+ const elysiaRouteHint = /\.(?:use|group|get|post|put|patch|delete|head|options|trace|connect|all|ws|route)\s*\(|\bnew\s+Elysia\b/;
173
+ bindings.visitModules(files, unit => visitRouteCalls(unit.source, call => readCall(call, rootFrames)), elysiaRouteHint);
413
174
 
414
- private extractValidationFromOptions(
415
- optsNode: Parser.SyntaxNode | undefined,
416
- resolvedImports: Map<string, string>
417
- ): { symbol: string; file?: string; line?: number } | undefined {
418
- if (!optsNode || optsNode.type !== "object") return undefined;
419
-
420
- for (const pair of optsNode.namedChildren) {
421
- if (pair.type === "pair") {
422
- const keyNode = pair.childForFieldName("key");
423
- const valNode = pair.childForFieldName("value");
424
- const keyText = keyNode ? keyNode.text.trim().replace(/^['"]|['"]$/g, "") : "";
425
-
426
- if (keyText === "body" && valNode) {
427
- const schemaSymbol = valNode.text.trim();
428
- const schemaIdent = schemaSymbol.replace(/^t\.[a-zA-Z0-9_]+\s*\(/, "").replace(/\)$/, "").trim();
429
- const targetIdent = schemaIdent.split(/[<({]/)[0].trim();
430
- const schemaFile = resolvedImports.get(targetIdent);
431
-
432
- return {
433
- symbol: targetIdent || schemaSymbol,
434
- file: schemaFile,
435
- line: pair.startPosition.row + 1,
436
- };
175
+ const slices: VerticalSliceCandidate[] = [];
176
+ for (const scope of scopes.values()) {
177
+ if (mounted.has(scope)) continue;
178
+ for (const route of scope.routes.values()) {
179
+ signal?.throwIfAborted();
180
+ const routeFile = fileOf(route.call);
181
+ const handler = bindings.handler(route.handler);
182
+ const action = handler ? (handler.name === "callback" ? "closure" : handler.name) : route.handler.getText();
183
+ const controllerFile = handler ? fileOf(handler.node) : null;
184
+ const controllerLine = handler ? lineOf(handler.node) : 0;
185
+ const controller = path.basename(controllerFile ?? routeFile).replace(/\.[^.]+$/, "");
186
+ const uri = route.uri || "/";
187
+ const chain: ExecutionChainNode[] = [{
188
+ stage: "ingress", symbol: route.method + " " + uri, file: routeFile, line: lineOf(route.call),
189
+ description: "Elysia Route Registration",
190
+ }];
191
+ if (route.schema) {
192
+ chain.push({
193
+ stage: "validation", symbol: route.schema.getText(), file: fileOf(route.schema), line: lineOf(route.schema),
194
+ description: "Elysia Route Schema Option",
195
+ });
437
196
  }
438
- }
439
- }
440
-
441
- return undefined;
442
- }
443
-
444
- private extractSingleHandler(node: Parser.SyntaxNode): { symbol: string; line: number; node: Parser.SyntaxNode } {
445
- const line = node.startPosition.row + 1;
446
- if (node.type === "identifier" || node.type === "member_expression") {
447
- return { symbol: node.text.trim(), line, node };
448
- }
449
- if (node.type === "arrow_function" || node.type === "function_expression" || node.type === "function") {
450
- const nameNode = node.childForFieldName("name");
451
- const name = nameNode ? nameNode.text.trim() : "closure";
452
- return { symbol: name, line, node };
453
- }
454
- return { symbol: "closure", line, node };
455
- }
456
-
457
- private resolvePrefixHierarchy(
458
- allMounts: ExtractedMount[],
459
- fileImports: Map<string, Map<string, string>>
460
- ): Map<string, string[]> {
461
- const parentMap = new Map<string, Array<{ parentKey: string; prefix: string }>>();
462
- const allRouterKeys = new Set<string>();
463
-
464
- for (const m of allMounts) {
465
- const parentKey = `${m.relPath}#${m.callerVar}`;
466
- allRouterKeys.add(parentKey);
467
-
468
- let targetKey: string | undefined;
469
- const importedFile = fileImports.get(m.relPath)?.get(m.targetVar);
470
- if (importedFile) {
471
- targetKey = `${importedFile}#${m.targetVar}`;
472
- } else {
473
- targetKey = `${m.relPath}#${m.targetVar}`;
474
- }
475
-
476
- allRouterKeys.add(targetKey);
477
- if (!parentMap.has(targetKey)) parentMap.set(targetKey, []);
478
- parentMap.get(targetKey)!.push({ parentKey, prefix: m.prefix });
479
- }
480
-
481
- const prefixesByRouter = new Map<string, string[]>();
482
-
483
- for (const rKey of allRouterKeys) {
484
- const parents = parentMap.get(rKey);
485
- if (!parents || parents.length === 0) {
486
- prefixesByRouter.set(rKey, [""]);
487
- }
488
- }
489
-
490
- const queue = Array.from(prefixesByRouter.keys());
491
- const visitedEdges = new Set<string>();
492
-
493
- while (queue.length > 0) {
494
- const current = queue.shift()!;
495
- const currentPrefixes = prefixesByRouter.get(current) ?? [""];
496
-
497
- for (const [targetKey, parents] of parentMap.entries()) {
498
- for (const p of parents) {
499
- if (p.parentKey === current) {
500
- const edgeKey = `${current}->${targetKey}:${p.prefix}`;
501
- if (visitedEdges.has(edgeKey)) continue;
502
- visitedEdges.add(edgeKey);
503
-
504
- const nextPrefixes = currentPrefixes.map((cp) => normalizeRouteUri(cp, p.prefix));
505
- const existing = prefixesByRouter.get(targetKey) ?? [];
506
- const merged = Array.from(new Set([...existing, ...nextPrefixes]));
507
- prefixesByRouter.set(targetKey, merged);
508
- queue.push(targetKey);
509
- }
197
+ if (handler && controllerFile) {
198
+ chain.push({
199
+ stage: "controller", symbol: action, file: controllerFile, line: controllerLine,
200
+ description: "Elysia Action Handler",
201
+ }, ...routeContext(handler, bindings, fileOf));
510
202
  }
203
+ slices.push({
204
+ domain_id: domainId ?? null, feature_key: `elysia.${controller.toLowerCase()}.${action}`,
205
+ http_method: route.method, route_uri: uri, route_name: `${controller}.${action}`,
206
+ controller_class: controller, action_name: action, controller_file: controllerFile,
207
+ controller_line: controllerLine, architecture_style: "mvc", entry_kind: "http_route",
208
+ execution_chain_json: JSON.stringify(chain),
209
+ });
511
210
  }
512
211
  }
513
-
514
- return prefixesByRouter;
515
- }
516
-
517
- private findSourceFiles(dir: string): string[] {
518
- const results: string[] = [];
519
- const traverse = (current: string) => {
520
- if (!fs.existsSync(current)) return;
521
- try {
522
- const entries = fs.readdirSync(current, { withFileTypes: true });
523
- for (const entry of entries) {
524
- if (isIgnoredDirectory(entry.name)) continue;
525
- const full = path.join(current, entry.name);
526
- if (entry.isDirectory()) {
527
- traverse(full);
528
- } else if (entry.isFile() && /\.(ts|js|tsx|jsx)$/.test(entry.name) && !entry.name.endsWith(".d.ts")) {
529
- results.push(full);
530
- }
531
- }
532
- } catch {}
533
- };
534
- traverse(dir);
535
- return results;
212
+ return slices;
536
213
  }
537
214
  }
538
-