All files / diff/src str.ts

100% Statements 464/464
99.67% Branches 309/310
100% Functions 19/19
100% Lines 396/396

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 74920x                               20x 22062x 22062x 21927x 9945x 9945x 9945x 9875x 9875x 33169x 33169x 33169x 33009x   9412x   533x 1003x 533x 2539x 2539x 2115x 2115x 1454x   533x     20x 44184x 44184x     20x 34664x 34664x                   20x 90190x 90190x 90190x 90190x 90190x 90190x 90190x 90190x 492761x 454x 454x   492307x 492307x   146993x 146993x 146993x 146993x   138344x 138344x 138344x 138344x   206970x 206970x                     34781x 34781x 25448x 25448x 1013x 1013x 1013x 1013x 1013x   558x 558x 558x 558x 558x 411x 411x 411x 411x   558x 416x 416x 416x   558x       34781x 34781x 34781x 979x 979x 979x 979x     206970x   602x 602x   206368x 206368x 206368x   187291x   72829x 72829x 1145x 1001x   144x 144x   1145x 1145x     72829x 72829x 1056x 1056x 1056x       187291x 187291x 187291x 187291x 310x 310x 186981x 62054x 62054x 124927x 53357x 53357x   71570x 71570x     206368x 206368x   15780x 15780x 190588x 206368x 206368x 206368x 206368x 206368x       90190x         90190x 90190x   90190x 215677x 215677x 215677x   28258x 28258x 28258x 28258x         28258x   356x 356x 356x 356x 27902x   430x 430x 430x 430x     215677x     90190x                           20x             41237x 31298x   31298x 5609x         41237x 30291x   30291x 5470x           41237x 900x               40337x 40337x 40337x             20x                 3538x 3538x 3538x                                 20x 45047x 45047x 45047x 45047x 45047x 45047x 45047x 45047x 2124438x 2124438x   45047x 45047x 45047x     45047x     45047x 45047x 45047x 45047x 45047x 45047x   45047x 45047x   388355x 177x 388178x 27415856x 27415856x 27415856x 27415856x 27415856x 2451944x 27415856x 27415856x 791129x 791129x   27415856x 27415856x 27377708x 27330359x 3651972x 3651972x 3651972x 2337358x         369958x 27312055x   27312055x 27312055x 27312055x         759821x 759821x   27312055x 27312055x 27277966x 27236156x 23615132x 23615132x 23615132x 21695127x 21695127x 21695127x         7171x 3810x                           20x 89431x 74274x 58626x 58626x 58626x 58626x 58626x 58626x 58626x 7556x 7556x 7556x                       51070x 6023x       45047x                   20x 162291x 12240x 12240x 12240x 12240x 12240x 38881x 15456x 15456x 23425x 38881x         12240x 12240x 8687x 8687x 8687x   12240x                   20x 163281x 16658x 16658x 16658x 16658x 16658x 43597x 22110x 22110x 21487x 43597x         16658x 12761x 12761x 12761x       12761x   12761x       12761x   1702x 1702x 1002x 1002x 1002x 1002x   1002x     1002x 465x       16658x                         20x 1143x 1143x 1143x 1140x 1140x 516x 516x 624x 1140x 1138x 1138x 1138x 1585x 1585x 1585x 447x 447x 119x 119x                             20x 89615x     89431x 89431x 89431x 89431x     89431x 89431x 89431x 89431x     89431x 89431x 89431x 89431x 89431x                         8941x                                         20x 609x 609x 560x 560x 560x 512x   393x 393x   512x 512x 512x 427x 427x 166x 166x 76x 76x 76x 76x   40x 40x 40x 40x 40x 40x   90x 90x 90x 90x   43x 43x 43x 43x 43x 43x     526x     20x 10636x 10636x 10636x 62877x 62877x   10636x     20x 10637x 10637x 10637x 62879x 62879x   10637x     20x 27641x 27641x                           4835x               20x           8451x 8451x 8451x 49316x 49316x 32014x   16006x 16006x 16006x        
import {bestSplit, deadlineLimits, type DiffLimits} from './limits';
 
export type {DiffLimits} from './limits';
 
export const enum PATCH_OP_TYPE {
  DEL = -1,
  EQL = 0,
  INS = 1,
}
 
