@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
|
@@ -1,25 +1,21 @@
|
|
|
1
1
|
import * as fs from "node:fs";
|
|
2
|
+
import { resolvePython } from "./languages/python.ts";
|
|
3
|
+
import { resolveGo } from "./languages/go.ts";
|
|
4
|
+
import { resolveRuby } from "./languages/ruby.ts";
|
|
5
|
+
import { resolveRust } from "./languages/rust.ts";
|
|
6
|
+
import { resolveJava, resolveCSharp } from "./languages/managed.ts";
|
|
7
|
+
import type { ResolutionIO } from "./languages/shared.ts";
|
|
2
8
|
import * as path from "node:path";
|
|
3
9
|
import { builtinModules } from "node:module";
|
|
4
10
|
import { computeContentHash } from "../ingestion/hasher.ts";
|
|
5
|
-
import { readSourceFile } from "../resources/source-files.ts";
|
|
11
|
+
import { readSourceFile, probeSourcePath, readSourceDirectory } from "../resources/source-files.ts";
|
|
6
12
|
import type { ImportResolution, ResolutionTarget } from "../../types/index.ts";
|
|
7
13
|
|
|
8
|
-
export const RESOLVER_REVISION = "
|
|
14
|
+
export const RESOLVER_REVISION = "5";
|
|
9
15
|
const GO_STDLIB = new Set("archive bufio builtin bytes cmp compress container context crypto database debug embed encoding errors expvar flag fmt go hash html image index io iter log maps math mime net os path plugin reflect regexp runtime slices sort strconv strings structs sync syscall testing text time unicode unique unsafe".split(" "));
|
|
10
16
|
|
|
11
17
|
const PYTHON_STDLIB = new Set("abc argparse array ast asyncio atexit base64 bdb binascii bisect builtins bz2 calendar cgi cgitb chunk cmath cmd code codecs codeop collections colorsys compileall concurrent configparser contextlib contextvars copy copyreg cProfile crypt csv ctypes curses dataclasses datetime dbm decimal difflib dis distutils doctest email encodings ensurepip enum errno faulthandler fcntl filecmp fileinput fnmatch fractions ftplib functools gc getopt getpass gettext glob graphlib gzip hashlib heapq hmac html http idlelib imaplib imghdr imp importlib inspect io ipaddress itertools json keyword lib2to3 linecache locale logging lzma mailbox mailcap marshal math mimetypes mmap modulefinder msilib msvcrt multiprocessing netrc nntplib numbers operator optparse os ossaudiodev pathlib pdb pickle pickletools pipes pkgutil platform plistlib poplib posix posixpath pprint profile pstats pty pwd py_compile pyclbr pydoc queue quopri random re readline reprlib resource rlcompleter runpy sched secrets select selectors shelve shlex shutil signal site smtpd smtplib sndhdr socket socketserver spwd sqlite3 ssl stat statistics string stringprep struct subprocess sunau symbol symtable sys sysconfig syslog tabnanny tarfile telnetlib tempfile termios test textwrap threading time timeit tkinter token tokenize tomllib trace traceback tracemalloc tty turtle turtledemo types typing unicodedata unittest urllib uu uuid venv warnings wave weakref webbrowser winreg winsound wsgiref xdrlib xml xmlrpc zipapp zipfile zipimport zlib zoneinfo".split(" "));
|
|
12
18
|
|
|
13
|
-
const PYTHON_DIST_TO_MODULE_MAP: Record<string, string[]> = {
|
|
14
|
-
pillow: ["pil"],
|
|
15
|
-
pyyaml: ["yaml"],
|
|
16
|
-
python_dotenv: ["dotenv"],
|
|
17
|
-
scikit_learn: ["sklearn"],
|
|
18
|
-
beautifulsoup4: ["bs4"],
|
|
19
|
-
opencv_python: ["cv2"],
|
|
20
|
-
protobuf: ["google"],
|
|
21
|
-
typing_extensions: ["typing_extensions"],
|
|
22
|
-
};
|
|
23
19
|
|
|
24
20
|
const PHP_STDLIB = new Set([
|
|
25
21
|
"stdClass", "Exception", "ErrorException", "Error", "TypeError", "ValueError", "ArgumentCountError",
|
|
@@ -36,13 +32,24 @@ const PHP_STDLIB = new Set([
|
|
|
36
32
|
"BadFunctionCallException", "BadMethodCallException", "Attribute"
|
|
37
33
|
]);
|
|
38
34
|
|
|
39
|
-
/** Static, workspace-contained resolution. No manifest scripts, downloads or retained cache. */
|
|
35
|
+
/** Static, workspace-contained resolution. No manifest scripts, downloads or retained cache across calls. */
|
|
40
36
|
export class ImportResolver {
|
|
41
37
|
private root: string;
|
|
42
|
-
|
|
38
|
+
private readonly batchCache: boolean;
|
|
39
|
+
private readonly batchReads = new Map<string, { text: string; hash: string } | null>();
|
|
40
|
+
private readonly batchProbes = new Map<string, ReturnType<typeof probeSourcePath>>();
|
|
41
|
+
private readonly batchJson = new Map<string, any>();
|
|
42
|
+
private readonly batchDerived = new Map<string, unknown>();
|
|
43
43
|
|
|
44
|
-
|
|
44
|
+
constructor(root: string, private packageRoots: string[] = [], options: { batchCache?: boolean } = {}) {
|
|
45
|
+
this.root = path.resolve(root);
|
|
46
|
+
this.batchCache = Boolean(options.batchCache);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
public resolve(target: string, sourceFile: string, statement?: string): ImportResolution {
|
|
45
50
|
const manifests: Record<string, string> = {};
|
|
51
|
+
const contents = new Map<string, string | undefined>();
|
|
52
|
+
let bytesRead = 0;
|
|
46
53
|
const result: ImportResolution = {
|
|
47
54
|
status: "unresolved", targets: [], reason: "target_not_found", coverage: "partial",
|
|
48
55
|
resolver_revision: RESOLVER_REVISION, config_revision: "", source: { file: sourceFile, target },
|
|
@@ -51,17 +58,52 @@ export class ImportResolver {
|
|
|
51
58
|
...result, status, reason, targets,
|
|
52
59
|
config_revision: computeContentHash(JSON.stringify({ root: this.root, revision: RESOLVER_REVISION, manifests })),
|
|
53
60
|
});
|
|
61
|
+
const probeCached = (file: string): ReturnType<typeof probeSourcePath> => {
|
|
62
|
+
if (this.batchCache) {
|
|
63
|
+
const cached = this.batchProbes.get(file);
|
|
64
|
+
if (cached !== undefined) return cached;
|
|
65
|
+
const kind = probeSourcePath(file);
|
|
66
|
+
this.batchProbes.set(file, kind);
|
|
67
|
+
return kind;
|
|
68
|
+
}
|
|
69
|
+
return probeSourcePath(file);
|
|
70
|
+
};
|
|
54
71
|
const read = (file: string): string | undefined => {
|
|
55
72
|
this.assertContained(file);
|
|
56
|
-
if (
|
|
57
|
-
|
|
73
|
+
if (contents.has(file)) return contents.get(file);
|
|
74
|
+
if (this.batchCache && this.batchReads.has(file)) {
|
|
75
|
+
const cached = this.batchReads.get(file);
|
|
76
|
+
if (cached === null || cached === undefined) {
|
|
77
|
+
manifests[path.relative(this.root, file)] = "missing";
|
|
78
|
+
contents.set(file, undefined);
|
|
79
|
+
return undefined;
|
|
80
|
+
}
|
|
81
|
+
contents.set(file, cached.text);
|
|
82
|
+
manifests[path.relative(this.root, file)] = cached.hash;
|
|
83
|
+
return cached.text;
|
|
84
|
+
}
|
|
85
|
+
if (probeCached(file) === "missing") {
|
|
86
|
+
manifests[path.relative(this.root, file)] = "missing";
|
|
87
|
+
if (this.batchCache) this.batchReads.set(file, null);
|
|
88
|
+
return undefined;
|
|
89
|
+
}
|
|
90
|
+
const text = readSourceFile(file);
|
|
91
|
+
bytesRead += Buffer.byteLength(text, "utf8");
|
|
92
|
+
if (bytesRead > 16 * 1024 * 1024) throw new Error("resolution_source_byte_limit");
|
|
93
|
+
const hash = computeContentHash(text);
|
|
94
|
+
contents.set(file, text);
|
|
95
|
+
if (this.batchCache) this.batchReads.set(file, { text, hash });
|
|
96
|
+
manifests[path.relative(this.root, file)] = hash;
|
|
97
|
+
return text;
|
|
58
98
|
};
|
|
59
99
|
const json = (file: string): any => {
|
|
60
100
|
const raw = read(file); if (raw === undefined) return {};
|
|
101
|
+
if (this.batchCache && this.batchJson.has(file)) return this.batchJson.get(file);
|
|
61
102
|
const clean = raw.replace(/"(?:\\.|[^"\\])*"|\/\/[^\r\n]*|\/\*[\s\S]*?\*\//g, token => token.startsWith('"') ? token : " ")
|
|
62
103
|
.replace(/"(?:\\.|[^"\\])*"|,\s*[}\]]/g, token => token.startsWith('"') ? token : token.slice(1));
|
|
63
104
|
const parsed = JSON.parse(clean);
|
|
64
105
|
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error("malformed_manifest");
|
|
106
|
+
if (this.batchCache) this.batchJson.set(file, parsed);
|
|
65
107
|
return parsed;
|
|
66
108
|
};
|
|
67
109
|
const filesAt = (base: string, extensions: string[]): string[] => {
|
|
@@ -83,7 +125,7 @@ export class ImportResolver {
|
|
|
83
125
|
const candidates = [base, ...extraCandidates, ...extensions.map(ext => base + ext), ...extensions.map(ext => path.join(base, "index" + ext))];
|
|
84
126
|
return [...new Set(candidates.filter(file => {
|
|
85
127
|
this.assertContained(file);
|
|
86
|
-
return
|
|
128
|
+
return probeCached(file) === "file";
|
|
87
129
|
}).map(file => path.relative(this.root, file).replace(/\\/g, "/")))];
|
|
88
130
|
};
|
|
89
131
|
const resolvedFiles = (files: string[], reason: string) => {
|
|
@@ -95,45 +137,37 @@ export class ImportResolver {
|
|
|
95
137
|
if (target.startsWith("dynamic:")) return finish("unresolved", "dynamic_target");
|
|
96
138
|
const source = path.resolve(this.root, sourceFile); this.assertContained(source);
|
|
97
139
|
const ext = path.extname(source).toLowerCase();
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
140
|
+
const io: ResolutionIO = {
|
|
141
|
+
root: this.root,
|
|
142
|
+
read,
|
|
143
|
+
probe: probeCached,
|
|
144
|
+
cache: this.batchCache ? this.batchDerived : undefined,
|
|
145
|
+
check: file => this.assertContained(file),
|
|
146
|
+
finish,
|
|
147
|
+
};
|
|
148
|
+
if (ext === ".go") return resolveGo(io, target, sourceFile, GO_STDLIB);
|
|
149
|
+
if (ext === ".py") return resolvePython(io, target, sourceFile, this.packageRoots, PYTHON_STDLIB);
|
|
150
|
+
if (ext === ".rb") return resolveRuby(io, target, sourceFile, statement);
|
|
151
|
+
if (ext === ".rs") return resolveRust(io, target, sourceFile);
|
|
152
|
+
if (ext === ".java") return resolveJava(io, target, sourceFile, statement);
|
|
153
|
+
if (ext === ".cs") return resolveCSharp(io, target, sourceFile, statement);
|
|
154
|
+
if (ext === ".php") {
|
|
155
|
+
let rawTarget = target.trim();
|
|
156
|
+
const useMatch = rawTarget.match(/^use\s+(?:function\s+|const\s+)?([^;\s]+)(?:\s+as\s+[^;\s]+)?\s*;?$/i);
|
|
157
|
+
if (useMatch) {
|
|
158
|
+
rawTarget = useMatch[1]!;
|
|
159
|
+
} else {
|
|
160
|
+
rawTarget = rawTarget.replace(/;+$/, "").trim();
|
|
106
161
|
}
|
|
107
|
-
if (
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
const packageDir = path.resolve(modDir, target.slice(moduleName.length).replace(/^\//, "")); this.assertContained(packageDir);
|
|
113
|
-
let parent = packageDir;
|
|
114
|
-
while (parent !== modDir) {
|
|
115
|
-
if (!parent.startsWith(modDir + path.sep)) return finish("unsupported", "outside_module");
|
|
116
|
-
if (read(path.join(parent, "go.mod")) !== undefined) return finish("unsupported", "nested_go_mod");
|
|
117
|
-
parent = path.dirname(parent);
|
|
162
|
+
if (rawTarget.endsWith(".php")) {
|
|
163
|
+
const absPhp = path.resolve(this.root, rawTarget.replace(/^\.\//, ""));
|
|
164
|
+
this.assertContained(absPhp);
|
|
165
|
+
if (probeSourcePath(absPhp) === "file") {
|
|
166
|
+
return resolvedFiles([path.relative(this.root, absPhp).replace(/\\/g, "/")], "php_file_path");
|
|
118
167
|
}
|
|
119
|
-
|
|
120
|
-
const names = fs.readdirSync(packageDir).filter(name => name.endsWith(".go") && !name.endsWith("_test.go")).sort();
|
|
121
|
-
const packageFiles: string[] = [];
|
|
122
|
-
for (const name of names) {
|
|
123
|
-
const file = path.join(packageDir, name); this.assertContained(file);
|
|
124
|
-
const content = readSourceFile(file);
|
|
125
|
-
if (/^\s*\/\/\s*(?:go:build|\+build)\b/m.test(content) || /_(?:linux|windows|darwin|freebsd|amd64|arm64|386|arm)\.go$/.test(name)) result.coverage = "conditional";
|
|
126
|
-
packageFiles.push(path.relative(this.root, file).replace(/\\/g, "/"));
|
|
127
|
-
}
|
|
128
|
-
return packageFiles.length ? finish("resolved", "go_module_package", [{ kind: "package", files: packageFiles }]) : finish("unresolved", "go_package_empty");
|
|
168
|
+
return finish("unresolved", "file_not_found");
|
|
129
169
|
}
|
|
130
|
-
|
|
131
|
-
const requirements = [...mod.matchAll(/^\s*(?:require\s+)?([A-Za-z0-9._~/-]+)\s+v[^\s]+/gm)].map(m => m[1]!);
|
|
132
|
-
if (requirements.some(name => target === name || target.startsWith(name + "/"))) return finish("external", "go_required_module");
|
|
133
|
-
return finish("unresolved", "go_module_not_declared");
|
|
134
|
-
}
|
|
135
|
-
if (ext === ".php") {
|
|
136
|
-
const normTarget = target.replace(/^\\/, "");
|
|
170
|
+
const normTarget = rawTarget.replace(/^\\/, "");
|
|
137
171
|
if (
|
|
138
172
|
PHP_STDLIB.has(normTarget) ||
|
|
139
173
|
normTarget.startsWith("Attribute") ||
|
|
@@ -142,7 +176,15 @@ export class ImportResolver {
|
|
|
142
176
|
return finish("external", "php_standard_library");
|
|
143
177
|
}
|
|
144
178
|
|
|
145
|
-
|
|
179
|
+
let composerDir = this.root;
|
|
180
|
+
for (let dir = path.dirname(source); dir === this.root || dir.startsWith(this.root + path.sep); dir = path.dirname(dir)) {
|
|
181
|
+
if (probeSourcePath(path.join(dir, "composer.json")) !== "missing") {
|
|
182
|
+
composerDir = dir;
|
|
183
|
+
break;
|
|
184
|
+
}
|
|
185
|
+
if (dir === this.root) break;
|
|
186
|
+
}
|
|
187
|
+
const composer = json(path.join(composerDir, "composer.json"));
|
|
146
188
|
const rules = { ...(composer.autoload?.["psr-4"] ?? {}), ...(composer["autoload-dev"]?.["psr-4"] ?? {}) };
|
|
147
189
|
const matches = Object.keys(rules)
|
|
148
190
|
.filter((prefix) => normTarget.startsWith(prefix.replace(/^\\/, "")))
|
|
@@ -157,7 +199,7 @@ export class ImportResolver {
|
|
|
157
199
|
const relativePath = normTarget.slice(cleanPrefix.length).replace(/\\/g, "/");
|
|
158
200
|
const candidateFiles: string[] = [];
|
|
159
201
|
for (const dir of dirs) {
|
|
160
|
-
const absBase = path.resolve(
|
|
202
|
+
const absBase = path.resolve(composerDir, dir, relativePath);
|
|
161
203
|
this.assertContained(absBase);
|
|
162
204
|
candidateFiles.push(...filesAt(absBase, [".php"]));
|
|
163
205
|
}
|
|
@@ -168,6 +210,38 @@ export class ImportResolver {
|
|
|
168
210
|
return resolvedFiles(candidateFiles, "composer_psr4");
|
|
169
211
|
}
|
|
170
212
|
|
|
213
|
+
// Check installed Composer vendor PSR-4 autoload map (covers transitive & non-matching package names like Carbon\*, Inertia\*)
|
|
214
|
+
const autoloadPsr4 = read(path.join(composerDir, "vendor", "composer", "autoload_psr4.php"));
|
|
215
|
+
if (autoloadPsr4) {
|
|
216
|
+
for (const m of autoloadPsr4.matchAll(/['"]([^'"]+)['"]\s*=>/g)) {
|
|
217
|
+
const prefix = m[1]!.replace(/\\\\/g, "\\").replace(/^\\/, "");
|
|
218
|
+
if (prefix && normTarget.startsWith(prefix)) {
|
|
219
|
+
return finish("external", "composer_vendor_psr4");
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
// Fallback: check composer.lock PSR-4 declarations when vendor/ is absent
|
|
225
|
+
const composerLockRaw = read(path.join(composerDir, "composer.lock"));
|
|
226
|
+
if (composerLockRaw) {
|
|
227
|
+
const lock = JSON.parse(composerLockRaw);
|
|
228
|
+
const lockPackages = [
|
|
229
|
+
...(Array.isArray(lock?.packages) ? lock.packages : []),
|
|
230
|
+
...(Array.isArray(lock?.["packages-dev"]) ? lock["packages-dev"] : []),
|
|
231
|
+
];
|
|
232
|
+
for (const pkgEntry of lockPackages) {
|
|
233
|
+
const psr4 = pkgEntry?.autoload?.["psr-4"];
|
|
234
|
+
if (psr4 && typeof psr4 === "object") {
|
|
235
|
+
for (const prefix of Object.keys(psr4)) {
|
|
236
|
+
const cleanPrefix = prefix.replace(/^\\/, "");
|
|
237
|
+
if (cleanPrefix && normTarget.startsWith(cleanPrefix)) {
|
|
238
|
+
return finish("external", "composer_lock_package");
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
|
|
171
245
|
// Check declared composer dependencies
|
|
172
246
|
const requirements = { ...(composer.require ?? {}), ...(composer["require-dev"] ?? {}) };
|
|
173
247
|
const topNamespace = normTarget.split("\\")[0]!.toLowerCase();
|
|
@@ -195,131 +269,27 @@ export class ImportResolver {
|
|
|
195
269
|
|
|
196
270
|
return finish("unresolved", "php_namespace_not_mapped");
|
|
197
271
|
}
|
|
198
|
-
if (ext === ".py") {
|
|
199
|
-
if (target.startsWith(".")) {
|
|
200
|
-
const dotsMatch = target.match(/^\.+/);
|
|
201
|
-
const dotCount = dotsMatch ? dotsMatch[0].length : 0;
|
|
202
|
-
const remainder = target.slice(dotCount);
|
|
203
|
-
let baseDir = path.dirname(source);
|
|
204
|
-
for (let i = 1; i < dotCount; i++) {
|
|
205
|
-
baseDir = path.dirname(baseDir);
|
|
206
|
-
}
|
|
207
|
-
this.assertContained(baseDir);
|
|
208
|
-
const fsSubpath = remainder ? remainder.split(".").join(path.sep) : "";
|
|
209
|
-
const targetDirOrFile = fsSubpath ? path.resolve(baseDir, fsSubpath) : baseDir;
|
|
210
|
-
this.assertContained(targetDirOrFile);
|
|
211
|
-
|
|
212
|
-
const candidates: string[] = [];
|
|
213
|
-
if (fsSubpath) {
|
|
214
|
-
const pyFile = targetDirOrFile + ".py";
|
|
215
|
-
if (fs.existsSync(pyFile) && fs.statSync(pyFile).isFile()) {
|
|
216
|
-
candidates.push(path.relative(this.root, pyFile).replace(/\\/g, "/"));
|
|
217
|
-
}
|
|
218
|
-
}
|
|
219
|
-
const initFile = path.join(targetDirOrFile, "__init__.py");
|
|
220
|
-
if (fs.existsSync(initFile) && fs.statSync(initFile).isFile()) {
|
|
221
|
-
candidates.push(path.relative(this.root, initFile).replace(/\\/g, "/"));
|
|
222
|
-
}
|
|
223
|
-
return resolvedFiles(candidates, "python_relative_module");
|
|
224
|
-
}
|
|
225
|
-
|
|
226
|
-
const parts = target.split(".");
|
|
227
|
-
const topPackage = parts[0]!;
|
|
228
|
-
const fsSubpath = parts.join(path.sep);
|
|
229
|
-
|
|
230
|
-
const searchRoots: string[] = [];
|
|
231
|
-
const srcDir = path.resolve(this.root, "src");
|
|
232
|
-
if (fs.existsSync(srcDir) && fs.statSync(srcDir).isDirectory()) {
|
|
233
|
-
searchRoots.push(srcDir);
|
|
234
|
-
}
|
|
235
|
-
searchRoots.push(this.root);
|
|
236
|
-
const callerDir = path.dirname(source);
|
|
237
|
-
if (callerDir !== this.root && callerDir !== srcDir) {
|
|
238
|
-
searchRoots.push(callerDir);
|
|
239
|
-
}
|
|
240
|
-
for (const pkgRoot of this.packageRoots) {
|
|
241
|
-
const abs = path.resolve(this.root, pkgRoot);
|
|
242
|
-
if (!searchRoots.includes(abs) && fs.existsSync(abs)) {
|
|
243
|
-
searchRoots.push(abs);
|
|
244
|
-
}
|
|
245
|
-
}
|
|
246
|
-
|
|
247
|
-
const localCandidates: string[] = [];
|
|
248
|
-
for (const sRoot of searchRoots) {
|
|
249
|
-
const candidateFile = path.resolve(sRoot, fsSubpath + ".py");
|
|
250
|
-
if (candidateFile.startsWith(this.root + path.sep) && fs.existsSync(candidateFile) && fs.statSync(candidateFile).isFile()) {
|
|
251
|
-
localCandidates.push(path.relative(this.root, candidateFile).replace(/\\/g, "/"));
|
|
252
|
-
}
|
|
253
|
-
const candidateInit = path.resolve(sRoot, fsSubpath, "__init__.py");
|
|
254
|
-
if (candidateInit.startsWith(this.root + path.sep) && fs.existsSync(candidateInit) && fs.statSync(candidateInit).isFile()) {
|
|
255
|
-
localCandidates.push(path.relative(this.root, candidateInit).replace(/\\/g, "/"));
|
|
256
|
-
}
|
|
257
|
-
}
|
|
258
|
-
|
|
259
|
-
const unique = [...new Set(localCandidates)].sort();
|
|
260
|
-
if (unique.length > 0) {
|
|
261
|
-
return finish(
|
|
262
|
-
unique.length === 1 ? "resolved" : "ambiguous",
|
|
263
|
-
unique.length === 1 ? "python_local_module" : "multiple_python_candidates",
|
|
264
|
-
unique.map(file => ({ kind: "file", files: [file] }))
|
|
265
|
-
);
|
|
266
|
-
}
|
|
267
|
-
|
|
268
|
-
if (PYTHON_STDLIB.has(topPackage)) {
|
|
269
|
-
return finish("external", "python_standard_library");
|
|
270
|
-
}
|
|
271
|
-
|
|
272
|
-
const declaredPackages = new Set<string>();
|
|
273
|
-
const reqText = read(path.join(this.root, "requirements.txt"));
|
|
274
|
-
if (reqText) {
|
|
275
|
-
for (const rawLine of reqText.split(/\r?\n/)) {
|
|
276
|
-
const line = rawLine.replace(/#.*$/, "").trim();
|
|
277
|
-
if (!line || line.startsWith("-")) continue;
|
|
278
|
-
const match = line.match(/^([A-Za-z0-9_.-]+)/);
|
|
279
|
-
if (match) declaredPackages.add(match[1].toLowerCase().replace(/[-_.]/g, "_"));
|
|
280
|
-
}
|
|
281
|
-
}
|
|
282
|
-
const pyprojectText = read(path.join(this.root, "pyproject.toml"));
|
|
283
|
-
if (pyprojectText) {
|
|
284
|
-
for (const rawLine of pyprojectText.split(/\r?\n/)) {
|
|
285
|
-
const line = rawLine.replace(/#.*$/, "").trim();
|
|
286
|
-
const matchArray = line.match(/^["']([A-Za-z0-9_.-]+)(?:[><=~!^;].*)?["']/);
|
|
287
|
-
if (matchArray) {
|
|
288
|
-
declaredPackages.add(matchArray[1].toLowerCase().replace(/[-_.]/g, "_"));
|
|
289
|
-
continue;
|
|
290
|
-
}
|
|
291
|
-
const matchKey = line.match(/^([A-Za-z0-9_.-]+)\s*=\s*(?:\{|"[^"]*"|'[^']*'|\d)/);
|
|
292
|
-
if (matchKey && !["python", "version", "name", "description"].includes(matchKey[1].toLowerCase())) {
|
|
293
|
-
declaredPackages.add(matchKey[1].toLowerCase().replace(/[-_.]/g, "_"));
|
|
294
|
-
}
|
|
295
|
-
}
|
|
296
|
-
}
|
|
297
|
-
const pipfileText = read(path.join(this.root, "Pipfile"));
|
|
298
|
-
if (pipfileText) {
|
|
299
|
-
for (const rawLine of pipfileText.split(/\r?\n/)) {
|
|
300
|
-
const line = rawLine.replace(/#.*$/, "").trim();
|
|
301
|
-
const match = line.match(/^([A-Za-z0-9_.-]+)\s*=/);
|
|
302
|
-
if (match) declaredPackages.add(match[1].toLowerCase().replace(/[-_.]/g, "_"));
|
|
303
|
-
}
|
|
304
|
-
}
|
|
305
|
-
|
|
306
|
-
const normalizedTop = topPackage.toLowerCase().replace(/[-_.]/g, "_");
|
|
307
|
-
const isDeclared = declaredPackages.has(normalizedTop) ||
|
|
308
|
-
Object.entries(PYTHON_DIST_TO_MODULE_MAP).some(([dist, mods]) => declaredPackages.has(dist) && mods.includes(normalizedTop));
|
|
309
|
-
|
|
310
|
-
if (isDeclared) {
|
|
311
|
-
return finish("external", "python_manifest_dependency");
|
|
312
|
-
}
|
|
313
|
-
|
|
314
|
-
return finish("unresolved", "python_module_not_declared");
|
|
315
|
-
}
|
|
316
272
|
if (!/\.(?:[cm]?[jt]sx?|vue|astro|svelte)$/.test(ext)) return finish("unsupported", "language_resolver_unavailable");
|
|
317
273
|
const extensions = [".ts", ".tsx", ".mts", ".cts", ".js", ".jsx", ".mjs", ".cjs", ".d.ts", ".json"];
|
|
318
274
|
if (target.startsWith(".") || path.isAbsolute(target)) return resolvedFiles(filesAt(path.resolve(path.dirname(source), target), extensions), "relative_path");
|
|
319
275
|
if (builtinModules.includes(target) || target.startsWith("node:") && builtinModules.includes(target.slice(5)) || target === "bun" || target.startsWith("bun:")) return finish("external", "runtime_builtin");
|
|
320
|
-
|
|
321
|
-
|
|
276
|
+
let nearestTsConfig = path.join(this.root, "tsconfig.json");
|
|
277
|
+
let nearestPkgDir = this.root;
|
|
278
|
+
let foundTsConfig = false;
|
|
279
|
+
let foundPkg = false;
|
|
280
|
+
for (let dir = path.dirname(source); dir === this.root || dir.startsWith(this.root + path.sep); dir = path.dirname(dir)) {
|
|
281
|
+
if (!foundTsConfig && probeSourcePath(path.join(dir, "tsconfig.json")) !== "missing") {
|
|
282
|
+
nearestTsConfig = path.join(dir, "tsconfig.json");
|
|
283
|
+
foundTsConfig = true;
|
|
284
|
+
}
|
|
285
|
+
if (!foundPkg && probeSourcePath(path.join(dir, "package.json")) !== "missing") {
|
|
286
|
+
nearestPkgDir = dir;
|
|
287
|
+
foundPkg = true;
|
|
288
|
+
}
|
|
289
|
+
if (foundTsConfig && foundPkg) break;
|
|
290
|
+
if (dir === this.root) break;
|
|
322
291
|
}
|
|
292
|
+
let extendsMissing = false;
|
|
323
293
|
const loadTsConfig = (configPath: string, visited = new Set<string>()): any => {
|
|
324
294
|
if (visited.has(configPath)) throw new Error("circular_tsconfig_extends");
|
|
325
295
|
visited.add(configPath);
|
|
@@ -333,12 +303,15 @@ export class ImportResolver {
|
|
|
333
303
|
: path.resolve(this.root, "node_modules", extRef);
|
|
334
304
|
this.assertContained(base);
|
|
335
305
|
let parentPath = base.endsWith(".json") ? base : base + ".json";
|
|
336
|
-
if (
|
|
306
|
+
if (probeSourcePath(parentPath) === "missing" && probeSourcePath(base) === "directory") {
|
|
337
307
|
const pkg = json(path.join(base, "package.json"));
|
|
338
308
|
parentPath = path.resolve(base, typeof pkg.tsconfig === "string" ? pkg.tsconfig : "tsconfig.json");
|
|
339
309
|
}
|
|
340
310
|
this.assertContained(parentPath);
|
|
341
|
-
if (
|
|
311
|
+
if (probeSourcePath(parentPath) === "missing") {
|
|
312
|
+
extendsMissing = true;
|
|
313
|
+
continue;
|
|
314
|
+
}
|
|
342
315
|
options = { ...options, ...loadTsConfig(parentPath, visited) };
|
|
343
316
|
}
|
|
344
317
|
const own = cfg.compilerOptions ?? {};
|
|
@@ -353,7 +326,7 @@ export class ImportResolver {
|
|
|
353
326
|
return options;
|
|
354
327
|
};
|
|
355
328
|
|
|
356
|
-
const options = loadTsConfig(
|
|
329
|
+
const options = loadTsConfig(nearestTsConfig);
|
|
357
330
|
const aliases = options.paths ?? {};
|
|
358
331
|
if (typeof aliases !== "object" || Array.isArray(aliases)) return finish("unsupported", "malformed_ts_paths");
|
|
359
332
|
const matching = Object.keys(aliases).filter(key => {
|
|
@@ -380,13 +353,14 @@ export class ImportResolver {
|
|
|
380
353
|
if (localFiles.length) return resolvedFiles(localFiles,"workspace_path");
|
|
381
354
|
}
|
|
382
355
|
const pkg = json(path.join(this.root,"package.json"));
|
|
356
|
+
const localPkg = nearestPkgDir !== this.root ? json(path.join(nearestPkgDir, "package.json")) : {};
|
|
383
357
|
const workspacePatterns = Array.isArray(pkg.workspaces) ? pkg.workspaces : pkg.workspaces?.packages ?? [];
|
|
384
358
|
const roots = [...this.packageRoots];
|
|
385
359
|
for (const pattern of workspacePatterns) {
|
|
386
360
|
if (typeof pattern !== "string") return finish("unsupported","malformed_workspace_pattern");
|
|
387
361
|
if (pattern.endsWith("/*")) {
|
|
388
362
|
const parent = path.resolve(this.root,pattern.slice(0,-2)); this.assertContained(parent);
|
|
389
|
-
if (
|
|
363
|
+
if (probeSourcePath(parent) !== "missing") roots.push(...readSourceDirectory(parent).filter(entry=>entry.isDirectory()).map(entry=>path.relative(this.root,path.join(parent,entry.name))));
|
|
390
364
|
} else if (!pattern.includes("*")) roots.push(pattern);
|
|
391
365
|
else return finish("unsupported","workspace_glob_not_supported");
|
|
392
366
|
}
|
|
@@ -420,7 +394,14 @@ export class ImportResolver {
|
|
|
420
394
|
}
|
|
421
395
|
if (workspaceFiles.length) return resolvedFiles(workspaceFiles,"workspace_package");
|
|
422
396
|
const name = target.startsWith("@") ? target.split("/").slice(0,2).join("/") : target.split("/")[0]!;
|
|
423
|
-
|
|
397
|
+
const depMaps = [
|
|
398
|
+
localPkg.dependencies, localPkg.devDependencies, localPkg.peerDependencies, localPkg.optionalDependencies,
|
|
399
|
+
pkg.dependencies, pkg.devDependencies, pkg.peerDependencies, pkg.optionalDependencies,
|
|
400
|
+
];
|
|
401
|
+
if (depMaps.some(deps => deps && Object.hasOwn(deps, name))) return finish("external", "package_manifest_dependency");
|
|
402
|
+
if (extendsMissing) {
|
|
403
|
+
return finish("unsupported", "manifest_or_source_error: tsconfig_extends_not_found");
|
|
404
|
+
}
|
|
424
405
|
return finish("unresolved", "package_not_declared");
|
|
425
406
|
} catch (error) {
|
|
426
407
|
return finish("unsupported", error instanceof Error && error.message.includes("outside_workspace") ? "outside_workspace" : `manifest_or_source_error: ${error instanceof Error ? error.message : String(error)}`);
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { basename } from "node:path";
|
|
2
|
+
|
|
3
|
+
const RESOLUTION_INPUT_BASENAMES = new Set([
|
|
4
|
+
"package.json",
|
|
5
|
+
"package-lock.json",
|
|
6
|
+
"pnpm-lock.yaml",
|
|
7
|
+
"pnpm-workspace.yaml",
|
|
8
|
+
"yarn.lock",
|
|
9
|
+
"bun.lock",
|
|
10
|
+
"bun.lockb",
|
|
11
|
+
"nest-cli.json",
|
|
12
|
+
"nx.json",
|
|
13
|
+
"turbo.json",
|
|
14
|
+
"lerna.json",
|
|
15
|
+
"pyproject.toml",
|
|
16
|
+
"setup.py",
|
|
17
|
+
"setup.cfg",
|
|
18
|
+
"pipfile",
|
|
19
|
+
"pipfile.lock",
|
|
20
|
+
"poetry.lock",
|
|
21
|
+
"uv.lock",
|
|
22
|
+
"pdm.lock",
|
|
23
|
+
"mypy.ini",
|
|
24
|
+
"pyrightconfig.json",
|
|
25
|
+
"go.mod",
|
|
26
|
+
"go.work",
|
|
27
|
+
"go.sum",
|
|
28
|
+
"cargo.toml",
|
|
29
|
+
"cargo.lock",
|
|
30
|
+
"composer.json",
|
|
31
|
+
"composer.lock",
|
|
32
|
+
"artisan",
|
|
33
|
+
"gemfile",
|
|
34
|
+
"gemfile.lock",
|
|
35
|
+
"pom.xml",
|
|
36
|
+
"build.gradle",
|
|
37
|
+
"build.gradle.kts",
|
|
38
|
+
"settings.gradle",
|
|
39
|
+
"settings.gradle.kts",
|
|
40
|
+
"gradle.properties",
|
|
41
|
+
"directory.build.props",
|
|
42
|
+
"directory.build.targets",
|
|
43
|
+
"packages.config",
|
|
44
|
+
]);
|
|
45
|
+
|
|
46
|
+
/** Files whose staged bytes and watcher events can change import interpretation. */
|
|
47
|
+
export function isResolutionInput(file: string): boolean {
|
|
48
|
+
const norm = file.replace(/\\/g, "/");
|
|
49
|
+
const base = basename(norm).toLowerCase();
|
|
50
|
+
if (RESOLUTION_INPUT_BASENAMES.has(base)) return true;
|
|
51
|
+
if (/^(?:tsconfig|jsconfig)(?:\.[^/]+)?\.jsonc?$/i.test(base)) return true;
|
|
52
|
+
if (/^requirements(?:[-_.][^/]*)?\.(?:txt|in)$/i.test(base) || /(?:^|\/)requirements\/[^/]+\.(?:txt|in)$/i.test(norm)) {
|
|
53
|
+
return true;
|
|
54
|
+
}
|
|
55
|
+
if (/\.(?:csproj|fsproj|vbproj|props|targets|gemspec|gradle|gradle\.kts)$/i.test(base)) return true;
|
|
56
|
+
// Inherited tsconfig/jsconfig or custom workspace JSON configs (e.g. configs/base.json),
|
|
57
|
+
// while excluding test fixtures/cassettes/locales.
|
|
58
|
+
if (
|
|
59
|
+
/\.(?:json|jsonc)$/i.test(base) &&
|
|
60
|
+
!/(?:^|\/)(?:tests?|__tests__|cassettes|fixtures?|__fixtures__|locales?|i18n|translations?)\//i.test(norm)
|
|
61
|
+
) {
|
|
62
|
+
return true;
|
|
63
|
+
}
|
|
64
|
+
return false;
|
|
65
|
+
}
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import * as path from "node:path";
|
|
2
|
+
import { probeSourcePath, readSourceDirectory } from "../../resources/source-files.ts";
|
|
3
|
+
import { ancestors, packageResult, type ResolutionIO } from "./shared.ts";
|
|
4
|
+
|
|
5
|
+
interface Replace { from: string; version?: string; to: string; remoteVersion?: string; directory: string }
|
|
6
|
+
function tokens(line: string): string[] {
|
|
7
|
+
const clean = line.replace(/"(?:\\.|[^"\\])*"|\/\/.*$/g, token => token.startsWith('"') ? token : "");
|
|
8
|
+
return (clean.match(/"(?:\\.|[^"\\])*"|[^\s]+/g) ?? []).map(token => token.startsWith('"') ? JSON.parse(token) : token);
|
|
9
|
+
}
|
|
10
|
+
function directives(text: string, kind: string): string[][] {
|
|
11
|
+
const result: string[][] = []; let block = false;
|
|
12
|
+
for (const line of text.split(/\r?\n/)) {
|
|
13
|
+
const parts = tokens(line); if (!parts.length) continue;
|
|
14
|
+
if (parts[0] === ")") { block = false; continue; }
|
|
15
|
+
if (parts[0] === kind) {
|
|
16
|
+
if (parts[1] === "(") block = true;
|
|
17
|
+
else result.push(parts.slice(1));
|
|
18
|
+
} else if (block) result.push(parts);
|
|
19
|
+
}
|
|
20
|
+
return result;
|
|
21
|
+
}
|
|
22
|
+
function replacements(text: string, directory: string): Replace[] {
|
|
23
|
+
return directives(text, "replace").map(parts => {
|
|
24
|
+
const arrow = parts.indexOf("=>");
|
|
25
|
+
if (![1, 2].includes(arrow) || ![arrow + 2, arrow + 3].includes(parts.length)) throw new Error("malformed_go_replace");
|
|
26
|
+
return { from: parts[0]!, version: arrow === 2 ? parts[1] : undefined, to: parts[arrow + 1]!, remoteVersion: parts[arrow + 2], directory };
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
function moduleName(text: string): string {
|
|
30
|
+
const names = directives(text, "module");
|
|
31
|
+
if (names.length !== 1 || names[0]!.length !== 1) throw new Error("malformed_go_mod");
|
|
32
|
+
return names[0]![0]!;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function resolveGo(io: ResolutionIO, target: string, source: string, stdlib: ReadonlySet<string>) {
|
|
36
|
+
const dirs = ancestors(io, source);
|
|
37
|
+
const mods = dirs.map(dir => ({ dir, text: io.read(path.join(dir, "go.mod")) }));
|
|
38
|
+
const own = mods.find(mod => mod.text !== undefined);
|
|
39
|
+
if (!own) return io.finish("unsupported", "go_mod_missing");
|
|
40
|
+
const ownName = moduleName(own.text!);
|
|
41
|
+
const matches = (name: string) => target === name || target.startsWith(name + "/");
|
|
42
|
+
if (!matches(ownName) && stdlib.has(target.split("/")[0]!)) return io.finish("external", "go_standard_library");
|
|
43
|
+
const works = dirs.map(dir => ({ dir, text: io.read(path.join(dir, "go.work")) }));
|
|
44
|
+
const work = works.find(work => work.text !== undefined);
|
|
45
|
+
const modules = new Map<string, string[]>();
|
|
46
|
+
const addModule = (dir: string, text?: string) => {
|
|
47
|
+
io.check(dir);
|
|
48
|
+
const content = text ?? io.read(path.join(dir, "go.mod"));
|
|
49
|
+
if (content === undefined) throw new Error("go_workspace_module_missing");
|
|
50
|
+
const name = moduleName(content);
|
|
51
|
+
modules.set(name, [...new Set([...(modules.get(name) ?? []), dir])]);
|
|
52
|
+
};
|
|
53
|
+
if (work) {
|
|
54
|
+
for (const use of directives(work.text!, "use")) {
|
|
55
|
+
if (use.length !== 1) throw new Error("malformed_go_work_use");
|
|
56
|
+
addModule(path.resolve(work.dir, use[0]!));
|
|
57
|
+
}
|
|
58
|
+
if (!modules.get(ownName)?.includes(own.dir)) return io.finish("unsupported", "go_source_module_not_in_workspace");
|
|
59
|
+
} else addModule(own.dir, own.text);
|
|
60
|
+
const required = new Map(directives(own.text!, "require").map(parts => [parts[0]!, parts[1]]));
|
|
61
|
+
const moduleReplaces = replacements(own.text!, own.dir);
|
|
62
|
+
const workReplaces = work ? replacements(work.text!, work.dir) : [];
|
|
63
|
+
const allNames = [...new Set([...modules.keys(), ...moduleReplaces.map(r => r.from), ...workReplaces.map(r => r.from)])]
|
|
64
|
+
.filter(matches).sort((a, b) => b.length - a.length);
|
|
65
|
+
const name = allNames[0];
|
|
66
|
+
if (name) {
|
|
67
|
+
const select = (entries: Replace[]) => entries.filter(r => r.from === name && (!r.version || r.version === required.get(name)))
|
|
68
|
+
.sort((a, b) => Number(Boolean(b.version)) - Number(Boolean(a.version)));
|
|
69
|
+
const candidates = select(workReplaces).length ? select(workReplaces) : select(moduleReplaces);
|
|
70
|
+
const replacement = candidates[0];
|
|
71
|
+
if (candidates.length > 1 && candidates[1]!.version === replacement!.version) return io.finish("ambiguous", "multiple_go_replacements");
|
|
72
|
+
let roots = modules.get(name) ?? [];
|
|
73
|
+
if (replacement) {
|
|
74
|
+
if (!modules.has(name) && !required.has(name)) return io.finish("unresolved", "go_module_not_required");
|
|
75
|
+
if (replacement.remoteVersion) return required.has(name) ? io.finish("external", "go_replaced_required_module") : io.finish("unresolved", "go_module_not_required");
|
|
76
|
+
if (!replacement.to.startsWith(".") && !path.isAbsolute(replacement.to)) return io.finish("unsupported", "go_replace_target_not_local");
|
|
77
|
+
roots = [path.resolve(replacement.directory, replacement.to)];
|
|
78
|
+
io.check(roots[0]!);
|
|
79
|
+
if (io.read(path.join(roots[0]!, "go.mod")) === undefined) return io.finish("unresolved", "go_replacement_module_missing");
|
|
80
|
+
}
|
|
81
|
+
if (roots.length !== 1) return io.finish(roots.length ? "ambiguous" : "unresolved", "go_module_root_not_unique");
|
|
82
|
+
const root = roots[0]!;
|
|
83
|
+
const directory = path.resolve(root, target.slice(name.length).replace(/^\//, "")); io.check(directory);
|
|
84
|
+
for (let dir = directory; dir !== root; dir = path.dirname(dir)) {
|
|
85
|
+
if (!dir.startsWith(root + path.sep)) return io.finish("unsupported", "outside_module");
|
|
86
|
+
if (io.read(path.join(dir, "go.mod")) !== undefined) return io.finish("unsupported", "nested_go_mod");
|
|
87
|
+
}
|
|
88
|
+
if (probeSourcePath(directory) !== "directory") return io.finish("unresolved", "go_package_missing");
|
|
89
|
+
const files: string[] = []; let conditional = false;
|
|
90
|
+
for (const entry of readSourceDirectory(directory)) {
|
|
91
|
+
if (!entry.name.endsWith(".go") || entry.name.endsWith("_test.go")) continue;
|
|
92
|
+
const file = path.join(directory, entry.name); io.check(file);
|
|
93
|
+
const content = io.read(file); if (content === undefined) continue;
|
|
94
|
+
conditional ||= /^\s*\/\/\s*(?:go:build|\+build)\b/m.test(content) || /_(?:linux|windows|darwin|freebsd|openbsd|netbsd|android|ios|amd64|arm64|386|arm)(?:_(?:amd64|arm64|386|arm))?\.go$/.test(entry.name);
|
|
95
|
+
files.push(path.relative(io.root, file).replace(/\\/g, "/"));
|
|
96
|
+
}
|
|
97
|
+
const result = packageResult(io, files, files.length ? "go_module_package" : "go_package_empty");
|
|
98
|
+
if (conditional) result.coverage = "conditional";
|
|
99
|
+
return result;
|
|
100
|
+
}
|
|
101
|
+
if ([...required.keys()].some(matches)) return io.finish("external", "go_required_module");
|
|
102
|
+
return io.finish("unresolved", "go_module_not_declared");
|
|
103
|
+
}
|