(function () {
  'use strict';

  function n$3(t,e,l,n,r){for(e=e.split?e.split("."):e,n=0;n<e.length;n++)t=t?t[e[n]]:r;return t===r?l:t}

  var n$2="function",t$1="string",e="undefined",r$2="boolean",o$1="object",u$2="array",c$2="number",i$2="symbol",a$3="null",m$2="any",v$1="*",O$1="__",S$1="form",j$1="input",A$2="button",E$2="select",P$1=typeof process!==e?process:{};P$1.env&&P$1.env.NODE_ENV||"";var $$1=typeof document!==e;null!=P$1.versions&&null!=P$1.versions.node;typeof Deno!==e&&typeof Deno.core!==e;$$1&&"nodejs"===window.name||typeof navigator!==e&&typeof navigator.userAgent!==e&&(navigator.userAgent.includes("Node.js")||navigator.userAgent.includes("jsdom"));function M$1(n,t){return t.charAt(0)[n]()+t.slice(1)}var U$1=M$1.bind(null,"toUpperCase"),H$1=M$1.bind(null,"toLowerCase");function J$2(n){return Y$1(n)?U$1(a$3):typeof n===o$1?yn(n):Object.prototype.toString.call(n).slice(8,-1)}function R$1(n,t){void 0===t&&(t=!0);var e=J$2(n);return t?H$1(e):e}function V$1(n,t){return typeof t===n}var W$1=V$1.bind(null,n$2),q$1=V$1.bind(null,t$1),I$2=V$1.bind(null,e);var Q$1=V$1.bind(null,r$2);V$1.bind(null,i$2);function Y$1(n){return null===n}function nn(n){return R$1(n)===c$2&&!isNaN(n)}function rn(n){return R$1(n)===u$2}function on(n){if(!un(n))return !1;for(var t=n;null!==Object.getPrototypeOf(t);)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(n)===t}function un(n){return n&&(typeof n===o$1||null!==n)}function yn(n){return W$1(n.constructor)?n.constructor.name:null}function hn(n){return n instanceof Error||q$1(n.message)&&n.constructor&&nn(n.constructor.stackTraceLimit)}function Sn(n,t){if("object"!=typeof t||Y$1(t))return !1;if(t instanceof n)return !0;var e=R$1(new n(""));if(hn(t))for(;t;){if(R$1(t)===e)return !0;t=Object.getPrototypeOf(t);}return !1}Sn.bind(null,TypeError);Sn.bind(null,SyntaxError);function $n(n,t){var e=n instanceof Element||n instanceof HTMLDocument;return e&&t?Tn(n,t):e}function Tn(n,t){return void 0===t&&(t=""),n&&n.nodeName===t.toUpperCase()}function _n(n){var t=[].slice.call(arguments,1);return function(){return n.apply(void 0,[].slice.call(arguments).concat(t))}}_n($n,S$1);_n($n,A$2);_n($n,j$1);_n($n,E$2);

  function n$1(e){try{return decodeURIComponent(e.replace(/\+/g," "))}catch(e){return null}}function s$1(r){return function(e){for(var r,t=Object.create(null),o=/([^&=]+)=?([^&]*)/g;r=o.exec(e);){var a=n$1(r[1]),i=n$1(r[2]);if(a)if("[]"===a.substring(a.length-2)){var u=t[a=a.substring(0,a.length-2)]||(t[a]=[]);t[a]=Array.isArray(u)?u:[],t[a].push(i);}else t[a]=""===i||i;}for(var c in t){var l=c.split("[");l.length>1&&(m$1(t,l.map(function(e){return e.replace(/[?[\]\\ ]/g,"")}),t[c]),delete t[c]);}return t}(function(r){if(r){var t=r.match(/\?(.*)/);return t&&t[1]?t[1].split("#")[0]:""}return $$1&&window.location.search.substring(1)}(r))}function m$1(e,r,t){for(var n=r.length-1,o=0;o<n;++o){var a=r[o];if("__proto__"===a||"constructor"===a)break;a in e||(e[a]={}),e=e[a];}e[r[n]]=t;}function b$2(){for(var e="",r=0,t=4294967295*Math.random()|0;r++<36;){var n="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx"[r-1],o=15&t;e+="-"==n||"4"==n?n:("x"==n?o:3&o|8).toString(16),t=r%8==0?4294967295*Math.random()|0:t>>4;}return e}

  var n="global",o=O$1+n+O$1,l$1=typeof self===o$1&&self.self===self&&self||typeof global===o$1&&global[n]===global&&global||void 0;function f(t){return l$1[o][t]}function a$2(t,e){return l$1[o][t]=e}function i$1(t){delete l$1[o][t];}function u$1(t,e,r){var n;try{if(s(t)){var o=window[t];n=o[e].bind(o);}}catch(t){}return n||r}l$1[o]||(l$1[o]={});var c$1={};function s(t){if(typeof c$1[t]!==e)return c$1[t];try{var e$1=window[t];e$1.setItem(e,e),e$1.removeItem(e);}catch(e){return c$1[t]=!1}return c$1[t]=!0}

  function g(){return g=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r]);}return e},g.apply(this,arguments)}var h$1="function",v="undefined",y="@@redux/"+Math.random().toString(36),b$1=/* #__PURE__ */function(){return typeof Symbol===h$1&&Symbol.observable||"@@observable"}(),I$1=" != "+h$1;function w(e,t,n){var r;if(typeof t===h$1&&typeof n===v&&(n=t,t=void 0),typeof n!==v){if(typeof n!==h$1)throw new Error("enhancer"+I$1);return n(w)(e,t)}if(typeof e!==h$1)throw new Error("reducer"+I$1);var i=e,a=t,o=[],u=o,s=!1;function l(){u===o&&(u=o.slice());}function f(){return a}function d(e){if(typeof e!==h$1)throw new Error("Listener"+I$1);var t=!0;return l(),u.push(e),function(){if(t){t=!1,l();var n=u.indexOf(e);u.splice(n,1);}}}function p(e){if(!on(e))throw new Error("Act != obj");if(typeof e.type===v)throw new Error("ActType "+v);if(s)throw new Error("Dispatch in reducer");try{s=!0,a=i(a,e);}finally{s=!1;}for(var t=o=u,n=0;n<t.length;n++)(0, t[n])();return e}return p({type:"@@redux/INIT"}),(r={dispatch:p,subscribe:d,getState:f,replaceReducer:function(e){if(typeof e!==h$1)throw new Error("next reducer"+I$1);i=e,p({type:"@@redux/INIT"});}})[b$1]=function(){var e,t=d;return (e={subscribe:function(e){if("object"!=typeof e)throw new TypeError("Observer != obj");function n(){e.next&&e.next(f());}return n(),{unsubscribe:t(n)}}})[b$1]=function(){return this},e},r}function E$1(e,t){var n=t&&t.type;return "action "+(n&&n.toString()||"?")+"reducer "+e+" returns "+v}function P(){var e=[].slice.call(arguments);return 0===e.length?function(e){return e}:1===e.length?e[0]:e.reduce(function(e,t){return function(){return e(t.apply(void 0,[].slice.call(arguments)))}})}function S(){var e=arguments;return function(t){return function(n,r,i){var a,o=t(n,r,i),u=o.dispatch,c={getState:o.getState,dispatch:function(e){return u(e)}};return a=[].slice.call(e).map(function(e){return e(c)}),g({},o,{dispatch:u=P.apply(void 0,a)(o.dispatch)})}}}var N$1=O$1+"anon_id",A$1=O$1+"user_id",_=O$1+"user_traits",j="userId",k$1="anonymousId",x$1=["bootstrap","params","campaign","initializeStart","initialize","initializeEnd","ready","resetStart","reset","resetEnd","pageStart","page","pageEnd","pageAborted","trackStart","track","trackEnd","trackAborted","identifyStart","identify","identifyEnd","identifyAborted","userIdChanged","registerPlugins","enablePlugin","disablePlugin","online","offline","setItemStart","setItem","setItemEnd","setItemAborted","removeItemStart","removeItem","removeItemEnd","removeItemAborted"],T=["name","EVENTS","config","loaded"],z=x$1.reduce(function(e,t){return e[t]=t,e},{registerPluginType:function(e){return "registerPlugin:"+e},pluginReadyType:function(e){return "ready:"+e}}),M=/^utm_/,q=/^an_prop_/,V=/^an_trait_/;function C$1(e){var t=e.storage.setItem;return function(n){return function(r){return function(i){if(i.type===z.bootstrap){var a=i.params,o=i.user,u=i.persistedUser,c=i.initialUser,s=u.userId===o.userId;u.anonymousId!==o.anonymousId&&t(N$1,o.anonymousId),s||t(A$1,o.userId),c.traits&&t(_,g({},s&&u.traits?u.traits:{},c.traits));var l=Object.keys(i.params);if(l.length){var f=a.an_uid,d=a.an_event,p=l.reduce(function(e,t){if(t.match(M)||t.match(/^(d|g)clid/)){var n=t.replace(M,"");e.campaign["campaign"===n?"name":n]=a[t];}return t.match(q)&&(e.props[t.replace(q,"")]=a[t]),t.match(V)&&(e.traits[t.replace(V,"")]=a[t]),e},{campaign:{},props:{},traits:{}});n.dispatch(g({type:z.params,raw:a},p,f?{userId:f}:{})),f&&setTimeout(function(){return e.identify(f,p.traits)},0),d&&setTimeout(function(){return e.track(d,p.props)},0),Object.keys(p.campaign).length&&n.dispatch({type:z.campaign,campaign:p.campaign});}}return r(i)}}}}function U(e){return function(t,n){if(void 0===t&&(t={}),void 0===n&&(n={}),n.type===z.setItemEnd){if(n.key===N$1)return g({},t,{anonymousId:n.value});if(n.key===A$1)return g({},t,{userId:n.value})}switch(n.type){case z.identify:return Object.assign({},t,{userId:n.userId,traits:g({},t.traits,n.traits)});case z.reset:return [A$1,N$1,_].forEach(function(t){e.removeItem(t);}),Object.assign({},t,{userId:null,anonymousId:null,traits:{}});default:return t}}}function R(e){return {userId:e.getItem(A$1),anonymousId:e.getItem(N$1),traits:e.getItem(_)}}var $=function(e){return O$1+"TEMP"+O$1+e};function D(t){var n=t.storage,r=n.setItem,a=n.removeItem,o=n.getItem;return function(t){return function(n){return function(u){var c=u.userId,s=u.traits,l=u.options;if(u.type===z.reset&&([A$1,_,N$1].forEach(function(e){a(e);}),[j,k$1,"traits"].forEach(function(e){i$1($(e));})),u.type===z.identify){o(N$1)||r(N$1,b$2());var f=o(A$1),d=o(_)||{};f&&f!==c&&t.dispatch({type:z.userIdChanged,old:{userId:f,traits:d},new:{userId:c,traits:s},options:l}),c&&r(A$1,c),s&&r(_,g({},d,s));}return n(u)}}}}var B={};function L$1(e,t){B[e]&&W$1(B[e])&&(B[e](t),delete B[e]);}function J$1(e,t,n){return new Promise(function(r,i){return t()?r(e):n<1?i(g({},e,{queue:!0})):new Promise(function(e){return setTimeout(e,10)}).then(function(a){return J$1(e,t,n-10).then(r,i)})})}function X(e){return {abort:e}}var H=function(e){var t=e.data,n=e.action,r=e.instance,i=e.state,a=e.allPlugins,o=e.allMatches,u=e.store,s=e.EVENTS;try{var f=i.plugins,d=i.context,p=n.type,m=p.match(W),h=t.exact.map(function(e){return e.pluginName});m&&(h=o.during.map(function(e){return e.pluginName}));var v=function(e,t){return function(n,r,i){var a=r.config,o=r.name,u=o+"."+n.type;i&&(u=i.event);var c=n.type.match(W)?function(e,t,n,r,i){return function(a,o){var u=r?r.name:e,c=o&&ne(o)?o:n;if(r&&(!(c=o&&ne(o)?o:[e]).includes(e)||1!==c.length))throw new Error("Method "+t+" can only abort "+e+" plugin. "+JSON.stringify(c)+" input valid");return g({},i,{abort:{reason:a,plugins:c,caller:t,_:u}})}}(o,u,t,i,n):function(e,t){return function(){throw new Error(e.type+" action not cancellable. Remove abort in "+t)}}(n,u);return {payload:ae(n),instance:e,config:a||{},abort:c}}}(r,h),y=t.exact.reduce(function(e,t){var n=t.pluginName,r=t.methodName,i=!1;return r.match(/^initialize/)||r.match(/^reset/)||(i=!f[n].loaded),d.offline&&r.match(/^(page|track|identify)/)&&(i=!0),e[""+n]=i,e},{});return Promise.resolve(t.exact.reduce(function(e,i,o){try{var u=i.pluginName;return Promise.resolve(e).then(function(e){function i(){return Promise.resolve(e)}var o=function(){if(t.namespaced&&t.namespaced[u])return Promise.resolve(t.namespaced[u].reduce(function(e,t,n){try{return Promise.resolve(e).then(function(e){return t.method&&W$1(t.method)?(function(e,t){var n=ie(e);if(n&&n.name===t){var r=ie(n.method);throw new Error([t+" plugin is calling method "+e,"Plugins cant call self","Use "+n.method+" "+(r?"or "+r.method:"")+" in "+t+" plugin insteadof "+e].join("\n"))}}(t.methodName,t.pluginName),Promise.resolve(t.method({payload:e,instance:r,abort:(n=e,i=u,o=t.pluginName,function(e,t){return g({},n,{abort:{reason:e,plugins:t||[i],caller:p,from:o||i}})}),config:Q(t.pluginName,f,a),plugins:f})).then(function(t){var n=on(t)?t:{};return Promise.resolve(g({},e,n))})):e;var n,i,o;})}catch(e){return Promise.reject(e)}},Promise.resolve(n))).then(function(t){e[u]=t;});e[u]=n;}();return o&&o.then?o.then(i):i()})}catch(e){return Promise.reject(e)}},Promise.resolve({}))).then(function(e){return Promise.resolve(t.exact.reduce(function(n,i,o){try{var s=t.exact.length===o+1,l=i.pluginName,d=a[l];return Promise.resolve(n).then(function(t){var n=e[l]?e[l]:{};if(m&&(n=t),ee(n,l))return K({data:n,method:p,instance:r,pluginName:l,store:u}),Promise.resolve(t);if(ee(t,l))return s&&K({data:t,method:p,instance:r,store:u}),Promise.resolve(t);if(y.hasOwnProperty(l)&&!0===y[l])return u.dispatch({type:"queue",plugin:l,payload:n,_:{called:"queue",from:"queueMechanism"}}),Promise.resolve(t);var i=v(e[l],a[l]);return Promise.resolve(d[p]({abort:i.abort,payload:n,instance:r,config:Q(l,f,a),plugins:f})).then(function(i){var a=on(i)?i:{},o=g({},t,a),s=e[l];if(ee(s,l))K({data:s,method:p,instance:r,pluginName:l,store:u});else {var f=p+":"+l;(f.match(/:/g)||[]).length<2&&!p.match(F$1)&&!p.match(G$1)&&r.dispatch(g({},m?o:n,{type:f,_:{called:f,from:"submethod"}}));}return Promise.resolve(o)})})}catch(e){return Promise.reject(e)}},Promise.resolve(n))).then(function(e){if(!(p.match(W)||p.match(/^registerPlugin/)||p.match(G$1)||p.match(F$1)||p.match(/^params/)||p.match(/^userIdChanged/))){if(s.plugins.includes(p),e._&&e._.originalAction===p)return e;var n=g({},e,{_:{originalAction:e.type,called:e.type,from:"engineEnd"}});te(e,t.exact.length)&&!p.match(/End$/)&&(n=g({},n,{type:e.type+"Aborted"})),u.dispatch(n);}return e})})}catch(e){return Promise.reject(e)}},W=/Start$/,F$1=/^bootstrap/,G$1=/^ready/;function K(e){var t=e.pluginName,n=e.method+"Aborted"+(t?":"+t:"");e.store.dispatch(g({},e.data,{type:n,_:{called:n,from:"abort"}}));}function Q(e,t,n){var r=t[e]||n[e];return r&&r.config?r.config:{}}function Y(e,t){return t.reduce(function(t,n){return n[e]?t.concat({methodName:e,pluginName:n.name,method:n[e]}):t},[])}function Z(e,t){var n=e.replace(W,""),r=t?":"+t:"";return [""+e+r,""+n+r,n+"End"+r]}function ee(e,t){var n=e.abort;return !!n&&(!0===n||re(n,t)||n&&re(n.plugins,t))}function te(e,t){var n=e.abort;if(!n)return !1;if(!0===n||q$1(n))return !0;var r=n.plugins;return ne(n)&&n.length===t||ne(r)&&r.length===t}function ne(e){return Array.isArray(e)}function re(e,t){return !(!e||!ne(e))&&e.includes(t)}function ie(e){var t=e.match(/(.*):(.*)/);return !!t&&{method:t[1],name:t[2]}}function ae(e){return Object.keys(e).reduce(function(t,n){return "type"===n||(t[n]=on(e[n])?Object.assign({},e[n]):e[n]),t},{})}function oe(e,t,n){var r={};return function(i){return function(a){return function(o){try{var u,s=function(e){return u?e:a(m)},d=o.type,p=o.plugins,m=o;if(o.abort)return Promise.resolve(a(o));if(d===z.enablePlugin&&i.dispatch({type:z.initializeStart,plugins:p,disabled:[],fromEnable:!0,meta:o.meta}),d===z.disablePlugin&&setTimeout(function(){return L$1(o.meta.rid,{payload:o})},0),d===z.initializeEnd){var h=t(),v=Object.keys(h),y=v.filter(function(e){return p.includes(e)}).map(function(e){return h[e]}),b=[],I=[],w=o.disabled,E=y.map(function(e){var t=e.loaded,n=e.name,a=e.config;return J$1(e,function(){return t({config:a})},1e4).then(function(t){return r[n]||(i.dispatch({type:z.pluginReadyType(n),name:n,events:Object.keys(e).filter(function(e){return !T.includes(e)})}),r[n]=!0),b=b.concat(n),e}).catch(function(e){if(e instanceof Error)throw new Error(e);return I=I.concat(e.name),e})});Promise.all(E).then(function(e){var t={plugins:b,failed:I,disabled:w};setTimeout(function(){v.length===E.length+w.length&&i.dispatch(g({},{type:z.ready},t));},0);});}var P=function(){if(d!==z.bootstrap)return /^ready:([^:]*)$/.test(d)&&setTimeout(function(){return function(e,t,n){var r={},i=t(),a=e.getState(),o=a.plugins,u=a.queue,s=a.user;if(!a.context.offline&&u&&u.actions&&u.actions.length){var f=u.actions.reduce(function(e,t,n){return o[t.plugin].loaded?(e.process.push(t),e.processIndex.push(n)):(e.requeue.push(t),e.requeueIndex.push(n)),e},{processIndex:[],process:[],requeue:[],requeueIndex:[]});if(f.processIndex&&f.processIndex.length){f.processIndex.forEach(function(t){var a=u.actions[t],f=a.plugin,d=a.payload.type,p=i[f][d];if(p&&W$1(p)){var m,h=function(e,t){return void 0===e&&(e={}),void 0===t&&(t={}),[j,k$1].reduce(function(n,r){return e.hasOwnProperty(r)&&t[r]&&t[r]!==e[r]&&(n[r]=t[r]),n},e)}(a.payload,s),v=r[h.meta.rid];if(!v&&(m=p({payload:h,config:o[f].config,instance:n,abort:X}))&&on(m)&&m.abort)return void(r[h.meta.rid]=!0);if(!v){var y=d+":"+f;e.dispatch(g({},h,{type:y,_:{called:y,from:"queueDrain"}}));}}});var d=u.actions.filter(function(e,t){return !~f.processIndex.indexOf(t)});u.actions=d;}}}(i,t,e)},0),Promise.resolve(function(e,t,n,r,i){try{var a=W$1(t)?t():t,o=e.type,u=o.replace(W,"");if(e._&&e._.called)return Promise.resolve(e);var c=n.getState(),s=(m=a,void 0===(h=c.plugins)&&(h={}),void 0===(v=e.options)&&(v={}),Object.keys(m).filter(function(e){var t=v.plugins||{};return Q$1(t[e])?t[e]:!1!==t.all&&(!h[e]||!1!==h[e].enabled)}).map(function(e){return m[e]}));o===z.initializeStart&&e.fromEnable&&(s=Object.keys(c.plugins).filter(function(t){var n=c.plugins[t];return e.plugins.includes(t)&&!n.initialized}).map(function(e){return a[e]}));var d=s.map(function(e){return e.name}),p=function(e,t,n){var r=Z(e).map(function(e){return Y(e,t)});return t.reduce(function(n,r){var i=r.name,a=Z(e,i).map(function(e){return Y(e,t)}),o=a[0],u=a[1],c=a[2];return o.length&&(n.beforeNS[i]=o),u.length&&(n.duringNS[i]=u),c.length&&(n.afterNS[i]=c),n},{before:r[0],beforeNS:{},during:r[1],duringNS:{},after:r[2],afterNS:{}})}(o,s);return Promise.resolve(H({action:e,data:{exact:p.before,namespaced:p.beforeNS},state:c,allPlugins:a,allMatches:p,instance:n,store:r,EVENTS:i})).then(function(e){function t(){var t=function(){if(o.match(W))return Promise.resolve(H({action:g({},s,{type:u+"End"}),data:{exact:p.after,namespaced:p.afterNS},state:c,allPlugins:a,allMatches:p,instance:n,store:r,EVENTS:i})).then(function(e){e.meta&&e.meta.hasCallback&&L$1(e.meta.rid,{payload:e});})}();return t&&t.then?t.then(function(){return e}):e}if(te(e,d.length))return e;var s,l=function(){if(o!==u)return Promise.resolve(H({action:g({},e,{type:u}),data:{exact:p.during,namespaced:p.duringNS},state:c,allPlugins:a,allMatches:p,instance:n,store:r,EVENTS:i})).then(function(e){s=e;});s=e;}();return l&&l.then?l.then(t):t()})}catch(e){return Promise.reject(e)}var m,h,v;}(o,t,e,i,n)).then(function(e){return u=1,a(e)})}();return Promise.resolve(P&&P.then?P.then(s):s(P))}catch(e){return Promise.reject(e)}}}}}function ue(e){return function(t){return function(t){return function(n){var r=n.type,i=n.key,a=n.value,o=n.options;if(r===z.setItem||r===z.removeItem){if(n.abort)return t(n);r===z.setItem?e.setItem(i,a,o):e.removeItem(i,o);}return t(n)}}}}var ce=function(){var e=this;this.before=[],this.after=[],this.addMiddleware=function(t,n){e[n]=e[n].concat(t);},this.removeMiddleware=function(t,n){var r=e[n].findIndex(function(e){return e===t});-1!==r&&(e[n]=[].concat(e[n].slice(0,r),e[n].slice(r+1)));},this.dynamicMiddlewares=function(t){return function(n){return function(r){return function(i){var a={getState:n.getState,dispatch:function(e){return n.dispatch(e)}},o=e[t].map(function(e){return e(a)});return P.apply(void 0,o)(r)(i)}}}};};function se(e){return function(t,n){void 0===t&&(t={});var r={};if("initialize:aborted"===n.type)return t;if(/^registerPlugin:([^:]*)$/.test(n.type)){var i=le(n.type,"registerPlugin"),a=e()[i];if(!a||!i)return t;var o=n.enabled,u=a.config;return r[i]={enabled:o,initialized:!!o&&Boolean(!a.initialize),loaded:!!o&&Boolean(a.loaded({config:u})),config:u},g({},t,r)}if(/^initialize:([^:]*)$/.test(n.type)){var c=le(n.type,z.initialize),s=e()[c];return s&&c?(r[c]=g({},t[c],{initialized:!0,loaded:Boolean(s.loaded({config:s.config}))}),g({},t,r)):t}if(/^ready:([^:]*)$/.test(n.type))return r[n.name]=g({},t[n.name],{loaded:!0}),g({},t,r);switch(n.type){case z.disablePlugin:return g({},t,fe(n.plugins,!1,t));case z.enablePlugin:return g({},t,fe(n.plugins,!0,t));default:return t}}}function le(e,t){return e.substring(t.length+1,e.length)}function fe(e,t,n){return e.reduce(function(e,r){return e[r]=g({},n[r],{enabled:t}),e},n)}function de(e){try{return JSON.parse(JSON.stringify(e))}catch(e){}return e}var pe={last:{},history:[]};function me(e,t){void 0===e&&(e=pe);var n=t.options,r=t.meta;if(t.type===z.track){var i=de(g({event:t.event,properties:t.properties},Object.keys(n).length&&{options:n},{meta:r}));return g({},e,{last:i,history:e.history.concat(i)})}return e}var ge={actions:[]};function he(e,t){void 0===e&&(e=ge);var n=t.payload;switch(t.type){case"queue":var r;return r=n&&n.type&&n.type===z.identify?[t].concat(e.actions):e.actions.concat(t),g({},e,{actions:r});case"dequeue":return [];default:return e}}var ve=/#.*$/;function ye(e){var t=/(http[s]?:\/\/)?([^\/\s]+\/)(.*)/g.exec(e);return "/"+(t&&t[3]?t[3].split("?")[0].replace(ve,""):"")}var be,Ie=function(e){if(void 0===e&&(e={}),!$$1)return e;var t=document,n=t.title,r=t.referrer,i=window,a=i.location,o=i.innerWidth,u=i.innerHeight,c=a.hash,s=a.search,l=function(e){var t=function(){if($$1)for(var e,t=document.getElementsByTagName("link"),n=0;e=t[n];n++)if("canonical"===e.getAttribute("rel"))return e.getAttribute("href")}();return t?t.match(/\?/)?t:t+e:window.location.href.replace(ve,"")}(s),f={title:n,url:l,path:ye(l),hash:c,search:s,width:o,height:u};return r&&""!==r&&(f.referrer=r),g({},f,e)},we={last:{},history:[]};function Ee(e,t){void 0===e&&(e=we);var n=t.options;if(t.type===z.page){var r=de(g({properties:t.properties,meta:t.meta},Object.keys(n).length&&{options:n}));return g({},e,{last:r,history:e.history.concat(r)})}return e}be={};var Pe={initialized:!1,sessionId:b$2(),app:null,version:null,debug:!1,offline:!!$$1&&!navigator.onLine,os:{name:"na"},userAgent:$$1?navigator.userAgent:"node",library:{name:"analytics",version:"0.12.16"},timezone:void 0,locale:void 0,campaign:{},referrer:be};function Se(e,t){void 0===e&&(e=Pe);var n=e.initialized,r=t.campaign;switch(t.type){case z.campaign:return g({},e,{campaign:r});case z.offline:return g({},e,{offline:!0});case z.online:return g({},e,{offline:!1});default:return n?e:g({},Pe,e,{initialized:!0})}}var Ne=["plugins","reducers","storage"];function Ae(){return a$2("analytics",[]),function(e){return function(t,n,r){var i=e(t,n,r),a=i.dispatch;return Object.assign(i,{dispatch:function(e){return l$1[o].analytics.push(e.action||e),a(e)}})}}}function _e(e){return function(){return P(P.apply(null,arguments),Ae())}}function Oe(e){return e?rn(e)?e:[e]:[]}function je(t,n,r){void 0===t&&(t={});var i,a,o=b$2();return n&&(B[o]=(i=n,a=function(e){for(var t,n=e||Array.prototype.slice.call(arguments),r=0;r<n.length;r++)if(W$1(n[r])){t=n[r];break}return t}(r),function(e){a&&a(e),i(e);})),g({},t,{rid:o,ts:(new Date).getTime()},n?{hasCallback:!0}:{})}function ke(o){void 0===o&&(o={});var u=o.reducers||{},s=o.initialUser||{},f$1=(o.plugins||[]).reduce(function(e,t){if(W$1(t))return e.middlewares=e.middlewares.concat(t),e;if(t.NAMESPACE&&(t.name=t.NAMESPACE),!t.name)throw new Error("https://lytics.dev/errors/1");t.config||(t.config={});var n=t.EVENTS?Object.keys(t.EVENTS).map(function(e){return t.EVENTS[e]}):[];e.pluginEnabled[t.name]=!(!1===t.enabled||!1===t.config.enabled),delete t.enabled,t.methods&&(e.methods[t.name]=Object.keys(t.methods).reduce(function(e,n){var r;return e[n]=(r=t.methods[n],function(){for(var e=Array.prototype.slice.call(arguments),t=new Array(r.length),n=0;n<e.length;n++)t[n]=e[n];return t[t.length]=K,r.apply({instance:K},t)}),e},{}),delete t.methods);var r=Object.keys(t).concat(n),i=new Set(e.events.concat(r));if(e.events=Array.from(i),e.pluginsArray=e.pluginsArray.concat(t),e.plugins[t.name])throw new Error(t.name+"AlreadyLoaded");return e.plugins[t.name]=t,e.plugins[t.name].loaded||(e.plugins[t.name].loaded=function(){return !0}),e},{plugins:{},pluginEnabled:{},methods:{},pluginsArray:[],middlewares:[],events:[]}),m=o.storage?o.storage:{getItem:f,setItem:a$2,removeItem:i$1},b=function(e){return function(t,n,i){return n.getState("user")[t]||(i&&on(i)&&i[t]?i[t]:R(e)[t]||f($(t))||null)}}(m),I=f$1.plugins,A=f$1.events.filter(function(e){return !T.includes(e)}).sort(),_=new Set(A.concat(x$1).filter(function(e){return !T.includes(e)})),O=Array.from(_).sort(),M=function(){return I},q=new ce,V=q.addMiddleware,B=q.removeMiddleware,L=q.dynamicMiddlewares,J=function(){throw new Error("Abort disabled inListener")},X=s$1(),H=R(m),W=g({},H,s,X.an_uid?{userId:X.an_uid}:{},X.an_aid?{anonymousId:X.an_aid}:{});W.anonymousId||(W.anonymousId=b$2());var F=g({enable:function(e,t){return new Promise(function(n){le.dispatch({type:z.enablePlugin,plugins:Oe(e),_:{originalAction:z.enablePlugin}},n,[t]);})},disable:function(e,t){return new Promise(function(n){le.dispatch({type:z.disablePlugin,plugins:Oe(e),_:{originalAction:z.disablePlugin}},n,[t]);})}},f$1.methods),G=!1,K={identify:function(e,t,n,r){try{var i=q$1(e)?e:null,o=on(e)?e:t,u=n||{},s=K.user();a$2($(j),i);var l=i||o.userId||b(j,K,o);return Promise.resolve(new Promise(function(e){le.dispatch(g({type:z.identifyStart,userId:l,traits:o||{},options:u,anonymousId:s.anonymousId},s.id&&s.id!==i&&{previousId:s.id}),e,[t,n,r]);}))}catch(e){return Promise.reject(e)}},track:function(e,t,n,r){try{var i=on(e)?e.event:e;if(!i||!q$1(i))throw new Error("EventMissing");var a=on(e)?e:t||{},o=on(n)?n:{};return Promise.resolve(new Promise(function(e){le.dispatch({type:z.trackStart,event:i,properties:a,options:o,userId:b(j,K,t),anonymousId:b(k$1,K,t)},e,[t,n,r]);}))}catch(e){return Promise.reject(e)}},page:function(e,t,n){try{var r=on(e)?e:{},i=on(t)?t:{};return Promise.resolve(new Promise(function(a){le.dispatch({type:z.pageStart,properties:Ie(r),options:i,userId:b(j,K,r),anonymousId:b(k$1,K,r)},a,[e,t,n]);}))}catch(e){return Promise.reject(e)}},user:function(e){if(e===j||"id"===e)return b(j,K);if(e===k$1||"anonId"===e)return b(k$1,K);var t=K.getState("user");return e?n$3(t,e):t},reset:function(e){return new Promise(function(t){le.dispatch({type:z.resetStart},t,e);})},ready:function(e){return G&&e({plugins:F,instance:K}),K.on(z.ready,function(t){e(t),G=!0;})},on:function(e,t){if(!e||!W$1(t))return !1;if(e===z.bootstrap)throw new Error(".on disabled for "+e);var n=/Start$|Start:/;if("*"===e){var r=function(e){return function(e){return function(r){return r.type.match(n)&&t({payload:r,instance:K,plugins:I}),e(r)}}},i=function(e){return function(e){return function(r){return r.type.match(n)||t({payload:r,instance:K,plugins:I}),e(r)}}};return V(r,xe),V(i,Te),function(){B(r,xe),B(i,Te);}}var a=e.match(n)?xe:Te,o=function(n){return function(n){return function(r){return r.type===e&&t({payload:r,instance:K,plugins:I,abort:J}),n(r)}}};return V(o,a),function(){return B(o,a)}},once:function(e,t){if(!e||!W$1(t))return !1;if(e===z.bootstrap)throw new Error(".once disabled for "+e);var n=K.on(e,function(e){t({payload:e.payload,instance:K,plugins:I,abort:J}),n();});return n},getState:function(e){var t=le.getState();return e?n$3(t,e):Object.assign({},t)},dispatch:function(e){var t=q$1(e)?{type:e}:e;if(x$1.includes(t.type))throw new Error("reserved action "+t.type);var n=g({},t,{_:g({originalAction:t.type},e._||{})});le.dispatch(n);},enablePlugin:F.enable,disablePlugin:F.disable,plugins:F,storage:{getItem:m.getItem,setItem:function(e,t,n){le.dispatch({type:z.setItemStart,key:e,value:t,options:n});},removeItem:function(e,t){le.dispatch({type:z.removeItemStart,key:e,options:t});}},setAnonymousId:function(e,t){K.storage.setItem(N$1,e,t);},events:{core:x$1,plugins:A}},Q=f$1.middlewares.concat([function(e){return function(e){return function(t){return t.meta||(t.meta=je()),e(t)}}},L(xe),oe(K,M,{all:O,plugins:A}),ue(m),C$1(K),D(K),L(Te)]),Y={context:Se,user:U(m),page:Ee,track:me,plugins:se(M),queue:he},Z=P,ee=P;if($$1&&o.debug){var te=window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__;te&&(Z=te({trace:!0,traceLimit:25})),ee=function(){return 0===arguments.length?Ae():on(typeof arguments[0])?_e():_e().apply(null,arguments)};}var ne,re=function(e){return Object.keys(e).reduce(function(t,n){return Ne.includes(n)||(t[n]=e[n]),t},{})}(o),ie=f$1.pluginsArray.reduce(function(e,t){var n=t.name,r=t.config,i=t.loaded,a=f$1.pluginEnabled[n];return e[n]={enabled:a,initialized:!!a&&Boolean(!t.initialize),loaded:Boolean(i({config:r})),config:r},e},{}),ae={context:re,user:W,plugins:ie},le=w(function(e){for(var t=Object.keys(e),n={},r=0;r<t.length;r++){var i=t[r];typeof e[i]===h$1&&(n[i]=e[i]);}var a,o=Object.keys(n);try{!function(e){Object.keys(e).forEach(function(t){var n=e[t];if(typeof n(void 0,{type:"@@redux/INIT"})===v||typeof n(void 0,{type:y})===v)throw new Error("reducer "+t+" "+v)});}(n);}catch(e){a=e;}return function(e,t){if(void 0===e&&(e={}),a)throw a;for(var r=!1,i={},u=0;u<o.length;u++){var c=o[u],s=e[c],l=(0, n[c])(s,t);if(typeof l===v){var f=E$1(c,t);throw new Error(f)}i[c]=l,r=r||l!==s;}return r?i:e}}(g({},Y,u)),ae,ee(Z(S.apply(void 0,Q))));le.dispatch=(ne=le.dispatch,function(e,t,n){var r=g({},e,{meta:je(e.meta,t,Oe(n))});return ne.apply(null,[r])});var fe=Object.keys(I);le.dispatch({type:z.bootstrap,plugins:fe,config:re,params:X,user:W,initialUser:s,persistedUser:H});var de=fe.filter(function(e){return f$1.pluginEnabled[e]}),pe=fe.filter(function(e){return !f$1.pluginEnabled[e]});return le.dispatch({type:z.registerPlugins,plugins:fe,enabled:f$1.pluginEnabled}),f$1.pluginsArray.map(function(e,t){var n=e.bootstrap,r=e.config,i=e.name;n&&W$1(n)&&n({instance:K,config:r,payload:e}),le.dispatch({type:z.registerPluginType(i),name:i,enabled:f$1.pluginEnabled[i],plugin:e}),f$1.pluginsArray.length===t+1&&le.dispatch({type:z.initializeStart,plugins:de,disabled:pe});}),K}var xe="before",Te="after";

  var t="cookie",i=a$1(),r$1=d$1,c=d$1;function u(e){return i?d$1(e,"",-1):i$1(e)}function a$1(){if(void 0!==i)return i;var e=t+t;try{d$1(e,e),i=-1!==document.cookie.indexOf(e),u(e);}catch(e){i=!1;}return i}function d$1(n,t,r,c,u,a){if("undefined"!=typeof window){var d=arguments.length>1;return !1===i&&(d?a$2(n,t):f(n)),d?document.cookie=n+"="+encodeURIComponent(t)+(r?"; expires="+new Date(+new Date+1e3*r).toUTCString()+(c?"; path="+c:"")+(u?"; domain="+u:"")+(a?"; secure":""):""):decodeURIComponent((("; "+document.cookie).split("; "+n+"=")[1]||"").split(";")[0])}}

  var r="localStorage",m=s.bind(null,r);u$1(r,"getItem",f);u$1(r,"setItem",a$2);u$1(r,"removeItem",i$1);

  var a="sessionStorage",l=s.bind(null,a);u$1(a,"getItem",f);u$1(a,"setItem",a$2);u$1(a,"removeItem",i$1);

  function I(t){var o=t;try{if("true"===(o=JSON.parse(t)))return !0;if("false"===o)return !1;if(on(o))return o;parseFloat(o)===o&&(o=parseFloat(o));}catch(t){}if(null!==o&&""!==o)return o}var k=m(),O=l(),x=a$1();function C(o,e){if(o){var r=A(e),a=!N(r),s=d(r)?I(localStorage.getItem(o)):void 0;if(a&&!I$2(s))return s;var n=h(r)?I(r$1(o)):void 0;if(a&&n)return n;var l=E(r)?I(sessionStorage.getItem(o)):void 0;if(a&&l)return l;var u=f(o);return a?u:{localStorage:s,sessionStorage:l,cookie:n,global:u}}}function L(r$2,a$1,l){if(r$2&&!I$2(a$1)){var u={},g=A(l),m=JSON.stringify(a$1),p=!N(g);return d(g)&&(u[r]=F(r,a$1,I(localStorage.getItem(r$2))),localStorage.setItem(r$2,m),p)?u[r]:h(g)&&(u[t]=F(t,a$1,I(r$1(r$2))),c(r$2,m),p)?u[t]:E(g)&&(u[a]=F(a,a$1,I(sessionStorage.getItem(r$2))),sessionStorage.setItem(r$2,m),p)?u[a]:(u[n]=F(n,a$1,f(r$2)),a$2(r$2,a$1),p?u[n]:u)}}function b(t$1,e){if(t$1){var a$1=A(e),i=C(t$1,v$1),n$1={};return !I$2(i.localStorage)&&d(a$1)&&(localStorage.removeItem(t$1),n$1[r]=i.localStorage),!I$2(i.cookie)&&h(a$1)&&(u(t$1),n$1[t]=i.cookie),!I$2(i.sessionStorage)&&E(a$1)&&(sessionStorage.removeItem(t$1),n$1[a]=i.sessionStorage),!I$2(i.global)&&G(a$1,n)&&(i$1(t$1),n$1[n]=i.global),n$1}}function A(t){return t?q$1(t)?t:t.storage:m$2}function d(t){return k&&G(t,r)}function h(t$1){return x&&G(t$1,t)}function E(t){return O&&G(t,a)}function N(t){return t===v$1||"all"===t}function G(t,o){return t===m$2||t===o||N(t)}function F(t,o,e){return {location:t,current:o,previous:e}}var J={setItem:L,getItem:C,removeItem:b};

  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 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 analyticsLib() {
    var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    var defaultSettings = {
      storage: J
    };
    return ke(_objectSpread2(_objectSpread2({}, defaultSettings), opts));
  }

  /** Parse cookie / config string values (JSON, booleans, numbers). */
  function parse(input) {
      let value = input;
      if (typeof input === "string" && input.indexOf("%7B%22") === 0) {
          value = decodeURIComponent(input);
      }
      try {
          value = JSON.parse(value);
          if (value === "true")
              return true;
          if (value === "false")
              return false;
          if (typeof value === "object")
              return value;
          if (parseFloat(value) === value) {
              value = parseFloat(value);
          }
      }
      catch (_a) {
          /* ignore */
      }
      if (value === null || value === "") {
          return;
      }
      return value;
  }

  function findScript(src) {
      const scripts = Array.prototype.slice.call(window.document.querySelectorAll("script"));
      return scripts.find(s => s.src === src);
  }
  function buildScriptSrc(src, options) {
      let result = src;
      if (!result.startsWith("http")) {
          result = `https://${(options === null || options === void 0 ? void 0 : options.www) ? "www." : ""}${result}`;
      }
      if (options === null || options === void 0 ? void 0 : options.min) {
          result = result + ".min.js";
      }
      else if (options === null || options === void 0 ? void 0 : options.js) {
          result = result + ".js";
      }
      if (options === null || options === void 0 ? void 0 : options.query) {
          result += "?" + options.query;
      }
      return result;
  }
  function loadScript(src, options) {
      const found = findScript(src);
      if (found !== undefined) {
          const status = found === null || found === void 0 ? void 0 : found.getAttribute("status");
          if (status === "loaded") {
              return Promise.resolve(found);
          }
          if (status === "loading") {
              return new Promise((resolve, reject) => {
                  found.addEventListener("load", () => resolve(found));
                  found.addEventListener("error", err => reject(err));
              });
          }
      }
      return new Promise((resolve, reject) => {
          var _a, _b;
          const script = window.document.createElement("script");
          script.type = "text/javascript";
          script.src = buildScriptSrc(src, options);
          script.async = true;
          script.setAttribute("status", "loading");
          for (const [k, v] of Object.entries((_a = options === null || options === void 0 ? void 0 : options.attributes) !== null && _a !== void 0 ? _a : {})) {
              script.setAttribute(k, v);
          }
          script.onload = () => {
              script.onerror = script.onload = null;
              script.setAttribute("status", "loaded");
              resolve(script);
          };
          script.onerror = () => {
              script.onerror = script.onload = null;
              script.setAttribute("status", "error");
              reject(new Error(`Failed to load ${src}`));
          };
          const tag = window.document.getElementsByTagName("script")[0];
          (_b = tag.parentElement) === null || _b === void 0 ? void 0 : _b.insertBefore(script, tag);
      });
  }

  var __awaiter$5 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
      function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
      return new (P || (P = Promise))(function (resolve, reject) {
          function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
          function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
          function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
          step((generator = generator.apply(thisArg, _arguments || [])).next());
      });
  };
  const tagPlugin = {
      id: "tag",
      handle(config, payload) {
          return __awaiter$5(this, void 0, void 0, function* () {
              if (!applyFilters(payload, config)) {
                  return;
              }
              insertTags(config.code, payload);
          });
      },
  };
  function insertTags(code, event, opts = {}) {
      let tag;
      try {
          tag = JSON.parse(code);
      }
      catch (e) {
          tag = { code, lang: "javascript" };
      }
      const debug = opts.debug || false;
      if (isInBrowser()) {
          if (tag.lang === "javascript") {
              execJs(tag.code, event);
          }
          else {
              const codeHolder = document.createElement("span");
              codeHolder.innerHTML = replaceMacro(tag.code, event);
              document.body.insertAdjacentElement("beforeend", codeHolder);
              const scripts = codeHolder.querySelectorAll("script");
              scripts.forEach(script => {
                  const scriptClone = document.createElement("script");
                  scriptClone.type = scriptClone.type || "text/javascript";
                  if (script.hasAttribute("src")) {
                      scriptClone.src = script.src;
                  }
                  scriptClone.text = script.text;
                  if (debug) {
                      console.log(`[JITSU] Executing script${script.hasAttribute("src") ? ` ${script.src}` : ""}`, scriptClone.text);
                  }
                  document.head.appendChild(scriptClone);
                  document.head.removeChild(scriptClone);
              });
          }
      }
      else {
          if (debug) {
              console.log(`[JITSU] insertTags(): cannot insert tags in non-browser environment`);
          }
      }
  }
  //This weird code is used to mask eval() usage.
  //Although the code can be executed in the browser, some server side bundlers (like Vercel) fails
  //the build if a direct reference to eval() is found.
  let al = "al";
  let ev = "ve".split("").reverse().join("");
  const execF = globalThis[ev + al];
  function execJs(code, event) {
      const varName = `jitsu_event_${randomId()}`;
      window[varName] = event;
      const iif = `(function(){
      const event = ${varName};
      ${code}
  })()`;
      try {
          execF(iif);
      }
      catch (e) {
          console.error(`[JITSU] Error executing JS code: ${e.message}. Code: `, iif);
      }
      finally {
          delete window[varName];
      }
      return iif;
  }
  function replaceMacro(code, event) {
      return code.replace(/{{\s*event\s*}}/g, JSON.stringify(event));
  }

  var __awaiter$4 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
      function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
      return new (P || (P = Promise))(function (resolve, reject) {
          function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
          function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
          function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
          step((generator = generator.apply(thisArg, _arguments || [])).next());
      });
  };
  const cdn = "cdn.lr-ingest.io/";
  const logrocketPlugin = {
      id: "logrocket",
      handle(config, payload) {
          return __awaiter$4(this, void 0, void 0, function* () {
              if (!applyFilters(payload, config)) {
                  return;
              }
              initLogrocketIfNeeded(config.appId);
              const action = logRocket => {
                  if (payload.type === "identify" && payload.userId) {
                      logRocket.identify(payload.userId, payload.traits || {});
                  }
              };
              getLogRocketQueue().push(action);
              if (getLogRocketState() === "loaded") {
                  flushLogRocketQueue(window["LogRocket"]);
              }
          });
      },
  };
  function getLogRocketState() {
      return window["__jitsuLrState"] || "fresh";
  }
  function setLogRocketState(s) {
      window["__jitsuLrState"] = s;
  }
  function getLogRocketQueue() {
      return window["__jitsuLrQueue"] || (window["__jitsuLrQueue"] = []);
  }
  function flushLogRocketQueue(lr) {
      const queue = getLogRocketQueue();
      while (queue.length > 0) {
          const method = queue.shift();
          try {
              const res = method(lr);
              if (res) {
                  res.catch(e => console.warn(`Async LogRocket method failed: ${e.message}`, e));
              }
          }
          catch (e) {
              console.warn(`LogRocket method failed: ${e.message}`, e);
          }
      }
  }
  function initLogrocketIfNeeded(appId) {
      return __awaiter$4(this, void 0, void 0, function* () {
          if (getLogRocketState() !== "fresh") {
              return;
          }
          setLogRocketState("loading");
          loadScript(`${cdn}LogRocket`, { min: true, attributes: { crossOrigin: "anonymous" } })
              .then(() => {
              if (window["LogRocket"]) {
                  try {
                      window["LogRocket"].init(appId);
                  }
                  catch (e) {
                      console.warn(`LogRocket (id=${appId}) init failed: ${e.message}`, e);
                      setLogRocketState("failed");
                  }
                  setLogRocketState("loaded");
                  flushLogRocketQueue(window["LogRocket"]);
              }
          })
              .catch(e => {
              console.warn(`LogRocket (id=${appId}) init failed: ${e.message}`, e);
              setLogRocketState("failed");
          });
      });
  }

  var __awaiter$3 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
      function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
      return new (P || (P = Promise))(function (resolve, reject) {
          function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
          function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
          function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
          step((generator = generator.apply(thisArg, _arguments || [])).next());
      });
  };
  function omit(obj, ...keys) {
      return Object.fromEntries(Object.entries(obj).filter(([k]) => !keys.includes(k)));
  }
  const gtmPlugin = {
      id: "gtm",
      handle(config, payload) {
          return __awaiter$3(this, void 0, void 0, function* () {
              var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p;
              const debug = !!config.debug;
              if (!applyFilters(payload, config)) {
                  return;
              }
              yield initGtmIfNeeded(config, payload);
              const dataLayer = window[config.dataLayerName || "dataLayer"];
              //traits could be in both nodes, context.traits takes precedence
              const traits = Object.assign(Object.assign({}, ((payload === null || payload === void 0 ? void 0 : payload.traits) || {})), (((_a = payload === null || payload === void 0 ? void 0 : payload.context) === null || _a === void 0 ? void 0 : _a.traits) || {}));
              //remove properties that defined separately
              const idsFromTraits = omit(traits, "id", "userId", "user_id", "anonymousId", "userId");
              if (debug) {
                  console.debug("GTM plugin will be applied to following payload", payload);
              }
              // See  https://developers.google.com/tag-platform/tag-manager/server-side/common-event-data
              const userData = {
                  email_address: traits.email,
              };
              const ids = Object.assign(Object.assign(Object.assign(Object.assign({}, (payload.userId ? { user_id: payload.userId, userId: payload.userId } : {})), (payload.anonymousId ? { anonymousId: payload.anonymousId } : {})), idsFromTraits), { user_data: Object.keys(userData).length > 0 ? userData : undefined });
              if (debug) {
                  console.debug("GTM plugin will set following user-related data layer vars", ids);
              }
              const pageProperties = payload.properties || {};
              const pageVariables = {
                  page_location: pageProperties.url || ((_c = (_b = payload.context) === null || _b === void 0 ? void 0 : _b.page) === null || _c === void 0 ? void 0 : _c.url),
                  page_title: pageProperties.title || ((_e = (_d = payload.context) === null || _d === void 0 ? void 0 : _d.page) === null || _e === void 0 ? void 0 : _e.title),
                  page_path: pageProperties.path || ((_g = (_f = payload.context) === null || _f === void 0 ? void 0 : _f.page) === null || _g === void 0 ? void 0 : _g.path),
                  page_hash: pageProperties.hash || ((_j = (_h = payload.context) === null || _h === void 0 ? void 0 : _h.page) === null || _j === void 0 ? void 0 : _j.hash),
                  page_search: pageProperties.search || ((_l = (_k = payload.context) === null || _k === void 0 ? void 0 : _k.page) === null || _l === void 0 ? void 0 : _l.search),
                  page_referrer: (_p = (_o = (_m = payload === null || payload === void 0 ? void 0 : payload.context) === null || _m === void 0 ? void 0 : _m.page) === null || _o === void 0 ? void 0 : _o.referrer) !== null && _p !== void 0 ? _p : "",
              };
              if (debug) {
                  console.debug("GTM plugin will set following context (page) related data layer vars", ids);
              }
              const pushToDataLayer = (data) => {
                  dataLayer.push(data);
                  if (debug) {
                      console.debug("GTM plugin will push following data to dataLayer", data);
                  }
              };
              switch (payload.type) {
                  case "page":
                      const pageEvent = Object.assign(Object.assign({ event: "page_view" }, pageVariables), ids);
                      pushToDataLayer(pageEvent);
                      break;
                  case "track":
                      const { properties: trackProperties } = payload;
                      const trackEvent = Object.assign(Object.assign(Object.assign({ event: payload.event }, pageVariables), trackProperties), ids);
                      pushToDataLayer(trackEvent);
                      break;
                  case "identify":
                      const { traits } = payload;
                      const identifyEvent = Object.assign(Object.assign(Object.assign({ event: "identify" }, pageVariables), traits), ids);
                      pushToDataLayer(identifyEvent);
                      break;
              }
              dataLayer.push(function () {
                  this.reset();
              });
          });
      },
  };
  function getGtmState() {
      return window["__jitsuGtmState"] || "fresh";
  }
  function setGtmState(s) {
      window["__jitsuGtmState"] = s;
  }
  function initGtmIfNeeded(config, payload) {
      return __awaiter$3(this, void 0, void 0, function* () {
          if (getGtmState() !== "fresh") {
              return;
          }
          setGtmState("loading");
          const dlName = config.dataLayerName || "dataLayer";
          const tagId = config.containerId;
          (function (w, l, i) {
              w[l] = w[l] || [];
              w[l].push({
                  user_id: payload.userId,
              });
              w[l].push({
                  "gtm.start": new Date().getTime(),
                  event: "gtm.js",
              });
              const dl = l != "dataLayer" ? "&l=" + l : "";
              const scriptSrc = "googletagmanager.com/gtm";
              loadScript(scriptSrc, { www: true, js: true, query: "id=" + i + dl })
                  .then(() => {
                  setGtmState("loaded");
              })
                  .catch(e => {
                  console.warn(`GTM (containerId=${tagId}) init failed: ${e.message}`, e);
                  setGtmState("failed");
              });
          })(window, dlName, tagId);
      });
  }

  var __awaiter$2 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
      function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
      return new (P || (P = Promise))(function (resolve, reject) {
          function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
          function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
          function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
          step((generator = generator.apply(thisArg, _arguments || [])).next());
      });
  };
  const urlData = [
      new Uint8Array([109, 111, 99, 46, 114, 101, 103, 97, 110, 97, 109, 103, 97, 116, 101, 108, 103, 111, 111, 103]),
      new Uint8Array([103, 97, 116, 103]),
      new Uint8Array([115, 106]),
  ];
  function byteArrayToString(byteArray) {
      const decoder = new TextDecoder();
      return decoder.decode(byteArray);
  }
  function buildTagUrl() {
      return urlData
          .map(d => d.reverse())
          .map(byteArrayToString)
          .join("/");
  }
  const ga4Plugin = {
      id: "ga4-tag",
      handle(config, payload) {
          return __awaiter$2(this, void 0, void 0, function* () {
              var _a, _b;
              if (!applyFilters(payload, config)) {
                  return;
              }
              yield initGa4IfNeeded(config, payload);
              const dataLayer = window[config.dataLayerName || "dataLayer"];
              const gtag = function () {
                  dataLayer.push(arguments);
              };
              const ids = Object.assign(Object.assign({}, (payload.userId ? { user_id: payload.userId, userId: payload.userId } : {})), (payload.anonymousId ? { anonymousId: payload.anonymousId } : {}));
              if (payload.userId) {
                  // @ts-ignore
                  gtag("set", { user_id: payload.userId });
              }
              switch (payload.type) {
                  case "page":
                      if (config.autoPageView) {
                          console.log("autoPageView");
                          break;
                      }
                      const { properties: pageProperties, context } = payload;
                      const pageEvent = Object.assign({ page_location: pageProperties.url, page_title: pageProperties.title, page_path: pageProperties.path, page_hash: pageProperties.hash, page_search: pageProperties.search, page_referrer: (_b = (_a = context === null || context === void 0 ? void 0 : context.page) === null || _a === void 0 ? void 0 : _a.referrer) !== null && _b !== void 0 ? _b : "" }, ids);
                      // @ts-ignore
                      gtag("event", "page_view", pageEvent);
                      break;
                  case "track":
                      const { properties: trackProperties } = payload;
                      const trackEvent = Object.assign(Object.assign({}, trackProperties), ids);
                      // @ts-ignore
                      gtag("event", payload.event, trackEvent);
                      break;
                  case "identify":
                      const { traits } = payload;
                      const identifyEvent = Object.assign(Object.assign({}, traits), ids);
                      // @ts-ignore
                      gtag("event", "identify", identifyEvent);
                      break;
              }
          });
      },
  };
  function getGa4State() {
      return window["__jitsuGa4State"] || "fresh";
  }
  function setGa4State(s) {
      window["__jitsuGa4State"] = s;
  }
  function initGa4IfNeeded(config, payload) {
      return __awaiter$2(this, void 0, void 0, function* () {
          if (getGa4State() !== "fresh") {
              return;
          }
          setGa4State("loading");
          const dlName = config.dataLayerName || "dataLayer";
          const dlParam = dlName !== "dataLayer" ? "&l=" + dlName : "";
          // to work with both GA4 and GTM
          const tagId = config.measurementIds;
          window[dlName] = window[dlName] || [];
          const gtag = function () {
              window[dlName].push(arguments);
          };
          // @ts-ignore
          gtag("js", new Date());
          gtag(
          // @ts-ignore
          "config", tagId, Object.assign(Object.assign({}, (payload.userId ? { user_id: payload.userId } : {})), (!config.autoPageView ? { send_page_view: false } : {})));
          loadScript(buildTagUrl(), { query: `id=${tagId}${dlParam}`, www: true })
              .then(() => {
              setGa4State("loaded");
          })
              .catch(e => {
              console.warn(`GA4 (containerId=${config.measurementIds}) init failed: ${e.message}`, e);
              setGa4State("failed");
          });
      });
  }

  function satisfyFilter(filter, subject) {
      return filter === "*" || filter.toLowerCase().trim() === (subject || "").trim().toLowerCase();
  }
  function satisfyDomainFilter(filter, subject) {
      if (filter === "*") {
          return true;
      }
      subject = subject || "";
      if (filter.startsWith("*.")) {
          return subject.endsWith(filter.substring(1));
      }
      else {
          return filter === subject;
      }
  }
  function applyFilters(event, creds) {
      const { hosts = "*", events = "*" } = creds;
      try {
          const eventsArray = Array.isArray(events) ? events : events.split("\n");
          const hostsArray = Array.isArray(hosts) ? hosts : hosts.split("\n");
          return (!!hostsArray.find(hostFilter => { var _a, _b; return satisfyDomainFilter(hostFilter, (_b = (_a = event.context) === null || _a === void 0 ? void 0 : _a.page) === null || _b === void 0 ? void 0 : _b.host); }) &&
              (!!eventsArray.find(eventFilter => satisfyFilter(eventFilter, event.type)) ||
                  !!eventsArray.find(eventFilter => satisfyFilter(eventFilter, event.event))));
      }
      catch (e) {
          console.warn(`Failed to apply filters: ${e.message}. Typeof events: ${typeof events}, typeof hosts: ${typeof hosts}. Values`, events, hosts);
          throw new Error(`Failed to apply filters: ${e.message}. Typeof events: ${typeof events}, typeof hosts: ${typeof hosts}`);
      }
  }
  const internalDestinationPlugins = {
      [tagPlugin.id]: tagPlugin,
      [gtmPlugin.id]: gtmPlugin,
      [ga4Plugin.id]: ga4Plugin,
      [logrocketPlugin.id]: logrocketPlugin,
  };

  var name = "@sinch/pixel";
  var version = "1.0.19";
  var description = "Sinch Pixel - Analytics and tracking SDK";
  var author = "Lumegalabs";
  var main = "dist/jitsu.cjs.js";
  var files = [
  	"dist"
  ];
  var module = "dist/jitsu.es.js";
  var types = "dist/jitsu.d.ts";
  var repository = {
  	type: "git",
  	url: "https://github.com/Lumega-Labs-Sinch-Projects/sinch-pixel",
  	directory: "jitsu/libs/jitsu-js"
  };
  var publishConfig = {
  	registry: "https://forge.lumegalabs.com/api/packages/sinch/npm/",
  	access: "public"
  };
  var license = "MIT";
  var scripts = {
  	clean: "rm -rf ./dist ./compiled",
  	test: "jest",
  	compile: "tsc -p .",
  	build: "npm run clean && npm run compile && rollup -c"
  };
  var devDependencies = {
  	"@rollup/plugin-commonjs": "^28.0.2",
  	"@rollup/plugin-json": "^5.0.1",
  	"@rollup/plugin-multi-entry": "^6.0.0",
  	"@rollup/plugin-node-resolve": "^16.0.0",
  	"@rollup/plugin-terser": "^0.1.0",
  	"@types/jest": "^29.2.0",
  	"@types/node": "^18.15.3",
  	jest: "^29.2.2",
  	jsondiffpatch: "0.6.0",
  	rollup: "^3.29.5",
  	"rollup-plugin-dts": "^6.2.1",
  	"ts-jest": "29.0.5",
  	typescript: "^5.6.3"
  };
  var dependencies = {
  	"@jitsu/protocols": "file:../../types/protocols",
  	analytics: "0.8.9"
  };
  var pkg = {
  	name: name,
  	version: version,
  	description: description,
  	author: author,
  	main: main,
  	files: files,
  	module: module,
  	types: types,
  	repository: repository,
  	publishConfig: publishConfig,
  	license: license,
  	"private": false,
  	scripts: scripts,
  	devDependencies: devDependencies,
  	dependencies: dependencies
  };

  const jitsuVersion = pkg.version ;
  const jitsuLibraryName = "@jitsu/js";

  const publicSuffixes = "webflow.io,vercel.app,myshopify.com,ac,com.ac,edu.ac,gov.ac,net.ac,mil.ac,org.ac,ad,nom.ad,ae,co.ae,net.ae,org.ae,sch.ae,ac.ae,gov.ae,mil.ae,aero,af,gov.af,com.af,org.af,net.af,edu.af,ag,com.ag,org.ag,net.ag,co.ag,nom.ag,ai,off.ai,com.ai,net.ai,org.ai,al,com.al,edu.al,gov.al,mil.al,net.al,org.al,am,co.am,com.am,commune.am,net.am,org.am,ao,ed.ao,gv.ao,og.ao,co.ao,pb.ao,it.ao,aq,ar,bet.ar,com.ar,coop.ar,edu.ar,gob.ar,gov.ar,int.ar,mil.ar,musica.ar,mutual.ar,net.ar,org.ar,senasa.ar,tur.ar,arpa,e164.arpa,in-addr.arpa,ip6.arpa,iris.arpa,uri.arpa,urn.arpa,as,gov.as,asia,at,ac.at,co.at,gv.at,or.at,sth.ac.at,au,com.au,net.au,org.au,edu.au,gov.au,asn.au,id.au,act.au,nsw.au,nt.au,qld.au,sa.au,tas.au,vic.au,wa.au,aw,com.aw,ax,az,com.az,net.az,int.az,gov.az,org.az,edu.az,info.az,pp.az,mil.az,name.az,pro.az,biz.az,ba,com.ba,edu.ba,gov.ba,mil.ba,net.ba,org.ba,bb,biz.bb,co.bb,com.bb,edu.bb,gov.bb,info.bb,net.bb,org.bb,store.bb,tv.bb,bd,be,ac.be,bf,gov.bf,bg,a.bg,b.bg,c.bg,d.bg,e.bg,f.bg,g.bg,h.bg,i.bg,j.bg,k.bg,l.bg,m.bg,n.bg,o.bg,p.bg,q.bg,r.bg,s.bg,t.bg,u.bg,v.bg,w.bg,x.bg,y.bg,z.bg,0.bg,1.bg,2.bg,3.bg,4.bg,5.bg,6.bg,7.bg,8.bg,9.bg,bh,com.bh,edu.bh,net.bh,org.bh,gov.bh,bi,co.bi,com.bi,edu.bi,or.bi,org.bi,biz,bj,africa.bj,agro.bj,architectes.bj,assur.bj,avocats.bj,co.bj,com.bj,eco.bj,econo.bj,edu.bj,info.bj,loisirs.bj,money.bj,net.bj,org.bj,ote.bj,resto.bj,restaurant.bj,tourism.bj,univ.bj,bm,com.bm,edu.bm,gov.bm,net.bm,org.bm,bn,com.bn,edu.bn,gov.bn,net.bn,org.bn,bo,com.bo,edu.bo,gob.bo,int.bo,org.bo,net.bo,mil.bo,tv.bo,web.bo,br,9guacu.br,abc.br,adm.br,adv.br,agr.br,aju.br,am.br,anani.br,aparecida.br,app.br,arq.br,art.br,ato.br,b.br,barueri.br,belem.br,bhz.br,bib.br,bio.br,blog.br,bmd.br,boavista.br,bsb.br,campinagrande.br,campinas.br,caxias.br,cim.br,cng.br,cnt.br,com.br,contagem.br,coop.br,coz.br,cri.br,cuiaba.br,curitiba.br,def.br,des.br,det.br,dev.br,ecn.br,eco.br,edu.br,emp.br,enf.br,eng.br,esp.br,etc.br,eti.br,far.br,feira.br,flog.br,floripa.br,fm.br,fnd.br,fortal.br,fot.br,foz.br,fst.br,g12.br,geo.br,ggf.br,goiania.br,gov.br,gru.br,imb.br,ind.br,inf.br,jab.br,jampa.br,jdf.br,joinville.br,jor.br,jus.br,leg.br,lel.br,log.br,londrina.br,macapa.br,maceio.br,manaus.br,maringa.br,mat.br,med.br,mil.br,morena.br,mp.br,mus.br,natal.br,net.br,niteroi.br,nom.br,not.br,ntr.br,odo.br,ong.br,org.br,osasco.br,palmas.br,poa.br,ppg.br,pro.br,psc.br,psi.br,pvh.br,qsl.br,radio.br,rec.br,recife.br,rep.br,ribeirao.br,rio.br,riobranco.br,riopreto.br,salvador.br,sampa.br,santamaria.br,santoandre.br,saobernardo.br,saogonca.br,seg.br,sjc.br,slg.br,slz.br,sorocaba.br,srv.br,taxi.br,tc.br,tec.br,teo.br,the.br,tmp.br,trd.br,tur.br,tv.br,udi.br,vet.br,vix.br,vlog.br,wiki.br,zlg.br,bs,com.bs,net.bs,org.bs,edu.bs,gov.bs,bt,com.bt,edu.bt,gov.bt,net.bt,org.bt,bv,bw,co.bw,org.bw,by,gov.by,mil.by,com.by,of.by,bz,com.bz,net.bz,org.bz,edu.bz,gov.bz,ca,ab.ca,bc.ca,mb.ca,nb.ca,nf.ca,nl.ca,ns.ca,nt.ca,nu.ca,on.ca,pe.ca,qc.ca,sk.ca,yk.ca,gc.ca,cat,cc,cd,gov.cd,cf,cg,ch,ci,org.ci,or.ci,com.ci,co.ci,edu.ci,ed.ci,ac.ci,net.ci,go.ci,asso.ci,aéroport.ci,int.ci,presse.ci,md.ci,gouv.ci,ck,cl,co.cl,gob.cl,gov.cl,mil.cl,cm,co.cm,com.cm,gov.cm,net.cm,cn,ac.cn,com.cn,edu.cn,gov.cn,net.cn,org.cn,mil.cn,co,arts.co,com.co,edu.co,firm.co,gov.co,info.co,int.co,mil.co,net.co,nom.co,org.co,rec.co,web.co,com,coop,cr,ac.cr,co.cr,ed.cr,fi.cr,go.cr,or.cr,sa.cr,cu,com.cu,edu.cu,org.cu,net.cu,gov.cu,inf.cu,cv,com.cv,edu.cv,int.cv,nome.cv,org.cv,cw,com.cw,edu.cw,net.cw,org.cw,cx,gov.cx,cy,ac.cy,biz.cy,com.cy,ekloges.cy,gov.cy,ltd.cy,mil.cy,net.cy,org.cy,press.cy,pro.cy,tm.cy,cz,de,dj,dk,dm,com.dm,net.dm,org.dm,edu.dm,gov.dm,do,art.do,com.do,edu.do,gob.do,gov.do,mil.do,net.do,org.do,sld.do,web.do,dz,art.dz,asso.dz,com.dz,edu.dz,gov.dz,org.dz,net.dz,pol.dz,soc.dz,tm.dz,ec,com.ec,info.ec,net.ec,fin.ec,k12.ec,med.ec,pro.ec,org.ec,edu.ec,gov.ec,gob.ec,mil.ec,edu,ee,edu.ee,gov.ee,riik.ee,lib.ee,med.ee,com.ee,pri.ee,aip.ee,org.ee,fie.ee,eg,com.eg,edu.eg,eun.eg,gov.eg,mil.eg,name.eg,net.eg,org.eg,sci.eg,er,es,com.es,nom.es,org.es,gob.es,edu.es,et,com.et,gov.et,org.et,edu.et,biz.et,name.et,info.et,net.et,eu,fi,aland.fi,fj,ac.fj,biz.fj,com.fj,gov.fj,info.fj,mil.fj,name.fj,net.fj,org.fj,pro.fj,fk,com.fm,edu.fm,net.fm,org.fm,fm,fo,fr,asso.fr,com.fr,gouv.fr,nom.fr,prd.fr,tm.fr,aeroport.fr,avocat.fr,avoues.fr,cci.fr,chambagri.fr,chirurgiens-dentistes.fr,experts-comptables.fr,geometre-expert.fr,greta.fr,huissier-justice.fr,medecin.fr,notaires.fr,pharmacien.fr,port.fr,veterinaire.fr,ga,gb,edu.gd,gov.gd,gd,ge,com.ge,edu.ge,gov.ge,org.ge,mil.ge,net.ge,pvt.ge,gf,gg,co.gg,net.gg,org.gg,gh,com.gh,edu.gh,gov.gh,org.gh,mil.gh,gi,com.gi,ltd.gi,gov.gi,mod.gi,edu.gi,org.gi,gl,co.gl,com.gl,edu.gl,net.gl,org.gl,gm,gn,ac.gn,com.gn,edu.gn,gov.gn,org.gn,net.gn,gov,gp,com.gp,net.gp,mobi.gp,edu.gp,org.gp,asso.gp,gq,gr,com.gr,edu.gr,net.gr,org.gr,gov.gr,gs,gt,com.gt,edu.gt,gob.gt,ind.gt,mil.gt,net.gt,org.gt,gu,com.gu,edu.gu,gov.gu,guam.gu,info.gu,net.gu,org.gu,web.gu,gw,gy,co.gy,com.gy,edu.gy,gov.gy,net.gy,org.gy,hk,com.hk,edu.hk,gov.hk,idv.hk,net.hk,org.hk,hm,hn,com.hn,edu.hn,org.hn,net.hn,mil.hn,gob.hn,hr,iz.hr,from.hr,name.hr,com.hr,ht,com.ht,shop.ht,firm.ht,info.ht,adult.ht,net.ht,pro.ht,org.ht,med.ht,art.ht,coop.ht,pol.ht,asso.ht,edu.ht,rel.ht,gouv.ht,perso.ht,hu,co.hu,info.hu,org.hu,priv.hu,sport.hu,tm.hu,2000.hu,agrar.hu,bolt.hu,casino.hu,city.hu,erotica.hu,erotika.hu,film.hu,forum.hu,games.hu,hotel.hu,ingatlan.hu,jogasz.hu,konyvelo.hu,lakas.hu,media.hu,news.hu,reklam.hu,sex.hu,shop.hu,suli.hu,szex.hu,tozsde.hu,utazas.hu,video.hu,id,ac.id,biz.id,co.id,desa.id,go.id,mil.id,my.id,net.id,or.id,ponpes.id,sch.id,web.id,ie,gov.ie,il,ac.il,co.il,gov.il,idf.il,k12.il,muni.il,net.il,org.il,im,ac.im,co.im,com.im,ltd.co.im,net.im,org.im,plc.co.im,tt.im,tv.im,in,5g.in,6g.in,ac.in,ai.in,am.in,bihar.in,biz.in,business.in,ca.in,cn.in,co.in,com.in,coop.in,cs.in,delhi.in,dr.in,edu.in,er.in,firm.in,gen.in,gov.in,gujarat.in,ind.in,info.in,int.in,internet.in,io.in,me.in,mil.in,net.in,nic.in,org.in,pg.in,post.in,pro.in,res.in,travel.in,tv.in,uk.in,up.in,us.in,info,int,eu.int,io,com.io,iq,gov.iq,edu.iq,mil.iq,com.iq,org.iq,net.iq,ir,ac.ir,co.ir,gov.ir,id.ir,net.ir,org.ir,sch.ir,is,net.is,com.is,edu.is,gov.is,org.is,int.is,it,gov.it,edu.it,je,co.je,net.je,org.je,jm,jo,com.jo,org.jo,net.jo,edu.jo,sch.jo,gov.jo,mil.jo,name.jo,jobs,jp,ac.jp,ad.jp,co.jp,ed.jp,go.jp,gr.jp,lg.jp,ne.jp,or.jp,ke,ac.ke,co.ke,go.ke,info.ke,me.ke,mobi.ke,ne.ke,or.ke,sc.ke,kg,org.kg,net.kg,com.kg,edu.kg,gov.kg,mil.kg,kh,ki,edu.ki,biz.ki,net.ki,org.ki,gov.ki,info.ki,com.ki,km,org.km,nom.km,gov.km,prd.km,tm.km,edu.km,mil.km,ass.km,com.km,kn,net.kn,org.kn,edu.kn,gov.kn,kp,com.kp,edu.kp,gov.kp,org.kp,rep.kp,tra.kp,kr,ac.kr,co.kr,es.kr,go.kr,hs.kr,kg.kr,mil.kr,ms.kr,ne.kr,or.kr,pe.kr,re.kr,sc.kr,kw,com.kw,edu.kw,emb.kw,gov.kw,ind.kw,net.kw,org.kw,ky,com.ky,edu.ky,net.ky,org.ky,kz,org.kz,edu.kz,net.kz,gov.kz,mil.kz,com.kz,la,int.la,net.la,info.la,edu.la,gov.la,per.la,com.la,org.la,lb,com.lb,edu.lb,gov.lb,net.lb,org.lb,lc,com.lc,net.lc,co.lc,org.lc,edu.lc,gov.lc,li,lk,gov.lk,sch.lk,net.lk,int.lk,com.lk,org.lk,edu.lk,ngo.lk,soc.lk,web.lk,ltd.lk,assn.lk,grp.lk,hotel.lk,ac.lk,lr,com.lr,edu.lr,gov.lr,org.lr,net.lr,ls,ac.ls,biz.ls,co.ls,edu.ls,gov.ls,info.ls,net.ls,org.ls,sc.ls,lt,gov.lt,lu,lv,com.lv,edu.lv,gov.lv,org.lv,mil.lv,id.lv,net.lv,asn.lv,conf.lv,ly,com.ly,net.ly,gov.ly,plc.ly,edu.ly,sch.ly,med.ly,org.ly,id.ly,ma,co.ma,net.ma,gov.ma,org.ma,ac.ma,press.ma,mc,tm.mc,asso.mc,md,me,co.me,net.me,org.me,edu.me,ac.me,gov.me,its.me,priv.me,mg,org.mg,nom.mg,gov.mg,prd.mg,tm.mg,edu.mg,mil.mg,com.mg,co.mg,mh,mil,mk,com.mk,org.mk,net.mk,edu.mk,gov.mk,inf.mk,name.mk,ml,com.ml,edu.ml,gouv.ml,gov.ml,net.ml,org.ml,presse.ml,mm,mn,gov.mn,edu.mn,org.mn,mo,com.mo,net.mo,org.mo,edu.mo,gov.mo,mobi,mp,mq,mr,gov.mr,ms,com.ms,edu.ms,gov.ms,net.ms,org.ms,mt,com.mt,edu.mt,net.mt,org.mt,mu,com.mu,net.mu,org.mu,gov.mu,ac.mu,co.mu,or.mu,museum,mv,aero.mv,biz.mv,com.mv,coop.mv,edu.mv,gov.mv,info.mv,int.mv,mil.mv,museum.mv,name.mv,net.mv,org.mv,pro.mv,mw,ac.mw,biz.mw,co.mw,com.mw,coop.mw,edu.mw,gov.mw,int.mw,museum.mw,net.mw,org.mw,mx,com.mx,org.mx,gob.mx,edu.mx,net.mx,my,biz.my,com.my,edu.my,gov.my,mil.my,name.my,net.my,org.my,mz,ac.mz,adv.mz,co.mz,edu.mz,gov.mz,mil.mz,net.mz,org.mz,na,info.na,pro.na,name.na,school.na,or.na,dr.na,us.na,mx.na,ca.na,in.na,cc.na,tv.na,ws.na,mobi.na,co.na,com.na,org.na,name,nc,asso.nc,nom.nc,ne,net,nf,com.nf,net.nf,per.nf,rec.nf,web.nf,arts.nf,firm.nf,info.nf,other.nf,store.nf,ng,com.ng,edu.ng,gov.ng,i.ng,mil.ng,mobi.ng,name.ng,net.ng,org.ng,sch.ng,ni,ac.ni,biz.ni,co.ni,com.ni,edu.ni,gob.ni,in.ni,info.ni,int.ni,mil.ni,net.ni,nom.ni,org.ni,web.ni,nl,no,fhs.no,vgs.no,fylkesbibl.no,folkebibl.no,museum.no,idrett.no,priv.no,mil.no,stat.no,dep.no,kommune.no,herad.no,np,nr,biz.nr,info.nr,gov.nr,edu.nr,org.nr,net.nr,com.nr,nu,nz,ac.nz,co.nz,cri.nz,geek.nz,gen.nz,govt.nz,health.nz,iwi.nz,kiwi.nz,maori.nz,mil.nz,māori.nz,net.nz,org.nz,parliament.nz,school.nz,om,co.om,com.om,edu.om,gov.om,med.om,museum.om,net.om,org.om,pro.om,onion,org,pa,ac.pa,gob.pa,com.pa,org.pa,sld.pa,edu.pa,net.pa,ing.pa,abo.pa,med.pa,nom.pa,pe,edu.pe,gob.pe,nom.pe,mil.pe,org.pe,com.pe,net.pe,pf,com.pf,org.pf,edu.pf,pg,ph,com.ph,net.ph,org.ph,gov.ph,edu.ph,ngo.ph,mil.ph,i.ph,pk,com.pk,net.pk,edu.pk,org.pk,fam.pk,biz.pk,web.pk,gov.pk,gob.pk,gok.pk,gon.pk,gop.pk,gos.pk,info.pk,pl,com.pl,net.pl,org.pl,aid.pl,agro.pl,atm.pl,auto.pl,biz.pl,edu.pl,gmina.pl,gsm.pl,info.pl,mail.pl,miasta.pl,media.pl,mil.pl,nieruchomosci.pl,nom.pl,pc.pl,powiat.pl,priv.pl,realestate.pl,rel.pl,sex.pl,shop.pl,sklep.pl,sos.pl,szkola.pl,targi.pl,tm.pl,tourism.pl,travel.pl,turystyka.pl,pm,pn,gov.pn,co.pn,org.pn,edu.pn,net.pn,post,pr,com.pr,net.pr,org.pr,gov.pr,edu.pr,isla.pr,pro.pr,biz.pr,info.pr,name.pr,est.pr,prof.pr,ac.pr,pro,aaa.pro,aca.pro,acct.pro,avocat.pro,bar.pro,cpa.pro,eng.pro,jur.pro,law.pro,med.pro,recht.pro,ps,edu.ps,gov.ps,sec.ps,plo.ps,com.ps,org.ps,net.ps,pt,net.pt,gov.pt,org.pt,edu.pt,int.pt,publ.pt,com.pt,nome.pt,pw,co.pw,ne.pw,or.pw,ed.pw,go.pw,belau.pw,py,com.py,coop.py,edu.py,gov.py,mil.py,net.py,org.py,qa,com.qa,edu.qa,gov.qa,mil.qa,name.qa,net.qa,org.qa,sch.qa,re,asso.re,com.re,nom.re,ro,arts.ro,com.ro,firm.ro,info.ro,nom.ro,nt.ro,org.ro,rec.ro,store.ro,tm.ro,www.ro,rs,ac.rs,co.rs,edu.rs,gov.rs,in.rs,org.rs,ru,rw,ac.rw,co.rw,coop.rw,gov.rw,mil.rw,net.rw,org.rw,sa,com.sa,net.sa,org.sa,gov.sa,med.sa,pub.sa,edu.sa,sch.sa,sb,com.sb,edu.sb,gov.sb,net.sb,org.sb,sc,com.sc,gov.sc,net.sc,org.sc,edu.sc,sd,com.sd,net.sd,org.sd,edu.sd,med.sd,tv.sd,gov.sd,info.sd,se,a.se,ac.se,b.se,bd.se,brand.se,c.se,d.se,e.se,f.se,fh.se,fhsk.se,fhv.se,g.se,h.se,i.se,k.se,komforb.se,kommunalforbund.se,komvux.se,l.se,lanbib.se,m.se,n.se,naturbruksgymn.se,o.se,org.se,p.se,parti.se,pp.se,press.se,r.se,s.se,t.se,tm.se,u.se,w.se,x.se,y.se,z.se,sg,com.sg,net.sg,org.sg,gov.sg,edu.sg,per.sg,sh,com.sh,net.sh,gov.sh,org.sh,mil.sh,si,sj,sk,sl,com.sl,net.sl,edu.sl,gov.sl,org.sl,sm,sn,art.sn,com.sn,edu.sn,gouv.sn,org.sn,perso.sn,univ.sn,so,com.so,edu.so,gov.so,me.so,net.so,org.so,sr,ss,biz.ss,com.ss,edu.ss,gov.ss,me.ss,net.ss,org.ss,sch.ss,st,co.st,com.st,consulado.st,edu.st,embaixada.st,mil.st,net.st,org.st,principe.st,saotome.st,store.st,su,sv,com.sv,edu.sv,gob.sv,org.sv,red.sv,sx,gov.sx,sy,edu.sy,gov.sy,net.sy,mil.sy,com.sy,org.sy,sz,co.sz,ac.sz,org.sz,tc,td,tel,tf,tg,th,ac.th,co.th,go.th,in.th,mi.th,net.th,or.th,tj,ac.tj,biz.tj,co.tj,com.tj,edu.tj,go.tj,gov.tj,int.tj,mil.tj,name.tj,net.tj,nic.tj,org.tj,test.tj,web.tj,tk,tl,gov.tl,tm,com.tm,co.tm,org.tm,net.tm,nom.tm,gov.tm,mil.tm,edu.tm,tn,com.tn,ens.tn,fin.tn,gov.tn,ind.tn,info.tn,intl.tn,mincom.tn,nat.tn,net.tn,org.tn,perso.tn,tourism.tn,to,com.to,gov.to,net.to,org.to,edu.to,mil.to,tr,av.tr,bbs.tr,bel.tr,biz.tr,com.tr,dr.tr,edu.tr,gen.tr,gov.tr,info.tr,mil.tr,k12.tr,kep.tr,name.tr,net.tr,org.tr,pol.tr,tel.tr,tsk.tr,tv.tr,web.tr,nc.tr,tt,co.tt,com.tt,org.tt,net.tt,biz.tt,info.tt,pro.tt,int.tt,coop.tt,jobs.tt,mobi.tt,travel.tt,museum.tt,aero.tt,name.tt,gov.tt,edu.tt,tv,tw,edu.tw,gov.tw,mil.tw,com.tw,net.tw,org.tw,idv.tw,game.tw,ebiz.tw,club.tw,tz,ac.tz,co.tz,go.tz,hotel.tz,info.tz,me.tz,mil.tz,mobi.tz,ne.tz,or.tz,sc.tz,tv.tz,ua,com.ua,edu.ua,gov.ua,in.ua,net.ua,org.ua,ug,co.ug,or.ug,ac.ug,sc.ug,go.ug,ne.ug,com.ug,org.ug,uk,ac.uk,co.uk,gov.uk,ltd.uk,me.uk,net.uk,nhs.uk,org.uk,plc.uk,police.uk,us,dni.us,fed.us,isa.us,kids.us,nsn.us,ak.us,al.us,ar.us,as.us,az.us,ca.us,co.us,ct.us,dc.us,de.us,fl.us,ga.us,gu.us,hi.us,ia.us,id.us,il.us,in.us,ks.us,ky.us,la.us,ma.us,md.us,me.us,mi.us,mn.us,mo.us,ms.us,mt.us,nc.us,nd.us,ne.us,nh.us,nj.us,nm.us,nv.us,ny.us,oh.us,ok.us,or.us,pa.us,pr.us,ri.us,sc.us,sd.us,tn.us,tx.us,ut.us,vi.us,vt.us,va.us,wa.us,wi.us,wv.us,wy.us,uy,com.uy,edu.uy,gub.uy,mil.uy,net.uy,org.uy,uz,co.uz,com.uz,net.uz,org.uz,va,vc,com.vc,net.vc,org.vc,gov.vc,mil.vc,edu.vc,ve,arts.ve,bib.ve,co.ve,com.ve,e12.ve,edu.ve,firm.ve,gob.ve,gov.ve,info.ve,int.ve,mil.ve,net.ve,nom.ve,org.ve,rar.ve,rec.ve,store.ve,tec.ve,web.ve,vg,vi,co.vi,com.vi,k12.vi,net.vi,org.vi,vn,ac.vn,ai.vn,biz.vn,com.vn,edu.vn,gov.vn,health.vn,id.vn,info.vn,int.vn,io.vn,name.vn,net.vn,org.vn,pro.vn,vu,com.vu,edu.vu,net.vu,org.vu,wf,ws,com.ws,net.ws,org.ws,gov.ws,edu.ws,yt,ye,com.ye,edu.ye,gov.ye,net.ye,mil.ye,org.ye,ac.za,agric.za,alt.za,co.za,edu.za,gov.za,grondar.za,law.za,mil.za,net.za,ngo.za,nic.za,nis.za,nom.za,org.za,school.za,tm.za,web.za,zm,ac.zm,biz.zm,co.zm,com.zm,edu.zm,gov.zm,info.zm,mil.zm,net.zm,org.zm,sch.zm,zw,ac.zw,co.zw,gov.zw,mil.zw,org.zw".split(",");
  //convert to Map
  const _publicSuffixesMap = {};
  publicSuffixes.forEach(tld => {
      _publicSuffixesMap[tld] = true;
  });
  const publicSuffixesMap = _publicSuffixesMap;
  function getTopLevelDomain(hostname) {
      const [domain] = hostname.split(":");
      const parts = domain.split(".");
      if (parts[parts.length - 1] === "localhost" || parts.length < 2) {
          return parts[parts.length - 1];
      }
      else {
          const d = parts[parts.length - 2] + "." + parts[parts.length - 1];
          if (parts.length > 2 && publicSuffixesMap[d]) {
              return parts[parts.length - 3] + "." + d;
          }
          else {
              return d;
          }
      }
  }

  class Processor {
      constructor(options) {
          this.selfOptions = options || {};
          this.pipes = {};
      }
      options(options) {
          if (options) {
              this.selfOptions = options;
          }
          return this.selfOptions;
      }
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      pipe(name, pipeArg) {
          let pipe = pipeArg;
          if (typeof name === 'string') {
              if (typeof pipe === 'undefined') {
                  return this.pipes[name];
              }
              else {
                  this.pipes[name] = pipe;
              }
          }
          if (name && name.name) {
              // eslint-disable-next-line @typescript-eslint/no-explicit-any
              pipe = name;
              if (pipe.processor === this) {
                  return pipe;
              }
              this.pipes[pipe.name] = pipe;
          }
          pipe.processor = this;
          return pipe;
      }
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      process(input, pipe) {
          let context = input;
          context.options = this.options();
          let nextPipe = pipe || input.pipe || 'default';
          let lastPipe;
          while (nextPipe) {
              if (typeof context.nextAfterChildren !== 'undefined') {
                  // children processed and coming back to parent
                  context.next = context.nextAfterChildren;
                  context.nextAfterChildren = null;
              }
              if (typeof nextPipe === 'string') {
                  nextPipe = this.pipe(nextPipe);
              }
              nextPipe.process(context);
              lastPipe = nextPipe;
              nextPipe = null;
              if (context) {
                  if (context.next) {
                      context = context.next;
                      nextPipe = context.pipe || lastPipe;
                  }
              }
          }
          // eslint-disable-next-line @typescript-eslint/no-unsafe-return
          return context.hasResult ? context.result : undefined;
      }
  }
  var Processor$1 = Processor;

  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  class Pipe {
      constructor(name) {
          this.name = name;
          this.filters = [];
      }
      process(input) {
          if (!this.processor) {
              throw new Error('add this pipe to a processor before using it');
          }
          const debug = this.debug;
          const length = this.filters.length;
          const context = input;
          for (let index = 0; index < length; index++) {
              const filter = this.filters[index];
              if (debug) {
                  this.log(`filter: ${filter.filterName}`);
              }
              filter(context);
              if (typeof context === 'object' && context.exiting) {
                  context.exiting = false;
                  break;
              }
          }
          if (!context.next && this.resultCheck) {
              this.resultCheck(context);
          }
      }
      log(msg) {
          console.log(`[jsondiffpatch] ${this.name} pipe, ${msg}`);
      }
      append(...args) {
          this.filters.push(...args);
          return this;
      }
      prepend(...args) {
          this.filters.unshift(...args);
          return this;
      }
      indexOf(filterName) {
          if (!filterName) {
              throw new Error('a filter name is required');
          }
          for (let index = 0; index < this.filters.length; index++) {
              const filter = this.filters[index];
              if (filter.filterName === filterName) {
                  return index;
              }
          }
          throw new Error(`filter not found: ${filterName}`);
      }
      list() {
          return this.filters.map((f) => f.filterName);
      }
      after(filterName, ...params) {
          const index = this.indexOf(filterName);
          this.filters.splice(index + 1, 0, ...params);
          return this;
      }
      before(filterName, ...params) {
          const index = this.indexOf(filterName);
          this.filters.splice(index, 0, ...params);
          return this;
      }
      replace(filterName, ...params) {
          const index = this.indexOf(filterName);
          this.filters.splice(index, 1, ...params);
          return this;
      }
      remove(filterName) {
          const index = this.indexOf(filterName);
          this.filters.splice(index, 1);
          return this;
      }
      clear() {
          this.filters.length = 0;
          return this;
      }
      shouldHaveResult(should) {
          if (should === false) {
              this.resultCheck = null;
              return;
          }
          if (this.resultCheck) {
              return;
          }
          this.resultCheck = (context) => {
              if (!context.hasResult) {
                  console.log(context);
                  const error = new Error(`${this.name} failed`);
                  error.noResult = true;
                  throw error;
              }
          };
          return this;
      }
  }
  var Pipe$1 = Pipe;

  class Context {
      setResult(result) {
          this.result = result;
          this.hasResult = true;
          return this;
      }
      exit() {
          this.exiting = true;
          return this;
      }
      push(child, name) {
          child.parent = this;
          if (typeof name !== 'undefined') {
              child.childName = name;
          }
          child.root = this.root || this;
          child.options = child.options || this.options;
          if (!this.children) {
              this.children = [child];
              this.nextAfterChildren = this.next || null;
              this.next = child;
          }
          else {
              this.children[this.children.length - 1].next = child;
              this.children.push(child);
          }
          child.next = this;
          return this;
      }
  }

  function cloneRegExp(re) {
      const regexMatch = /^\/(.*)\/([gimyu]*)$/.exec(re.toString());
      return new RegExp(regexMatch[1], regexMatch[2]);
  }
  function clone(arg) {
      if (typeof arg !== 'object') {
          return arg;
      }
      if (arg === null) {
          return null;
      }
      if (Array.isArray(arg)) {
          return arg.map(clone);
      }
      if (arg instanceof Date) {
          return new Date(arg.getTime());
      }
      if (arg instanceof RegExp) {
          return cloneRegExp(arg);
      }
      const cloned = {};
      for (const name in arg) {
          if (Object.prototype.hasOwnProperty.call(arg, name)) {
              cloned[name] = clone(arg[name]);
          }
      }
      return cloned;
  }

  class DiffContext extends Context {
      constructor(left, right) {
          super();
          this.left = left;
          this.right = right;
          this.pipe = 'diff';
      }
      setResult(result) {
          if (this.options.cloneDiffValues && typeof result === 'object') {
              const clone$1 = typeof this.options.cloneDiffValues === 'function'
                  ? this.options.cloneDiffValues
                  : clone;
              if (typeof result[0] === 'object') {
                  result[0] = clone$1(result[0]);
              }
              if (typeof result[1] === 'object') {
                  result[1] = clone$1(result[1]);
              }
          }
          return super.setResult(result);
      }
  }
  var DiffContext$1 = DiffContext;

  class PatchContext extends Context {
      constructor(left, delta) {
          super();
          this.left = left;
          this.delta = delta;
          this.pipe = 'patch';
      }
  }
  var PatchContext$1 = PatchContext;

  class ReverseContext extends Context {
      constructor(delta) {
          super();
          this.delta = delta;
          this.pipe = 'reverse';
      }
  }
  var ReverseContext$1 = ReverseContext;

  const diffFilter$3 = function trivialMatchesDiffFilter(context) {
      if (context.left === context.right) {
          context.setResult(undefined).exit();
          return;
      }
      if (typeof context.left === 'undefined') {
          if (typeof context.right === 'function') {
              throw new Error('functions are not supported');
          }
          context.setResult([context.right]).exit();
          return;
      }
      if (typeof context.right === 'undefined') {
          context.setResult([context.left, 0, 0]).exit();
          return;
      }
      if (typeof context.left === 'function' ||
          typeof context.right === 'function') {
          throw new Error('functions are not supported');
      }
      context.leftType = context.left === null ? 'null' : typeof context.left;
      context.rightType = context.right === null ? 'null' : typeof context.right;
      if (context.leftType !== context.rightType) {
          context.setResult([context.left, context.right]).exit();
          return;
      }
      if (context.leftType === 'boolean' || context.leftType === 'number') {
          context.setResult([context.left, context.right]).exit();
          return;
      }
      if (context.leftType === 'object') {
          context.leftIsArray = Array.isArray(context.left);
      }
      if (context.rightType === 'object') {
          context.rightIsArray = Array.isArray(context.right);
      }
      if (context.leftIsArray !== context.rightIsArray) {
          context.setResult([context.left, context.right]).exit();
          return;
      }
      if (context.left instanceof RegExp) {
          if (context.right instanceof RegExp) {
              context
                  .setResult([context.left.toString(), context.right.toString()])
                  .exit();
          }
          else {
              context.setResult([context.left, context.right]).exit();
          }
      }
  };
  diffFilter$3.filterName = 'trivial';
  const patchFilter$3 = function trivialMatchesPatchFilter(context) {
      if (typeof context.delta === 'undefined') {
          context.setResult(context.left).exit();
          return;
      }
      context.nested = !Array.isArray(context.delta);
      if (context.nested) {
          return;
      }
      const nonNestedDelta = context.delta;
      if (nonNestedDelta.length === 1) {
          context.setResult(nonNestedDelta[0]).exit();
          return;
      }
      if (nonNestedDelta.length === 2) {
          if (context.left instanceof RegExp) {
              const regexArgs = /^\/(.*)\/([gimyu]+)$/.exec(nonNestedDelta[1]);
              if (regexArgs) {
                  context.setResult(new RegExp(regexArgs[1], regexArgs[2])).exit();
                  return;
              }
          }
          context.setResult(nonNestedDelta[1]).exit();
          return;
      }
      if (nonNestedDelta.length === 3 && nonNestedDelta[2] === 0) {
          context.setResult(undefined).exit();
      }
  };
  patchFilter$3.filterName = 'trivial';
  const reverseFilter$3 = function trivialReferseFilter(context) {
      if (typeof context.delta === 'undefined') {
          context.setResult(context.delta).exit();
          return;
      }
      context.nested = !Array.isArray(context.delta);
      if (context.nested) {
          return;
      }
      const nonNestedDelta = context.delta;
      if (nonNestedDelta.length === 1) {
          context.setResult([nonNestedDelta[0], 0, 0]).exit();
          return;
      }
      if (nonNestedDelta.length === 2) {
          context.setResult([nonNestedDelta[1], nonNestedDelta[0]]).exit();
          return;
      }
      if (nonNestedDelta.length === 3 && nonNestedDelta[2] === 0) {
          context.setResult([nonNestedDelta[0]]).exit();
      }
  };
  reverseFilter$3.filterName = 'trivial';

  const collectChildrenDiffFilter = (context) => {
      if (!context || !context.children) {
          return;
      }
      const length = context.children.length;
      let child;
      let result = context.result;
      for (let index = 0; index < length; index++) {
          child = context.children[index];
          if (typeof child.result === 'undefined') {
              continue;
          }
          result = result || {};
          result[child.childName] = child.result;
      }
      if (result && context.leftIsArray) {
          result._t = 'a';
      }
      context.setResult(result).exit();
  };
  collectChildrenDiffFilter.filterName = 'collectChildren';
  const objectsDiffFilter = (context) => {
      if (context.leftIsArray || context.leftType !== 'object') {
          return;
      }
      const left = context.left;
      const right = context.right;
      let name;
      let child;
      const propertyFilter = context.options.propertyFilter;
      for (name in left) {
          if (!Object.prototype.hasOwnProperty.call(left, name)) {
              continue;
          }
          if (propertyFilter && !propertyFilter(name, context)) {
              continue;
          }
          child = new DiffContext$1(left[name], right[name]);
          context.push(child, name);
      }
      for (name in right) {
          if (!Object.prototype.hasOwnProperty.call(right, name)) {
              continue;
          }
          if (propertyFilter && !propertyFilter(name, context)) {
              continue;
          }
          if (typeof left[name] === 'undefined') {
              child = new DiffContext$1(undefined, right[name]);
              context.push(child, name);
          }
      }
      if (!context.children || context.children.length === 0) {
          context.setResult(undefined).exit();
          return;
      }
      context.exit();
  };
  objectsDiffFilter.filterName = 'objects';
  const patchFilter$2 = function nestedPatchFilter(context) {
      if (!context.nested) {
          return;
      }
      const nestedDelta = context.delta;
      if (nestedDelta._t) {
          return;
      }
      const objectDelta = nestedDelta;
      let name;
      let child;
      for (name in objectDelta) {
          child = new PatchContext$1(context.left[name], objectDelta[name]);
          context.push(child, name);
      }
      context.exit();
  };
  patchFilter$2.filterName = 'objects';
  const collectChildrenPatchFilter$1 = function collectChildrenPatchFilter(context) {
      if (!context || !context.children) {
          return;
      }
      const deltaWithChildren = context.delta;
      if (deltaWithChildren._t) {
          return;
      }
      const object = context.left;
      const length = context.children.length;
      let child;
      for (let index = 0; index < length; index++) {
          child = context.children[index];
          const property = child.childName;
          if (Object.prototype.hasOwnProperty.call(context.left, property) &&
              child.result === undefined) {
              delete object[property];
          }
          else if (object[property] !== child.result) {
              object[property] = child.result;
          }
      }
      context.setResult(object).exit();
  };
  collectChildrenPatchFilter$1.filterName = 'collectChildren';
  const reverseFilter$2 = function nestedReverseFilter(context) {
      if (!context.nested) {
          return;
      }
      const nestedDelta = context.delta;
      if (nestedDelta._t) {
          return;
      }
      const objectDelta = context.delta;
      let name;
      let child;
      for (name in objectDelta) {
          child = new ReverseContext$1(objectDelta[name]);
          context.push(child, name);
      }
      context.exit();
  };
  reverseFilter$2.filterName = 'objects';
  const collectChildrenReverseFilter$1 = (context) => {
      if (!context || !context.children) {
          return;
      }
      const deltaWithChildren = context.delta;
      if (deltaWithChildren._t) {
          return;
      }
      const length = context.children.length;
      let child;
      const delta = {};
      for (let index = 0; index < length; index++) {
          child = context.children[index];
          const property = child.childName;
          if (delta[property] !== child.result) {
              delta[property] = child.result;
          }
      }
      context.setResult(delta).exit();
  };
  collectChildrenReverseFilter$1.filterName = 'collectChildren';

  /*

  LCS implementation that supports arrays or strings

  reference: http://en.wikipedia.org/wiki/Longest_common_subsequence_problem

  */
  const defaultMatch = function (array1, array2, index1, index2) {
      return array1[index1] === array2[index2];
  };
  const lengthMatrix = function (array1, array2, match, context) {
      const len1 = array1.length;
      const len2 = array2.length;
      let x, y;
      // initialize empty matrix of len1+1 x len2+1
      const matrix = new Array(len1 + 1);
      for (x = 0; x < len1 + 1; x++) {
          matrix[x] = new Array(len2 + 1);
          for (y = 0; y < len2 + 1; y++) {
              matrix[x][y] = 0;
          }
      }
      matrix.match = match;
      // save sequence lengths for each coordinate
      for (x = 1; x < len1 + 1; x++) {
          for (y = 1; y < len2 + 1; y++) {
              if (match(array1, array2, x - 1, y - 1, context)) {
                  matrix[x][y] = matrix[x - 1][y - 1] + 1;
              }
              else {
                  matrix[x][y] = Math.max(matrix[x - 1][y], matrix[x][y - 1]);
              }
          }
      }
      return matrix;
  };
  const backtrack = function (matrix, array1, array2, context) {
      let index1 = array1.length;
      let index2 = array2.length;
      const subsequence = {
          sequence: [],
          indices1: [],
          indices2: [],
      };
      while (index1 !== 0 && index2 !== 0) {
          const sameLetter = matrix.match(array1, array2, index1 - 1, index2 - 1, context);
          if (sameLetter) {
              subsequence.sequence.unshift(array1[index1 - 1]);
              subsequence.indices1.unshift(index1 - 1);
              subsequence.indices2.unshift(index2 - 1);
              --index1;
              --index2;
          }
          else {
              const valueAtMatrixAbove = matrix[index1][index2 - 1];
              const valueAtMatrixLeft = matrix[index1 - 1][index2];
              if (valueAtMatrixAbove > valueAtMatrixLeft) {
                  --index2;
              }
              else {
                  --index1;
              }
          }
      }
      return subsequence;
  };
  const get = function (array1, array2, match, context) {
      const innerContext = context || {};
      const matrix = lengthMatrix(array1, array2, match || defaultMatch, innerContext);
      return backtrack(matrix, array1, array2, innerContext);
  };
  var lcs = {
      get,
  };

  const ARRAY_MOVE = 3;
  function arraysHaveMatchByRef(array1, array2, len1, len2) {
      for (let index1 = 0; index1 < len1; index1++) {
          const val1 = array1[index1];
          for (let index2 = 0; index2 < len2; index2++) {
              const val2 = array2[index2];
              if (index1 !== index2 && val1 === val2) {
                  return true;
              }
          }
      }
  }
  function matchItems(array1, array2, index1, index2, context) {
      const value1 = array1[index1];
      const value2 = array2[index2];
      if (value1 === value2) {
          return true;
      }
      if (typeof value1 !== 'object' || typeof value2 !== 'object') {
          return false;
      }
      const objectHash = context.objectHash;
      if (!objectHash) {
          // no way to match objects was provided, try match by position
          return context.matchByPosition && index1 === index2;
      }
      context.hashCache1 = context.hashCache1 || [];
      let hash1 = context.hashCache1[index1];
      if (typeof hash1 === 'undefined') {
          context.hashCache1[index1] = hash1 = objectHash(value1, index1);
      }
      if (typeof hash1 === 'undefined') {
          return false;
      }
      context.hashCache2 = context.hashCache2 || [];
      let hash2 = context.hashCache2[index2];
      if (typeof hash2 === 'undefined') {
          context.hashCache2[index2] = hash2 = objectHash(value2, index2);
      }
      if (typeof hash2 === 'undefined') {
          return false;
      }
      return hash1 === hash2;
  }
  const diffFilter$2 = function arraysDiffFilter(context) {
      if (!context.leftIsArray) {
          return;
      }
      const matchContext = {
          objectHash: context.options && context.options.objectHash,
          matchByPosition: context.options && context.options.matchByPosition,
      };
      let commonHead = 0;
      let commonTail = 0;
      let index;
      let index1;
      let index2;
      const array1 = context.left;
      const array2 = context.right;
      const len1 = array1.length;
      const len2 = array2.length;
      let child;
      if (len1 > 0 &&
          len2 > 0 &&
          !matchContext.objectHash &&
          typeof matchContext.matchByPosition !== 'boolean') {
          matchContext.matchByPosition = !arraysHaveMatchByRef(array1, array2, len1, len2);
      }
      // separate common head
      while (commonHead < len1 &&
          commonHead < len2 &&
          matchItems(array1, array2, commonHead, commonHead, matchContext)) {
          index = commonHead;
          child = new DiffContext$1(array1[index], array2[index]);
          context.push(child, index);
          commonHead++;
      }
      // separate common tail
      while (commonTail + commonHead < len1 &&
          commonTail + commonHead < len2 &&
          matchItems(array1, array2, len1 - 1 - commonTail, len2 - 1 - commonTail, matchContext)) {
          index1 = len1 - 1 - commonTail;
          index2 = len2 - 1 - commonTail;
          child = new DiffContext$1(array1[index1], array2[index2]);
          context.push(child, index2);
          commonTail++;
      }
      let result;
      if (commonHead + commonTail === len1) {
          if (len1 === len2) {
              // arrays are identical
              context.setResult(undefined).exit();
              return;
          }
          // trivial case, a block (1 or more consecutive items) was added
          result = result || {
              _t: 'a',
          };
          for (index = commonHead; index < len2 - commonTail; index++) {
              result[index] = [array2[index]];
          }
          context.setResult(result).exit();
          return;
      }
      if (commonHead + commonTail === len2) {
          // trivial case, a block (1 or more consecutive items) was removed
          result = result || {
              _t: 'a',
          };
          for (index = commonHead; index < len1 - commonTail; index++) {
              result[`_${index}`] = [array1[index], 0, 0];
          }
          context.setResult(result).exit();
          return;
      }
      // reset hash cache
      delete matchContext.hashCache1;
      delete matchContext.hashCache2;
      // diff is not trivial, find the LCS (Longest Common Subsequence)
      const trimmed1 = array1.slice(commonHead, len1 - commonTail);
      const trimmed2 = array2.slice(commonHead, len2 - commonTail);
      const seq = lcs.get(trimmed1, trimmed2, matchItems, matchContext);
      const removedItems = [];
      result = result || {
          _t: 'a',
      };
      for (index = commonHead; index < len1 - commonTail; index++) {
          if (seq.indices1.indexOf(index - commonHead) < 0) {
              // removed
              result[`_${index}`] = [array1[index], 0, 0];
              removedItems.push(index);
          }
      }
      let detectMove = true;
      if (context.options &&
          context.options.arrays &&
          context.options.arrays.detectMove === false) {
          detectMove = false;
      }
      let includeValueOnMove = false;
      if (context.options &&
          context.options.arrays &&
          context.options.arrays.includeValueOnMove) {
          includeValueOnMove = true;
      }
      const removedItemsLength = removedItems.length;
      for (index = commonHead; index < len2 - commonTail; index++) {
          const indexOnArray2 = seq.indices2.indexOf(index - commonHead);
          if (indexOnArray2 < 0) {
              // added, try to match with a removed item and register as position move
              let isMove = false;
              if (detectMove && removedItemsLength > 0) {
                  for (let removeItemIndex1 = 0; removeItemIndex1 < removedItemsLength; removeItemIndex1++) {
                      index1 = removedItems[removeItemIndex1];
                      if (matchItems(trimmed1, trimmed2, index1 - commonHead, index - commonHead, matchContext)) {
                          // store position move as: [originalValue, newPosition, ARRAY_MOVE]
                          result[`_${index1}`].splice(1, 2, index, ARRAY_MOVE);
                          if (!includeValueOnMove) {
                              // don't include moved value on diff, to save bytes
                              result[`_${index1}`][0] = '';
                          }
                          index2 = index;
                          child = new DiffContext$1(array1[index1], array2[index2]);
                          context.push(child, index2);
                          removedItems.splice(removeItemIndex1, 1);
                          isMove = true;
                          break;
                      }
                  }
              }
              if (!isMove) {
                  // added
                  result[index] = [array2[index]];
              }
          }
          else {
              // match, do inner diff
              index1 = seq.indices1[indexOnArray2] + commonHead;
              index2 = seq.indices2[indexOnArray2] + commonHead;
              child = new DiffContext$1(array1[index1], array2[index2]);
              context.push(child, index2);
          }
      }
      context.setResult(result).exit();
  };
  diffFilter$2.filterName = 'arrays';
  const compare = {
      numerically(a, b) {
          return a - b;
      },
      numericallyBy(name) {
          return (a, b) => a[name] - b[name];
      },
  };
  const patchFilter$1 = function nestedPatchFilter(context) {
      if (!context.nested) {
          return;
      }
      const nestedDelta = context.delta;
      if (nestedDelta._t !== 'a') {
          return;
      }
      let index;
      let index1;
      const delta = nestedDelta;
      const array = context.left;
      // first, separate removals, insertions and modifications
      let toRemove = [];
      let toInsert = [];
      const toModify = [];
      for (index in delta) {
          if (index !== '_t') {
              if (index[0] === '_') {
                  const removedOrMovedIndex = index;
                  // removed item from original array
                  if (delta[removedOrMovedIndex][2] === 0 ||
                      delta[removedOrMovedIndex][2] === ARRAY_MOVE) {
                      toRemove.push(parseInt(index.slice(1), 10));
                  }
                  else {
                      throw new Error('only removal or move can be applied at original array indices,' +
                          ` invalid diff type: ${delta[removedOrMovedIndex][2]}`);
                  }
              }
              else {
                  const numberIndex = index;
                  if (delta[numberIndex].length === 1) {
                      // added item at new array
                      toInsert.push({
                          index: parseInt(numberIndex, 10),
                          value: delta[numberIndex][0],
                      });
                  }
                  else {
                      // modified item at new array
                      toModify.push({
                          index: parseInt(numberIndex, 10),
                          delta: delta[numberIndex],
                      });
                  }
              }
          }
      }
      // remove items, in reverse order to avoid sawing our own floor
      toRemove = toRemove.sort(compare.numerically);
      for (index = toRemove.length - 1; index >= 0; index--) {
          index1 = toRemove[index];
          const indexDiff = delta[`_${index1}`];
          const removedValue = array.splice(index1, 1)[0];
          if (indexDiff[2] === ARRAY_MOVE) {
              // reinsert later
              toInsert.push({
                  index: indexDiff[1],
                  value: removedValue,
              });
          }
      }
      // insert items, in reverse order to avoid moving our own floor
      toInsert = toInsert.sort(compare.numericallyBy('index'));
      const toInsertLength = toInsert.length;
      for (index = 0; index < toInsertLength; index++) {
          const insertion = toInsert[index];
          array.splice(insertion.index, 0, insertion.value);
      }
      // apply modifications
      const toModifyLength = toModify.length;
      let child;
      if (toModifyLength > 0) {
          for (index = 0; index < toModifyLength; index++) {
              const modification = toModify[index];
              child = new PatchContext$1(array[modification.index], modification.delta);
              context.push(child, modification.index);
          }
      }
      if (!context.children) {
          context.setResult(array).exit();
          return;
      }
      context.exit();
  };
  patchFilter$1.filterName = 'arrays';
  const collectChildrenPatchFilter = function collectChildrenPatchFilter(context) {
      if (!context || !context.children) {
          return;
      }
      const deltaWithChildren = context.delta;
      if (deltaWithChildren._t !== 'a') {
          return;
      }
      const array = context.left;
      const length = context.children.length;
      let child;
      for (let index = 0; index < length; index++) {
          child = context.children[index];
          const arrayIndex = child.childName;
          array[arrayIndex] = child.result;
      }
      context.setResult(array).exit();
  };
  collectChildrenPatchFilter.filterName = 'arraysCollectChildren';
  const reverseFilter$1 = function arraysReverseFilter(context) {
      if (!context.nested) {
          const nonNestedDelta = context.delta;
          if (nonNestedDelta[2] === ARRAY_MOVE) {
              const arrayMoveDelta = nonNestedDelta;
              context.newName = `_${arrayMoveDelta[1]}`;
              context
                  .setResult([
                  arrayMoveDelta[0],
                  parseInt(context.childName.substring(1), 10),
                  ARRAY_MOVE,
              ])
                  .exit();
          }
          return;
      }
      const nestedDelta = context.delta;
      if (nestedDelta._t !== 'a') {
          return;
      }
      const arrayDelta = nestedDelta;
      let name;
      let child;
      for (name in arrayDelta) {
          if (name === '_t') {
              continue;
          }
          child = new ReverseContext$1(arrayDelta[name]);
          context.push(child, name);
      }
      context.exit();
  };
  reverseFilter$1.filterName = 'arrays';
  const reverseArrayDeltaIndex = (delta, index, itemDelta) => {
      if (typeof index === 'string' && index[0] === '_') {
          return parseInt(index.substring(1), 10);
      }
      else if (Array.isArray(itemDelta) && itemDelta[2] === 0) {
          return `_${index}`;
      }
      let reverseIndex = +index;
      for (const deltaIndex in delta) {
          const deltaItem = delta[deltaIndex];
          if (Array.isArray(deltaItem)) {
              if (deltaItem[2] === ARRAY_MOVE) {
                  const moveFromIndex = parseInt(deltaIndex.substring(1), 10);
                  const moveToIndex = deltaItem[1];
                  if (moveToIndex === +index) {
                      return moveFromIndex;
                  }
                  if (moveFromIndex <= reverseIndex && moveToIndex > reverseIndex) {
                      reverseIndex++;
                  }
                  else if (moveFromIndex >= reverseIndex &&
                      moveToIndex < reverseIndex) {
                      reverseIndex--;
                  }
              }
              else if (deltaItem[2] === 0) {
                  const deleteIndex = parseInt(deltaIndex.substring(1), 10);
                  if (deleteIndex <= reverseIndex) {
                      reverseIndex++;
                  }
              }
              else if (deltaItem.length === 1 &&
                  parseInt(deltaIndex, 10) <= reverseIndex) {
                  reverseIndex--;
              }
          }
      }
      return reverseIndex;
  };
  const collectChildrenReverseFilter = (context) => {
      if (!context || !context.children) {
          return;
      }
      const deltaWithChildren = context.delta;
      if (deltaWithChildren._t !== 'a') {
          return;
      }
      const arrayDelta = deltaWithChildren;
      const length = context.children.length;
      let child;
      const delta = {
          _t: 'a',
      };
      for (let index = 0; index < length; index++) {
          child = context.children[index];
          let name = child.newName;
          if (typeof name === 'undefined') {
              name = reverseArrayDeltaIndex(arrayDelta, child.childName, child.result);
          }
          if (delta[name] !== child.result) {
              // There's no way to type this well.
              delta[name] = child.result;
          }
      }
      context.setResult(delta).exit();
  };
  collectChildrenReverseFilter.filterName = 'arraysCollectChildren';

  const diffFilter$1 = function datesDiffFilter(context) {
      if (context.left instanceof Date) {
          if (context.right instanceof Date) {
              if (context.left.getTime() !== context.right.getTime()) {
                  context.setResult([context.left, context.right]);
              }
              else {
                  context.setResult(undefined);
              }
          }
          else {
              context.setResult([context.left, context.right]);
          }
          context.exit();
      }
      else if (context.right instanceof Date) {
          context.setResult([context.left, context.right]).exit();
      }
  };
  diffFilter$1.filterName = 'dates';

  const TEXT_DIFF = 2;
  const DEFAULT_MIN_LENGTH = 60;
  let cachedDiffPatch = null;
  function getDiffMatchPatch(options, required) {
      var _a;
      if (!cachedDiffPatch) {
          let instance;
          if ((_a = options === null || options === void 0 ? void 0 : options.textDiff) === null || _a === void 0 ? void 0 : _a.diffMatchPatch) {
              instance = new options.textDiff.diffMatchPatch();
          }
          else {
              if (!required) {
                  return null;
              }
              const error = new Error('The diff-match-patch library was not provided. Pass the library in through the options or use the `jsondiffpatch/with-text-diffs` entry-point.');
              // eslint-disable-next-line camelcase
              error.diff_match_patch_not_found = true;
              throw error;
          }
          cachedDiffPatch = {
              diff: function (txt1, txt2) {
                  return instance.patch_toText(instance.patch_make(txt1, txt2));
              },
              patch: function (txt1, patch) {
                  const results = instance.patch_apply(instance.patch_fromText(patch), txt1);
                  for (let i = 0; i < results[1].length; i++) {
                      if (!results[1][i]) {
                          const error = new Error('text patch failed');
                          error.textPatchFailed = true;
                      }
                  }
                  return results[0];
              },
          };
      }
      return cachedDiffPatch;
  }
  const diffFilter = function textsDiffFilter(context) {
      if (context.leftType !== 'string') {
          return;
      }
      const left = context.left;
      const right = context.right;
      const minLength = (context.options &&
          context.options.textDiff &&
          context.options.textDiff.minLength) ||
          DEFAULT_MIN_LENGTH;
      if (left.length < minLength || right.length < minLength) {
          context.setResult([left, right]).exit();
          return;
      }
      // large text, try to use a text-diff algorithm
      const diffMatchPatch = getDiffMatchPatch(context.options);
      if (!diffMatchPatch) {
          // diff-match-patch library not available,
          // fallback to regular string replace
          context.setResult([left, right]).exit();
          return;
      }
      const diff = diffMatchPatch.diff;
      context.setResult([diff(left, right), 0, TEXT_DIFF]).exit();
  };
  diffFilter.filterName = 'texts';
  const patchFilter = function textsPatchFilter(context) {
      if (context.nested) {
          return;
      }
      const nonNestedDelta = context.delta;
      if (nonNestedDelta[2] !== TEXT_DIFF) {
          return;
      }
      const textDiffDelta = nonNestedDelta;
      // text-diff, use a text-patch algorithm
      const patch = getDiffMatchPatch(context.options, true).patch;
      context.setResult(patch(context.left, textDiffDelta[0])).exit();
  };
  patchFilter.filterName = 'texts';
  const textDeltaReverse = function (delta) {
      let i;
      let l;
      let line;
      let lineTmp;
      let header = null;
      const headerRegex = /^@@ +-(\d+),(\d+) +\+(\d+),(\d+) +@@$/;
      let lineHeader;
      const lines = delta.split('\n');
      for (i = 0, l = lines.length; i < l; i++) {
          line = lines[i];
          const lineStart = line.slice(0, 1);
          if (lineStart === '@') {
              header = headerRegex.exec(line);
              lineHeader = i;
              // fix header
              lines[lineHeader] =
                  '@@ -' +
                      header[3] +
                      ',' +
                      header[4] +
                      ' +' +
                      header[1] +
                      ',' +
                      header[2] +
                      ' @@';
          }
          else if (lineStart === '+') {
              lines[i] = '-' + lines[i].slice(1);
              if (lines[i - 1].slice(0, 1) === '+') {
                  // swap lines to keep default order (-+)
                  lineTmp = lines[i];
                  lines[i] = lines[i - 1];
                  lines[i - 1] = lineTmp;
              }
          }
          else if (lineStart === '-') {
              lines[i] = '+' + lines[i].slice(1);
          }
      }
      return lines.join('\n');
  };
  const reverseFilter = function textsReverseFilter(context) {
      if (context.nested) {
          return;
      }
      const nonNestedDelta = context.delta;
      if (nonNestedDelta[2] !== TEXT_DIFF) {
          return;
      }
      const textDiffDelta = nonNestedDelta;
      // text-diff, use a text-diff algorithm
      context
          .setResult([textDeltaReverse(textDiffDelta[0]), 0, TEXT_DIFF])
          .exit();
  };
  reverseFilter.filterName = 'texts';

  class DiffPatcher {
      constructor(options) {
          this.processor = new Processor$1(options);
          this.processor.pipe(new Pipe$1('diff')
              .append(collectChildrenDiffFilter, diffFilter$3, diffFilter$1, diffFilter, objectsDiffFilter, diffFilter$2)
              .shouldHaveResult());
          this.processor.pipe(new Pipe$1('patch')
              .append(collectChildrenPatchFilter$1, collectChildrenPatchFilter, patchFilter$3, patchFilter, patchFilter$2, patchFilter$1)
              .shouldHaveResult());
          this.processor.pipe(new Pipe$1('reverse')
              .append(collectChildrenReverseFilter$1, collectChildrenReverseFilter, reverseFilter$3, reverseFilter, reverseFilter$2, reverseFilter$1)
              .shouldHaveResult());
      }
      options(options) {
          return this.processor.options(options);
      }
      diff(left, right) {
          return this.processor.process(new DiffContext$1(left, right));
      }
      patch(left, delta) {
          return this.processor.process(new PatchContext$1(left, delta));
      }
      reverse(delta) {
          return this.processor.process(new ReverseContext$1(delta));
      }
      unpatch(right, delta) {
          return this.patch(right, this.reverse(delta));
      }
      clone(value) {
          return clone(value);
      }
  }
  var DiffPatcher$1 = DiffPatcher;

  function create(options) {
      return new DiffPatcher$1(options);
  }

  /* global analytics */
  var __awaiter$1 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
      function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
      return new (P || (P = Promise))(function (resolve, reject) {
          function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
          function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
          function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
          step((generator = generator.apply(thisArg, _arguments || [])).next());
      });
  };
  const diff = create();
  const mergeConfig = (current, newConfig) => {
      const writeKey = newConfig.writeKey ||
          // Backward/consumer compatibility: some apps may pass `apiKey` while the SDK option is `writeKey`
          newConfig.apiKey;
      if (writeKey)
          current.writeKey = writeKey;
      if (newConfig.host)
          current.host = newConfig.host;
      if (newConfig.bearerToken)
          current.bearerToken = newConfig.bearerToken;
  };
  const parseQuery = (qs) => {
      if (!qs) {
          return {};
      }
      let queryString = qs.length > 0 && qs.charAt(0) === "?" ? qs.substring(1) : qs;
      let query = {};
      let pairs = (queryString[0] === "?" ? queryString.substr(1) : queryString).split("&");
      for (let i = 0; i < pairs.length; i++) {
          let pair = pairs[i].split("=");
          query[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1] || "");
      }
      return query;
  };
  function utmToKey(key) {
      const name = key.substring("utm_".length);
      return name === "campaign" ? "name" : name;
  }
  function parseUtms(query) {
      return Object.entries(query)
          .filter(([key]) => key.indexOf("utm_") === 0)
          .reduce((acc, [key, value]) => (Object.assign(Object.assign({}, acc), { [utmToKey(key)]: value })), {});
  }
  function safeCall(f, defaultVal) {
      try {
          return f();
      }
      catch (e) {
          return defaultVal;
      }
  }
  function restoreTraits(storage) {
      let val = storage.getItem("__user_traits");
      if (typeof val === "string") {
          val = safeCall(() => JSON.parse(val), {});
      }
      if (typeof val !== "object" || val === null || Array.isArray(val)) {
          val = {};
      }
      let groupVal = storage.getItem("__group_traits");
      if (typeof groupVal === "string") {
          groupVal = safeCall(() => JSON.parse(groupVal), {});
      }
      if (typeof groupVal !== "object" || groupVal === null || Array.isArray(groupVal)) {
          groupVal = {};
      }
      return Object.assign(Object.assign({}, (groupVal || {})), (val || {}));
  }
  function getCookie(name) {
      const value = `; ${document.cookie}`;
      const parts = value.split(`; ${name}=`);
      return parts.length === 2 ? parts.pop().split(";").shift() : undefined;
  }
  function getClientIds(runtime, customCookieCapture) {
      const cookieCapture = Object.assign({ fbc: "_fbc", fbp: "_fbp" }, customCookieCapture);
      const clientIds = Object.entries(cookieCapture).reduce((acc, [key, cookieName]) => {
          acc[key] = runtime.getCookie(cookieName);
          return acc;
      }, {});
      return Object.assign(Object.assign({}, clientIds), getGa4Ids(runtime));
  }
  function parseGa4SessionId(cookieValue) {
      if (typeof cookieValue !== "string") {
          return undefined;
      }
      if (cookieValue.startsWith("GA1") || cookieValue.startsWith("GS1")) {
          return cookieValue.split(".")[2];
      }
      else {
          // parse new GA4 cookie format, e.g.: GS2.1.s1747323152$o28$g0$t1747323152$j60$l0$h69286059
          const match = cookieValue.match(/^GS\d+\.\d+\.(?:[\w_-]+[$])*s(\d+)(?:$|[$])/);
          return match ? match[1] : undefined;
      }
  }
  function getGa4Ids(runtime) {
      var _a;
      const allCookies = runtime.getCookies();
      const clientId = (_a = allCookies["_ga"]) === null || _a === void 0 ? void 0 : _a.split(".").slice(-2).join(".");
      const gaSessionCookies = Object.entries(allCookies).filter(([key]) => key.startsWith("_ga_"));
      const sessionIds = gaSessionCookies.length > 0
          ? Object.fromEntries(gaSessionCookies
              .map(([key, value]) => {
              const sessionId = parseGa4SessionId(value);
              if (!sessionId) {
                  return null;
              }
              return [key.substring("_ga_".length), sessionId];
          })
              .filter(v => v !== null))
          : undefined;
      if (clientId || sessionIds) {
          return { ga4: { clientId, sessionIds } };
      }
      else {
          return undefined;
      }
  }
  function removeCookie(name, { domain, secure }) {
      document.cookie =
          name +
              "=;domain=" +
              domain +
              ";path=/" +
              ";expires=Thu, 01 Jan 1970 00:00:01 GMT;SameSite=" +
              (secure ? "None" : "Lax") +
              (secure ? ";secure" : "");
  }
  function setCookie(name, val, { domain, secure }) {
      document.cookie =
          name +
              "=" +
              val +
              ";domain=" +
              domain +
              ";path=/" +
              ";expires=" +
              new Date(new Date().getTime() + 1000 * 60 * 60 * 24 * 365 * 5).toUTCString() +
              ";SameSite=" +
              (secure ? "None" : "Lax") +
              (secure ? ";secure" : "");
  }
  const defaultCookie2Key = {
      __anon_id: "__eventn_id",
      __user_id: "__eventn_uid",
      __user_traits: "__eventn_id_usr",
      __group_id: "__group_id",
      __group_traits: "__group_traits",
  };
  const cookieStorage = (cookieDomain, key2cookie) => {
      return {
          setItem(key, val) {
              const cookieName = key2cookie(key) || key;
              if (typeof val === "undefined") {
                  removeCookie(cookieName, {
                      domain: cookieDomain,
                      secure: window.location.protocol === "https:",
                  });
                  return;
              }
              const strVal = typeof val === "object" && val !== null ? encodeURIComponent(JSON.stringify(val)) : val;
              setCookie(cookieName, strVal, {
                  domain: cookieDomain,
                  secure: window.location.protocol === "https:",
              });
          },
          getItem(key) {
              const cookieName = key2cookie(key) || key;
              const result = getCookie(cookieName);
              if (key === "__anon_id") {
                  //anonymous id must always be a string, so we don't parse it to preserve its exact value
                  return result;
              }
              return parse(result);
          },
          removeItem(key) {
              removeCookie(key2cookie(key) || key, {
                  domain: cookieDomain,
                  secure: window.location.protocol === "https:",
              });
          },
          reset() {
              for (const key of Object.keys(defaultCookie2Key)) {
                  removeCookie(key2cookie(key) || key, {
                      domain: cookieDomain,
                      secure: window.location.protocol === "https:",
                  });
              }
          },
      };
  };
  function windowRuntime(opts) {
      const key2Cookie = (key) => {
          switch (key) {
              case "__anon_id":
                  return defaultCookie2Key.__anon_id;
              case "__user_id":
                  return defaultCookie2Key.__user_id;
              case "__user_traits":
                  return defaultCookie2Key.__user_traits;
              case "__group_id":
                  return defaultCookie2Key.__group_id;
              case "__group_traits":
                  return defaultCookie2Key.__group_traits;
              default:
                  return key;
          }
      };
      return {
          getCookie(name) {
              const value = `; ${document.cookie}`;
              const parts = value.split(`; ${name}=`);
              return parts.length === 2 ? parts.pop().split(";").shift() : undefined;
          },
          getCookies() {
              const value = `; ${document.cookie}`;
              const cookies = {};
              const matches = value.matchAll(/(\w+)=([^;]+)/g);
              for (const match of matches) {
                  cookies[match[1]] = match[2];
              }
              return cookies;
          },
          documentEncoding() {
              return window.document.characterSet;
          },
          timezoneOffset() {
              return new Date().getTimezoneOffset();
          },
          store() {
              return cookieStorage(getTopLevelDomain(window.location.hostname), key2Cookie);
          },
          language() {
              return window.navigator.language;
          },
          pageTitle() {
              return window.document.title;
          },
          pageUrl() {
              return window.location.href;
          },
          referrer() {
              return window.document.referrer;
          },
          screen() {
              return {
                  width: window.screen.width,
                  height: window.screen.height,
                  innerWidth: window.innerWidth,
                  innerHeight: window.innerHeight,
                  density: Math.floor(window.devicePixelRatio),
              };
          },
          userAgent() {
              return window.navigator.userAgent;
          },
      };
  }
  function createInMemoryStorage(debug) {
      const storage = {};
      return {
          reset() {
              Object.keys(storage).forEach(key => delete storage[key]);
          },
          setItem(key, val) {
              if (debug) {
                  console.log(`[JITSU EMPTY RUNTIME] Set storage item ${key}=${JSON.stringify(val)}`);
              }
              if (typeof val === "undefined") {
                  delete storage[key];
              }
              else {
                  storage[key] = val;
              }
          },
          getItem(key) {
              const val = storage[key];
              return val;
          },
          removeItem(key) {
              if (debug) {
                  console.log(`[JITSU EMPTY RUNTIME] Get storage item ${key}=${storage[key]}`);
              }
              delete storage[key];
          },
      };
  }
  const emptyRuntime = (config) => ({
      documentEncoding() {
          return undefined;
      },
      timezoneOffset() {
          return undefined;
      },
      getCookie(name) {
          return undefined;
      },
      getCookies() {
          return {};
      },
      store() {
          return createInMemoryStorage(false);
      },
      language() {
          return undefined;
      },
      pageTitle() {
          return undefined;
      },
      pageUrl() {
          return undefined;
      },
      referrer() {
          return undefined;
      },
      screen() {
          return undefined;
      },
      userAgent() {
          return undefined;
      },
  });
  function deepCopy(o) {
      if (typeof o !== "object") {
          return o;
      }
      if (!o) {
          return o;
      }
      return JSON.parse(JSON.stringify(o));
  }
  function isInBrowser() {
      return typeof document !== "undefined" && typeof window !== "undefined";
  }
  /**
   * Fixes a weird bug in analytics URL where path
   * of https://test.com becomes //test.com
   */
  function fixPath(path) {
      if (path.indexOf("//") === 0 && path.lastIndexOf("/") === 1) {
          return "/";
      }
      return path;
  }
  const hashRegex = /#.*$/;
  /**
   * for compatibility with path produced by analytics.js
   * @param url
   */
  function urlPath(url) {
      const regex = /(http[s]?:\/\/)?([^\/\s]+\/)(.*)/g;
      const matches = regex.exec(url);
      const pathMatch = matches && matches[3] ? matches[3].split("?")[0].replace(hashRegex, "") : "";
      return "/" + pathMatch;
  }
  function canonicalUrl() {
      if (!isInBrowser())
          return;
      const tags = document.getElementsByTagName("link");
      for (var i = 0, tag; (tag = tags[i]); i++) {
          if (tag.getAttribute("rel") === "canonical") {
              return tag.getAttribute("href");
          }
      }
  }
  /**
   * bugged analytics.js logic that produces 'url' parameter by concating canonical URL with current search part
   * I produces broken results in some cases like SPA where path is changed but canonical URL is not updated
   */
  function analyticsJsUrl() {
      if (!isInBrowser())
          return;
      const canonical = canonicalUrl();
      if (!canonical)
          return window.location.href.replace(hashRegex, "");
      return canonical.match(/\?/) ? canonical : canonical + window.location.search;
  }
  function adjustPayload(payload, config, storage) {
      var _a, _b, _c, _d, _e, _f, _g, _h;
      const runtime = isInBrowser() ? windowRuntime() : emptyRuntime();
      const url = runtime.pageUrl();
      const parsedUrl = safeCall(() => new URL(url), undefined);
      const query = parsedUrl ? parseQuery(parsedUrl.search) : {};
      const properties = payload.properties || {};
      if (payload.type === "page" && (properties.url || url)) {
          // we don't trust analytics.js URL logic since it's sticks with canonical URL on SPA pages
          let targetUrl = url || properties.url;
          if (properties.url && properties.url !== analyticsJsUrl()) {
              // properties.url is not the same as provided by analytics.js
              // it means that it was not overridden by user and we should use it
              targetUrl = properties.url;
          }
          properties.url = targetUrl.replace(hashRegex, "");
          properties.path = fixPath(urlPath(targetUrl));
          // other properties are correctly based on window.location in analytics.js
      }
      const context = {
          library: {
              name: jitsuLibraryName,
              version: jitsuVersion,
              env: isInBrowser() ? "browser" : "node",
          },
          userAgent: (_a = runtime.userAgent) === null || _a === void 0 ? void 0 : _a.call(runtime),
          locale: (_b = runtime.language) === null || _b === void 0 ? void 0 : _b.call(runtime),
          screen: (_c = runtime.screen) === null || _c === void 0 ? void 0 : _c.call(runtime),
          ip: (_d = runtime === null || runtime === void 0 ? void 0 : runtime.ip) === null || _d === void 0 ? void 0 : _d.call(runtime),
          traits: payload.type != "identify" && payload.type != "group"
              ? Object.assign(Object.assign({}, (restoreTraits(storage) || {})), (((_e = payload === null || payload === void 0 ? void 0 : payload.options) === null || _e === void 0 ? void 0 : _e.traits) || {})) : undefined,
          page: {
              path: properties.path || (parsedUrl && parsedUrl.pathname),
              referrer: runtime.referrer(),
              referring_domain: safeCall(() => runtime.referrer() && new URL(runtime.referrer()).hostname),
              host: parsedUrl && parsedUrl.host,
              search: properties.search || (parsedUrl && parsedUrl.search),
              title: properties.title || runtime.pageTitle(),
              url: properties.url || url,
              encoding: properties.encoding || runtime.documentEncoding(),
          },
          clientIds: getClientIds(runtime, {}),
          campaign: parseUtms(query),
      };
      const withContext = Object.assign(Object.assign({}, payload), { userId: ((_f = payload === null || payload === void 0 ? void 0 : payload.options) === null || _f === void 0 ? void 0 : _f.userId) || (payload === null || payload === void 0 ? void 0 : payload.userId), anonymousId: ((_g = payload === null || payload === void 0 ? void 0 : payload.options) === null || _g === void 0 ? void 0 : _g.anonymousId) || (payload === null || payload === void 0 ? void 0 : payload.anonymousId), groupId: ((_h = payload === null || payload === void 0 ? void 0 : payload.options) === null || _h === void 0 ? void 0 : _h.groupId) || storage.getItem("__group_id"), timestamp: new Date().toISOString(), sentAt: new Date().toISOString(), messageId: randomId(properties.path || (parsedUrl && parsedUrl.pathname)), context: context });
      delete withContext.meta;
      delete withContext.options;
      return withContext;
  }
  function isDiff(obj) {
      const keys = Object.keys(obj);
      return keys.length === 1 && keys[0] === "__diff";
  }
  function processDestinations(destinations, method, originalEvent, debug, analyticsInstance) {
      return __awaiter$1(this, void 0, void 0, function* () {
          const promises = [];
          for (const destination of destinations) {
              let newEvents = [];
              if (destination.newEvents) {
                  try {
                      newEvents = destination.newEvents.map(e => e === "same" ? deepCopy(originalEvent) : isDiff(e) ? diff.patch(deepCopy(originalEvent), e.__diff) : e);
                  }
                  catch (e) {
                      console.error(`[JITSU] Error applying '${destination.id}' changes to event: ${e === null || e === void 0 ? void 0 : e.message}`, e);
                  }
              }
              else {
                  newEvents = [deepCopy(originalEvent)];
              }
              const credentials = Object.assign(Object.assign({}, destination.credentials), destination.options);
              if (destination.deviceOptions.type === "internal-plugin") {
                  const plugin = internalDestinationPlugins[destination.deviceOptions.name];
                  if (plugin) {
                      for (const event of newEvents) {
                          try {
                              promises.push(plugin.handle(Object.assign(Object.assign({}, credentials), { debug }), event));
                          }
                          catch (e) {
                              console.warn(`[JITSU] Error processing event with internal plugin '${destination.deviceOptions.name}': ${e === null || e === void 0 ? void 0 : e.message}`, e);
                          }
                      }
                  }
                  else {
                      console.warn(`[JITSU] Unknown internal plugin '${destination.deviceOptions.name}' for destination '${destination.id}'`);
                  }
              }
              else if (destination.deviceOptions.type === "analytics-plugin") {
                  yield loadScript(destination.deviceOptions.packageCdn);
                  const plugin = window[destination.deviceOptions.moduleVarName];
                  if (!plugin) {
                      console.warn(`[JITSU] Broken plugin '${destination.deviceOptions.packageCdn}' for destination '${destination.id}' - it doesn't export '${destination.deviceOptions.moduleVarName}' variable`);
                  }
                  else {
                      let pluginInstance;
                      try {
                          pluginInstance = (typeof plugin === "function" ? plugin : plugin.init)(credentials);
                      }
                      catch (e) {
                          console.warn(`[JITSU] Error creating plugin '${destination.deviceOptions.moduleVarName}@${destination.deviceOptions.packageCdn}' for destination '${destination.id}': ${e === null || e === void 0 ? void 0 : e.message}`, e);
                      }
                      try {
                          if (debug) {
                              console.log(`[JITSU] Plugin '${destination.deviceOptions.moduleVarName}@${destination.deviceOptions.packageCdn}' for destination '${destination.id}' initialized with config:`, pluginInstance.config);
                          }
                          pluginInstance.initialize({ config: pluginInstance.config, instance: analyticsInstance });
                      }
                      catch (e) {
                          console.warn(`[JITSU] Error initializing plugin '${destination.deviceOptions.moduleVarName}@${destination.deviceOptions.packageCdn}' for destination '${destination.id}': ${e === null || e === void 0 ? void 0 : e.message}. Config: ${JSON.stringify(pluginInstance.config)}`, e);
                          continue;
                      }
                      if (pluginInstance[method]) {
                          for (const event of newEvents) {
                              try {
                                  pluginInstance[method]({
                                      payload: event,
                                      config: pluginInstance.config,
                                      instance: analyticsInstance,
                                  });
                              }
                              catch (e) {
                                  console.warn(`[JITSU] Error processing ${method}() with plugin '${destination.deviceOptions.moduleVarName}@${destination.deviceOptions.packageCdn}' for destination '${destination.id}': ${e === null || e === void 0 ? void 0 : e.message}`, e);
                              }
                          }
                      }
                  }
              }
          }
          yield Promise.all(promises);
      });
  }
  function looksLikeCuid(id) {
      return id.length === 25 && id.charAt(0) === "c";
  }
  function validateWriteKey(writeKey) {
      if (writeKey) {
          const [, secret] = writeKey.split(":", 2);
          if (!secret && !looksLikeCuid(writeKey)) {
              throw new Error(`Legacy write key detected - ${writeKey}! This format doesn't work anymore, it should be 'key:secret'. Please download a new key from Jitsu UI`);
          }
      }
      return writeKey;
  }
  function send(method, payload, jitsuConfig, instance, store) {
      return __awaiter$1(this, void 0, void 0, function* () {
          const adjustedPayload = adjustPayload(payload, jitsuConfig, store);
          const url = method === "track" ? `${jitsuConfig.host}/cdp-event-api/v1/sdk-event` : `${jitsuConfig.host}/api/s/${method}`;
          const fetch = globalThis.fetch;
          if (!fetch) {
              throw new Error("fetch isn't available in global scope");
          }
          // Use lowercase to match how browsers/HTTP2 expose headers (`x-api-key`) in devtools/server frameworks
          const authHeader = jitsuConfig.writeKey ? { "x-api-key": jitsuConfig.writeKey } : {};
          const bearerHeader = jitsuConfig.bearerToken ? { Authorization: `Bearer ${jitsuConfig.bearerToken}` } : {};
          let fetchResult;
          try {
              fetchResult = yield fetch(url, {
                  method: "POST",
                  headers: Object.assign(Object.assign({ "Content-Type": "application/json" }, authHeader), bearerHeader),
                  body: JSON.stringify(adjustedPayload),
              });
          }
          catch (e) {
              console.error(`Call to ${url} failed with error ${e.message}`);
              return Promise.resolve();
          }
          let responseText;
          try {
              responseText = yield fetchResult.text();
          }
          catch (e) {
              console.warn(`Can't read response text from ${url} (status - ${fetchResult.status}  ${fetchResult.statusText}): ${e === null || e === void 0 ? void 0 : e.message}`);
          }
          if (!fetchResult.ok) {
              console.error(`Call to ${url} failed with error: ${fetchResult.status} - ${fetchResult.statusText}: ${responseText}`);
              return Promise.resolve();
          }
          let responseJson;
          try {
              responseJson = JSON.parse(responseText);
          }
          catch (e) {
              console.error(`Can't parse JSON: ${responseText}: ${e === null || e === void 0 ? void 0 : e.message}`);
              return Promise.resolve();
          }
          if (responseJson.destinations && responseJson.destinations.length > 0) {
              if (isInBrowser()) {
                  return processDestinations(responseJson.destinations, method, adjustedPayload, false, instance);
              }
          }
          return adjustedPayload;
      });
  }
  const controllingTraits = ["$doNotSend"];
  /**
   * Remove all members of traits that controls identify/group behavior (see analytics.d.ts), and should not be recorded. Returns
   * copy of the object with these members removed.
   *
   * Do not modify traits object, but creates one
   * @param traits
   */
  function stripControllingTraits(traits) {
      const res = Object.assign({}, traits);
      // see Traits definition in analytics.d.ts. We cannot define const here, so here's a little code duplication
      for (const key of controllingTraits) {
          delete res[key];
      }
      return res;
  }
  const jitsuAnalyticsPlugin = (jitsuOptions = {}, storage) => {
      // just to make sure that all undefined values are replaced with defaultConfig values
      mergeConfig(jitsuOptions, jitsuOptions);
      return {
          name: "jitsu",
          config: jitsuOptions,
          initialize: (args) => __awaiter$1(void 0, void 0, void 0, function* () {
              const { config } = args;
              if (!config.host) {
                  throw new Error("Please specify host variable in jitsu plugin initialization");
              }
              validateWriteKey(config.writeKey);
          }),
          page: args => {
              const { payload, config, instance } = args;
              return send("page", payload, config, instance, storage);
          },
          track: args => {
              const { payload, config, instance } = args;
              return send("track", payload, config, instance, storage);
          },
          identify: args => {
              var _a;
              const { payload, config, instance } = args;
              // Store traits in cache to be able to use them in page and track events that run asynchronously with current identify.
              storage.setItem("__user_id", payload.userId);
              const doNotSend = (_a = payload.traits) === null || _a === void 0 ? void 0 : _a.$doNotSend;
              if (payload.traits && typeof payload.traits === "object") {
                  payload.traits = stripControllingTraits(payload.traits);
                  storage.setItem("__user_traits", payload.traits);
              }
              if (doNotSend) {
                  return Promise.resolve();
              }
              return send("identify", payload, config, instance, storage);
          },
          reset: args => {
              storage.reset();
          },
          methods: {},
      };
  };
  let seedCounter = 0;
  function getSeed() {
      var _a;
      seedCounter = (seedCounter + 1) % Number.MAX_SAFE_INTEGER;
      const defaultSeed = Date.now() % 2147483647;
      const seed = isInBrowser() ? ((_a = window === null || window === void 0 ? void 0 : window.performance) === null || _a === void 0 ? void 0 : _a.now()) || defaultSeed : defaultSeed;
      return seed + seedCounter;
  }
  function randomId(hashString = "") {
      const d = Date.now();
      return (((Math.random() * d * hash(hashString !== null && hashString !== void 0 ? hashString : "", getSeed())) % Number.MAX_SAFE_INTEGER).toString(36) +
          ((Math.random() * d * hash(hashString !== null && hashString !== void 0 ? hashString : "", getSeed())) % Number.MAX_SAFE_INTEGER).toString(36));
  }
  function hash(str, seed = 0) {
      let h1 = 0xdeadbeef ^ seed, h2 = 0x41c6ce57 ^ seed;
      for (let i = 0, ch; i < str.length; i++) {
          ch = str.charCodeAt(i);
          h1 = Math.imul(h1 ^ ch, 2654435761);
          h2 = Math.imul(h2 ^ ch, 1597334677);
      }
      h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909);
      h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909);
      return 4294967296 * (2097151 & h2) + (h1 >>> 0);
  }

  var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
      function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
      return new (P || (P = Promise))(function (resolve, reject) {
          function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
          function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
          function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
          step((generator = generator.apply(thisArg, _arguments || [])).next());
      });
  };
  /**
   * Fetches userId from the lookup API using clientId or msisdn.
   */
  function fetchUserIdFromApi(opts, key, value) {
      return __awaiter(this, void 0, void 0, function* () {
          const fetch = globalThis.fetch;
          if (!fetch)
              return null;
          const host = opts.host ? opts.host.replace(/\/$/, "") : "";
          const url = `${host}/api/lookup?${key}=${encodeURIComponent(value)}`;
          const headers = {};
          if (opts.bearerToken) {
              headers["Authorization"] = `Bearer ${opts.bearerToken}`;
          }
          try {
              const res = yield fetch(url, { headers });
              if (!res.ok)
                  return null;
              const json = yield res.json();
              return json.userId;
          }
          catch (e) {
              console.warn(`[JITSU] Lookup failed for ${key}=${value}`, e);
              return null;
          }
      });
  }
  function createUnderlyingAnalyticsInstance(opts, rt, plugins = []) {
      var _a;
      const cachingStorageWrapper = (persistentStorage) => ({
          setItem(key, val) {
              persistentStorage.setItem(key, val);
          },
          getItem(key) {
              const value = persistentStorage.getItem(key);
              return value;
          },
          reset() {
              persistentStorage.reset();
          },
          removeItem(key) {
              persistentStorage.removeItem(key);
          },
      });
      const storage = cachingStorageWrapper(((_a = rt.store) === null || _a === void 0 ? void 0 : _a.call(rt)) || createInMemoryStorage(false));
      const analytics = analyticsLib({
          debug: false,
          storage,
          plugins: [jitsuAnalyticsPlugin(opts, storage), ...plugins],
      });
      const a = {
          track: analytics.track.bind(analytics),
          user: analytics.user.bind(analytics),
          identify: (...args) => __awaiter(this, void 0, void 0, function* () {
              var _a;
              if (args[0] && typeof args[0] !== "object" && typeof args[0] !== "string") {
                  args[0] = args[0] + "";
              }
              const storage = analytics.storage;
              const storageWrapper = cachingStorageWrapper(storage);
              const userId = typeof args[0] === "string" ? args[0] : (_a = args[0]) === null || _a === void 0 ? void 0 : _a.userId;
              const traits = typeof args[0] === "object" ? args[0] : args[1];
              if (userId) {
                  storageWrapper.setItem("__user_id", userId);
              }
              if (traits) {
                  storageWrapper.setItem("__user_traits", traits);
              }
              return analytics.identify(...args);
          }),
          identifyByUserId: (userId) => __awaiter(this, void 0, void 0, function* () {
              return a.identify(userId);
          }),
          identifyByClientId: (clientId) => __awaiter(this, void 0, void 0, function* () {
              const userId = yield fetchUserIdFromApi(opts, "clientId", clientId);
              if (userId) {
                  return a.identify(userId);
              }
              console.warn(`[JITSU] Could not resolve userId for clientId: ${clientId}`);
              return Promise.resolve({});
          }),
          identifyByMsisdn: (msisdn) => __awaiter(this, void 0, void 0, function* () {
              const userId = yield fetchUserIdFromApi(opts, "msisdn", msisdn);
              if (userId) {
                  return a.identify(userId);
              }
              console.warn(`[JITSU] Could not resolve userId for msisdn: ${msisdn}`);
              return Promise.resolve({});
          }),
          reset: () => {
              storage.reset();
              return analytics.reset();
          },
      };
      return a;
  }
  function fixOptions(opts) {
      var _a, _b;
      return Object.assign(Object.assign({}, opts), { host: ((_a = opts.host) !== null && _a !== void 0 ? _a : "").indexOf("https://") !== 0 && ((_b = opts.host) !== null && _b !== void 0 ? _b : "").indexOf("http://") !== 0
              ? `https://${opts.host}`
              : opts.host });
  }
  function createClient(_opts) {
      const opts = fixOptions(_opts);
      const inBrowser = isInBrowser();
      const rt = inBrowser ? windowRuntime() : emptyRuntime();
      return createUnderlyingAnalyticsInstance(opts, rt);
  }

  function snakeToCamel(s) {
      return s.replace(/([-_][a-z])/gi, $1 => {
          return $1.toUpperCase().replace("-", "").replace("_", "");
      });
  }
  const trimPrefix = (s, prefix) => s.replace(new RegExp(`^${prefix}`), "");
  const defaultParser = (nestedPath = []) => ({
      path: (name) => [
          ...nestedPath,
          snakeToCamel(nestedPath.length > 0 ? trimPrefix(name, nestedPath.join("-") + "-") : name),
      ],
      parse: (arg) => arg,
  });
  const parsers = {};
  function getParser(name) {
      return parsers[name] || defaultParser();
  }
  function setPath(obj, path, value) {
      let current = obj;
      let i = 0;
      for (; i < path.length - 1; i++) {
          const key = path[i];
          current[key] = current[key] || {};
          current = current[key];
      }
      current[path[i]] = value;
  }
  function getScriptAttributes(scriptElement) {
      return scriptElement
          .getAttributeNames()
          .filter(name => name.indexOf("data-") === 0)
          .map(name => name.substring("data-".length))
          .reduce((res, name) => {
          const parser = getParser(name);
          const path = parser.path(name);
          setPath(res, path, parser.parse(scriptElement.getAttribute(`data-${name}`)));
          return res;
      }, {});
  }
  function runCallback(callback, jitsu) {
      if (typeof callback === "function") {
          callback(jitsu);
      }
      else if (Array.isArray(callback) && typeof callback[0] === "string") {
          const [method, ...args] = callback;
          if (typeof jitsu[method] === "function") {
              jitsu[method](...args);
          }
      }
  }
  (function () {
      function readJitsuOptions() {
          const scriptElement = window.document.currentScript;
          if (!scriptElement) {
              throw new Error(`Can't find script element`);
          }
          const host = new URL(scriptElement.src).origin;
          return Object.assign(Object.assign(Object.assign({}, ((window === null || window === void 0 ? void 0 : window.jitsuConfig) || {})), getScriptAttributes(scriptElement)), { host });
      }
      const options = readJitsuOptions();
      const jitsu = createClient(options);
      window["jitsu"] = jitsu;
      /**
       * New callback based queue, see below
       */
      //make a copy of the queue
      const callbackQueue = window["jitsuQ"] && window["jitsuQ"].length ? [...window["jitsuQ"]] : [];
      //replace push with a function that calls callback immediately
      window["jitsuQ"] = {
          push: (callback) => {
              if (typeof callback === "function") {
                  callback(jitsu);
              }
          },
      };
      callbackQueue.forEach((callback) => {
          try {
              runCallback(callback, jitsu);
          }
          catch (e) {
              console.warn(`Error processing callback from Jitsu queue`, e);
          }
      });
  })();

})();