export type Patch = PatchOperation[];
export type PatchOperation = PatchOperationDelete | PatchOperationEqual | PatchOperationInsert;
export type PatchOperationDelete = [type: PATCH_OP_TYPE.DEL, txt: string];
export type PatchOperationEqual = [type: PATCH_OP_TYPE.EQL, txt: string];
export type PatchOperationInsert = [type: PATCH_OP_TYPE.INS, txt: string];
 
export const normalize = (patch: Patch): Patch => {
  const length = patch.length;
  if (!length) return patch;
  if (length === 1) return patch[0][1] ? patch : [];
  let i: number = 0;
  CHECK_IS_NORMALIZED: {
    if (!patch[0][1]) break CHECK_IS_NORMALIZED;
    i = 1;
    for (; i < length; i++) {
      const prev = patch[i - 1];
      const curr = patch[i];
      if (!curr[1]) break CHECK_IS_NORMALIZED;
      if (prev[0] === curr[0]) break CHECK_IS_NORMALIZED;
    }
    return patch;
  }
  const normalized: Patch = [];
  for (let j = 0; j < i; j++) normalized.push(patch[j]);
  for (let j = i; j < length; j++) {
    const op = patch[j];
    if (!op[1]) continue;
    const last = normalized.length > 0 ? normalized[normalized.length - 1] : null;
    if (last && last[0] === op[0]) normalized[normalized.length - 1] = [last[0], last[1] + op[1]] as PatchOperation;
    else normalized.push(op);
  }
  return normalized;
};
 
const startsWithPairEnd = (str: string) => {
  const code = str.charCodeAt(0);
  return code >= 0xdc00 && code <= 0xdfff;
};
 
const endsWithPairStart = (str: string): boolean => {
  const code = str.charCodeAt(str.length - 1);
  return code >= 0xd800 && code <= 0xdbff;
};
 
/**
 * Reorder and merge like edit sections. Merge equalities.
 * Any edit section can move as long as it doesn't cross an equality.
 *
 * @param diff Array of diff tuples.
 * @param fixUnicode Whether to normalize to a unicode-correct diff
 */
