@myrialabs/clopen 0.4.48 → 0.4.49

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 (91) hide show
  1. package/backend/chat/message-pages.test.ts +163 -0
  2. package/backend/chat/message-pages.ts +233 -0
  3. package/backend/chat/stream-manager.ts +29 -5
  4. package/backend/database/migrations/087_create_blob_line_stats.ts +37 -0
  5. package/backend/database/migrations/index.ts +7 -0
  6. package/backend/database/queries/blob-line-stats-queries.ts +48 -0
  7. package/backend/database/queries/index.ts +2 -0
  8. package/backend/db-client/env/diff.ts +9 -33
  9. package/backend/db-client/env/env.test.ts +8 -8
  10. package/backend/db-client/env/service.ts +1 -1
  11. package/backend/files/file-watcher.ts +19 -0
  12. package/backend/git/contributors.test.ts +35 -0
  13. package/backend/git/contributors.ts +46 -0
  14. package/backend/http/static-assets.test.ts +78 -0
  15. package/backend/http/static-assets.ts +104 -0
  16. package/backend/index.ts +11 -9
  17. package/backend/preview/browser/browser-preview-service.ts +24 -6
  18. package/backend/snapshot/blob-store.ts +9 -1
  19. package/backend/snapshot/helpers.ts +3 -10
  20. package/backend/snapshot/line-stats.test.ts +80 -0
  21. package/backend/snapshot/line-stats.ts +64 -0
  22. package/backend/snapshot/snapshot-service.ts +14 -27
  23. package/backend/snapshot/turn-changes.test.ts +10 -5
  24. package/backend/snapshot/turn-changes.ts +78 -40
  25. package/backend/terminal/ptykit.ts +6 -1
  26. package/backend/utils/ws-wire.test.ts +87 -0
  27. package/backend/utils/ws-wire.ts +189 -0
  28. package/backend/utils/ws.ts +40 -38
  29. package/backend/ws/chat/stream.ts +41 -10
  30. package/backend/ws/files/read.ts +30 -0
  31. package/backend/ws/git/log.ts +52 -0
  32. package/backend/ws/messages/crud.ts +49 -0
  33. package/backend/ws/preview/index.ts +2 -0
  34. package/backend/ws/preview/watchers.ts +84 -0
  35. package/backend/ws/sessions/crud.ts +8 -12
  36. package/backend/ws/snapshot/changes.ts +5 -6
  37. package/backend/ws/terminal/tunnel.ts +2 -2
  38. package/bin/clopen.ts +36 -30
  39. package/dist/assets/addon-clipboard-wHJhZAA4.js.br +0 -0
  40. package/dist/assets/addon-clipboard-wHJhZAA4.js.gz +0 -0
  41. package/dist/assets/addon-fit-DX4qG4td.js.br +1 -0
  42. package/dist/assets/addon-fit-DX4qG4td.js.gz +0 -0
  43. package/dist/assets/addon-ligatures-DpDY8N_X.js.br +0 -0
  44. package/dist/assets/addon-ligatures-DpDY8N_X.js.gz +0 -0
  45. package/dist/assets/addon-unicode11-Bt8F3D7-.js.br +0 -0
  46. package/dist/assets/addon-unicode11-Bt8F3D7-.js.gz +0 -0
  47. package/dist/assets/addon-web-links-DIbG5aQx.js.br +0 -0
  48. package/dist/assets/addon-web-links-DIbG5aQx.js.gz +0 -0
  49. package/dist/assets/diff.worker-BoHLxmr2.js +7 -0
  50. package/dist/assets/diff.worker-BoHLxmr2.js.br +0 -0
  51. package/dist/assets/diff.worker-BoHLxmr2.js.gz +0 -0
  52. package/dist/assets/graph-layout.worker-CRFqN7ZQ.js.br +0 -0
  53. package/dist/assets/graph-layout.worker-CRFqN7ZQ.js.gz +0 -0
  54. package/dist/assets/{index-CONlwAXZ.js → index-CrVWZH_D.js} +1 -1
  55. package/dist/assets/index-CrVWZH_D.js.br +0 -0
  56. package/dist/assets/index-CrVWZH_D.js.gz +0 -0
  57. package/dist/assets/{index-DJzwt-hq.js → index-DD0-3EWg.js} +1 -1
  58. package/dist/assets/index-DD0-3EWg.js.br +0 -0
  59. package/dist/assets/index-DD0-3EWg.js.gz +0 -0
  60. package/dist/assets/{main-nBOb9YOA.js → main-D2_TmcwQ.js} +604 -604
  61. package/dist/assets/main-D2_TmcwQ.js.br +0 -0
  62. package/dist/assets/main-D2_TmcwQ.js.gz +0 -0
  63. package/dist/assets/main-Yucigcmf.css +1 -0
  64. package/dist/assets/main-Yucigcmf.css.br +0 -0
  65. package/dist/assets/main-Yucigcmf.css.gz +0 -0
  66. package/dist/assets/preview-video.worker-DcpDhCWL.js.br +0 -0
  67. package/dist/assets/preview-video.worker-DcpDhCWL.js.gz +0 -0
  68. package/dist/assets/xterm-B-qIQCd3.js.br +0 -0
  69. package/dist/assets/xterm-B-qIQCd3.js.gz +0 -0
  70. package/dist/assets/zipkit-engine-CaR0t_Uy.wasm.br +0 -0
  71. package/dist/assets/zipkit-engine-CaR0t_Uy.wasm.gz +0 -0
  72. package/dist/fonts/dm-sans.css.br +0 -0
  73. package/dist/fonts/dm-sans.css.gz +0 -0
  74. package/dist/index.html +2 -2
  75. package/dist/index.html.br +0 -0
  76. package/dist/index.html.gz +0 -0
  77. package/dist/sw.js.br +0 -0
  78. package/dist/sw.js.gz +0 -0
  79. package/package.json +2 -3
  80. package/shared/types/unified/stream.ts +11 -1
  81. package/shared/utils/diff-calculator.test.ts +178 -41
  82. package/shared/utils/diff-calculator.ts +383 -100
  83. package/shared/utils/process-supervisor.test.ts +172 -0
  84. package/shared/utils/process-supervisor.ts +251 -0
  85. package/shared/utils/ws-chunk.test.ts +33 -0
  86. package/shared/utils/ws-chunk.ts +73 -0
  87. package/shared/utils/ws-client-chunks.test.ts +45 -0
  88. package/shared/utils/ws-client.ts +43 -0
  89. package/shared/utils/ws-server.ts +17 -14
  90. package/backend/database/migrations/086_single_owner.test.ts +0 -170
  91. package/dist/assets/main-BUiUL3eZ.css +0 -1
