@dimassetoid/septum-mcp 0.0.0-stage → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (119) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +142 -2
  3. package/bin/septum.ts +4 -0
  4. package/package.json +70 -4
  5. package/scripts/postinstall.ts +25 -0
  6. package/src/cli/commands/check.ts +133 -0
  7. package/src/cli/commands/hook.ts +205 -0
  8. package/src/cli/commands/init.ts +570 -0
  9. package/src/cli/commands/serve.ts +5 -0
  10. package/src/cli/commands/sync.ts +39 -0
  11. package/src/cli/hook-payload.ts +43 -0
  12. package/src/cli/index.ts +124 -0
  13. package/src/cli/scaffold/harness-config.ts +661 -0
  14. package/src/cli/templates/hooks.ts +110 -0
  15. package/src/cli/templates/rules.ts +35 -0
  16. package/src/cli/templates/skill.ts +55 -0
  17. package/src/cli/ui/prompts.ts +122 -0
  18. package/src/core/boundary/evaluator.ts +426 -0
  19. package/src/core/boundary/staged-auditor.ts +120 -0
  20. package/src/core/config/domain-ownership.ts +45 -0
  21. package/src/core/config/loader.ts +174 -0
  22. package/src/core/config/schema.ts +59 -0
  23. package/src/core/database/client.ts +60 -0
  24. package/src/core/database/repositories/dependency.repository.ts +733 -0
  25. package/src/core/database/repositories/domain.repository.ts +373 -0
  26. package/src/core/database/repositories/file.repository.ts +117 -0
  27. package/src/core/database/repositories/meta.repository.ts +33 -0
  28. package/src/core/database/repositories/symbol.repository.ts +647 -0
  29. package/src/core/database/repository.ts +358 -0
  30. package/src/core/database/schema.ts +123 -0
  31. package/src/core/discovery/navigation.ts +105 -0
  32. package/src/core/discovery/topology-detector.ts +863 -0
  33. package/src/core/ingestion/hasher.ts +5 -0
  34. package/src/core/ingestion/pipeline.ts +590 -0
  35. package/src/core/parser/behavioral-analyzer.ts +123 -0
  36. package/src/core/parser/boundary-tracker.ts +458 -0
  37. package/src/core/parser/extractors/base.ts +71 -0
  38. package/src/core/parser/extractors/blade.ts +159 -0
  39. package/src/core/parser/extractors/csharp.ts +248 -0
  40. package/src/core/parser/extractors/django-semantic.ts +655 -0
  41. package/src/core/parser/extractors/elysia-semantic.ts +517 -0
  42. package/src/core/parser/extractors/express-semantic.ts +429 -0
  43. package/src/core/parser/extractors/fastapi-semantic.ts +702 -0
  44. package/src/core/parser/extractors/fastify-semantic.ts +759 -0
  45. package/src/core/parser/extractors/flask-semantic.ts +482 -0
  46. package/src/core/parser/extractors/frontend.ts +149 -0
  47. package/src/core/parser/extractors/go-semantic.ts +670 -0
  48. package/src/core/parser/extractors/go.ts +491 -0
  49. package/src/core/parser/extractors/hono-semantic.ts +546 -0
  50. package/src/core/parser/extractors/java.ts +227 -0
  51. package/src/core/parser/extractors/laravel-semantic.ts +1150 -0
  52. package/src/core/parser/extractors/mcp-cli-semantic.ts +367 -0
  53. package/src/core/parser/extractors/nestjs-semantic.ts +527 -0
  54. package/src/core/parser/extractors/php.ts +585 -0
  55. package/src/core/parser/extractors/python.ts +503 -0
  56. package/src/core/parser/extractors/registry.ts +99 -0
  57. package/src/core/parser/extractors/ruby.ts +237 -0
  58. package/src/core/parser/extractors/rust.ts +304 -0
  59. package/src/core/parser/extractors/semantic-extractor.interface.ts +24 -0
  60. package/src/core/parser/extractors/symfony-semantic.ts +321 -0
  61. package/src/core/parser/extractors/typescript.ts +839 -0
  62. package/src/core/parser/implementation-fingerprint.ts +97 -0
  63. package/src/core/parser/language-capabilities.ts +87 -0
  64. package/src/core/parser/schema/providers/laravel-migration-provider.ts +239 -0
  65. package/src/core/parser/schema/schema-provider-registry.ts +41 -0
  66. package/src/core/parser/schema/schema-provider.interface.ts +34 -0
  67. package/src/core/parser/semantic-revision.ts +3 -0
  68. package/src/core/parser/static-string.ts +51 -0
  69. package/src/core/parser/tree-sitter.ts +63 -0
  70. package/src/core/parser/wasm-assets.ts +25 -0
  71. package/src/core/parser/wasm-loader.ts +274 -0
  72. package/src/core/resolver/call-graph-tracer.ts +1033 -0
  73. package/src/core/resolver/import-resolver.ts +365 -0
  74. package/src/core/resolver/interpretation-inputs.ts +7 -0
  75. package/src/core/resolver/languages/go.ts +103 -0
  76. package/src/core/resolver/languages/managed.ts +200 -0
  77. package/src/core/resolver/languages/python.ts +115 -0
  78. package/src/core/resolver/languages/ruby.ts +40 -0
  79. package/src/core/resolver/languages/rust.ts +127 -0
  80. package/src/core/resolver/languages/shared.ts +71 -0
  81. package/src/core/resolver/module-resolver.ts +486 -0
  82. package/src/core/resolver/path-resolver.ts +200 -0
  83. package/src/core/resolver/slice-catalog.ts +79 -0
  84. package/src/core/resolver/slice-format.ts +9 -0
  85. package/src/core/resolver/symbol-impact.ts +381 -0
  86. package/src/core/resolver/symbol-locator.ts +276 -0
  87. package/src/core/resolver/symbol-reference.ts +53 -0
  88. package/src/core/resolver/vertical-slice-tracer.ts +344 -0
  89. package/src/core/resources/ignore.ts +144 -0
  90. package/src/core/resources/limits.ts +14 -0
  91. package/src/core/resources/source-files.ts +185 -0
  92. package/src/core/resources/source-inventory.ts +55 -0
  93. package/src/core/resources/work-queue.ts +74 -0
  94. package/src/core/retrieval/context-page.ts +109 -0
  95. package/src/core/retrieval/context.ts +320 -0
  96. package/src/core/retrieval/resolution-warnings.ts +21 -0
  97. package/src/core/retrieval/symbol-evidence.ts +97 -0
  98. package/src/core/retrieval/typescript-references.ts +262 -0
  99. package/src/core/telemetry/telemetry.ts +142 -0
  100. package/src/index.ts +18 -0
  101. package/src/mcp/schemas.ts +746 -0
  102. package/src/mcp/server.ts +600 -0
  103. package/src/mcp/tools/boundary.ts +17 -0
  104. package/src/mcp/tools/check-boundary.ts +382 -0
  105. package/src/mcp/tools/get-domain-catalog.ts +39 -0
  106. package/src/mcp/tools/get-symbol-impact.ts +104 -0
  107. package/src/mcp/tools/get-symbol.ts +399 -0
  108. package/src/mcp/tools/locate-symbol.ts +236 -0
  109. package/src/mcp/tools/map.ts +26 -0
  110. package/src/mcp/tools/register-domain.ts +113 -0
  111. package/src/mcp/tools/slice.ts +16 -0
  112. package/src/mcp/tools/symbol.ts +95 -0
  113. package/src/mcp/tools/trace-vertical-slice.ts +106 -0
  114. package/src/mcp/workspace-manager.ts +170 -0
  115. package/src/mcp/workspace-watcher.ts +202 -0
  116. package/src/types/index.ts +438 -0
  117. package/src/types/wasm.d.ts +4 -0
  118. package/src/utils/version-check.ts +209 -0
  119. package/src/version.ts +1 -0