const cleanupMerge = (diff: Patch, fixUnicode: boolean) => {
  diff.push([PATCH_OP_TYPE.EQL, '']);
  let pointer = 0;
  let delCnt = 0;
  let insCnt = 0;
  let delTxt = '';
  let insTxt = '';
  let commonLength: number = 0;
  while (pointer < diff.length) {
    if (pointer < diff.length - 1 && !diff[pointer][1]) {
      diff.splice(pointer, 1);
      continue;
    }
    const d1 = diff[pointer];
    switch (d1[0]) {
      case PATCH_OP_TYPE.INS:
        insCnt++;
        pointer++;
        insTxt += d1[1];
        break;
      case PATCH_OP_TYPE.DEL:
        delCnt++;
        pointer++;
        delTxt += d1[1];
        break;
      case PATCH_OP_TYPE.EQL: {
        let prevEq = pointer - insCnt - delCnt - 1;
        if (fixUnicode) {
          // prevent splitting of unicode surrogate pairs. When `fixUnicode` is true,
          // we assume that the old and new text in the diff are complete and correct
          // unicode-encoded JS strings, but the tuple boundaries may fall between
          // surrogate pairs. We fix this by shaving off stray surrogates from the end
          // of the previous equality and the beginning of this equality. This may create
          // empty equalities or a common prefix or suffix. For example, if AB and AC are
          // emojis, `[[0, 'A'], [-1, 'BA'], [0, 'C']]` would turn into deleting 'ABAC' and
          // inserting 'AC', and then the common suffix 'AC' will be eliminated.  in this
          // particular case, both equalities go away, we absorb any previous inequalities,
          // and we keep scanning for the next equality before rewriting the tuples.
          const d = diff[prevEq];
          if (prevEq >= 0) {
            let str = d[1];
            if (endsWithPairStart(str)) {
              const stray = str.slice(-1);
              d[1] = str = str.slice(0, -1);
              delTxt = stray + delTxt;
              insTxt = stray + insTxt;
              if (!str) {
                // emptied out previous equality, so delete it and include previous delete/insert
                diff.splice(prevEq, 1);
                pointer--;
                let k = prevEq - 1;
                let dk = diff[k];
                if (dk && dk[0] === PATCH_OP_TYPE.INS) {
                  insCnt++;
                  insTxt = dk[1] + insTxt;
                  k--;
                  dk = diff[k];
                }
                if (dk && dk[0] === PATCH_OP_TYPE.DEL) {
                  delCnt++;
                  delTxt = dk[1] + delTxt;
                  k--;
                }
                prevEq = k;
              }
            }
          }
          const d1 = diff[pointer];
          const str1 = d1[1];
          if (startsWithPairEnd(str1)) {
            const stray = str1.charAt(0);
            d1[1] = str1.slice(1);
            delTxt += stray;
            insTxt += stray;
          }
        }
        if (pointer < diff.length - 1 && !diff[pointer][1]) {
          // for empty equality not at end, wait for next equality
          diff.splice(pointer, 1);
          break;
        }
        const hasDelTxt = delTxt.length > 0;
        const hasInsTxt = insTxt.length > 0;
        if (hasDelTxt || hasInsTxt) {
          // note that diff_commonPrefix and diff_commonSuffix are unicode-aware
          if (hasDelTxt && hasInsTxt) {
            // Factor out any common prefixes.
            commonLength = pfx(insTxt, delTxt);
            if (commonLength !== 0) {
              if (prevEq >= 0) {
                diff[prevEq][1] += insTxt.slice(0, commonLength);
              } else {
                diff.splice(0, 0, [PATCH_OP_TYPE.EQL, insTxt.slice(0, commonLength)]);
                pointer++;
              }
              insTxt = insTxt.slice(commonLength);
              delTxt = delTxt.slice(commonLength);
            }
            // Factor out any common suffixes.
            commonLength = sfx(insTxt, delTxt);
            if (commonLength !== 0) {
              diff[pointer][1] = insTxt.slice(insTxt.length - commonLength) + diff[pointer][1];
              insTxt = insTxt.slice(0, insTxt.length - commonLength);
              delTxt = delTxt.slice(0, delTxt.length - commonLength);
            }
          }
          // Delete the offending records and add the merged ones.
          const n = insCnt + delCnt;
          const delTxtLen = delTxt.length;
          const insTxtLen = insTxt.length;
          if (delTxtLen === 0 && insTxtLen === 0) {
            diff.splice(pointer - n, n);
            pointer = pointer - n;
          } else if (delTxtLen === 0) {
            diff.splice(pointer - n, n, [PATCH_OP_TYPE.INS, insTxt]);
            pointer = pointer - n + 1;
          } else if (insTxtLen === 0) {
            diff.splice(pointer - n, n, [PATCH_OP_TYPE.DEL, delTxt]);
            pointer = pointer - n + 1;
          } else {
            diff.splice(pointer - n, n, [PATCH_OP_TYPE.DEL, delTxt], [PATCH_OP_TYPE.INS, insTxt]);
            pointer = pointer - n + 2;
          }
        }
        const d0 = diff[pointer - 1];
        if (pointer !== 0 && d0[0] === PATCH_OP_TYPE.EQL) {
          // Merge this equality with the previous one.
          d0[1] += diff[pointer][1];
          diff.splice(pointer, 1);
        } else pointer++;
        insCnt = 0;
        delCnt = 0;
        delTxt = '';
        insTxt = '';
        break;
      }
    }
  }
  if (diff[diff.length - 1][1] === '') diff.pop(); // Remove the dummy entry at the end.
 
  // Second pass: look for single edits surrounded on both sides by equalities
  // which can be shifted sideways to eliminate an equality.
  // e.g: A<ins>BA</ins>C -> <ins>AB</ins>AC
  let changes = false;
  pointer = 1;
  // Intentionally ignore the first and last element (don't need checking).
  while (pointer < diff.length - 1) {
    const d0 = diff[pointer - 1];
    const d2 = diff[pointer + 1];
    if (d0[0] === PATCH_OP_TYPE.EQL && d2[0] === PATCH_OP_TYPE.EQL) {
      // This is a single edit surrounded by equalities.
      const str0 = d0[1];
      const d1 = diff[pointer];
      const str1 = d1[1];
      const str2 = d2[1];
      // With fixUnicode, skip a shift that would recreate the exact shape the
      // first pass shaves (an equality ending with a pair start or starting
      // with a pair end), otherwise ill-formed inputs oscillate between the
      // two passes and the trailing re-sweep recursion never terminates.
      if ((!fixUnicode || !startsWithPairEnd(str0)) && str1.slice(str1.length - str0.length) === str0) {
        // Shift the edit over the previous equality.
        diff[pointer][1] = str0 + str1.slice(0, str1.length - str0.length);
        d2[1] = str0 + str2;
        diff.splice(pointer - 1, 1);
        changes = true;
      } else if ((!fixUnicode || !endsWithPairStart(str2)) && str1.slice(0, str2.length) === str2) {
        // Shift the edit over the next equality.
        d0[1] += d2[1];
        d1[1] = str1.slice(str2.length) + str2;
        diff.splice(pointer + 1, 1);
        changes = true;
      }
    }
    pointer++;
  }
  // If shifts were made, the diff needs reordering and another shift sweep.
  if (changes) cleanupMerge(diff, fixUnicode);
};
 
