diff --git a/src/graph/build.ts b/src/graph/build.ts index ac007870c..308939aa1 100644 --- a/src/graph/build.ts +++ b/src/graph/build.ts @@ -36,6 +36,7 @@ import { writeFingerprint } from "./fingerprint.js"; import { seedGraph, type SeedResult } from "./seed.js"; import { filterByOnlyDirs, listSourceStats, normalizeExtensions } from "./source-files.js"; import { resolveEdges, type GoModule } from "./resolve.js"; +import { readTsAliases } from "./ts-paths.js"; import { enrichGraph, type EnrichStats } from "./enrich.js"; import { readGraph, writeGraph, wiringPath } from "./write.js"; import { writeCards, writeIndex, writeCovers, type CardStats } from "./cards.js"; @@ -220,7 +221,7 @@ export async function buildGraph( ): Promise { const root = resolve(dir); const outDir = contextDirFor(root, opts.contextDir); - // Enumerate once: source extraction, scope discovery, and Go module + // Enumerate once: source extraction, scope discovery, Go module, and TS alias // resolution must agree on the same Git-ignore-aware working-tree view — // including the repo's persisted directory and submodule choices. const walked = walkDir(root, readIncludeDirs(root), { @@ -365,7 +366,10 @@ export async function buildGraph( files: entries, }); - const edges = resolveEdges(nodes, rawEdges, { goModules: readGoModules(root, repoFiles) }); + const edges = resolveEdges(nodes, rawEdges, { + goModules: readGoModules(root, repoFiles), + tsAliases: readTsAliases(root, repoFiles), + }); // Guard 5 (minimum-substance): node counts aren't known until nodes are // assembled, so the merge-tiny-scopes-into-root guard runs here. diff --git a/src/graph/resolve.ts b/src/graph/resolve.ts index 50192a227..43da1a38f 100644 --- a/src/graph/resolve.ts +++ b/src/graph/resolve.ts @@ -17,6 +17,7 @@ import { toPosixPath } from "../util/paths.js"; import type { EdgeV1, Kind, NodeV1, Relation } from "./types.js"; import { languageOf, type RawEdge } from "./extract.js"; import { genericLangOf } from "./generic.js"; +import { resolveTsAlias, type TsPathConfig } from "./ts-paths.js"; const IMPORT_EXTS = [".ts", ".tsx", ".mts", ".cts", ".js", ".jsx", ".mjs", ".cjs", ".py"]; /** C/C++ source + header extensions, for resolving `#include` targets. */ @@ -126,6 +127,9 @@ export interface ResolveOptions { * (`example.com/app/pkg/util`) to the in-repo directory they name, relative to the * owning module's `go.mod` location. Empty/absent → Go imports stay external strings. */ goModules?: GoModule[]; + /** Compiled TS/JS path aliases. They are scoped to config directories and + * resolve only when a candidate is present in this graph. */ + tsAliases?: TsPathConfig[]; } export function resolveEdges( @@ -265,7 +269,7 @@ export function resolveEdges( ? resolvePhpUse(e.specifier, phpFilesBySuffix) : e.file.endsWith(".gleam") ? resolveGleamImport(e.specifier, gleamFilesBySuffix) - : resolveImport(e.specifier, e.file, byId); + : resolveImport(e.specifier, e.file, byId, opts.tsAliases); add(e.source, target, "imports", "extracted"); } else if (e.relation === "extends" || e.relation === "implements") { // `implements` also resolves to a `trait` — PHP models trait composition @@ -283,7 +287,7 @@ export function resolveEdges( ? resolvePhpUse(e.specifier, phpFilesBySuffix) : e.file.endsWith(".gleam") ? resolveGleamImport(e.specifier, gleamFilesBySuffix) - : resolveImport(e.specifier, e.file, byId); + : resolveImport(e.specifier, e.file, byId, opts.tsAliases); if (!byId.has(targetFile)) continue; // external or unresolved module const candidates = narrowGleamByKind(perFileName.get(targetFile)?.get(e.name) ?? [], e.file, TYPE_KINDS); if (candidates.length === 1) add(e.source, candidates[0].id, "references", "extracted"); @@ -408,7 +412,7 @@ export function resolveEdges( // module that defines the name resolves to that definition alone; one // that does not (a barrel re-export) keeps the name-based fallback. if (e.specifier) { - const targetFile = resolveImport(e.specifier, e.file, byId); + const targetFile = resolveImport(e.specifier, e.file, byId, opts.tsAliases); if (!byId.has(targetFile)) continue; const inModule = (perFileName.get(targetFile)?.get(e.name!) ?? []).filter((n) => callKinds.includes(n.kind), @@ -628,12 +632,25 @@ function resolveTraitMember( * Resolve a module specifier to a file node id when it points inside the repo; * otherwise return the raw specifier (external package or unresolved path). */ -function resolveImport(spec: string, file: string, byId: Map): string { - if (!spec.startsWith(".")) return spec; +function resolveImport( + spec: string, + file: string, + byId: Map, + tsAliases?: TsPathConfig[], +): string { + if (!spec.startsWith(".")) { + if (!/\.(ts|tsx|mts|cts|js|jsx|mjs|cjs|vue|svelte|astro)$/i.test(file)) return spec; + return resolveTsAlias(spec, file, tsAliases, (candidate) => findImportCandidate(candidate, byId)) ?? spec; + } // Belt-and-braces: `node.path` is posix by construction (`../util/paths.ts`), // but this also accepts a hand-written or hand-edited graph. const dir = posix.dirname(toPosixPath(file)); const base = posix.normalize(posix.join(dir, spec)); + return findImportCandidate(base, byId) ?? spec; +} + +/** The shared candidate order keeps aliases and relative imports equally certain. */ +function findImportCandidate(base: string, byId: Map): string | null { const noExt = base.replace(/\.(js|jsx|mjs|cjs|ts|tsx|py)$/, ""); const candidates = [ base, @@ -641,7 +658,7 @@ function resolveImport(spec: string, file: string, byId: Map): s ...IMPORT_EXTS.map((e) => `${noExt}/index${e}`), ]; for (const c of candidates) if (byId.has(c)) return c; - return spec; + return null; } /** diff --git a/src/graph/ts-paths.ts b/src/graph/ts-paths.ts new file mode 100644 index 000000000..71735534f --- /dev/null +++ b/src/graph/ts-paths.ts @@ -0,0 +1,308 @@ +import { existsSync, readFileSync } from "node:fs"; +import { posix, resolve } from "node:path"; +import { toPosixPath } from "../util/paths.js"; + +/** Compiled TypeScript path mappings. All stored paths are repo-relative and posix. */ +export interface TsPathTarget { + baseDir: string; + prefix: string; + suffix: string; + wildcard: boolean; +} + +export interface TsPathPattern { + prefix: string; + suffix: string; + wildcard: boolean; + targets: TsPathTarget[]; +} + +export interface TsPathConfig { + /** Repo-relative directory that scopes this config to its importers. */ + dir: string; + name: string; + baseUrl?: string; + patterns: TsPathPattern[]; +} + +const MAX_EXTENDS_DEPTH = 32; + +interface ParsedConfig { + extends?: string | string[]; + compilerOptions?: Record; +} + +interface EffectiveConfig { + baseUrl?: string; + paths?: TsPathPattern[]; +} + +/** `tsconfig.json`, `jsconfig.json` or `tsconfig..json`, by file name only. + * String checks rather than one regex over the whole path: a path made of many + * `/tsconfig.` segments made the regex backtrack polynomially (CodeQL). */ +function isTsConfigFile(file: string): boolean { + const name = file.slice(file.lastIndexOf("/") + 1); + if (name === "tsconfig.json" || name === "jsconfig.json") return true; + // `tsconfig.` + at least one character + `.json` + return name.startsWith("tsconfig.") && name.endsWith(".json") && name.length > "tsconfig.".length + ".json".length; +} + +/** Read and compile every visible TS config once for a build. `repoFiles` is the + * same Git-ignore-aware walk used by graph extraction, so aliases never describe + * a different repository view from the files that can become graph nodes. Config + * `include` and `exclude` are deliberately ignored; graph membership comes from + * graft's file walk, not the TypeScript program's compilation boundary. */ +export function readTsAliases(root: string, repoFiles: string[]): TsPathConfig[] { + const rootAbs = toPosixPath(resolve(root)); + const parsed = new Map(); + const configs: TsPathConfig[] = []; + const configFiles = repoFiles + .map(toPosixPath) + .filter(isTsConfigFile) + .sort(comparePath); + + for (const file of configFiles) { + const abs = posix.normalize(file); + const effective = readEffectiveConfig(abs, rootAbs, parsed, new Set(), 0); + if (!effective.baseUrl && !effective.paths?.length) continue; + const relDir = posix.relative(rootAbs, posix.dirname(abs)); + configs.push({ + dir: relDir === "." ? "" : relDir, + name: posix.basename(abs), + ...(effective.baseUrl ? { baseUrl: posix.relative(rootAbs, effective.baseUrl) || "." } : {}), + patterns: effective.paths ?? [], + }); + } + + configs.sort((a, b) => { + const depth = pathDepth(b.dir) - pathDepth(a.dir); + if (depth !== 0) return depth; + if (a.dir !== b.dir) return comparePath(a.dir, b.dir); + if (a.name === "tsconfig.json") return b.name === "tsconfig.json" ? 0 : -1; + if (b.name === "tsconfig.json") return 1; + return comparePath(a.name, b.name); + }); + return configs; +} + +/** Resolve one bare specifier through the nearest in-scope config that lands on + * an indexed file. `findFile` uses resolveEdges' in-memory node map, never disk. */ +export function resolveTsAlias( + specifier: string, + importer: string, + configs: TsPathConfig[] | undefined, + findFile: (candidate: string) => string | null, +): string | null { + if (!configs?.length) return null; + const file = posix.normalize(toPosixPath(importer)); + for (const config of configs) { + if (config.dir && file !== config.dir && !file.startsWith(`${config.dir}/`)) continue; + + const pattern = config.patterns.find((candidate) => matchPattern(candidate, specifier) !== null); + if (pattern) { + const capture = matchPattern(pattern, specifier)!; + for (const target of pattern.targets) { + const expanded = target.prefix + (target.wildcard ? capture : "") + target.suffix; + const hit = findFile(posix.normalize(posix.join(target.baseDir, expanded))); + if (hit) return hit; + } + // A matching paths key owns this lookup, even when none of its targets exists. + continue; + } + + if (config.baseUrl) { + const hit = findFile(posix.normalize(posix.join(config.baseUrl, specifier))); + if (hit) return hit; + } + } + return null; +} + +function readEffectiveConfig( + file: string, + root: string, + parsed: Map, + active: Set, + depth: number, +): EffectiveConfig { + const abs = posix.normalize(file); + const local = readParsedConfig(abs, parsed); + if (!local || active.has(abs)) return {}; + + active.add(abs); + try { + const effective: EffectiveConfig = {}; + if (depth < MAX_EXTENDS_DEPTH) { + const parents = typeof local.extends === "string" + ? [local.extends] + : Array.isArray(local.extends) + ? local.extends.filter((value): value is string => typeof value === "string") + : []; + for (const parentRef of parents) { + const parent = resolveRelativeExtends(abs, parentRef); + if (!parent || active.has(parent)) continue; + const inherited = readEffectiveConfig(parent, root, parsed, active, depth + 1); + if (inherited.baseUrl !== undefined) effective.baseUrl = inherited.baseUrl; + if (inherited.paths !== undefined) effective.paths = inherited.paths; + } + } + + const options = local.compilerOptions; + if (!options) return effective; + if (typeof options.baseUrl === "string") { + effective.baseUrl = resolveConfigPath(posix.dirname(abs), options.baseUrl); + } + if (Object.prototype.hasOwnProperty.call(options, "paths")) { + const base = effective.baseUrl ?? posix.dirname(abs); + effective.paths = compilePaths(options.paths, base, root); + } + return effective; + } finally { + active.delete(abs); + } +} + +function readParsedConfig(file: string, cache: Map): ParsedConfig | null { + if (cache.has(file)) return cache.get(file) ?? null; + let value: ParsedConfig | null = null; + try { + const parsed: unknown = JSON.parse(stripJsonCommentsAndTrailingCommas(readFileSync(file, "utf8"))); + if (isRecord(parsed)) { + value = { + ...(typeof parsed.extends === "string" || Array.isArray(parsed.extends) ? { extends: parsed.extends as string | string[] } : {}), + ...(isRecord(parsed.compilerOptions) ? { compilerOptions: parsed.compilerOptions } : {}), + }; + } + } catch { + /* unreadable or invalid JSONC — ignore this config */ + } + cache.set(file, value); + return value; +} + +function resolveRelativeExtends(config: string, value: string): string | null { + if (!value.startsWith(".")) return null; // package configs live outside the repo's path mapping + const base = resolveConfigPath(posix.dirname(config), value); + const candidates = value.endsWith(".json") + ? [base] + : [`${base}.json`, posix.join(base, "tsconfig.json")]; + for (const candidate of candidates) { + if (existsSync(candidate)) return candidate; + } + return null; +} + +function resolveConfigPath(base: string, path: string): string { + const normalized = toPosixPath(path); + if (posix.isAbsolute(normalized) || /^[A-Za-z]:\//.test(normalized)) return posix.normalize(normalized); + return posix.normalize(posix.join(base, normalized)); +} + +function compilePaths(value: unknown, base: string, root: string): TsPathPattern[] { + if (!isRecord(value)) return []; + const patterns: TsPathPattern[] = []; + for (const [key, rawTargets] of Object.entries(value)) { + const keyStar = key.indexOf("*"); + if (keyStar !== key.lastIndexOf("*")) continue; + const wildcard = keyStar >= 0; + const prefix = wildcard ? key.slice(0, keyStar) : key; + const suffix = wildcard ? key.slice(keyStar + 1) : ""; + if (!Array.isArray(rawTargets)) continue; + const targets: TsPathTarget[] = []; + for (const raw of rawTargets) { + if (typeof raw !== "string") continue; + const star = raw.indexOf("*"); + if (star !== raw.lastIndexOf("*") || (star >= 0 && !wildcard)) continue; + const targetBase = posix.relative(root, base) || "."; + targets.push({ + baseDir: targetBase, + prefix: star >= 0 ? raw.slice(0, star) : raw, + suffix: star >= 0 ? raw.slice(star + 1) : "", + wildcard: star >= 0, + }); + } + patterns.push({ prefix, suffix, wildcard, targets }); + } + patterns.sort((a, b) => b.prefix.length - a.prefix.length); + return patterns; +} + +function matchPattern(pattern: TsPathPattern, specifier: string): string | null { + if (!pattern.wildcard) return specifier === pattern.prefix ? "" : null; + if (!specifier.startsWith(pattern.prefix) || !specifier.endsWith(pattern.suffix)) return null; + const end = specifier.length - pattern.suffix.length; + if (end < pattern.prefix.length) return null; + return specifier.slice(pattern.prefix.length, end); +} + +/** JSONC comments and trailing commas are removed only outside quoted strings. */ +function stripJsonCommentsAndTrailingCommas(source: string): string { + const uncommented: string[] = []; + let inString = false; + for (let i = 0; i < source.length; i++) { + const char = source[i]; + if (inString) { + uncommented.push(char); + if (char === "\\" && i + 1 < source.length) uncommented.push(source[++i]); + else if (char === '"') inString = false; + } else if (char === '"') { + inString = true; + uncommented.push(char); + } else if (char === "/" && source[i + 1] === "/") { + uncommented.push(" "); + i += 2; + while (i < source.length && source[i] !== "\n" && source[i] !== "\r") { + uncommented.push(" "); + i++; + } + if (i < source.length) uncommented.push(source[i]); + } else if (char === "/" && source[i + 1] === "*") { + uncommented.push(" "); + i += 2; + while (i < source.length && !(source[i] === "*" && source[i + 1] === "/")) { + uncommented.push(source[i] === "\n" || source[i] === "\r" ? source[i] : " "); + i++; + } + if (i < source.length) { + uncommented.push(" "); + i++; + } + } else { + uncommented.push(char); + } + } + + const input = uncommented.join(""); + const output: string[] = []; + inString = false; + for (let i = 0; i < input.length; i++) { + const char = input[i]; + if (inString) { + output.push(char); + if (char === "\\" && i + 1 < input.length) output.push(input[++i]); + else if (char === '"') inString = false; + } else if (char === '"') { + inString = true; + output.push(char); + } else if (char === ",") { + let next = i + 1; + while (next < input.length && /\s/.test(input[next])) next++; + if (input[next] !== "}" && input[next] !== "]") output.push(char); + } else { + output.push(char); + } + } + return output.join(""); +} + +function isRecord(value: unknown): value is Record { + return value !== null && typeof value === "object" && !Array.isArray(value); +} + +function pathDepth(path: string): number { + return path ? path.split("/").length : 0; +} + +function comparePath(a: string, b: string): number { + return a < b ? -1 : a > b ? 1 : 0; +} diff --git a/test/graph-resolve-ts-paths.test.ts b/test/graph-resolve-ts-paths.test.ts new file mode 100644 index 000000000..1fabd4d2b --- /dev/null +++ b/test/graph-resolve-ts-paths.test.ts @@ -0,0 +1,252 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; +import { buildGraph } from "../src/graph/build.js"; +import { readGraph } from "../src/graph/write.js"; +import type { GraphV1 } from "../src/graph/types.js"; + +async function withGraph( + files: Record, + check: (graph: GraphV1) => void, +): Promise { + const root = mkdtempSync(join(tmpdir(), "graft-ts-paths-")); + try { + for (const [path, contents] of Object.entries(files)) { + const abs = join(root, ...path.split("/")); + mkdirSync(dirname(abs), { recursive: true }); + writeFileSync(abs, contents); + } + const result = await buildGraph(root, { graphOnly: true, reuse: false }); + const graph = readGraph(result.graphPath); + assert.ok(graph, "buildGraph writes a readable graph"); + check(graph); + } finally { + rmSync(root, { recursive: true, force: true }); + } +} + +function callTarget(graph: GraphV1, source: string): string | undefined { + return graph.edges.find((edge) => edge.relation === "calls" && edge.source === source)?.target; +} + +test("buildGraph resolves a wildcard named import through a directory index and records its caller", async () => { + await withGraph({ + "tsconfig.json": JSON.stringify({ compilerOptions: { paths: { "@core/*": ["./core/*"] } } }), + "core/dates/index.ts": "export function addDays(day: number): number { return day + 1; }\n", + "src/caller.ts": [ + 'import { addDays } from "@core/dates";', + "export function schedule(day: number): number { return addDays(day); }", + ].join("\n"), + }, (graph) => { + assert.ok(graph.edges.some((edge) => edge.relation === "imports" && edge.source === "src/caller.ts" && edge.target === "core/dates/index.ts")); + assert.equal(callTarget(graph, "src/caller.ts#schedule"), "core/dates/index.ts#addDays"); + assert.ok(graph.edges.some((edge) => edge.relation === "calls" && edge.target === "core/dates/index.ts#addDays"), + "the incoming calls edge is available to graft callers-style queries"); + }); +}); + +test("exact and prefix-suffix path patterns resolve to their declared files", async () => { + await withGraph({ + "tsconfig.json": JSON.stringify({ compilerOptions: { paths: { + "@exact": ["./src/exact"], + "@pkg/*-generated": ["./src/*-generated"], + } } }), + "src/exact.ts": "export function exactTarget(): number { return 1; }\n", + "src/middle-generated.ts": "export function suffixTarget(): number { return 2; }\n", + "src/caller.ts": [ + 'import { exactTarget } from "@exact";', + 'import { suffixTarget } from "@pkg/middle-generated";', + "export function runExact(): number { return exactTarget(); }", + "export function runSuffix(): number { return suffixTarget(); }", + ].join("\n"), + }, (graph) => { + assert.equal(callTarget(graph, "src/caller.ts#runExact"), "src/exact.ts#exactTarget"); + assert.equal(callTarget(graph, "src/caller.ts#runSuffix"), "src/middle-generated.ts#suffixTarget"); + }); +}); + +test("the longest matching prefix wins for overlapping patterns", async () => { + await withGraph({ + "tsconfig.json": JSON.stringify({ compilerOptions: { paths: { + "@*": ["./short/*"], + "@core/*": ["./long/*"], + } } }), + "short/dates.ts": "export function read(): number { return 1; }\n", + "long/dates.ts": "export function read(): number { return 2; }\n", + "src/caller.ts": 'import { read } from "@core/dates"; export function run(): number { return read(); }\n', + }, (graph) => { + assert.equal(callTarget(graph, "src/caller.ts#run"), "long/dates.ts#read"); + }); +}); + +test("baseUrl resolves an existing bare path and leaves an unknown package external", async () => { + await withGraph({ + "tsconfig.json": JSON.stringify({ compilerOptions: { baseUrl: "src" } }), + "src/core/dates.ts": "export function schedule(): number { return 1; }\n", + "src/vendor/react.ts": "export function useState(): number { return 0; }\n", + "src/caller.ts": [ + 'import { schedule } from "core/dates";', + 'import { useState } from "react";', + "export function local(): number { return schedule(); }", + "export function external(): number { return useState(); }", + ].join("\n"), + }, (graph) => { + assert.equal(callTarget(graph, "src/caller.ts#local"), "src/core/dates.ts#schedule"); + assert.ok(graph.edges.some((edge) => edge.relation === "imports" && edge.source === "src/caller.ts" && edge.target === "react")); + assert.equal(callTarget(graph, "src/caller.ts#external"), undefined); + }); +}); + +test("paths without baseUrl resolve from the config directory", async () => { + await withGraph({ + "backend/tsconfig.json": JSON.stringify({ compilerOptions: { paths: { "@lib/*": ["./lib/*"] } } }), + "backend/lib/math.ts": "export function add(): number { return 1; }\n", + "backend/src/caller.ts": 'import { add } from "@lib/math"; export function run(): number { return add(); }\n', + }, (graph) => { + assert.equal(callTarget(graph, "backend/src/caller.ts#run"), "backend/lib/math.ts#add"); + }); +}); + +test("extends chains, arrays, JSONC, inherited baseUrl, and child paths replacement resolve together", async () => { + await withGraph({ + "configs/base.json": `{ + // Base paths and baseUrl both belong to this config. + "compilerOptions": { "baseUrl": "../src", "paths": { "@old/*": ["old/*",], }, }, + }`, + "configs/overlay.json": JSON.stringify({ compilerOptions: { paths: { "@overlay/*": ["overlay/*"] } } }), + "configs/mid.json": JSON.stringify({ extends: ["./base", "./overlay.json"] }), + "tsconfig.json": `{ + // A path declared here uses the inherited baseUrl from configs/base.json. + "extends": "./configs/mid", + "compilerOptions": { "paths": { "@new/*": ["new/*",], }, }, + }`, + "src/new/dates.ts": "export function hit(): number { return 3; }\n", + "src/old/dates.ts": "export function hit(): number { return 1; }\n", + "src/overlay/dates.ts": "export function hit(): number { return 2; }\n", + "src/caller.ts": [ + 'import { hit as newHit } from "@new/dates";', + 'import { hit as oldHit } from "@old/dates";', + 'import { hit as overlayHit } from "@overlay/dates";', + "export function run(): number { return newHit() + oldHit() + overlayHit(); }", + ].join("\n"), + }, (graph) => { + assert.equal(callTarget(graph, "src/caller.ts#run"), "src/new/dates.ts#hit"); + assert.ok(graph.edges.some((edge) => edge.relation === "imports" && edge.source === "src/caller.ts" && edge.target === "@old/dates")); + assert.ok(graph.edges.some((edge) => edge.relation === "imports" && edge.source === "src/caller.ts" && edge.target === "@overlay/dates")); + }); +}); + +test("nested backend and frontend configs scope the same alias to different targets", async () => { + await withGraph({ + "backend/tsconfig.json": JSON.stringify({ compilerOptions: { paths: { "@/*": ["./src/*"] } } }), + "frontend/tsconfig.app.json": JSON.stringify({ compilerOptions: { paths: { "@/*": ["./lib/*"] } } }), + "backend/src/value.ts": "export function value(): number { return 1; }\n", + "frontend/lib/value.ts": "export function value(): number { return 2; }\n", + "backend/handler.ts": 'import { value } from "@/value"; export function run(): number { return value(); }\n', + "frontend/page.ts": 'import { value } from "@/value"; export function render(): number { return value(); }\n', + }, (graph) => { + assert.equal(callTarget(graph, "backend/handler.ts#run"), "backend/src/value.ts#value"); + assert.equal(callTarget(graph, "frontend/page.ts#render"), "frontend/lib/value.ts#value"); + }); +}); + +test("configs in one directory use tsconfig.json first and fall through when its target is absent", async () => { + await withGraph({ + "tsconfig.json": JSON.stringify({ compilerOptions: { paths: { + "@shared/*": ["./standard/*"], + "@fallback/*": ["./missing/*"], + } } }), + "tsconfig.app.json": JSON.stringify({ compilerOptions: { paths: { + "@shared/*": ["./app/*"], + "@fallback/*": ["./app/*"], + } } }), + "standard/value.ts": "export function shared(): number { return 1; }\n", + "app/value.ts": "export function fallback(): number { return 2; }\n", + "src/caller.ts": [ + 'import { shared } from "@shared/value";', + 'import { fallback } from "@fallback/value";', + "export function run(): number { return shared() + fallback(); }", + ].join("\n"), + }, (graph) => { + const targets = graph.edges + .filter((edge) => edge.relation === "calls" && edge.source === "src/caller.ts#run") + .map((edge) => edge.target) + .sort(); + assert.deepEqual(targets, ["app/value.ts#fallback", "standard/value.ts#shared"]); + }); +}); + +test("the first existing target in a paths list wins in declared order", async () => { + await withGraph({ + "tsconfig.json": JSON.stringify({ compilerOptions: { paths: { + "@tool/*": ["./missing/*", "./src/first/*", "./src/second/*"], + } } }), + "src/first/task.ts": "export function run(): number { return 1; }\n", + "src/second/task.ts": "export function run(): number { return 2; }\n", + "src/caller.ts": 'import { run as task } from "@tool/task"; export function call(): number { return task(); }\n', + }, (graph) => { + assert.equal(callTarget(graph, "src/caller.ts#call"), "src/first/task.ts#run"); + }); +}); + +test("Python imports ignore TS aliases and relative ESM .js imports keep resolving to .ts", async () => { + await withGraph({ + "tsconfig.json": JSON.stringify({ compilerOptions: { paths: { "core": ["./src/core.ts"] } } }), + "src/core.ts": "export function core(): number { return 1; }\n", + "src/relative.ts": "export function relative(): number { return 2; }\n", + "src/caller.ts": [ + 'import { relative } from "./relative.js";', + "export function run(): number { return relative(); }", + ].join("\n"), + "py/caller.py": "import core\n\ndef run():\n return core.value()\n", + }, (graph) => { + assert.equal(callTarget(graph, "src/caller.ts#run"), "src/relative.ts#relative"); + assert.ok(graph.edges.some((edge) => edge.relation === "imports" && edge.source === "py/caller.py" && edge.target === "core")); + assert.ok(!graph.edges.some((edge) => edge.relation === "imports" && edge.source === "py/caller.py" && edge.target === "src/core.ts")); + }); +}); + +test("an alias whose targets are absent stays external and invents no call edge", async () => { + await withGraph({ + "tsconfig.json": JSON.stringify({ compilerOptions: { paths: { "@missing/*": ["./src/absent/*"] } } }), + "src/caller.ts": 'import { run as missing } from "@missing/task"; export function call(): number { return missing(); }\n', + }, (graph) => { + assert.ok(graph.edges.some((edge) => edge.relation === "imports" && edge.source === "src/caller.ts" && edge.target === "@missing/task")); + assert.equal(callTarget(graph, "src/caller.ts#call"), undefined); + }); +}); + +test("only tsconfig.json, jsconfig.json and tsconfig..json are read as configs", async () => { + const paths = JSON.stringify({ compilerOptions: { paths: { "@lib/*": ["./lib/*"] } } }); + const importer = 'import { foo } from "@lib/foo"; export function run(): number { return foo(); }\n'; + + // Look-alike names (a bare `tsconfig..json`, a prefix, a file inside a folder named `tsconfig.d`) are not configs. + await withGraph({ + "lib/foo.ts": "export function foo(): number { return 1; }\n", + "mytsconfig.json": paths, + "tsconfig..json": paths, + "src/caller.ts": importer, + // `other.json` sits in a folder called `tsconfig.d`; it must not count as a config for the files beside it. + "tsconfig.d/other.json": paths, + "tsconfig.d/lib/foo.ts": "export function foo(): number { return 1; }\n", + "tsconfig.d/caller.ts": importer, + }, (graph) => { + for (const caller of ["src/caller.ts", "tsconfig.d/caller.ts"]) { + assert.ok(graph.edges.some((edge) => edge.relation === "imports" && edge.source === caller && edge.target === "@lib/foo"), caller); + assert.equal(callTarget(graph, `${caller}#run`), undefined, caller); + } + }); + + // Real names are read, including a dotted `tsconfig...json`. + for (const name of ["jsconfig.json", "tsconfig.build.prod.json"]) { + await withGraph({ + "lib/foo.ts": "export function foo(): number { return 1; }\n", + [name]: paths, + "src/caller.ts": importer, + }, (graph) => { + assert.equal(callTarget(graph, "src/caller.ts#run"), "lib/foo.ts#foo", name); + }); + } +});