@@ -1,7 +1,27 @@
1
1
  /**
2
2
  * Diff Calculator Utility
3
- * Calculates git-like line-level differences between file contents
4
- * Accepts Buffer for binary-safe handling — converts to string internally for line diffing.
3
+ *
4
+ * The ONE line-diff engine in Clopen. Every "+N / -M" number (checkpoint stats,
5
+ * the Changes tab, AI-change markers, Edit tool rows) and every rendered diff
6
+ * (tool diff blocks, restore and worktree conflict previews, the editor change
7
+ * gutter, the dotenv preview) comes from `matchTask` below, so no two surfaces
8
+ * can disagree about the same change.
9
+ *
10
+ * The engine is exact — it finds a longest common subsequence, i.e. a minimal
11
+ * edit script, the same numbers `git diff --stat` reports — and its cost
12
+ * follows the size of the CHANGE, not the size of the input. Each surface used
13
+ * to carry its own old×new LCS table: a 47k-line String Catalog edited by a few
14
+ * hundred lines needed 2.3 billion cells (~18 GB) on the server's only thread
15
+ * and froze every WebSocket of every user. Here the same edit is a few
16
+ * milliseconds, and memory stays linear in the input.
17
+ *
18
+ * Exact still has a worst case — no exact algorithm escapes one — so the work
19
+ * is RESUMABLE: it pauses at safe points and two drivers decide what a pause
20
+ * means. `runSliced` hands the thread back to the event loop every few
21
+ * milliseconds, which is what the server uses so a pathological diff can never
22
+ * stall a WebSocket. `runToEnd` ignores the pauses, which is what the browser's
23
+ * diff worker uses (it has its own thread to spend) and what tests use. The
24
+ * steps, and therefore the result, are identical under both.
5
25
  *
6
26
  * "Binary-safe" means binary files are not line-counted at all. Splitting a PNG
7
27
  * on newline bytes yields a line count with no meaning, and two screenshots
@@ -9,12 +29,6 @@
9
29
  * changes the number was there to describe.
10
30
  */
11
31
 
