UNPKG

@circuitly/diff

Version:

A javascript text diff implementation.

1 lines 32.4 kB
((global,factory)=>{"object"==typeof exports&&"undefined"!=typeof module?factory(exports):"function"==typeof define&&define.amd?define(["exports"],factory):factory((global="undefined"!=typeof globalThis?globalThis:global||self).Diff={})})(this,function(exports){function Diff(){}function buildValues(diff,lastComponent,newString,oldString,useLongestToken){for(var nextComponent,components=[];lastComponent;)components.push(lastComponent),nextComponent=lastComponent.previousComponent,delete lastComponent.previousComponent,lastComponent=nextComponent;components.reverse();for(var componentPos=0,componentLen=components.length,newPos=0,oldPos=0;componentPos<componentLen;componentPos++){var value,component=components[componentPos];component.removed?(component.value=diff.join(oldString.slice(oldPos,oldPos+component.count)),oldPos+=component.count):(!component.added&&useLongestToken?(value=(value=newString.slice(newPos,newPos+component.count)).map(function(value,i){i=oldString[oldPos+i];return i.length>value.length?i:value}),component.value=diff.join(value)):component.value=diff.join(newString.slice(newPos,newPos+component.count)),newPos+=component.count,component.added||(oldPos+=component.count))}return components}Diff.prototype={diff:function(oldString,newString){var options=2<arguments.length&&void 0!==arguments[2]?arguments[2]:{},callback=options.callback,self=("function"==typeof options&&(callback=options,options={}),this);function done(value){if(value=self.postProcess(value,options),!callback)return value;setTimeout(function(){callback(value)},0)}oldString=this.castInput(oldString,options),newString=this.castInput(newString,options),oldString=this.removeEmpty(this.tokenize(oldString,options));var newLen=(newString=this.removeEmpty(this.tokenize(newString,options))).length,oldLen=oldString.length,editLength=1,maxEditLength=newLen+oldLen,_options$timeout=(null!=options.maxEditLength&&(maxEditLength=Math.min(maxEditLength,options.maxEditLength)),null!=(_options$timeout=options.timeout)?_options$timeout:1/0),abortAfterTimestamp=Date.now()+_options$timeout,bestPath=[{oldPos:-1,lastComponent:void 0}],newPos=this.extractCommon(bestPath[0],newString,oldString,0,options);if(bestPath[0].oldPos+1>=oldLen&&newLen<=newPos+1)return done(buildValues(self,bestPath[0].lastComponent,newString,oldString,self.useLongestToken));var minDiagonalToConsider=-1/0,maxDiagonalToConsider=1/0;function execEditLength(){for(var diagonalPath=Math.max(minDiagonalToConsider,-editLength);diagonalPath<=Math.min(maxDiagonalToConsider,editLength);diagonalPath+=2){var basePath=void 0,removePath=bestPath[diagonalPath-1],addPath=bestPath[diagonalPath+1],canAdd=(removePath&&(bestPath[diagonalPath-1]=void 0),!1),addPathNewPos=(addPath&&(addPathNewPos=addPath.oldPos-diagonalPath,canAdd=addPath&&0<=addPathNewPos&&addPathNewPos<newLen),removePath&&removePath.oldPos+1<oldLen);if(canAdd||addPathNewPos){if(basePath=!addPathNewPos||canAdd&&removePath.oldPos<addPath.oldPos?self.addToPath(addPath,!0,!1,0,options):self.addToPath(removePath,!1,!0,1,options),newPos=self.extractCommon(basePath,newString,oldString,diagonalPath,options),options.returnPartialResults&&Date.now()>abortAfterTimestamp)return options.gotPartialResults=!0,done(buildValues(self,basePath.lastComponent,newString,oldString,self.useLongestToken));if(basePath.oldPos+1>=oldLen&&newLen<=newPos+1)return done(buildValues(self,basePath.lastComponent,newString,oldString,self.useLongestToken))||!0;(bestPath[diagonalPath]=basePath).oldPos+1>=oldLen&&(maxDiagonalToConsider=Math.min(maxDiagonalToConsider,diagonalPath-1)),newLen<=newPos+1&&(minDiagonalToConsider=Math.max(minDiagonalToConsider,diagonalPath+1))}else bestPath[diagonalPath]=void 0}editLength++}var abortAfterTimestamp2=options.returnPartialResults?abortAfterTimestamp+1.25*(null!=(_options$timeout=null==(_options$timeout=options)?void 0:_options$timeout.timeout)?_options$timeout:0):abortAfterTimestamp;if(callback)!function exec(){setTimeout(function(){if(maxEditLength<editLength||Date.now()>abortAfterTimestamp2)return callback();execEditLength()||exec()},0)}();else for(;editLength<=maxEditLength&&Date.now()<=abortAfterTimestamp2;){var ret=execEditLength();if(ret)return ret}},addToPath:function(path,added,removed,oldPosInc,options){var last=path.lastComponent;return last&&!options.oneChangePerToken&&last.added===added&&last.removed===removed?{oldPos:path.oldPos+oldPosInc,lastComponent:{count:last.count+1,added:added,removed:removed,previousComponent:last.previousComponent}}:{oldPos:path.oldPos+oldPosInc,lastComponent:{count:1,added:added,removed:removed,previousComponent:last}}},extractCommon:function(basePath,newString,oldString,diagonalPath,options){for(var newLen=newString.length,oldLen=oldString.length,oldPos=basePath.oldPos,newPos=oldPos-diagonalPath,commonCount=0;newPos+1<newLen&&oldPos+1<oldLen&&this.equals(oldString[oldPos+1],newString[newPos+1],options);)newPos++,oldPos++,commonCount++,options.oneChangePerToken&&(basePath.lastComponent={count:1,previousComponent:basePath.lastComponent,added:!1,removed:!1});return commonCount&&!options.oneChangePerToken&&(basePath.lastComponent={count:commonCount,previousComponent:basePath.lastComponent,added:!1,removed:!1}),basePath.oldPos=oldPos,newPos},equals:function(left,right,options){return options.comparator?options.comparator(left,right):left===right||options.ignoreCase&&left.toLowerCase()===right.toLowerCase()},removeEmpty:function(array){for(var ret=[],i=0;i<array.length;i++)array[i]&&ret.push(array[i]);return ret},castInput:function(value){return value},tokenize:function(value){return Array.from(value)},join:function(chars){return chars.join("")},postProcess:function(changeObjects){return changeObjects}};var characterDiff=new Diff;function longestCommonPrefix(str1,str2){for(var i=0;i<str1.length&&i<str2.length;i++)if(str1[i]!=str2[i])return str1.slice(0,i);return str1.slice(0,i)}function longestCommonSuffix(str1,str2){var i;if(!str1||!str2||str1[str1.length-1]!=str2[str2.length-1])return"";for(i=0;i<str1.length&&i<str2.length;i++)if(str1[str1.length-(i+1)]!=str2[str2.length-(i+1)])return str1.slice(-i);return str1.slice(-i)}function replacePrefix(string,oldPrefix,newPrefix){if(string.slice(0,oldPrefix.length)!=oldPrefix)throw Error("string ".concat(JSON.stringify(string)," doesn't start with prefix ").concat(JSON.stringify(oldPrefix),"; this is a bug"));return newPrefix+string.slice(oldPrefix.length)}function replaceSuffix(string,oldSuffix,newSuffix){if(!oldSuffix)return string+newSuffix;if(string.slice(-oldSuffix.length)!=oldSuffix)throw Error("string ".concat(JSON.stringify(string)," doesn't end with suffix ").concat(JSON.stringify(oldSuffix),"; this is a bug"));return string.slice(0,-oldSuffix.length)+newSuffix}function removePrefix(string,oldPrefix){return replacePrefix(string,oldPrefix,"")}function removeSuffix(string,oldSuffix){return replaceSuffix(string,oldSuffix,"")}function maximumOverlap(string1,string2){return string2.slice(0,((a,b)=>{var startA=0,endB=(a.length>b.length&&(startA=a.length-b.length),b.length),map=(a.length<b.length&&(endB=a.length),Array(endB)),k=0;map[0]=0;for(var j=1;j<endB;j++){for(b[j]==b[k]?map[j]=map[k]:map[j]=k;0<k&&b[j]!=b[k];)k=map[k];b[j]==b[k]&&k++}k=0;for(var i=startA;i<a.length;i++){for(;0<k&&a[i]!=b[k];)k=map[k];a[i]==b[k]&&k++}return k})(string1,string2))}function trailingWs(string){for(var i=string.length-1;0<=i&&string[i].match(/\s/);i--);return string.substring(i+1)}function leadingWs(string){return string.match(/^\s*/)[0]}var extendedWordChars="a-zA-Z0-9_\\u{C0}-\\u{FF}\\u{D8}-\\u{F6}\\u{F8}-\\u{2C6}\\u{2C8}-\\u{2D7}\\u{2DE}-\\u{2FF}\\u{1E00}-\\u{1EFF}",tokenizeIncludingWhitespace=new RegExp("[".concat(extendedWordChars,"]+|\\s+|[^").concat(extendedWordChars,"]"),"ug"),wordDiff=new Diff;function dedupeWhitespaceInChangeObjects(startKeep,deletion,insertion,endKeep){var newWsSuffix,oldWsSuffix,newWsPrefix,oldWsPrefix;deletion&&insertion?(oldWsPrefix=leadingWs(deletion.value),oldWsSuffix=trailingWs(deletion.value),newWsPrefix=leadingWs(insertion.value),newWsSuffix=trailingWs(insertion.value),startKeep&&(oldWsPrefix=longestCommonPrefix(oldWsPrefix,newWsPrefix),startKeep.value=replaceSuffix(startKeep.value,newWsPrefix,oldWsPrefix),deletion.value=removePrefix(deletion.value,oldWsPrefix),insertion.value=removePrefix(insertion.value,oldWsPrefix)),endKeep&&(newWsPrefix=longestCommonSuffix(oldWsSuffix,newWsSuffix),endKeep.value=replacePrefix(endKeep.value,newWsSuffix,newWsPrefix),deletion.value=removeSuffix(deletion.value,newWsPrefix),insertion.value=removeSuffix(insertion.value,newWsPrefix))):insertion?(startKeep&&(oldWsPrefix=leadingWs(insertion.value),insertion.value=insertion.value.substring(oldWsPrefix.length)),endKeep&&(oldWsSuffix=leadingWs(endKeep.value),endKeep.value=endKeep.value.substring(oldWsSuffix.length))):startKeep&&endKeep?(newWsSuffix=leadingWs(endKeep.value),newWsPrefix=leadingWs(deletion.value),insertion=trailingWs(deletion.value),oldWsPrefix=longestCommonPrefix(newWsSuffix,newWsPrefix),deletion.value=removePrefix(deletion.value,oldWsPrefix),oldWsSuffix=longestCommonSuffix(removePrefix(newWsSuffix,oldWsPrefix),insertion),deletion.value=removeSuffix(deletion.value,oldWsSuffix),endKeep.value=replacePrefix(endKeep.value,newWsSuffix,oldWsSuffix),startKeep.value=replaceSuffix(startKeep.value,newWsSuffix,newWsSuffix.slice(0,newWsSuffix.length-oldWsSuffix.length))):endKeep?(newWsPrefix=leadingWs(endKeep.value),oldWsPrefix=maximumOverlap(trailingWs(deletion.value),newWsPrefix),deletion.value=removeSuffix(deletion.value,oldWsPrefix)):startKeep&&(insertion=maximumOverlap(trailingWs(startKeep.value),leadingWs(deletion.value)),deletion.value=removePrefix(deletion.value,insertion))}wordDiff.equals=function(left,right,options){return options.ignoreCase&&(left=left.toLowerCase(),right=right.toLowerCase()),left.trim()===right.trim()},wordDiff.tokenize=function(value){var parts,options=1<arguments.length&&void 0!==arguments[1]?arguments[1]:{};if(options.intlSegmenter){if("word"!=options.intlSegmenter.resolvedOptions().granularity)throw new Error('The segmenter passed must have a granularity of "word"');parts=Array.from(options.intlSegmenter.segment(value),function(segment){return segment.segment})}else parts=value.match(tokenizeIncludingWhitespace)||[];var tokens=[],prevPart=null;return parts.forEach(function(part){/\s/.test(part)?tokens.push(null==prevPart?part:tokens.pop()+part):/\s/.test(prevPart)?tokens.push(tokens[tokens.length-1]==prevPart?tokens.pop()+part:prevPart+part):tokens.push(part),prevPart=part}),tokens},wordDiff.join=function(tokens){return tokens.map(function(token,i){return 0==i?token:token.replace(/^\s+/,"")}).join("")},wordDiff.postProcess=function(changes,options){var lastKeep,insertion,deletion;return changes&&!options.oneChangePerToken&&(deletion=insertion=lastKeep=null,changes.forEach(function(change){change.added?insertion=change:deletion=change.removed?change:((insertion||deletion)&&dedupeWhitespaceInChangeObjects(lastKeep,deletion,insertion,change),lastKeep=change,insertion=null)}),insertion||deletion)&&dedupeWhitespaceInChangeObjects(lastKeep,deletion,insertion,null),changes};var wordWithSpaceDiff=new Diff;function diffWordsWithSpace(oldStr,newStr,options){return wordWithSpaceDiff.diff(oldStr,newStr,options)}wordWithSpaceDiff.tokenize=function(value){var regex=new RegExp("(\\r?\\n)|[".concat(extendedWordChars,"]+|[^\\S\\n\\r]+|[^").concat(extendedWordChars,"]"),"ug");return value.match(regex)||[]};var lineDiff=new Diff;function diffLines(oldStr,newStr,callback){return lineDiff.diff(oldStr,newStr,callback)}lineDiff.tokenize=function(value,options){var retLines=[],linesAndNewlines=(value=options.stripTrailingCr?value.replace(/\r\n/g,"\n"):value).split(/(\n|\r\n)/);linesAndNewlines[linesAndNewlines.length-1]||linesAndNewlines.pop();for(var i=0;i<linesAndNewlines.length;i++){var line=linesAndNewlines[i];i%2&&!options.newlineIsToken?retLines[retLines.length-1]+=line:retLines.push(line)}return retLines},lineDiff.equals=function(left,right,options){return options.ignoreWhitespace?(options.newlineIsToken&&left.includes("\n")||(left=left.trim()),options.newlineIsToken&&right.includes("\n")||(right=right.trim())):options.ignoreNewlineAtEof&&!options.newlineIsToken&&(left.endsWith("\n")&&(left=left.slice(0,-1)),right.endsWith("\n"))&&(right=right.slice(0,-1)),Diff.prototype.equals.call(this,left,right,options)};var sentenceDiff=new Diff;sentenceDiff.tokenize=function(value){return value.split(/(?<=[.!?])(\s+|$)/)};var cssDiff=new Diff;function _arrayLikeToArray(r,a){(null==a||a>r.length)&&(a=r.length);for(var e=0,n=Array(a);e<a;e++)n[e]=r[e];return n}function _createForOfIteratorHelper(r,e){var o,a,u,n,t="undefined"!=typeof Symbol&&r[Symbol.iterator]||r["@@iterator"];if(t)return u=!(a=!0),{s:function(){t=t.call(r)},n:function(){var r=t.next();return a=r.done,r},e:function(r){u=!0,o=r},f:function(){try{a||null==t.return||t.return()}finally{if(u)throw o}}};if(Array.isArray(r)||(t=((r,a)=>{var t;if(r)return"string"==typeof r?_arrayLikeToArray(r,a):"Map"===(t="Object"===(t={}.toString.call(r).slice(8,-1))&&r.constructor?r.constructor.name:t)||"Set"===t?Array.from(r):"Arguments"===t||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?_arrayLikeToArray(r,a):void 0})(r))||e)return t&&(r=t),n=0,{s:e=function(){},n:function(){return n>=r.length?{done:!0}:{done:!1,value:r[n++]}},e:function(r){throw r},f:e};throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _defineProperty(e,r,t){(r=(t=>"symbol"==typeof(t=((t,r)=>{if("object"!=typeof t||!t)return t;var e=t[Symbol.toPrimitive];if(void 0===e)return("string"===r?String:Number)(t);if("object"!=typeof(e=e.call(t,r)))return e;throw new TypeError("@@toPrimitive must return a primitive value.")})(t,"string"))?t:t+"")(r))in e?Object.defineProperty(e,r,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[r]=t}function ownKeys(e,r){var o,t=Object.keys(e);return Object.getOwnPropertySymbols&&(o=Object.getOwnPropertySymbols(e),r&&(o=o.filter(function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable})),t.push.apply(t,o)),t}function _objectSpread2(e){for(var r=1;r<arguments.length;r++){var t=null!=arguments[r]?arguments[r]:{};r%2?ownKeys(Object(t),!0).forEach(function(r){_defineProperty(e,r,t[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):ownKeys(Object(t)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(t,r))})}return e}function _typeof(o){return(_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o})(o)}cssDiff.tokenize=function(value){return value.split(/([{}:;,]|\s+)/)};var jsonDiff=new Diff;function canonicalize(obj,stack,replacementStack,replacer,key){var i,canonicalizedObj;for(stack=stack||[],replacementStack=replacementStack||[],replacer&&(obj=replacer(void 0===key?"":key,obj)),i=0;i<stack.length;i+=1)if(stack[i]===obj)return replacementStack[i];if("[object Array]"===Object.prototype.toString.call(obj)){for(stack.push(obj),canonicalizedObj=new Array(obj.length),replacementStack.push(canonicalizedObj),i=0;i<obj.length;i+=1)canonicalizedObj[i]=canonicalize(obj[i],stack,replacementStack,replacer,String(i));stack.pop(),replacementStack.pop()}else if("object"===_typeof(obj=obj&&obj.toJSON?obj.toJSON():obj)&&null!==obj){stack.push(obj),replacementStack.push(canonicalizedObj={});var _key,sortedKeys=[];for(_key in obj)Object.prototype.hasOwnProperty.call(obj,_key)&&sortedKeys.push(_key);for(sortedKeys.sort(),i=0;i<sortedKeys.length;i+=1)canonicalizedObj[_key=sortedKeys[i]]=canonicalize(obj[_key],stack,replacementStack,replacer,_key);stack.pop(),replacementStack.pop()}else canonicalizedObj=obj;return canonicalizedObj}jsonDiff.useLongestToken=!0,jsonDiff.tokenize=lineDiff.tokenize,jsonDiff.castInput=function(value,options){var undefinedReplacement=options.undefinedReplacement,options=options.stringifyReplacer;return"string"==typeof value?value:JSON.stringify(canonicalize(value,null,null,void 0===options?function(k,v){return void 0===v?undefinedReplacement:v}:options),null," ")},jsonDiff.equals=function(left,right,options){return Diff.prototype.equals.call(jsonDiff,left.replace(/,([\r\n])/g,"$1"),right.replace(/,([\r\n])/g,"$1"),options)};var arrayDiff=new Diff;function unixToWin(patch){return Array.isArray(patch)?patch.map(unixToWin):_objectSpread2(_objectSpread2({},patch),{},{hunks:patch.hunks.map(function(hunk){return _objectSpread2(_objectSpread2({},hunk),{},{lines:hunk.lines.map(function(line,i){return line.startsWith("\\")||line.endsWith("\r")||null!=(i=hunk.lines[i+1])&&i.startsWith("\\")?line:line+"\r"})})})})}function winToUnix(patch){return Array.isArray(patch)?patch.map(winToUnix):_objectSpread2(_objectSpread2({},patch),{},{hunks:patch.hunks.map(function(hunk){return _objectSpread2(_objectSpread2({},hunk),{},{lines:hunk.lines.map(function(line){return line.endsWith("\r")?line.substring(0,line.length-1):line})})})})}function parsePatch(uniDiff){var diffstr=uniDiff.split(/\n/),list=[],i=0;function parseIndex(){var index={};for(list.push(index);i<diffstr.length;){var line=diffstr[i];if(/^(\-\-\-|\+\+\+|@@)\s/.test(line))break;line=/^(?:Index:|diff(?: -r \w+)+)\s+(.+?)\s*$/.exec(line);line&&(index.index=line[1]),i++}for(parseFileHeader(index),parseFileHeader(index),index.hunks=[];i<diffstr.length;){var _line=diffstr[i];if(/^(Index:\s|diff\s|\-\-\-\s|\+\+\+\s|===================================================================)/.test(_line))break;if(/^@@/.test(_line))index.hunks.push((()=>{var chunkHeaderIndex=i,chunkHeader=diffstr[i++].split(/@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/),hunk={oldStart:+chunkHeader[1],oldLines:void 0===chunkHeader[2]?1:+chunkHeader[2],newStart:+chunkHeader[3],newLines:void 0===chunkHeader[4]?1:+chunkHeader[4],lines:[]};0===hunk.oldLines&&(hunk.oldStart+=1),0===hunk.newLines&&(hunk.newStart+=1);for(var addCount=0,removeCount=0;i<diffstr.length&&(removeCount<hunk.oldLines||addCount<hunk.newLines||null!=(_diffstr$i=diffstr[i])&&_diffstr$i.startsWith("\\"));i++){var _diffstr$i=0==diffstr[i].length&&i!=diffstr.length-1?" ":diffstr[i][0];if("+"!==_diffstr$i&&"-"!==_diffstr$i&&" "!==_diffstr$i&&"\\"!==_diffstr$i)throw new Error("Hunk at line ".concat(chunkHeaderIndex+1," contained invalid line ").concat(diffstr[i]));hunk.lines.push(diffstr[i]),"+"===_diffstr$i?addCount++:"-"===_diffstr$i?removeCount++:" "===_diffstr$i&&(addCount++,removeCount++)}if(addCount||1!==hunk.newLines||(hunk.newLines=0),removeCount||1!==hunk.oldLines||(hunk.oldLines=0),addCount!==hunk.newLines)throw new Error("Added line count did not match for hunk at line "+(chunkHeaderIndex+1));if(removeCount===hunk.oldLines)return hunk;throw new Error("Removed line count did not match for hunk at line "+(chunkHeaderIndex+1))})());else{if(_line)throw new Error("Unknown line "+(i+1)+" "+JSON.stringify(_line));i++}}}function parseFileHeader(index){var keyPrefix,fileName,fileHeader=/^(---|\+\+\+)\s+(.*)\r?$/.exec(diffstr[i]);fileHeader&&(keyPrefix="---"===fileHeader[1]?"old":"new",fileName=(fileHeader=fileHeader[2].split("\t",2))[0].replace(/\\\\/g,"\\"),/^".*"$/.test(fileName)&&(fileName=fileName.substr(1,fileName.length-2)),index[keyPrefix+"FileName"]=fileName,index[keyPrefix+"Header"]=(fileHeader[1]||"").trim(),i++)}for(;i<diffstr.length;)parseIndex();return list}function applyPatch(source,uniDiff){var string,options=2<arguments.length&&void 0!==arguments[2]?arguments[2]:{};if("string"==typeof uniDiff&&(uniDiff=parsePatch(uniDiff)),Array.isArray(uniDiff)){if(1<uniDiff.length)throw new Error("applyPatch only works with a single input.");uniDiff=uniDiff[0]}!options.autoConvertLineEndings&&null!=options.autoConvertLineEndings||(!(string=source).includes("\r\n")||string.startsWith("\n")||string.match(/[^\r]\n/)||(string=uniDiff,(string=Array.isArray(string)?string:[string]).some(function(index){return index.hunks.some(function(hunk){return hunk.lines.some(function(line){return!line.startsWith("\\")&&line.endsWith("\r")})})}))?(string=>!string.includes("\r\n")&&string.includes("\n"))(source)&&(patch=>(patch=Array.isArray(patch)?patch:[patch]).some(function(index){return index.hunks.some(function(hunk){return hunk.lines.some(function(line){return line.endsWith("\r")})})})&&patch.every(function(index){return index.hunks.every(function(hunk){return hunk.lines.every(function(line,i){return line.startsWith("\\")||line.endsWith("\r")||(null==(line=hunk.lines[i+1])?void 0:line.startsWith("\\"))})})}))(uniDiff)&&(uniDiff=winToUnix(uniDiff)):uniDiff=unixToWin(uniDiff));var lines=source.split("\n"),hunks=uniDiff.hunks,compareLine=options.compareLine||function(lineNumber,line,operation,patchContent){return line===patchContent},fuzzFactor=options.fuzzFactor||0,minLine=0;if(fuzzFactor<0||!Number.isInteger(fuzzFactor))throw new Error("fuzzFactor must be a non-negative integer");if(!hunks.length)return source;for(var prevLine="",removeEOFNL=!1,addEOFNL=!1,i=0;i<hunks[hunks.length-1].lines.length;i++){var line=hunks[hunks.length-1].lines[i];"\\"==line[0]&&("+"==prevLine[0]?removeEOFNL=!0:"-"==prevLine[0]&&(addEOFNL=!0)),prevLine=line}if(removeEOFNL){if(addEOFNL){if(!fuzzFactor&&""==lines[lines.length-1])return!1}else if(""==lines[lines.length-1])lines.pop();else if(!fuzzFactor)return!1}else if(addEOFNL)if(""!=lines[lines.length-1])lines.push("");else if(!fuzzFactor)return!1;for(var resultLines=[],prevHunkOffset=0,_i=0;_i<hunks.length;_i++){for(var hunk=hunks[_i],hunkResult=void 0,maxLine=lines.length-hunk.oldLines+fuzzFactor,toPos=void 0,maxErrors=0;maxErrors<=fuzzFactor;maxErrors++){for(var iterator=((start,minLine,maxLine)=>{var wantForward=!0,backwardExhausted=!1,forwardExhausted=!1,localOffset=1;return function iterator(){if(wantForward&&!forwardExhausted){if(backwardExhausted?localOffset++:wantForward=!1,start+localOffset<=maxLine)return start+localOffset;forwardExhausted=!0}if(!backwardExhausted)return forwardExhausted||(wantForward=!0),minLine<=start-localOffset?start-localOffset++:(backwardExhausted=!0,iterator())}})(toPos=hunk.oldStart+prevHunkOffset-1,minLine,maxLine);void 0!==toPos&&!(hunkResult=function applyHunk(hunkLines,toPos,maxErrors,argument_3,argument_4,argument_5,argument_6){for(var hunkLinesI=3<arguments.length&&void 0!==argument_3?argument_3:0,lastContextLineMatched=!(4<arguments.length&&void 0!==argument_4)||argument_4,patchedLines=5<arguments.length&&void 0!==argument_5?argument_5:[],patchedLinesLength=6<arguments.length&&void 0!==argument_6?argument_6:0,nConsecutiveOldContextLines=0,nextContextLineMustMatch=!1;hunkLinesI<hunkLines.length;hunkLinesI++){var operation=0<(hunkLine=hunkLines[hunkLinesI]).length?hunkLine[0]:" ",hunkLine=0<hunkLine.length?hunkLine.substr(1):hunkLine;if("-"===operation){if(!compareLine(toPos+1,lines[toPos],operation,hunkLine))return maxErrors&&null!=lines[toPos]?(patchedLines[patchedLinesLength]=lines[toPos],applyHunk(hunkLines,toPos+1,maxErrors-1,hunkLinesI,!1,patchedLines,patchedLinesLength+1)):null;toPos++,nConsecutiveOldContextLines=0}if("+"===operation){if(!lastContextLineMatched)return null;patchedLines[patchedLinesLength]=hunkLine,patchedLinesLength++,nextContextLineMustMatch=!(nConsecutiveOldContextLines=0)}if(" "===operation){if(nConsecutiveOldContextLines++,patchedLines[patchedLinesLength]=lines[toPos],!compareLine(toPos+1,lines[toPos],operation,hunkLine))return nextContextLineMustMatch||!maxErrors?null:lines[toPos]&&(applyHunk(hunkLines,toPos+1,maxErrors-1,hunkLinesI+1,!1,patchedLines,patchedLinesLength+1)||applyHunk(hunkLines,toPos+1,maxErrors-1,hunkLinesI,!1,patchedLines,patchedLinesLength+1))||applyHunk(hunkLines,toPos,maxErrors-1,hunkLinesI+1,!1,patchedLines,patchedLinesLength);patchedLinesLength++,nextContextLineMustMatch=!(lastContextLineMatched=!0),toPos++}}return toPos-=nConsecutiveOldContextLines,patchedLines.length=patchedLinesLength-=nConsecutiveOldContextLines,{patchedLines:patchedLines,oldLineLastI:toPos-1}}(hunk.lines,toPos,maxErrors));toPos=iterator());if(hunkResult)break}if(!hunkResult)return!1;for(var _i2=minLine;_i2<toPos;_i2++)resultLines.push(lines[_i2]);for(var _i3=0;_i3<hunkResult.patchedLines.length;_i3++){var _line=hunkResult.patchedLines[_i3];resultLines.push(_line)}minLine=hunkResult.oldLineLastI+1,prevHunkOffset=toPos+1-hunk.oldStart}for(var _i4=minLine;_i4<lines.length;_i4++)resultLines.push(lines[_i4]);return resultLines.join("\n")}function structuredPatch(oldFileName,newFileName,oldStr,newStr,oldHeader,newHeader,options){if(void 0===(options="function"==typeof(options=options||{})?{callback:options}:options).context&&(options.context=4),options.newlineIsToken)throw new Error("newlineIsToken may not be used with patch-generation functions, only with diffing functions");if(!options.callback)return diffLinesResultToPatch(diffLines(oldStr,newStr,options));var _callback=options.callback;function diffLinesResultToPatch(diff){if(diff){diff.push({value:"",lines:[]});for(var startTime=performance.now(),hunks=[],oldRangeStart=0,newRangeStart=0,curRange=[],oldLine=1,newLine=1,i=0;i<diff.length&&!((_options2=void 0)!==(null==(_options2=options)?void 0:_options2.timeout)&&performance.now()-startTime>options.timeout);i++){var current=diff[i],_options2=current.lines||(text=>{var hasTrailingNl=text.endsWith("\n"),text=text.split("\n").map(function(line){return line+"\n"});return hasTrailingNl?text.pop():text.push(text.pop().slice(0,-1)),text})(current.value);if(current.lines=_options2,current.added||current.removed){!oldRangeStart&&(oldRangeStart=oldLine,newRangeStart=newLine,prev=diff[i-1])&&(oldRangeStart-=(curRange=0<options.context?contextLines(prev.lines.slice(-options.context)):[]).length,newRangeStart-=curRange.length);var _step,_iterator=_createForOfIteratorHelper(_options2);try{for(_iterator.s();!(_step=_iterator.n()).done;){var line=_step.value;curRange.push((current.added?"+":"-")+line)}}catch(err){_iterator.e(err)}finally{_iterator.f()}current.added?newLine+=_options2.length:oldLine+=_options2.length}else{if(oldRangeStart)if(_options2.length<=2*options.context&&i<diff.length-2){var _step2,_iterator2=_createForOfIteratorHelper(contextLines(_options2));try{for(_iterator2.s();!(_step2=_iterator2.n()).done;){var _line=_step2.value;curRange.push(_line)}}catch(err){_iterator2.e(err)}finally{_iterator2.f()}}else{var _step3,prev=Math.min(_options2.length,options.context),_iterator3=_createForOfIteratorHelper(contextLines(_options2.slice(0,prev)));try{for(_iterator3.s();!(_step3=_iterator3.n()).done;){var _line2=_step3.value;curRange.push(_line2)}}catch(err){_iterator3.e(err)}finally{_iterator3.f()}hunks.push({oldStart:oldRangeStart,oldLines:oldLine-oldRangeStart+prev,newStart:newRangeStart,newLines:newLine-newRangeStart+prev,lines:curRange}),newRangeStart=oldRangeStart=0,curRange=[]}oldLine+=_options2.length,newLine+=_options2.length}}for(var _i=0,_hunks=hunks;_i<_hunks.length;_i++)for(var _hunk=_hunks[_i],_i2=0;_i2<_hunk.lines.length;_i2++)_hunk.lines[_i2].endsWith("\n")?_hunk.lines[_i2]=_hunk.lines[_i2].slice(0,-1):(_hunk.lines.splice(_i2+1,0,"\\ No newline at end of file"),_i2++);return{oldFileName:oldFileName,newFileName:newFileName,oldHeader:oldHeader,newHeader:newHeader,hunks:hunks}}function contextLines(lines){return lines.map(function(entry){return" "+entry})}}diffLines(oldStr,newStr,_objectSpread2(_objectSpread2({},options),{},{callback:function(diff){diff=diffLinesResultToPatch(diff);_callback(diff)}}))}function formatPatch(diff){if(Array.isArray(diff))return diff.map(formatPatch).join("\n");var ret=[];diff.oldFileName==diff.newFileName&&ret.push("Index: "+diff.oldFileName),ret.push("==================================================================="),ret.push("--- "+diff.oldFileName+(void 0===diff.oldHeader?"":"\t"+diff.oldHeader)),ret.push("+++ "+diff.newFileName+(void 0===diff.newHeader?"":"\t"+diff.newHeader));for(var i=0;i<diff.hunks.length;i++){var _step4,hunk=diff.hunks[i],_iterator4=(0===hunk.oldLines&&--hunk.oldStart,0===hunk.newLines&&--hunk.newStart,ret.push("@@ -"+hunk.oldStart+","+hunk.oldLines+" +"+hunk.newStart+","+hunk.newLines+" @@"),_createForOfIteratorHelper(hunk.lines));try{for(_iterator4.s();!(_step4=_iterator4.n()).done;)ret.push(_step4.value)}catch(err){_iterator4.e(err)}finally{_iterator4.f()}}return ret.join("\n")+"\n"}function createTwoFilesPatch(oldFileName,newFileName,oldStr,newStr,oldHeader,newHeader,options){if(null!=(_options3=options="function"==typeof options?{callback:options}:options)&&_options3.callback){var _callback2=options.callback;structuredPatch(oldFileName,newFileName,oldStr,newStr,oldHeader,newHeader,_objectSpread2(_objectSpread2({},options),{},{callback:function(patchObj){patchObj?_callback2(formatPatch(patchObj)):_callback2()}}))}else{var _options3=structuredPatch(oldFileName,newFileName,oldStr,newStr,oldHeader,newHeader,options);if(_options3)return formatPatch(_options3)}}arrayDiff.tokenize=function(value){return value.slice()},arrayDiff.join=arrayDiff.removeEmpty=function(value){return value},exports.Diff=Diff,exports.applyPatch=applyPatch,exports.applyPatches=function(uniDiff,options){"string"==typeof uniDiff&&(uniDiff=parsePatch(uniDiff));var currentIndex=0;!function processIndex(){var index=uniDiff[currentIndex++];if(!index)return options.complete();options.loadFile(index,function(err,data){if(err)return options.complete(err);err=applyPatch(data,index,options),options.patched(index,err,function(err){if(err)return options.complete(err);processIndex()})})}()},exports.canonicalize=canonicalize,exports.convertChangesToDMP=function(changes){for(var change,operation,ret=[],i=0;i<changes.length;i++)operation=(change=changes[i]).added?1:change.removed?-1:0,ret.push([operation,change.value]);return ret},exports.convertChangesToXML=function(changes){for(var ret=[],i=0;i<changes.length;i++){var change=changes[i];change.added?ret.push("<ins>"):change.removed&&ret.push("<del>"),ret.push(change.value.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")),change.added?ret.push("</ins>"):change.removed&&ret.push("</del>")}return ret.join("")},exports.createPatch=function(fileName,oldStr,newStr,oldHeader,newHeader,options){return createTwoFilesPatch(fileName,fileName,oldStr,newStr,oldHeader,newHeader,options)},exports.createTwoFilesPatch=createTwoFilesPatch,exports.diffArrays=function(oldArr,newArr,callback){return arrayDiff.diff(oldArr,newArr,callback)},exports.diffChars=function(oldStr,newStr,options){return characterDiff.diff(oldStr,newStr,options)},exports.diffCss=function(oldStr,newStr,callback){return cssDiff.diff(oldStr,newStr,callback)},exports.diffJson=function(oldObj,newObj,options){return jsonDiff.diff(oldObj,newObj,options)},exports.diffLines=diffLines,exports.diffSentences=function(oldStr,newStr,callback){return sentenceDiff.diff(oldStr,newStr,callback)},exports.diffTrimmedLines=function(oldStr,newStr,callback){return callback=((options,defaults)=>{if("function"==typeof options)defaults.callback=options;else if(options)for(var name in options)options.hasOwnProperty(name)&&(defaults[name]=options[name]);return defaults})(callback,{ignoreWhitespace:!0}),lineDiff.diff(oldStr,newStr,callback)},exports.diffWords=function(oldStr,newStr,options){return null==(null==options?void 0:options.ignoreWhitespace)||options.ignoreWhitespace?wordDiff.diff(oldStr,newStr,options):diffWordsWithSpace(oldStr,newStr,options)},exports.diffWordsWithSpace=diffWordsWithSpace,exports.formatPatch=formatPatch,exports.parsePatch=parsePatch,exports.reversePatch=function reversePatch(structuredPatch){return Array.isArray(structuredPatch)?structuredPatch.map(reversePatch).reverse():_objectSpread2(_objectSpread2({},structuredPatch),{},{oldFileName:structuredPatch.newFileName,oldHeader:structuredPatch.newHeader,newFileName:structuredPatch.oldFileName,newHeader:structuredPatch.oldHeader,hunks:structuredPatch.hunks.map(function(hunk){return{oldLines:hunk.newLines,oldStart:hunk.newStart,newLines:hunk.oldLines,newStart:hunk.oldStart,lines:hunk.lines.map(function(l){return l.startsWith("-")?"+".concat(l.slice(1)):l.startsWith("+")?"-".concat(l.slice(1)):l})}})})},exports.structuredPatch=structuredPatch});