import path from "node:path"; import type { BundledLanguage } from "shiki"; import { MAX_DIFF_CACHE } from "../constants.ts"; import { detectLang, getHighlighter } from "./highlight.ts"; // ─── Types ─────────────────────────────────────────────────────────────────── export type DiffStatus = | "added" | "deleted" | "modified" | "renamed" | "copied"; export interface RenderedRow { type: "add" | "del" | "context"; oldLine: number | null; newLine: number | null; html: string; } export interface RenderedHunk { header: string; rows: RenderedRow[]; } export interface RenderedDiffFile { oldPath: string; newPath: string; status: DiffStatus; added: number; removed: number; isBinary: boolean; hunks: RenderedHunk[]; } // ─── Parser ────────────────────────────────────────────────────────────────── interface ParsedLine { type: "add" | "del" | "context"; content: string; } interface ParsedHunk { header: string; oldStart: number; newStart: number; lines: ParsedLine[]; } export interface ParsedFile { oldPath: string; newPath: string; status: DiffStatus; added: number; removed: number; isBinary: boolean; hunks: ParsedHunk[]; } export function parseDiff(raw: string): ParsedFile[] { const files: ParsedFile[] = []; const allLines = raw.split("\n"); let i = 0; while (i < allLines.length) { if (!allLines[i]!.startsWith("diff --git ")) { i++; continue; } const m = allLines[i]!.match(/^diff --git a\/(.+) b\/(.+)$/); const fallback = m ? (m[2] ?? "") : ""; const file: ParsedFile = { oldPath: fallback, newPath: fallback, status: "modified", added: 0, removed: 0, isBinary: false, hunks: [], }; i++; while (i < allLines.length) { const line = allLines[i]!; if (line.startsWith("diff --git ") || line.startsWith("@@ ")) break; if (line.startsWith("new file")) file.status = "added"; else if (line.startsWith("deleted file")) file.status = "deleted"; else if (line.startsWith("rename from ")) { file.status = "renamed"; file.oldPath = line.slice(12); } else if (line.startsWith("rename to ")) { file.newPath = line.slice(10); } else if (line.startsWith("copy from ")) { file.status = "copied"; file.oldPath = line.slice(10); } else if (line.startsWith("copy to ")) { file.newPath = line.slice(8); } else if (line.startsWith("--- ") && line !== "--- /dev/null") file.oldPath = line.slice(6); else if (line.startsWith("+++ ") && line !== "+++ /dev/null") file.newPath = line.slice(6); else if (line.startsWith("Binary files ")) file.isBinary = true; i++; } while (i < allLines.length && allLines[i]!.startsWith("@@ ")) { const hm = allLines[i]!.match( /@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/, ); const hunk: ParsedHunk = { header: allLines[i]!, oldStart: hm ? parseInt(hm[1]!, 10) : 1, newStart: hm ? parseInt(hm[2]!, 10) : 1, lines: [], }; i++; while ( i < allLines.length && !allLines[i]!.startsWith("@@ ") && !allLines[i]!.startsWith("diff --git ") ) { const l = allLines[i]!; if (l.startsWith("+")) { hunk.lines.push({ type: "add", content: l.slice(1) }); file.added++; } else if (l.startsWith("-")) { hunk.lines.push({ type: "del", content: l.slice(1) }); file.removed++; } else if (l.startsWith(" ")) { hunk.lines.push({ type: "context", content: l.slice(1) }); } // skip "\ No newline at end of file" i++; } file.hunks.push(hunk); } files.push(file); } return files; } function escapeHtml(s: string): string { return s.replace(/&/g, "&").replace(//g, ">"); } // ─── Highlight a hunk ──────────────────────────────────────────────────────── async function highlightHunk( hunk: ParsedHunk, lang: string, ): Promise { if (hunk.lines.length === 0) return []; const code = hunk.lines.map((l) => l.content).join("\n"); try { const h = await getHighlighter(); const tokensByLine = h.codeToTokensWithThemes(code, { lang: lang as BundledLanguage, themes: { light: "github-light", dark: "github-dark" }, }); const lines = tokensByLine.map((lineTokens) => lineTokens .map((token) => { const style = Object.entries(token.variants) .map( ([theme, v]) => `--shiki-${theme}:${v.color ?? "inherit"}`, ) .join(";"); return `${escapeHtml(token.content)}`; }) .join(""), ); while (lines.length < hunk.lines.length) lines.push(""); return lines; } catch { return hunk.lines.map((l) => escapeHtml(l.content)); } } // ─── Build rendered rows ────────────────────────────────────────────────────── function buildRows(hunk: ParsedHunk, highlighted: string[]): RenderedRow[] { const rows: RenderedRow[] = []; let oldLine = hunk.oldStart; let newLine = hunk.newStart; for (let i = 0; i < hunk.lines.length; i++) { const { type } = hunk.lines[i]!; const html = highlighted[i] ?? ""; if (type === "context") { rows.push({ type, oldLine: oldLine++, newLine: newLine++, html }); } else if (type === "add") { rows.push({ type, oldLine: null, newLine: newLine++, html }); } else { rows.push({ type, oldLine: oldLine++, newLine: null, html }); } } return rows; } // ─── Highlight a single parsed file ────────────────────────────────────────── export async function highlightFile( file: ParsedFile, ): Promise { const displayPath = file.newPath || file.oldPath; const lang = detectLang(path.basename(displayPath)); const highlightedHunks = await Promise.all( file.hunks.map((hunk) => highlightHunk(hunk, lang)), ); const hunks: RenderedHunk[] = file.hunks.map((hunk, i) => ({ header: hunk.header, rows: buildRows(hunk, highlightedHunks[i]!), })); return { oldPath: file.oldPath, newPath: file.newPath, status: file.status, added: file.added, removed: file.removed, isBinary: file.isBinary, hunks, }; } // ─── Public API ────────────────────────────────────────────────────────────── const diffCache = new Map(); export async function prepareDiff( rawDiff: string, cacheKey: string, ): Promise { const cached = diffCache.get(cacheKey); if (cached) return cached; const parsed = parseDiff(rawDiff); const result = await Promise.all( parsed.map(async (file) => { const displayPath = file.newPath || file.oldPath; const lang = detectLang(path.basename(displayPath)); const highlightedHunks = await Promise.all( file.hunks.map((hunk) => highlightHunk(hunk, lang)), ); const hunks: RenderedHunk[] = file.hunks.map((hunk, i) => ({ header: hunk.header, rows: buildRows(hunk, highlightedHunks[i]!), })); return { oldPath: file.oldPath, newPath: file.newPath, status: file.status, added: file.added, removed: file.removed, isBinary: file.isBinary, hunks, }; }), ); if (cacheKey) { if (diffCache.size >= MAX_DIFF_CACHE) diffCache.delete(diffCache.keys().next().value!); diffCache.set(cacheKey, result); } return result; }