12
- export interface FileChangeStats {
13
- filesChanged: number;
14
- insertions: number;
15
- deletions: number;
16
- }
17
-
18
32
  /**
19
33
  * Whether these bytes are binary, and so cannot be counted or diffed as lines.
20
34
  * A NUL byte in the first few KB is the same heuristic git uses.
@@ -27,116 +41,398 @@ export function isBinaryBuffer(buf: Buffer): boolean {
27
41
  return false;
28
42
  }
29
43
 
44
+ // ============================================================================
45
+ // Resumable work
46
+ // ============================================================================
47
+
48
+ /** A computation that may pause: every `yield` is a point where it is safe to stop. */
49
+ export type Resumable<T> = Generator<void, T, void>;
50
+
51
+ /** Units of work (compared elements, visited diagonals) between pause points. */
52
+ const WORK_PER_PAUSE = 1 << 14;
53
+
54
+ /** How long `runSliced` may hold the thread before handing it back. */
55
+ const SLICE_MS = 8;
56
+
57
+ /** Run to completion on the current thread, ignoring every pause point. */
58
+ export function runToEnd<T>(task: Resumable<T>): T {
59
+ for (;;) {
60
+ const step = task.next();
61
+ if (step.done) return step.value;
62
+ }
63
+ }
64
+
30
65
  /**
31
- * Calculate line-level diff statistics similar to git
32
- * Compares two file snapshots and returns stats about changes
66
+ * Run cooperatively: at most ~SLICE_MS at a time, then yield to the event loop
67
+ * so sockets, timers and other requests are served in between. Rejects with the
68
+ * signal's reason once it is aborted.
33
69
  */
