@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.
- package/README.md +46 -45
- package/package.json +8 -6
- package/src/cli/commands/check.ts +41 -26
- package/src/cli/commands/hook.ts +77 -105
- package/src/cli/commands/init.ts +35 -9
- package/src/cli/commands/stats.ts +33 -0
- package/src/cli/commands/sync-progress.ts +71 -0
- package/src/cli/commands/sync.ts +35 -9
- package/src/cli/hook-payload.ts +43 -0
- package/src/cli/index.ts +15 -51
- package/src/cli/scaffold/harness-config.ts +48 -8
- package/src/cli/templates/hooks.ts +51 -27
- package/src/cli/templates/rules.ts +34 -49
- package/src/cli/templates/skill.ts +46 -35
- package/src/core/boundary/audit.ts +383 -0
- package/src/core/boundary/evaluator.ts +299 -178
- package/src/core/boundary/staged-auditor.ts +188 -34
- package/src/core/config/domain-ownership.ts +47 -0
- package/src/core/config/domain-registration.ts +141 -0
- package/src/core/config/loader.ts +82 -54
- package/src/core/config/schema.ts +24 -46
- package/src/core/database/client.ts +2 -0
- package/src/core/database/repositories/dependency.repository.ts +326 -543
- package/src/core/database/repositories/domain.repository.ts +48 -4
- package/src/core/database/repositories/file.repository.ts +10 -0
- package/src/core/database/repositories/symbol.repository.ts +97 -259
- package/src/core/database/repository.ts +138 -24
- package/src/core/database/schema.ts +28 -33
- package/src/core/discovery/declarative-routes.ts +69 -0
- package/src/core/discovery/framework-detector.ts +149 -0
- package/src/core/discovery/navigation.ts +269 -0
- package/src/core/discovery/topology-detector.ts +153 -170
- package/src/core/errors.ts +19 -0
- package/src/core/ingestion/pipeline.ts +378 -212
- package/src/core/parser/behavioral-analyzer.ts +26 -22
- package/src/core/parser/boundary-tracker.ts +15 -0
- package/src/core/parser/extractors/base.ts +16 -4
- package/src/core/parser/extractors/csharp.ts +9 -5
- package/src/core/parser/extractors/django-routing.ts +163 -0
- package/src/core/parser/extractors/django-semantic.ts +400 -516
- package/src/core/parser/extractors/elysia-semantic.ts +172 -496
- package/src/core/parser/extractors/express-semantic.ts +195 -398
- package/src/core/parser/extractors/fastapi-semantic.ts +182 -399
- package/src/core/parser/extractors/fastify-semantic.ts +216 -732
- package/src/core/parser/extractors/flask-semantic.ts +92 -388
- package/src/core/parser/extractors/go-routing.ts +344 -0
- package/src/core/parser/extractors/go-semantic.ts +210 -508
- package/src/core/parser/extractors/go.ts +6 -3
- package/src/core/parser/extractors/graphql-entrypoint.ts +146 -0
- package/src/core/parser/extractors/hono-semantic.ts +132 -530
- package/src/core/parser/extractors/java.ts +7 -5
- package/src/core/parser/extractors/laravel-routing.ts +263 -0
- package/src/core/parser/extractors/laravel-semantic.ts +169 -333
- package/src/core/parser/extractors/manifest-helpers.ts +64 -0
- package/src/core/parser/extractors/mcp-cli-dispatch.ts +268 -0
- package/src/core/parser/extractors/mcp-cli-semantic.ts +84 -336
- package/src/core/parser/extractors/nestjs-semantic.ts +238 -510
- package/src/core/parser/extractors/nextjs-semantic.ts +164 -0
- package/src/core/parser/extractors/php-ast-helpers.ts +51 -0
- package/src/core/parser/extractors/php.ts +17 -1
- package/src/core/parser/extractors/python-route-ast.ts +249 -0
- package/src/core/parser/extractors/python.ts +9 -8
- package/src/core/parser/extractors/registry.ts +28 -5
- package/src/core/parser/extractors/route-prefixes.ts +43 -0
- package/src/core/parser/extractors/ruby.ts +10 -7
- package/src/core/parser/extractors/rust.ts +35 -17
- package/src/core/parser/extractors/semantic-extractor.interface.ts +3 -1
- package/src/core/parser/extractors/symfony-routing.ts +114 -0
- package/src/core/parser/extractors/symfony-semantic.ts +75 -262
- package/src/core/parser/extractors/typescript-bindings.ts +333 -0
- package/src/core/parser/extractors/typescript-compiler-fallback.ts +380 -0
- package/src/core/parser/extractors/typescript-fallback.ts +207 -0
- package/src/core/parser/extractors/typescript-route-context.ts +58 -0
- package/src/core/parser/extractors/typescript.ts +36 -216
- package/src/core/parser/implementation-fingerprint.ts +97 -0
- package/src/core/parser/language-capabilities.ts +23 -7
- package/src/core/parser/schema/providers/laravel-migration-provider.ts +77 -51
- package/src/core/parser/schema/schema-provider-registry.ts +1 -3
- package/src/core/parser/schema/schema-provider.interface.ts +2 -1
- package/src/core/parser/semantic-revision.ts +3 -0
- package/src/core/parser/static-string.ts +51 -0
- package/src/core/parser/wasm-loader.ts +6 -2
- package/src/core/resolver/ast-method-tracer.ts +230 -0
- package/src/core/resolver/call-graph-helpers.ts +72 -0
- package/src/core/resolver/call-graph-tracer.ts +375 -311
- package/src/core/resolver/dependency-analysis.ts +593 -0
- package/src/core/resolver/import-candidates.ts +120 -0
- package/src/core/resolver/import-evidence.ts +88 -0
- package/src/core/resolver/import-resolver.ts +162 -181
- package/src/core/resolver/interpretation-inputs.ts +65 -0
- package/src/core/resolver/languages/go.ts +103 -0
- package/src/core/resolver/languages/managed.ts +200 -0
- package/src/core/resolver/languages/python.ts +133 -0
- package/src/core/resolver/languages/ruby.ts +40 -0
- package/src/core/resolver/languages/rust.ts +127 -0
- package/src/core/resolver/languages/shared.ts +74 -0
- package/src/core/resolver/module-resolver.ts +18 -7
- package/src/core/resolver/path-resolver.ts +6 -3
- package/src/core/resolver/polyglot-slice-tracer.ts +197 -0
- package/src/core/resolver/slice-catalog.ts +94 -0
- package/src/core/resolver/slice-format.ts +22 -0
- package/src/core/resolver/slice-selection.ts +237 -0
- package/src/core/resolver/symbol-impact.ts +477 -0
- package/src/core/resolver/symbol-locator.ts +82 -15
- package/src/core/resolver/vertical-slice-tracer.ts +57 -278
- package/src/core/resources/ignore.ts +21 -1
- package/src/core/resources/limits.ts +2 -1
- package/src/core/resources/source-files.ts +143 -20
- package/src/core/resources/source-inventory.ts +55 -0
- package/src/core/resources/work-queue.ts +167 -4
- package/src/core/retrieval/context-page.ts +116 -0
- package/src/core/retrieval/context.ts +457 -0
- package/src/core/retrieval/resolution-warnings.ts +21 -0
- package/src/core/retrieval/source-context.ts +448 -0
- package/src/core/retrieval/symbol-details.ts +453 -0
- package/src/core/retrieval/symbol-evidence.ts +97 -0
- package/src/core/retrieval/typescript-references.ts +293 -0
- package/src/core/retrieval/universal-context.ts +182 -0
- package/src/core/telemetry/summary.ts +114 -0
- package/src/core/telemetry/telemetry.ts +225 -37
- package/src/index.ts +0 -3
- package/src/mcp/formatters/compact-text.ts +439 -0
- package/src/mcp/resources-and-prompts.ts +253 -0
- package/src/mcp/schemas/boundary.ts +145 -0
- package/src/mcp/schemas/map.ts +250 -0
- package/src/mcp/schemas/shared.ts +52 -0
- package/src/mcp/schemas/slice.ts +60 -0
- package/src/mcp/schemas/symbol.ts +268 -0
- package/src/mcp/schemas.ts +5 -1105
- package/src/mcp/server.ts +263 -597
- package/src/mcp/tool-catalog.ts +331 -0
- package/src/mcp/tools/boundary.ts +69 -4
- package/src/mcp/tools/map.ts +126 -0
- package/src/mcp/tools/slice.ts +101 -3
- package/src/mcp/tools/symbol.ts +480 -26
- package/src/mcp/ui/app-client.ts +899 -0
- package/src/mcp/ui/app.html +478 -0
- package/src/mcp/workflow-playbooks.ts +181 -0
- package/src/mcp/workspace-boundary.ts +50 -0
- package/src/mcp/workspace-manager.ts +102 -18
- package/src/mcp/workspace-watcher.ts +38 -19
- package/src/types/index.ts +47 -53
- package/src/cli/commands/topology.ts +0 -161
- package/src/core/database/repositories/environment.repository.ts +0 -207
- package/src/core/parser/schema/providers/prisma-schema-provider.ts +0 -90
- package/src/core/session/session-manager.ts +0 -107
- package/src/core/topology/environment-detector.ts +0 -973
- package/src/core/topology/types.ts +0 -83
- package/src/mcp/tools/check-boundary.ts +0 -387
- package/src/mcp/tools/domain.ts +0 -40
- package/src/mcp/tools/feature.ts +0 -67
- package/src/mcp/tools/get-domain-catalog.ts +0 -226
- package/src/mcp/tools/get-environment-topology.ts +0 -138
- package/src/mcp/tools/get-feature-context.ts +0 -224
- package/src/mcp/tools/get-symbol-hotspots.ts +0 -54
- package/src/mcp/tools/get-symbol-impact.ts +0 -64
- package/src/mcp/tools/get-symbol.ts +0 -175
- package/src/mcp/tools/locate-symbol.ts +0 -196
- package/src/mcp/tools/register-domain.ts +0 -75
- package/src/mcp/tools/register-feature.ts +0 -110
- package/src/mcp/tools/trace-vertical-slice.ts +0 -80
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
import * as path from "node:path";
|
|
2
|
+
import { blankCommentsAndStrings } from "../../parser/boundary-tracker.ts";
|
|
3
|
+
import { probeSourcePath, readSourceDirectory } from "../../resources/source-files.ts";
|
|
4
|
+
import { ancestors, fileResult, packageResult, walkFiles, literalString, type ResolutionIO } from "./shared.ts";
|
|
5
|
+
|
|
6
|
+
function xmlValues(text: string, tag: string): string[] {
|
|
7
|
+
return [...text.replace(new RegExp("<!--[\\s\\S]*?-->", "g"), "").matchAll(new RegExp(`<${tag}(?:\\s[^>]*)?>([^<]*)</${tag}>`, "g"))]
|
|
8
|
+
.map(match => literalString(match[1]!.trim().replace(/&/g, "&"), "dynamic_project_path"));
|
|
9
|
+
}
|
|
10
|
+
function xmlAttributes(text: string, tag: string, attribute: string): string[] {
|
|
11
|
+
return [...text.replace(new RegExp("<!--[\\s\\S]*?-->", "g"), "").matchAll(new RegExp(`<${tag}\\b([^>]*)>`, "g"))].flatMap(match => {
|
|
12
|
+
const value = new RegExp(`\\b${attribute}\\s*=\\s*["']([^"']+)["']`).exec(match[1]!);
|
|
13
|
+
return value ? [literalString(value[1]!.replace(/&/g, "&").replace(/\\/g, "/"), "dynamic_project_path")] : [];
|
|
14
|
+
});
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function javaRoots(io: ResolutionIO, source: string, state: { conditional: boolean }): string[] {
|
|
18
|
+
const testSource = /(?:^|\/)src\/test\//.test(source);
|
|
19
|
+
const dirs = ancestors(io, source);
|
|
20
|
+
const projects = dirs.map(dir => ({ dir, pom: io.read(path.join(dir, "pom.xml")),
|
|
21
|
+
gradle: io.read(path.join(dir, "build.gradle")) ?? io.read(path.join(dir, "build.gradle.kts")) }));
|
|
22
|
+
const nearest = projects.find(project => project.pom !== undefined || project.gradle !== undefined);
|
|
23
|
+
if (!nearest) return [io.root];
|
|
24
|
+
if (nearest.pom !== undefined) {
|
|
25
|
+
const catalog = new Map<string, { directory: string; text: string }>();
|
|
26
|
+
const visit = (directory: string, seen = new Set<string>()): void => {
|
|
27
|
+
io.check(directory);
|
|
28
|
+
if (seen.has(directory) || seen.size > 128) throw new Error("maven_module_cycle_or_limit");
|
|
29
|
+
seen.add(directory);
|
|
30
|
+
const raw = io.read(path.join(directory, "pom.xml")); if (raw === undefined) throw new Error("maven_module_missing");
|
|
31
|
+
const text = raw.replace(new RegExp("<!--[\\s\\S]*?-->", "g"), "");
|
|
32
|
+
catalog.set(directory, { directory, text });
|
|
33
|
+
const modules = xmlValues(text, "module");
|
|
34
|
+
for (const module of modules) visit(path.resolve(directory, module), seen);
|
|
35
|
+
};
|
|
36
|
+
const aggregate = [...projects].reverse().find(project => project.pom !== undefined) ?? nearest;
|
|
37
|
+
visit(aggregate.dir);
|
|
38
|
+
if (!catalog.has(nearest.dir)) visit(nearest.dir);
|
|
39
|
+
const selected = new Set<string>();
|
|
40
|
+
const roots: string[] = [];
|
|
41
|
+
const include = (directory: string): void => {
|
|
42
|
+
if (selected.has(directory)) return;
|
|
43
|
+
selected.add(directory);
|
|
44
|
+
const project = catalog.get(directory)!;
|
|
45
|
+
state.conditional ||= /<(?:profiles|activation)\b/.test(project.text);
|
|
46
|
+
const testRoots = directory === nearest.dir && testSource ? ["src/test/java", ...xmlValues(project.text, "testSourceDirectory")] : [];
|
|
47
|
+
for (const root of ["src/main/java", ...xmlValues(project.text, "sourceDirectory"), ...testRoots]) roots.push(path.resolve(directory, root));
|
|
48
|
+
const active = project.text.replace(/<dependencyManagement>[\s\S]*?<\/dependencyManagement>/g, "");
|
|
49
|
+
for (const block of active.matchAll(/<dependency>\s*([\s\S]*?)<\/dependency>/g)) {
|
|
50
|
+
const group = xmlValues(block[1]!, "groupId")[0], artifact = xmlValues(block[1]!, "artifactId")[0];
|
|
51
|
+
const matches = [...catalog.values()].filter(candidate => {
|
|
52
|
+
const header = candidate.text.split(/<(?:dependencies|dependencyManagement|build)>/)[0]!;
|
|
53
|
+
const ids = xmlValues(header, "artifactId");
|
|
54
|
+
return ids.at(-1) === artifact && xmlValues(header, "groupId").includes(group ?? "");
|
|
55
|
+
});
|
|
56
|
+
if (matches.length > 1) throw new Error("maven_project_dependency_ambiguous");
|
|
57
|
+
if (matches[0]) include(matches[0].directory);
|
|
58
|
+
}
|
|
59
|
+
};
|
|
60
|
+
include(nearest.dir); return roots;
|
|
61
|
+
}
|
|
62
|
+
const roots = [path.join(nearest.dir, "src/main/java"), ...(testSource ? [path.join(nearest.dir, "src/test/java")] : [])];
|
|
63
|
+
if (/\bsourceSets\b|\bsrcDirs?\b/.test(nearest.gradle!)) throw new Error("gradle_custom_sources_not_supported");
|
|
64
|
+
const settings = projects.map(project => ({ dir: project.dir,
|
|
65
|
+
text: io.read(path.join(project.dir, "settings.gradle")) ?? io.read(path.join(project.dir, "settings.gradle.kts")) })).find(project => project.text !== undefined);
|
|
66
|
+
const declared = new Set<string>();
|
|
67
|
+
if (settings) {
|
|
68
|
+
if (/\.projectDir\b|\bincludeBuild\b/.test(settings.text!)) throw new Error("gradle_custom_project_layout");
|
|
69
|
+
const mask = blankCommentsAndStrings(settings.text!);
|
|
70
|
+
for (const include of settings.text!.matchAll(/\binclude\b([^\n]+)/g)) {
|
|
71
|
+
if (!/^include\b/.test(mask.slice(include.index!))) continue;
|
|
72
|
+
for (const name of include[1]!.matchAll(/["'](:?[\w:-]+)["']/g)) declared.add(name[1]!.replace(/^:?/, ":"));
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
const gradleMask = blankCommentsAndStrings(nearest.gradle!);
|
|
76
|
+
state.conditional ||= /\b(?:if|when|findProperty|providers)\b/.test(gradleMask);
|
|
77
|
+
for (const match of nearest.gradle!.matchAll(/\bproject\s*\(\s*["'](:[\w:-]+)["']\s*\)/g)) {
|
|
78
|
+
if (!/^project\b/.test(gradleMask.slice(match.index!))) continue;
|
|
79
|
+
if (!settings || !declared.has(match[1]!)) throw new Error("gradle_project_not_declared");
|
|
80
|
+
const directory = path.join(settings.dir, match[1]!.slice(1).replace(/:/g, "/"));
|
|
81
|
+
const build = io.read(path.join(directory, "build.gradle")) ?? io.read(path.join(directory, "build.gradle.kts"));
|
|
82
|
+
if (build === undefined || /\bsourceSets\b|\bsrcDirs?\b/.test(build)) throw new Error("gradle_project_sources_not_supported");
|
|
83
|
+
roots.push(path.join(directory, "src/main/java"));
|
|
84
|
+
}
|
|
85
|
+
return roots;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export function resolveJava(io: ResolutionIO, target: string, source: string, statement?: string) {
|
|
89
|
+
const raw = (statement ?? target).replace(/^\s*import\s+(?:static\s+)?/, "").replace(/;\s*$/, "").trim();
|
|
90
|
+
if (raw.startsWith("java.")) return io.finish("external", "java_platform_package");
|
|
91
|
+
const wildcard = raw.endsWith(".*");
|
|
92
|
+
const requested = wildcard ? raw.slice(0, -2) : raw;
|
|
93
|
+
const state = { conditional: false };
|
|
94
|
+
const files = [...new Set(javaRoots(io, source, state).flatMap(root => walkFiles(io, root, file => file.endsWith(".java"))))];
|
|
95
|
+
const candidates: string[] = [];
|
|
96
|
+
for (const file of files) {
|
|
97
|
+
const mask = blankCommentsAndStrings(io.read(file)!);
|
|
98
|
+
const pkg = /\bpackage\s+([\w.]+)\s*;/.exec(mask)?.[1] ?? "";
|
|
99
|
+
const types = declarationScopes(mask, /\b(?:class|interface|enum|record)\s+([A-Za-z_]\w*)/g);
|
|
100
|
+
const matchingType = types.find(type => {
|
|
101
|
+
const qualified = [pkg, type.name].filter(Boolean).join(".");
|
|
102
|
+
if (requested === qualified) return true;
|
|
103
|
+
if (!/^\s*import\s+static\b/.test(statement ?? "") || !requested.startsWith(qualified + ".")) return false;
|
|
104
|
+
const member = requested.slice(qualified.length + 1);
|
|
105
|
+
return !member.includes(".") && new RegExp(`\\bstatic\\b[^;{}]*\\b${member}\\b`).test(mask.slice(type.start, type.end));
|
|
106
|
+
});
|
|
107
|
+
if (wildcard && requested === pkg || matchingType)
|
|
108
|
+
candidates.push(path.relative(io.root, file).replace(/\\/g, "/"));
|
|
109
|
+
}
|
|
110
|
+
const result = wildcard && candidates.length ? packageResult(io, candidates, "java_source_package")
|
|
111
|
+
: fileResult(io, candidates, candidates.length ? "java_source_type" : "java_classpath_not_established");
|
|
112
|
+
if (state.conditional) result.coverage = "conditional";
|
|
113
|
+
return result;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
interface Scope { name: string; start: number; end: number }
|
|
117
|
+
function closingBrace(mask: string, open: number): number {
|
|
118
|
+
let depth = 1;
|
|
119
|
+
for (let pos = open + 1; pos < mask.length; pos++) {
|
|
120
|
+
if (mask[pos] === "{") depth++;
|
|
121
|
+
if (mask[pos] === "}" && --depth === 0) return pos;
|
|
122
|
+
}
|
|
123
|
+
return mask.length;
|
|
124
|
+
}
|
|
125
|
+
function declarationScopes(mask: string, pattern: RegExp, fileScoped = false): Scope[] {
|
|
126
|
+
const scopes: Scope[] = [];
|
|
127
|
+
for (const match of mask.matchAll(pattern)) {
|
|
128
|
+
const parent = scopes.filter(scope => scope.start < match.index! && scope.end > match.index!).at(-1);
|
|
129
|
+
const delimiter = /[;{]/g; delimiter.lastIndex = match.index! + match[0].length;
|
|
130
|
+
const found = delimiter.exec(mask);
|
|
131
|
+
const end = found?.[0] === "{" ? closingBrace(mask, found.index) : fileScoped ? mask.length : found?.index ?? mask.length;
|
|
132
|
+
scopes.push({ name: [parent?.name, match[1]].filter(Boolean).join("."), start: match.index!, end });
|
|
133
|
+
}
|
|
134
|
+
return scopes;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function glob(pattern: string, file: string): boolean {
|
|
138
|
+
const escaped = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*\*\//g, "@@DIR@@").replace(/\*\*/g, "@@ALL@@").replace(/\*/g, "[^/]*").replace(/\?/g, "[^/]").replace(/@@DIR@@/g, "(?:.*/)?").replace(/@@ALL@@/g, ".*");
|
|
139
|
+
return new RegExp(`^${escaped}$`).test(file);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
export function resolveCSharp(io: ResolutionIO, target: string, source: string, statement?: string) {
|
|
143
|
+
const raw = (statement ?? target).replace(/^\s*(?:global\s+)?using\s+(?:static\s+)?/, "").replace(/;\s*$/, "").trim();
|
|
144
|
+
const requested = (raw.includes("=") ? raw.slice(raw.indexOf("=") + 1).trim() : raw).replace(/^global::/, "");
|
|
145
|
+
const dirs = ancestors(io, source);
|
|
146
|
+
let project: string | undefined;
|
|
147
|
+
for (const dir of dirs) {
|
|
148
|
+
if (probeSourcePath(dir) !== "directory") continue;
|
|
149
|
+
const projects = readSourceDirectory(dir).filter(entry => entry.isFile() && entry.name.endsWith(".csproj")).map(entry => path.join(dir, entry.name));
|
|
150
|
+
if (projects.length > 1) return io.finish("ambiguous", "csharp_source_project_ambiguous");
|
|
151
|
+
if (projects[0]) { project = projects[0]; break; }
|
|
152
|
+
}
|
|
153
|
+
let conditional = false;
|
|
154
|
+
const files = new Set<string>(); const visited = new Set<string>();
|
|
155
|
+
const visit = (file: string): void => {
|
|
156
|
+
if (visited.has(file)) return;
|
|
157
|
+
if (visited.size >= 128) throw new Error("csharp_project_limit");
|
|
158
|
+
visited.add(file); io.check(file);
|
|
159
|
+
const text = io.read(file); if (text === undefined) throw new Error("csharp_project_missing");
|
|
160
|
+
conditional ||= /\bCondition\s*=|<(?:Import|Choose|Target)\b/.test(text);
|
|
161
|
+
const directory = path.dirname(file);
|
|
162
|
+
const include = xmlAttributes(text, "Compile", "Include");
|
|
163
|
+
const remove = xmlAttributes(text, "Compile", "Remove");
|
|
164
|
+
const defaults = !/<EnableDefaultCompileItems>\s*false\s*<\//.test(text);
|
|
165
|
+
const searchRoots = [directory, ...include.flatMap(pattern => pattern.split(";").map(part => {
|
|
166
|
+
const firstGlob = part.search(/[?*]/);
|
|
167
|
+
return path.dirname(path.resolve(directory, firstGlob < 0 ? part : part.slice(0, firstGlob) + "placeholder"));
|
|
168
|
+
}))];
|
|
169
|
+
for (const sourceFile of [...new Set(searchRoots.flatMap(search => walkFiles(io, search, candidate => candidate.endsWith(".cs"))))]) {
|
|
170
|
+
const rel = path.relative(directory, sourceFile).replace(/\\/g, "/");
|
|
171
|
+
if ((defaults || include.some(pattern => pattern.split(";").some(p => glob(p, rel)))) && !remove.some(pattern => pattern.split(";").some(p => glob(p, rel)))) files.add(sourceFile);
|
|
172
|
+
}
|
|
173
|
+
for (const reference of xmlAttributes(text, "ProjectReference", "Include")) visit(path.resolve(directory, reference));
|
|
174
|
+
};
|
|
175
|
+
if (project) visit(project); else for (const file of walkFiles(io, io.root, file => file.endsWith(".cs"))) files.add(file);
|
|
176
|
+
const matches: string[] = [];
|
|
177
|
+
let namespaceMatch = false;
|
|
178
|
+
const matchedTypes: { file: string; partial: boolean }[] = [];
|
|
179
|
+
for (const file of files) {
|
|
180
|
+
const mask = blankCommentsAndStrings(io.read(file)!);
|
|
181
|
+
conditional ||= /^\s*#\s*(?:if|elif)\b/m.test(mask);
|
|
182
|
+
const namespaces = declarationScopes(mask, /\bnamespace\s+([\w.]+)/g, true);
|
|
183
|
+
const types = declarationScopes(mask, /\b(?:class|interface|struct|enum|record(?:\s+(?:class|struct))?)\s+([A-Za-z_]\w*)/g);
|
|
184
|
+
const inNamespace = namespaces.some(namespace => namespace.name === requested);
|
|
185
|
+
namespaceMatch ||= inNamespace;
|
|
186
|
+
const declaredType = types.find(type => {
|
|
187
|
+
const owner = namespaces.filter(namespace => namespace.start < type.start && namespace.end > type.start).at(-1);
|
|
188
|
+
return [owner?.name, type.name].filter(Boolean).join(".") === requested;
|
|
189
|
+
});
|
|
190
|
+
if (declaredType) matchedTypes.push({ file, partial: /\bpartial\s*$/.test(mask.slice(Math.max(0, declaredType.start - 32), declaredType.start)) });
|
|
191
|
+
if (inNamespace || declaredType)
|
|
192
|
+
matches.push(path.relative(io.root, file).replace(/\\/g, "/"));
|
|
193
|
+
}
|
|
194
|
+
if (matchedTypes.length > 1 && !matchedTypes.every(type => type.partial) || namespaceMatch && matchedTypes.length)
|
|
195
|
+
return io.finish("ambiguous", "csharp_type_or_namespace_ambiguous");
|
|
196
|
+
if (!matches.length && (requested === "System" || requested.startsWith("System."))) return io.finish("external", "csharp_platform_namespace");
|
|
197
|
+
const result = packageResult(io, matches, matches.length ? "csharp_source_namespace_or_type" : "csharp_namespace_not_established");
|
|
198
|
+
if (conditional) result.coverage = "conditional";
|
|
199
|
+
return result;
|
|
200
|
+
}
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import * as path from "node:path";
|
|
2
|
+
import { ancestors, existingFiles, fileResult, toml, type ResolutionIO } from "./shared.ts";
|
|
3
|
+
|
|
4
|
+
const DIST_MODULES: Record<string, string[]> = {
|
|
5
|
+
pillow: ["pil"], pyyaml: ["yaml"], python_dotenv: ["dotenv"], scikit_learn: ["sklearn"],
|
|
6
|
+
beautifulsoup4: ["bs4"], opencv_python: ["cv2"], protobuf: ["google"], typing_extensions: ["typing_extensions"],
|
|
7
|
+
pyjwt: ["jwt"], python_jose: ["jose"], python_dateutil: ["dateutil"], django_rest_framework: ["rest_framework"],
|
|
8
|
+
djangorestframework: ["rest_framework"], psycopg2_binary: ["psycopg2"], opencv_python_headless: ["cv2"],
|
|
9
|
+
graphql_core: ["graphql"], graphql: ["graphql"], graphene: ["graphene"], strawberry_graphql: ["strawberry"],
|
|
10
|
+
};
|
|
11
|
+
const manifests = ["requirements.txt", "pyproject.toml", "Pipfile", "poetry.lock", "uv.lock", "Pipfile.lock"];
|
|
12
|
+
const normalize = (name: string) => name.toLowerCase().replace(/[-_.]+/g, "_");
|
|
13
|
+
|
|
14
|
+
function distribution(value: string): string | undefined {
|
|
15
|
+
return /^\s*([A-Za-z0-9][A-Za-z0-9_.-]*)/.exec(value)?.[1];
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function declaredDependencies(io: ResolutionIO, owner: string): { packages: Set<string>; local: Map<string, string> } {
|
|
19
|
+
const cacheKey = `py_deps:${owner}`;
|
|
20
|
+
const cached = io.cache?.get(cacheKey) as { packages: Set<string>; local: Map<string, string>; files: string[] } | undefined;
|
|
21
|
+
if (cached) {
|
|
22
|
+
// Still touch manifests via io.read so config_revision reflects all observed manifests
|
|
23
|
+
for (const file of cached.files) io.read(file);
|
|
24
|
+
return cached;
|
|
25
|
+
}
|
|
26
|
+
const observedFiles: string[] = [];
|
|
27
|
+
const readManifest = (file: string): string | undefined => {
|
|
28
|
+
observedFiles.push(file);
|
|
29
|
+
return io.read(file);
|
|
30
|
+
};
|
|
31
|
+
const packages = new Set<string>();
|
|
32
|
+
const local = new Map<string, string>();
|
|
33
|
+
const add = (name: string) => { packages.add(normalize(name)); };
|
|
34
|
+
const requirementFile = (file: string, visited = new Set<string>()): void => {
|
|
35
|
+
if (visited.has(file) || visited.size >= 64) throw new Error("python_requirements_cycle_or_limit");
|
|
36
|
+
visited.add(file);
|
|
37
|
+
const text = readManifest(file);
|
|
38
|
+
if (text === undefined) throw new Error("python_requirements_include_missing");
|
|
39
|
+
for (const raw of text.replace(/\\\r?\n/g, " ").split(/\r?\n/)) {
|
|
40
|
+
const line = raw.replace(/\s+#.*$/, "").trim();
|
|
41
|
+
if (!line || line.startsWith("#")) continue;
|
|
42
|
+
const include = /^(?:-r\s*|--requirement(?:=|\s+))(.+)$/.exec(line);
|
|
43
|
+
if (include) { requirementFile(path.resolve(path.dirname(file), include[1]!.trim()), new Set(visited)); continue; }
|
|
44
|
+
// Constraints restrict versions but do not declare installed distributions.
|
|
45
|
+
if (line.startsWith("-")) continue;
|
|
46
|
+
const name = distribution(line); if (name) add(name);
|
|
47
|
+
}
|
|
48
|
+
};
|
|
49
|
+
if (readManifest(path.join(owner, "requirements.txt")) !== undefined) requirementFile(path.join(owner, "requirements.txt"));
|
|
50
|
+
const projectText = readManifest(path.join(owner, "pyproject.toml"));
|
|
51
|
+
if (projectText !== undefined) {
|
|
52
|
+
const project = toml(projectText);
|
|
53
|
+
const arrays = [project.project?.dependencies, ...Object.values(project.project?.["optional-dependencies"] ?? {}),
|
|
54
|
+
...Object.values(project["dependency-groups"] ?? {})];
|
|
55
|
+
for (const values of arrays) {
|
|
56
|
+
if (values === undefined) continue;
|
|
57
|
+
if (!Array.isArray(values)) throw new Error("malformed_python_dependencies");
|
|
58
|
+
for (const value of values) if (typeof value === "string") { const name = distribution(value); if (name) add(name); }
|
|
59
|
+
}
|
|
60
|
+
const poetry = project.tool?.poetry;
|
|
61
|
+
for (const group of [poetry?.dependencies, poetry?.["dev-dependencies"],
|
|
62
|
+
...Object.values(poetry?.group ?? {}).map((group: any) => group.dependencies)]) {
|
|
63
|
+
for (const [name, value] of Object.entries(group ?? {})) if (name !== "python") {
|
|
64
|
+
add(name);
|
|
65
|
+
if (typeof (value as any)?.path === "string") local.set(normalize(name), path.resolve(owner, (value as any).path));
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
const pipfile = readManifest(path.join(owner, "Pipfile"));
|
|
70
|
+
if (pipfile !== undefined) {
|
|
71
|
+
const parsed = toml(pipfile);
|
|
72
|
+
for (const group of [parsed.packages, parsed["dev-packages"]]) for (const [name, value] of Object.entries(group ?? {})) {
|
|
73
|
+
add(name); if (typeof (value as any)?.path === "string") local.set(normalize(name), path.resolve(owner, (value as any).path));
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
for (const name of ["poetry.lock", "uv.lock"]) {
|
|
77
|
+
const text = readManifest(path.join(owner, name));
|
|
78
|
+
if (text === undefined) continue;
|
|
79
|
+
const locked = toml(text).package;
|
|
80
|
+
if (!Array.isArray(locked)) throw new Error("malformed_python_lockfile");
|
|
81
|
+
for (const pkg of locked) if (typeof pkg.name === "string") {
|
|
82
|
+
add(pkg.name);
|
|
83
|
+
const location = pkg.source?.editable ?? pkg.source?.directory ?? pkg.source?.virtual ??
|
|
84
|
+
(pkg.source?.type === "directory" ? pkg.source.url : undefined);
|
|
85
|
+
if (typeof location === "string") local.set(normalize(pkg.name), path.resolve(owner, location));
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
const piplock = readManifest(path.join(owner, "Pipfile.lock"));
|
|
89
|
+
if (piplock !== undefined) {
|
|
90
|
+
const parsed = JSON.parse(piplock);
|
|
91
|
+
for (const group of [parsed.default, parsed.develop]) for (const [name, value] of Object.entries(group ?? {})) {
|
|
92
|
+
add(name); if (typeof (value as any)?.path === "string") local.set(normalize(name), path.resolve(owner, (value as any).path));
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
const result = { packages, local, files: [...new Set(observedFiles)] };
|
|
96
|
+
io.cache?.set(cacheKey, result);
|
|
97
|
+
return result;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export function resolvePython(io: ResolutionIO, target: string, source: string, roots: string[], stdlib: ReadonlySet<string>) {
|
|
101
|
+
const dirs = ancestors(io, source);
|
|
102
|
+
if (target.startsWith(".")) {
|
|
103
|
+
const dots = /^\.+/.exec(target)![0].length;
|
|
104
|
+
const rest = target.slice(dots).replace(/\./g, path.sep);
|
|
105
|
+
const base = path.resolve(dirs[0]!, "../".repeat(dots - 1), rest);
|
|
106
|
+
return fileResult(io, existingFiles(io, [...(rest ? [base + ".py"] : []), path.join(base, "__init__.py")]), "python_relative_module");
|
|
107
|
+
}
|
|
108
|
+
let owner = io.root;
|
|
109
|
+
for (const dir of dirs) {
|
|
110
|
+
// Observe absent manifests too, so later creation invalidates the selection.
|
|
111
|
+
const present = manifests.map(file => io.read(path.join(dir, file)) !== undefined);
|
|
112
|
+
if (present.some(Boolean)) { owner = dir; break; }
|
|
113
|
+
}
|
|
114
|
+
const top = target.split(".")[0]!;
|
|
115
|
+
if (stdlib.has(top)) return io.finish("external", "python_standard_library");
|
|
116
|
+
const { packages, local: dependencyPaths } = declaredDependencies(io, owner);
|
|
117
|
+
const normalized = normalize(top);
|
|
118
|
+
for (const [name, directory] of dependencyPaths) {
|
|
119
|
+
if (name !== normalized && !DIST_MODULES[name]?.includes(normalized)) continue;
|
|
120
|
+
const subpath = target.replace(/\./g, path.sep);
|
|
121
|
+
return fileResult(io, existingFiles(io, [directory, path.join(directory, "src")].flatMap(base =>
|
|
122
|
+
[path.join(base, subpath + ".py"), path.join(base, subpath, "__init__.py")])), "python_local_path_dependency");
|
|
123
|
+
}
|
|
124
|
+
const isManifestDep = packages.has(normalized) || Object.entries(DIST_MODULES).some(([dist, modules]) => packages.has(dist) && modules.includes(normalized));
|
|
125
|
+
if (isManifestDep) return io.finish("external", "python_manifest_dependency");
|
|
126
|
+
|
|
127
|
+
const search = [...new Set([path.join(owner, "src"), owner, dirs[0]!, ...roots.map(root => path.resolve(io.root, root))])];
|
|
128
|
+
const subpath = target.replace(/\./g, path.sep);
|
|
129
|
+
const local = existingFiles(io, search.flatMap(root => [path.join(root, subpath + ".py"), path.join(root, subpath, "__init__.py")]));
|
|
130
|
+
if (local.length) return fileResult(io, local, local.length === 1 ? "python_local_module" : "multiple_python_candidates");
|
|
131
|
+
|
|
132
|
+
return io.finish("unresolved", "python_module_not_declared");
|
|
133
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import * as path from "node:path";
|
|
2
|
+
import { blankCommentsAndStrings } from "../../parser/boundary-tracker.ts";
|
|
3
|
+
import { ancestors, existingFiles, fileResult, type ResolutionIO } from "./shared.ts";
|
|
4
|
+
|
|
5
|
+
const STDLIB = new Set("abbrev base64 benchmark bigdecimal bundler cgi csv date delegate digest drb english erb etc fcntl fiddle fileutils find forwardable io ipaddr irb json logger monitor mutex_m net objspace observer open-uri openssl optparse ostruct pathname pp prettyprint pstore psych racc rdoc readline resolv rexml ripper securerandom set shellwords singleton socket stringio strscan tempfile time timeout tmpdir tsort uri weakref yaml zlib".split(" "));
|
|
6
|
+
const GEM_IMPORTS: Record<string, string[]> = { activerecord: ["active_record"], activesupport: ["active_support"], actionpack: ["action_controller", "action_dispatch"], railties: ["rails"], nokogiri: ["nokogiri"], concurrent_ruby: ["concurrent"] };
|
|
7
|
+
|
|
8
|
+
export function resolveRuby(io: ResolutionIO, target: string, source: string, statement?: string) {
|
|
9
|
+
const syntax = /^(require_relative|require)\s*(?:\(\s*)?["']([^"']+)["']/.exec(statement ?? target);
|
|
10
|
+
const value = syntax?.[2] ?? target;
|
|
11
|
+
const relative = syntax?.[1] === "require_relative" || !syntax && value.startsWith(".");
|
|
12
|
+
if (relative) return fileResult(io, existingFiles(io, [path.resolve(io.root, path.dirname(source), value), path.resolve(io.root, path.dirname(source), value + ".rb")]), "ruby_require_relative");
|
|
13
|
+
const dirs = ancestors(io, source);
|
|
14
|
+
let owner = io.root; let gemfile: string | undefined; let lock: string | undefined;
|
|
15
|
+
for (const dir of dirs) {
|
|
16
|
+
const manifest = io.read(path.join(dir, "Gemfile"));
|
|
17
|
+
const locked = io.read(path.join(dir, "Gemfile.lock"));
|
|
18
|
+
if (manifest !== undefined || locked !== undefined) { owner = dir; gemfile = manifest; lock = locked; break; }
|
|
19
|
+
}
|
|
20
|
+
const files = existingFiles(io, [path.resolve(owner, "lib", value), path.resolve(owner, "lib", value + ".rb")]);
|
|
21
|
+
if (files.length) return fileResult(io, files, "ruby_local_load_path");
|
|
22
|
+
const top = value.split("/")[0]!;
|
|
23
|
+
if (STDLIB.has(top)) return io.finish("external", "ruby_standard_library");
|
|
24
|
+
const gems = new Set<string>();
|
|
25
|
+
const mask = blankCommentsAndStrings(gemfile ?? "", { hashComments: true });
|
|
26
|
+
if (/^\s*(?:path|gemspec|eval_gemfile)\b/m.test(mask) || /<<[-~]?\s*["']?[A-Za-z_]\w*/.test(gemfile ?? ""))
|
|
27
|
+
return io.finish("unsupported", "ruby_dynamic_gem_configuration");
|
|
28
|
+
for (const match of (gemfile ?? "").matchAll(/^\s*gem\s*(?:\(\s*)?["']([^"']+)["']([^\n]*)/gm)) {
|
|
29
|
+
if (!/^\s*gem\b/.test(mask.slice(match.index!, match.index! + match[0].length))) continue;
|
|
30
|
+
const name = match[1]!; gems.add(name.replace(/-/g, "_"));
|
|
31
|
+
const local = /\bpath:\s*["']([^"']+)["']/.exec(match[2]!);
|
|
32
|
+
if (local && (top === name.replace(/-/g, "_") || GEM_IMPORTS[name.replace(/-/g, "_")]?.includes(top))) {
|
|
33
|
+
const base = path.resolve(owner, local[1]!, "lib", value);
|
|
34
|
+
return fileResult(io, existingFiles(io, [base, base + ".rb"]), "ruby_path_gem");
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
for (const match of (lock ?? "").matchAll(/^ {4}([A-Za-z0-9_-]+)\s+\([^\n]+\)/gm)) gems.add(match[1]!.replace(/-/g, "_"));
|
|
38
|
+
if (gems.has(top) || [...gems].some(gem => GEM_IMPORTS[gem]?.includes(top))) return io.finish("external", "ruby_manifest_dependency");
|
|
39
|
+
return io.finish("unresolved", "ruby_load_path_not_established");
|
|
40
|
+
}
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import * as path from "node:path";
|
|
2
|
+
import { blankCommentsAndStrings } from "../../parser/boundary-tracker.ts";
|
|
3
|
+
import { ancestors, existingFiles, fileResult, packageResult, toml, type ResolutionIO } from "./shared.ts";
|
|
4
|
+
|
|
5
|
+
interface Module { file: string; name: string[]; mask: string; children: Map<string, Module> }
|
|
6
|
+
function modules(io: ResolutionIO, file: string, name: string[], state: { count: number; conditional: boolean }, active = new Set<string>(), body?: string, inlineDirectory?: string): Module {
|
|
7
|
+
if (++state.count > 256 || name.length > 32) throw new Error("rust_module_limit");
|
|
8
|
+
if (body === undefined && active.has(file)) throw new Error("rust_module_cycle");
|
|
9
|
+
const source = body ?? io.read(file);
|
|
10
|
+
if (source === undefined) throw new Error("rust_module_file_missing");
|
|
11
|
+
if (/#\s*\[\s*(?:cfg|cfg_attr)\b/.test(source)) state.conditional = true;
|
|
12
|
+
const mask = blankCommentsAndStrings(source.replace(/'[A-Za-z_]\w*\b(?!')/g, value => " " + value.slice(1)));
|
|
13
|
+
const directory = inlineDirectory ?? (/^(?:lib|main|mod)\.rs$/.test(path.basename(file)) ? path.dirname(file) : file.replace(/\.rs$/, ""));
|
|
14
|
+
const result: Module = { file, name, mask, children: new Map() };
|
|
15
|
+
const children = /\bmod\s+([A-Za-z_]\w*)\s*([;{])/g;
|
|
16
|
+
let match: RegExpExecArray | null; let scanned = 0; let depth = 0;
|
|
17
|
+
while ((match = children.exec(mask))) {
|
|
18
|
+
for (; scanned < match.index; scanned++) { if (mask[scanned] === "{") depth++; if (mask[scanned] === "}") depth--; }
|
|
19
|
+
if (depth !== 0) continue;
|
|
20
|
+
const childName = match[1]!;
|
|
21
|
+
if (match[2] === "{") {
|
|
22
|
+
const open = children.lastIndex - 1; let end = open + 1, nesting = 1;
|
|
23
|
+
for (; end < mask.length && nesting; end++) { if (mask[end] === "{") nesting++; if (mask[end] === "}") nesting--; }
|
|
24
|
+
if (nesting) throw new Error("rust_unclosed_module");
|
|
25
|
+
result.children.set(childName, modules(io, file, [...name, childName], state, active, source.slice(open + 1, end - 1), path.join(directory, childName)));
|
|
26
|
+
children.lastIndex = end; scanned = end;
|
|
27
|
+
} else {
|
|
28
|
+
const prior = source.slice(Math.max(0, match.index - 160), match.index);
|
|
29
|
+
const attr = /#\s*\[\s*path\s*=\s*"([^"\n]+)"\s*\]\s*(?:pub(?:\([^)]*\))?\s*)?$/.exec(prior);
|
|
30
|
+
const candidates = attr ? [path.resolve(path.dirname(file), attr[1]!)]
|
|
31
|
+
: [path.join(directory, childName + ".rs"), path.join(directory, childName, "mod.rs")];
|
|
32
|
+
const files = existingFiles(io, candidates);
|
|
33
|
+
if (files.length !== 1) throw new Error(files.length ? "rust_ambiguous_module" : "rust_module_file_missing");
|
|
34
|
+
result.children.set(childName, modules(io, path.resolve(io.root, files[0]!), [...name, childName], state, new Set([...active, file])));
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
return result;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function resolveRust(io: ResolutionIO, target: string, source: string) {
|
|
41
|
+
const dirs = ancestors(io, source);
|
|
42
|
+
const manifests = dirs.map(dir => ({ dir, text: io.read(path.join(dir, "Cargo.toml")) }));
|
|
43
|
+
const own = manifests.find(entry => entry.text !== undefined && toml(entry.text).package);
|
|
44
|
+
if (!own) return io.finish("unsupported", "cargo_package_missing");
|
|
45
|
+
const cargo = toml(own.text!);
|
|
46
|
+
const workspace = manifests.find(entry => entry.text !== undefined && toml(entry.text).workspace);
|
|
47
|
+
const inherited = workspace ? toml(workspace.text!).workspace.dependencies ?? {} : {};
|
|
48
|
+
const deps: Record<string, any> = { ...cargo.dependencies, ...cargo["dev-dependencies"], ...cargo["build-dependencies"] };
|
|
49
|
+
const conditional = Object.values(cargo.target ?? {}).some((config: any) => Object.keys(config.dependencies ?? {}).some(name => target === name || target.startsWith(name + "::")));
|
|
50
|
+
for (const cfg of Object.values(cargo.target ?? {}) as any[]) Object.assign(deps, cfg.dependencies);
|
|
51
|
+
const parts = target.replace(/^mod:/, "").split("::");
|
|
52
|
+
const first = parts[0]!;
|
|
53
|
+
if (["std", "core", "alloc"].includes(first)) return io.finish("external", "rust_standard_library");
|
|
54
|
+
const depKey = Object.keys(deps).find(name => name.replace(/-/g, "_") === first);
|
|
55
|
+
if (depKey) {
|
|
56
|
+
let dependency = deps[depKey]; let owner = own.dir;
|
|
57
|
+
if (dependency?.workspace === true) {
|
|
58
|
+
const base = inherited[depKey];
|
|
59
|
+
if (base === undefined) return io.finish("unsupported", "cargo_workspace_dependency_missing");
|
|
60
|
+
dependency = { ...(typeof base === "string" ? { version: base } : base), ...dependency };
|
|
61
|
+
owner = workspace?.dir ?? own.dir;
|
|
62
|
+
}
|
|
63
|
+
if (dependency === undefined) return io.finish("unsupported", "cargo_workspace_dependency_missing");
|
|
64
|
+
if (typeof dependency !== "string" && typeof dependency !== "object") return io.finish("unsupported", "malformed_cargo_dependency");
|
|
65
|
+
if (!dependency.path) {
|
|
66
|
+
const result = io.finish("external", "cargo_manifest_dependency"); if (conditional || dependency.optional) result.coverage = "conditional"; return result;
|
|
67
|
+
}
|
|
68
|
+
const directory = path.resolve(owner, dependency.path); io.check(directory);
|
|
69
|
+
const text = io.read(path.join(directory, "Cargo.toml"));
|
|
70
|
+
if (!text) return io.finish("unresolved", "cargo_path_dependency_missing");
|
|
71
|
+
const lib = toml(text).lib?.path ?? "src/lib.rs";
|
|
72
|
+
const root = path.resolve(directory, lib); io.check(root);
|
|
73
|
+
const state = { count: 0, conditional: conditional || Boolean(dependency.optional) };
|
|
74
|
+
const tree = modules(io, root, [], state);
|
|
75
|
+
return select(io, tree, tree, parts.slice(1), state.conditional);
|
|
76
|
+
}
|
|
77
|
+
const rootFiles = existingFiles(io, [path.resolve(own.dir, cargo.lib?.path ?? "src/lib.rs"), path.join(own.dir, "src/main.rs"),
|
|
78
|
+
...(cargo.bin ?? []).flatMap((bin: any) => typeof bin.path === "string" ? [path.resolve(own.dir, bin.path)] : [])]);
|
|
79
|
+
const matches: { root: Module; current: Module; conditional: boolean }[] = [];
|
|
80
|
+
for (const file of rootFiles) {
|
|
81
|
+
const state = { count: 0, conditional: false };
|
|
82
|
+
const tree = modules(io, path.resolve(io.root, file), [], state);
|
|
83
|
+
const visit = (node: Module) => {
|
|
84
|
+
if (path.relative(io.root, node.file).replace(/\\/g, "/") === source) matches.push({ root: tree, current: node, conditional: state.conditional });
|
|
85
|
+
for (const child of node.children.values()) visit(child);
|
|
86
|
+
};
|
|
87
|
+
visit(tree);
|
|
88
|
+
}
|
|
89
|
+
// Inline modules need a declaration span to distinguish multiple contexts in one file.
|
|
90
|
+
const contexts = parts[0] === "crate" ? matches.filter(match => match.current === match.root || !matches.some(other => other.root === match.root && other.current === other.root)) : matches;
|
|
91
|
+
if (contexts.length !== 1) return io.finish(contexts.length ? "ambiguous" : "unresolved", "rust_source_module_not_unique");
|
|
92
|
+
const match = contexts[0]!;
|
|
93
|
+
if (target.startsWith("mod:")) return select(io, match.root, match.current, parts, match.conditional);
|
|
94
|
+
if (first === "crate") return select(io, match.root, match.root, parts.slice(1), match.conditional);
|
|
95
|
+
if (first === "self") return select(io, match.root, match.current, parts.slice(1), match.conditional);
|
|
96
|
+
if (first === "super") {
|
|
97
|
+
let count = 0; while (parts[count] === "super") count++;
|
|
98
|
+
if (count > match.current.name.length) return io.finish("unresolved", "rust_super_outside_crate");
|
|
99
|
+
let parent = match.root;
|
|
100
|
+
for (const name of match.current.name.slice(0, -count)) parent = parent.children.get(name)!;
|
|
101
|
+
return select(io, match.root, parent, parts.slice(count), match.conditional);
|
|
102
|
+
}
|
|
103
|
+
return select(io, match.root, match.root, parts, match.conditional);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function select(io: ResolutionIO, _root: Module, start: Module, parts: string[], conditional: boolean) {
|
|
107
|
+
let node = start; let index = 0;
|
|
108
|
+
for (; index < parts.length && node.children.has(parts[index]!); index++) node = node.children.get(parts[index]!)!;
|
|
109
|
+
const rest = parts.slice(index);
|
|
110
|
+
if (rest.length > 1) return io.finish("unsupported", "rust_associated_item_not_resolved");
|
|
111
|
+
let declared = false;
|
|
112
|
+
const declarations = /\b(?:struct|enum|trait|type|fn|const|static|mod)\s+([A-Za-z_]\w*)/g;
|
|
113
|
+
let position = 0, depth = 0;
|
|
114
|
+
for (const declaration of node.mask.matchAll(declarations)) {
|
|
115
|
+
for (; position < declaration.index!; position++) {
|
|
116
|
+
if (node.mask[position] === "{") depth++;
|
|
117
|
+
if (node.mask[position] === "}") depth--;
|
|
118
|
+
}
|
|
119
|
+
if (depth === 0 && declaration[1] === rest[0]) declared = true;
|
|
120
|
+
}
|
|
121
|
+
if (rest.length && rest[0] !== "*" && !declared)
|
|
122
|
+
return io.finish("unresolved", "rust_item_or_reexport_not_resolved");
|
|
123
|
+
const file = path.relative(io.root, node.file).replace(/\\/g, "/");
|
|
124
|
+
const result = rest[0] === "*" ? packageResult(io, [file, ...[...node.children.values()].map(child => path.relative(io.root, child.file).replace(/\\/g, "/"))], "rust_module_glob") : fileResult(io, [file], "rust_module_item");
|
|
125
|
+
if (conditional) result.coverage = "conditional";
|
|
126
|
+
return result;
|
|
127
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import * as path from "node:path";
|
|
2
|
+
import type { ImportResolution } from "../../../types/index.ts";
|
|
3
|
+
import { probeSourcePath, readSourceDirectory } from "../../resources/source-files.ts";
|
|
4
|
+
|
|
5
|
+
export interface ResolutionIO {
|
|
6
|
+
root: string;
|
|
7
|
+
read(file: string): string | undefined;
|
|
8
|
+
probe?(file: string): ReturnType<typeof probeSourcePath>;
|
|
9
|
+
cache?: Map<string, unknown>;
|
|
10
|
+
check(file: string): void;
|
|
11
|
+
finish(status: ImportResolution["status"], reason: string, targets?: ImportResolution["targets"]): ImportResolution;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export function ancestors(io: ResolutionIO, source: string): string[] {
|
|
15
|
+
let directory = path.dirname(path.resolve(io.root, source));
|
|
16
|
+
io.check(directory);
|
|
17
|
+
const result: string[] = [];
|
|
18
|
+
for (;;) {
|
|
19
|
+
result.push(directory);
|
|
20
|
+
if (directory === io.root) return result;
|
|
21
|
+
directory = path.dirname(directory);
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function existingFiles(io: ResolutionIO, candidates: string[]): string[] {
|
|
26
|
+
const probe = io.probe ?? probeSourcePath;
|
|
27
|
+
return [...new Set(candidates.filter(file => {
|
|
28
|
+
io.check(file);
|
|
29
|
+
return probe(file) === "file";
|
|
30
|
+
}).map(file => path.relative(io.root, file).replace(/\\/g, "/")))].sort();
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function fileResult(io: ResolutionIO, files: string[], reason: string): ImportResolution {
|
|
34
|
+
const unique = [...new Set(files)].sort();
|
|
35
|
+
return io.finish(unique.length === 1 ? "resolved" : unique.length ? "ambiguous" : "unresolved", reason,
|
|
36
|
+
unique.map(file => ({ kind: "file", files: [file] })));
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function packageResult(io: ResolutionIO, files: string[], reason: string): ImportResolution {
|
|
40
|
+
return io.finish(files.length ? "resolved" : "unresolved", reason,
|
|
41
|
+
files.length ? [{ kind: "package", files: [...new Set(files)].sort() }] : []);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// All discovery reads use the same tracked filesystem observations as source reads.
|
|
45
|
+
export function walkFiles(io: ResolutionIO, directory: string, accept: (file: string) => boolean): string[] {
|
|
46
|
+
const ignored = new Set([".git", ".septum", "node_modules", "vendor", "target", "build", "dist", "bin", "obj", ".venv", "__pycache__"]);
|
|
47
|
+
const result: string[] = [];
|
|
48
|
+
let entriesSeen = 0;
|
|
49
|
+
const visit = (dir: string, depth: number): void => {
|
|
50
|
+
io.check(dir);
|
|
51
|
+
if (probeSourcePath(dir) === "missing") return;
|
|
52
|
+
if (depth > 64) throw new Error("resolution_scan_depth_limit");
|
|
53
|
+
for (const entry of readSourceDirectory(dir)) {
|
|
54
|
+
if (++entriesSeen > 20000) throw new Error("resolution_scan_entry_limit");
|
|
55
|
+
const file = path.join(dir, entry.name);
|
|
56
|
+
if (entry.isDirectory() && !ignored.has(entry.name)) visit(file, depth + 1);
|
|
57
|
+
else if ((entry.isFile() || entry.isSymbolicLink()) && accept(file)) {
|
|
58
|
+
io.check(file);
|
|
59
|
+
if (probeSourcePath(file) === "file") result.push(file);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
};
|
|
63
|
+
visit(directory, 0);
|
|
64
|
+
return result.sort();
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export function toml(text: string): Record<string, any> {
|
|
68
|
+
return Bun.TOML.parse(text) as Record<string, any>;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export function literalString(value: unknown, reason: string): string {
|
|
72
|
+
if (typeof value !== "string" || /\$\(|\$\{|[<>]/.test(value)) throw new Error(reason);
|
|
73
|
+
return value;
|
|
74
|
+
}
|
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
import { ImportResolver } from "./import-resolver.ts";
|
|
2
2
|
import * as fs from "node:fs";
|
|
3
3
|
import * as path from "node:path";
|
|
4
|
+
import type { ImportResolution } from "../../types/index.ts";
|
|
4
5
|
import type { ValidatedSeptumConfig } from "../config/schema.ts";
|
|
5
6
|
import type { SeptumRepository } from "../database/repository.ts";
|
|
7
|
+
import { assertUniqueDomainRoots } from "../config/domain-ownership.ts";
|
|
6
8
|
|
|
7
9
|
export interface PathAliasRule {
|
|
8
10
|
prefix: string;
|
|
@@ -30,8 +32,8 @@ export class ModuleResolver {
|
|
|
30
32
|
this.repo = repo;
|
|
31
33
|
}
|
|
32
34
|
|
|
33
|
-
public resolveImport(target: string, sourceFile: string) {
|
|
34
|
-
return new ImportResolver(this.projectRoot, this.repo?.getAllDomains?.().map(domain => domain.root_path) ?? []).resolve(target, sourceFile);
|
|
35
|
+
public resolveImport(target: string, sourceFile: string, statement?: string) {
|
|
36
|
+
return new ImportResolver(this.projectRoot, this.repo?.getAllDomains?.().map(domain => domain.root_path) ?? []).resolve(target, sourceFile, statement);
|
|
35
37
|
}
|
|
36
38
|
|
|
37
39
|
public setRepository(repo: SeptumRepository): void {
|
|
@@ -102,6 +104,7 @@ export class ModuleResolver {
|
|
|
102
104
|
filePath: string,
|
|
103
105
|
config: ValidatedSeptumConfig
|
|
104
106
|
): string | null {
|
|
107
|
+
assertUniqueDomainRoots(config.domains, this.projectRoot);
|
|
105
108
|
return this.matchDomainByPath(filePath, config);
|
|
106
109
|
}
|
|
107
110
|
|
|
@@ -111,13 +114,13 @@ export class ModuleResolver {
|
|
|
111
114
|
public resolveTargetDomain(
|
|
112
115
|
targetStatement: string,
|
|
113
116
|
sourceFilePath: string | undefined,
|
|
114
|
-
config: ValidatedSeptumConfig
|
|
117
|
+
config: ValidatedSeptumConfig,
|
|
118
|
+
statement?: string
|
|
115
119
|
): string | null {
|
|
120
|
+
assertUniqueDomainRoots(config.domains, this.projectRoot);
|
|
116
121
|
if (sourceFilePath && (fs.existsSync(path.resolve(this.projectRoot,sourceFilePath)) || this.repo?.getMeta?.("workspace_root"))) {
|
|
117
|
-
const resolution = this.resolveImport(targetStatement,sourceFilePath);
|
|
118
|
-
|
|
119
|
-
const domains = [...new Set(resolution.targets.flatMap(target => target.files.map(file => this.matchDomainByPath(file,config))).filter((d): d is string => !!d))];
|
|
120
|
-
return domains.length === 1 ? domains[0]! : null;
|
|
122
|
+
const resolution = this.resolveImport(targetStatement,sourceFilePath,statement);
|
|
123
|
+
return this.resolveDomainFromEvidence(resolution, config);
|
|
121
124
|
}
|
|
122
125
|
// Legacy index-only/path-policy callers have no physical source evidence.
|
|
123
126
|
this.ensureConfigLoaded();
|
|
@@ -240,6 +243,14 @@ export class ModuleResolver {
|
|
|
240
243
|
return null;
|
|
241
244
|
}
|
|
242
245
|
|
|
246
|
+
public resolveDomainFromEvidence(resolution: ImportResolution, config: ValidatedSeptumConfig): string | null {
|
|
247
|
+
if (resolution.status !== "resolved" || resolution.coverage === "conditional") return null;
|
|
248
|
+
const domains = new Set(resolution.targets.flatMap(target => target.files.map(file => this.matchDomainByPath(file, config))).filter(
|
|
249
|
+
(domain): domain is string => domain !== null,
|
|
250
|
+
));
|
|
251
|
+
return domains.size === 1 ? [...domains][0]! : null;
|
|
252
|
+
}
|
|
253
|
+
|
|
243
254
|
private matchDomainByPath(targetPath: string, config: ValidatedSeptumConfig): string | null {
|
|
244
255
|
const absTargetPath = this.toAbsolutePath(targetPath);
|
|
245
256
|
|