(function (global, factory) {
  typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  typeof define === 'function' && define.amd ? define(['exports'], factory) :
  (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.diff = {}));
})(this, (function (exports) { 'use strict';

  function ownKeys(object, enumerableOnly) {
    var keys = Object.keys(object);

    if (Object.getOwnPropertySymbols) {
      var symbols = Object.getOwnPropertySymbols(object);
      enumerableOnly && (symbols = symbols.filter(function (sym) {
        return Object.getOwnPropertyDescriptor(object, sym).enumerable;
      })), keys.push.apply(keys, symbols);
    }

    return keys;
  }

  function _objectSpread2(target) {
    for (var i = 1; i < arguments.length; i++) {
      var source = null != arguments[i] ? arguments[i] : {};
      i % 2 ? ownKeys(Object(source), !0).forEach(function (key) {
        _defineProperty(target, key, source[key]);
      }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) {
        Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
      });
    }

    return target;
  }

  function _classCallCheck(instance, Constructor) {
    if (!(instance instanceof Constructor)) {
      throw new TypeError("Cannot call a class as a function");
    }
  }

  function _defineProperties(target, props) {
    for (var i = 0; i < props.length; i++) {
      var descriptor = props[i];
      descriptor.enumerable = descriptor.enumerable || false;
      descriptor.configurable = true;
      if ("value" in descriptor) descriptor.writable = true;
      Object.defineProperty(target, descriptor.key, descriptor);
    }
  }

  function _createClass(Constructor, protoProps, staticProps) {
    if (protoProps) _defineProperties(Constructor.prototype, protoProps);
    if (staticProps) _defineProperties(Constructor, staticProps);
    Object.defineProperty(Constructor, "prototype", {
      writable: false
    });
    return Constructor;
  }

  function _defineProperty(obj, key, value) {
    if (key in obj) {
      Object.defineProperty(obj, key, {
        value: value,
        enumerable: true,
        configurable: true,
        writable: true
      });
    } else {
      obj[key] = value;
    }

    return obj;
  }

  function _slicedToArray(arr, i) {
    return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest();
  }

  function _toConsumableArray(arr) {
    return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
  }

  function _arrayWithoutHoles(arr) {
    if (Array.isArray(arr)) return _arrayLikeToArray(arr);
  }

  function _arrayWithHoles(arr) {
    if (Array.isArray(arr)) return arr;
  }

  function _iterableToArray(iter) {
    if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
  }

  function _iterableToArrayLimit(arr, i) {
    var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];

    if (_i == null) return;
    var _arr = [];
    var _n = true;
    var _d = false;

    var _s, _e;

    try {
      for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) {
        _arr.push(_s.value);

        if (i && _arr.length === i) break;
      }
    } catch (err) {
      _d = true;
      _e = err;
    } finally {
      try {
        if (!_n && _i["return"] != null) _i["return"]();
      } finally {
        if (_d) throw _e;
      }
    }

    return _arr;
  }

  function _unsupportedIterableToArray(o, minLen) {
    if (!o) return;
    if (typeof o === "string") return _arrayLikeToArray(o, minLen);
    var n = Object.prototype.toString.call(o).slice(8, -1);
    if (n === "Object" && o.constructor) n = o.constructor.name;
    if (n === "Map" || n === "Set") return Array.from(o);
    if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
  }

  function _arrayLikeToArray(arr, len) {
    if (len == null || len > arr.length) len = arr.length;

    for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];

    return arr2;
  }

  function _nonIterableSpread() {
    throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  }

  function _nonIterableRest() {
    throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  }

  var NODE_TYPE={ELEMENT:1,ATTR:2,TEXT:3,COMMENT:8,FRAGMENT:11};var EMPTY={STR:"",NUM:1,OBJ:{},ARR:[],MAP:new Map,SET:new Set,DOM:{},FUN:function(){}};var PATCH_TYPE={SET_ATTRIBUTE:0,REMOVE_ATTRIBUTE:1,NODE_VALUE:2,INSERT_BEFORE:3,REPLACE_CHILD:4,REMOVE_CHILD:5};var TransitionStateNames=["attached","detached","replaced","attributeChanged","textChanged"];var TransitionCache=new Map([["attached",new Set],["detached",new Set],["replaced",new Set],["attributeChanged",new Set],["textChanged",new Set]]);var StateCache=new Map;var NodeCache=new Map;var MiddlewareCache=new Set;var CreateTreeHookCache=new Set;var CreateNodeHookCache=new Set;var SyncTreeHookCache=new Set;var ReleaseHookCache=new Set;var ParseHookCache=new Set;

  var internalProcess = typeof process!=="undefined"?process:{env:{NODE_ENV:"development"},argv:[]};

  var globalThis = typeof global==="object"?global:(typeof window==="object"?window:self)||{};

  var parseInt=Number.parseInt;var parse$1=JSON.parse;var globalConfig={collectMetrics:true,executeScripts:true};function formatValue(value,type){var valueAsString=String(value);switch(type){case"boolean":{return valueAsString!=="false"}case"string":{return valueAsString}case"number":{return parseInt(valueAsString,10)}case"object":{return parse$1(valueAsString)}}}function getConfig(name,defaultValue){var type=arguments.length>2&&arguments[2]!==undefined?arguments[2]:typeof defaultValue;var overrides=arguments.length>3?arguments[3]:undefined;var location=globalThis.location,URLSearchParams=globalThis.URLSearchParams;var hasSearchParams=typeof URLSearchParams!=="undefined";var hasLocation=typeof location!=="undefined";var useSearchParams=hasSearchParams&&hasLocation;var useEnv=internalProcess.env;if(overrides&&name in overrides){return overrides[name]}var keyName="DIFF_".concat(name.replace(/[^a-zA-Z0-9]/,""));if(useSearchParams){var searchParams=new URLSearchParams(location.search);var lowerKey=keyName.toLowerCase();if(searchParams.has(lowerKey)){return formatValue(decodeURIComponent(String(searchParams.get(lowerKey))),type)}}var upperKey=keyName.toUpperCase();if(useEnv&&upperKey in internalProcess.env){return formatValue(internalProcess.env[upperKey.toUpperCase()],type)}return defaultValue}

  var size=getConfig("initialPoolSize",5000);var free=new Set;var allocate=new Set;var protect$1=new Set;var shape=function(){return {rawNodeName:EMPTY.STR,nodeName:EMPTY.STR,nodeValue:EMPTY.STR,nodeType:NODE_TYPE.ELEMENT,key:EMPTY.STR,childNodes:[],attributes:{}}};var memory$3={free:free,allocated:allocate,protected:protect$1};var freeValues=free.values();var Pool={size:size,memory:memory$3,fill:function(){var _this=this;for(var i=free.size;i<this.size;i++){free.add(shape());}if(this.size<free.size){free.forEach(function(value){if(free.size!==_this.size){free.delete(value);}});}},get:function(){var _freeValues$next=freeValues.next(),_freeValues$next$valu=_freeValues$next.value,value=_freeValues$next$valu===void 0?shape():_freeValues$next$valu,done=_freeValues$next.done;if(done){freeValues=free.values();}free.delete(value);allocate.add(value);return value},protect:function(vTree){allocate.delete(vTree);protect$1.add(vTree);},unprotect:function(vTree){if(protect$1.has(vTree)||allocate.has(vTree)){protect$1.delete(vTree);allocate.delete(vTree);free.add(vTree);}}};Pool.fill();

  var isArray$3=Array.isArray;var memory$2=Pool.memory;var fragmentName="#document-fragment";var textName$1="#text";function flatten(vTrees){var retVal=arguments.length>1&&arguments[1]!==undefined?arguments[1]:[];for(var i=0;i<vTrees.length;i++){var vTree=vTrees[i];if(vTree&&vTree.rawNodeName===fragmentName){flatten(vTree.childNodes,retVal);}else if(vTree){retVal.push(vTree);}}return retVal}function createTree(input,attributes,childNodes){var entry=null;if(memory$2.protected.has(input)||memory$2.allocated.has(input)){entry=input;}else if(!input||isArray$3(input)){var length=input?input.length:0;childNodes=[];for(var i=0;i<length;i++){var hasInput=input&&!input[i];if(hasInput)continue;input&&childNodes.push(input[i]);}entry=createTree(fragmentName,null,childNodes);}if(entry){return entry}var isObject=typeof input==="object";var inputAsHTMLEl=input;if(input&&isObject&&"ownerDocument"in inputAsHTMLEl){var nodeType=inputAsHTMLEl.nodeType;if(nodeType===NODE_TYPE.TEXT){var vTree=createTree(textName$1,inputAsHTMLEl.nodeValue);NodeCache.set(vTree,inputAsHTMLEl);return vTree}attributes={};childNodes=[];var inputAttrs=inputAsHTMLEl.attributes;if(inputAsHTMLEl.nodeType===NODE_TYPE.ELEMENT&&inputAttrs&&inputAttrs.length){for(var _i=0;_i<inputAttrs.length;_i++){var _inputAttrs$_i=inputAttrs[_i],name=_inputAttrs$_i.name,value=_inputAttrs$_i.value;if(value===EMPTY.STR&&name in inputAsHTMLEl){attributes[name]=input[name];continue}attributes[name]=value;}}if(inputAsHTMLEl.nodeType===NODE_TYPE.ELEMENT||inputAsHTMLEl.nodeType===NODE_TYPE.FRAGMENT){childNodes=[];for(var _i2=0;_i2<inputAsHTMLEl.childNodes.length;_i2++){var childNodeElement=inputAsHTMLEl.childNodes[_i2];childNodes.push(createTree(childNodeElement));}}NodeCache.forEach(function(domNode,vTree){if(domNode===input){entry=vTree;}});entry=entry||createTree(inputAsHTMLEl.nodeName,attributes,childNodes);entry.attributes=_objectSpread2(_objectSpread2({},entry.attributes),attributes);entry.childNodes=childNodes;NodeCache.set(entry,inputAsHTMLEl);return entry}if(isObject){var rawNodeName=input.rawNodeName,nodeName=input.nodeName,nodeValue=input.nodeValue,_attributes=input.attributes,_childNodes=input.childNodes,children=input.children;var treeName=rawNodeName||nodeName;var _vTree=createTree(treeName,_attributes||null,children||_childNodes);if(nodeValue){_vTree.nodeValue=nodeValue;}return _vTree}for(var _len=arguments.length,rest=new Array(_len>3?_len-3:0),_key=3;_key<_len;_key++){rest[_key-3]=arguments[_key];}if(rest.length){childNodes=[childNodes].concat(rest);}entry=Pool.get();var isTextNode=input===textName$1;var isString=typeof input==="string";if(isString){entry.rawNodeName=input;entry.nodeName=entry.rawNodeName.toLowerCase();}else {entry.rawNodeName=input;entry.nodeName=fragmentName;}entry.nodeValue=EMPTY.STR;entry.key=EMPTY.STR;entry.childNodes.length=0;entry.attributes={};var useAttributes=isArray$3(attributes)||typeof attributes!=="object";var useNodes=useAttributes?attributes:childNodes;var allNodes=flatten(isArray$3(useNodes)?useNodes:[useNodes]);if(isTextNode){var _nodeValue=allNodes.join(EMPTY.STR);entry.nodeType=NODE_TYPE.TEXT;entry.nodeValue=String(_nodeValue);return entry}else if(entry.nodeName===fragmentName){entry.nodeType=NODE_TYPE.FRAGMENT;}else if(input==="#comment"){entry.nodeType=NODE_TYPE.COMMENT;}else {entry.nodeType=NODE_TYPE.ELEMENT;}if(useNodes&&allNodes.length&&(!attributes||!attributes.childNodes)){for(var _i3=0;_i3<allNodes.length;_i3++){var newNode=allNodes[_i3];if(isArray$3(newNode)){var _entry$childNodes;(_entry$childNodes=entry.childNodes).push.apply(_entry$childNodes,_toConsumableArray(newNode));}else if(!newNode){continue}else if(newNode.nodeType===NODE_TYPE.FRAGMENT&&typeof newNode.rawNodeName==="string"){var _entry$childNodes2;(_entry$childNodes2=entry.childNodes).push.apply(_entry$childNodes2,_toConsumableArray(newNode.childNodes));}else if(newNode&&typeof newNode==="object"){entry.childNodes.push(createTree(newNode));}else {entry.childNodes.push(createTree(textName$1,null,newNode));}}}if(attributes&&typeof attributes==="object"&&!isArray$3(attributes)){entry.attributes=_objectSpread2({},attributes);if(attributes.childNodes){var _isObject=typeof attributes.childNodes==="object";entry.childNodes.push(_isObject?createTree(attributes.childNodes):createTree("#text",attributes.childNodes));}}if(entry.nodeName==="script"&&entry.attributes.src){entry.key=String(entry.attributes.src);}if(entry.attributes&&"key"in entry.attributes){entry.key=String(entry.attributes.key);}if(CreateTreeHookCache.size){CreateTreeHookCache.forEach(function(fn,retVal){if(retVal=fn(entry)){entry=createTree(retVal);}});}return entry}

  var TOKEN="__DIFFHTML__";var doctypeEx=/<!DOCTYPE.*>/i;var spaceEx=/[^ ]/;var tokenEx=new RegExp("".concat(TOKEN,"([^_]*)__"));var defaultSupplemental={tags:[],attributes:{},children:{}};var assign$1=Object.assign;var isArray$2=Array.isArray;var rawElementsDefaults=["script","noscript","style","template"];var selfClosingElementsDefaults=["source","embed","param","track","input","meta","link","area","base","col","wbr","img","br","hr"];var kElementsClosedByOpening={li:{li:true},p:{p:true,div:true},td:{td:true,th:true},th:{td:true,th:true}};var kElementsClosedByClosing={li:{ul:true,ol:true},a:{div:true},b:{div:true},i:{div:true},p:{div:true},td:{tr:true,table:true},th:{tr:true,table:true}};var interpolateChildNodes=function(currentParent,markup,supplemental){var _currentParent$childN;if("childNodes"in currentParent.attributes){return}if(markup&&!doctypeEx.test(markup)&&!tokenEx.test(markup)){return currentParent.childNodes.push(createTree("#text",markup))}var childNodes=[];var parts=markup.split(tokenEx);for(var i=0;i<parts.length;i++){var value=parts[i];if(!value){continue}if(i%2===1){var supValue=supplemental.children[value];var innerTree=value in supplemental.children?supValue:createTree("#text","".concat(TOKEN).concat(value,"__"));if(!innerTree)continue;var isFragment=innerTree.nodeType===NODE_TYPE.FRAGMENT;if(typeof innerTree.rawNodeName==="string"&&isFragment){childNodes.push.apply(childNodes,_toConsumableArray(innerTree.childNodes));}else {childNodes.push(innerTree);}}else if(!doctypeEx.test(value)){childNodes.push(createTree("#text",value));}}(_currentParent$childN=currentParent.childNodes).push.apply(_currentParent$childN,childNodes);};var HTMLElement=function(nodeName,rawAttrs,supplemental,options){var match=null;var attrEx=/([_@$#a-z][^\s\x00-\x1F"'>\/=\uFDD0-\uFDEF\uFFFE\uFFFF]*)\s*(=\s*("([^"]+)"|'([^']+)'|(\S+)))?/ig;if(match=tokenEx.exec(nodeName)){return HTMLElement(supplemental.tags[match[1]],rawAttrs,supplemental)}var attributes={};for(var _match;_match=attrEx.exec(rawAttrs||EMPTY.STR);){var isHTML=typeof nodeName==="string";var name=_match[1];var tokenValue=void 0;if(name===""){var _match2=rawAttrs.match(tokenEx);tokenValue=_match2?_match2[0]:"";}var testValue=_match[6]||_match[5]||_match[4];var rawValue=tokenValue||testValue||(isHTML?_match[1]:testValue||true);var value=rawValue==="''"||rawValue==="\"\""?EMPTY.STR:rawValue;var valueMatchesToken=String(value).match(tokenEx);if(valueMatchesToken&&valueMatchesToken.length){var parts=String(value).split(tokenEx);var hasToken=tokenEx.exec(name);var newName=hasToken?supplemental.attributes[hasToken[1]]:name;for(var i=0;i<parts.length;i++){var _value=parts[i];if(!_value){continue}if(i%2===1){var isObject=typeof newName==="object";var hasSupValue=(_value in supplemental.attributes);var supValue=supplemental.attributes[_value];var fallback="".concat(TOKEN).concat(_value,"__");if(attributes[newName]){attributes[newName]+=hasSupValue?supValue:fallback;}else if(isObject){if(newName&&!isArray$2(newName)){assign$1(attributes,newName);}else {if(internalProcess.env.NODE_ENV!=="production"){throw new Error("Arrays cannot be spread as attributes")}}}else if(newName){var defaultValue=hasSupValue?supValue:fallback;attributes[newName]=testValue?defaultValue:true;}}else if(attributes[newName]){attributes[newName]+=_value;}else {attributes[newName]=_value;}}}else if(valueMatchesToken=tokenEx.exec(name)){var nameAndValue=supplemental.attributes[valueMatchesToken[1]];if(typeof nameAndValue==="object"&&!isArray$2(nameAndValue)){assign$1(attributes,nameAndValue);}else {attributes[nameAndValue]=value;}}else {attributes[name]=testValue!==undefined?value:true;}}return createTree(nodeName,attributes,attributes.childNodes||[])};function parse(html,supplemental){var options=arguments.length>2&&arguments[2]!==undefined?arguments[2]:{};if(!options.parser){options.parser={};}if(!supplemental){supplemental=defaultSupplemental;}var blockText=new Set(getConfig("rawElements",rawElementsDefaults,"array",options.parser));var selfClosing=new Set(getConfig("selfClosingElements",selfClosingElementsDefaults,"array",options.parser));var tagEx=/<!--[^]*?(?=-->)-->|<(\/?)([a-z\-\_][a-z0-9\-\_]*)\s*([^>]*?)(".*?"|'.*?')?(\/?)>/ig;var root=createTree("#document-fragment",null,[]);var stack=[root];var currentParent=root;var lastTextPos=-1;if(internalProcess.env.NODE_ENV!=="production"){var markup=[html];if(!html.includes("<")&&options.parser.strict){markup.splice(1,0,"\nPossibly invalid markup. Opening tag was not properly opened.\n      ");throw new Error("\n\n".concat(markup.join("\n")))}if(!html.includes(">")&&options.parser.strict){markup.splice(1,0,"\nPossibly invalid markup. Opening tag was not properly closed.\n      ");throw new Error("\n\n".concat(markup.join("\n")))}}if(!html.includes("<")&&html){interpolateChildNodes(currentParent,html,supplemental);return root}for(var match,text,i=0;match=tagEx.exec(html);i++){var _match3=match,_match4=_slicedToArray(_match3,6),fullMatch=_match4[0],isClosingMatch=_match4[1],tagMatch=_match4[2],attributeMatch=_match4[3],extraMatch=_match4[4],selfClosingMatch=_match4[5];if(lastTextPos>-1){if(lastTextPos+fullMatch.length<tagEx.lastIndex){text=html.slice(lastTextPos,tagEx.lastIndex-fullMatch.length);if(text){interpolateChildNodes(currentParent,text,supplemental);}}}var matchOffset=tagEx.lastIndex-fullMatch.length;if(lastTextPos===-1&&matchOffset>0){var string=html.slice(0,matchOffset);if(string&&!doctypeEx.exec(string)){interpolateChildNodes(currentParent,string,supplemental);}}lastTextPos=tagEx.lastIndex;if(match[0][1]==="!"){continue}var tokenMatch=tokenEx.exec(tagMatch);var supTag=tokenMatch&&supplemental.tags[tokenMatch[1]];var name=supTag?supTag.name||supTag:tagMatch;var bypassMatch=void 0;if(!isClosingMatch){if(!match[4]&&kElementsClosedByOpening[currentParent.rawNodeName]){if(kElementsClosedByOpening[currentParent.rawNodeName][name]){stack.pop();currentParent=stack[stack.length-1];}}var attrs=attributeMatch+(extraMatch||"");currentParent=currentParent.childNodes[currentParent.childNodes.push(HTMLElement(tagMatch,attrs,supplemental))-1];stack.push(currentParent);if(options.parser.strict||blockText.has(name)){var closeMarkup="</".concat(name,">");var index=html.indexOf(closeMarkup,tagEx.lastIndex);if(internalProcess.env.NODE_ENV!=="production"){if(index===-1&&options.parser.strict&&!selfClosing.has(name)){var _markup=html.slice(tagEx.lastIndex-fullMatch.length).split("\n").map(function(line){return line.replace(tokenEx,function(value,index){if(!supplemental){return value}var _supplemental=supplemental,tags=_supplemental.tags,children=_supplemental.children,attributes=_supplemental.attributes;return tags[index]||children[index]||attributes[index]})}).slice(0,3);var lookup=spaceEx.exec(_markup[0]);var caret=Array((lookup?lookup.index-1:0)+closeMarkup.length-1).join(" ")+"^";_markup.splice(1,0,"".concat(caret,"\n    Possibly invalid markup. <").concat(name,"> must be closed in strict mode.\n            "));throw new Error("\n\n".concat(_markup.join("\n")))}}if(blockText.has(name)){if(index===-1){lastTextPos=tagEx.lastIndex=html.length+1;}else {lastTextPos=index+closeMarkup.length;tagEx.lastIndex=lastTextPos;bypassMatch=true;}var newText=html.slice(match.index+fullMatch.length,index);interpolateChildNodes(currentParent,newText,supplemental);}}}if(bypassMatch||isClosingMatch||selfClosingMatch||selfClosing.has(name)){if(internalProcess.env.NODE_ENV!=="production"){if(currentParent&&name!==currentParent.rawNodeName&&options.parser.strict){var nodeName=currentParent.rawNodeName;var _markup2=html.slice(tagEx.lastIndex-fullMatch.length).split("\n").map(function(line){return line.replace(tokenEx,function(value,index){if(!supplemental){return value}var _supplemental2=supplemental,tags=_supplemental2.tags,children=_supplemental2.children,attributes=_supplemental2.attributes;return tags[index]||children[index]||attributes[index]})}).slice(0,3);var _lookup=spaceEx.exec(_markup2[0]);var _caret=Array(_lookup?_lookup.index:0).join(" ")+"^";_markup2.splice(1,0,"".concat(_caret,"\n  Possibly invalid markup. Saw ").concat(name,", expected ").concat(nodeName,"...\n          "));throw new Error("\n\n".concat(_markup2.join("\n")))}}while(currentParent){if(selfClosingMatch==="/"&&tokenMatch){stack.pop();currentParent=stack[stack.length-1];break}else if(supTag){if(currentParent.rawNodeName===name){stack.pop();currentParent=stack[stack.length-1];break}}if(currentParent.rawNodeName===name){stack.pop();currentParent=stack[stack.length-1];break}else {var tag=kElementsClosedByClosing[currentParent.rawNodeName];if(tag){if(tag[name]){stack.pop();currentParent=stack[stack.length-1];continue}}break}}}}var remainingText=html.slice(lastTextPos===-1?0:lastTextPos);if(internalProcess.env.NODE_ENV!=="production"){if((remainingText.includes(">")||remainingText.includes("<"))&&options.parser.strict){var _markup3=[remainingText];var _lookup2=spaceEx.exec(_markup3[0]);var _caret2=Array(_lookup2?_lookup2.index:0).join(" ")+"^";if(remainingText.includes(">")){_markup3.splice(1,0,"".concat(_caret2,"\n  Possibly invalid markup. Opening tag was not properly opened.\n        "));}else {_markup3.splice(1,0,"".concat(_caret2,"\n  Possibly invalid markup. Opening tag was not properly closed.\n        "));}throw new Error("\n\n".concat(_markup3.join("\n")))}}if(remainingText){interpolateChildNodes(currentParent,remainingText,supplemental);}if(root.childNodes.length&&root.childNodes[0].nodeName==="html"){var head={before:[],after:[]};var body={after:[]};var HTML=root.childNodes[0];var beforeHead=true;var beforeBody=true;HTML.childNodes=HTML.childNodes.filter(function(el){if(el.nodeName==="body"||el.nodeName==="head"){if(el.nodeName==="head")beforeHead=false;if(el.nodeName==="body")beforeBody=false;return true}else if(el.nodeType===NODE_TYPE.ELEMENT){if(beforeHead&&beforeBody)head.before.push(el);else if(!beforeHead&&beforeBody)head.after.push(el);else if(!beforeBody)body.after.push(el);}});if(!HTML.childNodes[0]||HTML.childNodes[0].nodeName!=="head"){var headInstance=createTree("head",null,[]);if(headInstance){var existing=headInstance.childNodes;existing.unshift.apply(existing,head.before);existing.push.apply(existing,head.after);HTML.childNodes.unshift(headInstance);}}else {var _existing=HTML.childNodes[0].childNodes;_existing.unshift.apply(_existing,head.before);_existing.push.apply(_existing,head.after);}if(!HTML.childNodes[1]||HTML.childNodes[1].nodeName!=="body"){var bodyInstance=createTree("body",null,[]);if(bodyInstance){var _existing2=bodyInstance.childNodes;_existing2.push.apply(_existing2,body.after);HTML.childNodes.push(bodyInstance);}}else {var _existing3=HTML.childNodes[1].childNodes;_existing3.push.apply(_existing3,body.after);}}return root}

  var prefix="diffHTML";var marks=new Map;var count=0;function makeMeasure(transaction){var mount=transaction.mount,input=transaction.input;var inputAsVTree=input;var id=count++;if(!getConfig("collectMetrics",false)){return EMPTY.FUN}return function(name){name="[".concat(id,"] ").concat(name);var host=mount.host;if(mount&&host){name="".concat(host.constructor.name," ").concat(name);}else if(inputAsVTree&&typeof inputAsVTree.rawNodeName==="function"){name="".concat(inputAsVTree.rawNodeName.name," ").concat(name);}var endName="".concat(name,"-end");if(marks.has(name)){var prevMark=marks.get(name)||0;var totalMs=(performance.now()-prevMark).toFixed(3);marks.delete(name);performance.mark(endName);performance.measure("".concat(prefix," ").concat(name," (").concat(totalMs,"ms)"),name,endName);}else {marks.set(name,performance.now());performance.mark(name);}}}

  var protect=Pool.protect,unprotect=Pool.unprotect,memory=Pool.memory;function protectVTree(vTree){protect(vTree);if(vTree.childNodes.length){for(var i=0;i<vTree.childNodes.length;i++){protectVTree(vTree.childNodes[i]);}}}function unprotectVTree(vTree){if(vTree.childNodes.length){for(var i=0;i<vTree.childNodes.length;i++){unprotectVTree(vTree.childNodes[i]);}}NodeCache.delete(vTree);unprotect(vTree);}function gc(){memory.allocated.forEach(function(vTree){vTree.attributes={};vTree.childNodes.length=0;memory.free.add(vTree);memory.allocated.delete(vTree);NodeCache.delete(vTree);});}

  var memory$1 = /*#__PURE__*/Object.freeze({
    __proto__: null,
    protectVTree: protectVTree,
    unprotectVTree: unprotectVTree,
    gc: gc
  });

  function schedule(transaction){var state=transaction.state,isRendering=transaction.state.isRendering;state.measure("schedule");StateCache.forEach(function(val){var oldMount=val.activeTransaction&&val.activeTransaction.mount;var newMount=transaction.mount;if(!oldMount||!newMount||!val.isRendering){return}else if(oldMount.contains&&oldMount.contains(newMount)||newMount.contains&&newMount.contains(oldMount)){state=val;isRendering=true;}else if(oldMount===newMount){state=val;isRendering=true;}});var _state=state,activeTransaction=_state.activeTransaction,nextTransaction=_state.nextTransaction;if(isRendering){var tasks=transaction.tasks;state.nextTransaction=transaction;transaction.abort();var promise=nextTransaction&&nextTransaction.promise||activeTransaction.promise||Promise.resolve();return transaction.promise=promise.then(function(){transaction.aborted=false;transaction.state.isRendering=true;transaction.state.activeTransaction=transaction;state.measure("schedule");return Transaction.flow(transaction,tasks.slice(1))})}state.isRendering=true;state.activeTransaction=transaction;state.measure("schedule");}

  function shouldUpdate(transaction){var mount=transaction.mount,input=transaction.input,measure=transaction.state.measure,options=transaction.config;var prop=options.inner?"innerHTML":"outerHTML";measure("should update");var mountAsHTMLEl=mount;if(typeof input==="string"&&mountAsHTMLEl[prop]===input){return transaction.abort(true)}measure("should update");}

  var hasIdle=typeof requestIdleCallback!=="undefined";var gcTimerId=-1;var scheduleTimeout=function(fn){return (hasIdle?requestIdleCallback:setTimeout)(fn)};var cancelTimeout=function(id){return (hasIdle?cancelIdleCallback:clearTimeout)(id)};function release(mount){if(StateCache.has(mount)){var _StateCache$get=StateCache.get(mount),mutationObserver=_StateCache$get.mutationObserver,oldTree=_StateCache$get.oldTree;mutationObserver&&mutationObserver.disconnect();if(oldTree&&!NodeCache.has(oldTree)){ReleaseHookCache.forEach(function(fn){return fn(oldTree)});unprotectVTree(oldTree);}StateCache.delete(mount);}if(!mount){return}var asHTMLElement=mount;if(asHTMLElement.childNodes&&asHTMLElement.childNodes.length){for(var i=0;i<asHTMLElement.childNodes.length;i++){release(asHTMLElement.childNodes[i]);}}if(asHTMLElement.shadowRoot){release(asHTMLElement.shadowRoot);}NodeCache.forEach(function(domNode,vTree){if(domNode===asHTMLElement){ReleaseHookCache.forEach(function(fn){return fn(vTree)});unprotectVTree(vTree);}});cancelTimeout(gcTimerId);gcTimerId=scheduleTimeout(gc);}

  function reconcileTrees(transaction){var state=transaction.state,mount=transaction.mount,input=transaction.input,options=transaction.config;var inner=options.inner;var mountAsHTMLEl=mount;if(state.mutationObserver&&!state.isDirty){state.isDirty=Boolean(state.mutationObserver.takeRecords().length);}else if(!state.mutationObserver){state.isDirty=false;}if(state.isDirty||!state.oldTree){release(mountAsHTMLEl);if(mountAsHTMLEl.ownerDocument&&state.mutationObserver){state.mutationObserver.observe(mountAsHTMLEl,{subtree:true,childList:true,attributes:true,characterData:true});}state.oldTree=createTree(mountAsHTMLEl);protectVTree(state.oldTree);StateCache.set(mount,state);}var _state$oldTree=state.oldTree,nodeName=_state$oldTree.nodeName,attributes=_state$oldTree.attributes;if(!transaction.newTree){transaction.newTree=createTree(input);}var inputAsVTree=transaction.newTree;if(!inner&&inputAsVTree.nodeType===NODE_TYPE.FRAGMENT&&state.oldTree.nodeType!==NODE_TYPE.FRAGMENT){var foundElements=[];for(var i=0;i<inputAsVTree.childNodes.length;i++){var value=inputAsVTree.childNodes[i];var isText=value.nodeType===NODE_TYPE.TEXT;if(!isText||value.nodeValue.trim()){foundElements.push(value);}}if(foundElements.length===1){transaction.newTree=foundElements[0];}else if(foundElements.length>1){transaction.newTree=createTree(inputAsVTree.childNodes);}}transaction.oldTree=state.oldTree;var oldTree=transaction.oldTree,newTree=transaction.newTree;if(inner&&oldTree&&newTree){var isUnknown=typeof newTree.rawNodeName!=="string";var isFragment=newTree.nodeType===NODE_TYPE.FRAGMENT;var children=isFragment&&!isUnknown?newTree.childNodes:newTree;transaction.newTree=createTree(nodeName,attributes,children);}}

  var max=Math.max;var keyNames=["old","new"];var textName="#text";function syncTree(oldTree,newTree){var patches=arguments.length>2&&arguments[2]!==undefined?arguments[2]:[];var state=arguments.length>3&&arguments[3]!==undefined?arguments[3]:{};var transaction=arguments.length>4&&arguments[4]!==undefined?arguments[4]:EMPTY.OBJ;var attributesOnly=arguments.length>5?arguments[5]:undefined;if(!oldTree)oldTree=EMPTY.OBJ;if(!newTree)newTree=EMPTY.OBJ;var _state$svgElements=state.svgElements,svgElements=_state$svgElements===void 0?new Set:_state$svgElements;var oldNodeName=oldTree.nodeName;var newNodeName=newTree.nodeName;var isEmpty=oldTree===EMPTY.OBJ||attributesOnly;var isSVG=newNodeName==="svg"||svgElements.has(newTree);var shortCircuit=null;if(SyncTreeHookCache.size){SyncTreeHookCache.forEach(function(fn){var entry=fn(oldTree,newTree,transaction);if(entry&&entry===oldTree){shortCircuit=patches;}else if(entry===false){shortCircuit=false;}else if(entry){newTree=entry;}});}if(shortCircuit!==null||!newTree){return shortCircuit}if(newNodeName===textName){if(oldNodeName===textName&&oldTree.nodeValue!==newTree.nodeValue){patches.push(PATCH_TYPE.NODE_VALUE,oldTree,newTree.nodeValue,oldTree.nodeValue);oldTree.nodeValue=newTree.nodeValue;return patches}else if(isEmpty){patches.push(PATCH_TYPE.NODE_VALUE,newTree,newTree.nodeValue,null);return patches}}var newChildNodes=newTree.childNodes||[];if(newTree.nodeType===NODE_TYPE.ELEMENT){var oldAttributes=isEmpty?EMPTY.OBJ:oldTree.attributes;var newAttributes=newTree.attributes||{};for(var key in newAttributes){var value=newAttributes[key];if(key in oldAttributes&&oldAttributes[key]===newAttributes[key]){continue}if(!isEmpty){oldAttributes[key]=value;}if((!oldTree||oldTree.nodeName!=="script")&&newTree.nodeName==="script"&&key==="type"){continue}patches.push(PATCH_TYPE.SET_ATTRIBUTE,isEmpty?newTree:oldTree,key,value);}if(!isEmpty){for(var _key in oldAttributes){if(_key in newAttributes){continue}patches.push(PATCH_TYPE.REMOVE_ATTRIBUTE,oldTree,_key);delete oldAttributes[_key];}}}if(attributesOnly){for(var i=0;i<newChildNodes.length;i++){isSVG&&svgElements.add(newChildNodes[i]);syncTree(null,newChildNodes[i],patches,state,transaction,true);}return patches}var keysLookup={old:new Map,new:new Map};for(var _i=0;_i<keyNames.length;_i++){var keyName=keyNames[_i];var map=keysLookup[keyName];var vTree=arguments[_i];var nodes=vTree&&vTree.childNodes;if(nodes&&nodes.length){for(var _i2=0;_i2<nodes.length;_i2++){var _vTree=nodes[_i2];if(_vTree.key){if(internalProcess.env.NODE_ENV!=="production"){if(map.has(_vTree.key)){throw new Error("Key: ".concat(_vTree.key," cannot be duplicated"))}}map.set(_vTree.key,_vTree);}}}}var oldChildNodes=oldTree.childNodes||[];var maxLength=max(newChildNodes.length,oldChildNodes.length);for(var _i3=0;_i3<maxLength;_i3++){var oldChildNode=oldChildNodes&&oldChildNodes[_i3];var newChildNode=newChildNodes[_i3];if(isSVG||newChildNode&&newChildNode.nodeName==="svg"){svgElements.add(newChildNode);}if(!newChildNode){if(syncTree(oldChildNode,null,patches,state,transaction,true)===false){newChildNodes.splice(_i3,0,oldChildNode);}continue}if(!oldChildNode){oldChildNodes.push(newChildNode);syncTree(null,newChildNode,patches,state,transaction,true);patches.push(PATCH_TYPE.INSERT_BEFORE,oldTree,newChildNode,null);continue}var newKey=newChildNode.key;var oldKey=oldChildNode.key;var oldInNew=keysLookup.new.has(oldKey);var newInOld=keysLookup.old.has(newKey);if(oldKey||newKey){if(!oldInNew&&!newInOld){oldChildNodes.splice(oldChildNodes.indexOf(oldChildNode),1,newChildNode);syncTree(null,newChildNode,patches,state,transaction,true);patches.push(PATCH_TYPE.REPLACE_CHILD,newChildNode,oldChildNode);_i3=_i3-1;continue}else if(!oldInNew){patches.push(PATCH_TYPE.REMOVE_CHILD,oldChildNode);oldChildNodes.splice(oldChildNodes.indexOf(oldChildNode),1);_i3=_i3-1;continue}if(newKey!==oldKey){var optimalNewNode=newChildNode;if(newKey&&newInOld){optimalNewNode=keysLookup.old.get(newKey);oldChildNodes.splice(oldChildNodes.indexOf(optimalNewNode),1);}else {optimalNewNode=newChildNode;}syncTree(null,optimalNewNode,patches,state,transaction,true);patches.push(PATCH_TYPE.INSERT_BEFORE,oldTree,optimalNewNode,oldChildNode);oldChildNodes.splice(_i3,0,optimalNewNode);continue}}var sameType=oldChildNode.nodeName===newChildNode.nodeName;var retVal=syncTree(oldChildNode,newChildNode,patches,state,transaction,!sameType);if(retVal===false){newChildNodes.splice(_i3,0,oldChildNode);maxLength+=1;continue}if(!sameType){oldChildNodes[_i3]=newChildNode;var lookupIndex=oldChildNodes.lastIndexOf(newChildNode);if(lookupIndex>_i3){oldChildNodes.splice(lookupIndex,1);}patches.push(PATCH_TYPE.REPLACE_CHILD,newChildNode,oldChildNode);}}if(oldChildNodes.length!==newChildNodes.length){for(var _i4=newChildNodes.length;_i4<oldChildNodes.length;_i4++){patches.push(PATCH_TYPE.REMOVE_CHILD,oldChildNodes[_i4]);}oldChildNodes.length=newChildNodes.length;}return patches}

  var namespace="http://www.w3.org/2000/svg";function createNode(vTreeLike){var ownerDocument=arguments.length>1&&arguments[1]!==undefined?arguments[1]:globalThis.document;var isSVG=arguments.length>2?arguments[2]:undefined;if(internalProcess.env.NODE_ENV!=="production"){if(!vTreeLike){throw new Error("Missing VTree when trying to create DOM Node")}}var vTree=createTree(vTreeLike);var existingNode=NodeCache.get(vTree);if(existingNode){return existingNode}var nodeName=vTree.nodeName,_vTree$rawNodeName=vTree.rawNodeName,rawNodeName=_vTree$rawNodeName===void 0?nodeName:_vTree$rawNodeName,_vTree$childNodes=vTree.childNodes,childNodes=_vTree$childNodes===void 0?[]:_vTree$childNodes;isSVG=isSVG||nodeName==="svg";var domNodeCheck=null;var retVal=null;CreateNodeHookCache.forEach(function(fn){if(retVal=fn(vTree)){domNodeCheck=retVal;}});if(!ownerDocument){return domNodeCheck}var domNode=domNodeCheck;if(!domNode){if(nodeName==="#text"){domNode=ownerDocument.createTextNode(vTree.nodeValue||EMPTY.STR);}else if(nodeName==="#document-fragment"){domNode=ownerDocument.createDocumentFragment();}else if(isSVG){domNode=ownerDocument.createElementNS(namespace,rawNodeName);}else {domNode=ownerDocument.createElement(rawNodeName);}if(nodeName==="script"){domNode.type="no-execute";}}NodeCache.set(vTree,domNode);for(var i=0;i<childNodes.length;i++){var validChildNode=createNode(childNodes[i],ownerDocument,isSVG);if(domNode&&validChildNode){domNode.appendChild(validChildNode);}}return domNode}

  function syncTrees(transaction){var state=transaction.state,measure=transaction.state.measure,oldTree=transaction.oldTree,newTree=transaction.newTree,mount=transaction.mount;measure("sync trees");if(internalProcess.env.NODE_ENV!=="production"){if(!oldTree){throw new Error("Missing old tree during synchronization")}if(!newTree){throw new Error("Missing new tree during synchronization")}}if(oldTree&&newTree&&oldTree.nodeName!==newTree.nodeName&&newTree.nodeType!==NODE_TYPE.FRAGMENT){if(internalProcess.env.NODE_ENV!=="production"){if(!mount.parentNode){throw new Error("Unable to replace top level node without a parent")}}transaction.patches=[PATCH_TYPE.REPLACE_CHILD,newTree,oldTree];transaction.oldTree=state.oldTree=newTree;var newNode=createNode(newTree);StateCache.delete(mount);StateCache.set(newNode,state);transaction.mount=newNode;if(newTree.nodeName==="script"){state.scriptsToExecute.set(newTree,newTree.attributes.type||EMPTY.STR);}}else {transaction.patches=syncTree(oldTree||null,newTree||null,[],state,transaction);}measure("sync trees");}

  function addTransitionState(stateName,callback){var _TransitionCache$get;if(internalProcess.env.NODE_ENV!=="production"){if(!TransitionStateNames.includes(stateName)){throw new Error("Invalid state name '".concat(stateName,"'"))}if(!callback){throw new Error("Missing transition state callback")}}(_TransitionCache$get=TransitionCache.get(stateName))===null||_TransitionCache$get===void 0?void 0:_TransitionCache$get.add(callback);}function removeTransitionState(stateName,callback){if(internalProcess.env.NODE_ENV!=="production"){if(stateName&&!TransitionStateNames.includes(stateName)){throw new Error("Invalid state name '".concat(stateName,"'"))}}if(!callback&&stateName){var _TransitionCache$get2;(_TransitionCache$get2=TransitionCache.get(stateName))===null||_TransitionCache$get2===void 0?void 0:_TransitionCache$get2.clear();}else if(stateName&&callback){var _TransitionCache$get3;(_TransitionCache$get3=TransitionCache.get(stateName))===null||_TransitionCache$get3===void 0?void 0:_TransitionCache$get3.delete(callback);}else {for(var i=0;i<TransitionStateNames.length;i++){var _TransitionCache$get4;(_TransitionCache$get4=TransitionCache.get(TransitionStateNames[i]))===null||_TransitionCache$get4===void 0?void 0:_TransitionCache$get4.clear();}}}function runTransitions(setName){for(var _len=arguments.length,args=new Array(_len>1?_len-1:0),_key=1;_key<_len;_key++){args[_key-1]=arguments[_key];}var set=TransitionCache.get(setName);var promises=[];if(!set){return promises}var vTree=args[0];var isElement=vTree.nodeType===NODE_TYPE.ELEMENT;if(!set.size||setName!=="textChanged"&&!isElement){return promises}set.forEach(function(callback){var nodes=args.map(function(x){return NodeCache.get(x)||x});var retVal=callback.apply(void 0,_toConsumableArray(nodes));if(typeof retVal==="object"&&retVal.then){promises.push(retVal);}});if(setName==="attached"||setName==="detached"){vTree.childNodes.forEach(function(childTree){promises.push.apply(promises,_toConsumableArray(runTransitions.apply(void 0,[setName,childTree].concat(_toConsumableArray(args.slice(1))))));});}return promises}

  var element$1=globalThis.document?document.createElement("div"):null;function decodeEntities(string){if(!element$1||!string||!string.indexOf||!string.includes("&")){return string}element$1.innerHTML=string;return element$1.textContent||EMPTY.STR}

  var $$strict=Symbol.for("diff.strict");var $$insertAfter=Symbol.for("diff.after");var $$diffHTML=Symbol.for("diffHTML");

  var keys$1=Object.keys;var blocklist=new Set;var allowlist=new Set;var setAttribute=function(vTree,domNode,name,value){var isObject=typeof value==="object"&&value;var isFunction=typeof value==="function";var isSymbol=typeof value==="symbol";var isEvent=name.indexOf("on")===0;var anyNode=domNode;var lowerName=isEvent?name.toLowerCase():name;var blocklistName="s-"+vTree.nodeName+"-"+lowerName;var htmlElement=domNode;if(allowlist.has(blocklistName)){anyNode[lowerName]=value;}else if(!blocklist.has(blocklistName)){try{anyNode[lowerName]=value;allowlist.add(blocklistName);}catch(_unused){blocklist.add(blocklistName);}}if(!isObject&&!isFunction&&!isSymbol){var emptyValue=value===null||value===undefined||value===true;htmlElement.setAttribute(lowerName,emptyValue?EMPTY.STR:value);}else if(isObject&&lowerName==="style"){var valueKeys=keys$1(value);for(var i=0;i<valueKeys.length;i++){htmlElement.style[valueKeys[i]]=value[valueKeys[i]];}}};var removeAttribute=function(vTree,domNode,name){var blocklistName="r-"+vTree.nodeName+"-"+name;var anyNode=domNode;if(allowlist.has(blocklistName)){anyNode[name]=undefined;delete anyNode[name];}else if(!blocklist.has(blocklistName)){try{anyNode[name]=undefined;delete anyNode[name];allowlist.add(blocklistName);}catch(_unused2){blocklist.add(blocklistName);}}domNode.removeAttribute(name);};var changeNodeValue=function(domNode,nodeValue){var htmlElement=domNode;if(nodeValue.includes("&")){htmlElement.nodeValue=decodeEntities(nodeValue);}else {htmlElement.nodeValue=nodeValue;}};function patchNode$1(patches){var state=arguments.length>1&&arguments[1]!==undefined?arguments[1]:EMPTY.OBJ;var promises=[];var ownerDocument=state.ownerDocument,_state$svgElements=state.svgElements,svgElements=_state$svgElements===void 0?new Set:_state$svgElements;var length=patches.length;var i=0;while(true){var patchType=patches[i];if(i===length){break}switch(patchType){case PATCH_TYPE.REMOVE_ATTRIBUTE:case PATCH_TYPE.SET_ATTRIBUTE:{var _ret=function(){var isSet=patchType===PATCH_TYPE.SET_ATTRIBUTE;var vTree=patches[i+1];var name=patches[i+2];var value=isSet?decodeEntities(patches[i+3]):null;i+=isSet?4:3;var isSVG=svgElements.has(vTree);var domNode=createNode(vTree,ownerDocument,isSVG);var oldValue=domNode.getAttribute(name);var attributeChangedPromises=runTransitions("attributeChanged",vTree,name,oldValue,value);protectVTree(vTree);var setOrRemove=isSet?setAttribute:removeAttribute;if(attributeChangedPromises.length){Promise.all(attributeChangedPromises).then(function(){return setOrRemove(vTree,domNode,name,value)});promises.push.apply(promises,_toConsumableArray(attributeChangedPromises));}else {setOrRemove(vTree,domNode,name,value);}return "break"}();if(_ret==="break")break}case PATCH_TYPE.NODE_VALUE:{var _ret2=function(){var vTree=patches[i+1];var nodeValue=patches[i+2];var oldValue=patches[i+3];var isSVG=svgElements.has(vTree);i+=4;var domNode=createNode(vTree,ownerDocument,isSVG);protectVTree(vTree);var textChangedPromises=runTransitions("textChanged",vTree,oldValue,nodeValue);if(textChangedPromises.length){Promise.all(textChangedPromises).then(function(){return changeNodeValue(domNode,nodeValue)});promises.push.apply(promises,_toConsumableArray(textChangedPromises));}else {changeNodeValue(domNode,nodeValue);}return "break"}();if(_ret2==="break")break}case PATCH_TYPE.INSERT_BEFORE:{var vTree=patches[i+1];var newTree=patches[i+2];var refTree=patches[i+3];i+=4;if(!NodeCache.has(vTree)&&vTree!==$$insertAfter){continue}var domNode=NodeCache.get(vTree);if(vTree===$$insertAfter){var _refNode=NodeCache.get(refTree);if(_refNode){domNode=_refNode.parentNode;refTree=_refNode.nextSibling?_refNode.nextSibling:null;}}var isSVG=svgElements.has(newTree);protectVTree(newTree);var refNode=refTree&&createNode(refTree,ownerDocument,isSVG);var newNode=createNode(newTree,ownerDocument,isSVG);domNode.insertBefore(newNode,refNode||null);promises.push.apply(promises,_toConsumableArray(runTransitions("attached",newTree)));break}case PATCH_TYPE.REPLACE_CHILD:{var _ret3=function(){var _TransitionCache$get,_TransitionCache$get2,_TransitionCache$get3;var newTree=patches[i+1];var oldTree=patches[i+2];i+=3;var isSVG=svgElements.has(newTree);var oldDomNode=NodeCache.get(oldTree);var newDomNode=createNode(newTree,ownerDocument,isSVG);if(!oldDomNode||!oldDomNode.parentNode){return "break"}protectVTree(newTree);var hasAttached=(_TransitionCache$get=TransitionCache.get("attached"))===null||_TransitionCache$get===void 0?void 0:_TransitionCache$get.size;var hasDetached=(_TransitionCache$get2=TransitionCache.get("detached"))===null||_TransitionCache$get2===void 0?void 0:_TransitionCache$get2.size;var hasReplaced=(_TransitionCache$get3=TransitionCache.get("replaced"))===null||_TransitionCache$get3===void 0?void 0:_TransitionCache$get3.size;if(!hasAttached&&!hasDetached&&!hasReplaced){oldDomNode.parentNode.replaceChild(newDomNode,oldDomNode);unprotectVTree(oldTree);return "break"}oldDomNode.parentNode.insertBefore(newDomNode,oldDomNode);var allPromises=[].concat(_toConsumableArray(hasAttached&&runTransitions("attached",newTree)||EMPTY.ARR),_toConsumableArray(hasDetached&&runTransitions("detached",oldTree)||EMPTY.ARR),_toConsumableArray(hasReplaced&&runTransitions("replaced",oldTree,newTree)||EMPTY.ARR));if(allPromises.length){Promise.all(allPromises).then(function(){if(oldDomNode.parentNode){oldDomNode.parentNode.removeChild(oldDomNode);}unprotectVTree(oldTree);});promises.push.apply(promises,_toConsumableArray(allPromises));}else {oldDomNode.parentNode.removeChild(oldDomNode);unprotectVTree(oldTree);}return "break"}();if(_ret3==="break")break}case PATCH_TYPE.REMOVE_CHILD:{var _ret4=function(){var vTree=patches[i+1];i+=2;var domNode=NodeCache.get(vTree);if(!domNode||!domNode.parentNode){return "break"}var detachedPromises=runTransitions("detached",vTree);if(detachedPromises.length){Promise.all(detachedPromises).then(function(){if(domNode.parentNode){domNode.parentNode.removeChild(domNode);}unprotectVTree(vTree);});promises.push.apply(promises,_toConsumableArray(detachedPromises));}else {domNode.parentNode.removeChild(domNode);unprotectVTree(vTree);}return "break"}();if(_ret4==="break")break}}}return promises}

  function patchNode(transaction){var mount=transaction.mount,state=transaction.state,patches=transaction.patches;var mutationObserver=state.mutationObserver,measure=state.measure,scriptsToExecute=state.scriptsToExecute;measure("patch node");var ownerDocument=mount.ownerDocument;var promises=transaction.promises||[];state.ownerDocument=ownerDocument||globalThis.document;if(mutationObserver){mutationObserver.disconnect();}var collectScripts=function(vTree){if(vTree.nodeName==="script"){scriptsToExecute.set(vTree,vTree.attributes.type);}};CreateNodeHookCache.add(collectScripts);if(state.ownerDocument){promises.push.apply(promises,_toConsumableArray(patchNode$1(patches,state)));}CreateNodeHookCache.delete(collectScripts);transaction.promises=promises;measure("patch node");}

  function endAsPromise(transaction){var promises=transaction.promises;if(promises&&promises.length){return transaction.promise=Promise.all(promises).then(function(){return transaction.end()})}return transaction.promise=Promise.resolve(transaction.end())}

  var element=globalThis.document?document.createElement("script"):null;function hasModule(){return Boolean(element&&"noModule"in element)}

  var assign=Object.assign;var defaultTasks=[schedule,shouldUpdate,reconcileTrees,syncTrees,patchNode,endAsPromise];var tasks={schedule:schedule,shouldUpdate:shouldUpdate,reconcileTrees:reconcileTrees,syncTrees:syncTrees,patchNode:patchNode,endAsPromise:endAsPromise};var Transaction=function(){function Transaction(mount,input,config){_classCallCheck(this,Transaction);_defineProperty(this,"state",EMPTY.OBJ);_defineProperty(this,"mount",EMPTY.OBJ);_defineProperty(this,"input",EMPTY.OBJ);_defineProperty(this,"oldTree",undefined);_defineProperty(this,"newTree",undefined);_defineProperty(this,"promise",undefined);_defineProperty(this,"promises",undefined);_defineProperty(this,"tasks",[]);_defineProperty(this,"patches",[]);this.mount=mount;this.input=input;this.config=config;var useObserver=!config.disableMutationObserver&&"MutationObserver"in(globalThis.window||EMPTY.OBJ);this.state=StateCache.get(mount)||{measure:makeMeasure(this),svgElements:new Set,scriptsToExecute:new Map,activeTransaction:this,mutationObserver:useObserver&&new globalThis.window.MutationObserver(EMPTY.FUN)};this.tasks=getConfig("tasks",defaultTasks,undefined,config).slice();this.endedCallbacks=new Set;StateCache.set(mount,this.state);}_createClass(Transaction,[{key:"start",value:function start(){if(internalProcess.env.NODE_ENV!=="production"){Transaction.assert(this);}var measure=this.state.measure,tasks=this.tasks;var takeLastTask=tasks.pop();measure("render");this.aborted=false;Transaction.invokeMiddleware(this);takeLastTask&&tasks.push(takeLastTask);return Transaction.flow(this,tasks)}},{key:"abort",value:function abort(isReturn){this.aborted=true;if(isReturn){return this.tasks[this.tasks.length-1](this)}}},{key:"end",value:function end(){var _this=this;var state=this.state,config=this.config,mount=this.mount;var mutationObserver=state.mutationObserver,measure=state.measure,svgElements=state.svgElements,scriptsToExecute=state.scriptsToExecute;var mountAsHTMLEl=mount;measure("finalize");this.completed=true;svgElements.clear();state.isRendering=false;state.isDirty=false;if(mountAsHTMLEl.ownerDocument&&mutationObserver){mutationObserver.observe(mountAsHTMLEl,{subtree:true,childList:true,attributes:true,characterData:true});}else {state.isDirty=true;}scriptsToExecute.forEach(function(type,vTree){var oldNode=NodeCache.get(vTree);oldNode.type=type;if(!config.executeScripts||hasModule()&&type==="nomodule"){return}var newNode=assign(oldNode.ownerDocument.createElement("script"),oldNode);for(var key in vTree.attributes){var value=vTree.attributes[key];newNode.setAttribute(key,value);}newNode.textContent=oldNode.textContent;if(StateCache.has(oldNode)){release(oldNode);StateCache.set(newNode,state);}NodeCache.set(vTree,newNode);oldNode.parentNode&&oldNode.parentNode.replaceChild(newNode,oldNode);});scriptsToExecute.clear();this.endedCallbacks.forEach(function(callback){return callback(_this)});this.endedCallbacks.clear();measure("finalize");measure("render");if(state.oldTree)protectVTree(state.oldTree);return this}},{key:"onceEnded",value:function onceEnded(callback){this.endedCallbacks.add(callback);}}],[{key:"create",value:function create(mount,input,options){return new Transaction(mount,input,options)}},{key:"flow",value:function flow(transaction,tasks){var retVal=transaction;for(var i=0;i<tasks.length;i++){if(transaction.aborted){return retVal}retVal=tasks[i](transaction);if(retVal!==undefined&&retVal!==transaction){return retVal}}return retVal}},{key:"assert",value:function assert(transaction){if(internalProcess.env.NODE_ENV!=="production"){if(typeof transaction.mount!=="object"||!transaction.mount){throw new Error("Transaction requires a DOM Node mount point")}if(transaction.aborted&&transaction.completed){throw new Error("Transaction was previously aborted")}if(transaction.completed){throw new Error("Transaction was previously completed")}}}},{key:"invokeMiddleware",value:function invokeMiddleware(transaction){var measure=transaction.state.measure,tasks=transaction.tasks;MiddlewareCache.forEach(function(fn){var label="invoke ".concat(fn.name||"anon");measure(label);var result=fn(transaction);if(result){tasks.push(result);}measure(label);});}}]);return Transaction}();

  function parseNewTree(transaction){var state=transaction.state,input=transaction.input,options=transaction.config;var measure=state.measure;if(typeof input==="string"){measure("parsing input for new tree");var _parse=parse(input,undefined,options),childNodes=_parse.childNodes;var vTree=createTree(childNodes);if(vTree){transaction.newTree=vTree;}measure("parsing input for new tree");}}

  function escape(unescaped){return unescaped.replace(/[&<>]/g,function(match){return "&#".concat(match.charCodeAt(0),";")})}

  var caches={StateCache:StateCache,NodeCache:NodeCache,TransitionCache:TransitionCache,MiddlewareCache:MiddlewareCache,CreateTreeHookCache:CreateTreeHookCache,CreateNodeHookCache:CreateNodeHookCache,SyncTreeHookCache:SyncTreeHookCache,ReleaseHookCache:ReleaseHookCache,ParseHookCache:ParseHookCache};var internals = _objectSpread2({decodeEntities:decodeEntities,escape:escape,makeMeasure:makeMeasure,memory:memory$1,Pool:Pool,process:internalProcess,PATCH_TYPE:PATCH_TYPE,globalConfig:globalConfig,createNode:createNode,syncTree:syncTree,Transaction:Transaction,defaultTasks:defaultTasks,tasks:tasks},caches);

  function innerHTML(mount){var input=arguments.length>1&&arguments[1]!==undefined?arguments[1]:EMPTY.STR;var config=arguments.length>2&&arguments[2]!==undefined?arguments[2]:{};config.inner=true;config.executeScripts="executeScripts"in config?config.executeScripts:true;config.tasks=config.tasks||defaultTasks;return Transaction.create(mount,input,config).start()}

  function outerHTML(mount){var input=arguments.length>1&&arguments[1]!==undefined?arguments[1]:EMPTY.STR;var config=arguments.length>2&&arguments[2]!==undefined?arguments[2]:{};config.inner=false;config.executeScripts="executeScripts"in config?config.executeScripts:true;config.tasks=config.tasks||defaultTasks;return Transaction.create(mount,input,config).start()}

  var keys=Object.keys;function toString(input){var config=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var oldTree=createTree();var activeTasks=new Set(config.tasks||defaultTasks);activeTasks.delete(tasks.patchNode);activeTasks.delete(tasks.endAsPromise);activeTasks.add(function endAsString(transaction){return serializeVTree(transaction.oldTree)});config.tasks=_toConsumableArray(activeTasks);config.inner=true;var markup="";try{markup=Transaction.create(oldTree,input,config).start();}catch(e){release(oldTree);throw e}release(oldTree);return markup}function serializeAttributes(attributes){var attrs=keys(attributes);return attrs.length?" "+attrs.map(function(keyName){var value=attributes[keyName];var isFalsy=!value;var isDynamic=typeof value==="object"||typeof value==="function";if(value===true){return keyName}return "".concat(keyName).concat(!isFalsy&&!isDynamic?"=\"".concat(String(value),"\""):"")}).join(" "):""}function serializeVTree(vTree){var output="";if(!vTree){return output}var childNodes=vTree.childNodes,nodeType=vTree.nodeType,tag=vTree.nodeName,nodeValue=vTree.nodeValue,attributes=vTree.attributes;if(nodeType===11){for(var i=0;i<childNodes.length;i++){output+=serializeVTree(childNodes[i]);}}else if(!childNodes.length&&nodeType===1){output+="<".concat(tag).concat(serializeAttributes(attributes),"></").concat(tag,">");}else if(nodeType===3){output+=nodeValue;}else if(childNodes.length){var children=childNodes.map(function(childNode){return "".concat(serializeVTree(childNode))}).join("");output+="<".concat(tag).concat(serializeAttributes(attributes),">").concat(children,"</").concat(tag,">");}return output}

  var isArray$1=Array.isArray;var isTagEx=/(<|\/)/;var nextValue=function(values){var value=values.shift();return typeof value==="string"?escape(decodeEntities(value)):value};function handleTaggedTemplate(strings){for(var _len=arguments.length,values=new Array(_len>1?_len-1:0),_key=1;_key<_len;_key++){values[_key-1]=arguments[_key];}var empty=createTree("#text",EMPTY.STR);if(!strings){return empty}else if(typeof strings==="string"){strings=[strings];}if(strings.length===1&&!values.length){if(!strings[0]){return empty}var _strict=getConfig("strict",false,"boolean",{strict:handleTaggedTemplate[$$strict]});delete handleTaggedTemplate[$$strict];var _parse=parse(strings[0],undefined,{parser:{strict:_strict}}),_childNodes=_parse.childNodes;return createTree(_childNodes.length===1?_childNodes[0]:_childNodes)}var HTML=EMPTY.STR;var supplemental={attributes:{},children:{},tags:{}};strings.forEach(function(string,i){HTML+=string;if(values.length){var value=nextValue(values);var lastCharacter=HTML.trim().slice(-1);var isAttribute=HTML.lastIndexOf(">")<HTML.lastIndexOf("<");var isTag=Boolean(lastCharacter.match(isTagEx));var isObject=typeof value==="object";var token="".concat(TOKEN).concat(i,"__");if(isTag){supplemental.tags[i]=value;HTML+=token;}else if(isAttribute){supplemental.attributes[i]=value;HTML+=token;}else if(isArray$1(value)||isObject){supplemental.children[i]=createTree(value);HTML+=token;}else if(value){HTML+=value;}}});var strict=getConfig("strict",false,"boolean",{strict:handleTaggedTemplate[$$strict]});var _parse2=parse(HTML,supplemental,{parser:{strict:strict}}),childNodes=_parse2.childNodes;return createTree(childNodes.length===1?childNodes[0]:childNodes)}delete handleTaggedTemplate[$$strict];function setStrictMode(markup){handleTaggedTemplate[$$strict]=true;try{for(var _len2=arguments.length,args=new Array(_len2>1?_len2-1:0),_key2=1;_key2<_len2;_key2++){args[_key2-1]=arguments[_key2];}return handleTaggedTemplate.apply(void 0,[markup].concat(args))}catch(e){handleTaggedTemplate[$$strict]=false;throw e}}handleTaggedTemplate.strict=setStrictMode;

  var isArray=Array.isArray;function use(middleware){var isFunction=typeof middleware==="function";var isObject=typeof middleware==="object";if(internalProcess.env.NODE_ENV!=="production"){if(!middleware||!isFunction&&!isObject||isArray(middleware)){throw new Error("Middleware must be a function or plain object")}}var subscribe=middleware.subscribe,unsubscribe=middleware.unsubscribe,createTreeHook=middleware.createTreeHook,createNodeHook=middleware.createNodeHook,syncTreeHook=middleware.syncTreeHook,releaseHook=middleware.releaseHook,parseHook=middleware.parseHook;isFunction&&MiddlewareCache.add(middleware);subscribe&&subscribe(internals);createTreeHook&&CreateTreeHookCache.add(createTreeHook);createNodeHook&&CreateNodeHookCache.add(createNodeHook);syncTreeHook&&SyncTreeHookCache.add(syncTreeHook);releaseHook&&ReleaseHookCache.add(releaseHook);parseHook&&ParseHookCache.add(parseHook);return function(){isFunction&&MiddlewareCache.delete(middleware);unsubscribe&&unsubscribe(internals);createTreeHook&&CreateTreeHookCache.delete(createTreeHook);createNodeHook&&CreateNodeHookCache.delete(createNodeHook);syncTreeHook&&SyncTreeHookCache.delete(syncTreeHook);releaseHook&&ReleaseHookCache.delete(releaseHook);parseHook&&ParseHookCache.delete(parseHook);}}

  var __VERSION__="1.0.0-beta.29";

  defaultTasks.splice(defaultTasks.indexOf(reconcileTrees),0,parseNewTree);internals.parse=parse;internals.VERSION=__VERSION__;var api={};api.VERSION=__VERSION__;api.addTransitionState=addTransitionState;api.removeTransitionState=removeTransitionState;api.release=release;api.createTree=createTree;api.use=use;api.outerHTML=outerHTML;api.innerHTML=innerHTML;api.toString=toString;api.html=handleTaggedTemplate;api.Internals=internals;var global$1=globalThis;if($$diffHTML in globalThis){var existingApi=global$1[$$diffHTML];if(__VERSION__!==existingApi.VERSION){console.log("Loaded ".concat(__VERSION__," after ").concat(existingApi.VERSION));}}global$1[$$diffHTML]=api;if(global$1.devTools){global$1.unsubscribeDevTools=use(global$1.devTools(internals));}

  exports.Internals = internals;
  exports.VERSION = __VERSION__;
  exports.addTransitionState = addTransitionState;
  exports.createTree = createTree;
  exports["default"] = api;
  exports.html = handleTaggedTemplate;
  exports.innerHTML = innerHTML;
  exports.outerHTML = outerHTML;
  exports.release = release;
  exports.removeTransitionState = removeTransitionState;
  exports.toString = toString;
  exports.use = use;

  Object.defineProperty(exports, '__esModule', { value: true });

}));
