svelte-highlight 7.23.2 → 7.24.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/AnsiOutput.svelte +33 -6
  2. package/AnsiOutput.svelte.d.ts +8 -0
  3. package/CodeToolbar.svelte +144 -0
  4. package/CodeToolbar.svelte.d.ts +125 -0
  5. package/CodeWindow.svelte +19 -0
  6. package/CodeWindow.svelte.d.ts +10 -0
  7. package/CopyButton.svelte +107 -3
  8. package/CopyButton.svelte.d.ts +17 -1
  9. package/DiffFileList.svelte +523 -0
  10. package/DiffFileList.svelte.d.ts +94 -0
  11. package/DiffFileListItem.svelte +44 -0
  12. package/DiffMinimap.svelte +99 -0
  13. package/DiffMinimap.svelte.d.ts +17 -0
  14. package/DiffStats.svelte +43 -0
  15. package/DiffStats.svelte.d.ts +17 -0
  16. package/DiffView.svelte +1213 -0
  17. package/DiffView.svelte.d.ts +76 -0
  18. package/FileTabs.svelte +2 -5
  19. package/Highlight.svelte +158 -2
  20. package/Highlight.svelte.d.ts +50 -2
  21. package/HighlightAuto.svelte.d.ts +3 -2
  22. package/HighlightAutoLazy.svelte +112 -0
  23. package/HighlightAutoLazy.svelte.d.ts +66 -0
  24. package/HighlightDiff.svelte +162 -0
  25. package/HighlightDiff.svelte.d.ts +102 -0
  26. package/HighlightEditable.svelte +65 -756
  27. package/HighlightEditable.svelte.d.ts +15 -5
  28. package/HighlightStream.svelte +117 -218
  29. package/HighlightStream.svelte.d.ts +8 -0
  30. package/HighlightSvelte.svelte.d.ts +3 -2
  31. package/HighlightVirtual.svelte +41 -8
  32. package/HighlightVirtual.svelte.d.ts +8 -0
  33. package/LangTag.svelte +33 -4
  34. package/LangTag.svelte.d.ts +6 -2
  35. package/LineNumbers.svelte +25 -4
  36. package/LineNumbers.svelte.d.ts +8 -0
  37. package/MarkdownStream.svelte +1 -0
  38. package/README.md +735 -18
  39. package/ToolbarButton.svelte +90 -0
  40. package/ToolbarButton.svelte.d.ts +106 -0
  41. package/Typewriter.svelte +59 -10
  42. package/Typewriter.svelte.d.ts +7 -0
  43. package/WrapToggle.svelte +34 -0
  44. package/WrapToggle.svelte.d.ts +39 -0
  45. package/action.js +7 -3
  46. package/ansi.d.ts +1 -3
  47. package/auto-detect.d.ts +52 -0
  48. package/auto-detect.js +208 -0
  49. package/code-region.d.ts +7 -0
  50. package/code-region.js +20 -0
  51. package/css-highlights.js +115 -0
  52. package/css-walk.js +50 -0
  53. package/diff-controller.d.ts +120 -0
  54. package/diff-controller.js +721 -0
  55. package/diff-edits.d.ts +101 -0
  56. package/diff-edits.js +890 -0
  57. package/diff-html.d.ts +8 -0
  58. package/diff-html.js +60 -0
  59. package/diff-languages.d.ts +4 -0
  60. package/diff-languages.js +73 -0
  61. package/diff.d.ts +161 -0
  62. package/diff.js +1111 -0
  63. package/editable-commands.js +81 -0
  64. package/editable-css-paint.js +5 -3
  65. package/editable-dom-paint.js +1 -1
  66. package/editable-history.js +199 -0
  67. package/editable-line-dom.js +176 -1
  68. package/editable-painter.js +356 -0
  69. package/editable.d.ts +118 -0
  70. package/editable.js +513 -0
  71. package/engine.d.ts +1 -1
  72. package/fence.js +1 -1
  73. package/highlight-cascade.js +679 -0
  74. package/highlight-theme.js +6 -47
  75. package/incremental-tokenize.js +1 -1
  76. package/index.d.ts +39 -6
  77. package/index.js +30 -0
  78. package/languages/detect-index.d.ts +16 -0
  79. package/languages/detect-index.js +6 -0
  80. package/languages/loaders.d.ts +8 -0
  81. package/languages/loaders.js +370 -0
  82. package/package.json +50 -2
  83. package/preprocessor.js +20 -5
  84. package/search.js +2 -2
  85. package/stream-highlighter.js +198 -0
  86. package/stream.css +16 -0
  87. package/stream.d.ts +60 -0
  88. package/stream.js +283 -0
  89. package/style-registry.js +34 -3
  90. package/themes/_base-css.d.ts +1 -0
  91. package/themes/_base-css.js +1 -0
  92. package/typewriter-units.d.ts +3 -0
  93. package/typewriter-units.js +43 -0
  94. package/virtual-window.js +9 -4