/**
 * Given the location of the 'middle snake', split the diff in two parts
 * and recurse.
 *
 * @param text1 Old string to be diffed.
 * @param text2 New string to be diffed.
 * @param x Index of split point in text1.
 * @param y Index of split point in text2.
 * @param limits Optional bounds, carried into both halves.
 * @return Array of diff tuples.
 */
const bisectSplit = (text1: string, text2: string, x: number, y: number, limits?: DiffLimits): Patch => {
  // Adjust split points to avoid breaking surrogate pairs.
  // The bisect algorithm uses .charAt() which operates on UTF-16 code units,
  // so the split points (x, y) might fall in the middle of a surrogate pair.
  // We need to adjust them to ensure we don't split emoji or other multi-unit characters.
 
  // If x is in the middle of a surrogate pair in text1, move it back
  if (x > 0 && x < text1.length) {
    const code = text1.charCodeAt(x);
    // If x points to a low surrogate, we're splitting a pair
    if (code >= 0xdc00 && code <= 0xdfff) {
      x--;
    }
  }
 
  // If y is in the middle of a surrogate pair in text2, move it back
  if (y > 0 && y < text2.length) {
    const code = text2.charCodeAt(y);
    // If y points to a low surrogate, we're splitting a pair
    if (code >= 0xdc00 && code <= 0xdfff) {
      y--;
    }
  }
 
  // A degenerate split (possible with ill-formed inputs) would recurse on the
  // same pair of strings forever; bail out with a trivial diff instead.
  if ((x === 0 && y === 0) || (x === text1.length && y === text2.length)) {
    return [
      [PATCH_OP_TYPE.DEL, text1],
      [PATCH_OP_TYPE.INS, text2],
    ];
  }
 
  // Use fixUnicode: true to ensure the recursive diffs also handle Unicode properly.
  // This prevents issues where surrogate pairs might be split at diff boundaries.
  const diffsA = diff_(text1.slice(0, x), text2.slice(0, y), false, limits);
  const diffsB = diff_(text1.slice(x), text2.slice(y), false, limits);
  return diffsA.concat(diffsB);
};
 
// A bound was hit: split at the best diagonal reached instead of searching on.
// A degenerate split point is `bisectSplit`'s trivial case, which terminates.
// `sub` is what the two halves are diffed under, which is the caller's own
// limits except when an expired clock hands them a cost bound instead.
const degrade = (
  text1: string,
  text2: string,
  v1: number[],
  v2: number[],
  vOffset: number,
  limits?: DiffLimits,
  sub: DiffLimits | undefined = limits,
): Patch => {
  Eif (limits) limits.hitLimit = true;
  const [x, y] = bestSplit(v1, v2, vOffset, text1.length, text2.length);
  return bisectSplit(text1, text2, x, y, sub);
};
 
/**
 * Find the 'middle snake' of a diff, split the problem in two
 * and return the recursively constructed diff.
 *
 * This is a port of `diff-patch-match` implementation to TypeScript.
 *
 * @see http://www.xmailserver.org/diff2.pdf EUGENE W. MYERS 1986 paper: An
 *     O(ND) Difference Algorithm and Its Variations.
 *
 * @param text1 Old string to be diffed.
 * @param text2 New string to be diffed.
 * @param limits Optional bounds on the `d` loop.
 * @return A {@link Patch} - an array of patch operations.
 */