@@ -0,0 +1,365 @@
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";
8
+ import * as path from "node:path";
9
+ import { builtinModules } from "node:module";
10
+ import { computeContentHash } from "../ingestion/hasher.ts";
11
+ import { readSourceFile, probeSourcePath, readSourceDirectory } from "../resources/source-files.ts";
12
+ import type { ImportResolution, ResolutionTarget } from "../../types/index.ts";
13
+
14
+ export const RESOLVER_REVISION = "5";
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(" "));
16
+
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(" "));
18
+
19
+
20
+ const PHP_STDLIB = new Set([
21
+ "stdClass", "Exception", "ErrorException", "Error", "TypeError", "ValueError", "ArgumentCountError",
22
+ "ArithmeticError", "DivisionByZeroError", "ParseError", "AssertionError", "DateTime", "DateTimeImmutable",
23
+ "DateTimeZone", "DateInterval", "DatePeriod", "PDO", "PDOStatement", "PDOException", "Closure", "Generator",
24
+ "Fiber", "Throwable", "Stringable", "Countable", "Iterator", "IteratorAggregate", "Traversable", "ArrayAccess",
25
+ "Serializable", "SplFileInfo", "SplFileObject", "SplFixedArray", "SplDoublyLinkedList", "SplQueue", "SplStack",
26
+ "SplHeap", "SplMinHeap", "SplMaxHeap", "SplPriorityQueue", "SplObserver", "SplSubject", "Reflection",
27
+ "ReflectionClass", "ReflectionMethod", "ReflectionFunction", "ReflectionProperty", "ReflectionParameter",
28
+ "ReflectionType", "ReflectionNamedType", "ReflectionUnionType", "ReflectionIntersectionType", "ReflectionAttribute",
29
+ "ReflectionEnum", "ReflectionEnumUnitCase", "ReflectionEnumBackedCase", "JsonException", "DomainException",
30
+ "InvalidArgumentException", "LengthException", "LogicException", "OutOfBoundsException", "OutOfRangeException",
31
+ "OverflowException", "RangeException", "RuntimeException", "UnderflowException", "UnexpectedValueException",
32
+ "BadFunctionCallException", "BadMethodCallException", "Attribute"
33
+ ]);
34
+
35
+ /** Static, workspace-contained resolution. No manifest scripts, downloads or retained cache. */
36
+ export class ImportResolver {
37
+ private root: string;
38
+ constructor(root: string, private packageRoots: string[] = []) { this.root = path.resolve(root); }
39
+
40
+ public resolve(target: string, sourceFile: string, statement?: string): ImportResolution {
41
+ const manifests: Record<string, string> = {};
42
+ const contents = new Map<string, string | undefined>();
43
+ let bytesRead = 0;
44
+ const result: ImportResolution = {
45
+ status: "unresolved", targets: [], reason: "target_not_found", coverage: "partial",
46
+ resolver_revision: RESOLVER_REVISION, config_revision: "", source: { file: sourceFile, target },
47
+ };
48
+ const finish = (status: ImportResolution["status"], reason: string, targets: ResolutionTarget[] = []) => ({
49
+ ...result, status, reason, targets,
50
+ config_revision: computeContentHash(JSON.stringify({ root: this.root, revision: RESOLVER_REVISION, manifests })),
51
+ });
52
+ const read = (file: string): string | undefined => {
53
+ this.assertContained(file);
54
+ if (contents.has(file)) return contents.get(file);
55
+ if (probeSourcePath(file) === "missing") { manifests[path.relative(this.root, file)] = "missing"; return undefined; }
56
+ const text = readSourceFile(file);
57
+ bytesRead += Buffer.byteLength(text, "utf8");
58
+ if (bytesRead > 16 * 1024 * 1024) throw new Error("resolution_source_byte_limit");
59
+ contents.set(file, text);
60
+ manifests[path.relative(this.root, file)] = computeContentHash(text); return text;
61
+ };
62
+ const json = (file: string): any => {
63
+ const raw = read(file); if (raw === undefined) return {};
64
+ const clean = raw.replace(/"(?:\\.|[^"\\])*"|\/\/[^\r\n]*|\/\*[\s\S]*?\*\//g, token => token.startsWith('"') ? token : " ")
65
+ .replace(/"(?:\\.|[^"\\])*"|,\s*[}\]]/g, token => token.startsWith('"') ? token : token.slice(1));
66
+ const parsed = JSON.parse(clean);
67
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error("malformed_manifest");
68
+ return parsed;
69
+ };
70
+ const filesAt = (base: string, extensions: string[]): string[] => {
71
+ this.assertContained(base);
72
+ const extraCandidates: string[] = [];
73
+ if (base.endsWith(".js")) {
74
+ const stripped = base.slice(0, -3);
75
+ extraCandidates.push(stripped + ".ts", stripped + ".tsx", stripped + ".d.ts", path.join(stripped, "index.ts"));
76
+ } else if (base.endsWith(".mjs")) {
77
+ const stripped = base.slice(0, -4);
78
+ extraCandidates.push(stripped + ".mts", stripped + ".d.mts");
79
+ } else if (base.endsWith(".cjs")) {
80
+ const stripped = base.slice(0, -4);
81
+ extraCandidates.push(stripped + ".cts", stripped + ".d.cts");
82
+ } else if (base.endsWith(".jsx")) {
83
+ const stripped = base.slice(0, -4);
84
+ extraCandidates.push(stripped + ".tsx");
85
+ }
86
+ const candidates = [base, ...extraCandidates, ...extensions.map(ext => base + ext), ...extensions.map(ext => path.join(base, "index" + ext))];
87
+ return [...new Set(candidates.filter(file => {
88
+ this.assertContained(file);
89
+ return probeSourcePath(file) === "file";
90
+ }).map(file => path.relative(this.root, file).replace(/\\/g, "/")))];
91
+ };
92
+ const resolvedFiles = (files: string[], reason: string) => {
93
+ const unique = [...new Set(files)].sort();
94
+ return finish(unique.length === 1 ? "resolved" : unique.length > 1 ? "ambiguous" : "unresolved", reason,
95
+ unique.map(file => ({ kind: "file", files: [file] })));
96
+ };
97
+ try {
98
+ if (target.startsWith("dynamic:")) return finish("unresolved", "dynamic_target");
99
+ const source = path.resolve(this.root, sourceFile); this.assertContained(source);
100
+ const ext = path.extname(source).toLowerCase();
101
+ const io: ResolutionIO = { root: this.root, read, check: file => this.assertContained(file), finish };
102
+ if (ext === ".go") return resolveGo(io, target, sourceFile, GO_STDLIB);
103
+ if (ext === ".py") return resolvePython(io, target, sourceFile, this.packageRoots, PYTHON_STDLIB);
104
+ if (ext === ".rb") return resolveRuby(io, target, sourceFile, statement);
105
+ if (ext === ".rs") return resolveRust(io, target, sourceFile);
106
+ if (ext === ".java") return resolveJava(io, target, sourceFile, statement);
107
+ if (ext === ".cs") return resolveCSharp(io, target, sourceFile, statement);
108
+ if (ext === ".php") {
109
+ let rawTarget = target.trim();
110
+ const useMatch = rawTarget.match(/^use\s+(?:function\s+|const\s+)?([^;\s]+)(?:\s+as\s+[^;\s]+)?\s*;?$/i);
111
+ if (useMatch) {
112
+ rawTarget = useMatch[1]!;
113
+ } else {
114
+ rawTarget = rawTarget.replace(/;+$/, "").trim();
115
+ }
116
+ if (rawTarget.endsWith(".php")) {
117
+ const absPhp = path.resolve(this.root, rawTarget.replace(/^\.\//, ""));
118
+ this.assertContained(absPhp);
119
+ if (probeSourcePath(absPhp) === "file") {
120
+ return resolvedFiles([path.relative(this.root, absPhp).replace(/\\/g, "/")], "php_file_path");
121
+ }
122
+ return finish("unresolved", "file_not_found");
123
+ }
124
+ const normTarget = rawTarget.replace(/^\\/, "");
125
+ if (
126
+ PHP_STDLIB.has(normTarget) ||
127
+ normTarget.startsWith("Attribute") ||
128
+ normTarget.startsWith("ReturnTypeWillChange")
129
+ ) {
130
+ return finish("external", "php_standard_library");
131
+ }
132
+
133
+ let composerDir = this.root;
134
+ for (let dir = path.dirname(source); dir === this.root || dir.startsWith(this.root + path.sep); dir = path.dirname(dir)) {
135
+ if (probeSourcePath(path.join(dir, "composer.json")) !== "missing") {
136
+ composerDir = dir;
137
+ break;
138
+ }
139
+ if (dir === this.root) break;
140
+ }
141
+ const composer = json(path.join(composerDir, "composer.json"));
142
+ const rules = { ...(composer.autoload?.["psr-4"] ?? {}), ...(composer["autoload-dev"]?.["psr-4"] ?? {}) };
143
+ const matches = Object.keys(rules)
144
+ .filter((prefix) => normTarget.startsWith(prefix.replace(/^\\/, "")))
145
+ .sort((a, b) => b.length - a.length);
146
+
147
+ if (matches.length > 0) {
148
+ const prefix = matches[0]!;
149
+ const cleanPrefix = prefix.replace(/^\\/, "");
150
+ const dirs = Array.isArray(rules[prefix]) ? rules[prefix] : [rules[prefix]];
151
+ if (!dirs.every((d: unknown) => typeof d === "string")) return finish("unsupported", "malformed_psr4");
152
+
153
+ const relativePath = normTarget.slice(cleanPrefix.length).replace(/\\/g, "/");
154
+ const candidateFiles: string[] = [];
155
+ for (const dir of dirs) {
156
+ const absBase = path.resolve(composerDir, dir, relativePath);
157
+ this.assertContained(absBase);
158
+ candidateFiles.push(...filesAt(absBase, [".php"]));
159
+ }
160
+
161
+ if (candidateFiles.length === 0) {
162
+ return finish("unresolved", "file_not_found");
163
+ }
164
+ return resolvedFiles(candidateFiles, "composer_psr4");
165
+ }
166
+
167
+ // Check installed Composer vendor PSR-4 autoload map (covers transitive & non-matching package names like Carbon\*, Inertia\*)
168
+ const autoloadPsr4 = read(path.join(composerDir, "vendor", "composer", "autoload_psr4.php"));
169
+ if (autoloadPsr4) {
170
+ for (const m of autoloadPsr4.matchAll(/['"]([^'"]+)['"]\s*=>/g)) {
171
+ const prefix = m[1]!.replace(/\\\\/g, "\\").replace(/^\\/, "");
172
+ if (prefix && normTarget.startsWith(prefix)) {
173
+ return finish("external", "composer_vendor_psr4");
174
+ }
175
+ }
176
+ }
177
+
178
+ // Fallback: check composer.lock PSR-4 declarations when vendor/ is absent
179
+ const composerLockRaw = read(path.join(composerDir, "composer.lock"));
180
+ if (composerLockRaw) {
181
+ const lock = JSON.parse(composerLockRaw);
182
+ const lockPackages = [
183
+ ...(Array.isArray(lock?.packages) ? lock.packages : []),
184
+ ...(Array.isArray(lock?.["packages-dev"]) ? lock["packages-dev"] : []),
185
+ ];
186
+ for (const pkgEntry of lockPackages) {
187
+ const psr4 = pkgEntry?.autoload?.["psr-4"];
188
+ if (psr4 && typeof psr4 === "object") {
189
+ for (const prefix of Object.keys(psr4)) {
190
+ const cleanPrefix = prefix.replace(/^\\/, "");
191
+ if (cleanPrefix && normTarget.startsWith(cleanPrefix)) {
192
+ return finish("external", "composer_lock_package");
193
+ }
194
+ }
195
+ }
196
+ }
197
+ }
198
+
199
+ // Check declared composer dependencies
200
+ const requirements = { ...(composer.require ?? {}), ...(composer["require-dev"] ?? {}) };
201
+ const topNamespace = normTarget.split("\\")[0]!.toLowerCase();
202
+ for (const reqPackage of Object.keys(requirements)) {
203
+ const [vendor, pkg] = reqPackage.toLowerCase().split("/");
204
+ if (
205
+ vendor === topNamespace ||
206
+ pkg === topNamespace ||
207
+ (vendor === "laravel" && topNamespace === "illuminate") ||
208
+ (vendor === "symfony" && topNamespace === "symfony") ||
209
+ (vendor === "guzzlehttp" && topNamespace === "guzzlehttp")
210
+ ) {
211
+ return finish("external", "composer_required_package");
212
+ }
213
+ }
214
+
215
+ if (
216
+ normTarget.startsWith("Illuminate\\") ||
217
+ normTarget.startsWith("Symfony\\") ||
218
+ normTarget.startsWith("Psr\\") ||
219
+ normTarget.startsWith("Composer\\")
220
+ ) {
221
+ return finish("external", "php_framework_namespace");
222
+ }
223
+
224
+ return finish("unresolved", "php_namespace_not_mapped");
225
+ }
226
+ if (!/\.(?:[cm]?[jt]sx?|vue|astro|svelte)$/.test(ext)) return finish("unsupported", "language_resolver_unavailable");
227
+ const extensions = [".ts", ".tsx", ".mts", ".cts", ".js", ".jsx", ".mjs", ".cjs", ".d.ts", ".json"];
228
+ if (target.startsWith(".") || path.isAbsolute(target)) return resolvedFiles(filesAt(path.resolve(path.dirname(source), target), extensions), "relative_path");
229
+ if (builtinModules.includes(target) || target.startsWith("node:") && builtinModules.includes(target.slice(5)) || target === "bun" || target.startsWith("bun:")) return finish("external", "runtime_builtin");
230
+ let nearestTsConfig = path.join(this.root, "tsconfig.json");
231
+ let nearestPkgDir = this.root;
232
+ let foundTsConfig = false;
233
+ let foundPkg = false;
234
+ for (let dir = path.dirname(source); dir === this.root || dir.startsWith(this.root + path.sep); dir = path.dirname(dir)) {
235
+ if (!foundTsConfig && probeSourcePath(path.join(dir, "tsconfig.json")) !== "missing") {
236
+ nearestTsConfig = path.join(dir, "tsconfig.json");
237
+ foundTsConfig = true;
238
+ }
239
+ if (!foundPkg && probeSourcePath(path.join(dir, "package.json")) !== "missing") {
240
+ nearestPkgDir = dir;
241
+ foundPkg = true;
242
+ }
243
+ if (foundTsConfig && foundPkg) break;
244
+ if (dir === this.root) break;
245
+ }
246
+ const loadTsConfig = (configPath: string, visited = new Set<string>()): any => {
247
+ if (visited.has(configPath)) throw new Error("circular_tsconfig_extends");
248
+ visited.add(configPath);
249
+ const cfg = json(configPath);
250
+ let options: any = {};
251
+ const extendsList = cfg.extends === undefined ? [] : Array.isArray(cfg.extends) ? cfg.extends : [cfg.extends];
252
+ for (const extRef of extendsList) {
253
+ if (typeof extRef !== "string") throw new Error("malformed_tsconfig_extends");
254
+ const base = extRef.startsWith(".") || path.isAbsolute(extRef)
255
+ ? path.resolve(path.dirname(configPath), extRef)
256
+ : path.resolve(this.root, "node_modules", extRef);
257
+ this.assertContained(base);
258
+ let parentPath = base.endsWith(".json") ? base : base + ".json";
259
+ if (probeSourcePath(parentPath) === "missing" && probeSourcePath(base) === "directory") {
260
+ const pkg = json(path.join(base, "package.json"));
261
+ parentPath = path.resolve(base, typeof pkg.tsconfig === "string" ? pkg.tsconfig : "tsconfig.json");
262
+ }
263
+ this.assertContained(parentPath);
264
+ if (probeSourcePath(parentPath) === "missing") throw new Error("tsconfig_extends_not_found");
265
+ options = { ...options, ...loadTsConfig(parentPath, visited) };
266
+ }
267
+ const own = cfg.compilerOptions ?? {};
268
+ if (typeof own !== "object" || Array.isArray(own)) throw new Error("malformed_tsconfig_options");
269
+ options = { ...options, ...own };
270
+ if (Object.hasOwn(own, "baseUrl")) {
271
+ if (typeof own.baseUrl !== "string") throw new Error("malformed_tsconfig_baseurl");
272
+ options.baseUrl = path.resolve(path.dirname(configPath), own.baseUrl);
273
+ }
274
+ if (Object.hasOwn(own, "paths")) options.pathsBase = path.dirname(configPath);
275
+ visited.delete(configPath);
276
+ return options;
277
+ };
278
+
279
+ const options = loadTsConfig(nearestTsConfig);
280
+ const aliases = options.paths ?? {};
281
+ if (typeof aliases !== "object" || Array.isArray(aliases)) return finish("unsupported", "malformed_ts_paths");
282
+ const matching = Object.keys(aliases).filter(key => {
283
+ const star = key.indexOf("*");
284
+ return star < 0 ? target === key : key.indexOf("*", star + 1) < 0 && target.startsWith(key.slice(0, star)) && target.endsWith(key.slice(star + 1)) && target.length >= key.length - 1;
285
+ }).sort((a,b) => (b.includes("*") ? b.indexOf("*") : Number.MAX_SAFE_INTEGER) - (a.includes("*") ? a.indexOf("*") : Number.MAX_SAFE_INTEGER));
286
+ if (matching.length) {
287
+ const key = matching[0]!; const values = aliases[key];
288
+ if (!Array.isArray(values) || !values.every(v=>typeof v === "string")) return finish("unsupported", "malformed_ts_paths");
289
+ for (const value of values as string[]) {
290
+ const star = key.indexOf("*");
291
+ const matched = star < 0 ? "" : target.slice(star, target.length - (key.length - star - 1));
292
+ const files = filesAt(path.resolve(options.baseUrl ?? options.pathsBase ?? this.root, value.replace("*", matched)), extensions);
293
+ if (files.length) return resolvedFiles(files, "tsconfig_paths");
294
+ }
295
+ }
296
+ if (options.baseUrl && !matching.length) {
297
+ const baseFiles = filesAt(path.resolve(options.baseUrl, target), extensions);
298
+ if (baseFiles.length) return resolvedFiles(baseFiles, "tsconfig_baseurl");
299
+ }
300
+ if (!options.baseUrl && !matching.length) {
301
+ const local = target.startsWith("@/") ? target.replace(/^@\//,"src/") : target;
302
+ const localFiles = filesAt(path.resolve(this.root,local),extensions);
303
+ if (localFiles.length) return resolvedFiles(localFiles,"workspace_path");
304
+ }
305
+ const pkg = json(path.join(this.root,"package.json"));
306
+ const localPkg = nearestPkgDir !== this.root ? json(path.join(nearestPkgDir, "package.json")) : {};
307
+ const workspacePatterns = Array.isArray(pkg.workspaces) ? pkg.workspaces : pkg.workspaces?.packages ?? [];
308
+ const roots = [...this.packageRoots];
309
+ for (const pattern of workspacePatterns) {
310
+ if (typeof pattern !== "string") return finish("unsupported","malformed_workspace_pattern");
311
+ if (pattern.endsWith("/*")) {
312
+ const parent = path.resolve(this.root,pattern.slice(0,-2)); this.assertContained(parent);
313
+ if (probeSourcePath(parent) !== "missing") roots.push(...readSourceDirectory(parent).filter(entry=>entry.isDirectory()).map(entry=>path.relative(this.root,path.join(parent,entry.name))));
314
+ } else if (!pattern.includes("*")) roots.push(pattern);
315
+ else return finish("unsupported","workspace_glob_not_supported");
316
+ }
317
+ const workspaceFiles: string[] = [];
318
+ for (const directory of [...new Set(roots)]) {
319
+ const workspace = json(path.resolve(this.root,directory,"package.json"));
320
+ if (typeof workspace.name !== "string" || !(target === workspace.name || target.startsWith(workspace.name + "/"))) continue;
321
+ const subpath = target.slice(workspace.name.length).replace(/^\//, "");
322
+ let resolvedEntry: string | undefined;
323
+
324
+ if (!subpath) {
325
+ const exported = typeof workspace.exports === "string" ? workspace.exports : workspace.exports?.["."];
326
+ if (typeof exported === "string") {
327
+ resolvedEntry = exported;
328
+ } else if (exported && typeof exported === "object") {
329
+ resolvedEntry = exported.import || exported.default || exported.require || exported.types;
330
+ if (typeof resolvedEntry !== "string") return finish("unsupported", "conditional_package_exports");
331
+ }
332
+ } else if (workspace.exports && typeof workspace.exports === "object") {
333
+ const subExport = workspace.exports["./" + subpath] ?? workspace.exports["./" + subpath + ".js"];
334
+ if (typeof subExport === "string") {
335
+ resolvedEntry = subExport;
336
+ } else if (subExport && typeof subExport === "object") {
337
+ resolvedEntry = subExport.import || subExport.default || subExport.require || subExport.types;
338
+ }
339
+ }
340
+
341
+ const entry = resolvedEntry || subpath || workspace.module || workspace.main || "index";
342
+ if (typeof entry !== "string") return finish("unsupported","package_entry_not_literal");
343
+ workspaceFiles.push(...filesAt(path.resolve(this.root,directory,entry),extensions));
344
+ }
345
+ if (workspaceFiles.length) return resolvedFiles(workspaceFiles,"workspace_package");
346
+ const name = target.startsWith("@") ? target.split("/").slice(0,2).join("/") : target.split("/")[0]!;
347
+ const depMaps = [
348
+ localPkg.dependencies, localPkg.devDependencies, localPkg.peerDependencies, localPkg.optionalDependencies,
349
+ pkg.dependencies, pkg.devDependencies, pkg.peerDependencies, pkg.optionalDependencies,
350
+ ];
351
+ if (depMaps.some(deps => deps && Object.hasOwn(deps, name))) return finish("external", "package_manifest_dependency");
352
+ return finish("unresolved", "package_not_declared");
353
+ } catch (error) {
354
+ return finish("unsupported", error instanceof Error && error.message.includes("outside_workspace") ? "outside_workspace" : `manifest_or_source_error: ${error instanceof Error ? error.message : String(error)}`);
355
+ }
356
+ }
357
+
358
+ private assertContained(file: string): void {
359
+ const contained = (candidate: string, root: string) => candidate === root || candidate.startsWith(root + path.sep);
360
+ if (!contained(path.resolve(file), this.root)) throw new Error("outside_workspace");
361
+ let existing = file;
362
+ while (!fs.existsSync(existing) && existing !== this.root) existing = path.dirname(existing);
363
+ if (fs.existsSync(existing) && !contained(fs.realpathSync(existing), fs.realpathSync(this.root))) throw new Error("outside_workspace");
364
+ }
365
+ }
@@ -0,0 +1,7 @@
1
+ import { basename } from "node:path";
2
+
3
+ /** Files whose staged bytes and watcher events can change import interpretation. */
4
+ export function isResolutionInput(file: string): boolean {
5
+ return /\.(?:json|jsonc|toml|ya?ml|xml|csproj|props|targets|gradle|gradle\.kts|gemspec|lock|txt|in)$/i.test(file) ||
6
+ /^(?:Gemfile|Pipfile|go\.mod|go\.work|artisan|nest-cli\.json)$/.test(basename(file));
7
+ }
@@ -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
+ }