package/diff.js ADDED
@@ -0,0 +1,1111 @@
1
+ // Headless line diff: patience anchors + Myers, streaming sessions whose
2
+ // rows only change past the last sealed anchor, a row model for unified and
3
+ // split views, word-level diffs, moved-block detection, and review helpers.
4
+
5
+ /**
6
+ * A run of the edit script. `equal` runs cover the same line count on both
7
+ * sides (unless `unknown`, for gaps a patch doesn't include); `change` runs
8
+ * delete `before[a, aEnd)` and insert `after[b, bEnd)`.
9
+ * @typedef {{
10
+ * type: "equal" | "change",
11
+ * a: number, aEnd: number,
12
+ * b: number, bEnd: number,
13
+ * id?: number,
14
+ * unknown?: boolean,
15
+ * header?: string,
16
+ * }} Block
17
+ */
18
+
19
+ /**
20
+ * @typedef {{
21
+ * beforeLines: string[],
22
+ * afterLines: string[],
23
+ * partial: string | null,
24
+ * blocks: Block[],
25
+ * pendingA: number,
26
+ * streaming: boolean,
27
+ * beforeNoEol: boolean,
28
+ * afterNoEol: boolean,
29
+ * sealedBlocks: number,
30
+ * version: number,
31
+ * }} DiffState
32
+ */
33
+
34
+ // Past this many edits in one region, Myers gives up and replaces the region.
35
+ const MAX_COST = 2000;
36
+ // An equal run at least this long seals everything before it while streaming.
37
+ const SEAL_RUN = 3;
38
+
39
+ /**
40
+ * Splits text into lines without the trailing empty line a final "\n" makes.
41
+ * @param {string} text
42
+ * @returns {{ lines: string[], noEol: boolean }}
43
+ */
44
+ export function splitText(text) {
45
+ if (text === "") return { lines: [], noEol: false };
46
+ const lines = text.split("\n");
47
+ const noEol = lines[lines.length - 1] !== "";
48
+ if (!noEol) lines.pop();
49
+ return { lines, noEol };
50
+ }
51
+
52
+ /**
53
+ * Maps each line to a small integer id, so comparisons are O(1).
54
+ * @param {string[][]} sides
55
+ * @param {(line: string) => string} key
56
+ * @returns {Int32Array[]}
57
+ */
58
+ function intern(sides, key) {
59
+ /** @type {Map<string, number>} */
60
+ const ids = new Map();
61
+ return sides.map((lines) => {
62
+ const out = new Int32Array(lines.length);
63
+ for (let i = 0; i < lines.length; i++) {
64
+ const k = key(/** @type {string} */ (lines[i]));
65
+ let id = ids.get(k);
66
+ if (id === undefined) {
67
+ id = ids.size;
68
+ ids.set(k, id);
69
+ }
70
+ out[i] = id;
71
+ }
72
+ return out;
73
+ });
74
+ }
75
+
76
+ const WHITESPACE_RE = /\s+/g;
77
+
78
+ /** @param {boolean} ignoreWhitespace */
79
+ function lineKey(ignoreWhitespace) {
80
+ return ignoreWhitespace
81
+ ? (/** @type {string} */ line) => line.replace(WHITESPACE_RE, " ").trim()
82
+ : (/** @type {string} */ line) => line;
83
+ }
84
+
85
+ /**
86
+ * Appends a run, merging it into the previous run of the same type.
87
+ * @param {Block[]} out
88
+ * @param {"equal" | "change"} type
89
+ * @param {number} a
90
+ * @param {number} aEnd
91
+ * @param {number} b
92
+ * @param {number} bEnd
93
+ */
94
+ function pushRun(out, type, a, aEnd, b, bEnd) {
95
+ if (a === aEnd && b === bEnd) return;
96
+ const last = out[out.length - 1];
97
+ if (last && last.type === type && last.aEnd === a && last.bEnd === b) {
98
+ last.aEnd = aEnd;
99
+ last.bEnd = bEnd;
100
+ return;
101
+ }
102
+ out.push({ type, a, aEnd, b, bEnd });
103
+ }
104
+
105
+ /**
106
+ * Myers O(ND). With `prefix`, stops once all of `b` is consumed, so trailing
107
+ * lines of `a` cost nothing (they stay "pending"). Returns the end of the
108
+ * consumed `a` range.
109
+ * @param {Int32Array} a
110
+ * @param {number} aLo
111
+ * @param {number} aHi
112
+ * @param {Int32Array} b
113
+ * @param {number} bLo
114
+ * @param {number} bHi
115
+ * @param {Block[]} out
116
+ * @param {boolean} prefix
117
+ * @returns {number}
118
+ */
119
+ function myers(a, aLo, aHi, b, bLo, bHi, out, prefix) {
120
+ const n = aHi - aLo;
121
+ const m = bHi - bLo;
122
+ const max = Math.min(n + m, MAX_COST);
123
+ const offset = max + 1;
124
+ // -1 marks a diagonal with no in-bounds point yet.
125
+ const v = new Int32Array(2 * max + 3).fill(-1);
126
+ v[offset + 1] = 0;
127
+ /** @type {Int32Array[]} */
128
+ const trace = [];
129
+ let endX = -1;
130
+ let endY = -1;
131
+
132
+ /**
133
+ * Furthest in-bounds x on diagonal `k`, and whether it came from `k + 1`.
134
+ * @param {(k: number) => number} at
135
+ * @param {number} k
136
+ * @returns {[number, boolean]}
137
+ */
138
+ const pick = (at, k) => {
139
+ let down = at(k + 1);
140
+ if (down >= 0 && down - k > m) down = -1;
141
+ let right = at(k - 1);
142
+ right = right >= 0 && right + 1 <= n ? right + 1 : -1;
143
+ return down >= right ? [down, true] : [right, false];
144
+ };
145
+ const fromV = (/** @type {number} */ k) =>
146
+ /** @type {number} */ (v[offset + k]);
147
+
148
+ outer: for (let d = 0; d <= max; d++) {
149
+ // Only k in [-d-1, d+1] is read while backtracking from step d.
150
+ trace.push(v.slice(offset - d - 1, offset + d + 2));
151
+ for (let k = -d; k <= d; k += 2) {
152
+ let [x] = pick(fromV, k);
153
+ if (x < 0) {
154
+ v[offset + k] = -1;
155
+ continue;
156
+ }
157
+ let y = x - k;
158
+ while (x < n && y < m && a[aLo + x] === b[bLo + y]) {
159
+ x++;
160
+ y++;
161
+ }
162
+ v[offset + k] = x;
163
+ if (y === m && (prefix || x === n)) {
164
+ endX = x;
165
+ endY = y;
166
+ break outer;
167
+ }
168
+ }
169
+ }
170
+
171
+ if (endX < 0) {
172
+ // Too many edits: treat the region as one replacement.
173
+ if (prefix) {
174
+ pushRun(out, "change", aLo, aLo, bLo, bHi);
175
+ return aLo;
176
+ }
177
+ pushRun(out, "change", aLo, aHi, bLo, bHi);
178
+ return aHi;
179
+ }
180
+
181
+ /** @type {Array<[number, number, number, number, "equal" | "change"]>} */
182
+ const reversed = [];
183
+ let x = endX;
184
+ let y = endY;
185
+ for (let d = trace.length - 1; d >= 0; d--) {
186
+ const t = /** @type {Int32Array} */ (trace[d]);
187
+ const k = x - y;
188
+ if (d === 0) {
189
+ if (x > 0) reversed.push([0, x, 0, y, "equal"]);
190
+ break;
191
+ }
192
+ const [, fromDown] = pick(
193
+ (kk) => /** @type {number} */ (t[kk + d + 1] ?? -1),
194
+ k,
195
+ );
196
+ const prevK = fromDown ? k + 1 : k - 1;
197
+ const prevX = /** @type {number} */ (t[prevK + d + 1]);
198
+ const prevY = prevX - prevK;
199
+ const snakeX = fromDown ? prevX : prevX + 1;
200
+ const snakeY = snakeX - k;
201
+ if (x > snakeX) reversed.push([snakeX, x, snakeY, y, "equal"]);
202
+ reversed.push([prevX, snakeX, prevY, snakeY, "change"]);
203
+ x = prevX;
204
+ y = prevY;
205
+ }
206
+ for (let i = reversed.length - 1; i >= 0; i--) {
207
+ const [x0, x1, y0, y1, type] = /** @type {any} */ (reversed[i]);
208
+ pushRun(out, type, aLo + x0, aLo + x1, bLo + y0, bLo + y1);
209
+ }
210
+ return aLo + endX;
211
+ }
212
+
213
+ /**
214
+ * Lines unique to both ranges, as an increasing (a, b) chain (patience).
215
+ * @param {Int32Array} a
216
+ * @param {number} aLo
217
+ * @param {number} aHi
218
+ * @param {Int32Array} b
219
+ * @param {number} bLo
220
+ * @param {number} bHi
221
+ * @returns {Array<[number, number]>}
222
+ */
223
+ function uniqueAnchors(a, aLo, aHi, b, bLo, bHi) {
224
+ /** @type {Map<number, number>} id -> index in a, or -1 if repeated */
225
+ const inA = new Map();
226
+ for (let i = aLo; i < aHi; i++) {
227
+ const id = /** @type {number} */ (a[i]);
228
+ inA.set(id, inA.has(id) ? -1 : i);
229
+ }
230
+ /** @type {Map<number, number>} */
231
+ const inB = new Map();
232
+ for (let j = bLo; j < bHi; j++) {
233
+ const id = /** @type {number} */ (b[j]);
234
+ if (!inA.has(id) || inA.get(id) === -1) continue;
235
+ inB.set(id, inB.has(id) ? -1 : j);
236
+ }
237
+ /** @type {Array<[number, number]>} */
238
+ const pairs = [];
239
+ for (const [id, j] of inB) {
240
+ if (j === -1) continue;
241
+ pairs.push([/** @type {number} */ (inA.get(id)), j]);
242
+ }
243
+ if (pairs.length === 0) return pairs;
244
+ pairs.sort((p, q) => p[0] - q[0]);
245
+
246
+ // Longest increasing subsequence on b, via patience sorting.
247
+ /** @type {number[]} */
248
+ const tails = [];
249
+ const prev = new Int32Array(pairs.length).fill(-1);
250
+ for (let i = 0; i < pairs.length; i++) {
251
+ const bj = /** @type {[number, number]} */ (pairs[i])[1];
252
+ let lo = 0;
253
+ let hi = tails.length;
254
+ while (lo < hi) {
255
+ const mid = (lo + hi) >> 1;
256
+ const t = /** @type {[number, number]} */ (
257
+ pairs[/** @type {number} */ (tails[mid])]
258
+ );
259
+ if (t[1] < bj) lo = mid + 1;
260
+ else hi = mid;
261
+ }
262
+ if (lo > 0) prev[i] = /** @type {number} */ (tails[lo - 1]);
263
+ tails[lo] = i;
264
+ }
265
+ /** @type {Array<[number, number]>} */
266
+ const chain = [];
267
+ for (
268
+ let i = /** @type {number} */ (tails[tails.length - 1]);
269
+ i !== -1;
270
+ i = /** @type {number} */ (prev[i])
271
+ ) {
272
+ chain.push(/** @type {[number, number]} */ (pairs[i]));
273
+ }
274
+ return chain.reverse();
275
+ }
276
+
277
+ /**
278
+ * @param {Int32Array} a
279
+ * @param {number} aStart
280
+ * @param {number} aHi
281
+ * @param {Int32Array} b
282
+ * @param {number} bStart
283
+ * @param {number} bHi
284
+ * @param {Block[]} out
285
+ */
286
+ function diffRange(a, aStart, aHi, b, bStart, bHi, out) {
287
+ let aLo = aStart;
288
+ let bLo = bStart;
289
+ while (aLo < aHi && bLo < bHi && a[aLo] === b[bLo]) {
290
+ pushRun(out, "equal", aLo, aLo + 1, bLo, bLo + 1);
291
+ aLo++;
292
+ bLo++;
293
+ }
294
+ let suffix = 0;
295
+ while (
296
+ aHi - suffix > aLo &&
297
+ bHi - suffix > bLo &&
298
+ a[aHi - suffix - 1] === b[bHi - suffix - 1]
299
+ ) {
300
+ suffix++;
301
+ }
302
+ const aMid = aHi - suffix;
303
+ const bMid = bHi - suffix;
304
+
305
+ if (aLo === aMid || bLo === bMid) {
306
+ pushRun(out, "change", aLo, aMid, bLo, bMid);
307
+ } else {
308
+ const anchors = uniqueAnchors(a, aLo, aMid, b, bLo, bMid);
309
+ if (anchors.length === 0) {
310
+ myers(a, aLo, aMid, b, bLo, bMid, out, false);
311
+ } else {
312
+ let pa = aLo;
313
+ let pb = bLo;
314
+ for (const [ai, bi] of anchors) {
315
+ diffRange(a, pa, ai, b, pb, bi, out);
316
+ pushRun(out, "equal", ai, ai + 1, bi, bi + 1);
317
+ pa = ai + 1;
318
+ pb = bi + 1;
319
+ }
320
+ diffRange(a, pa, aMid, b, pb, bMid, out);
321
+ }
322
+ }
323
+ if (suffix > 0) pushRun(out, "equal", aMid, aHi, bMid, bHi);
324
+ }
325
+
326
+ /**
327
+ * Line diff of two line arrays.
328
+ * @param {string[]} before
329
+ * @param {string[]} after
330
+ * @param {{ ignoreWhitespace?: boolean }} [options]
331
+ * @returns {Block[]}
332
+ */
333
+ export function diffLines(before, after, { ignoreWhitespace = false } = {}) {
334
+ const [a, b] = /** @type {[Int32Array, Int32Array]} */ (
335
+ intern([before, after], lineKey(ignoreWhitespace))
336
+ );
337
+ /** @type {Block[]} */
338
+ const out = [];
339
+ diffRange(a, 0, a.length, b, 0, b.length, out);
340
+ return out;
341
+ }
342
+
343
+ /**
344
+ * Diffs `before` against a prefix of `after` that is still growing: the end
345
+ * of `before` that `after` hasn't reached yet is left out ("pending").
346
+ * @param {Int32Array} a
347
+ * @param {number} aLo
348
+ * @param {Int32Array} b
349
+ * @param {number} bLo
350
+ * @param {Block[]} out
351
+ * @returns {number} where the pending part of `before` starts
352
+ */
353
+ function diffPrefix(a, aLo, b, bLo, out) {
354
+ let aI = aLo;
355
+ let bI = bLo;
356
+ while (aI < a.length && bI < b.length && a[aI] === b[bI]) {
357
+ aI++;
358
+ bI++;
359
+ }
360
+ pushRun(out, "equal", aLo, aI, bLo, bI);
361
+ if (bI === b.length) return aI;
362
+ // Bound the lookahead so a stray "}" can't match 5,000 lines ahead.
363
+ const window = Math.min(a.length, aI + (b.length - bI) * 4 + 200);
364
+ return myers(a, aI, window, b, bI, b.length, out, true);
365
+ }
366
+
367
+ /**
368
+ * Stateful diff that reuses work when `after` only grows: the split and
369
+ * interned lines of both sides are kept, so a streamed chunk only splits
370
+ * and interns its own new lines, and only the part past the last sealed
371
+ * anchor is re-diffed. While streaming, `afterLines` grows in place.
372
+ * @param {{ ignoreWhitespace?: boolean }} [options]
373
+ */
374
+ export function createDiffSession({ ignoreWhitespace = false } = {}) {
375
+ const key = lineKey(ignoreWhitespace);
376
+
377
+ let before = "";
378
+ let after = "";
379
+ let wasStreaming = false;
380
+ /** @type {Block[]} */
381
+ let sealed = [];
382
+ let sealA = 0;
383
+ let sealB = 0;
384
+ let version = 0;
385
+
386
+ /** @type {Map<string, number>} line key -> id, shared by both sides */
387
+ let ids = new Map();
388
+ /** @type {{ lines: string[], noEol: boolean, ids: Int32Array }} */
389
+ let b4 = { lines: [], noEol: false, ids: new Int32Array(0) };
390
+
391
+ // Streaming `after`: complete lines and their ids, up to `afterCut`.
392
+ /** @type {string[]} */
393
+ let afterLines = [];
394
+ let afterIds = new Int32Array(64);
395
+ let afterCount = 0;
396
+ let afterCut = 0;
397
+
398
+ /** @type {DiffState | null} */
399
+ let last = null;
400
+
401
+ /** @param {string} line */
402
+ function idOf(line) {
403
+ const k = key(line);
404
+ let id = ids.get(k);
405
+ if (id === undefined) {
406
+ id = ids.size;
407
+ ids.set(k, id);
408
+ }
409
+ return id;
410
+ }
411
+
412
+ /** @param {string} text */
413
+ function setBefore(text) {
414
+ ids = new Map();
415
+ const { lines, noEol } = splitText(text);
416
+ const out = new Int32Array(lines.length);
417
+ for (let i = 0; i < lines.length; i++) {
418
+ out[i] = idOf(/** @type {string} */ (lines[i]));
419
+ }
420
+ b4 = { lines, noEol, ids: out };
421
+ }
422
+
423
+ function resetAfter() {
424
+ afterLines = [];
425
+ afterCount = 0;
426
+ afterCut = 0;
427
+ }
428
+
429
+ /** Splits and interns the complete lines of `text` past `afterCut`. */
430
+ function growAfter(/** @type {string} */ text) {
431
+ const cut = text.lastIndexOf("\n");
432
+ if (cut < afterCut) return;
433
+ const fresh = text.slice(afterCut, cut).split("\n");
434
+ if (afterCount + fresh.length > afterIds.length) {
435
+ const grown = new Int32Array(
436
+ Math.max(afterIds.length * 2, afterCount + fresh.length),
437
+ );
438
+ grown.set(afterIds.subarray(0, afterCount));
439
+ afterIds = grown;
440
+ }
441
+ for (const line of fresh) {
442
+ afterLines.push(line);
443
+ afterIds[afterCount++] = idOf(line);
444
+ }
445
+ afterCut = cut + 1;
446
+ }
447
+
448
+ /**
449
+ * @param {string} beforeText
450
+ * @param {string} afterText
451
+ * @param {{ streaming?: boolean }} [options]
452
+ * @returns {DiffState}
453
+ */
454
+ function update(beforeText, afterText, { streaming = false } = {}) {
455
+ if (
456
+ last &&
457
+ beforeText === before &&
458
+ afterText === after &&
459
+ streaming === wasStreaming
460
+ ) {
461
+ return last;
462
+ }
463
+ const beforeChanged = last === null || beforeText !== before;
464
+ const continues =
465
+ wasStreaming && !beforeChanged && afterText.startsWith(after);
466
+ const afterEndsOpen = afterText !== "" && !afterText.endsWith("\n");
467
+ const grows = streaming && continues;
468
+ // Ending a stream keeps the sealed rows, so nothing the reader saw
469
+ // reshuffles, unless a final-newline mismatch would change a sealed line.
470
+ const finishing = !streaming && continues && b4.noEol === afterEndsOpen;
471
+ if (beforeChanged) setBefore(beforeText);
472
+ if (!grows && !finishing) {
473
+ sealed = [];
474
+ sealA = 0;
475
+ sealB = 0;
476
+ resetAfter();
477
+ }
478
+ before = beforeText;
479
+ after = afterText;
480
+ wasStreaming = streaming;
481
+
482
+ /** @type {string[]} */
483
+ let lines;
484
+ /** @type {Int32Array} */
485
+ let a = b4.ids;
486
+ /** @type {Int32Array} */
487
+ let b;
488
+ /** @type {string | null} */
489
+ let partial = null;
490
+ let afterNoEol = false;
491
+ if (streaming) {
492
+ growAfter(afterText);
493
+ lines = afterLines;
494
+ b = afterIds.subarray(0, afterCount);
495
+ const rest = afterText.slice(afterCut);
496
+ partial = rest === "" ? null : rest;
497
+ } else if (finishing) {
498
+ // The last line counts too, even without a final newline.
499
+ growAfter(afterEndsOpen ? `${afterText}\n` : afterText);
500
+ lines = afterLines;
501
+ afterNoEol = afterEndsOpen;
502
+ b = afterIds.subarray(0, afterCount);
503
+ } else {
504
+ const split = splitText(afterText);
505
+ lines = split.lines;
506
+ afterNoEol = split.noEol;
507
+ b = new Int32Array(lines.length);
508
+ for (let i = 0; i < lines.length; i++) {
509
+ b[i] = idOf(/** @type {string} */ (lines[i]));
510
+ }
511
+ // A missing final newline on one side only counts as a change.
512
+ if (b4.noEol !== afterNoEol) {
513
+ if (b4.noEol && a.length > 0) {
514
+ a = a.slice();
515
+ a[a.length - 1] = -1;
516
+ }
517
+ if (afterNoEol && b.length > 0) b[b.length - 1] = -2;
518
+ }
519
+ }
520
+
521
+ /** @type {Block[]} */
522
+ const tail = [];
523
+ let pendingA = b4.lines.length;
524
+ if (streaming) {
525
+ pendingA = diffPrefix(a, sealA, b, sealB, tail);
526
+ } else {
527
+ diffRange(a, sealA, a.length, b, sealB, b.length, tail);
528
+ }
529
+
530
+ const blocks = sealed.slice();
531
+ for (const block of tail) {
532
+ const prev = blocks[blocks.length - 1];
533
+ if (
534
+ prev &&
535
+ prev.type === block.type &&
536
+ prev.aEnd === block.a &&
537
+ prev.bEnd === block.b
538
+ ) {
539
+ blocks[blocks.length - 1] = {
540
+ ...prev,
541
+ aEnd: block.aEnd,
542
+ bEnd: block.bEnd,
543
+ };
544
+ } else {
545
+ blocks.push({ ...block });
546
+ }
547
+ }
548
+ // Positional ids, so a change keeps its id across streamed updates.
549
+ let id = 0;
550
+ for (const block of blocks) {
551
+ if (block.type === "change") block.id = id++;
552
+ }
553
+
554
+ if (streaming) {
555
+ // Seal through the last long equal run; later chunks only diff past it.
556
+ for (let i = blocks.length - 1; i >= 0; i--) {
557
+ const block = /** @type {Block} */ (blocks[i]);
558
+ if (block.type === "equal" && block.aEnd - block.a >= SEAL_RUN) {
559
+ sealed = blocks.slice(0, i + 1).map((x) => ({ ...x }));
560
+ sealA = block.aEnd;
561
+ sealB = block.bEnd;
562
+ break;
563
+ }
564
+ }
565
+ }
566
+
567
+ version++;
568
+ last = {
569
+ beforeLines: b4.lines,
570
+ afterLines: lines,
571
+ partial,
572
+ blocks,
573
+ pendingA,
574
+ streaming,
575
+ beforeNoEol: b4.noEol,
576
+ afterNoEol,
577
+ sealedBlocks: streaming ? sealed.length : blocks.length,
578
+ version,
579
+ };
580
+ return last;
581
+ }
582
+
583
+ return { update };
584
+ }
585
+
586
+ /**
587
+ * One-shot diff of two texts.
588
+ * @param {string} before
589
+ * @param {string} after
590
+ * @param {{ ignoreWhitespace?: boolean }} [options]
591
+ * @returns {DiffState}
592
+ */
593
+ export function diffTexts(before, after, options) {
594
+ return createDiffSession(options).update(before, after);
595
+ }
596
+
597
+ /**
598
+ * @typedef {{
599
+ * key: string,
600
+ * kind: "context" | "del" | "add" | "change" | "fold" | "pending" | "incoming",
601
+ * old?: number,
602
+ * new?: number,
603
+ * change?: number,
604
+ * pairOld?: number,
605
+ * pairNew?: number,
606
+ * moved?: number,
607
+ * movedTo?: number,
608
+ * movedFrom?: number,
609
+ * first?: boolean,
610
+ * fold?: { a: number, aEnd: number, b: number, bEnd: number, unknown: boolean, header: string },
611
+ * count?: number,
612
+ * }} Row
613
+ */
614
+
615
+ /**
616
+ * Unified or split rows, with unchanged runs past `context` folded unless
617
+ * their key is in `expanded`.
618
+ * @param {DiffState} state
619
+ * @param {{
620
+ * view?: "unified" | "split",
621
+ * context?: number,
622
+ * expanded?: Set<string>,
623
+ * moves?: Map<number, { group: number, to?: number, from?: number }>,
624
+ * movesNew?: Map<number, { group: number, to?: number, from?: number }>,
625
+ * }} [options]
626
+ * @returns {Row[]}
627
+ */
628
+ export function buildRows(
629
+ state,
630
+ {
631
+ view = "unified",
632
+ context = 3,
633
+ expanded = new Set(),
634
+ moves = new Map(),
635
+ movesNew = new Map(),
636
+ } = {},
637
+ ) {
638
+ /** @type {Row[]} */
639
+ const rows = [];
640
+ const { blocks } = state;
641
+ const hasChanges =
642
+ blocks.some((b) => b.type === "change") || state.partial !== null;
643
+
644
+ /** @param {number} a @param {number} b */
645
+ const pushContext = (a, b) =>
646
+ rows.push({ key: `c${a}:${b}`, kind: "context", old: a, new: b });
647
+
648
+ for (let bi = 0; bi < blocks.length; bi++) {
649
+ const block = /** @type {Block} */ (blocks[bi]);
650
+ if (block.type === "change") {
651
+ const dels = block.aEnd - block.a;
652
+ const adds = block.bEnd - block.b;
653
+ const id = /** @type {number} */ (block.id);
654
+ if (view === "split") {
655
+ const n = Math.max(dels, adds);
656
+ for (let i = 0; i < n; i++) {
657
+ /** @type {Row} */
658
+ const row = {
659
+ key: `x${id}:${i}`,
660
+ kind: "change",
661
+ change: id,
662
+ first: i === 0,
663
+ };
664
+ if (i < dels) row.old = block.a + i;
665
+ if (i < adds) row.new = block.b + i;
666
+ const mo = row.old === undefined ? undefined : moves.get(row.old);
667
+ const mn = row.new === undefined ? undefined : movesNew.get(row.new);
668
+ if (mo) {
669
+ row.moved = mo.group;
670
+ if (mo.to !== undefined) row.movedTo = mo.to;
671
+ }
672
+ if (mn) {
673
+ row.moved = mn.group;
674
+ if (mn.from !== undefined) row.movedFrom = mn.from;
675
+ }
676
+ rows.push(row);
677
+ }
678
+ } else {
679
+ for (let i = 0; i < dels; i++) {
680
+ /** @type {Row} */
681
+ const row = {
682
+ key: `d${block.a + i}`,
683
+ kind: "del",
684
+ old: block.a + i,
685
+ change: id,
686
+ first: i === 0,
687
+ };
688
+ if (i < adds) row.pairNew = block.b + i;
689
+ const mo = moves.get(block.a + i);
690
+ if (mo) {
691
+ row.moved = mo.group;
692
+ if (mo.to !== undefined) row.movedTo = mo.to;
693
+ }
694
+ rows.push(row);
695
+ }
696
+ for (let i = 0; i < adds; i++) {
697
+ /** @type {Row} */
698
+ const row = {
699
+ key: `a${block.b + i}`,
700
+ kind: "add",
701
+ new: block.b + i,
702
+ change: id,
703
+ first: dels === 0 && i === 0,
704
+ };
705
+ if (i < dels) row.pairOld = block.a + i;
706
+ const mn = movesNew.get(block.b + i);
707
+ if (mn) {
708
+ row.moved = mn.group;
709
+ if (mn.from !== undefined) row.movedFrom = mn.from;
710
+ }
711
+ rows.push(row);
712
+ }
713
+ }
714
+ continue;
715
+ }
716
+
717
+ const n = block.aEnd - block.a;
718
+ const foldKey = `f${block.a}:${block.b}`;
719
+ const isFirst = bi === 0;
720
+ const isLast = bi === blocks.length - 1 && state.partial === null;
721
+ if (block.unknown) {
722
+ rows.push({
723
+ key: foldKey,
724
+ kind: "fold",
725
+ fold: {
726
+ a: block.a,
727
+ aEnd: block.aEnd,
728
+ b: block.b,
729
+ bEnd: block.bEnd,
730
+ unknown: true,
731
+ header: block.header ?? hunkHeader(blocks, bi + 1),
732
+ },
733
+ count: Math.max(n, block.bEnd - block.b),
734
+ });
735
+ continue;
736
+ }
737
+ const lead = isFirst ? 0 : context;
738
+ const trail = isLast && !state.streaming ? 0 : context;
739
+ if (!hasChanges || expanded.has(foldKey) || n <= lead + trail + 1) {
740
+ if (!hasChanges && !expanded.has(foldKey) && n > 0) {
741
+ rows.push({
742
+ key: foldKey,
743
+ kind: "fold",
744
+ fold: {
745
+ a: block.a,
746
+ aEnd: block.aEnd,
747
+ b: block.b,
748
+ bEnd: block.bEnd,
749
+ unknown: false,
750
+ header: "",
751
+ },
752
+ count: n,
753
+ });
754
+ continue;
755
+ }
756
+ for (let i = 0; i < n; i++) pushContext(block.a + i, block.b + i);
757
+ continue;
758
+ }
759
+ for (let i = 0; i < lead; i++) pushContext(block.a + i, block.b + i);
760
+ const hidden = n - lead - trail;
761
+ rows.push({
762
+ key: foldKey,
763
+ kind: "fold",
764
+ fold: {
765
+ a: block.a + lead,
766
+ aEnd: block.aEnd - trail,
767
+ b: block.b + lead,
768
+ bEnd: block.bEnd - trail,
769
+ unknown: false,
770
+ header: isLast ? "" : hunkHeader(blocks, bi + 1, context),
771
+ },
772
+ count: hidden,
773
+ });
774
+ for (let i = n - trail; i < n; i++) pushContext(block.a + i, block.b + i);
775
+ }
776
+
777
+ if (state.partial !== null) {
778
+ rows.push({
779
+ key: `i${state.afterLines.length}`,
780
+ kind: "incoming",
781
+ new: state.afterLines.length,
782
+ });
783
+ }
784
+ if (state.streaming && state.pendingA < state.beforeLines.length) {
785
+ rows.push({
786
+ key: "pending",
787
+ kind: "pending",
788
+ old: state.pendingA,
789
+ count: state.beforeLines.length - state.pendingA,
790
+ });
791
+ }
792
+ return rows;
793
+ }
794
+
795
+ /**
796
+ * `@@ -a,n +b,m @@` for the hunk that starts at block `from`.
797
+ * @param {Block[]} blocks
798
+ * @param {number} from
799
+ * @param {number} [context]
800
+ */
801
+ function hunkHeader(blocks, from, context = 3) {
802
+ const start = blocks[from];
803
+ if (!start) return "";
804
+ let a0 = start.a;
805
+ let b0 = start.b;
806
+ let a1 = start.aEnd;
807
+ let b1 = start.bEnd;
808
+ // Extend through changes separated by short equal runs, then take the
809
+ // trailing context.
810
+ for (let i = from + 1; i < blocks.length; i++) {
811
+ const block = /** @type {Block} */ (blocks[i]);
812
+ const n = block.aEnd - block.a;
813
+ if (
814
+ block.type === "equal" &&
815
+ (n > context * 2 || i === blocks.length - 1)
816
+ ) {
817
+ const take = Math.min(n, context);
818
+ a1 = block.a + take;
819
+ b1 = block.b + take;
820
+ break;
821
+ }
822
+ a1 = block.aEnd;
823
+ b1 = block.bEnd;
824
+ }
825
+ a0 = Math.max(0, a0 - context);
826
+ b0 = Math.max(0, b0 - context);
827
+ return `@@ -${hunkRange(a0, a1 - a0)} +${hunkRange(b0, b1 - b0)} @@`;
828
+ }
829
+
830
+ /**
831
+ * Lines removed in one change and added in another, in runs of at least
832
+ * `minLines`, ignoring indentation.
833
+ * @param {DiffState} state
834
+ * @param {{ minLines?: number }} [options]
835
+ */
836
+ export function detectMoves(state, { minLines = 3 } = {}) {
837
+ /** @type {Map<number, { group: number, to?: number, from?: number }>} */
838
+ const oldMoves = new Map();
839
+ /** @type {Map<number, { group: number, to?: number, from?: number }>} */
840
+ const newMoves = new Map();
841
+ /** @type {Map<string, number[]>} */
842
+ const addsByKey = new Map();
843
+ /** @type {Map<number, number>} new index -> change id */
844
+ const addChange = new Map();
845
+ /** @type {Map<number, number>} old index -> change id */
846
+ const delChange = new Map();
847
+ const moveKey = (/** @type {string} */ line) => line.trim();
848
+ const trivial = (/** @type {string} */ k) =>
849
+ k.replace(/[\s{}()[\];,]/g, "").length < 3;
850
+
851
+ for (const block of state.blocks) {
852
+ if (block.type !== "change") continue;
853
+ for (let j = block.b; j < block.bEnd; j++) {
854
+ addChange.set(j, /** @type {number} */ (block.id));
855
+ const k = moveKey(/** @type {string} */ (state.afterLines[j]));
856
+ if (trivial(k)) continue;
857
+ const list = addsByKey.get(k);
858
+ if (list) list.push(j);
859
+ else addsByKey.set(k, [j]);
860
+ }
861
+ for (let i = block.a; i < block.aEnd; i++) {
862
+ delChange.set(i, /** @type {number} */ (block.id));
863
+ }
864
+ }
865
+
866
+ let group = 0;
867
+ for (const block of state.blocks) {
868
+ if (block.type !== "change") continue;
869
+ let i = block.a;
870
+ while (i < block.aEnd) {
871
+ if (oldMoves.has(i)) {
872
+ i++;
873
+ continue;
874
+ }
875
+ const k = moveKey(/** @type {string} */ (state.beforeLines[i]));
876
+ let best = 0;
877
+ let bestJ = -1;
878
+ for (const j of addsByKey.get(k) ?? []) {
879
+ if (addChange.get(j) === block.id || newMoves.has(j)) continue;
880
+ let len = 0;
881
+ while (
882
+ i + len < block.aEnd &&
883
+ addChange.has(j + len) &&
884
+ !newMoves.has(j + len) &&
885
+ moveKey(/** @type {string} */ (state.beforeLines[i + len])) ===
886
+ moveKey(/** @type {string} */ (state.afterLines[j + len]))
887
+ ) {
888
+ len++;
889
+ }
890
+ if (len > best) {
891
+ best = len;
892
+ bestJ = j;
893
+ }
894
+ }
895
+ if (best >= minLines) {
896
+ for (let t = 0; t < best; t++) {
897
+ oldMoves.set(i + t, { group, to: bestJ + t });
898
+ newMoves.set(bestJ + t, { group, from: i + t });
899
+ }
900
+ group++;
901
+ i += best;
902
+ } else {
903
+ i++;
904
+ }
905
+ }
906
+ }
907
+ return { oldMoves, newMoves, groups: group };
908
+ }
909
+
910
+ const BLANK_RE = /^\s*$/;
911
+ const WORD_RE = /[\p{L}\p{N}_]+|\s+|[^\p{L}\p{N}_\s]/gu;
912
+
913
+ /**
914
+ * Character ranges that differ between two lines, by word tokens.
915
+ * Returns empty ranges when the lines share too little to be worth it.
916
+ * @param {string} oldText
917
+ * @param {string} newText
918
+ * @returns {{ old: Array<[number, number]>, new: Array<[number, number]>, similarity: number }}
919
+ */
920
+ export function wordDiff(oldText, newText) {
921
+ const ta = oldText.match(WORD_RE) ?? [];
922
+ const tb = newText.match(WORD_RE) ?? [];
923
+ if (ta.length + tb.length > 1200) {
924
+ return { old: [], new: [], similarity: 0 };
925
+ }
926
+ const [a, b] = /** @type {[Int32Array, Int32Array]} */ (
927
+ intern([ta, tb], (t) => t)
928
+ );
929
+ /** @type {Block[]} */
930
+ const ops = [];
931
+ diffRange(a, 0, a.length, b, 0, b.length, ops);
932
+
933
+ const offsets = (/** @type {string[]} */ tokens) => {
934
+ const out = new Int32Array(tokens.length + 1);
935
+ for (let i = 0; i < tokens.length; i++) {
936
+ out[i + 1] =
937
+ /** @type {number} */ (out[i]) +
938
+ /** @type {string} */ (tokens[i]).length;
939
+ }
940
+ return out;
941
+ };
942
+ const oa = offsets(ta);
943
+ const ob = offsets(tb);
944
+
945
+ let same = 0;
946
+ /** @type {Array<[number, number]>} */
947
+ const oldRanges = [];
948
+ /** @type {Array<[number, number]>} */
949
+ const newRanges = [];
950
+ /**
951
+ * @param {Array<[number, number]>} list
952
+ * @param {number} s
953
+ * @param {number} e
954
+ * @param {string} text
955
+ */
956
+ const add = (list, s, e, text) => {
957
+ if (s === e) return;
958
+ const prev = list[list.length - 1];
959
+ // Bridge whitespace-only gaps so "a b c" reads as one change.
960
+ if (prev && BLANK_RE.test(text.slice(prev[1], s))) prev[1] = e;
961
+ else list.push([s, e]);
962
+ };
963
+ for (const op of ops) {
964
+ if (op.type === "equal") {
965
+ same +=
966
+ /** @type {number} */ (oa[op.aEnd]) - /** @type {number} */ (oa[op.a]);
967
+ continue;
968
+ }
969
+ add(
970
+ oldRanges,
971
+ /** @type {number} */ (oa[op.a]),
972
+ /** @type {number} */ (oa[op.aEnd]),
973
+ oldText,
974
+ );
975
+ add(
976
+ newRanges,
977
+ /** @type {number} */ (ob[op.b]),
978
+ /** @type {number} */ (ob[op.bEnd]),
979
+ newText,
980
+ );
981
+ }
982
+ const total = oldText.length + newText.length;
983
+ const similarity = total === 0 ? 1 : (2 * same) / total;
984
+ if (similarity < 0.35) return { old: [], new: [], similarity };
985
+ return { old: oldRanges, new: newRanges, similarity };
986
+ }
987
+
988
+ /**
989
+ * Text with each change taken from `after` unless its id is rejected.
990
+ * @param {DiffState} state
991
+ * @param {Map<number, "accepted" | "rejected">} decisions
992
+ */
993
+ export function applyReview(state, decisions) {
994
+ /** @type {string[]} */
995
+ const out = [];
996
+ for (const block of state.blocks) {
997
+ if (block.type === "equal") {
998
+ out.push(...state.afterLines.slice(block.b, block.bEnd));
999
+ } else if (decisions.get(/** @type {number} */ (block.id)) === "rejected") {
1000
+ out.push(...state.beforeLines.slice(block.a, block.aEnd));
1001
+ } else {
1002
+ out.push(...state.afterLines.slice(block.b, block.bEnd));
1003
+ }
1004
+ }
1005
+ if (state.streaming) {
1006
+ out.push(...state.beforeLines.slice(state.pendingA));
1007
+ }
1008
+ const text = out.join("\n");
1009
+ return out.length === 0 || state.afterNoEol ? text : `${text}\n`;
1010
+ }
1011
+
1012
+ /**
1013
+ * Added and removed line counts.
1014
+ * @param {DiffState} state
1015
+ */
1016
+ export function diffStats(state) {
1017
+ let additions = 0;
1018
+ let deletions = 0;
1019
+ let changes = 0;
1020
+ for (const block of state.blocks) {
1021
+ if (block.type !== "change") continue;
1022
+ additions += block.bEnd - block.b;
1023
+ deletions += block.aEnd - block.a;
1024
+ changes++;
1025
+ }
1026
+ return { additions, deletions, changes };
1027
+ }
1028
+
1029
+ /**
1030
+ * A unified patch (`git apply`-able) for the diff.
1031
+ * @param {DiffState} state
1032
+ * @param {{ oldPath?: string, newPath?: string, context?: number }} [options]
1033
+ */
1034
+ export function toUnifiedPatch(
1035
+ state,
1036
+ { oldPath = "a", newPath = "b", context = 3 } = {},
1037
+ ) {
1038
+ const { blocks, beforeLines, afterLines } = state;
1039
+ const lines = [`--- ${oldPath}`, `+++ ${newPath}`];
1040
+ const lastOld = state.beforeNoEol ? beforeLines.length - 1 : -1;
1041
+ const lastNew = state.afterNoEol ? afterLines.length - 1 : -1;
1042
+ const NoEol = "\";
1043
+ /** @type {string[]} */
1044
+ let body = [];
1045
+ /** @param {number} k */
1046
+ const context_ = (k) => {
1047
+ body.push(` ${beforeLines[k]}`);
1048
+ if (k === lastOld) body.push(NoEol);
1049
+ };
1050
+ /** @param {number} k */
1051
+ const removed = (k) => {
1052
+ body.push(`-${beforeLines[k]}`);
1053
+ if (k === lastOld) body.push(NoEol);
1054
+ };
1055
+ /** @param {number} k */
1056
+ const added = (k) => {
1057
+ body.push(`+${afterLines[k]}`);
1058
+ if (k === lastNew) body.push(NoEol);
1059
+ };
1060
+
1061
+ let i = 0;
1062
+ while (i < blocks.length) {
1063
+ while (i < blocks.length && blocks[i]?.type === "equal") i++;
1064
+ if (i >= blocks.length) break;
1065
+ const first = /** @type {Block} */ (blocks[i]);
1066
+ const a0 = Math.max(0, first.a - context);
1067
+ const b0 = Math.max(0, first.b - context);
1068
+ body = [];
1069
+ for (let k = a0; k < first.a; k++) context_(k);
1070
+ let end = i;
1071
+ let a1 = first.a;
1072
+ let b1 = first.b;
1073
+ for (let j = i; j < blocks.length; j++) {
1074
+ const block = /** @type {Block} */ (blocks[j]);
1075
+ if (block.type === "equal") {
1076
+ const n = block.aEnd - block.a;
1077
+ const isLast = j === blocks.length - 1;
1078
+ if (n > context * 2 || isLast) {
1079
+ const take = Math.min(n, context);
1080
+ for (let k = 0; k < take; k++) context_(block.a + k);
1081
+ a1 = block.a + take;
1082
+ b1 = block.b + take;
1083
+ end = j;
1084
+ break;
1085
+ }
1086
+ for (let k = block.a; k < block.aEnd; k++) context_(k);
1087
+ } else {
1088
+ for (let k = block.a; k < block.aEnd; k++) removed(k);
1089
+ for (let k = block.b; k < block.bEnd; k++) added(k);
1090
+ }
1091
+ a1 = block.aEnd;
1092
+ b1 = block.bEnd;
1093
+ end = j + 1;
1094
+ }
1095
+ lines.push(
1096
+ `@@ -${hunkRange(a0, a1 - a0)} +${hunkRange(b0, b1 - b0)} @@`,
1097
+ ...body,
1098
+ );
1099
+ i = Math.max(end, i + 1);
1100
+ }
1101
+ return `${lines.join("\n")}\n`;
1102
+ }
1103
+
1104
+ /**
1105
+ * A hunk range as git writes it: an empty range names the line before it.
1106
+ * @param {number} start 0-based
1107
+ * @param {number} count
1108
+ */
1109
+ function hunkRange(start, count) {
1110
+ return count === 0 ? `${start},0` : `${start + 1},${count}`;
1111
+ }