import assert from "node:assert/strict"; import { test } from "node:test"; import { indexCommit, toPackage } from "../code-index/build.ts"; import { buildGraph } from "../code-index/graph.ts"; import { outline } from "../code-index/outline.ts"; import { CODE_MAP_VERSION, claimBuild, readCodeMap, saveCodeMap } from "../code-index/store.ts"; import { codeChanges } from "../code-maps.ts"; import type { ChangeSet, CodeGraph } from "../contract/views.ts"; import { d1, migrated } from "./d1.ts"; const names = (source: string) => outline(source).symbols.map((symbol) => `${symbol.kind} ${symbol.name} ${symbol.start}-${symbol.end}${symbol.exported ? " exported" : ""}`); test("an outline finds top-level declarations with their line ranges", () => { const source = [ 'import { helper } from "./helper.ts";', "/** Adds two numbers. */", "export function add(a: number, b: number): { sum: number } {", " return { sum: helper(a) + b };", "}", "const LIMIT = 3;", "export const double = (value: number) => value * 2;", "export type Shape = { kind: string };", "interface Point {", " x: number;", "}", "enum Color { Red, Green }", "export default function main() {}", ].join("\n"); assert.deepEqual(names(source), ["function add 3-5 exported", "const LIMIT 6-6", "function double 7-7 exported", "type Shape 8-8 exported", "interface Point 9-11", "enum Color 12-12", "function main 13-13 exported"]); const found = outline(source); assert.equal(found.symbols[0].doc, "Adds two numbers."); assert.deepEqual(found.exports, [{ exported: "default", local: "main" }]); assert.deepEqual(found.imports, [{ local: "helper", module: "./helper.ts", imported: "helper" }]); assert.deepEqual(found.references[0].map((reference) => reference.name), ["a", "helper", "a", "b"]); }); test("an outline finds class members and marks `this.` uses as member uses", () => { const source = ["export class Store {", " #items: string[] = [];", " constructor(private readonly name: string) {}", " add(item: string) {", " this.#items.push(item);", " this.notify();", " }", " notify(): void {}", " get size() {", " return this.#items.length;", " }", "}"].join("\n"); const found = outline(source); assert.deepEqual(found.symbols.map((symbol) => `${symbol.kind} ${symbol.name} ${symbol.start}-${symbol.end} ${symbol.parent}`), ["class Store 1-12 null", "field #items 2-2 0", "method constructor 3-3 0", "method add 4-7 0", "method notify 8-8 0", "method size 9-11 0"]); assert.deepEqual(found.references[3].filter((reference) => reference.member).map((reference) => reference.name), ["#items", "notify"]); assert.deepEqual(found.references[0], []); }); test("an outline reads JSX tags as uses and does not mistake `` for a regular expression", () => { const source = ['import { Card } from "./card.tsx";', "export function Page({ items }: { items: string[] }) {", " return ;", "}", "function List({ items }: { items: string[] }) {", " return ;", "}"].join("\n"); const found = outline(source); assert.deepEqual(names(source), ["function Page 2-4 exported", "function List 5-7"]); assert.deepEqual(found.references[0].filter((reference) => reference.call).map((reference) => reference.name), ["Card", "List"]); }); test("the graph resolves uses across relative imports, re-exports and workspace packages", () => { const graph = buildGraph( "c1", [ { path: "app/main.ts", text: 'import { createStore } from "./store/index.ts";\nimport { format } from "@acme/util/format";\nexport function main() {\n const store = createStore();\n return format(store.name);\n}' }, { path: "app/store/index.ts", text: 'export { createStore } from "./create.ts";' }, { path: "app/store/create.ts", text: 'import type { Store } from "./types.ts";\nexport function createStore(): Store {\n return new MemoryStore();\n}\nclass MemoryStore {\n name = "s";\n}' }, { path: "app/store/types.ts", text: "export interface Store {\n name: string;\n}" }, { path: "packages/util/format.ts", text: "export function format(value: string) {\n return value.trim();\n}" }, ], [{ name: "@acme/util", dir: "packages/util", exports: new Map([["./format", "format.ts"]]) }], 2, ); const edges = graph.edges.map((edge) => `${edge.from} ${edge.kind} ${edge.to}`).sort(); assert.deepEqual(edges, [ "app/main.ts#main calls app/store/create.ts#createStore", "app/main.ts#main calls packages/util/format.ts#format", "app/store/create.ts#createStore creates app/store/create.ts#MemoryStore", "app/store/create.ts#createStore types app/store/types.ts#Store", ]); assert.equal(graph.skipped, 2); assert.deepEqual(graph.files.map((file) => file.path), ["app/main.ts", "app/store/create.ts", "app/store/index.ts", "app/store/types.ts", "packages/util/format.ts"]); }); test("a package's exports map becomes repository paths", () => { const pkg = toPackage("packages/ui/package.json", JSON.stringify({ name: "@acme/ui", exports: { ".": "./index.ts", "./icons": { import: "./icons.tsx" } } })); assert.deepEqual(pkg && { name: pkg.name, dir: pkg.dir, exports: [...pkg.exports] }, { name: "@acme/ui", dir: "packages/ui", exports: [[".", "index.ts"], ["./icons", "icons.tsx"]] }); assert.equal(toPackage("package.json", "not json"), null); }); function fakeRepo(): ArtifactsRepo { const trees: Record = { root: [ { name: "src", hash: "src", type: "tree", mode: "40000" }, { name: "node_modules", hash: "deps", type: "tree", mode: "40000" }, { name: "package.json", hash: "pkg", type: "blob", mode: "100644" }, { name: "README.md", hash: "readme", type: "blob", mode: "100644" }, ], src: [ { name: "app.ts", hash: "app", type: "blob", mode: "100644" }, { name: "env.d.ts", hash: "env", type: "blob", mode: "100644" }, ], deps: [{ name: "lib.js", hash: "lib", type: "blob", mode: "100644" }], }; const blobs: Record = { app: "export function app() {}\n", env: "declare const x: number;", lib: "export function lib() {}", pkg: '{"name":"demo"}', readme: "# demo" }; return { readCommit: async (hash: string) => (hash === "c1" ? { hash, treeHash: "root", parents: [], message: "m", author: { name: "A", email: "a@x" }, committer: { name: "A", email: "a@x" }, authoredAt: 1, committedAt: 1 } : null), readTree: async (hash: string) => trees[hash] ?? null, readBlob: async (hash: string) => (hash in blobs ? new Blob([blobs[hash]]) : null), } as unknown as ArtifactsRepo; } test("indexing a commit reads its source files and skips dependencies and declaration files", async () => { const graph = await indexCommit(fakeRepo(), "c1"); assert.deepEqual(graph.files, [{ path: "src/app.ts", lines: 2 }]); assert.deepEqual(graph.symbols.map((symbol) => symbol.id), ["src/app.ts#app"]); await assert.rejects(indexCommit(fakeRepo(), "missing"), /Commit missing was not found/); }); test("a commit's map is built once, then read back from storage", async () => { const db = d1(migrated()); const graph: CodeGraph = { commit: "c1", files: [{ path: "a.ts", lines: 1 }], symbols: [{ id: "a.ts#a", file: "a.ts", name: "a", kind: "function", parent: null, start: 1, end: 1, exported: true, doc: null }], edges: [], skipped: 0 }; assert.equal(await readCodeMap(db, "r1", "c1", 100), null); assert.equal(await claimBuild(db, "r1", "c1", 100), true); assert.equal(await claimBuild(db, "r1", "c1", 101), false); assert.deepEqual(await readCodeMap(db, "r1", "c1", 102), { kind: "indexing", commit: "c1" }); await saveCodeMap(db, "r1", graph, 103); assert.deepEqual(await readCodeMap(db, "r1", "c1", 104), { kind: "ready", graph }); assert.equal(await claimBuild(db, "r1", "c1", 105), false); assert.equal(CODE_MAP_VERSION, 1); }); test("a build that never finished is taken over, and an empty commit is stored as empty", async () => { const db = d1(migrated()); assert.equal(await claimBuild(db, "r1", "c2", 100), true); assert.equal(await claimBuild(db, "r1", "c2", 100 + 10 * 60), true); await saveCodeMap(db, "r1", { commit: "c2", files: [], symbols: [], edges: [], skipped: 0 }, 700); assert.deepEqual(await readCodeMap(db, "r1", "c2", 701), { kind: "unavailable", commit: "c2", reason: "empty" }); }); test("code changes place added lines and removed lines on the head version", () => { const changes = { base: "b", head: "h", commits: [], additions: 2, deletions: 1, truncated: false, files: [ { path: "a.ts", status: "modified", kind: "text", additions: 2, deletions: 1, before: "one\ntwo\nthree\n", after: "one\nTWO\nthree\nfour\n", truncated: false }, { path: "img.png", status: "added", kind: "binary", additions: 0, deletions: 0, before: null, after: null, truncated: false }, ], } satisfies ChangeSet; assert.deepEqual(codeChanges(changes), [ { path: "a.ts", status: "modified", additions: 2, deletions: 1, added: [2, 4], removed: [{ after: 1, text: "two" }] }, { path: "img.png", status: "added", additions: 0, deletions: 0, added: [], removed: [] }, ]); });