/** * @module line-diff-helper * * Native, zero-dependency Myers / LCS line-diffing engine for text files. * * Computes precise line-by-line diff chunks between text files without external libraries. */ import { GLOBAL_LOG_A_LOT } from '../../../core-constants.mjs'; const lcFile = `[line-diff-helper]`; const logalot = GLOBAL_LOG_A_LOT; export interface LineDiffChunk { /** * Line index in old text where the chunk starts (0-indexed) */ old_i: number; /** * Deleted lines from old text */ oldLines: string[]; /** * Inserted lines in new text */ newLines: string[]; } export interface LineDiffResult { /** * Array of line diff chunks */ chunks: LineDiffChunk[]; /** * Set if total lines exceed max limit and force flag was false */ tooBig?: boolean; /** * Set if binary data was detected and force flag was false */ treatedAsBinary?: boolean; } export interface LineDiffOpts { /** * Old file data buffer (optional if new file addition) */ oldData?: Uint8Array; /** * New file data buffer */ newData: Uint8Array; /** * File encoding (defaults to 'utf8') */ fileEncoding?: string; /** * Max line count limit before requiring force flag (defaults to 10000) */ maxLines?: number; /** * Force diff computation even if file is large or binary */ force?: boolean; } /** * Basic binary detection check. * Checks for null bytes (0x00) within the first 1024 bytes. */ export function isBinaryBuffer(data: Uint8Array): boolean { const sampleSize = Math.min(data.length, 1024); for (let i = 0; i < sampleSize; i++) { if (data[i] === 0) { return true; } } return false; } /** * Decodes Uint8Array buffer into array of text lines. */ export function decodeToLines(data?: Uint8Array, encoding: string = 'utf8'): string[] { if (!data || data.length === 0) { return []; } try { const textDecoder = new TextDecoder(encoding || 'utf8', { fatal: false }); const text = textDecoder.decode(data); return text.split(/\r?\n/); } catch { return []; } } /** * Computes Longest Common Subsequence (LCS) edit script between two arrays of lines. * Returns array of LineDiffChunk structures. * * Optimizations: * 1. Fast path: identical lines. * 2. Prefix & suffix trimming: strips common leading and trailing lines before * allocating the DP matrix (Myers diff pre-pass). * 3. Short-circuit for pure additions or deletions in the middle slice. * 4. Integer line interning: lines in the middle slice are interned to unique 32-bit * integers for single-cycle equality checks. * 5. Flat Int32Array matrix: avoids nested object allocations for LCS DP cells. */ export function computeLineLcsDiff(oldLines: string[], newLines: string[]): LineDiffChunk[] { const M = oldLines.length; const N = newLines.length; // 1. Fast path: identical lines if (M === N && oldLines.every((line, idx) => line === newLines[idx])) { return []; } // 2. Common prefix trimming let prefixCount = 0; while (prefixCount < M && prefixCount < N && oldLines[prefixCount] === newLines[prefixCount]) { prefixCount++; } // 3. Common suffix trimming (cannot overlap with prefix) let suffixCount = 0; while ( suffixCount < (M - prefixCount) && suffixCount < (N - prefixCount) && oldLines[M - 1 - suffixCount] === newLines[N - 1 - suffixCount] ) { suffixCount++; } const M_prime = M - prefixCount - suffixCount; const N_prime = N - prefixCount - suffixCount; // 4. Short-circuit: pure insertion in the middle if (M_prime === 0 && N_prime > 0) { return [{ old_i: prefixCount, oldLines: [], newLines: newLines.slice(prefixCount, N - suffixCount), }]; } // 5. Short-circuit: pure deletion in the middle if (M_prime > 0 && N_prime === 0) { return [{ old_i: prefixCount, oldLines: oldLines.slice(prefixCount, M - suffixCount), newLines: [], }]; } // If both slices are empty (safety check) if (M_prime === 0 && N_prime === 0) { return []; } const oldMiddle = oldLines.slice(prefixCount, M - suffixCount); const newMiddle = newLines.slice(prefixCount, N - suffixCount); // 6. Integer Line Interning const lineMap = new Map(); let nextId = 1; const intern = (line: string): number => { let id = lineMap.get(line); if (id === undefined) { id = nextId++; lineMap.set(line, id); } return id; }; const oldIds = new Int32Array(M_prime); for (let i = 0; i < M_prime; i++) { oldIds[i] = intern(oldMiddle[i]); } const newIds = new Int32Array(N_prime); for (let j = 0; j < N_prime; j++) { newIds[j] = intern(newMiddle[j]); } // 7. Flat Int32Array DP Matrix const stride = N_prime + 1; const dp = new Int32Array((M_prime + 1) * stride); for (let i = 1; i <= M_prime; i++) { const rowPrev = (i - 1) * stride; const rowCurr = i * stride; const oldId = oldIds[i - 1]; for (let j = 1; j <= N_prime; j++) { if (oldId === newIds[j - 1]) { dp[rowCurr + j] = dp[rowPrev + j - 1] + 1; } else { const up = dp[rowPrev + j]; const left = dp[rowCurr + j - 1]; dp[rowCurr + j] = up > left ? up : left; } } } // 8. Backtracking let i = M_prime; let j = N_prime; const rawEdits: Array<{ type: 'delete' | 'insert' | 'equal'; line: string }> = []; while (i > 0 || j > 0) { const rowCurr = i * stride; const rowPrev = (i - 1) * stride; if (i > 0 && j > 0 && oldIds[i - 1] === newIds[j - 1]) { rawEdits.push({ type: 'equal', line: oldMiddle[i - 1] }); i--; j--; } else if (j > 0 && (i === 0 || dp[rowCurr + j - 1] >= dp[rowPrev + j])) { rawEdits.push({ type: 'insert', line: newMiddle[j - 1] }); j--; } else if (i > 0 && (j === 0 || dp[rowCurr + j - 1] < dp[rowPrev + j])) { rawEdits.push({ type: 'delete', line: oldMiddle[i - 1] }); i--; } } rawEdits.reverse(); // 9. Group edit operations into chunks const chunks: LineDiffChunk[] = []; let currentChunk: LineDiffChunk | null = null; let oldLineCursor = prefixCount; for (const edit of rawEdits) { if (edit.type === 'equal') { if (currentChunk) { chunks.push(currentChunk); currentChunk = null; } oldLineCursor++; } else { if (!currentChunk) { currentChunk = { old_i: oldLineCursor, oldLines: [], newLines: [], }; } if (edit.type === 'delete') { currentChunk.oldLines.push(edit.line); oldLineCursor++; } else if (edit.type === 'insert') { currentChunk.newLines.push(edit.line); } } } if (currentChunk) { chunks.push(currentChunk); } return chunks; } /** * Main line diff helper function for text files. */ export function getLineDiffChunks(opts: LineDiffOpts): LineDiffResult { const lc = `${lcFile}[${getLineDiffChunks.name}]`; const { oldData, newData, fileEncoding = 'utf8', maxLines = 10000, force = false, } = opts; // Check for binary data const oldIsBin = oldData ? isBinaryBuffer(oldData) : false; const newIsBin = isBinaryBuffer(newData); if ((oldIsBin || newIsBin) && !force) { if (logalot) { console.log(`${lc} Binary data detected, skipping line diff.`); } return { chunks: [], treatedAsBinary: true }; } const oldLines = decodeToLines(oldData, fileEncoding); const newLines = decodeToLines(newData, fileEncoding); // Check max lines threshold if ((oldLines.length > maxLines || newLines.length > maxLines) && !force) { if (logalot) { console.log(`${lc} Line count exceeds limit (${maxLines}), skipping line diff.`); } return { chunks: [], tooBig: true }; } const chunks = computeLineLcsDiff(oldLines, newLines); return { chunks }; }