diff.mjs 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. // 行级差异引擎:Myers diff + 左右对齐 + 行内字符级高亮。
  2. // 只依赖 Node 内置能力,不引入任何 npm 包。
  3. const EQ = 1;
  4. const DEL = 2;
  5. const INS = 3;
  6. export const ROW_SAME = "=";
  7. export const ROW_CHANGE = "~";
  8. export const ROW_LEFT_ONLY = "-";
  9. export const ROW_RIGHT_ONLY = "+";
  10. export function splitLines(text) {
  11. if (text === "") return [];
  12. const lines = text.split(/\r\n|\r|\n/);
  13. if (lines.length > 0 && lines[lines.length - 1] === "") lines.pop();
  14. return lines;
  15. }
  16. // 一个超长单行文件(例如把整个类挤在一行的混淆源码)会退化成字符级比较,
  17. // 这里按固定宽度切断,既保留可读性又让 diff 有可对齐的单位。
  18. const LONG_LINE_LIMIT = 2000;
  19. const CHUNK_WIDTH = 160;
  20. export function splitLinesForDiff(text) {
  21. const raw = splitLines(text);
  22. let needsChunk = false;
  23. for (const line of raw) {
  24. if (line.length > LONG_LINE_LIMIT) {
  25. needsChunk = true;
  26. break;
  27. }
  28. }
  29. if (!needsChunk) return { lines: raw, chunked: false };
  30. const out = [];
  31. for (const line of raw) {
  32. if (line.length <= LONG_LINE_LIMIT) {
  33. out.push(line);
  34. continue;
  35. }
  36. for (let i = 0; i < line.length; i += CHUNK_WIDTH) {
  37. out.push(line.slice(i, i + CHUNK_WIDTH));
  38. }
  39. }
  40. return { lines: out, chunked: true };
  41. }
  42. function myersCore(a, b, maxD) {
  43. const n = a.length;
  44. const m = b.length;
  45. if (n === 0 && m === 0) return [];
  46. const max = Math.min(maxD, n + m);
  47. const size = 2 * max + 1;
  48. const v = new Int32Array(size);
  49. const traces = [];
  50. for (let d = 0; d <= max; d++) {
  51. traces.push(v.slice());
  52. for (let k = -d; k <= d; k += 2) {
  53. let x;
  54. if (k === -d || (k !== d && v[max + k - 1] < v[max + k + 1])) x = v[max + k + 1];
  55. else x = v[max + k - 1] + 1;
  56. let y = x - k;
  57. while (x < n && y < m && a[x] === b[y]) {
  58. x++;
  59. y++;
  60. }
  61. v[max + k] = x;
  62. if (x >= n && y >= m) return backtrack(traces, n, m, max);
  63. }
  64. }
  65. return null;
  66. }
  67. function backtrack(traces, n, m, max) {
  68. let x = n;
  69. let y = m;
  70. const ops = [];
  71. for (let d = traces.length - 1; d >= 0; d--) {
  72. const v = traces[d];
  73. const k = x - y;
  74. let prevK;
  75. if (k === -d || (k !== d && v[max + k - 1] < v[max + k + 1])) prevK = k + 1;
  76. else prevK = k - 1;
  77. const prevX = v[max + prevK];
  78. const prevY = prevX - prevK;
  79. while (x > prevX && y > prevY) {
  80. ops.push([EQ, x - 1, y - 1]);
  81. x--;
  82. y--;
  83. }
  84. if (d > 0) {
  85. if (x === prevX) {
  86. ops.push([INS, -1, y - 1]);
  87. y--;
  88. } else {
  89. ops.push([DEL, x - 1, -1]);
  90. x--;
  91. }
  92. }
  93. }
  94. ops.reverse();
  95. return ops;
  96. }
  97. function opsFor(a, b, maxD) {
  98. // 先削掉公共前缀/后缀,常见场景(文件里只有局部改动)能省掉绝大部分计算。
  99. let start = 0;
  100. while (start < a.length && start < b.length && a[start] === b[start]) start++;
  101. let endA = a.length;
  102. let endB = b.length;
  103. while (endA > start && endB > start && a[endA - 1] === b[endB - 1]) {
  104. endA--;
  105. endB--;
  106. }
  107. const midA = a.slice(start, endA);
  108. const midB = b.slice(start, endB);
  109. const ops = myersCore(midA, midB, maxD);
  110. const head = [];
  111. for (let i = 0; i < start; i++) head.push([EQ, i, i]);
  112. if (ops === null) {
  113. // 差异过大:退化成“整块替换”,仍然保证左右行号正确。
  114. const block = [];
  115. for (let i = 0; i < midA.length; i++) block.push([DEL, start + i, -1]);
  116. for (let i = 0; i < midB.length; i++) block.push([INS, -1, start + i]);
  117. const tail = [];
  118. for (let i = 0; i < a.length - endA; i++) tail.push([EQ, endA + i, endB + i]);
  119. return { ops: head.concat(block, tail), collapsed: true };
  120. }
  121. const shifted = ops.map(([type, ai, bi]) => [
  122. type,
  123. ai < 0 ? -1 : ai + start,
  124. bi < 0 ? -1 : bi + start,
  125. ]);
  126. const tail = [];
  127. for (let i = 0; i < a.length - endA; i++) tail.push([EQ, endA + i, endB + i]);
  128. return { ops: head.concat(shifted, tail), collapsed: false };
  129. }
  130. /**
  131. * 生成左右对齐的行数组。
  132. * 返回 { rows, stats, collapsed, totalRows }
  133. * row: { type, leftNo, rightNo, left, right, inline? }
  134. */
  135. export function buildRows(leftText, rightText, options = {}) {
  136. const maxD = options.maxD ?? 900;
  137. const inline = options.inline !== false;
  138. const left = splitLinesForDiff(leftText ?? "");
  139. const right = splitLinesForDiff(rightText ?? "");
  140. const a = left.lines;
  141. const b = right.lines;
  142. const { ops, collapsed } = opsFor(a, b, maxD);
  143. const rows = [];
  144. const stats = { added: 0, removed: 0, changed: 0, unchanged: 0 };
  145. let i = 0;
  146. while (i < ops.length) {
  147. const op = ops[i];
  148. if (op[0] === EQ) {
  149. rows.push({
  150. type: ROW_SAME,
  151. leftNo: op[1] + 1,
  152. rightNo: op[2] + 1,
  153. left: a[op[1]],
  154. right: b[op[2]],
  155. });
  156. stats.unchanged++;
  157. i++;
  158. continue;
  159. }
  160. // 收集连续的删除/新增块,配对的算“修改”,落单的算纯增/纯删。
  161. const dels = [];
  162. const inss = [];
  163. while (i < ops.length && ops[i][0] !== EQ) {
  164. if (ops[i][0] === DEL) dels.push(ops[i][1]);
  165. else inss.push(ops[i][2]);
  166. i++;
  167. }
  168. const pairs = Math.min(dels.length, inss.length);
  169. for (let p = 0; p < pairs; p++) {
  170. const li = dels[p];
  171. const ri = inss[p];
  172. const row = {
  173. type: ROW_CHANGE,
  174. leftNo: li + 1,
  175. rightNo: ri + 1,
  176. left: a[li],
  177. right: b[ri],
  178. };
  179. if (inline) {
  180. const seg = inlineSegments(a[li], b[ri]);
  181. row.leftSeg = seg.left;
  182. row.rightSeg = seg.right;
  183. }
  184. rows.push(row);
  185. stats.changed++;
  186. }
  187. for (let p = pairs; p < dels.length; p++) {
  188. rows.push({
  189. type: ROW_LEFT_ONLY,
  190. leftNo: dels[p] + 1,
  191. rightNo: null,
  192. left: a[dels[p]],
  193. right: null,
  194. });
  195. stats.removed++;
  196. }
  197. for (let p = pairs; p < inss.length; p++) {
  198. rows.push({
  199. type: ROW_RIGHT_ONLY,
  200. leftNo: null,
  201. rightNo: inss[p] + 1,
  202. left: null,
  203. right: b[inss[p]],
  204. });
  205. stats.added++;
  206. }
  207. }
  208. return {
  209. rows,
  210. stats,
  211. collapsed,
  212. chunked: left.chunked || right.chunked,
  213. totalRows: rows.length,
  214. };
  215. }
  216. const TOKEN_RE = /[\p{L}\p{N}_$]+|\s+|./gu;
  217. const INLINE_TOKEN_LIMIT = 2200;
  218. function tokenize(line) {
  219. const out = [];
  220. const re = new RegExp(TOKEN_RE.source, TOKEN_RE.flags);
  221. let m;
  222. while ((m = re.exec(line)) !== null) {
  223. out.push(m[0]);
  224. if (out.length > INLINE_TOKEN_LIMIT) return null;
  225. }
  226. return out;
  227. }
  228. function commonPrefixSuffix(a, b) {
  229. let prefix = 0;
  230. const minLen = Math.min(a.length, b.length);
  231. while (prefix < minLen && a.charCodeAt(prefix) === b.charCodeAt(prefix)) prefix++;
  232. let suffix = 0;
  233. while (
  234. suffix < minLen - prefix &&
  235. a.charCodeAt(a.length - 1 - suffix) === b.charCodeAt(b.length - 1 - suffix)
  236. ) {
  237. suffix++;
  238. }
  239. return { prefix, suffix };
  240. }
  241. /**
  242. * 行内高亮:返回左右两边的片段数组 [{ t: 文本, c: 0 相同 / 1 差异 }]。
  243. * 同一行差异过大时退化为“公共前后缀 + 中间整体标红”,避免页面被碎片淹没。
  244. */
  245. export function inlineSegments(a, b) {
  246. if (a === b) {
  247. return { left: [{ t: a, c: 0 }], right: [{ t: b, c: 0 }] };
  248. }
  249. const ta = tokenize(a);
  250. const tb = tokenize(b);
  251. let pairs = null;
  252. if (ta && tb) {
  253. const ops = myersCore(ta, tb, 240);
  254. if (ops) {
  255. pairs = { ops, ta, tb };
  256. }
  257. }
  258. if (pairs) {
  259. const { ops, ta: la, tb: lb } = pairs;
  260. const left = [];
  261. const right = [];
  262. let sawDiff = false;
  263. for (const [type, ai, bi] of ops) {
  264. if (type === EQ) {
  265. pushSeg(left, la[ai], 0);
  266. pushSeg(right, lb[bi], 0);
  267. } else if (type === DEL) {
  268. pushSeg(left, la[ai], 1);
  269. sawDiff = true;
  270. } else {
  271. pushSeg(right, lb[bi], 1);
  272. sawDiff = true;
  273. }
  274. }
  275. if (sawDiff) return { left, right };
  276. }
  277. const { prefix, suffix } = commonPrefixSuffix(a, b);
  278. const leftMid = a.slice(prefix, a.length - suffix);
  279. const rightMid = b.slice(prefix, b.length - suffix);
  280. const left = [];
  281. const right = [];
  282. pushSeg(left, a.slice(0, prefix), 0);
  283. if (leftMid) pushSeg(left, leftMid, 1);
  284. pushSeg(left, a.slice(a.length - suffix), 0);
  285. pushSeg(right, b.slice(0, prefix), 0);
  286. if (rightMid) pushSeg(right, rightMid, 1);
  287. pushSeg(right, b.slice(b.length - suffix), 0);
  288. return { left, right };
  289. }
  290. function pushSeg(list, text, code) {
  291. if (!text) return;
  292. const last = list[list.length - 1];
  293. if (last && last.c === code) last.t += text;
  294. else list.push({ t: text, c: code });
  295. }
  296. /**
  297. * 只保留差异块及其上下文,用于“仅显示差异”。
  298. * rows 是 buildRows 的结果,返回新的 rows 子集;被省略的位置插入省略标记。
  299. */
  300. export function collapseRows(rows, context = 3) {
  301. const keep = new Array(rows.length).fill(false);
  302. for (let i = 0; i < rows.length; i++) {
  303. if (rows[i].type === ROW_SAME) continue;
  304. const from = Math.max(0, i - context);
  305. const to = Math.min(rows.length - 1, i + context);
  306. for (let j = from; j <= to; j++) keep[j] = true;
  307. }
  308. const out = [];
  309. let hidden = 0;
  310. for (let i = 0; i < rows.length; i++) {
  311. if (keep[i]) {
  312. if (hidden > 0) {
  313. out.push({ type: "gap", hidden });
  314. hidden = 0;
  315. }
  316. out.push(rows[i]);
  317. } else {
  318. hidden++;
  319. }
  320. }
  321. if (hidden > 0) out.push({ type: "gap", hidden });
  322. return out;
  323. }