const bisect = (text1: string, text2: string, limits?: DiffLimits): Patch => {
  const text1Length = text1.length;
  const text2Length = text2.length;
  const maxD = Math.ceil((text1Length + text2Length) / 2);
  const vOffset = maxD;
  const vLength = 2 * maxD;
  const v1 = new Array(vLength);
  const v2 = new Array(vLength);
  for (let x = 0; x < vLength; x++) {
    v1[x] = -1;
    v2[x] = -1;
  }
  v1[vOffset + 1] = 0;
  v2[vOffset + 1] = 0;
  const delta = text1Length - text2Length;
  // If the total number of characters is odd, then the front path will collide
  // with the reverse path.
  const front = delta % 2 !== 0;
  // Offsets for start and end of k loop.
  // Prevents mapping of space beyond the grid.
  let k1start = 0;
  let k1end = 0;
  let k2start = 0;
  let k2end = 0;
  const maxCost = limits?.maxCost;
  const deadline = limits?.deadline;
  // NaN and negative budgets collapse to zero: a bad budget must still bound.
  const bound = maxCost === undefined || maxCost >= maxD ? maxD : maxCost > 0 ? maxCost : 0;
  for (let d = 0; d < bound; d++) {
    // The ranges below inherit a cost bound rather than the dead clock.
    if (deadline !== undefined && !deadline.isValid())
      return degrade(text1, text2, v1, v2, vOffset, limits, deadlineLimits(text1Length, text2Length));
    for (let k1 = -d + k1start; k1 <= d - k1end; k1 += 2) {
      const k1_offset = vOffset + k1;
      let x1: number = 0;
      const v10 = v1[k1_offset - 1];
      const v11 = v1[k1_offset + 1];
      if (k1 === -d || (k1 !== d && v10 < v11)) x1 = v11;
      else x1 = v10 + 1;
      let y1 = x1 - k1;
      while (x1 < text1Length && y1 < text2Length && text1.charAt(x1) === text2.charAt(y1)) {
        x1++;
        y1++;
      }
      v1[k1_offset] = x1;
      if (x1 > text1Length) k1end += 2;
      else if (y1 > text2Length) k1start += 2;
      else if (front) {
        const k2Offset = vOffset + delta - k1;
        const v2Offset = v2[k2Offset];
        if (k2Offset >= 0 && k2Offset < vLength && v2Offset !== -1) {
          if (x1 >= text1Length - v2Offset) return bisectSplit(text1, text2, x1, y1, limits);
        }
      }
    }
    // Walk the reverse path one step.
    for (let k2 = -d + k2start; k2 <= d - k2end; k2 += 2) {
      const k2_offset = vOffset + k2;
      let x2 =
        k2 === -d || (k2 !== d && v2[k2_offset - 1] < v2[k2_offset + 1]) ? v2[k2_offset + 1] : v2[k2_offset - 1] + 1;
      let y2 = x2 - k2;
      while (
        x2 < text1Length &&
        y2 < text2Length &&
        text1.charAt(text1Length - x2 - 1) === text2.charAt(text2Length - y2 - 1)
      ) {
        x2++;
        y2++;
      }
      v2[k2_offset] = x2;
      if (x2 > text1Length) k2end += 2;
      else if (y2 > text2Length) k2start += 2;
      else if (!front) {
        const k1_offset = vOffset + delta - k2;
        const x1 = v1[k1_offset];
        if (k1_offset >= 0 && k1_offset < vLength && x1 !== -1) {
          const y1 = vOffset + x1 - k1_offset;
          x2 = text1Length - x2;
          if (x1 >= x2) return bisectSplit(text1, text2, x1, y1, limits);
        }
      }
    }
  }
  if (bound < maxD) return degrade(text1, text2, v1, v2, vOffset, limits);
  return [
    [PATCH_OP_TYPE.DEL, text1],
    [PATCH_OP_TYPE.INS, text2],
  ];
};
 
/**
 * Find the differences between two texts. Assumes that the texts do not
 * have any common prefix or suffix.
 *
 * @param src Old string to be diffed.
 * @param dst New string to be diffed.
 * @return A {@link Patch} - an array of patch operations.
 */
