import { createHash } from 'node:crypto'; import { createTwoFilesPatch, diffLines } from 'diff'; import type { FilePatchSummary } from '../../types.js'; const MAX_BYTES = 5 * 1024 * 1024; const MAX_LINES = 200_000; const MAX_DIFF_CHARS = 16_000; function hash(value: string): string { return createHash('sha256').update(value).digest('hex'); } export function buildPatchSummary( before: string, after: string, label: string, ): FilePatchSummary { const beforeHash = hash(before); const afterHash = hash(after); const totalBytes = Buffer.byteLength(before) + Buffer.byteLength(after); const totalLines = (before.match(/\n/g)?.length ?? 0) + (after.match(/\n/g)?.length ?? 0) + 2; if (totalBytes > MAX_BYTES || totalLines > MAX_LINES) { // Strip identical outer lines before expensive diff work. A large file with // a small edit still gets a real preview with original line coordinates. let prefix = 0; while (prefix < Math.min(before.length, after.length) && before[prefix] === after[prefix]) prefix++; const start = before.lastIndexOf('\n', Math.max(0, prefix - 1)) + 1; let suffix = 0; while (suffix < Math.min(before.length, after.length) - start && before[before.length - suffix - 1] === after[after.length - suffix - 1]) suffix++; const tail = before.indexOf('\n', before.length - suffix); const suffixLength = tail < 0 ? 0 : before.length - tail - 1; const oldWindow = before.slice(start, before.length - suffixLength); const newWindow = after.slice(start, after.length - suffixLength); if (Buffer.byteLength(oldWindow) + Buffer.byteLength(newWindow) <= MAX_BYTES && (oldWindow.match(/\n/g)?.length ?? 0) + (newWindow.match(/\n/g)?.length ?? 0) + 2 <= MAX_LINES) { const local = buildPatchSummary(oldWindow, newWindow, label); const shift = (before.slice(0, start).match(/\n/g)?.length ?? 0); return { ...local, beforeHash, afterHash, unifiedDiff: local.unifiedDiff?.replace(/@@ -(\d+)(,\d+)? \+(\d+)(,\d+)? @@/g, (_, a, ac = '', b, bc = '') => `@@ -${Number(a) + shift}${ac} +${Number(b) + shift}${bc} @@`) }; } return { beforeHash, afterHash, truncated: true, omittedReason: 'too_large', }; } const changes = diffLines(before, after, { timeout: 500, maxEditLength: 10_000 }); if (!changes) return { beforeHash, afterHash, truncated: true, omittedReason: 'too_large' }; const additions = changes .filter((change) => change.added) .reduce((sum, change) => sum + (change.count ?? 0), 0); const deletions = changes .filter((change) => change.removed) .reduce((sum, change) => sum + (change.count ?? 0), 0); let unifiedDiff = createTwoFilesPatch( `a/${label}`, `b/${label}`, before, after, undefined, undefined, { context: 3 }, ); const truncated = unifiedDiff.length > MAX_DIFF_CHARS; if (truncated) { unifiedDiff = `${unifiedDiff.slice(0, MAX_DIFF_CHARS)}\n... (diff preview truncated)`; } return { unifiedDiff, beforeHash, afterHash, additions, deletions, truncated, }; }