import type { CodeChange, CodeEdge, CodeGraph, CodeSymbol, CodeSymbolKind } from "@refs/backend/contract"; /** A block on the map: `root`, a folder (`dir:path`), a file (`file:path`) or a symbol (its own id). */ export type NodeId = string; export type NodeKind = "project" | "folder" | "file" | CodeSymbolKind; export type DiffStatus = "added" | "changed" | "reaches" | "none"; export interface LineDiff { readonly added: number; readonly removed: number; } /** One line of a code card: a head line, a removed line, or a fold that stands for unchanged lines. */ export type CardLine = | { readonly kind: "line"; readonly number: number; readonly text: string; readonly added: boolean } | { readonly kind: "removed"; readonly text: string } | { readonly kind: "fold"; readonly count: number }; const ROOT = "root"; const FOLD_CONTEXT = 2; const NO_DIFF: LineDiff = { added: 0, removed: 0 }; /** * The code map of one commit, as blocks inside blocks: folders, files, declarations and class members. A chain of * folders that each hold only one folder shows as one block, so deep paths stay one step away. */ export class CodeModel { readonly graph: CodeGraph; readonly #children = new Map(); readonly #parents = new Map(); readonly #symbols = new Map(); readonly #lines = new Map(); readonly #outgoing = new Map(); readonly #incoming = new Map(); readonly #changes = new Map(); readonly #added = new Map>(); readonly #diffs = new Map(); readonly #reaching = new Set(); readonly #chains = new Map(); readonly changedSymbols: readonly string[]; constructor(graph: CodeGraph, changes: readonly CodeChange[] = []) { this.graph = graph; for (const symbol of graph.symbols) this.#symbols.set(symbol.id, symbol); for (const file of graph.files) this.#lines.set(file.path, file.lines); for (const edge of graph.edges) { push(this.#outgoing, edge.from, edge); push(this.#incoming, edge.to, edge); } this.#buildTree(); for (const change of changes) this.#changes.set(change.path, change); for (const change of changes) this.#added.set(change.path, new Set(change.added)); this.changedSymbols = this.#mapChanges(); this.#findReaching(); } get hasChanges(): boolean { return this.#changes.size > 0; } kids(id: NodeId): readonly NodeId[] { return this.#children.get(id) ?? []; } parent(id: NodeId): NodeId | null { return this.#parents.get(id) ?? null; } /** The blocks from the root down to this one. */ chain(id: NodeId): readonly NodeId[] { const known = this.#chains.get(id); if (known) return known; const parent = this.parent(id); const chain = parent ? [...this.chain(parent), id] : [id]; this.#chains.set(id, chain); return chain; } symbol(id: NodeId): CodeSymbol | undefined { return this.#symbols.get(id); } kind(id: NodeId): NodeKind { if (id === ROOT) return "project"; if (id.startsWith("dir:")) return "folder"; if (id.startsWith("file:")) return "file"; return this.#symbols.get(id)?.kind ?? "const"; } label(id: NodeId): string { if (id === ROOT) return "Project"; const symbol = this.#symbols.get(id); if (symbol) return symbol.name; const path = id.slice(id.indexOf(":") + 1); const parent = this.parent(id); const base = parent && parent !== ROOT ? parent.slice(parent.indexOf(":") + 1) : ""; const own = base && path.startsWith(`${base}/`) ? path.slice(base.length + 1) : path; return id.startsWith("dir:") ? `${own}/` : own; } /** `Class.member` for a member, the name otherwise. */ qualifiedName(id: NodeId): string { const symbol = this.#symbols.get(id); if (!symbol) return id.startsWith("file:") ? (id.split("/").pop() ?? id) : this.label(id); const parent = symbol.parent ? this.#symbols.get(symbol.parent) : undefined; return parent ? `${parent.name}.${symbol.name}` : symbol.name; } /** Where a card's code comes from: a declaration's lines, or a whole file. Null for a folder. */ span(id: NodeId): { readonly file: string; readonly start: number; readonly end: number } | null { const symbol = this.#symbols.get(id); if (symbol) return symbol; if (id.startsWith("file:")) return { file: id.slice(5), start: 1, end: this.fileLines(id.slice(5)) }; return null; } /** A block and every block inside it. */ within(id: NodeId): Set { const inside = new Set([id]); for (const node of inside) for (const kid of this.kids(node)) inside.add(kid); return inside; } fileLines(path: string): number { return this.#lines.get(path) ?? 0; } outgoing(id: string): readonly CodeEdge[] { return this.#outgoing.get(id) ?? []; } /** The declarations outside a block that use it, most uses first. */ callers(id: string): string[] { const inside = this.within(id); const counts = new Map(); for (const target of inside) for (const edge of this.#incoming.get(target) ?? []) if (!inside.has(edge.from)) counts.set(edge.from, (counts.get(edge.from) ?? 0) + edge.count); return [...counts].sort((a, b) => b[1] - a[1]).map(([from]) => from); } /** The names a card of this block can follow, and where each one goes. Uses inside its members, or inside a whole file, count too. */ followable(id: string): ReadonlyMap { const inside = this.within(id); const names = new Map(); for (const from of inside) { for (const edge of this.outgoing(from)) { const target = this.#symbols.get(edge.to); if (target && !inside.has(edge.to)) names.set(target.name, edge.to); } } return names; } /** Every declaration whose name contains `query`, best matches first. */ search(query: string, limit: number): CodeSymbol[] { const needle = query.trim().toLowerCase(); if (!needle) return []; return this.graph.symbols .filter((symbol) => symbol.name.toLowerCase().includes(needle)) .sort((a, b) => a.name.toLowerCase().indexOf(needle) - b.name.toLowerCase().indexOf(needle) || a.name.length - b.name.length) .slice(0, limit); } /** The declaration that a session most likely starts from: an exported function that nothing uses and that uses the most. */ entryPoint(): string | null { const used = new Set(this.graph.edges.map((edge) => edge.to)); let best: string | null = null; let reach = -1; for (const symbol of this.graph.symbols) { if (symbol.parent || symbol.kind !== "function" || !symbol.exported || used.has(symbol.id)) continue; const out = this.outgoing(symbol.id).length; if (out > reach) [best, reach] = [symbol.id, out]; } return best ?? this.graph.symbols[0]?.id ?? null; } change(path: string): CodeChange | undefined { return this.#changes.get(path); } changes(): readonly CodeChange[] { return [...this.#changes.values()]; } /** Lines added and removed inside a block and everything in it. */ diff(id: NodeId): LineDiff { return this.#diffs.get(id) ?? NO_DIFF; } status(id: NodeId): DiffStatus { const diff = this.diff(id); if (diff.added || diff.removed) { const symbol = this.#symbols.get(id); const added = symbol && this.#added.get(symbol.file); if (symbol && added && !diff.removed && diff.added >= symbol.end - symbol.start + 1) return "added"; return "changed"; } return this.#reaching.has(id) ? "reaches" : "none"; } /** * The lines of a declaration for its card. With a change, removed lines sit where they were, and with `fold` * the unchanged lines between changes fold into one row. */ cardLines(id: string, source: readonly string[] | null, fold: boolean): CardLine[] { const symbol = this.span(id); if (!symbol || !source) return []; const change = this.#changes.get(symbol.file); const added = this.#added.get(symbol.file); const removedAfter = new Map(); for (const line of change?.removed ?? []) if (line.after >= symbol.start - 1 && line.after < symbol.end) push(removedAfter, line.after, line.text); const lines: CardLine[] = [...(removedAfter.get(symbol.start - 1) ?? []).map((text) => ({ kind: "removed" as const, text }))]; for (let number = symbol.start; number <= Math.min(symbol.end, source.length); number++) { lines.push({ kind: "line", number, text: source[number - 1] ?? "", added: added?.has(number) ?? false }); if (number < symbol.end) for (const text of removedAfter.get(number) ?? []) lines.push({ kind: "removed", text }); } if (!fold || !lines.some((line) => line.kind === "removed" || (line.kind === "line" && line.added))) return lines; const keep = new Set(); lines.forEach((line, index) => { if (line.kind === "removed" || (line.kind === "line" && line.added)) for (let near = index - FOLD_CONTEXT; near <= index + FOLD_CONTEXT; near++) keep.add(near); }); const folded: CardLine[] = []; let skipped = 0; lines.forEach((line, index) => { if (!keep.has(index)) return void skipped++; if (skipped) folded.push({ kind: "fold", count: skipped }); skipped = 0; folded.push(line); }); if (skipped) folded.push({ kind: "fold", count: skipped }); return folded; } #buildTree() { const folders = new Map; files: string[] }>(); const folder = (path: string) => folders.get(path) ?? folders.set(path, { folders: new Set(), files: [] }).get(path)!; for (const file of this.graph.files) { const parts = file.path.split("/"); for (let depth = 0; depth < parts.length - 1; depth++) folder(parts.slice(0, depth).join("/")).folders.add(parts.slice(0, depth + 1).join("/")); folder(parts.slice(0, -1).join("/")).files.push(file.path); } folder(""); const collapse = (path: string): string => { let at = path; for (let entry = folders.get(at); entry && entry.files.length === 0 && entry.folders.size === 1; entry = folders.get(at)) at = [...entry.folders][0]; return at; }; const visit = (node: NodeId, path: string) => { const entry = folders.get(path)!; const kids = [...[...entry.folders].sort().map((child) => `dir:${collapse(child)}`), ...entry.files.sort().map((file) => `file:${file}`)]; this.#children.set(node, kids); for (const kid of kids) { this.#parents.set(kid, node); if (kid.startsWith("dir:")) visit(kid, kid.slice(4)); } }; visit(ROOT, collapse("")); const byFile = new Map(); for (const symbol of this.graph.symbols) { const holder = symbol.parent ?? `file:${symbol.file}`; this.#parents.set(symbol.id, holder); push(byFile, holder, symbol.id); } for (const [holder, ids] of byFile) this.#children.set(holder, ids.sort((a, b) => this.#symbols.get(a)!.start - this.#symbols.get(b)!.start)); } /** Gives each changed line to the innermost declaration that holds it, and sums the counts up the tree. */ #mapChanges(): string[] { const touched = new Set(); const count = (id: NodeId, key: keyof LineDiff) => { for (const at of this.chain(id)) { const diff = this.#diffs.get(at) ?? NO_DIFF; this.#diffs.set(at, { ...diff, [key]: diff[key] + 1 }); } }; for (const change of this.#changes.values()) { const file = `file:${change.path}`; if (!this.#parents.has(file)) continue; const owner = (line: number) => this.#innermost(change.path, line) ?? file; for (const line of change.added) { const id = owner(line); count(id, "added"); if (id !== file) touched.add(id); } for (const line of change.removed) { const id = owner(Math.max(1, line.after)); count(id, "removed"); if (id !== file) touched.add(id); } } return [...touched].sort((a, b) => { const x = this.#symbols.get(a)!; const y = this.#symbols.get(b)!; return x.file.localeCompare(y.file) || x.start - y.start; }); } #innermost(path: string, line: number): string | null { let best: CodeSymbol | null = null; for (const id of this.kids(`file:${path}`)) { const symbol = this.#symbols.get(id)!; if (line < symbol.start || line > symbol.end) continue; best = symbol; for (const member of this.kids(id)) { const inner = this.#symbols.get(member)!; if (line >= inner.start && line <= inner.end) best = inner; } } return best?.id ?? null; } /** Declarations that use a changed one, directly or through others. A type use counts only one step away. */ #findReaching() { const queue: [string, number][] = this.changedSymbols.map((id) => [id, 0]); const seen = new Set(this.changedSymbols); for (let index = 0; index < queue.length; index++) { const [id, depth] = queue[index]; for (const edge of this.#incoming.get(id) ?? []) { if ((edge.kind === "types" && depth > 0) || seen.has(edge.from)) continue; seen.add(edge.from); this.#reaching.add(edge.from); queue.push([edge.from, depth + 1]); } } for (const id of [...this.#reaching]) for (const at of this.chain(id)) this.#reaching.add(at); } } function push(map: Map, key: K, value: V) { const list = map.get(key); if (list) list.push(value); else map.set(key, [value]); }