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-edits.js ADDED
@@ -0,0 +1,890 @@
1
+ // Parses the edit formats LLMs emit (SEARCH/REPLACE blocks, unified diffs,
2
+ // str_replace tool calls, apply_patch envelopes) and applies them to a
3
+ // source file, falling back to whitespace-insensitive and fuzzy matching.
4
+ // Also parses git patches into diff states for patch-only rendering.
5
+
6
+ import { splitText } from "./diff.js";
7
+
8
+ const APPLY_PATCH_RE = /^\*\*\* Begin Patch/m;
9
+ const SEARCH_MARKER_LINE_RE = /^<{5,9} SEARCH/m;
10
+ const SEARCH_MARKER_RE = /^<{5,9} SEARCH/;
11
+ const STR_REPLACE_JSON_RE = /"old_str(ing)?"\s*:/;
12
+ const STR_REPLACE_TAG_RE = /<old_str>/;
13
+ const HUNK_LINE_RE = /^@@/m;
14
+ const FILE_HEADERS_RE = /^--- .*\n\+\+\+ /m;
15
+ const FENCE_LINE_RE = /^```/m;
16
+ const PATH_LINE_RE = /^[\w./-]+\.\w+$/;
17
+ const DIVIDER_RE = /^={5,9}\s*$/;
18
+ const REPLACE_MARKER_RE = /^>{5,9} REPLACE/;
19
+ const PATCH_FILE_RE = /^\*\*\* (Update|Add|Delete) File: (.+)$/;
20
+ const B_PREFIX_RE = /^b\//;
21
+ const WHOLE_FILE_RE = /^```[^\n]*\n([\s\S]*?)(\n```|$)/m;
22
+ const INDENT_RE = /^[ \t]*/;
23
+ const AB_PREFIX_RE = /^[ab]\//;
24
+ const TAB_SUFFIX_RE = /\t.*$/;
25
+ const GIT_HEADER_RE = /^diff --git a\/(.+) b\/(.+)$/;
26
+ const HUNK_HEADER_RE = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@ ?(.*)$/;
27
+
28
+ /**
29
+ * @typedef {{
30
+ * search: string,
31
+ * replace: string,
32
+ * path?: string | undefined,
33
+ * searchComplete: boolean,
34
+ * complete: boolean,
35
+ * }} Edit
36
+ *
37
+ * @typedef {"search-replace" | "unified-diff" | "str-replace" | "apply-patch" | "whole-file" | "unknown"} EditFormat
38
+ */
39
+
40
+ /**
41
+ * @param {string} text
42
+ * @returns {EditFormat}
43
+ */
44
+ export function detectEditFormat(text) {
45
+ if (APPLY_PATCH_RE.test(text)) return "apply-patch";
46
+ if (SEARCH_MARKER_LINE_RE.test(text)) return "search-replace";
47
+ if (STR_REPLACE_JSON_RE.test(text) || STR_REPLACE_TAG_RE.test(text)) {
48
+ return "str-replace";
49
+ }
50
+ if (HUNK_LINE_RE.test(text) || FILE_HEADERS_RE.test(text)) {
51
+ return "unified-diff";
52
+ }
53
+ if (FENCE_LINE_RE.test(text)) return "whole-file";
54
+ return "unknown";
55
+ }
56
+
57
+ const FENCE_RE = /^```/;
58
+
59
+ /**
60
+ * Parses edits, tolerating a truncated final edit (for streamed output).
61
+ * @param {string} text
62
+ * @returns {{ format: EditFormat, edits: Edit[] }}
63
+ */
64
+ export function parseEdits(text) {
65
+ const format = detectEditFormat(text);
66
+ switch (format) {
67
+ case "search-replace":
68
+ return { format, edits: parseSearchReplace(text) };
69
+ case "apply-patch":
70
+ return { format, edits: parseApplyPatch(text) };
71
+ case "unified-diff":
72
+ return { format, edits: parseUnifiedEdits(text) };
73
+ case "str-replace":
74
+ return { format, edits: parseStrReplace(text) };
75
+ case "whole-file":
76
+ return { format, edits: parseWholeFile(text) };
77
+ default:
78
+ return { format, edits: [] };
79
+ }
80
+ }
81
+
82
+ /** @param {string[]} lines */
83
+ function joinLines(lines) {
84
+ return lines.length === 0 ? "" : `${lines.join("\n")}\n`;
85
+ }
86
+
87
+ /** @param {string} text */
88
+ function parseSearchReplace(text) {
89
+ const lines = text.split("\n");
90
+ /** @type {Edit[]} */
91
+ const edits = [];
92
+ /** @type {string | undefined} */
93
+ let path;
94
+ let i = 0;
95
+ while (i < lines.length) {
96
+ const line = /** @type {string} */ (lines[i]);
97
+ if (!SEARCH_MARKER_RE.test(line)) {
98
+ const trimmed = line.trim();
99
+ // A bare path line (Aider style) names the file for the next blocks.
100
+ if (trimmed && !FENCE_RE.test(trimmed) && PATH_LINE_RE.test(trimmed)) {
101
+ path = trimmed;
102
+ }
103
+ i++;
104
+ continue;
105
+ }
106
+ i++;
107
+ /** @type {string[]} */
108
+ const search = [];
109
+ while (
110
+ i < lines.length &&
111
+ !DIVIDER_RE.test(/** @type {string} */ (lines[i]))
112
+ ) {
113
+ search.push(/** @type {string} */ (lines[i]));
114
+ i++;
115
+ }
116
+ if (i >= lines.length) {
117
+ edits.push({
118
+ search: joinLines(search),
119
+ replace: "",
120
+ path,
121
+ searchComplete: false,
122
+ complete: false,
123
+ });
124
+ break;
125
+ }
126
+ i++;
127
+ /** @type {string[]} */
128
+ const replace = [];
129
+ while (
130
+ i < lines.length &&
131
+ !REPLACE_MARKER_RE.test(/** @type {string} */ (lines[i]))
132
+ ) {
133
+ replace.push(/** @type {string} */ (lines[i]));
134
+ i++;
135
+ }
136
+ const complete = i < lines.length;
137
+ // Hold back a partial last line that may still become the closing marker.
138
+ const tail = replace[replace.length - 1];
139
+ const heldBack =
140
+ !complete &&
141
+ tail !== undefined &&
142
+ tail !== "" &&
143
+ ">>>>>>> REPLACE".startsWith(tail);
144
+ if (heldBack) replace.pop();
145
+ // A truncated replace keeps its partial last line without a newline.
146
+ const replaceText =
147
+ complete || heldBack ? joinLines(replace) : replace.join("\n");
148
+ edits.push({
149
+ search: joinLines(search),
150
+ replace: replaceText,
151
+ path,
152
+ searchComplete: true,
153
+ complete,
154
+ });
155
+ i++;
156
+ }
157
+ return edits;
158
+ }
159
+
160
+ /** @param {string} text */
161
+ function parseApplyPatch(text) {
162
+ const lines = text.split("\n");
163
+ /** @type {Edit[]} */
164
+ const edits = [];
165
+ /** @type {string | undefined} */
166
+ let path;
167
+ /** @type {string[] | null} */
168
+ let search = null;
169
+ /** @type {string[]} */
170
+ let replace = [];
171
+ let adding = false;
172
+ const flush = (/** @type {boolean} */ complete) => {
173
+ if (search === null) return;
174
+ if (search.length > 0 || replace.length > 0) {
175
+ edits.push({
176
+ search: joinLines(search),
177
+ replace: joinLines(replace),
178
+ path,
179
+ searchComplete: complete,
180
+ complete,
181
+ });
182
+ }
183
+ search = null;
184
+ replace = [];
185
+ };
186
+ let ended = false;
187
+ for (const line of lines) {
188
+ if (line.startsWith("*** End Patch")) {
189
+ ended = true;
190
+ break;
191
+ }
192
+ const file = PATCH_FILE_RE.exec(line);
193
+ if (file) {
194
+ flush(true);
195
+ path = /** @type {string} */ (file[2]).trim();
196
+ adding = file[1] === "Add";
197
+ search = [];
198
+ continue;
199
+ }
200
+ if (line.startsWith("@@")) {
201
+ flush(true);
202
+ search = [];
203
+ continue;
204
+ }
205
+ if (line.startsWith("*** ")) continue;
206
+ if (search === null) continue;
207
+ if (adding) {
208
+ replace.push(line.startsWith("+") ? line.slice(1) : line);
209
+ } else if (line.startsWith("-")) {
210
+ search.push(line.slice(1));
211
+ } else if (line.startsWith("+")) {
212
+ replace.push(line.slice(1));
213
+ } else {
214
+ const ctx = line.startsWith(" ") ? line.slice(1) : line;
215
+ search.push(ctx);
216
+ replace.push(ctx);
217
+ }
218
+ }
219
+ flush(ended);
220
+ return edits;
221
+ }
222
+
223
+ /** @param {string} text */
224
+ function parseUnifiedEdits(text) {
225
+ /** @type {Edit[]} */
226
+ const edits = [];
227
+ /** @type {string | undefined} */
228
+ let path;
229
+ /** @type {string[] | null} */
230
+ let search = null;
231
+ /** @type {string[]} */
232
+ let replace = [];
233
+ const flush = (/** @type {boolean} */ complete) => {
234
+ if (search === null) return;
235
+ // Trailing blank context is usually an artifact of the model's output.
236
+ while (
237
+ search.length &&
238
+ search[search.length - 1] === "" &&
239
+ replace[replace.length - 1] === ""
240
+ ) {
241
+ search.pop();
242
+ replace.pop();
243
+ }
244
+ edits.push({
245
+ search: joinLines(search),
246
+ replace: joinLines(replace),
247
+ path,
248
+ searchComplete: complete,
249
+ complete,
250
+ });
251
+ search = null;
252
+ replace = [];
253
+ };
254
+ for (const line of text.split("\n")) {
255
+ if (FENCE_RE.test(line)) continue;
256
+ if (line.startsWith("+++ ")) {
257
+ path = line.slice(4).replace(B_PREFIX_RE, "").trim();
258
+ continue;
259
+ }
260
+ if (
261
+ line.startsWith("--- ") ||
262
+ line.startsWith("diff ") ||
263
+ line.startsWith("index ")
264
+ ) {
265
+ flush(true);
266
+ continue;
267
+ }
268
+ if (line.startsWith("@@")) {
269
+ flush(true);
270
+ search = [];
271
+ continue;
272
+ }
273
+ if (search === null || line.startsWith("\\")) continue;
274
+ if (line.startsWith("-")) search.push(line.slice(1));
275
+ else if (line.startsWith("+")) replace.push(line.slice(1));
276
+ else {
277
+ // Models often drop the leading space on context lines.
278
+ const ctx = line.startsWith(" ") ? line.slice(1) : line;
279
+ search.push(ctx);
280
+ replace.push(ctx);
281
+ }
282
+ }
283
+ flush(true);
284
+ return edits;
285
+ }
286
+
287
+ /** @param {string} text */
288
+ function parseStrReplace(text) {
289
+ /** @type {Edit[]} */
290
+ const edits = [];
291
+ /** @param {any} value @param {string | undefined} path */
292
+ const visit = (value, path) => {
293
+ if (Array.isArray(value)) {
294
+ for (const v of value) visit(v, path);
295
+ return;
296
+ }
297
+ if (!value || typeof value !== "object") return;
298
+ const p = value.path ?? value.file_path ?? value.filePath ?? path;
299
+ const oldStr = value.old_str ?? value.old_string ?? value.oldText;
300
+ const newStr = value.new_str ?? value.new_string ?? value.newText;
301
+ if (typeof oldStr === "string" && typeof newStr === "string") {
302
+ edits.push({
303
+ search: oldStr,
304
+ replace: newStr,
305
+ path: p,
306
+ searchComplete: true,
307
+ complete: true,
308
+ });
309
+ }
310
+ for (const key of [
311
+ "edits",
312
+ "input",
313
+ "arguments",
314
+ "parameters",
315
+ "tool_calls",
316
+ ]) {
317
+ if (value[key]) {
318
+ visit(
319
+ typeof value[key] === "string" ? safeJson(value[key]) : value[key],
320
+ p,
321
+ );
322
+ }
323
+ }
324
+ };
325
+ const whole = safeJson(text.trim().replace(/^```\w*\n|```\s*$/g, ""));
326
+ if (whole !== undefined) {
327
+ visit(whole, undefined);
328
+ return edits;
329
+ }
330
+ // One JSON object per line or block, or <old_str>/<new_str> tags.
331
+ for (const block of text.match(/\{[\s\S]*?\}(?=\s*(\n|$))/g) ?? []) {
332
+ visit(safeJson(block), undefined);
333
+ }
334
+ const tagRe =
335
+ /<old_str>\n?([\s\S]*?)<\/old_str>\s*<new_str>\n?([\s\S]*?)<\/new_str>/g;
336
+ for (let m = tagRe.exec(text); m; m = tagRe.exec(text)) {
337
+ edits.push({
338
+ search: m[1] ?? "",
339
+ replace: m[2] ?? "",
340
+ searchComplete: true,
341
+ complete: true,
342
+ });
343
+ }
344
+ return edits;
345
+ }
346
+
347
+ /** @param {string} text */
348
+ function safeJson(text) {
349
+ try {
350
+ return JSON.parse(text);
351
+ } catch {
352
+ return undefined;
353
+ }
354
+ }
355
+
356
+ /** @param {string} text */
357
+ function parseWholeFile(text) {
358
+ const m = WHOLE_FILE_RE.exec(text);
359
+ if (!m) return [];
360
+ return [
361
+ {
362
+ search: "",
363
+ replace: `${m[1]}\n`,
364
+ searchComplete: true,
365
+ complete: m[2] !== "",
366
+ whole: true,
367
+ },
368
+ ];
369
+ }
370
+
371
+ /**
372
+ * @typedef {{
373
+ * edit: Edit,
374
+ * status: "applied" | "failed",
375
+ * strategy?: "exact" | "trailing-whitespace" | "indentation" | "fuzzy" | "whole-file" | "append",
376
+ * score?: number,
377
+ * start?: number,
378
+ * end?: number,
379
+ * reason?: string,
380
+ * }} EditResult
381
+ */
382
+
383
+ /**
384
+ * Bigram set of a trimmed line, for Dice similarity.
385
+ * @param {string} line
386
+ */
387
+ function bigrams(line) {
388
+ const s = line.trim();
389
+ /** @type {Map<string, number>} */
390
+ const out = new Map();
391
+ for (let i = 0; i < s.length - 1; i++) {
392
+ const g = s.slice(i, i + 2);
393
+ out.set(g, (out.get(g) ?? 0) + 1);
394
+ }
395
+ return out;
396
+ }
397
+
398
+ /**
399
+ * @param {Map<string, number>} x
400
+ * @param {Map<string, number>} y
401
+ * @param {string} xs
402
+ * @param {string} ys
403
+ */
404
+ function dice(x, y, xs, ys) {
405
+ if (xs.trim() === ys.trim()) return 1;
406
+ let sizeX = 0;
407
+ let sizeY = 0;
408
+ let both = 0;
409
+ for (const n of x.values()) sizeX += n;
410
+ for (const n of y.values()) sizeY += n;
411
+ if (sizeX + sizeY === 0) return 0;
412
+ for (const [g, n] of x) both += Math.min(n, y.get(g) ?? 0);
413
+ return (2 * both) / (sizeX + sizeY);
414
+ }
415
+
416
+ /**
417
+ * Finds `search` lines in `lines`, first exactly, then ignoring trailing
418
+ * whitespace, then indentation, then by fuzzy line similarity.
419
+ * @param {string[]} lines
420
+ * @param {string[]} search
421
+ * @param {number} from preferred start (edits usually arrive in order)
422
+ * @returns {{ start: number, strategy: "exact" | "trailing-whitespace" | "indentation" | "fuzzy", score: number } | null}
423
+ */
424
+ export function locate(lines, search, from = 0) {
425
+ const k = search.length;
426
+ if (k === 0) return null;
427
+ /** @type {Array<[(l: string) => string, "exact" | "trailing-whitespace" | "indentation"]>} */
428
+ const passes = [
429
+ [(l) => l, "exact"],
430
+ [(l) => l.trimEnd(), "trailing-whitespace"],
431
+ [(l) => l.trim(), "indentation"],
432
+ ];
433
+ for (const [norm, strategy] of passes) {
434
+ const target = search.map(norm);
435
+ for (const start of [from, 0]) {
436
+ for (let i = start; i + k <= lines.length; i++) {
437
+ let ok = true;
438
+ for (let j = 0; j < k; j++) {
439
+ if (norm(/** @type {string} */ (lines[i + j])) !== target[j]) {
440
+ ok = false;
441
+ break;
442
+ }
443
+ }
444
+ if (ok) return { start: i, strategy, score: 1 };
445
+ }
446
+ }
447
+ }
448
+
449
+ // Fuzzy: best window by mean line similarity.
450
+ const searchGrams = search.map(bigrams);
451
+ /** @type {Map<number, Map<string, number>>} */
452
+ const cache = new Map();
453
+ const gramsAt = (/** @type {number} */ i) => {
454
+ let g = cache.get(i);
455
+ if (!g) {
456
+ g = bigrams(/** @type {string} */ (lines[i]));
457
+ cache.set(i, g);
458
+ }
459
+ return g;
460
+ };
461
+ let best = 0;
462
+ let bestStart = -1;
463
+ for (let i = 0; i + k <= lines.length; i++) {
464
+ // Cheap reject on the first line before scoring the window.
465
+ const first = dice(
466
+ gramsAt(i),
467
+ /** @type {Map<string, number>} */ (searchGrams[0]),
468
+ /** @type {string} */ (lines[i]),
469
+ /** @type {string} */ (search[0]),
470
+ );
471
+ if (first < 0.5 && k > 1) continue;
472
+ let total = first;
473
+ for (let j = 1; j < k; j++) {
474
+ total += dice(
475
+ gramsAt(i + j),
476
+ /** @type {Map<string, number>} */ (searchGrams[j]),
477
+ /** @type {string} */ (lines[i + j]),
478
+ /** @type {string} */ (search[j]),
479
+ );
480
+ }
481
+ const score = total / k;
482
+ if (score > best) {
483
+ best = score;
484
+ bestStart = i;
485
+ }
486
+ }
487
+ if (bestStart >= 0 && best >= 0.8) {
488
+ return { start: bestStart, strategy: "fuzzy", score: best };
489
+ }
490
+ return null;
491
+ }
492
+
493
+ /** @param {string} line */
494
+ const indentOf = (line) => INDENT_RE.exec(line)?.[0] ?? "";
495
+
496
+ /**
497
+ * Shifts `replace` by the indentation difference between what the model
498
+ * wrote and what the file has, so a de-indented edit lands in place.
499
+ * @param {string[]} replace
500
+ * @param {string[]} search
501
+ * @param {string[]} found
502
+ */
503
+ function reindent(replace, search, found) {
504
+ const si = search.findIndex((l) => l.trim() !== "");
505
+ if (si < 0) return replace;
506
+ const want = indentOf(/** @type {string} */ (found[si] ?? ""));
507
+ const have = indentOf(/** @type {string} */ (search[si]));
508
+ if (want === have) return replace;
509
+ return replace.map((line) => {
510
+ if (line.trim() === "") return line;
511
+ if (line.startsWith(have)) return want + line.slice(have.length);
512
+ return want + line.trimStart();
513
+ });
514
+ }
515
+
516
+ /**
517
+ * Applies complete edits to `source`. Edits that can't be located, or that
518
+ * overlap an earlier one, are reported as failed and skipped.
519
+ * @param {string} source
520
+ * @param {Edit[]} edits
521
+ * @returns {{ text: string, results: EditResult[] }}
522
+ */
523
+ export function applyEdits(source, edits) {
524
+ const { lines, noEol } = splitText(source);
525
+ /** @type {EditResult[]} */
526
+ const results = [];
527
+ /** @type {Array<{ start: number, end: number, lines: string[] }>} */
528
+ const splices = [];
529
+ let cursor = 0;
530
+
531
+ for (const edit of edits) {
532
+ if (!edit.complete) continue;
533
+ const replaceLines = splitText(edit.replace).lines;
534
+ if (/** @type {any} */ (edit).whole) {
535
+ return {
536
+ text: edit.replace,
537
+ results: [
538
+ {
539
+ edit,
540
+ status: "applied",
541
+ strategy: "whole-file",
542
+ score: 1,
543
+ start: 0,
544
+ end: lines.length,
545
+ },
546
+ ],
547
+ };
548
+ }
549
+ const searchLines = splitText(edit.search).lines;
550
+ if (searchLines.length === 0) {
551
+ splices.push({
552
+ start: lines.length,
553
+ end: lines.length,
554
+ lines: replaceLines,
555
+ });
556
+ results.push({
557
+ edit,
558
+ status: "applied",
559
+ strategy: "append",
560
+ score: 1,
561
+ start: lines.length,
562
+ end: lines.length,
563
+ });
564
+ continue;
565
+ }
566
+ const hit = locate(lines, searchLines, cursor);
567
+ if (!hit) {
568
+ results.push({ edit, status: "failed", reason: "search text not found" });
569
+ continue;
570
+ }
571
+ const start = hit.start;
572
+ const end = start + searchLines.length;
573
+ if (splices.some((s) => start < s.end && end > s.start)) {
574
+ results.push({
575
+ edit,
576
+ status: "failed",
577
+ reason: "overlaps an earlier edit",
578
+ });
579
+ continue;
580
+ }
581
+ const replaced =
582
+ hit.strategy === "exact" || hit.strategy === "trailing-whitespace"
583
+ ? replaceLines
584
+ : reindent(replaceLines, searchLines, lines.slice(start, end));
585
+ splices.push({ start, end, lines: replaced });
586
+ results.push({
587
+ edit,
588
+ status: "applied",
589
+ strategy: hit.strategy,
590
+ score: hit.score,
591
+ start,
592
+ end,
593
+ });
594
+ cursor = end;
595
+ }
596
+
597
+ splices.sort((x, y) => x.start - y.start);
598
+ /** @type {string[]} */
599
+ const out = [];
600
+ let pos = 0;
601
+ for (const s of splices) {
602
+ out.push(...lines.slice(pos, s.start), ...s.lines);
603
+ pos = s.end;
604
+ }
605
+ out.push(...lines.slice(pos));
606
+ const text = out.join("\n");
607
+ return { text: out.length === 0 || noEol ? text : `${text}\n`, results };
608
+ }
609
+
610
+ /**
611
+ * The longest prefix of the edited file that streamed edit output has
612
+ * settled so far. Grows append-only while edits arrive in file order, so a
613
+ * streaming diff session can render it incrementally.
614
+ * @param {string} source
615
+ * @param {string} partialOutput
616
+ * @param {{ done?: boolean }} [options]
617
+ * @returns {{ after: string, format: EditFormat, edits: Edit[], done: boolean }}
618
+ */
619
+ export function streamEditPrefix(source, partialOutput, { done = false } = {}) {
620
+ const { format, edits } = parseEdits(partialOutput);
621
+ const { lines } = splitText(source);
622
+ /** @type {string[]} */
623
+ const out = [];
624
+ let pos = 0;
625
+ let tail = "";
626
+ let settled = true;
627
+ for (const edit of edits) {
628
+ if (!edit.searchComplete) {
629
+ settled = false;
630
+ break;
631
+ }
632
+ const searchLines = splitText(edit.search).lines;
633
+ const hit = searchLines.length ? locate(lines, searchLines, pos) : null;
634
+ if (!hit || hit.start < pos) continue;
635
+ out.push(...lines.slice(pos, hit.start));
636
+ if (!edit.complete) {
637
+ // Show the replacement as it streams in, partial last line included.
638
+ const cut = edit.replace.lastIndexOf("\n");
639
+ if (cut >= 0) out.push(...edit.replace.slice(0, cut).split("\n"));
640
+ tail = edit.replace.slice(cut + 1);
641
+ settled = false;
642
+ break;
643
+ }
644
+ const replaced =
645
+ hit.strategy === "exact" || hit.strategy === "trailing-whitespace"
646
+ ? splitText(edit.replace).lines
647
+ : reindent(
648
+ splitText(edit.replace).lines,
649
+ searchLines,
650
+ lines.slice(hit.start, hit.start + searchLines.length),
651
+ );
652
+ out.push(...replaced);
653
+ pos = hit.start + searchLines.length;
654
+ }
655
+ const finished = done && settled;
656
+ if (finished) out.push(...lines.slice(pos));
657
+ let after = out.length ? `${out.join("\n")}\n` : "";
658
+ after += tail;
659
+ return { after, format, edits, done: finished };
660
+ }
661
+
662
+ /**
663
+ * @typedef {{
664
+ * oldPath: string,
665
+ * newPath: string,
666
+ * status: "modified" | "added" | "deleted" | "renamed" | "binary",
667
+ * hunks: Array<{
668
+ * oldStart: number, oldLines: number, newStart: number, newLines: number,
669
+ * section: string,
670
+ * lines: Array<{ type: " " | "-" | "+", text: string }>,
671
+ * }>,
672
+ * additions: number,
673
+ * deletions: number,
674
+ * }} FilePatch
675
+ */
676
+
677
+ /**
678
+ * Parses a (possibly multi-file) git or unified patch.
679
+ * @param {string} text
680
+ * @returns {FilePatch[]}
681
+ */
682
+ export function parsePatch(text) {
683
+ /** @type {FilePatch[]} */
684
+ const files = [];
685
+ /** @type {FilePatch | null} */
686
+ let file = null;
687
+ /** @type {FilePatch["hunks"][number] | null} */
688
+ let hunk = null;
689
+ const start = (
690
+ /** @type {string} */ oldPath,
691
+ /** @type {string} */ newPath,
692
+ ) => {
693
+ file = {
694
+ oldPath,
695
+ newPath,
696
+ status: "modified",
697
+ hunks: [],
698
+ additions: 0,
699
+ deletions: 0,
700
+ };
701
+ files.push(file);
702
+ hunk = null;
703
+ };
704
+ const strip = (/** @type {string} */ p) =>
705
+ p.trim().replace(AB_PREFIX_RE, "").replace(TAB_SUFFIX_RE, "");
706
+
707
+ for (const line of text.split("\n")) {
708
+ const git = GIT_HEADER_RE.exec(line);
709
+ if (git) {
710
+ start(/** @type {string} */ (git[1]), /** @type {string} */ (git[2]));
711
+ continue;
712
+ }
713
+ if (line.startsWith("--- ") && (!file || hunk)) {
714
+ const p = strip(line.slice(4));
715
+ start(p, p);
716
+ continue;
717
+ }
718
+ if (!file) continue;
719
+ /** @type {FilePatch} */
720
+ const f = file;
721
+ if (line.startsWith("--- ")) {
722
+ const p = line.slice(4).trim();
723
+ if (p === "/dev/null") f.status = "added";
724
+ else f.oldPath = strip(p);
725
+ continue;
726
+ }
727
+ if (line.startsWith("+++ ")) {
728
+ const p = line.slice(4).trim();
729
+ if (p === "/dev/null") f.status = "deleted";
730
+ else f.newPath = strip(p);
731
+ continue;
732
+ }
733
+ if (line.startsWith("new file mode")) f.status = "added";
734
+ else if (line.startsWith("deleted file mode")) f.status = "deleted";
735
+ else if (line.startsWith("rename from")) f.status = "renamed";
736
+ else if (line.startsWith("Binary files")) f.status = "binary";
737
+ const h = HUNK_HEADER_RE.exec(line);
738
+ if (h) {
739
+ hunk = {
740
+ oldStart: Number(h[1]),
741
+ oldLines: h[2] === undefined ? 1 : Number(h[2]),
742
+ newStart: Number(h[3]),
743
+ newLines: h[4] === undefined ? 1 : Number(h[4]),
744
+ section: h[5] ?? "",
745
+ lines: [],
746
+ };
747
+ f.hunks.push(hunk);
748
+ continue;
749
+ }
750
+ if (!hunk || line.startsWith("\\")) continue;
751
+ /** @type {FilePatch["hunks"][number]} */
752
+ const hk = hunk;
753
+ const type = line[0];
754
+ if (type === "+" || type === "-" || type === " ") {
755
+ hk.lines.push({ type, text: line.slice(1) });
756
+ if (type === "+") f.additions++;
757
+ if (type === "-") f.deletions++;
758
+ } else if (line === "") {
759
+ hk.lines.push({ type: " ", text: "" });
760
+ }
761
+ }
762
+ // Drop blank context lines past a hunk's declared length (the empty
763
+ // lines between files, or after the patch's final newline).
764
+ for (const f of files) {
765
+ for (const h of f.hunks) {
766
+ let oldCount = h.lines.filter((l) => l.type !== "+").length;
767
+ while (
768
+ oldCount > h.oldLines &&
769
+ h.lines[h.lines.length - 1]?.type === " " &&
770
+ h.lines[h.lines.length - 1]?.text === ""
771
+ ) {
772
+ h.lines.pop();
773
+ oldCount--;
774
+ }
775
+ }
776
+ }
777
+ return files;
778
+ }
779
+
780
+ /**
781
+ * A diff state for a patch alone: the lines between hunks are unknown, so
782
+ * they become blank filler inside folds that can't be expanded, keeping
783
+ * real line numbers.
784
+ * @param {FilePatch} file
785
+ * @returns {import("./diff.js").DiffState & { beforeText: string, afterText: string }}
786
+ */
787
+ export function patchToState(file) {
788
+ /** @type {string[]} */
789
+ const beforeLines = [];
790
+ /** @type {string[]} */
791
+ const afterLines = [];
792
+ /** @type {import("./diff.js").Block[]} */
793
+ const blocks = [];
794
+ let id = 0;
795
+ /**
796
+ * @param {"equal" | "change"} type
797
+ * @param {number} aN
798
+ * @param {number} bN
799
+ * @param {boolean} [unknown]
800
+ */
801
+ const push = (type, aN, bN, unknown = false) => {
802
+ const a = beforeLines.length - aN;
803
+ const b = afterLines.length - bN;
804
+ const last = blocks[blocks.length - 1];
805
+ if (
806
+ last &&
807
+ last.type === type &&
808
+ !last.unknown &&
809
+ !unknown &&
810
+ last.aEnd === a &&
811
+ last.bEnd === b
812
+ ) {
813
+ last.aEnd += aN;
814
+ last.bEnd += bN;
815
+ return;
816
+ }
817
+ /** @type {import("./diff.js").Block} */
818
+ const block = { type, a, aEnd: a + aN, b, bEnd: b + bN };
819
+ if (unknown) block.unknown = true;
820
+ if (type === "change") block.id = id++;
821
+ blocks.push(block);
822
+ };
823
+
824
+ for (const hunk of file.hunks) {
825
+ const gapA = Math.max(0, hunk.oldStart - 1 - beforeLines.length);
826
+ const gapB = Math.max(0, hunk.newStart - 1 - afterLines.length);
827
+ if (gapA > 0 || gapB > 0) {
828
+ for (let i = 0; i < gapA; i++) beforeLines.push("");
829
+ for (let i = 0; i < gapB; i++) afterLines.push("");
830
+ push("equal", gapA, gapB, true);
831
+ const gap = /** @type {import("./diff.js").Block} */ (
832
+ blocks[blocks.length - 1]
833
+ );
834
+ gap.header =
835
+ `@@ -${hunk.oldStart},${hunk.oldLines} +${hunk.newStart},${hunk.newLines} @@ ${hunk.section}`.trim();
836
+ }
837
+ let i = 0;
838
+ const ls = hunk.lines;
839
+ while (i < ls.length) {
840
+ if (ls[i]?.type === " ") {
841
+ let n = 0;
842
+ while (ls[i]?.type === " ") {
843
+ const text = /** @type {{ text: string }} */ (ls[i]).text;
844
+ beforeLines.push(text);
845
+ afterLines.push(text);
846
+ i++;
847
+ n++;
848
+ }
849
+ push("equal", n, n);
850
+ continue;
851
+ }
852
+ let dels = 0;
853
+ let adds = 0;
854
+ while (ls[i] && ls[i]?.type !== " ") {
855
+ const l = /** @type {{ type: string, text: string }} */ (ls[i]);
856
+ if (l.type === "-") {
857
+ beforeLines.push(l.text);
858
+ dels++;
859
+ }
860
+ i++;
861
+ }
862
+ // Re-walk for adds, keeping their order.
863
+ let j = i - 1;
864
+ while (j >= 0 && ls[j]?.type !== " ") j--;
865
+ for (let t = j + 1; t < i; t++) {
866
+ const l = /** @type {{ type: string, text: string }} */ (ls[t]);
867
+ if (l.type === "+") {
868
+ afterLines.push(l.text);
869
+ adds++;
870
+ }
871
+ }
872
+ push("change", dels, adds);
873
+ }
874
+ }
875
+
876
+ return {
877
+ beforeLines,
878
+ afterLines,
879
+ partial: null,
880
+ blocks,
881
+ pendingA: beforeLines.length,
882
+ streaming: false,
883
+ beforeNoEol: false,
884
+ afterNoEol: false,
885
+ sealedBlocks: blocks.length,
886
+ version: 0,
887
+ beforeText: joinLines(beforeLines),
888
+ afterText: joinLines(afterLines),
889
+ };
890
+ }