const diffNoCommonAffix = (src: string, dst: string, limits?: DiffLimits): Patch => {
  if (!src) return [[PATCH_OP_TYPE.INS, dst]];
  if (!dst) return [[PATCH_OP_TYPE.DEL, src]];
  const text1Length = src.length;
  const text2Length = dst.length;
  const long = text1Length > text2Length ? src : dst;
  const short = text1Length > text2Length ? dst : src;
  const shortTextLength = short.length;
  const indexOfContainedShort = long.indexOf(short);
  if (indexOfContainedShort >= 0) {
    const start = long.slice(0, indexOfContainedShort);
    const end = long.slice(indexOfContainedShort + shortTextLength);
    return text1Length > text2Length
      ? [
          [PATCH_OP_TYPE.DEL, start],
          [PATCH_OP_TYPE.EQL, short],
          [PATCH_OP_TYPE.DEL, end],
        ]
      : [
          [PATCH_OP_TYPE.INS, start],
          [PATCH_OP_TYPE.EQL, short],
          [PATCH_OP_TYPE.INS, end],
        ];
  }
  if (shortTextLength === 1)
    return [
      [PATCH_OP_TYPE.DEL, src],
      [PATCH_OP_TYPE.INS, dst],
    ];
  return bisect(src, dst, limits);
};
 
/**
 * Determine the common prefix of two strings.
 *
 * @param txt1 First string.
 * @param txt2 Second string.
 * @return The number of characters common to the start of each string.
 */
export const pfx = (txt1: string, txt2: string): number => {
  if (!txt1 || !txt2 || txt1.charAt(0) !== txt2.charAt(0)) return 0;
  let min = 0;
  let max = Math.min(txt1.length, txt2.length);
  let mid = max;
  let start = 0;
  while (min < mid) {
    if (txt1.slice(start, mid) === txt2.slice(start, mid)) {
      min = mid;
      start = min;
    } else max = mid;
    mid = Math.floor((max - min) / 2 + min);
  }
  // Back off only when the boundary actually splits a surrogate pair: the
  // prefix ends with a high surrogate and either string continues with a low
  // surrogate. A lone high surrogate (ill-formed input) is left alone.
  const code = txt1.charCodeAt(mid - 1);
  if (code >= 0xd800 && code <= 0xdbff) {
    const next1 = txt1.charCodeAt(mid);
    const next2 = txt2.charCodeAt(mid);
    if ((next1 >= 0xdc00 && next1 <= 0xdfff) || (next2 >= 0xdc00 && next2 <= 0xdfff)) mid--;
  }
  return mid;
};
 
/**
 * Determine the common suffix of two strings.
 *
 * @param txt1 First string.
 * @param txt2 Second string.
 * @return The number of characters common to the end of each string.
 */
export const sfx = (txt1: string, txt2: string): number => {
  if (!txt1 || !txt2 || txt1.slice(-1) !== txt2.slice(-1)) return 0;
  let min = 0;
  let max = Math.min(txt1.length, txt2.length);
  let mid = max;
  let end = 0;
  while (min < mid) {
    if (txt1.slice(txt1.length - mid, txt1.length - end) === txt2.slice(txt2.length - mid, txt2.length - end)) {
      min = mid;
      end = min;
    } else max = mid;
    mid = Math.floor((max - min) / 2 + min);
  }
  // Check if we're splitting a surrogate pair or combining character sequence
  // We need to check the character BEFORE the matched suffix to see if we're
  // splitting a grapheme cluster.
  if (mid > 0 && mid < txt1.length) {
    const boundaryPos = txt1.length - mid - 1;
    const code = txt1.charCodeAt(boundaryPos);
    const next = txt1.charCodeAt(boundaryPos + 1);
    // Back off only when the boundary actually splits a surrogate pair: a
    // high surrogate right before a low surrogate. A lone high surrogate
    // (ill-formed input) is left alone.
    const isSplitPair = code >= 0xd800 && code <= 0xdbff && next >= 0xdc00 && next <= 0xdfff;
    const isCombining =
      code === 0x200d || // ZWJ
      (code >= 0xfe00 && code <= 0xfe0f) || // Variation selectors
      (code >= 0x0300 && code <= 0x036f); // Combining diacritical marks
 
    if (isSplitPair || isCombining) {
      // We're splitting a grapheme cluster. Walk backwards to include the full cluster.
      mid--;
      while (mid > 0) {
        const pos = txt1.length - mid - 1;
        const prevCode = txt1.charCodeAt(pos);
        const prevNext = txt1.charCodeAt(pos + 1);
        const isPrevSplitPair = prevCode >= 0xd800 && prevCode <= 0xdbff && prevNext >= 0xdc00 && prevNext <= 0xdfff;
        const isPrevCombining =
          prevCode === 0x200d ||
          (prevCode >= 0xfe00 && prevCode <= 0xfe0f) ||
          (prevCode >= 0x0300 && prevCode <= 0x036f);
        if (!isPrevSplitPair && !isPrevCombining) break;
        mid--;
      }
    }
  }
  return mid;
};
 
