Skip to content

armgit / Ix

Public Imported from GitHub
0

Understand any codebase instantly. System intelligence for codebases, built for humans and AI.

fix(ingest): resolve tsconfig module mappings

Hiro-Chiba7d834235b99d
diff --git a/core-ingestion/src/__tests__/resolveEdges.test.ts b/core-ingestion/src/__tests__/resolveEdges.test.ts
index 1a28b7c5..6dcbf3a0 100644
--- a/core-ingestion/src/__tests__/resolveEdges.test.ts
+++ b/core-ingestion/src/__tests__/resolveEdges.test.ts
@@ -287,6 +287,115 @@ describe('resolveEdges', () => {
});
});
+ it('prefers configured JS/TS module targets over unrelated stem matches', () => {
+ const consumer = parseFile(
+ '/repo/src/consumer.ts',
+ 'import { execute } from "@core";\nexport function run() { return execute(); }\n',
+ )!;
+ const intended = parseFile(
+ '/repo/src/adapters/worker.ts',
+ 'export function execute() { return "worker"; }\n',
+ )!;
+ const unrelated = parseFile(
+ '/repo/legacy/core.ts',
+ 'export function execute() { return "legacy"; }\n',
+ )!;
+
+ const resolved = resolveEdges([consumer, intended, unrelated], undefined, undefined, {
+ resolveModuleSpecifier: (_source, specifier) =>
+ specifier === '@core' ? ['/repo/src/adapters/worker.ts'] : undefined,
+ });
+
+ expect(resolved).toContainEqual(expect.objectContaining({
+ srcFilePath: '/repo/src/consumer.ts',
+ dstFilePath: '/repo/src/adapters/worker.ts',
+ predicate: 'IMPORTS',
+ confidence: 0.9,
+ }));
+ expect(resolved).toContainEqual(expect.objectContaining({
+ srcFilePath: '/repo/src/consumer.ts',
+ dstFilePath: '/repo/src/adapters/worker.ts',
+ predicate: 'CALLS',
+ confidence: 0.9,
+ }));
+ expect(resolved.some(edge => edge.dstFilePath === '/repo/legacy/core.ts')).toBe(false);
+ });
+
+ it('uses mapped runtime files for calls and declaration files for references', () => {
+ const consumer = parseFile(
+ '/repo/src/consumer.ts',
+ 'import { run, type Foo } from "@pkg";\n'
+ + 'export function call() { return run(); }\n'
+ + 'export function use(value: Foo) { return value; }\n',
+ )!;
+ const runtime = parseFile('/repo/lib/index.js', 'export function run() { return 1; }\n')!;
+ const declarations = parseFile('/repo/lib/index.d.ts', 'export interface Foo { id: string; }\n')!;
+
+ const resolved = resolveEdges([consumer, runtime, declarations], undefined, undefined, {
+ resolveModuleSpecifier: (_source, _specifier, kind) =>
+ kind === 'types' ? ['/repo/lib/index.d.ts'] : ['/repo/lib/index.js'],
+ });
+
+ expect(resolved).toContainEqual(expect.objectContaining({
+ dstFilePath: '/repo/lib/index.js',
+ predicate: 'CALLS',
+ confidence: 0.9,
+ }));
+ expect(resolved).toContainEqual(expect.objectContaining({
+ dstFilePath: '/repo/lib/index.d.ts',
+ predicate: 'REFERENCES',
+ confidence: 0.9,
+ }));
+ });
+
+ it('does not fall back to a stem when a configured JS/TS import is unresolved', () => {
+ const consumer = parseFile(
+ '/repo/src/consumer.ts',
+ 'import { execute } from "@core";\nexport function run() { return execute(); }\n',
+ )!;
+ const unrelated = parseFile(
+ '/repo/legacy/core.ts',
+ 'export function execute() { return "legacy"; }\n',
+ )!;
+
+ expect(resolveEdges([consumer, unrelated], undefined, undefined, {
+ resolveModuleSpecifier: () => [],
+ })).toEqual([]);
+ });
+
+ it('keeps transitive resolution when a configured module target is a barrel', () => {
+ const consumer = parseFile(
+ '/repo/app/consumer.ts',
+ 'import { execute } from "@pkg";\nexport function run() { return execute(); }\n',
+ )!;
+ const barrel = parseFile(
+ '/repo/pkg/index.ts',
+ 'export { execute } from "./worker.js";\n',
+ )!;
+ const worker = parseFile(
+ '/repo/pkg/worker.ts',
+ 'export function execute() { return "worker"; }\n',
+ )!;
+
+ const resolved = resolveEdges([consumer, barrel, worker], undefined, undefined, {
+ resolveModuleSpecifier: (_source, specifier) =>
+ specifier === '@pkg' ? ['/repo/pkg/index.ts'] : undefined,
+ });
+
+ expect(resolved).toContainEqual(expect.objectContaining({
+ srcFilePath: '/repo/app/consumer.ts',
+ dstFilePath: '/repo/pkg/index.ts',
+ predicate: 'IMPORTS',
+ confidence: 0.9,
+ }));
+ expect(resolved).toContainEqual(expect.objectContaining({
+ srcFilePath: '/repo/app/consumer.ts',
+ dstFilePath: '/repo/pkg/worker.ts',
+ predicate: 'CALLS',
+ confidence: 0.8,
+ }));
+ });
+
it('resolves a call through a provider export alias', () => {
const provider = parseFile(
'/repo/provider.ts',
diff --git a/core-ingestion/src/index.ts b/core-ingestion/src/index.ts
index 006c9c66..ae161bbf 100644
--- a/core-ingestion/src/index.ts
+++ b/core-ingestion/src/index.ts
@@ -3165,6 +3165,14 @@ export function resolveEdges(
// cross-repo gate so genuine edges survive even where import-to-package matching
// can't bridge the gap (e.g. Java's Maven artifactId vs `import com.google...`).
declaredRepoDeps?: Record<string, string[]>;
+ // Workspace-aware JS/TS module resolution supplied by the CLI. `undefined`
+ // preserves the existing fallback; an empty array is authoritative and
+ // prevents a configured import from falling through to an unrelated stem.
+ resolveModuleSpecifier?: (
+ srcFilePath: string,
+ specifier: string,
+ kind?: 'runtime' | 'types',
+ ) => string[] | undefined;
},
): ResolvedEdge[] {
// Provide a default no-op stats bag when caller passes none (backward compat).
@@ -3690,13 +3698,25 @@ export function resolveEdges(
srcLanguage: SupportedLanguages,
modName: unknown,
importRaw?: unknown,
+ kind: 'runtime' | 'types' = 'runtime',
): string[] {
+ const configuredMatches =
+ (srcLanguage === SupportedLanguages.JavaScript || srcLanguage === SupportedLanguages.TypeScript) &&
+ typeof importRaw === 'string' &&
+ !importRaw.startsWith('./') &&
+ !importRaw.startsWith('../')
+ ? opts?.resolveModuleSpecifier?.(srcFilePath, importRaw, kind)
+ : undefined;
+ const indexedConfiguredMatches = configuredMatches?.flatMap(filePath =>
+ normalizedPathToFiles.get(normalizedPathKey(filePath)) ?? []
+ ).filter(filePath => normalizedPathKey(filePath) !== normalizedPathKey(srcFilePath));
// fileLanguage only covers the current parse batch; cross-batch candidates
// come from the global stem index, so fall back to the extension-derived
// language (always available) — otherwise an undefined dst language would
// slip cross-language matches (e.g. a Python import -> a Rust/Elixir file).
- const importMatches = (resolveRelativeImportTargets(srcFilePath, srcLanguage, importRaw) ??
- modNameToFiles(modName, srcFilePath))
+ const importMatches = (configuredMatches === undefined
+ ? resolveRelativeImportTargets(srcFilePath, srcLanguage, importRaw) ?? modNameToFiles(modName, srcFilePath)
+ : indexedConfiguredMatches ?? [])
.filter(fp => importLanguageCompatible(srcLanguage, fileLanguage.get(fp) ?? languageFromPath(fp)));
if (srcLanguage !== SupportedLanguages.Go || importMatches.length <= 1) return importMatches;
return narrowGoImportCandidates(srcFilePath, modName, importMatches, files => {
@@ -3968,6 +3988,16 @@ export function resolveEdges(
const binding = rel.importBinding === false
? undefined
: importBindingsByLocal.get(srcFilePath)?.get(origDstName);
+ const configuredBindingTargets = binding &&
+ (srcLanguage === SupportedLanguages.JavaScript || srcLanguage === SupportedLanguages.TypeScript) &&
+ !binding.pkg.startsWith('./') &&
+ !binding.pkg.startsWith('../')
+ ? opts?.resolveModuleSpecifier?.(
+ srcFilePath,
+ binding.pkg,
+ rel.predicate === 'CALLS' ? 'runtime' : 'types',
+ )
+ : undefined;
// Tier 1: same-file — already correct in buildPatch, skip here. Check the
// call-site name before any import binding rewrite so a local shadow wins.
@@ -3986,7 +4016,28 @@ export function resolveEdges(
srcLanguage,
binding.pkg,
binding.pkg,
+ rel.predicate === 'CALLS' ? 'runtime' : 'types',
))];
+ if (
+ configuredBindingTargets !== undefined &&
+ providerFiles.length === 1 &&
+ fileHasSymbol.get(providerFiles[0])?.has(binding.imported)
+ ) {
+ const fp = providerFiles[0];
+ const dstQualifiedKey = bestQKey(fileQKeys, fp, binding.imported);
+ if (dstQualifiedKey !== null) {
+ resolved.push({
+ srcFilePath,
+ srcName,
+ dstFilePath: fp,
+ dstName: origDstName,
+ dstQualifiedKey,
+ predicate: rel.predicate,
+ confidence: 0.9,
+ });
+ continue;
+ }
+ }
const publicMatches: Array<{ fp: string; local: string }> = [];
for (const fp of providerFiles.length === 1 ? providerFiles : []) {
const local = filePublicNames.get(fp)?.get(binding.imported);
@@ -4120,6 +4171,7 @@ export function resolveEdges(
resolved.push({ srcFilePath, srcName, dstFilePath: fp, dstName: origDstName, dstQualifiedKey, predicate: rel.predicate, confidence: 0.8 });
continue;
}
+ if (configuredBindingTargets?.length === 0) continue;
if (rel.predicate === 'CALLS' && relativeCallBindings.get(srcFilePath)?.has(origDstName)) {
stats.skippedAmbiguous++;
continue;
diff --git a/ix-cli/src/cli/__tests__/ts-module-resolution.test.ts b/ix-cli/src/cli/__tests__/ts-module-resolution.test.ts
new file mode 100644
index 00000000..ed60db97
--- /dev/null
+++ b/ix-cli/src/cli/__tests__/ts-module-resolution.test.ts
@@ -0,0 +1,154 @@
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+
+import { afterEach, describe, expect, it } from "vitest";
+
+import { createTypeScriptModuleResolver } from "../ts-module-resolution.js";
+
+const workspaces: string[] = [];
+
+function workspace(): string {
+ const root = mkdtempSync(join(tmpdir(), "ix-ts-resolution-"));
+ workspaces.push(root);
+ return root;
+}
+
+function write(root: string, relativePath: string, content = ""): string {
+ const filePath = join(root, relativePath);
+ mkdirSync(dirname(filePath), { recursive: true });
+ writeFileSync(filePath, content);
+ return filePath;
+}
+
+afterEach(() => {
+ for (const root of workspaces.splice(0)) rmSync(root, { recursive: true, force: true });
+});
+
+describe("createTypeScriptModuleResolver", () => {
+ it("resolves tsconfig paths before an unrelated same-stem file", () => {
+ const root = workspace();
+ const config = write(
+ root,
+ "tsconfig.json",
+ `{
+ // JSONC comments and trailing commas are valid in tsconfig files.
+ "compilerOptions": {
+ "baseUrl": ".",
+ "paths": { "@core": ["src/adapters/worker"], },
+ },
+ }`,
+ );
+ const consumer = write(root, "src/consumer.ts");
+ const worker = write(root, "src/adapters/worker.ts");
+ const unrelated = write(root, "legacy/core.ts");
+ const resolve = createTypeScriptModuleResolver(root, [config, consumer, worker, unrelated]);
+
+ expect(resolve("src/consumer.ts", "@core")).toEqual(["src/adapters/worker.ts"]);
+ });
+
+ it("treats an unresolved matching paths rule as authoritative", () => {
+ const root = workspace();
+ const config = write(
+ root,
+ "tsconfig.json",
+ JSON.stringify({
+ compilerOptions: { paths: { "@core/*": ["src/core/*"] } },
+ }),
+ );
+ const consumer = write(root, "src/consumer.ts");
+ const unrelated = write(root, "legacy/missing.ts");
+ const resolve = createTypeScriptModuleResolver(root, [config, consumer, unrelated]);
+
+ expect(resolve("src/consumer.ts", "@core/missing")).toEqual([]);
+ });
+
+ it("resolves baseUrl modules", () => {
+ const root = workspace();
+ const config = write(
+ root,
+ "tsconfig.json",
+ JSON.stringify({
+ compilerOptions: { baseUrl: "src" },
+ }),
+ );
+ const consumer = write(root, "src/consumer.ts");
+ const worker = write(root, "src/services/worker.ts");
+ const unrelated = write(root, "vendor/worker.ts");
+ const resolve = createTypeScriptModuleResolver(root, [config, consumer, worker, unrelated]);
+
+ expect(resolve("src/consumer.ts", "services/worker")).toEqual(["src/services/worker.ts"]);
+ });
+
+ it("treats an unresolved baseUrl module as authoritative", () => {
+ const root = workspace();
+ const config = write(
+ root,
+ "tsconfig.json",
+ JSON.stringify({
+ compilerOptions: { baseUrl: "src" },
+ }),
+ );
+ const consumer = write(root, "src/consumer.ts");
+ const unrelated = write(root, "legacy/missing.ts");
+ const resolve = createTypeScriptModuleResolver(root, [config, consumer, unrelated]);
+
+ expect(resolve("src/consumer.ts", "services/missing")).toEqual([]);
+ });
+
+ it("prefers JavaScript for extensionless imports from JavaScript files", () => {
+ const root = workspace();
+ const config = write(
+ root,
+ "jsconfig.json",
+ JSON.stringify({
+ compilerOptions: { baseUrl: "src" },
+ }),
+ );
+ const consumer = write(root, "src/consumer.js");
+ const javascript = write(root, "src/services/worker.js");
+ const typescript = write(root, "src/services/worker.ts");
+ const resolve = createTypeScriptModuleResolver(root, [
+ config,
+ consumer,
+ javascript,
+ typescript,
+ ]);
+
+ expect(resolve("src/consumer.js", "services/worker")).toEqual(["src/services/worker.js"]);
+ });
+
+ it("matches mapped paths case-insensitively on case-insensitive filesystems", () => {
+ const root = workspace();
+ const config = write(
+ root,
+ "tsconfig.json",
+ JSON.stringify({ compilerOptions: { paths: { "@utils": ["src/utils"] } } }),
+ );
+ const consumer = write(root, "src/consumer.ts");
+ const actual = write(root, "src/Utils.ts");
+ const resolve = createTypeScriptModuleResolver(root, [config, consumer, actual], {
+ caseSensitive: false,
+ });
+
+ expect(resolve("src/consumer.ts", "@utils")).toEqual(["src/Utils.ts"]);
+ });
+
+ it("selects runtime and declaration targets for mapped JavaScript paths", () => {
+ const root = workspace();
+ const config = write(
+ root,
+ "tsconfig.json",
+ JSON.stringify({
+ compilerOptions: { paths: { "@sample/tool": ["lib/index.js"] } },
+ }),
+ );
+ const consumer = write(root, "apps/client.ts");
+ const declarations = write(root, "lib/index.d.ts");
+ const runtime = write(root, "lib/index.js");
+ const resolve = createTypeScriptModuleResolver(root, [config, consumer, declarations, runtime]);
+
+ expect(resolve("apps/client.ts", "@sample/tool", "runtime")).toEqual(["lib/index.js"]);
+ expect(resolve("apps/client.ts", "@sample/tool", "types")).toEqual(["lib/index.d.ts"]);
+ });
+});
diff --git a/ix-cli/src/cli/commands/ingest.ts b/ix-cli/src/cli/commands/ingest.ts
index 2c2a123a..af952df3 100644
--- a/ix-cli/src/cli/commands/ingest.ts
+++ b/ix-cli/src/cli/commands/ingest.ts
@@ -20,6 +20,7 @@ import { detectSystem, repoWorkspaceIdFor, lookupPackage, readPackageNames, read
import { CLIENT_EXPECTED_SCHEMA_VERSION } from '../backend-status.js';
import { SUPPORTED_EXTENSIONS } from '../supported-extensions.js';
import { canRenderProgress } from '../stderr.js';
+import { createTypeScriptModuleResolver } from '../ts-module-resolution.js';
import {
deterministicId,
transformIssue,
@@ -770,7 +771,7 @@ export async function ingestFiles(
const packageRegistry = detectedSystem?.packageRegistry ?? {};
const packageOf = (mod: string): string | undefined => lookupPackage(packageRegistry, mod);
const declaredRepoDeps = detectedSystem?.repoDeps;
- const resolveOpts = systemId ? { repoOf, packageOf, declaredRepoDeps } : undefined;
+ const crossRepoResolveOpts = systemId ? { repoOf, packageOf, declaredRepoDeps } : undefined;
// ── Path-2 separate-ingest stitcher (Ix#225 Half A) ──────────────────
// Co-ingest already forms cross-repo edges in-batch, so the stitcher only runs
@@ -1043,6 +1044,10 @@ export async function ingestFiles(
? (isSupportedSourceFile(resolvedPath) ? [resolvedPath] : [])
: (tryGitLsFiles(resolvedPath, opts.recursive ?? true) ?? Array.from(walkFiles(resolvedPath, opts.recursive ?? true))),
);
+ const resolveOpts = {
+ ...crossRepoResolveOpts,
+ resolveModuleSpecifier: createTypeScriptModuleResolver(workspaceRoot, filePaths),
+ };
filesDiscovered = filePaths.length;
const discovered = performance.now();
diff --git a/ix-cli/src/cli/ts-module-resolution.ts b/ix-cli/src/cli/ts-module-resolution.ts
new file mode 100644
index 00000000..019fee8b
--- /dev/null
+++ b/ix-cli/src/cli/ts-module-resolution.ts
@@ -0,0 +1,315 @@
+import * as fs from "node:fs";
+import * as nodePath from "node:path";
+
+interface PathRule {
+ pattern: string;
+ targets: string[];
+ baseDir: string;
+}
+
+interface LoadedConfig {
+ dir: string;
+ baseUrl?: string;
+ paths: PathRule[];
+}
+
+export type TypeScriptModuleResolver = (
+ sourcePath: string,
+ specifier: string,
+ kind?: "runtime" | "types",
+) => string[] | undefined;
+
+const SOURCE_SUFFIXES = [".ts", ".tsx", ".d.ts", ".js", ".jsx", ".mjs", ".cjs"];
+
+function normalizePath(value: string): string {
+ return nodePath.posix.normalize(value.replace(/\\/g, "/"));
+}
+
+function isWithinDir(filePath: string, dir: string): boolean {
+ return dir === "." || filePath === dir || filePath.startsWith(`${dir}/`);
+}
+
+function toggleFirstAsciiCase(value: string): string | undefined {
+ const index = value.search(/[A-Za-z]/);
+ if (index === -1) return undefined;
+ const char = value[index];
+ const toggled = char === char.toLowerCase() ? char.toUpperCase() : char.toLowerCase();
+ return value.slice(0, index) + toggled + value.slice(index + 1);
+}
+
+function isCaseSensitiveFilesystem(workspaceRoot: string, absoluteFilePaths: string[]): boolean {
+ for (const candidate of [...absoluteFilePaths, workspaceRoot]) {
+ const basename = nodePath.basename(candidate);
+ const toggled = toggleFirstAsciiCase(basename);
+ if (!toggled || toggled === basename) continue;
+ const alternate = nodePath.join(nodePath.dirname(candidate), toggled);
+ try {
+ return fs.realpathSync.native(candidate) !== fs.realpathSync.native(alternate);
+ } catch {
+ return true;
+ }
+ }
+ return true;
+}
+
+function parseJsonc(text: string): unknown {
+ let output = "";
+ let inString = false;
+ let escaped = false;
+ let lineComment = false;
+ let blockComment = false;
+
+ for (let i = 0; i < text.length; i += 1) {
+ const char = text[i];
+ const next = text[i + 1];
+ if (lineComment) {
+ if (char === "\n") {
+ lineComment = false;
+ output += char;
+ } else {
+ output += " ";
+ }
+ continue;
+ }
+ if (blockComment) {
+ if (char === "*" && next === "/") {
+ output += " ";
+ blockComment = false;
+ i += 1;
+ } else {
+ output += char === "\n" ? "\n" : " ";
+ }
+ continue;
+ }
+ if (inString) {
+ output += char;
+ if (escaped) escaped = false;
+ else if (char === "\\") escaped = true;
+ else if (char === '"') inString = false;
+ continue;
+ }
+ if (char === '"') {
+ inString = true;
+ output += char;
+ } else if (char === "/" && next === "/") {
+ lineComment = true;
+ output += " ";
+ i += 1;
+ } else if (char === "/" && next === "*") {
+ blockComment = true;
+ output += " ";
+ i += 1;
+ } else {
+ output += char;
+ }
+ }
+
+ let normalized = "";
+ inString = false;
+ escaped = false;
+ for (let i = 0; i < output.length; i += 1) {
+ const char = output[i];
+ if (inString) {
+ normalized += char;
+ if (escaped) escaped = false;
+ else if (char === "\\") escaped = true;
+ else if (char === '"') inString = false;
+ continue;
+ }
+ if (char === '"') {
+ inString = true;
+ normalized += char;
+ continue;
+ }
+ if (char === ",") {
+ let next = i + 1;
+ while (/\s/.test(output[next] ?? "")) next += 1;
+ if (output[next] === "}" || output[next] === "]") continue;
+ }
+ normalized += char;
+ }
+
+ return JSON.parse(normalized);
+}
+
+function readObject(filePath: string): Record<string, unknown> | undefined {
+ try {
+ const parsed = parseJsonc(fs.readFileSync(filePath, "utf8"));
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed)
+ ? (parsed as Record<string, unknown>)
+ : undefined;
+ } catch {
+ return undefined;
+ }
+}
+
+function resolveExtends(configPath: string, value: unknown): string | undefined {
+ if (typeof value !== "string" || !value.startsWith(".")) return undefined;
+ const unresolved = nodePath.resolve(nodePath.dirname(configPath), value);
+ const candidates = [unresolved, `${unresolved}.json`, nodePath.join(unresolved, "tsconfig.json")];
+ return candidates.find((candidate) => fs.existsSync(candidate));
+}
+
+function loadConfig(
+ workspaceRoot: string,
+ configPath: string,
+ cache: Map<string, LoadedConfig | undefined>,
+ loading = new Set<string>(),
+): LoadedConfig | undefined {
+ const absoluteConfig = nodePath.resolve(configPath);
+ if (cache.has(absoluteConfig)) return cache.get(absoluteConfig);
+ if (loading.has(absoluteConfig)) return undefined;
+ loading.add(absoluteConfig);
+
+ const raw = readObject(absoluteConfig);
+ if (!raw) {
+ cache.set(absoluteConfig, undefined);
+ loading.delete(absoluteConfig);
+ return undefined;
+ }
+
+ const parentPath = resolveExtends(absoluteConfig, raw.extends);
+ const parent = parentPath ? loadConfig(workspaceRoot, parentPath, cache, loading) : undefined;
+ const configDir = nodePath.dirname(absoluteConfig);
+ const compilerOptions =
+ raw.compilerOptions && typeof raw.compilerOptions === "object"
+ ? (raw.compilerOptions as Record<string, unknown>)
+ : {};
+ const ownBaseUrl =
+ typeof compilerOptions.baseUrl === "string"
+ ? nodePath.resolve(configDir, compilerOptions.baseUrl)
+ : undefined;
+ const baseUrl = ownBaseUrl ?? parent?.baseUrl;
+ let paths = parent?.paths ?? [];
+ if (compilerOptions.paths && typeof compilerOptions.paths === "object") {
+ const pathBase = baseUrl ?? configDir;
+ paths = Object.entries(compilerOptions.paths as Record<string, unknown>)
+ .filter(
+ (entry): entry is [string, string[]] =>
+ Array.isArray(entry[1]) && entry[1].every((target) => typeof target === "string"),
+ )
+ .map(([pattern, targets]) => ({ pattern, targets, baseDir: pathBase }))
+ .sort((a, b) => {
+ const aStar = a.pattern.indexOf("*");
+ const bStar = b.pattern.indexOf("*");
+ if (aStar === -1 || bStar === -1) return aStar === -1 ? -1 : 1;
+ return bStar - aStar;
+ });
+ }
+
+ const relativeDir = normalizePath(nodePath.relative(workspaceRoot, configDir) || ".");
+ const loaded = { dir: relativeDir, baseUrl, paths };
+ cache.set(absoluteConfig, loaded);
+ loading.delete(absoluteConfig);
+ return loaded;
+}
+
+function matchPathPattern(pattern: string, specifier: string): string | undefined {
+ const star = pattern.indexOf("*");
+ if (star === -1) return pattern === specifier ? "" : undefined;
+ if (pattern.indexOf("*", star + 1) !== -1) return undefined;
+ const prefix = pattern.slice(0, star);
+ const suffix = pattern.slice(star + 1);
+ return specifier.startsWith(prefix) && specifier.endsWith(suffix)
+ ? specifier.slice(prefix.length, specifier.length - suffix.length)
+ : undefined;
+}
+
+export function createTypeScriptModuleResolver(
+ workspaceRoot: string,
+ absoluteFilePaths: string[],
+ options: { caseSensitive?: boolean } = {},
+): TypeScriptModuleResolver {
+ const root = nodePath.resolve(workspaceRoot);
+ const caseSensitive =
+ options.caseSensitive ?? isCaseSensitiveFilesystem(root, absoluteFilePaths);
+ const pathKey = (value: string): string => {
+ const normalized = normalizePath(value);
+ return caseSensitive ? normalized : normalized.toLowerCase();
+ };
+ const indexed = new Map(
+ absoluteFilePaths.map((filePath) => {
+ const relativePath = normalizePath(nodePath.relative(root, nodePath.resolve(filePath)));
+ return [pathKey(relativePath), relativePath];
+ }),
+ );
+
+ const resolveCandidate = (
+ absoluteTarget: string,
+ sourcePath: string,
+ kind: "runtime" | "types",
+ ): string[] => {
+ const relativeTarget = normalizePath(nodePath.relative(root, absoluteTarget));
+ const extension = nodePath.posix.extname(relativeTarget).toLowerCase();
+ const base = extension ? relativeTarget.slice(0, -extension.length) : relativeTarget;
+ const sourceExtension = nodePath.posix.extname(normalizePath(sourcePath)).toLowerCase();
+ const preferJavaScript = [".js", ".jsx", ".mjs", ".cjs"].includes(sourceExtension);
+ const extensionlessSuffixes =
+ kind === "types"
+ ? SOURCE_SUFFIXES
+ : preferJavaScript
+ ? [".js", ".jsx", ".mjs", ".cjs", ".ts", ".tsx", ".d.ts"]
+ : [".ts", ".tsx", ".js", ".jsx", ".d.ts", ".mjs", ".cjs"];
+ const candidates =
+ extension === ".js"
+ ? kind === "types"
+ ? [base + ".ts", base + ".tsx", base + ".d.ts", relativeTarget, base + ".jsx"]
+ : preferJavaScript
+ ? [relativeTarget, base + ".jsx", base + ".ts", base + ".tsx", base + ".d.ts"]
+ : [base + ".ts", base + ".tsx", relativeTarget, base + ".jsx", base + ".d.ts"]
+ : extension === ".jsx"
+ ? kind === "types"
+ ? [base + ".tsx", base + ".d.ts", relativeTarget]
+ : preferJavaScript
+ ? [relativeTarget, base + ".tsx", base + ".d.ts"]
+ : [base + ".tsx", relativeTarget, base + ".d.ts"]
+ : extension
+ ? [relativeTarget]
+ : [
+ ...extensionlessSuffixes.map((suffix) => relativeTarget + suffix),
+ ...extensionlessSuffixes.map((suffix) =>
+ nodePath.posix.join(relativeTarget, "index" + suffix),
+ ),
+ ];
+ const match = candidates.map((candidate) => indexed.get(pathKey(candidate))).find(Boolean);
+ return match ? [match] : [];
+ };
+
+ const configCache = new Map<string, LoadedConfig | undefined>();
+ const configs = absoluteFilePaths
+ .filter((filePath) => /(?:^|[/\\])(?:tsconfig|jsconfig)\.json$/i.test(filePath))
+ .map((filePath) => loadConfig(root, filePath, configCache))
+ .filter((config): config is LoadedConfig => config !== undefined)
+ .sort((a, b) => b.dir.length - a.dir.length);
+
+ return (sourcePath: string, rawSpecifier: string, kind = "runtime"): string[] | undefined => {
+ const specifier = rawSpecifier.split(/[?#]/, 1)[0];
+ if (!specifier || specifier.startsWith(".") || specifier.startsWith("/")) return undefined;
+ const normalizedSource = normalizePath(sourcePath);
+ const config = configs.find((candidate) => isWithinDir(normalizedSource, candidate.dir));
+ if (config) {
+ for (const rule of config.paths) {
+ const star = matchPathPattern(rule.pattern, specifier);
+ if (star === undefined) continue;
+ for (const target of rule.targets) {
+ const matches = resolveCandidate(
+ nodePath.resolve(rule.baseDir, target.replace("*", star)),
+ sourcePath,
+ kind,
+ );
+ if (matches.length > 0) return matches;
+ }
+ return [];
+ }
+ if (config.baseUrl) {
+ const matches = resolveCandidate(
+ nodePath.resolve(config.baseUrl, specifier),
+ sourcePath,
+ kind,
+ );
+ if (matches.length > 0) return matches;
+ }
+ }
+ return config?.baseUrl ? [] : undefined;
+ };
+}