UNPKG

@fishan/myers-core-diff

Version:

A high-performance core diff engine based on Myers' algorithm, with plugin support for custom strategies (e.g., Patience, Preserve Structure).

8 lines (7 loc) 2.38 kB
/** * @license * Copyright (c) 2025, Internal Implementation * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */import{DiffOperation as _}from"./myers_core_diff.js";const s=!1,N={minMatchLength:2,quickDiffThreshold:16,hugeDiffThreshold:64,jumpStep:1,huntChunkSize:2,minAnchorConfidence:.7,useAnchors:!0},U={minMatchLength:30,huntChunkSize:10,jumpStep:10,minAnchorConfidence:.75,useAnchors:!0,quickDiffThreshold:32,hugeDiffThreshold:128,anchorSearchMode:"floating",preservePositions:!0};function G(t,n,u,l,a,p){const r=new Set(t.subarray(n,u));if(r.size===0)return!1;for(let c=a;c<p;c++)if(r.has(l[c]))return!0;return!1}function C(t,n,u,l,a,p,r,c,f,o){const A=[];let g=u,h=p;for(;g<l&&h<r;){const e=t._findNextLocalAnchor(n,g,l,a,h,r,f.localLookahead||50,o),P=e?.oldPos??l,i=e?.newPos??r;if(P>g||i>h){const D=O(t,n,g,P,a,h,i,c,f,o);A.push(...D)}e?(A.push([_.EQUAL,c[n[e.oldPos]]]),g=e.oldPos+1,h=e.newPos+1):(g=l,h=r)}if(g<l)for(let e=g;e<l;e++)A.push([_.REMOVE,c[n[e]]]);if(h<r)for(let e=h;e<r;e++)A.push([_.ADD,c[a[e]]]);return A}function O(t,n,u,l,a,p,r,c,f,o){const A=l-u,g=r-p,h=A+g;if(h===0)return[];if(!G(n,u,l,a,p,r))return t._guidedCalculateDiff(n,u,l,a,p,r,c,f,o);if(h>=f.quickDiffThreshold/2){const i={...f,...N},D=t._findAnchors(n,u,l,a,p,r,i,o),S=t._mergeAndFilterAnchors(D,i,o);if(S.length>0){const y=[];let m=u,$=p;for(const L of S){if(L.oldPos>m||L.newPos>$){const R=O(t,n,m,L.oldPos,a,$,L.newPos,c,f,o);y.push(...R)}for(let R=0;R<L.length;R++)y.push([_.EQUAL,c[n[L.oldPos+R]]]);m=L.oldPos+L.length,$=L.newPos+L.length}if(m<l||$<r){const L=O(t,n,m,l,a,$,r,c,f,o);y.push(...L)}return y}}return t._guidedCalculateDiff(n,u,l,a,p,r,c,f,o)}const b=(t,n,u,l,a,p,r,c,f,o)=>{const A=l-u+(r-p);let g=[];if(f.useAnchors&&A>f.quickDiffThreshold){const e={...f,...U},P=t._findAnchors(n,u,l,a,p,r,e,o);g=t._mergeAndFilterAnchors(P,f,o)}const h=[];if(g.length>0){let e=u,P=p;for(const i of g){if(i.oldPos>e||i.newPos>P){const D=C(t,n,e,i.oldPos,a,P,i.newPos,c,f,o);h.push(...D)}for(let D=0;D<i.length;D++)h.push([_.EQUAL,c[n[i.oldPos+D]]]);e=i.oldPos+i.length,P=i.newPos+i.length}if(e<l||P<r){const i=C(t,n,e,l,a,P,r,c,f,o);h.push(...i)}}else{const e=C(t,n,u,l,a,p,r,c,f,o);h.push(...e)}return h};function z(t){t.registerStrategy("preserveStructure",b)}export{z as registerPreserveStructureStrategy};