/**
 * Determine if the suffix of one string is the prefix of another.
 *
 * @see http://neil.fraser.name/news/2010/11/04/
 *
 * @param str1 First string.
 * @param str2 Second string.
 * @return {number} The number of characters common to the end of the first
 *     string and the start of the second string.
 */
export const overlap = (str1: string, str2: string): number => {
  const str1Len = str1.length;
  const str2Len = str2.length;
  if (str1Len === 0 || str2Len === 0) return 0;
  let minLen = str1Len;
  if (str1Len > str2Len) {
    minLen = str2Len;
    str1 = str1.substring(str1Len - str2Len);
  } else if (str1Len < str2Len) str2 = str2.substring(0, str1Len);
  if (str1 === str2) return minLen;
  let best = 0;
  let length = 1;
  while (true) {
    const pattern = str1.substring(minLen - length);
    const found = str2.indexOf(pattern);
    if (found === -1) return best;
    length += found;
    if (found === 0 || str1.substring(minLen - length) === str2.substring(0, length)) {
      best = length;
      length++;
    }
  }
};
 
/**
 * Find the differences between two texts. Simplifies the problem by stripping
 * any common prefix or suffix off the texts before diffing.
 *
 * @param src Old string to be diffed.
 * @param dst New string to be diffed.
 * @param fixUnicode Whether to apply semantic cleanup before returning.
 * @param limits Optional bounds on the Myers search.
 * @return A {@link Patch} - an array of patch operations.
 */
const diff_ = (src: string, dst: string, fixUnicode: boolean, limits?: DiffLimits): Patch => {
  if (src === dst) return src ? [[PATCH_OP_TYPE.EQL, src]] : [];
 
  // Trim off common prefix (speedup).
  const prefixLength = pfx(src, dst);
  const prefix = src.slice(0, prefixLength);
  src = src.slice(prefixLength);
  dst = dst.slice(prefixLength);
 
  // Trim off common suffix (speedup).
  const suffixLength = sfx(src, dst);
  const suffix = src.slice(src.length - suffixLength);
  src = src.slice(0, src.length - suffixLength);
  dst = dst.slice(0, dst.length - suffixLength);
 
  // Compute the diff on the middle block.
  const diff: Patch = diffNoCommonAffix(src, dst, limits);
  if (prefix) diff.unshift([PATCH_OP_TYPE.EQL, prefix]);
  if (suffix) diff.push([PATCH_OP_TYPE.EQL, suffix]);
  cleanupMerge(diff, fixUnicode);
  return diff;
};
 
/**
 * Find the differences between two texts.
 *
 * @param src Old string to be diffed.
 * @param dst New string to be diffed.
 * @param limits Optional bounds; without them the patch is minimal. When a
 *     bound is hit the patch is near-minimal instead, and
 *     {@link DiffLimits.hitLimit} is set on the passed object.
 * @return A {@link Patch} - an array of patch operations.
 */
export const diff = (src: string, dst: string, limits?: DiffLimits): Patch => diff_(src, dst, true, limits);
 
/**
 * Considers simple insertion and deletion cases around the caret position in
 * the destination string. If the fast patch cannot be constructed, it falls
 * back to the default full implementation.
 *
 * Cases considered:
 *
 * 1. Insertion of a single or multiple characters right before the caret.
 * 2. Deletion of one or more characters right before the caret.
 *
 * @param src Old string to be diffed.
 * @param dst New string to be diffed.
 * @param caret The position of the caret in the new string (`dst`).
 *     Out-of-range values are tolerated; a caret pointing inside a surrogate
 *     pair is rounded down to the pair boundary. Set to -1 to ignore the
 *     caret position.
 * @param limits Optional bounds, used only when the fast path does not apply.
 * @return A {@link Patch} - an array of patch operations.
 */