34
- export function calculateFileChangeStats(
35
- previousSnapshot: Record<string, Buffer>,
36
- currentSnapshot: Record<string, Buffer>
37
- ): FileChangeStats {
38
- let totalInsertions = 0;
39
- let totalDeletions = 0;
40
- const changedFiles = new Set<string>();
41
-
42
- // Check added and modified files. A binary file still counts as changed — it
43
- // just contributes no lines, because it has none.
44
- for (const [filepath, newContent] of Object.entries(currentSnapshot)) {
45
- const oldContent = previousSnapshot[filepath];
46
-
47
- if (!oldContent) {
48
- changedFiles.add(filepath);
49
- if (isBinaryBuffer(newContent)) continue;
50
- totalInsertions += countLines(newContent.toString('utf-8'));
51
- } else if (!oldContent.equals(newContent)) {
52
- changedFiles.add(filepath);
53
- if (isBinaryBuffer(newContent) || isBinaryBuffer(oldContent)) continue;
54
- const diff = calculateLineDiff(oldContent.toString('utf-8'), newContent.toString('utf-8'));
55
- totalInsertions += diff.insertions;
56
- totalDeletions += diff.deletions;
70
+ export async function runSliced<T>(task: Resumable<T>, signal?: AbortSignal): Promise<T> {
71
+ let sliceStart = performance.now();
72
+ for (;;) {
73
+ signal?.throwIfAborted();
74
+ const step = task.next();
75
+ if (step.done) return step.value;
76
+ if (performance.now() - sliceStart >= SLICE_MS) {
77
+ await yieldToEventLoop();
78
+ sliceStart = performance.now();
57
79
  }
58
80
  }
81
+ }
59
82
 
60
- // Check deleted files
61
- for (const [filepath, oldContent] of Object.entries(previousSnapshot)) {
62
- if (!currentSnapshot[filepath]) {
63
- changedFiles.add(filepath);
64
- if (isBinaryBuffer(oldContent)) continue;
65
- totalDeletions += countLines(oldContent.toString('utf-8'));
66
- }
67
- }
83
+ function yieldToEventLoop(): Promise<void> {
84
+ // setImmediate runs after pending I/O (Bun, Node); browsers only have timers.
85
+ return new Promise((resolve) =>
86
+ typeof setImmediate === 'function' ? setImmediate(resolve) : setTimeout(resolve, 0)
87
+ );
88
+ }
89
+
90
+ // ============================================================================
91
+ // Public API
92
+ // ============================================================================
68
93
 
69
- return {
70
- filesChanged: changedFiles.size,
71
- insertions: totalInsertions,
72
- deletions: totalDeletions
73
- };
94
+ /** One step of an edit script, indexed into the two input sequences. */
95
+ export type DiffOp =
96
+ | { type: 'keep'; oldIndex: number; newIndex: number }
97
+ | { type: 'delete'; oldIndex: number }
98
+ | { type: 'insert'; newIndex: number };
99
+
100
+ export interface LineChangeCount {
101
+ additions: number;
102
+ deletions: number;
74
103
  }
75
104
 
76
105
  /**
77
- * Count only the lines that actually changed between two strings, using the
78
- * same LCS-based diff as git — identical (context) lines are excluded. Use this
79
- * for +/- badges instead of naively counting every line of each side.
106
+ * Count only the lines that actually changed between two strings — identical
107
+ * (context) lines are excluded, exactly as `git diff --stat` counts them. Use
108
+ * this for +/- badges instead of naively counting every line of each side.
80
109
  */
81
- export function countLineChanges(
82
- oldContent: string,
83
- newContent: string
84
- ): { additions: number; deletions: number } {
85
- const { insertions, deletions } = calculateLineDiff(oldContent, newContent);
86
- return { additions: insertions, deletions };
110
+ export function* countLineChangesTask(oldContent: string, newContent: string): Resumable<LineChangeCount> {
111
+ const oldLines = splitLines(oldContent);
112
+ const newLines = splitLines(newContent);
113
+ const common = (yield* matchTask(oldLines, newLines)).length;
114
+ return { additions: newLines.length - common, deletions: oldLines.length - common };
87
115
  }
88
116
 
89
117
  /**
90
- * Calculate line-level diff between two file contents
91
- * Uses simple line-by-line comparison (similar to diff -u)
118
+ * A minimal edit script turning `a` into `b`. Within each changed region the
119
+ * deletions come before the insertions, as in a unified diff.
92
120
  */
93
- function calculateLineDiff(
94
- oldContent: string,
95
- newContent: string
96
- ): { insertions: number; deletions: number } {
97
- const oldLines = splitLines(oldContent);
98
- const newLines = splitLines(newContent);
121
+ export function* diffSequencesTask(a: readonly string[], b: readonly string[]): Resumable<DiffOp[]> {
122
+ const matches = yield* matchTask(a, b);
123
+ const ops: DiffOp[] = [];
124
+ let i = 0;
125
+ let j = 0;
126
+ for (const [mi, mj] of matches) {
127
+ while (i < mi) ops.push({ type: 'delete', oldIndex: i++ });
128
+ while (j < mj) ops.push({ type: 'insert', newIndex: j++ });
129
+ ops.push({ type: 'keep', oldIndex: i++, newIndex: j++ });
130
+ }
131
+ while (i < a.length) ops.push({ type: 'delete', oldIndex: i++ });
132
+ while (j < b.length) ops.push({ type: 'insert', newIndex: j++ });
133
+ return ops;
134
+ }
135
+
136
+ /** Synchronous drivers — for a worker thread and for tests, never a shared thread. */
137
+ export const countLineChanges = (oldContent: string, newContent: string): LineChangeCount =>
138
+ runToEnd(countLineChangesTask(oldContent, newContent));
139
+ export const diffSequences = (a: readonly string[], b: readonly string[]): DiffOp[] =>
140
+ runToEnd(diffSequencesTask(a, b));
141
+ export const matchSequences = (a: readonly string[], b: readonly string[]): Array<[number, number]> =>
142
+ runToEnd(matchTask(a, b));
143
+ /** How many elements two sequences share, in order (their LCS length). */
144
+ export const countCommon = (a: readonly string[], b: readonly string[]): number => matchSequences(a, b).length;
99
145
 
100
- // Use Myers diff algorithm (simplified version)
101
- // For performance, we use a simple LCS-based approach
102
- const lcs = longestCommonSubsequence(oldLines, newLines);
146
+ /** Cooperative drivers — for the server's event loop. */
147
+ export const countLineChangesAsync = (oldContent: string, newContent: string, signal?: AbortSignal) =>
148
+ runSliced(countLineChangesTask(oldContent, newContent), signal);
149
+ export const diffSequencesAsync = (a: readonly string[], b: readonly string[], signal?: AbortSignal) =>
150
+ runSliced(diffSequencesTask(a, b), signal);
103
151
 
104
- const insertions = newLines.length - lcs;
105
- const deletions = oldLines.length - lcs;
152
+ // ============================================================================
153
+ // Engine
154
+ // ============================================================================
106
155
 
107
- return { insertions, deletions };
156
+ /**
157
+ * The matched (oldIndex, newIndex) pairs of a longest common subsequence, in
158
+ * increasing order. Everything else in this module is derived from this.
159
+ *
160
+ * Every reduction below keeps the result exact; they only shrink what the
161
+ * Myers search has to walk:
162
+ * 1. A shared head and tail are common by definition — an edit in the middle
163
+ * of a huge file leaves only the edited region.
164
+ * 2. Elements are interned to integers, so the search compares numbers, not
165
+ * strings.
166
+ * 3. An element that never occurs on the other side cannot be part of ANY
167
+ * common subsequence, so dropping it changes nothing — and it is what
168
+ * keeps a rewritten region from costing its full size squared.
169
+ */
170
+ export function* matchTask(a: readonly string[], b: readonly string[]): Resumable<Array<[number, number]>> {
171
+ const matches: Array<[number, number]> = [];
172
+
173
+ let start = 0;
174
+ while (start < a.length && start < b.length && a[start] === b[start]) {
175
+ matches.push([start, start]);
176
+ start++;
177
+ }
178
+
179
+ let endA = a.length;
180
+ let endB = b.length;
181
+ while (endA > start && endB > start && a[endA - 1] === b[endB - 1]) {
182
+ endA--;
183
+ endB--;
184
+ }
185
+
186
+ if (endA > start && endB > start) {
187
+ // Intern: one id per distinct element of the middle region.
188
+ const ids = new Map<string, number>();
189
+ const rawA = new Int32Array(endA - start);
190
+ const rawB = new Int32Array(endB - start);
191
+ let work = 0;
192
+ for (let i = start; i < endA; i++) {
193
+ rawA[i - start] = intern(ids, a[i]);
194
+ if (++work === WORK_PER_PAUSE) {
195
+ work = 0;
196
+ yield;
197
+ }
198
+ }
199
+ for (let i = start; i < endB; i++) {
200
+ rawB[i - start] = intern(ids, b[i]);
201
+ if (++work === WORK_PER_PAUSE) {
202
+ work = 0;
203
+ yield;
204
+ }
205
+ }
206
+
207
+ const inA = new Uint8Array(ids.size);
208
+ const inB = new Uint8Array(ids.size);
209
+ for (let i = 0; i < rawA.length; i++) inA[rawA[i]] = 1;
210
+ for (let i = 0; i < rawB.length; i++) inB[rawB[i]] = 1;
211
+
212
+ const keptA = keepShared(rawA, inB);
213
+ const keptB = keepShared(rawB, inA);
214
+
215
+ if (keptA.values.length > 0 && keptB.values.length > 0) {
216
+ const matchOf = yield* myersMatches(keptA.values, keptB.values);
217
+ for (let p = 0; p < matchOf.length; p++) {
218
+ if (matchOf[p] >= 0) {
219
+ matches.push([start + keptA.origin[p], start + keptB.origin[matchOf[p]]]);
220
+ }
221
+ }
222
+ }
223
+ }
224
+
225
+ for (let s = 0; s < a.length - endA; s++) matches.push([endA + s, endB + s]);
226
+ return matches;
227
+ }
228
+
229
+ function intern(ids: Map<string, number>, value: string): number {
230
+ let id = ids.get(value);
231
+ if (id === undefined) {
232
+ id = ids.size;
233
+ ids.set(value, id);
234
+ }
235
+ return id;
236
+ }
237
+
238
+ /** The ids of `seq` that also occur on the other side, with where each came from. */
239
+ function keepShared(seq: Int32Array, onOtherSide: Uint8Array): { values: Int32Array; origin: Int32Array } {
240
+ const values = new Int32Array(seq.length);
241
+ const origin = new Int32Array(seq.length);
242
+ let n = 0;
243
+ for (let i = 0; i < seq.length; i++) {
244
+ if (onOtherSide[seq[i]]) {
245
+ values[n] = seq[i];
246
+ origin[n] = i;
247
+ n++;
248
+ }
249
+ }
250
+ return { values: values.subarray(0, n), origin: origin.subarray(0, n) };
251
+ }
252
+
253
+ /**
254
+ * Myers' O((N+M)·D) diff in linear space ("middle snake" divide and conquer),
255
+ * where D is the number of inserted plus deleted elements.
256
+ *
257
+ * Returns, for each index of `a`, the index of `b` it is matched with (or -1).
258
+ * The search itself lives in `MyersSearch.step`, a plain method, because
259
+ * engines do not optimise hot loops inside generator bodies — the same loop
260
+ * written as a generator ran 2.5–5× slower. This wrapper only adds the pauses.
261
+ */
262
+ function* myersMatches(a: Int32Array, b: Int32Array): Resumable<Int32Array> {
263
+ const search = new MyersSearch(a, b);
264
+ while (!search.step(WORK_PER_PAUSE)) yield;
265
+ return search.matchOf;
108
266
  }
109
267
 
110
268
  /**
111
- * Calculate Longest Common Subsequence length
112
- * Used to determine how many lines are unchanged
269
+ * The search as a resumable state machine. Matches are recorded per index of
270
+ * `a` instead of in emission order, which is what lets the sub-problems live on
271
+ * a plain stack: each one's middle snake depends only on its own range, so the
272
+ * order they are solved in cannot change the result. Only two O(N+M) frontiers
273
+ * are allocated, shared by every sub-problem.
113
274
  */
114
- function longestCommonSubsequence(arr1: string[], arr2: string[]): number {
115
- const m = arr1.length;
116
- const n = arr2.length;
117
-
118
- // Create DP table
119
- const dp: number[][] = Array(m + 1).fill(0).map(() => Array(n + 1).fill(0));
120
-
121
- // Fill DP table
122
- for (let i = 1; i <= m; i++) {
123
- for (let j = 1; j <= n; j++) {
124
- if (arr1[i - 1] === arr2[j - 1]) {
125
- dp[i][j] = dp[i - 1][j - 1] + 1;
126
- } else {
127
- dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
275
+ class MyersSearch {
276
+ readonly matchOf: Int32Array;
277
+ private readonly vf: Int32Array;
278
+ private readonly vb: Int32Array;
279
+ private readonly offset: number;
280
+ private readonly stack: number[];
281
+
282
+ // The sub-problem being searched, and where its search stands.
283
+ private searching = false;
284
+ private aLo = 0;
285
+ private aHi = 0;
286
+ private bLo = 0;
287
+ private bHi = 0;
288
+ private d = 0;
289
+ private k = 0;
290
+ private backward = false;
291
+
292
+ constructor(
293
+ private readonly a: Int32Array,
294
+ private readonly b: Int32Array
295
+ ) {
296
+ this.matchOf = new Int32Array(a.length).fill(-1);
297
+ const max = a.length + b.length;
298
+ this.offset = max + 1;
299
+ this.vf = new Int32Array(2 * max + 3);
300
+ this.vb = new Int32Array(2 * max + 3);
301
+ this.stack = [0, a.length, 0, b.length];
302
+ }
303
+
304
+ /** Advance by roughly `budget` units of work. True once every match is known. */
305
+ step(budget: number): boolean {
306
+ const { a, b, matchOf, vf, vb, offset, stack } = this;
307
+
308
+ for (;;) {
309
+ if (!this.searching) {
310
+ if (stack.length === 0) return true;
311
+ let bHi = stack.pop()!;
312
+ let bLo = stack.pop()!;
313
+ let aHi = stack.pop()!;
314
+ let aLo = stack.pop()!;
315
+
316
+ // Shared ends of this range are matched directly.
317
+ while (aLo < aHi && bLo < bHi && a[aLo] === b[bLo]) matchOf[aLo++] = bLo++;
318
+ while (aLo < aHi && bLo < bHi && a[aHi - 1] === b[bHi - 1]) matchOf[--aHi] = --bHi;
319
+ if (aLo >= aHi || bLo >= bHi) continue;
320
+
321
+ // Both ends differ here, so D ≥ 2 and the middle snake splits the
322
+ // range into two strictly smaller problems.
323
+ this.aLo = aLo;
324
+ this.aHi = aHi;
325
+ this.bLo = bLo;
326
+ this.bHi = bHi;
327
+ this.d = 0;
328
+ this.k = 0;
329
+ this.backward = false;
330
+ this.searching = true;
331
+ vf[offset + 1] = 0;
332
+ vb[offset + 1] = 0;
128
333
  }
334
+
335
+ const { aLo, aHi, bLo, bHi } = this;
336
+ const n = aHi - aLo;
337
+ const m = bHi - bLo;
338
+ const delta = n - m;
339
+ const odd = (delta & 1) !== 0;
340
+ const limit = Math.ceil((n + m) / 2);
341
+ let d = this.d;
342
+ let k = this.k;
343
+ let backward = this.backward;
344
+ let snake: [number, number, number, number] | null = null;
345
+
346
+ search: while (snake === null) {
347
+ if (d > limit) {
348
+ // Unreachable for valid input: the two searches always meet by D/2.
349
+ throw new Error('diff: middle snake not found');
350
+ }
351
+
352
+ if (!backward) {
353
+ // Forward: furthest x on each diagonal k = x - y, from the start.
354
+ for (; k <= d; k += 2) {
355
+ let x =
356
+ k === -d || (k !== d && vf[offset + k - 1] < vf[offset + k + 1])
357
+ ? vf[offset + k + 1]
358
+ : vf[offset + k - 1] + 1;
359
+ let y = x - k;
360
+ const x0 = x;
361
+ const y0 = y;
362
+ while (x < n && y < m && a[aLo + x] === b[bLo + y]) {
363
+ x++;
364
+ y++;
365
+ }
366
+ vf[offset + k] = x;
367
+ const c = delta - k;
368
+ if (odd && c >= -(d - 1) && c <= d - 1 && x + vb[offset + c] >= n) {
369
+ snake = [aLo + x0, bLo + y0, aLo + x, bLo + y];
370
+ break search;
371
+ }
372
+ budget -= x - x0 + 1;
373
+ if (budget <= 0) {
374
+ this.save(d, k + 2, false);
375
+ return false;
376
+ }
377
+ }
378
+ backward = true;
379
+ k = -d;
380
+ }
381
+
382
+ // Backward: the same walk over both ranges reversed.
383
+ for (; k <= d; k += 2) {
384
+ let x =
385
+ k === -d || (k !== d && vb[offset + k - 1] < vb[offset + k + 1])
386
+ ? vb[offset + k + 1]
387
+ : vb[offset + k - 1] + 1;
388
+ let y = x - k;
389
+ const x0 = x;
390
+ const y0 = y;
391
+ while (x < n && y < m && a[aHi - 1 - x] === b[bHi - 1 - y]) {
392
+ x++;
393
+ y++;
394
+ }
395
+ vb[offset + k] = x;
396
+ const c = delta - k;
397
+ if (!odd && c >= -d && c <= d && x + vf[offset + c] >= n) {
398
+ snake = [aLo + n - x, bLo + m - y, aLo + n - x0, bLo + m - y0];
399
+ break search;
400
+ }
401
+ budget -= x - x0 + 1;
402
+ if (budget <= 0) {
403
+ this.save(d, k + 2, true);
404
+ return false;
405
+ }
406
+ }
407
+ d++;
408
+ k = -d;
409
+ backward = false;
410
+ }
411
+
412
+ const [x, y, u, v] = snake;
413
+ for (let s = 0; s < u - x; s++) matchOf[x + s] = y + s;
414
+ stack.push(aLo, x, bLo, y, u, aHi, v, bHi);
415
+ this.searching = false;
416
+ if (budget <= 0) return false;
129
417
  }
130
418
  }
131
419
 
132
- return dp[m][n];
420
+ /**
421
+ * Where to pick the search up again. `k` may run past `d`; the loop that
422
+ * resumes it then simply finishes that direction and moves on.
423
+ */
424
+ private save(d: number, k: number, backward: boolean): void {
425
+ this.d = d;
426
+ this.k = k;
427
+ this.backward = backward;
428
+ }
133
429
  }
134
430
 
135
431
  /**
136
432
  * Split content into lines
137
433
  * Handles different line endings (CRLF, LF)
138
434
  */
139
- function splitLines(content: string): string[] {
435
+ export function splitLines(content: string): string[] {
140
436
  if (!content) return [];
141
437
  // Normalize line endings and split
142
438
  const lines = content.replace(/\r\n/g, '\n').split('\n');
@@ -147,16 +443,3 @@ function splitLines(content: string): string[] {
147
443
  if (lines.length > 1 && lines[lines.length - 1] === '') lines.pop();
148
444
  return lines;
149
445
  }
150
-
151
- /**
152
- * Count number of lines in content
153
- */
154
- function countLines(content: string): number {
155
- if (!content) return 0;
156
- const lines = splitLines(content);
157
- // Don't count empty last line
158
- if (lines.length > 0 && lines[lines.length - 1] === '') {
159
- return lines.length - 1;
160
- }
161
- return lines.length;
162
- }