import type { CodeEdge, CodeEdgeKind, CodeFile, CodeGraph, CodeSymbol } from "../contract/views.ts"; import { outline, type FileOutline, type Reference } from "./outline.ts"; export interface SourceFile { readonly path: string; readonly text: string; } /** A workspace package: its name, its folder, and the files its `exports` map names. */ export interface WorkspacePackage { readonly name: string; readonly dir: string; readonly exports: ReadonlyMap; } const EXTENSIONS = [".ts", ".tsx", ".mts", ".cts", ".js", ".jsx", ".mjs", ".cjs"]; const MAX_EXPORT_HOPS = 8; interface ParsedFile { readonly path: string; readonly lines: number; readonly outline: FileOutline; readonly ids: readonly (string | null)[]; } /** Builds the code map of a set of source files: each file's declarations, then the uses between them across imports. */ export function buildGraph(commit: string, sources: readonly SourceFile[], packages: readonly WorkspacePackage[], skipped: number): CodeGraph { const files = new Map(); const symbols = new Map(); for (const source of sources) files.set(source.path, parse(source, symbols)); const resolver = new Resolver(files, packages); const edges = new Map(); for (const file of files.values()) { file.outline.references.forEach((references, index) => { const from = file.ids[index]; if (!from) return; for (const reference of references) { const to = resolver.target(file, index, reference); if (!to || to === from || symbols.get(to)?.parent === from) continue; const kind = edgeKind(reference, symbols.get(to)!); const key = `${from}\u0000${to}\u0000${kind}`; const edge = edges.get(key); if (edge) edge.count++; else edges.set(key, { from, to, kind, count: 1 }); } }); } const fileList: CodeFile[] = [...files.values()].map((file) => ({ path: file.path, lines: file.lines })).sort((a, b) => a.path.localeCompare(b.path)); return { commit, files: fileList, symbols: [...symbols.values()], edges: [...edges.values()] satisfies CodeEdge[], skipped }; } function parse(source: SourceFile, symbols: Map): ParsedFile { const found = outline(source.text); const ids = found.symbols.map((symbol) => { const parent = symbol.parent === null ? null : found.symbols[symbol.parent]; const id = parent ? `${source.path}#${parent.name}.${symbol.name}` : `${source.path}#${symbol.name}`; const known = symbols.get(id); if (known) { symbols.set(id, { ...known, end: Math.max(known.end, symbol.end) }); return id; } symbols.set(id, { id, file: source.path, name: symbol.name, kind: symbol.kind, parent: parent ? `${source.path}#${parent.name}` : null, start: symbol.start, end: symbol.end, exported: symbol.exported, doc: symbol.doc }); return id; }); return { path: source.path, lines: source.text.split("\n").length, outline: found, ids }; } function edgeKind(reference: Reference, target: CodeSymbol): CodeEdgeKind { if (target.kind === "type" || target.kind === "interface") return "types"; if (reference.construct && target.kind === "class") return "creates"; if (reference.call) return "calls"; return "reads"; } class Resolver { readonly #files: ReadonlyMap; readonly #packages: readonly WorkspacePackage[]; constructor(files: ReadonlyMap, packages: readonly WorkspacePackage[]) { this.#files = files; this.#packages = [...packages].sort((a, b) => b.name.length - a.name.length); } /** The symbol a reference points at: a member of its class, a declaration in its file, or an imported declaration. */ target(file: ParsedFile, index: number, reference: Reference): string | null { const symbols = file.outline.symbols; const own = symbols[index]; if (reference.member) { const owner = own.parent ?? (own.kind === "class" ? index : null); if (owner === null) return null; const member = symbols.findIndex((symbol) => symbol.parent === owner && symbol.name === reference.name); return member >= 0 ? file.ids[member] : null; } const local = symbols.findIndex((symbol) => symbol.parent === null && symbol.name === reference.name); if (local >= 0) return file.ids[local]; const binding = file.outline.imports.find((entry) => entry.local === reference.name); if (!binding || binding.imported === "*") return null; const target = this.#module(file.path, binding.module); return target ? this.#exported(target, binding.imported, 0) : null; } #exported(file: ParsedFile, name: string, hops: number): string | null { if (hops > MAX_EXPORT_HOPS) return null; const symbols = file.outline.symbols; for (const entry of file.outline.exports) { if (entry.exported !== name) continue; if (entry.local !== undefined) { const local = symbols.findIndex((symbol) => symbol.parent === null && symbol.name === entry.local); if (local >= 0) return file.ids[local]; const binding = file.outline.imports.find((imported) => imported.local === entry.local); const next = binding && binding.imported !== "*" ? this.#module(file.path, binding.module) : null; return next && binding ? this.#exported(next, binding.imported, hops + 1) : null; } if (entry.module && entry.imported && entry.imported !== "*") { const next = this.#module(file.path, entry.module); return next ? this.#exported(next, entry.imported, hops + 1) : null; } } if (name !== "default") { const declared = symbols.findIndex((symbol) => symbol.parent === null && symbol.exported && symbol.name === name); if (declared >= 0) return file.ids[declared]; } for (const entry of file.outline.exports) { if (entry.exported !== "*" || !entry.module) continue; const next = this.#module(file.path, entry.module); const found = next && this.#exported(next, name, hops + 1); if (found) return found; } return null; } #module(from: string, specifier: string): ParsedFile | null { if (specifier.startsWith(".")) return this.#file(join(dirname(from), specifier)); const pkg = this.#packages.find((entry) => specifier === entry.name || specifier.startsWith(`${entry.name}/`)); if (!pkg) return null; const subpath = `.${specifier.slice(pkg.name.length)}`; const mapped = pkg.exports.get(subpath); return this.#file(join(pkg.dir, mapped ?? subpath)); } #file(path: string): ParsedFile | null { const exact = this.#files.get(path); if (exact) return exact; const bare = path.replace(/\.(m|c)?jsx?$/, ""); for (const ext of EXTENSIONS) { const found = this.#files.get(bare + ext) ?? this.#files.get(`${path}/index${ext}`); if (found) return found; } return null; } } function dirname(path: string): string { const slash = path.lastIndexOf("/"); return slash < 0 ? "" : path.slice(0, slash); } /** Joins and normalises a repository path. Paths never leave the repository root. */ export function join(base: string, relative: string): string { const parts: string[] = []; for (const part of `${base}/${relative}`.split("/")) { if (!part || part === ".") continue; if (part === "..") parts.pop(); else parts.push(part); } return parts.join("/"); }