export const diffEdit = (src: string, dst: string, caret: number, limits?: DiffLimits) => {
  edit: {
    if (caret < 0) break edit;
    const srcLen = src.length;
    const dstLen = dst.length;
    if (srcLen === dstLen) break edit;
    if (caret > 0 && caret < dstLen) {
      // Round a caret inside a surrogate pair down to the pair boundary.
      const code = dst.charCodeAt(caret);
      if (code >= 0xdc00 && code <= 0xdfff) caret--;
    }
    const dstSfx = dst.slice(caret);
    const sfxLen = dstSfx.length;
    if (sfxLen > srcLen) break edit;
    const srcSfx = src.slice(srcLen - sfxLen);
    if (srcSfx !== dstSfx) break edit;
    const isInsert = dstLen > srcLen;
    if (isInsert) {
      const pfxLen = srcLen - sfxLen;
      const srcPfx = src.slice(0, pfxLen);
      const dstPfx = dst.slice(0, pfxLen);
      if (srcPfx !== dstPfx) break edit;
      // insert.length === dstLen - srcLen > 0
      const insert = dst.slice(pfxLen, caret);
      const patch: Patch = [];
      if (srcPfx) patch.push([PATCH_OP_TYPE.EQL, srcPfx]);
      patch.push([PATCH_OP_TYPE.INS, insert]);
      if (dstSfx) patch.push([PATCH_OP_TYPE.EQL, dstSfx]);
      return patch;
    } else {
      const pfxLen = dstLen - sfxLen;
      const dstPfx = dst.slice(0, pfxLen);
      const srcPfx = src.slice(0, pfxLen);
      if (srcPfx !== dstPfx) break edit;
      // del.length === srcLen - dstLen > 0
      const del = src.slice(pfxLen, srcLen - sfxLen);
      const patch: Patch = [];
      if (srcPfx) patch.push([PATCH_OP_TYPE.EQL, srcPfx]);
      patch.push([PATCH_OP_TYPE.DEL, del]);
      if (dstSfx) patch.push([PATCH_OP_TYPE.EQL, dstSfx]);
      return patch;
    }
  }
  return diff(src, dst, limits);
};
 
export const src = (patch: Patch): string => {
  let txt = '';
  const length = patch.length;
  for (let i = 0; i < length; i++) {
    const op = patch[i];
    if (op[0] !== PATCH_OP_TYPE.INS) txt += op[1];
  }
  return txt;
};
 
export const dst = (patch: Patch): string => {
  let txt = '';
  const length = patch.length;
  for (let i = 0; i < length; i++) {
    const op = patch[i];
    if (op[0] !== PATCH_OP_TYPE.DEL) txt += op[1];
  }
  return txt;
};
 
const invertOp = (op: PatchOperation): PatchOperation => {
  const type = op[0];
  return type === PATCH_OP_TYPE.EQL
    ? [PATCH_OP_TYPE.EQL, op[1]]
    : type === PATCH_OP_TYPE.INS
      ? [PATCH_OP_TYPE.DEL, op[1]]
      : [PATCH_OP_TYPE.INS, op[1]];
};
 
/**
 * Inverts patch such that it can be applied to `dst` to get `src` (instead of
 * `src` to get `dst`).
 *
 * @param patch The patch to invert.
 * @returns Inverted patch.
 */
export const invert = (patch: Patch): Patch => patch.map(invertOp);
 
/**
 * @param patch The patch to apply.
 * @param srcLen The length of the source string.
 * @param onInsert Callback for insert operations.
 * @param onDelete Callback for delete operations.
 */
export const apply = (
  patch: Patch,
  srcLen: number,
  onInsert: (pos: number, str: string) => void,
  onDelete: (pos: number, len: number, str: string) => void,
) => {
  const length = patch.length;
  let pos = srcLen;
  for (let i = length - 1; i >= 0; i--) {
    const [type, str] = patch[i];
    if (type === PATCH_OP_TYPE.EQL) pos -= str.length;
    else if (type === PATCH_OP_TYPE.INS) onInsert(pos, str);
    else {
      const len = str.length;
      pos -= len;
      onDelete(pos, len, str);
    }
  }
};