@sprig-technologies/sprig-browser 2.28.1 → 2.29.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,19 @@
1
+ "use strict";var Os=Object.defineProperty;var Ds=(e,t,n)=>t in e?Os(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var N=(e,t,n)=>(Ds(e,typeof t!="symbol"?t+"":t,n),n);var he=(e=>(e.Closed="close.click",e.Complete="survey.completed",e.FeedbackClosed="feedback.closed",e.PageChange="page.change",e.API="api",e.Override="override",e))(he||{}),C=(e=>(e.ReplayCapture="replay.capture",e.FeedbackButtonLoaded="feedback.button.loaded",e.SDKReady="sdk.ready",e.SurveyAppeared="survey.appeared",e.SurveyClosed="survey.closed",e.SurveyDimensions="survey.dimensions",e.SurveyFadingOut="survey.fadingOut",e.SurveyHeight="survey.height",e.SurveyPresented="survey.presented",e.SurveyLifeCycle="survey.lifeCycle",e.SurveyWidth="survey.width",e.SurveyWillClose="survey.willClose",e.SurveyWillPresent="survey.will.present",e.CloseSurveyOnOverlayClick="close.survey.overlayClick",e.VisitorIDUpdated="visitor.id.updated",e.QuestionAnswered="question.answered",e))(C||{});const wt={FEEDBACK_BUTTON_LOADED:"feedback.button.loaded",SDK_READY:"sdk.ready",SURVEY_APPEARED:"survey.appeared",SURVEY_CLOSED:"survey.closed",SURVEY_DIMENSIONS:"survey.dimensions",SURVEY_FADING_OUT:"survey.fadingOut",SURVEY_HEIGHT:"survey.height",SURVEY_WIDTH:"survey.width",SURVEY_PRESENTED:"survey.presented",SURVEY_LIFE_CYCLE:"survey.lifeCycle",SURVEY_WILL_CLOSE:"survey.willClose",SURVEY_WILL_PRESENT:"survey.will.present",QUESTION_ANSWERED:"question.answered",REPLAY_CAPTURE:"replay.capture",CLOSE_SURVEY_ON_OVERLAY_CLICK:"close.survey.overlayClick",VISITOR_ID_UPDATED:"visitor.id.updated",DATA:{DISMISS_REASONS:{API:"api",CLOSED:"close.click",COMPLETE:"survey.completed",PAGE_CHANGE:"page.change",OVERRIDE:"override"},SURVEY_ID:"survey.id"}};let Ot;const Ps=new Uint8Array(16);function Ts(){if(!Ot&&(Ot=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!Ot))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Ot(Ps)}const z=[];for(let e=0;e<256;++e)z.push((e+256).toString(16).slice(1));function Bs(e,t=0){return z[e[t+0]]+z[e[t+1]]+z[e[t+2]]+z[e[t+3]]+"-"+z[e[t+4]]+z[e[t+5]]+"-"+z[e[t+6]]+z[e[t+7]]+"-"+z[e[t+8]]+z[e[t+9]]+"-"+z[e[t+10]]+z[e[t+11]]+z[e[t+12]]+z[e[t+13]]+z[e[t+14]]+z[e[t+15]]}const Ms=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),Nr={randomUUID:Ms};function $e(e,t,n){if(Nr.randomUUID&&!t&&!e)return Nr.randomUUID();e=e||{};const i=e.random||(e.rng||Ts)();if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,t){n=n||0;for(let r=0;r<16;++r)t[n+r]=i[r];return t}return Bs(i)}const Fs='.ul-loading-spinner-container{font-size:1.8rem;flex-grow:1;width:100%;height:100%;display:flex;align-items:center;justify-content:center}.ul-loading-spinner{display:inline-block;position:relative;width:6rem;height:6rem}.ul-loading-spinner div{box-sizing:border-box;display:block;position:absolute;width:80%;height:80%;margin:5px;border:5px solid #152e3e;border-radius:50%;animation:lds-ring 1.2s cubic-bezier(.5,0,.5,1) infinite;border-color:#152e3e transparent transparent transparent}.ul-loading-spinner .first{animation-delay:-.45s}.ul-loading-spinner .second{animation-delay:-.3s}.ul-loading-spinner .third{animation-delay:-.15s}@keyframes lds-ring{0%{transform:rotate(0)}to{transform:rotate(360deg)}}.fade-in-transition{animation:fadeIn .4s ease-in}@keyframes fadeIn{0%{opacity:0}to{opacity:1}}#sprig-feedback-button{border-left:0;border-radius:0 8px 8px 0;display:grid;padding:8px;text-align:center;transition:all ease-in-out 1s;z-index:inherit}#sprig-feedback-button:hover{cursor:pointer}.sprig-feedback-button-label{writing-mode:vertical-lr;text-orientation:sideways}.sprig-feedback-button-right{transform:rotate(180deg)}.sprig-feedback-button-bottom{align-self:flex-end;margin-bottom:20px}.sprig-feedback-button-light{background:#efefee;color:#000;border:1px solid #e2e3e1}.sprig-feedback-button-dark{background:#000;color:#fff;border:1px solid #000000}#sprig-feedback-container{display:flex;align-items:center;position:fixed;transition:right .2s linear,left .2s linear;z-index:2147483646}.sprig-feedback-container-left{flex-flow:row-reverse}.sprig-feedback-container-center{top:50%;transform:translateY(-50%)}.sprig-feedback-container-bottom{bottom:0%;margin-bottom:15px}.sprig-feedback-loading-container{align-items:center;background-color:#fff;border:2px solid var(--feedback-border);display:flex;max-height:90vh;max-width:90vw;min-width:0px}.sprig-feedback-loading-container-left{border-left:none;border-radius:0 8px 8px 0}.sprig-feedback-loading-container-right{border-right:none;border-radius:8px 0 0 8px}#sprig-feedback-error-container{margin:auto;text-align:center;width:360px}.sprig-feedback-error-text{font-weight:400;font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica,Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji",Segoe UI Symbol}#sprig-feedback-loading-container .ul-container{position:relative;max-height:inherit}#sprig-feedback-loading-animation{position:absolute}.sprig-feedback-loading-container-previews iframe{max-height:inherit!important}',mi="360px",js="ul-app",Ks="#e6e6e6",Ns="#bd282a",$s=500,qs=1030,yi=()=>{try{return window.parent.Intercom}catch{return null}},Vs=()=>{const e=yi();e&&(e.ul_wasVisible&&e("update",{hide_default_launcher:!1}),delete e.ul_wasVisible)},Ws=()=>{const e=yi();e&&(e.ul_wasVisible=!!document.querySelector("iframe.intercom-launcher-frame"),e.ul_wasVisible&&e("update",{hide_default_launcher:!0}))},zs=Object.freeze(Object.defineProperty({__proto__:null,disable:Ws,enable:Vs},Symbol.toStringTag,{value:"Module"})),$r=[zs];class gi{static disable(){$r.forEach(t=>t.disable())}static enable(){$r.forEach(t=>t.enable())}}var Hs=class extends Error{constructor(e,t,n){super(`Possible EventEmitter memory leak detected. ${n} ${t.toString()} listeners added. Use emitter.setMaxListeners() to increase limit`),this.emitter=e,this.type=t,this.count=n,this.name="MaxListenersExceededWarning"}},wi=class{static listenerCount(e,t){return e.listenerCount(t)}constructor(){this.events=new Map,this.maxListeners=wi.defaultMaxListeners,this.hasWarnedAboutPotentialMemoryLeak=!1}_emitInternalEvent(e,t,n){this.emit(e,t,n)}_getListeners(e){return Array.prototype.concat.apply([],this.events.get(e))||[]}_removeListener(e,t){const n=e.indexOf(t);return n>-1&&e.splice(n,1),[]}_wrapOnceListener(e,t){const n=(...i)=>(this.removeListener(e,n),t.apply(this,i));return Object.defineProperty(n,"name",{value:t.name}),n}setMaxListeners(e){return this.maxListeners=e,this}getMaxListeners(){return this.maxListeners}eventNames(){return Array.from(this.events.keys())}emit(e,...t){const n=this._getListeners(e);return n.forEach(i=>{i.apply(this,t)}),n.length>0}addListener(e,t){this._emitInternalEvent("newListener",e,t);const n=this._getListeners(e).concat(t);if(this.events.set(e,n),this.maxListeners>0&&this.listenerCount(e)>this.maxListeners&&!this.hasWarnedAboutPotentialMemoryLeak){this.hasWarnedAboutPotentialMemoryLeak=!0;const i=new Hs(this,e,this.listenerCount(e));console.warn(i)}return this}on(e,t){return this.addListener(e,t)}once(e,t){return this.addListener(e,this._wrapOnceListener(e,t))}prependListener(e,t){const n=this._getListeners(e);if(n.length>0){const i=[t].concat(n);this.events.set(e,i)}else this.events.set(e,n.concat(t));return this}prependOnceListener(e,t){return this.prependListener(e,this._wrapOnceListener(e,t))}removeListener(e,t){const n=this._getListeners(e);return n.length>0&&(this._removeListener(n,t),this.events.set(e,n),this._emitInternalEvent("removeListener",e,t)),this}off(e,t){return this.removeListener(e,t)}removeAllListeners(e){return e?this.events.delete(e):this.events.clear(),this}listeners(e){return Array.from(this._getListeners(e))}listenerCount(e){return this._getListeners(e).length}rawListeners(e){return this.listeners(e)}},vi=wi;vi.defaultMaxListeners=10;const R=new vi,Xt=e=>new Promise(t=>{setTimeout(()=>{t()},e)}),bi=({"userleap-platform":e})=>e!=="web";class _i{constructor(t){N(this,"storage");N(this,"tempStorage",{});N(this,"isStorageAvailable");this.storage=window[t],this.isStorageAvailable=this.checkIfStorageAvailable()}checkIfStorageAvailable(){try{const t="__storage_test__";return this.storage.setItem(t,t),this.storage.removeItem(t),!0}catch{return!1}}setItem(t,n){this.isStorageAvailable?this.storage.setItem(t,n):this.tempStorage[t]=n}getItem(t){return this.isStorageAvailable?this.storage.getItem(t):this.tempStorage[t]}removeItem(t){this.isStorageAvailable?this.storage.removeItem(t):delete this.tempStorage[t]}clear(){this.isStorageAvailable?this.storage.clear():this.tempStorage={}}}const Ie=new _i("sessionStorage"),ee=new _i("localStorage");class Gs{constructor(t){N(this,"payload");N(this,"promise");N(this,"reject",()=>{});N(this,"resolve",()=>{});this.payload=t,this.promise=new Promise((n,i)=>{this.reject=i,this.resolve=n})}resolveRequest(t){this.resolve(t)}}const Ys={RATELIMIT_RESET_DEFAULT:10};let Si=!1,Ei="",Dt=!1,ki=!1,Nt=[];const Js=e=>e._config&&e._config.installationMethod?e._config.installationMethod:e._gtm?"web-gtm":e._segment?"web-segment":"web-snippet",Pn=e=>{var t;(t=e==null?void 0:e.blockedURI)!=null&&t.includes(window.UserLeap._API_URL)&&(ki=!0,console.warn(`[Sprig] ${e.blockedURI} is blocked by Content-Security-Policy`),document.removeEventListener("securitypolicyviolation",Pn))},Tn=(e="")=>{Si=!0,Ei=e};function Fe(e={}){const t={"Content-Type":"application/json","userleap-platform":"web","x-ul-sdk-version":"2.29.0","x-ul-installation-method":Js(e)};if(e.envId&&(t["x-ul-environment-id"]=e.envId),e.token&&(t.Authorization="Bearer "+e.token),e.userId&&(t["x-ul-user-id"]=e.userId),e.visitorId&&(t["x-ul-visitor-id"]=e.visitorId),e.partnerAnonymousId&&(t["x-ul-anonymous-id"]=e.partnerAnonymousId),e.mobileHeadersJSON){const n=JSON.parse(e.mobileHeadersJSON);Object.assign(t,n)}return e.locale&&(t["accept-language"]=e.locale),window.previewMode&&(t["x-ul-preview-mode"]="1"),t}const qr=async({shouldDropOnRateLimit:e,...t})=>{if(e)return{status:429};{const n=new Gs(t);return Nt.push(n),n.promise}},ye=async(e,t)=>{const{retries:n=0,shouldDropOnRateLimit:i=!1,shouldRetryRequest:r=!1,...s}=t,o={url:e,options:s,retries:n,shouldDropOnRateLimit:i};if(Dt&&!r)return qr(o);const a={ok:!1,reportError:!1};if(Si)return console.info(`UserLeap - ${Ei}`),a;try{const l=await fetch(e,s);if(l.status===429)if(!Dt&&!i||r){Dt=!0;const c=l.headers.has("ratelimit-reset")?Number(l.headers.get("ratelimit-reset")):Ys.RATELIMIT_RESET_DEFAULT;return await Xt(c*1e3),ye(e,{...s,shouldDropOnRateLimit:i,shouldRetryRequest:!0})}else return qr(o);if(Dt=!1,Nt.length&&(Nt.map(u=>{const c=u.payload;ye(c.url,{...c.options,retries:c.retries,shouldDropOnRateLimit:c.shouldDropOnRateLimit}).then(p=>{u.resolveRequest(p)})}),Nt=[]),l.ok){if(l.status===249)return Tn(),a;const u=await l.text();try{return u&&u!=="OK"&&(l.json=JSON.parse(u)),l}catch{return{ok:!1,reportError:!1,error:new Error(`failed parsing response json for ${e} - ${u}`)}}}return l}catch(l){const u=n+1;return u>5||ki?{ok:!1,reportError:!1,error:l}:(await Xt(Math.pow(2,n)*1e3),ye(e,{...s,retries:u}))}},et={Error:1,Warn:2,Info:3,Debug:4};let Bn=1e3,Zt=et.Debug,Qe=[];const Qs=e=>{const t=Object.entries(et).find(n=>n[1]===e);return(t==null?void 0:t[0])??""},Xs=e=>e.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit",fractionalSecondDigits:3}),Zs=(e,t)=>`${Xs(t)}:${e}`,eo=()=>{Qe=Qe.filter(e=>e.level<=Zt)},to=()=>{Qe.length>Bn&&Qe.shift()},hn=(e,t)=>{e>Zt||(Qe.push({level:e,line:Zs(t,new Date)}),to())},vt=e=>{hn(et.Debug,e)},I=e=>{hn(et.Info,e)},Mn=e=>{hn(et.Warn,e)},Li=e=>{hn(et.Error,e)},no=()=>Qe.map(e=>e.line),ro=()=>new TextEncoder().encode(no().join(`
2
+ `)),Ii=async e=>{if(!e)return;const t=ro();return ye(e,{body:t,method:"PUT"})},io=(e,t)=>{e!==void 0&&(Bn=e),t!==void 0&&(Zt=t),vt(`Initializing logger with limit of ${Bn} lines and ${Qs(Zt)} level`),eo()};var Fn=(e=>(e[e.DomContentLoaded=0]="DomContentLoaded",e[e.Load=1]="Load",e[e.FullSnapshot=2]="FullSnapshot",e[e.IncrementalSnapshot=3]="IncrementalSnapshot",e[e.Meta=4]="Meta",e[e.Custom=5]="Custom",e[e.Plugin=6]="Plugin",e))(Fn||{});class so{constructor(t){N(this,"awaitingResolvers",[]);N(this,"activeCount",0);this.capacity=t}async acquire(){if(this.activeCount<this.capacity){this.activeCount++;return}return new Promise(t=>{this.awaitingResolvers.push(t)})}release(){const t=this.awaitingResolvers.shift();t&&this.activeCount<=this.capacity?t():this.activeCount--}async execute(t){try{return await this.acquire(),await t()}finally{this.release()}}setLimit(t){this.capacity=t}}const Ui=new so(2),oo=e=>Ui.setLimit(e),ao=async e=>Ui.execute(async()=>{var i;I(`Beginning upload of chunk ${e.chunkIndex} for survey: ${e.surveyId}`);const t=await ye(e.uploadUrl,{body:e.data,method:"PUT"});I(`Completed upload of chunk ${e.chunkIndex} for survey: ${e.surveyId}`);const n=(i=t.headers)==null?void 0:i.get("ETag");if(!n)throw new Error(`Upload response did not include etag for upload ${e.uploadId}, part ${e.chunkIndex}`);return n}),xi=async({apiUrl:e,surveyId:t,uploadId:n,etags:i,headers:r,responseGroupUuid:s,replayDuration:o,eventDigest:a},l=!1)=>{var c;if(!l&&!n&&!i){I(`Cannot mark upload complete: isMobile: ${l} / uploadId: ${n} / etags: ${i}`);return}I(`Marking upload complete for survey: ${t}`);const u=await ye(`${e}/sdk/1/completeSessionReplay`,{method:"POST",body:JSON.stringify({etags:i,uploadId:n,responseGroupUuid:s,surveyId:t,replayDuration:o,eventDigest:a,userAgent:(c=window==null?void 0:window.navigator)==null?void 0:c.userAgent}),headers:r,shouldRetryRequest:!0});return I(`Done marking upload complete for survey: ${t}`),u},F=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,q=Object.keys,G=Array.isArray;function J(e,t){return typeof t!="object"||q(t).forEach(function(n){e[n]=t[n]}),e}typeof Promise>"u"||F.Promise||(F.Promise=Promise);const bt=Object.getPrototypeOf,lo={}.hasOwnProperty;function te(e,t){return lo.call(e,t)}function Xe(e,t){typeof t=="function"&&(t=t(bt(e))),(typeof Reflect>"u"?q:Reflect.ownKeys)(t).forEach(n=>{ge(e,n,t[n])})}const Ai=Object.defineProperty;function ge(e,t,n,i){Ai(e,t,J(n&&te(n,"get")&&typeof n.get=="function"?{get:n.get,set:n.set,configurable:!0}:{value:n,configurable:!0,writable:!0},i))}function He(e){return{from:function(t){return e.prototype=Object.create(t.prototype),ge(e.prototype,"constructor",e),{extend:Xe.bind(null,e.prototype)}}}}const co=Object.getOwnPropertyDescriptor;function _r(e,t){let n;return co(e,t)||(n=bt(e))&&_r(n,t)}const uo=[].slice;function en(e,t,n){return uo.call(e,t,n)}function Ri(e,t){return t(e)}function at(e){if(!e)throw new Error("Assertion Failed")}function Ci(e){F.setImmediate?setImmediate(e):setTimeout(e,0)}function Oi(e,t){return e.reduce((n,i,r)=>{var s=t(i,r);return s&&(n[s[0]]=s[1]),n},{})}function we(e,t){if(typeof t=="string"&&te(e,t))return e[t];if(!t)return e;if(typeof t!="string"){for(var n=[],i=0,r=t.length;i<r;++i){var s=we(e,t[i]);n.push(s)}return n}var o=t.indexOf(".");if(o!==-1){var a=e[t.substr(0,o)];return a==null?void 0:we(a,t.substr(o+1))}}function re(e,t,n){if(e&&t!==void 0&&(!("isFrozen"in Object)||!Object.isFrozen(e)))if(typeof t!="string"&&"length"in t){at(typeof n!="string"&&"length"in n);for(var i=0,r=t.length;i<r;++i)re(e,t[i],n[i])}else{var s=t.indexOf(".");if(s!==-1){var o=t.substr(0,s),a=t.substr(s+1);if(a==="")n===void 0?G(e)&&!isNaN(parseInt(o))?e.splice(o,1):delete e[o]:e[o]=n;else{var l=e[o];l&&te(e,o)||(l=e[o]={}),re(l,a,n)}}else n===void 0?G(e)&&!isNaN(parseInt(t))?e.splice(t,1):delete e[t]:e[t]=n}}function Di(e){var t={};for(var n in e)te(e,n)&&(t[n]=e[n]);return t}const po=[].concat;function Pi(e){return po.apply([],e)}const Ti="BigUint64Array,BigInt64Array,Array,Boolean,String,Date,RegExp,Blob,File,FileList,FileSystemFileHandle,FileSystemDirectoryHandle,ArrayBuffer,DataView,Uint8ClampedArray,ImageBitmap,ImageData,Map,Set,CryptoKey".split(",").concat(Pi([8,16,32,64].map(e=>["Int","Uint","Float"].map(t=>t+e+"Array")))).filter(e=>F[e]),ho=Ti.map(e=>F[e]);Oi(Ti,e=>[e,!0]);let Se=null;function xt(e){Se=typeof WeakMap<"u"&&new WeakMap;const t=jn(e);return Se=null,t}function jn(e){if(!e||typeof e!="object")return e;let t=Se&&Se.get(e);if(t)return t;if(G(e)){t=[],Se&&Se.set(e,t);for(var n=0,i=e.length;n<i;++n)t.push(jn(e[n]))}else if(ho.indexOf(e.constructor)>=0)t=e;else{const s=bt(e);for(var r in t=s===Object.prototype?{}:Object.create(s),Se&&Se.set(e,t),e)te(e,r)&&(t[r]=jn(e[r]))}return t}const{toString:fo}={};function Kn(e){return fo.call(e).slice(8,-1)}const Nn=typeof Symbol<"u"?Symbol.iterator:"@@iterator",mo=typeof Nn=="symbol"?function(e){var t;return e!=null&&(t=e[Nn])&&t.apply(e)}:function(){return null},ze={};function fe(e){var t,n,i,r;if(arguments.length===1){if(G(e))return e.slice();if(this===ze&&typeof e=="string")return[e];if(r=mo(e)){for(n=[];!(i=r.next()).done;)n.push(i.value);return n}if(e==null)return[e];if(typeof(t=e.length)=="number"){for(n=new Array(t);t--;)n[t]=e[t];return n}return[e]}for(t=arguments.length,n=new Array(t);t--;)n[t]=arguments[t];return n}const Sr=typeof Symbol<"u"?e=>e[Symbol.toStringTag]==="AsyncFunction":()=>!1;var ae=typeof location<"u"&&/^(http|https):\/\/(localhost|127\.0\.0\.1)/.test(location.href);function Bi(e,t){ae=e,Mi=t}var Mi=()=>!0;const yo=!new Error("").stack;function qe(){if(yo)try{throw qe.arguments,new Error}catch(e){return e}return new Error}function $n(e,t){var n=e.stack;return n?(t=t||0,n.indexOf(e.name)===0&&(t+=(e.name+e.message).split(`
3
+ `).length),n.split(`
4
+ `).slice(t).filter(Mi).map(i=>`
5
+ `+i).join("")):""}var Fi=["Unknown","Constraint","Data","TransactionInactive","ReadOnly","Version","NotFound","InvalidState","InvalidAccess","Abort","Timeout","QuotaExceeded","Syntax","DataClone"],Er=["Modify","Bulk","OpenFailed","VersionChange","Schema","Upgrade","InvalidTable","MissingAPI","NoSuchDatabase","InvalidArgument","SubTransaction","Unsupported","Internal","DatabaseClosed","PrematureCommit","ForeignAwait"].concat(Fi),go={VersionChanged:"Database version changed by other database connection",DatabaseClosed:"Database has been closed",Abort:"Transaction aborted",TransactionInactive:"Transaction has already completed or failed",MissingAPI:"IndexedDB API missing. Please visit https://tinyurl.com/y2uuvskb"};function Ge(e,t){this._e=qe(),this.name=e,this.message=t}function ji(e,t){return e+". Errors: "+Object.keys(t).map(n=>t[n].toString()).filter((n,i,r)=>r.indexOf(n)===i).join(`
6
+ `)}function tn(e,t,n,i){this._e=qe(),this.failures=t,this.failedKeys=i,this.successCount=n,this.message=ji(e,t)}function dt(e,t){this._e=qe(),this.name="BulkError",this.failures=Object.keys(t).map(n=>t[n]),this.failuresByPos=t,this.message=ji(e,t)}He(Ge).from(Error).extend({stack:{get:function(){return this._stack||(this._stack=this.name+": "+this.message+$n(this._e,2))}},toString:function(){return this.name+": "+this.message}}),He(tn).from(Ge),He(dt).from(Ge);var kr=Er.reduce((e,t)=>(e[t]=t+"Error",e),{});const wo=Ge;var x=Er.reduce((e,t)=>{var n=t+"Error";function i(r,s){this._e=qe(),this.name=n,r?typeof r=="string"?(this.message=`${r}${s?`
7
+ `+s:""}`,this.inner=s||null):typeof r=="object"&&(this.message=`${r.name} ${r.message}`,this.inner=r):(this.message=go[t]||n,this.inner=null)}return He(i).from(wo),e[t]=i,e},{});x.Syntax=SyntaxError,x.Type=TypeError,x.Range=RangeError;var Vr=Fi.reduce((e,t)=>(e[t+"Error"]=x[t],e),{}),$t=Er.reduce((e,t)=>(["Syntax","Type","Range"].indexOf(t)===-1&&(e[t+"Error"]=x[t]),e),{});function B(){}function _t(e){return e}function vo(e,t){return e==null||e===_t?t:function(n){return t(e(n))}}function je(e,t){return function(){e.apply(this,arguments),t.apply(this,arguments)}}function bo(e,t){return e===B?t:function(){var n=e.apply(this,arguments);n!==void 0&&(arguments[0]=n);var i=this.onsuccess,r=this.onerror;this.onsuccess=null,this.onerror=null;var s=t.apply(this,arguments);return i&&(this.onsuccess=this.onsuccess?je(i,this.onsuccess):i),r&&(this.onerror=this.onerror?je(r,this.onerror):r),s!==void 0?s:n}}function _o(e,t){return e===B?t:function(){e.apply(this,arguments);var n=this.onsuccess,i=this.onerror;this.onsuccess=this.onerror=null,t.apply(this,arguments),n&&(this.onsuccess=this.onsuccess?je(n,this.onsuccess):n),i&&(this.onerror=this.onerror?je(i,this.onerror):i)}}function So(e,t){return e===B?t:function(n){var i=e.apply(this,arguments);J(n,i);var r=this.onsuccess,s=this.onerror;this.onsuccess=null,this.onerror=null;var o=t.apply(this,arguments);return r&&(this.onsuccess=this.onsuccess?je(r,this.onsuccess):r),s&&(this.onerror=this.onerror?je(s,this.onerror):s),i===void 0?o===void 0?void 0:o:J(i,o)}}function Eo(e,t){return e===B?t:function(){return t.apply(this,arguments)!==!1&&e.apply(this,arguments)}}function Lr(e,t){return e===B?t:function(){var n=e.apply(this,arguments);if(n&&typeof n.then=="function"){for(var i=this,r=arguments.length,s=new Array(r);r--;)s[r]=arguments[r];return n.then(function(){return t.apply(i,s)})}return t.apply(this,arguments)}}$t.ModifyError=tn,$t.DexieError=Ge,$t.BulkError=dt;var St={};const Ki=100,[qn,nn,Vn]=typeof Promise>"u"?[]:(()=>{let e=Promise.resolve();if(typeof crypto>"u"||!crypto.subtle)return[e,bt(e),e];const t=crypto.subtle.digest("SHA-512",new Uint8Array([0]));return[t,bt(t),e]})(),Ni=nn&&nn.then,qt=qn&&qn.constructor,Ir=!!Vn;var Wn=!1,ko=Vn?()=>{Vn.then(Pt)}:F.setImmediate?setImmediate.bind(null,Pt):F.MutationObserver?()=>{var e=document.createElement("div");new MutationObserver(()=>{Pt(),e=null}).observe(e,{attributes:!0}),e.setAttribute("i","1")}:()=>{setTimeout(Pt,0)},pt=function(e,t){lt.push([e,t]),rn&&(ko(),rn=!1)},zn=!0,rn=!0,Te=[],Vt=[],Hn=null,Gn=_t,Ye={id:"global",global:!0,ref:0,unhandleds:[],onunhandled:Hr,pgp:!1,env:{},finalize:function(){this.unhandleds.forEach(e=>{try{Hr(e[0],e[1])}catch{}})}},U=Ye,lt=[],Be=0,Wt=[];function L(e){if(typeof this!="object")throw new TypeError("Promises must be constructed via new");this._listeners=[],this.onuncatched=B,this._lib=!1;var t=this._PSD=U;if(ae&&(this._stackHolder=qe(),this._prev=null,this._numPrev=0),typeof e!="function"){if(e!==St)throw new TypeError("Not a function");return this._state=arguments[1],this._value=arguments[2],void(this._state===!1&&Jn(this,this._value))}this._state=null,this._value=null,++t.ref,qi(this,e)}const Yn={get:function(){var e=U,t=sn;function n(i,r){var s=!e.global&&(e!==U||t!==sn);const o=s&&!ve();var a=new L((l,u)=>{Ur(this,new $i(on(i,e,s,o),on(r,e,s,o),l,u,e))});return ae&&zi(a,this),a}return n.prototype=St,n},set:function(e){ge(this,"then",e&&e.prototype===St?Yn:{get:function(){return e},set:Yn.set})}};function $i(e,t,n,i,r){this.onFulfilled=typeof e=="function"?e:null,this.onRejected=typeof t=="function"?t:null,this.resolve=n,this.reject=i,this.psd=r}function qi(e,t){try{t(n=>{if(e._state===null){if(n===e)throw new TypeError("A promise cannot be resolved with itself.");var i=e._lib&&At();n&&typeof n.then=="function"?qi(e,(r,s)=>{n instanceof L?n._then(r,s):n.then(r,s)}):(e._state=!0,e._value=n,Vi(e)),i&&Rt()}},Jn.bind(null,e))}catch(n){Jn(e,n)}}function Jn(e,t){if(Vt.push(t),e._state===null){var n=e._lib&&At();t=Gn(t),e._state=!1,e._value=t,ae&&t!==null&&typeof t=="object"&&!t._promise&&function(i,r,s){try{i.apply(null,s)}catch(o){r&&r(o)}}(()=>{var i=_r(t,"stack");t._promise=e,ge(t,"stack",{get:()=>Wn?i&&(i.get?i.get.apply(t):i.value):e.stack})}),function(i){Te.some(r=>r._value===i._value)||Te.push(i)}(e),Vi(e),n&&Rt()}}function Vi(e){var t=e._listeners;e._listeners=[];for(var n=0,i=t.length;n<i;++n)Ur(e,t[n]);var r=e._PSD;--r.ref||r.finalize(),Be===0&&(++Be,pt(()=>{--Be==0&&xr()},[]))}function Ur(e,t){if(e._state!==null){var n=e._state?t.onFulfilled:t.onRejected;if(n===null)return(e._state?t.resolve:t.reject)(e._value);++t.psd.ref,++Be,pt(Lo,[n,e,t])}else e._listeners.push(t)}function Lo(e,t,n){try{Hn=t;var i,r=t._value;t._state?i=e(r):(Vt.length&&(Vt=[]),i=e(r),Vt.indexOf(r)===-1&&function(s){for(var o=Te.length;o;)if(Te[--o]._value===s._value)return void Te.splice(o,1)}(t)),n.resolve(i)}catch(s){n.reject(s)}finally{Hn=null,--Be==0&&xr(),--n.psd.ref||n.psd.finalize()}}function Wi(e,t,n){if(t.length===n)return t;var i="";if(e._state===!1){var r,s,o=e._value;o!=null?(r=o.name||"Error",s=o.message||o,i=$n(o,0)):(r=o,s=""),t.push(r+(s?": "+s:"")+i)}return ae&&((i=$n(e._stackHolder,2))&&t.indexOf(i)===-1&&t.push(i),e._prev&&Wi(e._prev,t,n)),t}function zi(e,t){var n=t?t._numPrev+1:0;n<100&&(e._prev=t,e._numPrev=n)}function Pt(){At()&&Rt()}function At(){var e=zn;return zn=!1,rn=!1,e}function Rt(){var e,t,n;do for(;lt.length>0;)for(e=lt,lt=[],n=e.length,t=0;t<n;++t){var i=e[t];i[0].apply(null,i[1])}while(lt.length>0);zn=!0,rn=!0}function xr(){var e=Te;Te=[],e.forEach(i=>{i._PSD.onunhandled.call(null,i._value,i)});for(var t=Wt.slice(0),n=t.length;n;)t[--n]()}function Tt(e){return new L(St,!1,e)}function K(e,t){var n=U;return function(){var i=At(),r=U;try{return xe(n,!0),e.apply(this,arguments)}catch(s){t&&t(s)}finally{xe(r,!1),i&&Rt()}}}Xe(L.prototype,{then:Yn,_then:function(e,t){Ur(this,new $i(null,null,e,t,U))},catch:function(e){if(arguments.length===1)return this.then(null,e);var t=arguments[0],n=arguments[1];return typeof t=="function"?this.then(null,i=>i instanceof t?n(i):Tt(i)):this.then(null,i=>i&&i.name===t?n(i):Tt(i))},finally:function(e){return this.then(t=>(e(),t),t=>(e(),Tt(t)))},stack:{get:function(){if(this._stack)return this._stack;try{Wn=!0;var e=Wi(this,[],20).join(`
8
+ From previous: `);return this._state!==null&&(this._stack=e),e}finally{Wn=!1}}},timeout:function(e,t){return e<1/0?new L((n,i)=>{var r=setTimeout(()=>i(new x.Timeout(t)),e);this.then(n,i).finally(clearTimeout.bind(null,r))}):this}}),typeof Symbol<"u"&&Symbol.toStringTag&&ge(L.prototype,Symbol.toStringTag,"Dexie.Promise"),Ye.env=Hi(),Xe(L,{all:function(){var e=fe.apply(null,arguments).map(Bt);return new L(function(t,n){e.length===0&&t([]);var i=e.length;e.forEach((r,s)=>L.resolve(r).then(o=>{e[s]=o,--i||t(e)},n))})},resolve:e=>{if(e instanceof L)return e;if(e&&typeof e.then=="function")return new L((n,i)=>{e.then(n,i)});var t=new L(St,!0,e);return zi(t,Hn),t},reject:Tt,race:function(){var e=fe.apply(null,arguments).map(Bt);return new L((t,n)=>{e.map(i=>L.resolve(i).then(t,n))})},PSD:{get:()=>U,set:e=>U=e},totalEchoes:{get:()=>sn},newPSD:Ue,usePSD:nt,scheduler:{get:()=>pt,set:e=>{pt=e}},rejectionMapper:{get:()=>Gn,set:e=>{Gn=e}},follow:(e,t)=>new L((n,i)=>Ue((r,s)=>{var o=U;o.unhandleds=[],o.onunhandled=s,o.finalize=je(function(){(function(a){function l(){a(),Wt.splice(Wt.indexOf(l),1)}Wt.push(l),++Be,pt(()=>{--Be==0&&xr()},[])})(()=>{this.unhandleds.length===0?r():s(this.unhandleds[0])})},o.finalize),e()},t,n,i))}),qt&&(qt.allSettled&&ge(L,"allSettled",function(){const e=fe.apply(null,arguments).map(Bt);return new L(t=>{e.length===0&&t([]);let n=e.length;const i=new Array(n);e.forEach((r,s)=>L.resolve(r).then(o=>i[s]={status:"fulfilled",value:o},o=>i[s]={status:"rejected",reason:o}).then(()=>--n||t(i)))})}),qt.any&&typeof AggregateError<"u"&&ge(L,"any",function(){const e=fe.apply(null,arguments).map(Bt);return new L((t,n)=>{e.length===0&&n(new AggregateError([]));let i=e.length;const r=new Array(i);e.forEach((s,o)=>L.resolve(s).then(a=>t(a),a=>{r[o]=a,--i||n(new AggregateError(r))}))})}));const H={awaits:0,echoes:0,id:0};var Io=0,zt=[],_n=0,sn=0,Uo=0;function Ue(e,t,n,i){var r=U,s=Object.create(r);s.parent=r,s.ref=0,s.global=!1,s.id=++Uo;var o=Ye.env;s.env=Ir?{Promise:L,PromiseProp:{value:L,configurable:!0,writable:!0},all:L.all,race:L.race,allSettled:L.allSettled,any:L.any,resolve:L.resolve,reject:L.reject,nthen:Wr(o.nthen,s),gthen:Wr(o.gthen,s)}:{},t&&J(s,t),++r.ref,s.finalize=function(){--this.parent.ref||this.parent.finalize()};var a=nt(s,e,n,i);return s.ref===0&&s.finalize(),a}function tt(){return H.id||(H.id=++Io),++H.awaits,H.echoes+=Ki,H.id}function ve(){return!!H.awaits&&(--H.awaits==0&&(H.id=0),H.echoes=H.awaits*Ki,!0)}function Bt(e){return H.echoes&&e&&e.constructor===qt?(tt(),e.then(t=>(ve(),t),t=>(ve(),V(t)))):e}function xo(e){++sn,H.echoes&&--H.echoes!=0||(H.echoes=H.id=0),zt.push(U),xe(e,!0)}function Ao(){var e=zt[zt.length-1];zt.pop(),xe(e,!1)}function xe(e,t){var n=U;if((t?!H.echoes||_n++&&e===U:!_n||--_n&&e===U)||Gi(t?xo.bind(null,e):Ao),e!==U&&(U=e,n===Ye&&(Ye.env=Hi()),Ir)){var i=Ye.env.Promise,r=e.env;nn.then=r.nthen,i.prototype.then=r.gthen,(n.global||e.global)&&(Object.defineProperty(F,"Promise",r.PromiseProp),i.all=r.all,i.race=r.race,i.resolve=r.resolve,i.reject=r.reject,r.allSettled&&(i.allSettled=r.allSettled),r.any&&(i.any=r.any))}}function Hi(){var e=F.Promise;return Ir?{Promise:e,PromiseProp:Object.getOwnPropertyDescriptor(F,"Promise"),all:e.all,race:e.race,allSettled:e.allSettled,any:e.any,resolve:e.resolve,reject:e.reject,nthen:nn.then,gthen:e.prototype.then}:{}}function nt(e,t,n,i,r){var s=U;try{return xe(e,!0),t(n,i,r)}finally{xe(s,!1)}}function Gi(e){Ni.call(qn,e)}function on(e,t,n,i){return typeof e!="function"?e:function(){var r=U;n&&tt(),xe(t,!0);try{return e.apply(this,arguments)}finally{xe(r,!1),i&&Gi(ve)}}}function Wr(e,t){return function(n,i){return e.call(this,on(n,t),on(i,t))}}(""+Ni).indexOf("[native code]")===-1&&(tt=ve=B);const zr="unhandledrejection";function Hr(e,t){var n;try{n=t.onuncatched(e)}catch{}if(n!==!1)try{var i,r={promise:t,reason:e};if(F.document&&document.createEvent?((i=document.createEvent("Event")).initEvent(zr,!0,!0),J(i,r)):F.CustomEvent&&J(i=new CustomEvent(zr,{detail:r}),r),i&&F.dispatchEvent&&(dispatchEvent(i),!F.PromiseRejectionEvent&&F.onunhandledrejection))try{F.onunhandledrejection(i)}catch{}ae&&i&&!i.defaultPrevented&&console.warn(`Unhandled rejection: ${e.stack||e}`)}catch{}}var V=L.reject;function Qn(e,t,n,i){if(e.idbdb&&(e._state.openComplete||U.letThrough||e._vip)){var r=e._createTransaction(t,n,e._dbSchema);try{r.create(),e._state.PR1398_maxLoop=3}catch(s){return s.name===kr.InvalidState&&e.isOpen()&&--e._state.PR1398_maxLoop>0?(console.warn("Dexie: Need to reopen db"),e._close(),e.open().then(()=>Qn(e,t,n,i))):V(s)}return r._promise(t,(s,o)=>Ue(()=>(U.trans=r,i(s,o,r)))).then(s=>r._completion.then(()=>s))}if(e._state.openComplete)return V(new x.DatabaseClosed(e._state.dbOpenError));if(!e._state.isBeingOpened){if(!e._options.autoOpen)return V(new x.DatabaseClosed);e.open().catch(B)}return e._state.dbReadyPromise.then(()=>Qn(e,t,n,i))}const Gr="3.2.7",De="￿",Xn=-1/0,de="Invalid key provided. Keys must be of type string, number, Date or Array<string | number | Date>.",Yi="String expected.",ht=[],fn=typeof navigator<"u"&&/(MSIE|Trident|Edge)/.test(navigator.userAgent),Ro=fn,Co=fn,Ji=e=>!/(dexie\.js|dexie\.min\.js)/.test(e),mn="__dbnames",Sn="readonly",En="readwrite";function Ke(e,t){return e?t?function(){return e.apply(this,arguments)&&t.apply(this,arguments)}:e:t}const Qi={type:3,lower:-1/0,lowerOpen:!1,upper:[[]],upperOpen:!1};function Mt(e){return typeof e!="string"||/\./.test(e)?t=>t:t=>(t[e]===void 0&&e in t&&delete(t=xt(t))[e],t)}class Oo{_trans(t,n,i){const r=this._tx||U.trans,s=this.name;function o(l,u,c){if(!c.schema[s])throw new x.NotFound("Table "+s+" not part of transaction");return n(c.idbtrans,c)}const a=At();try{return r&&r.db===this.db?r===U.trans?r._promise(t,o,i):Ue(()=>r._promise(t,o,i),{trans:r,transless:U.transless||U}):Qn(this.db,t,[this.name],o)}finally{a&&Rt()}}get(t,n){return t&&t.constructor===Object?this.where(t).first(n):this._trans("readonly",i=>this.core.get({trans:i,key:t}).then(r=>this.hook.reading.fire(r))).then(n)}where(t){if(typeof t=="string")return new this.db.WhereClause(this,t);if(G(t))return new this.db.WhereClause(this,`[${t.join("+")}]`);const n=q(t);if(n.length===1)return this.where(n[0]).equals(t[n[0]]);const i=this.schema.indexes.concat(this.schema.primKey).filter(u=>{if(u.compound&&n.every(c=>u.keyPath.indexOf(c)>=0)){for(let c=0;c<n.length;++c)if(n.indexOf(u.keyPath[c])===-1)return!1;return!0}return!1}).sort((u,c)=>u.keyPath.length-c.keyPath.length)[0];if(i&&this.db._maxKey!==De){const u=i.keyPath.slice(0,n.length);return this.where(u).equals(u.map(c=>t[c]))}!i&&ae&&console.warn(`The query ${JSON.stringify(t)} on ${this.name} would benefit of a compound index [${n.join("+")}]`);const{idxByName:r}=this.schema,s=this.db._deps.indexedDB;function o(u,c){try{return s.cmp(u,c)===0}catch{return!1}}const[a,l]=n.reduce(([u,c],p)=>{const d=r[p],h=t[p];return[u||d,u||!d?Ke(c,d&&d.multi?g=>{const y=we(g,p);return G(y)&&y.some(w=>o(h,w))}:g=>o(h,we(g,p))):c]},[null,null]);return a?this.where(a.name).equals(t[a.keyPath]).filter(l):i?this.filter(l):this.where(n).equals("")}filter(t){return this.toCollection().and(t)}count(t){return this.toCollection().count(t)}offset(t){return this.toCollection().offset(t)}limit(t){return this.toCollection().limit(t)}each(t){return this.toCollection().each(t)}toArray(t){return this.toCollection().toArray(t)}toCollection(){return new this.db.Collection(new this.db.WhereClause(this))}orderBy(t){return new this.db.Collection(new this.db.WhereClause(this,G(t)?`[${t.join("+")}]`:t))}reverse(){return this.toCollection().reverse()}mapToClass(t){this.schema.mappedClass=t;const n=i=>{if(!i)return i;const r=Object.create(t.prototype);for(var s in i)if(te(i,s))try{r[s]=i[s]}catch{}return r};return this.schema.readHook&&this.hook.reading.unsubscribe(this.schema.readHook),this.schema.readHook=n,this.hook("reading",n),t}defineClass(){return this.mapToClass(function(t){J(this,t)})}add(t,n){const{auto:i,keyPath:r}=this.schema.primKey;let s=t;return r&&i&&(s=Mt(r)(t)),this._trans("readwrite",o=>this.core.mutate({trans:o,type:"add",keys:n!=null?[n]:null,values:[s]})).then(o=>o.numFailures?L.reject(o.failures[0]):o.lastResult).then(o=>{if(r)try{re(t,r,o)}catch{}return o})}update(t,n){if(typeof t!="object"||G(t))return this.where(":id").equals(t).modify(n);{const i=we(t,this.schema.primKey.keyPath);if(i===void 0)return V(new x.InvalidArgument("Given object does not contain its primary key"));try{typeof n!="function"?q(n).forEach(r=>{re(t,r,n[r])}):n(t,{value:t,primKey:i})}catch{}return this.where(":id").equals(i).modify(n)}}put(t,n){const{auto:i,keyPath:r}=this.schema.primKey;let s=t;return r&&i&&(s=Mt(r)(t)),this._trans("readwrite",o=>this.core.mutate({trans:o,type:"put",values:[s],keys:n!=null?[n]:null})).then(o=>o.numFailures?L.reject(o.failures[0]):o.lastResult).then(o=>{if(r)try{re(t,r,o)}catch{}return o})}delete(t){return this._trans("readwrite",n=>this.core.mutate({trans:n,type:"delete",keys:[t]})).then(n=>n.numFailures?L.reject(n.failures[0]):void 0)}clear(){return this._trans("readwrite",t=>this.core.mutate({trans:t,type:"deleteRange",range:Qi})).then(t=>t.numFailures?L.reject(t.failures[0]):void 0)}bulkGet(t){return this._trans("readonly",n=>this.core.getMany({keys:t,trans:n}).then(i=>i.map(r=>this.hook.reading.fire(r))))}bulkAdd(t,n,i){const r=Array.isArray(n)?n:void 0,s=(i=i||(r?void 0:n))?i.allKeys:void 0;return this._trans("readwrite",o=>{const{auto:a,keyPath:l}=this.schema.primKey;if(l&&r)throw new x.InvalidArgument("bulkAdd(): keys argument invalid on tables with inbound keys");if(r&&r.length!==t.length)throw new x.InvalidArgument("Arguments objects and keys must have the same length");const u=t.length;let c=l&&a?t.map(Mt(l)):t;return this.core.mutate({trans:o,type:"add",keys:r,values:c,wantResults:s}).then(({numFailures:p,results:d,lastResult:h,failures:g})=>{if(p===0)return s?d:h;throw new dt(`${this.name}.bulkAdd(): ${p} of ${u} operations failed`,g)})})}bulkPut(t,n,i){const r=Array.isArray(n)?n:void 0,s=(i=i||(r?void 0:n))?i.allKeys:void 0;return this._trans("readwrite",o=>{const{auto:a,keyPath:l}=this.schema.primKey;if(l&&r)throw new x.InvalidArgument("bulkPut(): keys argument invalid on tables with inbound keys");if(r&&r.length!==t.length)throw new x.InvalidArgument("Arguments objects and keys must have the same length");const u=t.length;let c=l&&a?t.map(Mt(l)):t;return this.core.mutate({trans:o,type:"put",keys:r,values:c,wantResults:s}).then(({numFailures:p,results:d,lastResult:h,failures:g})=>{if(p===0)return s?d:h;throw new dt(`${this.name}.bulkPut(): ${p} of ${u} operations failed`,g)})})}bulkDelete(t){const n=t.length;return this._trans("readwrite",i=>this.core.mutate({trans:i,type:"delete",keys:t})).then(({numFailures:i,lastResult:r,failures:s})=>{if(i===0)return r;throw new dt(`${this.name}.bulkDelete(): ${i} of ${n} operations failed`,s)})}}function ft(e){var t={},n=function(o,a){if(a){for(var l=arguments.length,u=new Array(l-1);--l;)u[l-1]=arguments[l];return t[o].subscribe.apply(null,u),e}if(typeof o=="string")return t[o]};n.addEventType=s;for(var i=1,r=arguments.length;i<r;++i)s(arguments[i]);return n;function s(o,a,l){if(typeof o!="object"){var u;a||(a=Eo),l||(l=B);var c={subscribers:[],fire:l,subscribe:function(p){c.subscribers.indexOf(p)===-1&&(c.subscribers.push(p),c.fire=a(c.fire,p))},unsubscribe:function(p){c.subscribers=c.subscribers.filter(function(d){return d!==p}),c.fire=c.subscribers.reduce(a,l)}};return t[o]=n[o]=c,c}q(u=o).forEach(function(p){var d=u[p];if(G(d))s(p,u[p][0],u[p][1]);else{if(d!=="asap")throw new x.InvalidArgument("Invalid event config");var h=s(p,_t,function(){for(var g=arguments.length,y=new Array(g);g--;)y[g]=arguments[g];h.subscribers.forEach(function(w){Ci(function(){w.apply(null,y)})})})}})}}function st(e,t){return He(t).from({prototype:e}),t}function Ve(e,t){return!(e.filter||e.algorithm||e.or)&&(t?e.justLimit:!e.replayFilter)}function kn(e,t){e.filter=Ke(e.filter,t)}function Ln(e,t,n){var i=e.replayFilter;e.replayFilter=i?()=>Ke(i(),t()):t,e.justLimit=n&&!i}function Ht(e,t){if(e.isPrimKey)return t.primaryKey;const n=t.getIndexByKeyPath(e.index);if(!n)throw new x.Schema("KeyPath "+e.index+" on object store "+t.name+" is not indexed");return n}function Yr(e,t,n){const i=Ht(e,t.schema);return t.openCursor({trans:n,values:!e.keysOnly,reverse:e.dir==="prev",unique:!!e.unique,query:{index:i,range:e.range}})}function Ft(e,t,n,i){const r=e.replayFilter?Ke(e.filter,e.replayFilter()):e.filter;if(e.or){const s={},o=(a,l,u)=>{if(!r||r(l,u,d=>l.stop(d),d=>l.fail(d))){var c=l.primaryKey,p=""+c;p==="[object ArrayBuffer]"&&(p=""+new Uint8Array(c)),te(s,p)||(s[p]=!0,t(a,l,u))}};return Promise.all([e.or._iterate(o,n),Jr(Yr(e,i,n),e.algorithm,o,!e.keysOnly&&e.valueMapper)])}return Jr(Yr(e,i,n),Ke(e.algorithm,r),t,!e.keysOnly&&e.valueMapper)}function Jr(e,t,n,i){var r=K(i?(s,o,a)=>n(i(s),o,a):n);return e.then(s=>{if(s)return s.start(()=>{var o=()=>s.continue();t&&!t(s,a=>o=a,a=>{s.stop(a),o=B},a=>{s.fail(a),o=B})||r(s.value,s,a=>o=a),o()})})}function Y(e,t){try{const n=Qr(e),i=Qr(t);if(n!==i)return n==="Array"?1:i==="Array"?-1:n==="binary"?1:i==="binary"?-1:n==="string"?1:i==="string"?-1:n==="Date"?1:i!=="Date"?NaN:-1;switch(n){case"number":case"Date":case"string":return e>t?1:e<t?-1:0;case"binary":return function(r,s){const o=r.length,a=s.length,l=o<a?o:a;for(let u=0;u<l;++u)if(r[u]!==s[u])return r[u]<s[u]?-1:1;return o===a?0:o<a?-1:1}(Xr(e),Xr(t));case"Array":return function(r,s){const o=r.length,a=s.length,l=o<a?o:a;for(let u=0;u<l;++u){const c=Y(r[u],s[u]);if(c!==0)return c}return o===a?0:o<a?-1:1}(e,t)}}catch{}return NaN}function Qr(e){const t=typeof e;if(t!=="object")return t;if(ArrayBuffer.isView(e))return"binary";const n=Kn(e);return n==="ArrayBuffer"?"binary":n}function Xr(e){return e instanceof Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e)}class Do{_read(t,n){var i=this._ctx;return i.error?i.table._trans(null,V.bind(null,i.error)):i.table._trans("readonly",t).then(n)}_write(t){var n=this._ctx;return n.error?n.table._trans(null,V.bind(null,n.error)):n.table._trans("readwrite",t,"locked")}_addAlgorithm(t){var n=this._ctx;n.algorithm=Ke(n.algorithm,t)}_iterate(t,n){return Ft(this._ctx,t,n,this._ctx.table.core)}clone(t){var n=Object.create(this.constructor.prototype),i=Object.create(this._ctx);return t&&J(i,t),n._ctx=i,n}raw(){return this._ctx.valueMapper=null,this}each(t){var n=this._ctx;return this._read(i=>Ft(n,t,i,n.table.core))}count(t){return this._read(n=>{const i=this._ctx,r=i.table.core;if(Ve(i,!0))return r.count({trans:n,query:{index:Ht(i,r.schema),range:i.range}}).then(o=>Math.min(o,i.limit));var s=0;return Ft(i,()=>(++s,!1),n,r).then(()=>s)}).then(t)}sortBy(t,n){const i=t.split(".").reverse(),r=i[0],s=i.length-1;function o(u,c){return c?o(u[i[c]],c-1):u[r]}var a=this._ctx.dir==="next"?1:-1;function l(u,c){var p=o(u,s),d=o(c,s);return p<d?-a:p>d?a:0}return this.toArray(function(u){return u.sort(l)}).then(n)}toArray(t){return this._read(n=>{var i=this._ctx;if(i.dir==="next"&&Ve(i,!0)&&i.limit>0){const{valueMapper:r}=i,s=Ht(i,i.table.core.schema);return i.table.core.query({trans:n,limit:i.limit,values:!0,query:{index:s,range:i.range}}).then(({result:o})=>r?o.map(r):o)}{const r=[];return Ft(i,s=>r.push(s),n,i.table.core).then(()=>r)}},t)}offset(t){var n=this._ctx;return t<=0||(n.offset+=t,Ve(n)?Ln(n,()=>{var i=t;return(r,s)=>i===0||(i===1?(--i,!1):(s(()=>{r.advance(i),i=0}),!1))}):Ln(n,()=>{var i=t;return()=>--i<0})),this}limit(t){return this._ctx.limit=Math.min(this._ctx.limit,t),Ln(this._ctx,()=>{var n=t;return function(i,r,s){return--n<=0&&r(s),n>=0}},!0),this}until(t,n){return kn(this._ctx,function(i,r,s){return!t(i.value)||(r(s),n)}),this}first(t){return this.limit(1).toArray(function(n){return n[0]}).then(t)}last(t){return this.reverse().first(t)}filter(t){var n,i;return kn(this._ctx,function(r){return t(r.value)}),n=this._ctx,i=t,n.isMatch=Ke(n.isMatch,i),this}and(t){return this.filter(t)}or(t){return new this.db.WhereClause(this._ctx.table,t,this)}reverse(){return this._ctx.dir=this._ctx.dir==="prev"?"next":"prev",this._ondirectionchange&&this._ondirectionchange(this._ctx.dir),this}desc(){return this.reverse()}eachKey(t){var n=this._ctx;return n.keysOnly=!n.isMatch,this.each(function(i,r){t(r.key,r)})}eachUniqueKey(t){return this._ctx.unique="unique",this.eachKey(t)}eachPrimaryKey(t){var n=this._ctx;return n.keysOnly=!n.isMatch,this.each(function(i,r){t(r.primaryKey,r)})}keys(t){var n=this._ctx;n.keysOnly=!n.isMatch;var i=[];return this.each(function(r,s){i.push(s.key)}).then(function(){return i}).then(t)}primaryKeys(t){var n=this._ctx;if(n.dir==="next"&&Ve(n,!0)&&n.limit>0)return this._read(r=>{var s=Ht(n,n.table.core.schema);return n.table.core.query({trans:r,values:!1,limit:n.limit,query:{index:s,range:n.range}})}).then(({result:r})=>r).then(t);n.keysOnly=!n.isMatch;var i=[];return this.each(function(r,s){i.push(s.primaryKey)}).then(function(){return i}).then(t)}uniqueKeys(t){return this._ctx.unique="unique",this.keys(t)}firstKey(t){return this.limit(1).keys(function(n){return n[0]}).then(t)}lastKey(t){return this.reverse().firstKey(t)}distinct(){var t=this._ctx,n=t.index&&t.table.schema.idxByName[t.index];if(!n||!n.multi)return this;var i={};return kn(this._ctx,function(r){var s=r.primaryKey.toString(),o=te(i,s);return i[s]=!0,!o}),this}modify(t){var n=this._ctx;return this._write(i=>{var r;if(typeof t=="function")r=t;else{var s=q(t),o=s.length;r=function(y){for(var w=!1,m=0;m<o;++m){var f=s[m],b=t[f];we(y,f)!==b&&(re(y,f,b),w=!0)}return w}}const a=n.table.core,{outbound:l,extractKey:u}=a.schema.primaryKey,c=this.db._options.modifyChunkSize||200,p=[];let d=0;const h=[],g=(y,w)=>{const{failures:m,numFailures:f}=w;d+=y-f;for(let b of q(m))p.push(m[b])};return this.clone().primaryKeys().then(y=>{const w=m=>{const f=Math.min(c,y.length-m);return a.getMany({trans:i,keys:y.slice(m,m+f),cache:"immutable"}).then(b=>{const _=[],v=[],k=l?[]:null,S=[];for(let E=0;E<f;++E){const j=b[E],P={value:xt(j),primKey:y[m+E]};r.call(P,P.value,P)!==!1&&(P.value==null?S.push(y[m+E]):l||Y(u(j),u(P.value))===0?(v.push(P.value),l&&k.push(y[m+E])):(S.push(y[m+E]),_.push(P.value)))}const A=Ve(n)&&n.limit===1/0&&(typeof t!="function"||t===In)&&{index:n.index,range:n.range};return Promise.resolve(_.length>0&&a.mutate({trans:i,type:"add",values:_}).then(E=>{for(let j in E.failures)S.splice(parseInt(j),1);g(_.length,E)})).then(()=>(v.length>0||A&&typeof t=="object")&&a.mutate({trans:i,type:"put",keys:k,values:v,criteria:A,changeSpec:typeof t!="function"&&t}).then(E=>g(v.length,E))).then(()=>(S.length>0||A&&t===In)&&a.mutate({trans:i,type:"delete",keys:S,criteria:A}).then(E=>g(S.length,E))).then(()=>y.length>m+f&&w(m+c))})};return w(0).then(()=>{if(p.length>0)throw new tn("Error modifying one or more objects",p,d,h);return y.length})})})}delete(){var t=this._ctx,n=t.range;return Ve(t)&&(t.isPrimKey&&!Co||n.type===3)?this._write(i=>{const{primaryKey:r}=t.table.core.schema,s=n;return t.table.core.count({trans:i,query:{index:r,range:s}}).then(o=>t.table.core.mutate({trans:i,type:"deleteRange",range:s}).then(({failures:a,lastResult:l,results:u,numFailures:c})=>{if(c)throw new tn("Could not delete some values",Object.keys(a).map(p=>a[p]),o-c);return o-c}))}):this.modify(In)}}const In=(e,t)=>t.value=null;function Po(e,t){return e<t?-1:e===t?0:1}function To(e,t){return e>t?-1:e===t?0:1}function X(e,t,n){var i=e instanceof Zi?new e.Collection(e):e;return i._ctx.error=n?new n(t):new TypeError(t),i}function We(e){return new e.Collection(e,()=>Xi("")).limit(0)}function Bo(e,t,n,i,r,s){for(var o=Math.min(e.length,i.length),a=-1,l=0;l<o;++l){var u=t[l];if(u!==i[l])return r(e[l],n[l])<0?e.substr(0,l)+n[l]+n.substr(l+1):r(e[l],i[l])<0?e.substr(0,l)+i[l]+n.substr(l+1):a>=0?e.substr(0,a)+t[a]+n.substr(a+1):null;r(e[l],u)<0&&(a=l)}return o<i.length&&s==="next"?e+n.substr(e.length):o<e.length&&s==="prev"?e.substr(0,n.length):a<0?null:e.substr(0,a)+i[a]+n.substr(a+1)}function jt(e,t,n,i){var r,s,o,a,l,u,c,p=n.length;if(!n.every(y=>typeof y=="string"))return X(e,Yi);function d(y){r=function(m){return m==="next"?f=>f.toUpperCase():f=>f.toLowerCase()}(y),s=function(m){return m==="next"?f=>f.toLowerCase():f=>f.toUpperCase()}(y),o=y==="next"?Po:To;var w=n.map(function(m){return{lower:s(m),upper:r(m)}}).sort(function(m,f){return o(m.lower,f.lower)});a=w.map(function(m){return m.upper}),l=w.map(function(m){return m.lower}),u=y,c=y==="next"?"":i}d("next");var h=new e.Collection(e,()=>_e(a[0],l[p-1]+i));h._ondirectionchange=function(y){d(y)};var g=0;return h._addAlgorithm(function(y,w,m){var f=y.key;if(typeof f!="string")return!1;var b=s(f);if(t(b,l,g))return!0;for(var _=null,v=g;v<p;++v){var k=Bo(f,b,a[v],l[v],o,u);k===null&&_===null?g=v+1:(_===null||o(_,k)>0)&&(_=k)}return w(_!==null?function(){y.continue(_+c)}:m),!1}),h}function _e(e,t,n,i){return{type:2,lower:e,upper:t,lowerOpen:n,upperOpen:i}}function Xi(e){return{type:1,lower:e,upper:e}}class Zi{get Collection(){return this._ctx.table.db.Collection}between(t,n,i,r){i=i!==!1,r=r===!0;try{return this._cmp(t,n)>0||this._cmp(t,n)===0&&(i||r)&&(!i||!r)?We(this):new this.Collection(this,()=>_e(t,n,!i,!r))}catch{return X(this,de)}}equals(t){return t==null?X(this,de):new this.Collection(this,()=>Xi(t))}above(t){return t==null?X(this,de):new this.Collection(this,()=>_e(t,void 0,!0))}aboveOrEqual(t){return t==null?X(this,de):new this.Collection(this,()=>_e(t,void 0,!1))}below(t){return t==null?X(this,de):new this.Collection(this,()=>_e(void 0,t,!1,!0))}belowOrEqual(t){return t==null?X(this,de):new this.Collection(this,()=>_e(void 0,t))}startsWith(t){return typeof t!="string"?X(this,Yi):this.between(t,t+De,!0,!0)}startsWithIgnoreCase(t){return t===""?this.startsWith(t):jt(this,(n,i)=>n.indexOf(i[0])===0,[t],De)}equalsIgnoreCase(t){return jt(this,(n,i)=>n===i[0],[t],"")}anyOfIgnoreCase(){var t=fe.apply(ze,arguments);return t.length===0?We(this):jt(this,(n,i)=>i.indexOf(n)!==-1,t,"")}startsWithAnyOfIgnoreCase(){var t=fe.apply(ze,arguments);return t.length===0?We(this):jt(this,(n,i)=>i.some(r=>n.indexOf(r)===0),t,De)}anyOf(){const t=fe.apply(ze,arguments);let n=this._cmp;try{t.sort(n)}catch{return X(this,de)}if(t.length===0)return We(this);const i=new this.Collection(this,()=>_e(t[0],t[t.length-1]));i._ondirectionchange=s=>{n=s==="next"?this._ascending:this._descending,t.sort(n)};let r=0;return i._addAlgorithm((s,o,a)=>{const l=s.key;for(;n(l,t[r])>0;)if(++r,r===t.length)return o(a),!1;return n(l,t[r])===0||(o(()=>{s.continue(t[r])}),!1)}),i}notEqual(t){return this.inAnyRange([[Xn,t],[t,this.db._maxKey]],{includeLowers:!1,includeUppers:!1})}noneOf(){const t=fe.apply(ze,arguments);if(t.length===0)return new this.Collection(this);try{t.sort(this._ascending)}catch{return X(this,de)}const n=t.reduce((i,r)=>i?i.concat([[i[i.length-1][1],r]]):[[Xn,r]],null);return n.push([t[t.length-1],this.db._maxKey]),this.inAnyRange(n,{includeLowers:!1,includeUppers:!1})}inAnyRange(t,n){const i=this._cmp,r=this._ascending,s=this._descending,o=this._min,a=this._max;if(t.length===0)return We(this);if(!t.every(f=>f[0]!==void 0&&f[1]!==void 0&&r(f[0],f[1])<=0))return X(this,"First argument to inAnyRange() must be an Array of two-value Arrays [lower,upper] where upper must not be lower than lower",x.InvalidArgument);const l=!n||n.includeLowers!==!1,u=n&&n.includeUppers===!0;let c,p=r;function d(f,b){return p(f[0],b[0])}try{c=t.reduce(function(f,b){let _=0,v=f.length;for(;_<v;++_){const k=f[_];if(i(b[0],k[1])<0&&i(b[1],k[0])>0){k[0]=o(k[0],b[0]),k[1]=a(k[1],b[1]);break}}return _===v&&f.push(b),f},[]),c.sort(d)}catch{return X(this,de)}let h=0;const g=u?f=>r(f,c[h][1])>0:f=>r(f,c[h][1])>=0,y=l?f=>s(f,c[h][0])>0:f=>s(f,c[h][0])>=0;let w=g;const m=new this.Collection(this,()=>_e(c[0][0],c[c.length-1][1],!l,!u));return m._ondirectionchange=f=>{f==="next"?(w=g,p=r):(w=y,p=s),c.sort(d)},m._addAlgorithm((f,b,_)=>{for(var v=f.key;w(v);)if(++h,h===c.length)return b(_),!1;return!!function(k){return!g(k)&&!y(k)}(v)||(this._cmp(v,c[h][1])===0||this._cmp(v,c[h][0])===0||b(()=>{p===r?f.continue(c[h][0]):f.continue(c[h][1])}),!1)}),m}startsWithAnyOf(){const t=fe.apply(ze,arguments);return t.every(n=>typeof n=="string")?t.length===0?We(this):this.inAnyRange(t.map(n=>[n,n+De])):X(this,"startsWithAnyOf() only works with strings")}}function ie(e){return K(function(t){return Et(t),e(t.target.error),!1})}function Et(e){e.stopPropagation&&e.stopPropagation(),e.preventDefault&&e.preventDefault()}const kt="storagemutated",ke="x-storagemutated-1",Ae=ft(null,kt);class Mo{_lock(){return at(!U.global),++this._reculock,this._reculock!==1||U.global||(U.lockOwnerFor=this),this}_unlock(){if(at(!U.global),--this._reculock==0)for(U.global||(U.lockOwnerFor=null);this._blockedFuncs.length>0&&!this._locked();){var t=this._blockedFuncs.shift();try{nt(t[1],t[0])}catch{}}return this}_locked(){return this._reculock&&U.lockOwnerFor!==this}create(t){if(!this.mode)return this;const n=this.db.idbdb,i=this.db._state.dbOpenError;if(at(!this.idbtrans),!t&&!n)switch(i&&i.name){case"DatabaseClosedError":throw new x.DatabaseClosed(i);case"MissingAPIError":throw new x.MissingAPI(i.message,i);default:throw new x.OpenFailed(i)}if(!this.active)throw new x.TransactionInactive;return at(this._completion._state===null),(t=this.idbtrans=t||(this.db.core?this.db.core.transaction(this.storeNames,this.mode,{durability:this.chromeTransactionDurability}):n.transaction(this.storeNames,this.mode,{durability:this.chromeTransactionDurability}))).onerror=K(r=>{Et(r),this._reject(t.error)}),t.onabort=K(r=>{Et(r),this.active&&this._reject(new x.Abort(t.error)),this.active=!1,this.on("abort").fire(r)}),t.oncomplete=K(()=>{this.active=!1,this._resolve(),"mutatedParts"in t&&Ae.storagemutated.fire(t.mutatedParts)}),this}_promise(t,n,i){if(t==="readwrite"&&this.mode!=="readwrite")return V(new x.ReadOnly("Transaction is readonly"));if(!this.active)return V(new x.TransactionInactive);if(this._locked())return new L((s,o)=>{this._blockedFuncs.push([()=>{this._promise(t,n,i).then(s,o)},U])});if(i)return Ue(()=>{var s=new L((o,a)=>{this._lock();const l=n(o,a,this);l&&l.then&&l.then(o,a)});return s.finally(()=>this._unlock()),s._lib=!0,s});var r=new L((s,o)=>{var a=n(s,o,this);a&&a.then&&a.then(s,o)});return r._lib=!0,r}_root(){return this.parent?this.parent._root():this}waitFor(t){var n=this._root();const i=L.resolve(t);if(n._waitingFor)n._waitingFor=n._waitingFor.then(()=>i);else{n._waitingFor=i,n._waitingQueue=[];var r=n.idbtrans.objectStore(n.storeNames[0]);(function o(){for(++n._spinCount;n._waitingQueue.length;)n._waitingQueue.shift()();n._waitingFor&&(r.get(-1/0).onsuccess=o)})()}var s=n._waitingFor;return new L((o,a)=>{i.then(l=>n._waitingQueue.push(K(o.bind(null,l))),l=>n._waitingQueue.push(K(a.bind(null,l)))).finally(()=>{n._waitingFor===s&&(n._waitingFor=null)})})}abort(){this.active&&(this.active=!1,this.idbtrans&&this.idbtrans.abort(),this._reject(new x.Abort))}table(t){const n=this._memoizedTables||(this._memoizedTables={});if(te(n,t))return n[t];const i=this.schema[t];if(!i)throw new x.NotFound("Table "+t+" not part of transaction");const r=new this.db.Table(t,i,this);return r.core=this.db.core.table(t),n[t]=r,r}}function Zn(e,t,n,i,r,s,o){return{name:e,keyPath:t,unique:n,multi:i,auto:r,compound:s,src:(n&&!o?"&":"")+(i?"*":"")+(r?"++":"")+es(t)}}function es(e){return typeof e=="string"?e:e?"["+[].join.call(e,"+")+"]":""}function ts(e,t,n){return{name:e,primKey:t,indexes:n,mappedClass:null,idxByName:Oi(n,i=>[i.name,i])}}let Lt=e=>{try{return e.only([[]]),Lt=()=>[[]],[[]]}catch{return Lt=()=>De,De}};function er(e){return e==null?()=>{}:typeof e=="string"?function(t){return t.split(".").length===1?i=>i[t]:i=>we(i,t)}(e):t=>we(t,e)}function Zr(e){return[].slice.call(e)}let Fo=0;function mt(e){return e==null?":id":typeof e=="string"?e:`[${e.join("+")}]`}function jo(e,t,n){function i(l){if(l.type===3)return null;if(l.type===4)throw new Error("Cannot convert never type to IDBKeyRange");const{lower:u,upper:c,lowerOpen:p,upperOpen:d}=l;return u===void 0?c===void 0?null:t.upperBound(c,!!d):c===void 0?t.lowerBound(u,!!p):t.bound(u,c,!!p,!!d)}const{schema:r,hasGetAll:s}=function(l,u){const c=Zr(l.objectStoreNames);return{schema:{name:l.name,tables:c.map(p=>u.objectStore(p)).map(p=>{const{keyPath:d,autoIncrement:h}=p,g=G(d),y=d==null,w={},m={name:p.name,primaryKey:{name:null,isPrimaryKey:!0,outbound:y,compound:g,keyPath:d,autoIncrement:h,unique:!0,extractKey:er(d)},indexes:Zr(p.indexNames).map(f=>p.index(f)).map(f=>{const{name:b,unique:_,multiEntry:v,keyPath:k}=f,S={name:b,compound:G(k),keyPath:k,unique:_,multiEntry:v,extractKey:er(k)};return w[mt(k)]=S,S}),getIndexByKeyPath:f=>w[mt(f)]};return w[":id"]=m.primaryKey,d!=null&&(w[mt(d)]=m.primaryKey),m})},hasGetAll:c.length>0&&"getAll"in u.objectStore(c[0])&&!(typeof navigator<"u"&&/Safari/.test(navigator.userAgent)&&!/(Chrome\/|Edge\/)/.test(navigator.userAgent)&&[].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1]<604)}}(e,n),o=r.tables.map(l=>function(u){const c=u.name;return{name:c,schema:u,mutate:function({trans:p,type:d,keys:h,values:g,range:y}){return new Promise((w,m)=>{w=K(w);const f=p.objectStore(c),b=f.keyPath==null,_=d==="put"||d==="add";if(!_&&d!=="delete"&&d!=="deleteRange")throw new Error("Invalid operation type: "+d);const{length:v}=h||g||{length:1};if(h&&g&&h.length!==g.length)throw new Error("Given keys array must have same length as given values array.");if(v===0)return w({numFailures:0,failures:{},results:[],lastResult:void 0});let k;const S=[],A=[];let E=0;const j=W=>{++E,Et(W)};if(d==="deleteRange"){if(y.type===4)return w({numFailures:E,failures:A,results:[],lastResult:void 0});y.type===3?S.push(k=f.clear()):S.push(k=f.delete(i(y)))}else{const[W,$]=_?b?[g,h]:[g,null]:[h,null];if(_)for(let M=0;M<v;++M)S.push(k=$&&$[M]!==void 0?f[d](W[M],$[M]):f[d](W[M])),k.onerror=j;else for(let M=0;M<v;++M)S.push(k=f[d](W[M])),k.onerror=j}const P=W=>{const $=W.target.result;S.forEach((M,le)=>M.error!=null&&(A[le]=M.error)),w({numFailures:E,failures:A,results:d==="delete"?h:S.map(M=>M.result),lastResult:$})};k.onerror=W=>{j(W),P(W)},k.onsuccess=P})},getMany:({trans:p,keys:d})=>new Promise((h,g)=>{h=K(h);const y=p.objectStore(c),w=d.length,m=new Array(w);let f,b=0,_=0;const v=S=>{const A=S.target;m[A._pos]=A.result,++_===b&&h(m)},k=ie(g);for(let S=0;S<w;++S)d[S]!=null&&(f=y.get(d[S]),f._pos=S,f.onsuccess=v,f.onerror=k,++b);b===0&&h(m)}),get:({trans:p,key:d})=>new Promise((h,g)=>{h=K(h);const y=p.objectStore(c).get(d);y.onsuccess=w=>h(w.target.result),y.onerror=ie(g)}),query:function(p){return d=>new Promise((h,g)=>{h=K(h);const{trans:y,values:w,limit:m,query:f}=d,b=m===1/0?void 0:m,{index:_,range:v}=f,k=y.objectStore(c),S=_.isPrimaryKey?k:k.index(_.name),A=i(v);if(m===0)return h({result:[]});if(p){const E=w?S.getAll(A,b):S.getAllKeys(A,b);E.onsuccess=j=>h({result:j.target.result}),E.onerror=ie(g)}else{let E=0;const j=w||!("openKeyCursor"in S)?S.openCursor(A):S.openKeyCursor(A),P=[];j.onsuccess=W=>{const $=j.result;return $?(P.push(w?$.value:$.primaryKey),++E===m?h({result:P}):void $.continue()):h({result:P})},j.onerror=ie(g)}})}(s),openCursor:function({trans:p,values:d,query:h,reverse:g,unique:y}){return new Promise((w,m)=>{w=K(w);const{index:f,range:b}=h,_=p.objectStore(c),v=f.isPrimaryKey?_:_.index(f.name),k=g?y?"prevunique":"prev":y?"nextunique":"next",S=d||!("openKeyCursor"in v)?v.openCursor(i(b),k):v.openKeyCursor(i(b),k);S.onerror=ie(m),S.onsuccess=K(A=>{const E=S.result;if(!E)return void w(null);E.___id=++Fo,E.done=!1;const j=E.continue.bind(E);let P=E.continuePrimaryKey;P&&(P=P.bind(E));const W=E.advance.bind(E),$=()=>{throw new Error("Cursor not stopped")};E.trans=p,E.stop=E.continue=E.continuePrimaryKey=E.advance=()=>{throw new Error("Cursor not started")},E.fail=K(m),E.next=function(){let M=1;return this.start(()=>M--?this.continue():this.stop()).then(()=>this)},E.start=M=>{const le=new Promise((D,ue)=>{D=K(D),S.onerror=ie(ue),E.fail=ue,E.stop=it=>{E.stop=E.continue=E.continuePrimaryKey=E.advance=$,D(it)}}),ce=()=>{if(S.result)try{M()}catch(D){E.fail(D)}else E.done=!0,E.start=()=>{throw new Error("Cursor behind last entry")},E.stop()};return S.onsuccess=K(D=>{S.onsuccess=ce,ce()}),E.continue=j,E.continuePrimaryKey=P,E.advance=W,ce(),le},w(E)},m)})},count({query:p,trans:d}){const{index:h,range:g}=p;return new Promise((y,w)=>{const m=d.objectStore(c),f=h.isPrimaryKey?m:m.index(h.name),b=i(g),_=b?f.count(b):f.count();_.onsuccess=K(v=>y(v.target.result)),_.onerror=ie(w)})}}}(l)),a={};return o.forEach(l=>a[l.name]=l),{stack:"dbcore",transaction:e.transaction.bind(e),table(l){if(!a[l])throw new Error(`Table '${l}' not found`);return a[l]},MIN_KEY:-1/0,MAX_KEY:Lt(t),schema:r}}function tr({_novip:e},t){const n=t.db,i=function(r,s,{IDBKeyRange:o,indexedDB:a},l){return{dbcore:function(c,p){return p.reduce((d,{create:h})=>({...d,...h(d)}),c)}(jo(s,o,l),r.dbcore)}}(e._middlewares,n,e._deps,t);e.core=i.dbcore,e.tables.forEach(r=>{const s=r.name;e.core.schema.tables.some(o=>o.name===s)&&(r.core=e.core.table(s),e[s]instanceof e.Table&&(e[s].core=r.core))})}function an({_novip:e},t,n,i){n.forEach(r=>{const s=i[r];t.forEach(o=>{const a=_r(o,r);(!a||"value"in a&&a.value===void 0)&&(o===e.Transaction.prototype||o instanceof e.Transaction?ge(o,r,{get(){return this.table(r)},set(l){Ai(this,r,{value:l,writable:!0,configurable:!0,enumerable:!0})}}):o[r]=new e.Table(r,s))})})}function nr({_novip:e},t){t.forEach(n=>{for(let i in n)n[i]instanceof e.Table&&delete n[i]})}function Ko(e,t){return e._cfg.version-t._cfg.version}function No(e,t,n,i){const r=e._dbSchema,s=e._createTransaction("readwrite",e._storeNames,r);s.create(n),s._completion.catch(i);const o=s._reject.bind(s),a=U.transless||U;Ue(()=>{U.trans=s,U.transless=a,t===0?(q(r).forEach(l=>{Un(n,l,r[l].primKey,r[l].indexes)}),tr(e,n),L.follow(()=>e.on.populate.fire(s)).catch(o)):function({_novip:l},u,c,p){const d=[],h=l._versions;let g=l._dbSchema=ir(l,l.idbdb,p),y=!1;const w=h.filter(f=>f._cfg.version>=u);function m(){return d.length?L.resolve(d.shift()(c.idbtrans)).then(m):L.resolve()}return w.forEach(f=>{d.push(()=>{const b=g,_=f._cfg.dbschema;sr(l,b,p),sr(l,_,p),g=l._dbSchema=_;const v=ns(b,_);v.add.forEach(S=>{Un(p,S[0],S[1].primKey,S[1].indexes)}),v.change.forEach(S=>{if(S.recreate)throw new x.Upgrade("Not yet support for changing primary key");{const A=p.objectStore(S.name);S.add.forEach(E=>rr(A,E)),S.change.forEach(E=>{A.deleteIndex(E.name),rr(A,E)}),S.del.forEach(E=>A.deleteIndex(E))}});const k=f._cfg.contentUpgrade;if(k&&f._cfg.version>u){tr(l,p),c._memoizedTables={},y=!0;let S=Di(_);v.del.forEach(P=>{S[P]=b[P]}),nr(l,[l.Transaction.prototype]),an(l,[l.Transaction.prototype],q(S),S),c.schema=S;const A=Sr(k);let E;A&&tt();const j=L.follow(()=>{if(E=k(c),E&&A){var P=ve.bind(null,null);E.then(P,P)}});return E&&typeof E.then=="function"?L.resolve(E):j.then(()=>E)}}),d.push(b=>{(!y||!Ro)&&function(_,v){[].slice.call(v.db.objectStoreNames).forEach(k=>_[k]==null&&v.db.deleteObjectStore(k))}(f._cfg.dbschema,b),nr(l,[l.Transaction.prototype]),an(l,[l.Transaction.prototype],l._storeNames,l._dbSchema),c.schema=l._dbSchema})}),m().then(()=>{var f,b;b=p,q(f=g).forEach(_=>{b.db.objectStoreNames.contains(_)||Un(b,_,f[_].primKey,f[_].indexes)})})}(e,t,s,n).catch(o)})}function ns(e,t){const n={del:[],add:[],change:[]};let i;for(i in e)t[i]||n.del.push(i);for(i in t){const r=e[i],s=t[i];if(r){const o={name:i,def:s,recreate:!1,del:[],add:[],change:[]};if(""+(r.primKey.keyPath||"")!=""+(s.primKey.keyPath||"")||r.primKey.auto!==s.primKey.auto&&!fn)o.recreate=!0,n.change.push(o);else{const a=r.idxByName,l=s.idxByName;let u;for(u in a)l[u]||o.del.push(u);for(u in l){const c=a[u],p=l[u];c?c.src!==p.src&&o.change.push(p):o.add.push(p)}(o.del.length>0||o.add.length>0||o.change.length>0)&&n.change.push(o)}}else n.add.push([i,s])}return n}function Un(e,t,n,i){const r=e.db.createObjectStore(t,n.keyPath?{keyPath:n.keyPath,autoIncrement:n.auto}:{autoIncrement:n.auto});return i.forEach(s=>rr(r,s)),r}function rr(e,t){e.createIndex(t.name,t.keyPath,{unique:t.unique,multiEntry:t.multi})}function ir(e,t,n){const i={};return en(t.objectStoreNames,0).forEach(r=>{const s=n.objectStore(r);let o=s.keyPath;const a=Zn(es(o),o||"",!1,!1,!!s.autoIncrement,o&&typeof o!="string",!0),l=[];for(let c=0;c<s.indexNames.length;++c){const p=s.index(s.indexNames[c]);o=p.keyPath;var u=Zn(p.name,o,!!p.unique,!!p.multiEntry,!1,o&&typeof o!="string",!1);l.push(u)}i[r]=ts(r,a,l)}),i}function sr({_novip:e},t,n){const i=n.db.objectStoreNames;for(let r=0;r<i.length;++r){const s=i[r],o=n.objectStore(s);e._hasGetAll="getAll"in o;for(let a=0;a<o.indexNames.length;++a){const l=o.indexNames[a],u=o.index(l).keyPath,c=typeof u=="string"?u:"["+en(u).join("+")+"]";if(t[s]){const p=t[s].idxByName[c];p&&(p.name=l,delete t[s].idxByName[c],t[s].idxByName[l]=p)}}}typeof navigator<"u"&&/Safari/.test(navigator.userAgent)&&!/(Chrome\/|Edge\/)/.test(navigator.userAgent)&&F.WorkerGlobalScope&&F instanceof F.WorkerGlobalScope&&[].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1]<604&&(e._hasGetAll=!1)}class $o{_parseStoresSpec(t,n){q(t).forEach(i=>{if(t[i]!==null){var r=t[i].split(",").map((o,a)=>{const l=(o=o.trim()).replace(/([&*]|\+\+)/g,""),u=/^\[/.test(l)?l.match(/^\[(.*)\]$/)[1].split("+"):l;return Zn(l,u||null,/\&/.test(o),/\*/.test(o),/\+\+/.test(o),G(u),a===0)}),s=r.shift();if(s.multi)throw new x.Schema("Primary key cannot be multi-valued");r.forEach(o=>{if(o.auto)throw new x.Schema("Only primary key can be marked as autoIncrement (++)");if(!o.keyPath)throw new x.Schema("Index must have a name and cannot be an empty string")}),n[i]=ts(i,s,r)}})}stores(t){const n=this.db;this._cfg.storesSource=this._cfg.storesSource?J(this._cfg.storesSource,t):t;const i=n._versions,r={};let s={};return i.forEach(o=>{J(r,o._cfg.storesSource),s=o._cfg.dbschema={},o._parseStoresSpec(r,s)}),n._dbSchema=s,nr(n,[n._allTables,n,n.Transaction.prototype]),an(n,[n._allTables,n,n.Transaction.prototype,this._cfg.tables],q(s),s),n._storeNames=q(s),this}upgrade(t){return this._cfg.contentUpgrade=Lr(this._cfg.contentUpgrade||B,t),this}}function Ar(e,t){let n=e._dbNamesDB;return n||(n=e._dbNamesDB=new Me(mn,{addons:[],indexedDB:e,IDBKeyRange:t}),n.version(1).stores({dbnames:"name"})),n.table("dbnames")}function Rr(e){return e&&typeof e.databases=="function"}function or(e){return Ue(function(){return U.letThrough=!0,e()})}function qo(){var e;return!navigator.userAgentData&&/Safari\//.test(navigator.userAgent)&&!/Chrom(e|ium)\//.test(navigator.userAgent)&&indexedDB.databases?new Promise(function(t){var n=function(){return indexedDB.databases().finally(t)};e=setInterval(n,100),n()}).finally(function(){return clearInterval(e)}):Promise.resolve()}function Vo(e){const t=e._state,{indexedDB:n}=e._deps;if(t.isBeingOpened||e.idbdb)return t.dbReadyPromise.then(()=>t.dbOpenError?V(t.dbOpenError):e);ae&&(t.openCanceller._stackHolder=qe()),t.isBeingOpened=!0,t.dbOpenError=null,t.openComplete=!1;const i=t.openCanceller;function r(){if(t.openCanceller!==i)throw new x.DatabaseClosed("db.open() was cancelled")}let s=t.dbReadyResolve,o=null,a=!1;const l=()=>new L((u,c)=>{if(r(),!n)throw new x.MissingAPI;const p=e.name,d=t.autoSchema?n.open(p):n.open(p,Math.round(10*e.verno));if(!d)throw new x.MissingAPI;d.onerror=ie(c),d.onblocked=K(e._fireOnBlocked),d.onupgradeneeded=K(h=>{if(o=d.transaction,t.autoSchema&&!e._options.allowEmptyDB){d.onerror=Et,o.abort(),d.result.close();const y=n.deleteDatabase(p);y.onsuccess=y.onerror=K(()=>{c(new x.NoSuchDatabase(`Database ${p} doesnt exist`))})}else{o.onerror=ie(c);var g=h.oldVersion>Math.pow(2,62)?0:h.oldVersion;a=g<1,e._novip.idbdb=d.result,No(e,g/10,o,c)}},c),d.onsuccess=K(()=>{o=null;const h=e._novip.idbdb=d.result,g=en(h.objectStoreNames);if(g.length>0)try{const w=h.transaction((y=g).length===1?y[0]:y,"readonly");t.autoSchema?function({_novip:m},f,b){m.verno=f.version/10;const _=m._dbSchema=ir(0,f,b);m._storeNames=en(f.objectStoreNames,0),an(m,[m._allTables],q(_),_)}(e,h,w):(sr(e,e._dbSchema,w),function(m,f){const b=ns(ir(0,m.idbdb,f),m._dbSchema);return!(b.add.length||b.change.some(_=>_.add.length||_.change.length))}(e,w)||console.warn("Dexie SchemaDiff: Schema was extended without increasing the number passed to db.version(). Some queries may fail.")),tr(e,w)}catch{}var y;ht.push(e),h.onversionchange=K(w=>{t.vcFired=!0,e.on("versionchange").fire(w)}),h.onclose=K(w=>{e.on("close").fire(w)}),a&&function({indexedDB:w,IDBKeyRange:m},f){!Rr(w)&&f!==mn&&Ar(w,m).put({name:f}).catch(B)}(e._deps,p),u()},c)}).catch(u=>u&&u.name==="UnknownError"&&t.PR1398_maxLoop>0?(t.PR1398_maxLoop--,console.warn("Dexie: Workaround for Chrome UnknownError on open()"),l()):L.reject(u));return L.race([i,(typeof navigator>"u"?L.resolve():qo()).then(l)]).then(()=>(r(),t.onReadyBeingFired=[],L.resolve(or(()=>e.on.ready.fire(e.vip))).then(function u(){if(t.onReadyBeingFired.length>0){let c=t.onReadyBeingFired.reduce(Lr,B);return t.onReadyBeingFired=[],L.resolve(or(()=>c(e.vip))).then(u)}}))).finally(()=>{t.onReadyBeingFired=null,t.isBeingOpened=!1}).then(()=>e).catch(u=>{t.dbOpenError=u;try{o&&o.abort()}catch{}return i===t.openCanceller&&e._close(),V(u)}).finally(()=>{t.openComplete=!0,s()})}function ar(e){var t=s=>e.next(s),n=r(t),i=r(s=>e.throw(s));function r(s){return o=>{var a=s(o),l=a.value;return a.done?l:l&&typeof l.then=="function"?l.then(n,i):G(l)?Promise.all(l).then(n,i):n(l)}}return r(t)()}function Wo(e,t,n){var i=arguments.length;if(i<2)throw new x.InvalidArgument("Too few arguments");for(var r=new Array(i-1);--i;)r[i-1]=arguments[i];return n=r.pop(),[e,Pi(r),n]}function rs(e,t,n,i,r){return L.resolve().then(()=>{const s=U.transless||U,o=e._createTransaction(t,n,e._dbSchema,i),a={trans:o,transless:s};if(i)o.idbtrans=i.idbtrans;else try{o.create(),e._state.PR1398_maxLoop=3}catch(p){return p.name===kr.InvalidState&&e.isOpen()&&--e._state.PR1398_maxLoop>0?(console.warn("Dexie: Need to reopen db"),e._close(),e.open().then(()=>rs(e,t,n,null,r))):V(p)}const l=Sr(r);let u;l&&tt();const c=L.follow(()=>{if(u=r.call(o,o),u)if(l){var p=ve.bind(null,null);u.then(p,p)}else typeof u.next=="function"&&typeof u.throw=="function"&&(u=ar(u))},a);return(u&&typeof u.then=="function"?L.resolve(u).then(p=>o.active?p:V(new x.PrematureCommit("Transaction committed too early. See http://bit.ly/2kdckMn"))):c.then(()=>u)).then(p=>(i&&o._resolve(),o._completion.then(()=>p))).catch(p=>(o._reject(p),V(p)))})}function Kt(e,t,n){const i=G(e)?e.slice():[e];for(let r=0;r<n;++r)i.push(t);return i}const zo={stack:"dbcore",name:"VirtualIndexMiddleware",level:1,create:function(e){return{...e,table(t){const n=e.table(t),{schema:i}=n,r={},s=[];function o(c,p,d){const h=mt(c),g=r[h]=r[h]||[],y=c==null?0:typeof c=="string"?1:c.length,w=p>0,m={...d,isVirtual:w,keyTail:p,keyLength:y,extractKey:er(c),unique:!w&&d.unique};return g.push(m),m.isPrimaryKey||s.push(m),y>1&&o(y===2?c[0]:c.slice(0,y-1),p+1,d),g.sort((f,b)=>f.keyTail-b.keyTail),m}const a=o(i.primaryKey.keyPath,0,i.primaryKey);r[":id"]=[a];for(const c of i.indexes)o(c.keyPath,0,c);function l(c){const p=c.query.index;return p.isVirtual?{...c,query:{index:p,range:(d=c.query.range,h=p.keyTail,{type:d.type===1?2:d.type,lower:Kt(d.lower,d.lowerOpen?e.MAX_KEY:e.MIN_KEY,h),lowerOpen:!0,upper:Kt(d.upper,d.upperOpen?e.MIN_KEY:e.MAX_KEY,h),upperOpen:!0})}}:c;var d,h}return{...n,schema:{...i,primaryKey:a,indexes:s,getIndexByKeyPath:function(c){const p=r[mt(c)];return p&&p[0]}},count:c=>n.count(l(c)),query:c=>n.query(l(c)),openCursor(c){const{keyTail:p,isVirtual:d,keyLength:h}=c.query.index;return d?n.openCursor(l(c)).then(g=>g&&function(y){return Object.create(y,{continue:{value:function(m){m!=null?y.continue(Kt(m,c.reverse?e.MAX_KEY:e.MIN_KEY,p)):c.unique?y.continue(y.key.slice(0,h).concat(c.reverse?e.MIN_KEY:e.MAX_KEY,p)):y.continue()}},continuePrimaryKey:{value(m,f){y.continuePrimaryKey(Kt(m,e.MAX_KEY,p),f)}},primaryKey:{get:()=>y.primaryKey},key:{get(){const m=y.key;return h===1?m[0]:m.slice(0,h)}},value:{get:()=>y.value}})}(g)):n.openCursor(c)}}}}}};function Cr(e,t,n,i){return n=n||{},i=i||"",q(e).forEach(r=>{if(te(t,r)){var s=e[r],o=t[r];if(typeof s=="object"&&typeof o=="object"&&s&&o){const a=Kn(s);a!==Kn(o)?n[i+r]=t[r]:a==="Object"?Cr(s,o,n,i+r+"."):s!==o&&(n[i+r]=t[r])}else s!==o&&(n[i+r]=t[r])}else n[i+r]=void 0}),q(t).forEach(r=>{te(e,r)||(n[i+r]=t[r])}),n}const Ho={stack:"dbcore",name:"HooksMiddleware",level:2,create:e=>({...e,table(t){const n=e.table(t),{primaryKey:i}=n.schema;return{...n,mutate(s){const o=U.trans,{deleting:a,creating:l,updating:u}=o.table(t).hook;switch(s.type){case"add":if(l.fire===B)break;return o._promise("readwrite",()=>c(s),!0);case"put":if(l.fire===B&&u.fire===B)break;return o._promise("readwrite",()=>c(s),!0);case"delete":if(a.fire===B)break;return o._promise("readwrite",()=>c(s),!0);case"deleteRange":if(a.fire===B)break;return o._promise("readwrite",()=>function(d){return p(d.trans,d.range,1e4)}(s),!0)}return n.mutate(s);function c(d){const h=U.trans,g=d.keys||function(y,w){return w.type==="delete"?w.keys:w.keys||w.values.map(y.extractKey)}(i,d);if(!g)throw new Error("Keys missing");return(d=d.type==="add"||d.type==="put"?{...d,keys:g}:{...d}).type!=="delete"&&(d.values=[...d.values]),d.keys&&(d.keys=[...d.keys]),function(y,w,m){return w.type==="add"?Promise.resolve([]):y.getMany({trans:w.trans,keys:m,cache:"immutable"})}(n,d,g).then(y=>{const w=g.map((m,f)=>{const b=y[f],_={onerror:null,onsuccess:null};if(d.type==="delete")a.fire.call(_,m,b,h);else if(d.type==="add"||b===void 0){const v=l.fire.call(_,m,d.values[f],h);m==null&&v!=null&&(m=v,d.keys[f]=m,i.outbound||re(d.values[f],i.keyPath,m))}else{const v=Cr(b,d.values[f]),k=u.fire.call(_,v,m,b,h);if(k){const S=d.values[f];Object.keys(k).forEach(A=>{te(S,A)?S[A]=k[A]:re(S,A,k[A])})}}return _});return n.mutate(d).then(({failures:m,results:f,numFailures:b,lastResult:_})=>{for(let v=0;v<g.length;++v){const k=f?f[v]:g[v],S=w[v];k==null?S.onerror&&S.onerror(m[v]):S.onsuccess&&S.onsuccess(d.type==="put"&&y[v]?d.values[v]:k)}return{failures:m,results:f,numFailures:b,lastResult:_}}).catch(m=>(w.forEach(f=>f.onerror&&f.onerror(m)),Promise.reject(m)))})}function p(d,h,g){return n.query({trans:d,values:!1,query:{index:i,range:h},limit:g}).then(({result:y})=>c({type:"delete",keys:y,trans:d}).then(w=>w.numFailures>0?Promise.reject(w.failures[0]):y.length<g?{failures:[],numFailures:0,lastResult:void 0}:p(d,{...h,lower:y[y.length-1],lowerOpen:!0},g)))}}}}})};function is(e,t,n){try{if(!t||t.keys.length<e.length)return null;const i=[];for(let r=0,s=0;r<t.keys.length&&s<e.length;++r)Y(t.keys[r],e[s])===0&&(i.push(n?xt(t.values[r]):t.values[r]),++s);return i.length===e.length?i:null}catch{return null}}const Go={stack:"dbcore",level:-1,create:e=>({table:t=>{const n=e.table(t);return{...n,getMany:i=>{if(!i.cache)return n.getMany(i);const r=is(i.keys,i.trans._cache,i.cache==="clone");return r?L.resolve(r):n.getMany(i).then(s=>(i.trans._cache={keys:i.keys,values:i.cache==="clone"?xt(s):s},s))},mutate:i=>(i.type!=="add"&&(i.trans._cache=null),n.mutate(i))}}})};function Or(e){return!("from"in e)}const pe=function(e,t){if(!this){const n=new pe;return e&&"d"in e&&J(n,e),n}J(this,arguments.length?{d:1,from:e,to:arguments.length>1?t:e}:{d:0})};function It(e,t,n){const i=Y(t,n);if(isNaN(i))return;if(i>0)throw RangeError();if(Or(e))return J(e,{from:t,to:n,d:1});const r=e.l,s=e.r;if(Y(n,e.from)<0)return r?It(r,t,n):e.l={from:t,to:n,d:1,l:null,r:null},ei(e);if(Y(t,e.to)>0)return s?It(s,t,n):e.r={from:t,to:n,d:1,l:null,r:null},ei(e);Y(t,e.from)<0&&(e.from=t,e.l=null,e.d=s?s.d+1:1),Y(n,e.to)>0&&(e.to=n,e.r=null,e.d=e.l?e.l.d+1:1);const o=!e.r;r&&!e.l&&ln(e,r),s&&o&&ln(e,s)}function ln(e,t){Or(t)||function n(i,{from:r,to:s,l:o,r:a}){It(i,r,s),o&&n(i,o),a&&n(i,a)}(e,t)}function Yo(e,t){const n=lr(t);let i=n.next();if(i.done)return!1;let r=i.value;const s=lr(e);let o=s.next(r.from),a=o.value;for(;!i.done&&!o.done;){if(Y(a.from,r.to)<=0&&Y(a.to,r.from)>=0)return!0;Y(r.from,a.from)<0?r=(i=n.next(a.from)).value:a=(o=s.next(r.from)).value}return!1}function lr(e){let t=Or(e)?null:{s:0,n:e};return{next(n){const i=arguments.length>0;for(;t;)switch(t.s){case 0:if(t.s=1,i)for(;t.n.l&&Y(n,t.n.from)<0;)t={up:t,n:t.n.l,s:1};else for(;t.n.l;)t={up:t,n:t.n.l,s:1};case 1:if(t.s=2,!i||Y(n,t.n.to)<=0)return{value:t.n,done:!1};case 2:if(t.n.r){t.s=3,t={up:t,n:t.n.r,s:0};continue}case 3:t=t.up}return{done:!0}}}}function ei(e){var t,n;const i=(((t=e.r)===null||t===void 0?void 0:t.d)||0)-(((n=e.l)===null||n===void 0?void 0:n.d)||0),r=i>1?"r":i<-1?"l":"";if(r){const s=r==="r"?"l":"r",o={...e},a=e[r];e.from=a.from,e.to=a.to,e[r]=a[r],o[r]=a[s],e[s]=o,o.d=ti(o)}e.d=ti(e)}function ti({r:e,l:t}){return(e?t?Math.max(e.d,t.d):e.d:t?t.d:0)+1}Xe(pe.prototype,{add(e){return ln(this,e),this},addKey(e){return It(this,e,e),this},addKeys(e){return e.forEach(t=>It(this,t,t)),this},[Nn](){return lr(this)}});const Jo={stack:"dbcore",level:0,create:e=>{const t=e.schema.name,n=new pe(e.MIN_KEY,e.MAX_KEY);return{...e,table:i=>{const r=e.table(i),{schema:s}=r,{primaryKey:o}=s,{extractKey:a,outbound:l}=o,u={...r,mutate:d=>{const h=d.trans,g=h.mutatedParts||(h.mutatedParts={}),y=k=>{const S=`idb://${t}/${i}/${k}`;return g[S]||(g[S]=new pe)},w=y(""),m=y(":dels"),{type:f}=d;let[b,_]=d.type==="deleteRange"?[d.range]:d.type==="delete"?[d.keys]:d.values.length<50?[[],d.values]:[];const v=d.trans._cache;return r.mutate(d).then(k=>{if(G(b)){f!=="delete"&&(b=k.results),w.addKeys(b);const S=is(b,v);S||f==="add"||m.addKeys(b),(S||_)&&function(A,E,j,P){function W($){const M=A($.name||"");function le(D){return D!=null?$.extractKey(D):null}const ce=D=>$.multiEntry&&G(D)?D.forEach(ue=>M.addKey(ue)):M.addKey(D);(j||P).forEach((D,ue)=>{const it=j&&le(j[ue]),bn=P&&le(P[ue]);Y(it,bn)!==0&&(it!=null&&ce(it),bn!=null&&ce(bn))})}E.indexes.forEach(W)}(y,s,S,_)}else if(b){const S={from:b.lower,to:b.upper};m.add(S),w.add(S)}else w.add(n),m.add(n),s.indexes.forEach(S=>y(S.name).add(n));return k})}},c=({query:{index:d,range:h}})=>{var g,y;return[d,new pe((g=h.lower)!==null&&g!==void 0?g:e.MIN_KEY,(y=h.upper)!==null&&y!==void 0?y:e.MAX_KEY)]},p={get:d=>[o,new pe(d.key)],getMany:d=>[o,new pe().addKeys(d.keys)],count:c,query:c,openCursor:c};return q(p).forEach(d=>{u[d]=function(h){const{subscr:g}=U;if(g){const y=_=>{const v=`idb://${t}/${i}/${_}`;return g[v]||(g[v]=new pe)},w=y(""),m=y(":dels"),[f,b]=p[d](h);if(y(f.name||"").add(b),!f.isPrimaryKey){if(d!=="count"){const _=d==="query"&&l&&h.values&&r.query({...h,values:!1});return r[d].apply(this,arguments).then(v=>{if(d==="query"){if(l&&h.values)return _.then(({result:S})=>(w.addKeys(S),v));const k=h.values?v.result.map(a):v.result;h.values?w.addKeys(k):m.addKeys(k)}else if(d==="openCursor"){const k=v,S=h.values;return k&&Object.create(k,{key:{get:()=>(m.addKey(k.primaryKey),k.key)},primaryKey:{get(){const A=k.primaryKey;return m.addKey(A),A}},value:{get:()=>(S&&w.addKey(k.primaryKey),k.value)}})}return v})}m.add(n)}}return r[d].apply(this,arguments)}}),u}}}};class Me{constructor(t,n){this._middlewares={},this.verno=0;const i=Me.dependencies;this._options=n={addons:Me.addons,autoOpen:!0,indexedDB:i.indexedDB,IDBKeyRange:i.IDBKeyRange,...n},this._deps={indexedDB:n.indexedDB,IDBKeyRange:n.IDBKeyRange};const{addons:r}=n;this._dbSchema={},this._versions=[],this._storeNames=[],this._allTables={},this.idbdb=null,this._novip=this;const s={dbOpenError:null,isBeingOpened:!1,onReadyBeingFired:null,openComplete:!1,dbReadyResolve:B,dbReadyPromise:null,cancelOpen:B,openCanceller:null,autoSchema:!0,PR1398_maxLoop:3};var o;s.dbReadyPromise=new L(a=>{s.dbReadyResolve=a}),s.openCanceller=new L((a,l)=>{s.cancelOpen=l}),this._state=s,this.name=t,this.on=ft(this,"populate","blocked","versionchange","close",{ready:[Lr,B]}),this.on.ready.subscribe=Ri(this.on.ready.subscribe,a=>(l,u)=>{Me.vip(()=>{const c=this._state;if(c.openComplete)c.dbOpenError||L.resolve().then(l),u&&a(l);else if(c.onReadyBeingFired)c.onReadyBeingFired.push(l),u&&a(l);else{a(l);const p=this;u||a(function d(){p.on.ready.unsubscribe(l),p.on.ready.unsubscribe(d)})}})}),this.Collection=(o=this,st(Do.prototype,function(a,l){this.db=o;let u=Qi,c=null;if(l)try{u=l()}catch(g){c=g}const p=a._ctx,d=p.table,h=d.hook.reading.fire;this._ctx={table:d,index:p.index,isPrimKey:!p.index||d.schema.primKey.keyPath&&p.index===d.schema.primKey.name,range:u,keysOnly:!1,dir:"next",unique:"",algorithm:null,filter:null,replayFilter:null,justLimit:!0,isMatch:null,offset:0,limit:1/0,error:c,or:p.or,valueMapper:h!==_t?h:null}})),this.Table=function(a){return st(Oo.prototype,function(l,u,c){this.db=a,this._tx=c,this.name=l,this.schema=u,this.hook=a._allTables[l]?a._allTables[l].hook:ft(null,{creating:[bo,B],reading:[vo,_t],updating:[So,B],deleting:[_o,B]})})}(this),this.Transaction=function(a){return st(Mo.prototype,function(l,u,c,p,d){this.db=a,this.mode=l,this.storeNames=u,this.schema=c,this.chromeTransactionDurability=p,this.idbtrans=null,this.on=ft(this,"complete","error","abort"),this.parent=d||null,this.active=!0,this._reculock=0,this._blockedFuncs=[],this._resolve=null,this._reject=null,this._waitingFor=null,this._waitingQueue=null,this._spinCount=0,this._completion=new L((h,g)=>{this._resolve=h,this._reject=g}),this._completion.then(()=>{this.active=!1,this.on.complete.fire()},h=>{var g=this.active;return this.active=!1,this.on.error.fire(h),this.parent?this.parent._reject(h):g&&this.idbtrans&&this.idbtrans.abort(),V(h)})})}(this),this.Version=function(a){return st($o.prototype,function(l){this.db=a,this._cfg={version:l,storesSource:null,dbschema:{},tables:{},contentUpgrade:null}})}(this),this.WhereClause=function(a){return st(Zi.prototype,function(l,u,c){this.db=a,this._ctx={table:l,index:u===":id"?null:u,or:c};const p=a._deps.indexedDB;if(!p)throw new x.MissingAPI;this._cmp=this._ascending=p.cmp.bind(p),this._descending=(d,h)=>p.cmp(h,d),this._max=(d,h)=>p.cmp(d,h)>0?d:h,this._min=(d,h)=>p.cmp(d,h)<0?d:h,this._IDBKeyRange=a._deps.IDBKeyRange})}(this),this.on("versionchange",a=>{a.newVersion>0?console.warn(`Another connection wants to upgrade database '${this.name}'. Closing db now to resume the upgrade.`):console.warn(`Another connection wants to delete database '${this.name}'. Closing db now to resume the delete request.`),this.close()}),this.on("blocked",a=>{!a.newVersion||a.newVersion<a.oldVersion?console.warn(`Dexie.delete('${this.name}') was blocked`):console.warn(`Upgrade '${this.name}' blocked by other connection holding version ${a.oldVersion/10}`)}),this._maxKey=Lt(n.IDBKeyRange),this._createTransaction=(a,l,u,c)=>new this.Transaction(a,l,u,this._options.chromeTransactionDurability,c),this._fireOnBlocked=a=>{this.on("blocked").fire(a),ht.filter(l=>l.name===this.name&&l!==this&&!l._state.vcFired).map(l=>l.on("versionchange").fire(a))},this.use(zo),this.use(Ho),this.use(Jo),this.use(Go),this.vip=Object.create(this,{_vip:{value:!0}}),r.forEach(a=>a(this))}version(t){if(isNaN(t)||t<.1)throw new x.Type("Given version is not a positive number");if(t=Math.round(10*t)/10,this.idbdb||this._state.isBeingOpened)throw new x.Schema("Cannot add version when database is open");this.verno=Math.max(this.verno,t);const n=this._versions;var i=n.filter(r=>r._cfg.version===t)[0];return i||(i=new this.Version(t),n.push(i),n.sort(Ko),i.stores({}),this._state.autoSchema=!1,i)}_whenReady(t){return this.idbdb&&(this._state.openComplete||U.letThrough||this._vip)?t():new L((n,i)=>{if(this._state.openComplete)return i(new x.DatabaseClosed(this._state.dbOpenError));if(!this._state.isBeingOpened){if(!this._options.autoOpen)return void i(new x.DatabaseClosed);this.open().catch(B)}this._state.dbReadyPromise.then(n,i)}).then(t)}use({stack:t,create:n,level:i,name:r}){r&&this.unuse({stack:t,name:r});const s=this._middlewares[t]||(this._middlewares[t]=[]);return s.push({stack:t,create:n,level:i??10,name:r}),s.sort((o,a)=>o.level-a.level),this}unuse({stack:t,name:n,create:i}){return t&&this._middlewares[t]&&(this._middlewares[t]=this._middlewares[t].filter(r=>i?r.create!==i:!!n&&r.name!==n)),this}open(){return Vo(this)}_close(){const t=this._state,n=ht.indexOf(this);if(n>=0&&ht.splice(n,1),this.idbdb){try{this.idbdb.close()}catch{}this._novip.idbdb=null}t.dbReadyPromise=new L(i=>{t.dbReadyResolve=i}),t.openCanceller=new L((i,r)=>{t.cancelOpen=r})}close(){this._close();const t=this._state;this._options.autoOpen=!1,t.dbOpenError=new x.DatabaseClosed,t.isBeingOpened&&t.cancelOpen(t.dbOpenError)}delete(){const t=arguments.length>0,n=this._state;return new L((i,r)=>{const s=()=>{this.close();var o=this._deps.indexedDB.deleteDatabase(this.name);o.onsuccess=K(()=>{(function({indexedDB:a,IDBKeyRange:l},u){!Rr(a)&&u!==mn&&Ar(a,l).delete(u).catch(B)})(this._deps,this.name),i()}),o.onerror=ie(r),o.onblocked=this._fireOnBlocked};if(t)throw new x.InvalidArgument("Arguments not allowed in db.delete()");n.isBeingOpened?n.dbReadyPromise.then(s):s()})}backendDB(){return this.idbdb}isOpen(){return this.idbdb!==null}hasBeenClosed(){const t=this._state.dbOpenError;return t&&t.name==="DatabaseClosed"}hasFailed(){return this._state.dbOpenError!==null}dynamicallyOpened(){return this._state.autoSchema}get tables(){return q(this._allTables).map(t=>this._allTables[t])}transaction(){const t=Wo.apply(this,arguments);return this._transaction.apply(this,t)}_transaction(t,n,i){let r=U.trans;r&&r.db===this&&t.indexOf("!")===-1||(r=null);const s=t.indexOf("?")!==-1;let o,a;t=t.replace("!","").replace("?","");try{if(a=n.map(u=>{var c=u instanceof this.Table?u.name:u;if(typeof c!="string")throw new TypeError("Invalid table argument to Dexie.transaction(). Only Table or String are allowed");return c}),t=="r"||t===Sn)o=Sn;else{if(t!="rw"&&t!=En)throw new x.InvalidArgument("Invalid transaction mode: "+t);o=En}if(r){if(r.mode===Sn&&o===En){if(!s)throw new x.SubTransaction("Cannot enter a sub-transaction with READWRITE mode when parent transaction is READONLY");r=null}r&&a.forEach(u=>{if(r&&r.storeNames.indexOf(u)===-1){if(!s)throw new x.SubTransaction("Table "+u+" not included in parent transaction.");r=null}}),s&&r&&!r.active&&(r=null)}}catch(u){return r?r._promise(null,(c,p)=>{p(u)}):V(u)}const l=rs.bind(null,this,o,a,r,i);return r?r._promise(o,l,"lock"):U.trans?nt(U.transless,()=>this._whenReady(l)):this._whenReady(l)}table(t){if(!te(this._allTables,t))throw new x.InvalidTable(`Table ${t} does not exist`);return this._allTables[t]}}const Qo=typeof Symbol<"u"&&"observable"in Symbol?Symbol.observable:"@@observable";class Xo{constructor(t){this._subscribe=t}subscribe(t,n,i){return this._subscribe(t&&typeof t!="function"?t:{next:t,error:n,complete:i})}[Qo](){return this}}function ss(e,t){return q(t).forEach(n=>{ln(e[n]||(e[n]=new pe),t[n])}),e}function Zo(e){let t,n=!1;const i=new Xo(r=>{const s=Sr(e);let o=!1,a={},l={};const u={get closed(){return o},unsubscribe:()=>{o=!0,Ae.storagemutated.unsubscribe(h)}};r.start&&r.start(u);let c=!1,p=!1;function d(){return q(l).some(y=>a[y]&&Yo(a[y],l[y]))}const h=y=>{ss(a,y),d()&&g()},g=()=>{if(c||o)return;a={};const y={},w=function(m){s&&tt();const f=()=>Ue(e,{subscr:m,trans:null}),b=U.trans?nt(U.transless,f):f();return s&&b.then(ve,ve),b}(y);p||(Ae(kt,h),p=!0),c=!0,Promise.resolve(w).then(m=>{n=!0,t=m,c=!1,o||(d()?g():(a={},l=y,r.next&&r.next(m)))},m=>{c=!1,n=!1,r.error&&r.error(m),u.unsubscribe()})};return g(),u});return i.hasValue=()=>n,i.getValue=()=>t,i}let cr;try{cr={indexedDB:F.indexedDB||F.mozIndexedDB||F.webkitIndexedDB||F.msIndexedDB,IDBKeyRange:F.IDBKeyRange||F.webkitIDBKeyRange}}catch{cr={indexedDB:null,IDBKeyRange:null}}const Re=Me;function Gt(e){let t=me;try{me=!0,Ae.storagemutated.fire(e)}finally{me=t}}Xe(Re,{...$t,delete:e=>new Re(e,{addons:[]}).delete(),exists:e=>new Re(e,{addons:[]}).open().then(t=>(t.close(),!0)).catch("NoSuchDatabaseError",()=>!1),getDatabaseNames(e){try{return function({indexedDB:t,IDBKeyRange:n}){return Rr(t)?Promise.resolve(t.databases()).then(i=>i.map(r=>r.name).filter(r=>r!==mn)):Ar(t,n).toCollection().primaryKeys()}(Re.dependencies).then(e)}catch{return V(new x.MissingAPI)}},defineClass:()=>function(e){J(this,e)},ignoreTransaction:e=>U.trans?nt(U.transless,e):e(),vip:or,async:function(e){return function(){try{var t=ar(e.apply(this,arguments));return t&&typeof t.then=="function"?t:L.resolve(t)}catch(n){return V(n)}}},spawn:function(e,t,n){try{var i=ar(e.apply(n,t||[]));return i&&typeof i.then=="function"?i:L.resolve(i)}catch(r){return V(r)}},currentTransaction:{get:()=>U.trans||null},waitFor:function(e,t){const n=L.resolve(typeof e=="function"?Re.ignoreTransaction(e):e).timeout(t||6e4);return U.trans?U.trans.waitFor(n):n},Promise:L,debug:{get:()=>ae,set:e=>{Bi(e,e==="dexie"?()=>!0:Ji)}},derive:He,extend:J,props:Xe,override:Ri,Events:ft,on:Ae,liveQuery:Zo,extendObservabilitySet:ss,getByKeyPath:we,setByKeyPath:re,delByKeyPath:function(e,t){typeof t=="string"?re(e,t,void 0):"length"in t&&[].map.call(t,function(n){re(e,n,void 0)})},shallowClone:Di,deepClone:xt,getObjectDiff:Cr,cmp:Y,asap:Ci,minKey:Xn,addons:[],connections:ht,errnames:kr,dependencies:cr,semVer:Gr,version:Gr.split(".").map(e=>parseInt(e)).reduce((e,t,n)=>e+t/Math.pow(10,2*n))}),Re.maxKey=Lt(Re.dependencies.IDBKeyRange),typeof dispatchEvent<"u"&&typeof addEventListener<"u"&&(Ae(kt,e=>{if(!me){let t;fn?(t=document.createEvent("CustomEvent"),t.initCustomEvent(ke,!0,!0,e)):t=new CustomEvent(ke,{detail:e}),me=!0,dispatchEvent(t),me=!1}}),addEventListener(ke,({detail:e})=>{me||Gt(e)}));let me=!1;if(typeof BroadcastChannel<"u"){const e=new BroadcastChannel(ke);typeof e.unref=="function"&&e.unref(),Ae(kt,t=>{me||e.postMessage(t)}),e.onmessage=t=>{t.data&&Gt(t.data)}}else if(typeof self<"u"&&typeof navigator<"u"){Ae(kt,t=>{try{me||(typeof localStorage<"u"&&localStorage.setItem(ke,JSON.stringify({trig:Math.random(),changedParts:t})),typeof self.clients=="object"&&[...self.clients.matchAll({includeUncontrolled:!0})].forEach(n=>n.postMessage({type:ke,changedParts:t})))}catch{}}),typeof addEventListener<"u"&&addEventListener("storage",t=>{if(t.key===ke){const n=JSON.parse(t.newValue);n&&Gt(n.changedParts)}});const e=self.document&&navigator.serviceWorker;e&&e.addEventListener("message",function({data:t}){t&&t.type===ke&&Gt(t.changedParts)})}L.rejectionMapper=function(e,t){if(!e||e instanceof Ge||e instanceof TypeError||e instanceof SyntaxError||!e.name||!Vr[e.name])return e;var n=new Vr[e.name](t||e.message,e);return"stack"in e&&ge(n,"stack",{get:function(){return this.inner.stack}}),n},Bi(ae,Ji);let os=!0,Dr=!1;const ea=()=>os=!1,ta=()=>Dr=!0,na=["sdk_event_queue_latency_seconds","sdk_replay_add_event_batch_seconds","sdk_replay_cleanup_seconds","sdk_replay_compression_seconds","sdk_replay_get_events_between_seconds","sdk_replay_snapshot_seconds"];let ct={},ur;class ra{constructor(t){N(this,"_values",[]);N(this,"_isWebMetric");this.name=t,this._isWebMetric=na.includes(this.name)}report(t){if(os&&this._values.push({time:Date.now(),value:t}),Dr||!this._isWebMetric)return;const n=this.findExceededThreshold(t);n&&ur&&ur(t,n)}collect(){const t=this._values;return this._values=[],t}findExceededThreshold(t){const n=ct[this.name];if(n)return n.find(i=>this.valueExceedsThreshold(t,i))}valueExceedsThreshold(t,n){return n.type==="max"?t>n.value:n.type==="min"?t<n.value:!1}}const ia=(e,t)=>{ct={},Dr=!1,e==null||e.forEach(n=>{var i;n.metric in ct||(ct[n.metric]=[]),(i=ct[n.metric])==null||i.push(n)}),ur=t},Ct={},yn=e=>{const t=new ra(e);return Ct[e]=t,t},as=(e,t)=>{let n=Ct[e];return n||(n=yn(e)),n.report(t)},sa=async e=>{const t=Object.values(Ct).map(n=>({name:n.name,values:n.collect()}));if(t.some(n=>n.values.length))try{await e(JSON.stringify(t))}catch(n){Mn(`Error posting metrics: ${n}`)}},oa=({reportingIntervalSeconds:e,postMetrics:t})=>{e?setInterval(()=>{sa(t)},e*1e3):ea()},ls=async(e,t)=>{const n=performance.now();try{await e()}finally{const i=performance.now()-n;let r=Ct[t];r||(r=yn(t)),r.report(i/1e3)}},cs=(e,t)=>{const n=performance.now();try{e()}finally{const i=performance.now()-n;let r=Ct[t];r||(r=yn(t)),r.report(i/1e3)}},aa=30,us=()=>{Ie.setItem("sprig.disableReplayRecording","disabled")},Ne=()=>!!Ie.getItem("sprig.disableReplayRecording"),la=["did not allow mutations","called in an invalid security context"],ca=e=>{if(!e)return!0;for(const t of la)if(e.toLowerCase().includes(t))return!1;return!0},ua=(e,t,{reportError:n=!0,extraInfo:i})=>{Ne()||t instanceof Error&&(us(),ca(t==null?void 0:t.message)&&(n&&window.UserLeap.reportError(e,t,i),ha()))},da=async(e,t,{reportError:n}={reportError:!0})=>{var r;let i;try{if(n&&((r=window.navigator.storage)!=null&&r.estimate)){const{quota:s,usage:o}=await window.navigator.storage.estimate();i={availableSpaceInMB:s&&o?(s-o)/(1024*1024):void 0,quota:s,usage:o}}}catch(s){window.UserLeap.reportError("Error getting storage estimate",s,{originalMessage:e,originalError:t})}ua(e,t,{reportError:n,extraInfo:i})},pa=()=>{const e=Ie.getItem("sprig.sessionId");if(e)return I(`Found saved session id: ${e}`),Ie.removeItem("sprig.sessionId"),e;const t=$e();return I(`Generating new uuid: ${t}`),t},Q=pa();window.addEventListener("beforeunload",()=>{I(`Before page unload saving session id: ${Q}`),Ie.setItem("sprig.sessionId",Q)});const ha=async()=>{O.transaction("rw",O.events,O.chunkUploads,O.pendingCaptures,()=>{O.events.clear(),O.chunkUploads.clear(),O.pendingCaptures.clear()}).catch(()=>{})},xn=(e,t,n=()=>!0)=>O.table(t).where("timestamp").below(e).and(n).delete(),fa=async(e,t)=>{let n=[];return await ls(async()=>{n=await O.events.where("[sessionId+timestamp]").between([Q,e],[Q,t??Date.now()]).toArray()},"sdk_replay_get_events_between_seconds"),n},ma=(e,t,n)=>{const i=new Date,r=i.setMinutes(i.getMinutes()+(n??aa));return O.events.where("[sessionId+timestamp]").between([Q,e],[Q,t]).modify({expiredAt:r})},ya=e=>O.chunkUploads.add({...e,sessionId:e.sessionId??Q}),ga=(e,t)=>O.chunkUploads.update(e,{data:null,etag:t,status:"UploadComplete"}),wa=({status:e,uploadId:t})=>t?O.chunkUploads.where({uploadId:t,status:e}).toArray():O.chunkUploads.where({sessionId:Q,status:e}).toArray(),va=e=>O.chunkUploads.where({uploadId:e,status:"UploadComplete"}).toArray(),ba=e=>O.chunkUploads.where({uploadId:e,status:"UploadComplete"}).delete(),_a=e=>O.pendingCaptures.add({...e,sessionId:e.sessionId??Q,canUpload:!1}),Sa=()=>O.pendingCaptures.where("sessionId").equals(Q).and(e=>e.targetTimestamp<Date.now()).toArray(),Ea=()=>O.pendingCaptures.where("sessionId").equals(Q).toArray(),ka=e=>O.pendingCaptures.where("sessionId").equals(Q).and(t=>t.captureParams.responseGroupId===e).modify({canUpload:!0}),La=async e=>{var t;if((t=window.navigator.storage)!=null&&t.estimate){const{quota:n,usage:i}=await window.navigator.storage.estimate();if(n&&i&&(n-i)/1073741824<e)return!1}return!0};class Ia extends Me{constructor(){super("replayStorage",{autoOpen:!1});N(this,"events");N(this,"chunkUploads");N(this,"pendingCaptures")}}const O=new Ia;O.version(1).stores({events:"uuid, timestamp, [sessionId+timestamp]",chunkUploads:"uuid, timestamp, [sessionId+status], [uploadId+status], [sessionId+status+uploadId]",pendingCaptures:"uuid, timestamp, [sessionId+targetTimestamp]"});O.open().catch(e=>{Li(`Error opening replay storage: ${JSON.stringify(e)}`),us()});const Ua=async(e,t,n)=>new Promise((i,r)=>{const s=e.createElement("script");s.src=t,s.onload=i,s.onerror=r,n&&(s.nonce=n),e.head.appendChild(s)});let ni=1,dr=5e3,Yt=6e4;const xa=5,ri=1e3,ds=30,cn=ds+xa,Aa="sprig.pendingCount";let pr,hr,ps,ii=Date.now(),gn=!1,Jt;const Ra=async(e,t,n,i=2,r)=>{await Ze(async()=>{if(Ne()){I("Not initializing replay because recording is disabled");return}if(!t){I("Not initializing replay because config didn't specify maxReplayDurationSeconds");return}if(r!=null&&r.minAvailableGb&&(ni=r.minAvailableGb),!await La(ni)){Mn("Minimum storage not available");return}I("Initializing replay"),r!=null&&r.minDuration&&(dr=r.minDuration),r!=null&&r.batchDuration&&(Yt=r.batchDuration),oo(i),Fa(),Pa(t+cn,30*60,t+cn),Ta(),window.rrwebRecord||(I("Loading recording script"),await Ua(e,"https://cdn.sprig.com/dependencies/record-2.0.0-alpha.6.min.js",n),I("Recording script finished loading"));const s=window.rrwebRecord;if(!s){Mn("Record script failed to set global function");return}let o=!0,a=0;Jt=s({checkoutEveryNms:ds*1e3,sampling:{input:"last",scroll:250,media:800},emit:(l,u)=>{if(Ne())return;if(ii=Date.now(),u&&l.type===Fn.Meta)a=performance.now();else if(u&&a&&l.type===Fn.FullSnapshot){const p=performance.now()-a;as("sdk_replay_snapshot_seconds",p/1e3)}const c=o||!!u;o=!1,Ca({uuid:$e(),event:JSON.stringify(l),isValidStart:c,timestamp:Date.now()})},...r}),gn=!0,hr||(hr=window.setInterval(()=>{Date.now()-ii>ri&&be("Sprig_Noop",{})},ri)),R.on("survey.complete",l=>{Wa({id:l,userAgent:window.navigator.userAgent})})},"Error initializing replay")};let fr=!1,mr=[];const Ca=e=>{mr.push(e),fr||Da()},Oa=e=>{const t=e.map(n=>({...n,sessionId:n.sessionId??Q}));if(t.length!==0)return O.transaction("rw",O.events,()=>{O.events.bulkAdd(t)}).catch(n=>{rt("Error storing replay events",n)})},Da=()=>{fr=!0,setTimeout(async()=>{if(Ne())return;const e=mr;mr=[],fr=!1,cs(async()=>{await Oa(e)},"sdk_replay_add_event_batch_seconds")},500)},Pa=(e=6*60,t=30*60,n=4*60)=>{pr=window.setInterval(()=>{const i=Date.now();Ne()||(vt(`Performing periodic replay data cleanup / Event Seconds ${e} / Chunk Seconds ${t} / Pending Capture Seconds ${n}`),ls(()=>O.transaction("rw!",O.events,O.chunkUploads,O.pendingCaptures,()=>{xn(i-e*1e3,"events",r=>r.expiredAt===void 0||r.expiredAt<i-e*1e3),xn(i-t*1e3,"chunkUploads"),xn(i-n*1e3,"pendingCaptures",r=>r.canUpload===void 0||r.canUpload===!1)}).catch(r=>{clearInterval(pr),rt("Error deleting table rows",r)}),"sdk_replay_cleanup_seconds"),I("Cleanup complete"))},30*1e3)},Ta=(e=5)=>{ps=window.setInterval(async()=>{Ze(async()=>{const t=parseInt(Pe??"0");if(t===0)return;const n=await Sa();n!=null&&n.length&&(await Promise.all(n.map(async i=>(await O.pendingCaptures.delete(i.uuid),ms(i.captureParams,i.canUpload)))),Pe=(t-n.length).toString(),Ie.setItem(Aa,Pe))},"Error initiating pending captures")},e*1e3)},Ba=async(e,t,n,i,r)=>{const s=Math.min(e+r,n),o=`from: ${new Date(e).toLocaleTimeString()} to ${new Date(s).toLocaleTimeString()}`;I(`Getting event batch ${o}`);const a=await fa(e,s);if(!(a!=null&&a.length))return I(`No events found ${o}`),{validStartFound:i,events:[]};if(!i){I(`Searching for valid start in ${a.length} events ${o}`);let l=-1;if(a==null||a.forEach((c,p)=>{if(!c.isValidStart)return;const d=c.timestamp<=t;(l<0||d)&&(l=p)}),l<0)return I(`No valid start found in ${a.length} events ${o}`),{validStartFound:i,events:[]};const u=a[l].timestamp;return I(`Found valid start at: ${new Date(u).toLocaleTimeString()} in events ${o}`),{validStartFound:!0,events:a==null?void 0:a.slice(l)}}return{validStartFound:i,events:a}},Ma=(e,t,n)=>{const i=e.length,r=t*1024*1024,s=Math.ceil(i/n),o=Math.max(r,s);I(`Total file bytes: ${i} / target chunk size: ${o}`);const a=[];let l=0;for(;l<i;)a.push(e.slice(l,l+o)),l+=o;return a},hs=e=>Promise.all(e.map(async t=>{const n=await ao(t);return await ga(t.uuid,n),t.uploadId})),fs=async e=>{I(`Marking upload complete if finished: ${e}`);const t=await va(e);if(!(t!=null&&t.length)){I(`No finished chunks found for upload: ${e}`);return}const n=t.reduce((s,o)=>(s.find(a=>a.chunkIndex===o.chunkIndex)||s.push(o),s),[]);n.sort((s,o)=>s.chunkIndex-o.chunkIndex);const i=n.map(s=>({ETag:s.etag,PartNumber:s.chunkIndex})).filter(s=>s.ETag!==null),r=n[0];await xi({apiUrl:r.apiUrl,surveyId:r.surveyId,uploadId:e,responseGroupUuid:r.responseGroupId,etags:i,headers:r.completeUploadHeaders,replayDuration:r.replayDuration}),I(`Cleaning up chunks for ${e}`),await ba(e),I(`Done cleaning up chunks for ${e}`)},Fa=async()=>{Ze(async()=>{const e=await wa({status:"ReadyForUpload"});if(!(e!=null&&e.length))return;const t=await hs(e);I(`Finished uploading unfinished chunks for ${t}`),t!=null&&t.length&&await Promise.all(t.map(n=>{if(n)return fs(n)}))},"Error uploading unfinished chunks")},ja=async(e,t)=>{await hs(t),I(`Done uploading chunks for uploads: ${e.join(",")}`),await Promise.all(e.map(n=>fs(n)))},Ka=e=>{let t=0;e.forEach(r=>{t+=r.length});const n=new Uint8Array(t);let i=0;return e.forEach(r=>{n.set(r,i),i+=r.length}),n},si=async(e,t,n)=>{const i=new TextEncoder;let r=null,s=null,o=null,a=!1,l=!1,[u,c]=[0,0];const p=e-cn*1e3,d=[];let h=[];I(`Getting events between ${new Date(e).toLocaleTimeString()} and ${new Date(t).toLocaleTimeString()}`),I(`Using batch duration: ${Yt}ms`);for(let y=p;y<t;y+=Yt){if({validStartFound:l,events:h}=await Ba(y,e,t,l,Yt),!(h!=null&&h.length)){I("No events found");continue}u===0&&(u=h[0].timestamp),c=h[h.length-1].timestamp,I(`Last event time in batch: ${new Date(c).toLocaleTimeString()}`);const w=`${a?",":"["}${h.map(f=>f.event).join(",")}`,m=i.encode(w);n&&s===null&&(vt("Attempting compression"),o=new window.CompressionStream("gzip"),s=o.writable.getWriter()),cs(()=>{n&&s?s.write(m):d.push(m)},"sdk_replay_compression_seconds"),a=!0}if(c-u<dr)return I(`Replay duration is shorter than minimum of ${dr}ms / Start:${u} / End:${c}`),null;const g=i.encode("]");return vt("Writing final close brace"),s&&o?(s.write(g),s.close(),r=new Uint8Array(await new Response(o.readable).arrayBuffer())):(d.push(g),r=Ka(d)),I("Finished generating file data"),r},Na=async(e,t)=>{const n=window.CompressionStream!==void 0;let i=null;const r=t??Date.now(),s=r-e;try{i=await si(s,r,n)}catch(o){o instanceof Error&&window.UserLeap.reportError("Error compressing replay",o),n&&Ze(async()=>{await si(s,r,!1)},"fileData fallback failed")}return i},oi=async e=>{const{surveyId:t,responseGroupId:n,visitorId:i,apiUrl:r,completeUploadHeaders:s,replayParams:o,triggerTimestamp:a}=e,l=await Na(o.replayDurationSeconds*1e3,a);if(l!=null&&l.length)I(`Found file data for survey: ${t}`);else{I(`File data is empty for survey: ${t}`);return}const u=Ma(l,o.minimumChunkSizeMb,o.signedUrls.length);I(`Got ${u.length} chunks for survey: ${t}`);const c=await Promise.all(u.map(async(p,d)=>{const h=$e(),g={apiUrl:r,chunkIndex:d+1,completeUploadHeaders:s,etag:null,responseGroupId:n,status:"ReadyForUpload",surveyId:t,timestamp:a,totalChunks:u.length,data:p,uploadId:o.uploadId,uploadUrl:o.signedUrls[d].url,uuid:h,visitorId:i};return I(`Recording chunk upload: ${JSON.stringify({index:g.chunkIndex,surveyId:g.surveyId,uploadId:g.uploadId,size:p.length,id:h},null,2)}`),await ya(g),I(`Done creating chunk upload: ${h}`),g}));I(`All chunk records created. Beginning upload for survey: ${t}`),await ja([o.uploadId],c)},ms=async(e,t)=>{if(I(`Attempting replay capture: ${JSON.stringify({isStandalone:e.isStandalone,duration:e.replayParams.replayDurationSeconds,type:e.replayParams.replayDurationType,responseGroupId:e.responseGroupId,surveyId:e.surveyId,triggerTimestamp:e.triggerTimestamp,visitorId:e.visitorId},null,2)}`),Ne()){I(`Replay recording is disabled: ${e.surveyId}`);return}I(`Replay recording enabled: ${e.surveyId}`);const{isStandalone:n,replayParams:i,triggerTimestamp:r,responseGroupId:s}=e,o=async()=>{setTimeout(()=>R.removeListener(C.QuestionAnswered,o),0),Ze(async()=>{i.replayDurationType==="before"?await oi(e):await ka(s)},"Error in schedule/capture callback")};Ze(async()=>{if(i.replayDurationType==="after"||i.replayDurationType==="beforeAndAfter"){n||(I("Attaching QuestionAnswered listener for non-standalone replay"),R.on(C.QuestionAnswered,o)),I(`Scheduling capture for replay of type: ${i.replayDurationType}`),await $a(e);return}if(n||t)I(`Proceeding to capture replay for survey: ${e.surveyId} / standalone? ${n} / canUpload? ${t}`),await oi(e);else{const a=cn+i.replayDurationSeconds,l=r-a*1e3,u=r;I(`Setting expiry minutes to ${i.expirationTimeLimitMinutes} for events from ${new Date(l).toLocaleTimeString()} to ${new Date(u).toLocaleTimeString()}`),await ma(l,u,i.expirationTimeLimitMinutes),I("Attaching QuestionAnswered listener"),R.on(C.QuestionAnswered,o)}},"Error in scheduling/capturing replay")},ai=()=>{if(Ne()){vt("Not clearing user data, replay is disabled");return}return O.transaction("rw",O.events,O.pendingCaptures,()=>{O.events.where("sessionId").equals(Q).delete(),O.pendingCaptures.where("sessionId").equals(Q).delete()}).catch(e=>{rt("Error clearing session event data",e)})};let Pe=Ie.getItem("sprig.pendingCount");const $a=async e=>{I(`Scheduling replay capture: ${JSON.stringify(e)}`);const{surveyId:t}=e,n=await Ea(),i=n==null?void 0:n.filter(o=>o.captureParams.surveyId===t);if(i!=null&&i.length){I(`Pending capture exists for survey: ${t}`);return}const r={...e,replayParams:{...e.replayParams}};e.replayParams.replayDurationType==="beforeAndAfter"&&(r.replayParams.replayDurationSeconds*=2),r.replayParams.replayDurationType="before";const s=e.triggerTimestamp+e.replayParams.replayDurationSeconds*1e3;return r.triggerTimestamp=s,Pe=Pe?(parseInt(Pe)+1).toString():"1",Ie.setItem("sprig.pendingCount",Pe),_a({uuid:$e(),targetTimestamp:s,timestamp:Date.now(),captureParams:r})},be=(e,t)=>{var n,i;if(gn)try{(i=(n=window.rrwebRecord)==null?void 0:n.addCustomEvent)==null||i.call(n,e,t)}catch(r){rt("Error recording custom event",r)}},Ze=async(e,t)=>{try{await e()}catch(n){rt(t,n)}},li=e=>{e.description&&(e.description=Pr(e.description)),be("Sprig_PageView",e)},qa=e=>{be("Sprig_TrackEvent",e)},Va=e=>{be("Sprig_ShowSurvey",e)},Wa=e=>{be("Sprig_SubmitSurvey",e)},za=e=>{var t;(t=e==null?void 0:e.elementAttributes)!=null&&t.text&&(e.elementAttributes.text=Pr(e.elementAttributes.text)),be("Sprig_Click",e)},Ha=e=>{be("Sprig_Refresh",e)},Ga=e=>{e.currentPageTitle&&(e.currentPageTitle=Pr(e.currentPageTitle)),be("Sprig_BackForward",e)},Ya=e=>{be("Sprig_Keystroke",e)},rt=(e,t,{reportError:n}={reportError:!0})=>(Jt&&(Jt(),Jt=void 0),gn=!1,[pr,hr,ps].forEach(i=>{i&&clearInterval(i)}),Li(`${e} - ${JSON.stringify(t)}`),da(e,t,{reportError:n})),ys=()=>gn,Pr=e=>e&&e.trim().substring(0,500).replace(/\s\s+/g," ").replace(/\r?\n|\r/g," ").substring(0,250),ci="ul-view-sdk-script",Ja=["ios","android"],Ee="visitors",Le="environments",ui=Object.freeze({contains:(e,t)=>t.includes(e),notContains:(e,t)=>!t.includes(e),exactly:(e,t)=>t===e,notExactly:(e,t)=>t!==e,startsWith:(e,t)=>t.startsWith(e),endsWith:(e,t)=>t.endsWith(e),regex:(e,t)=>new RegExp(e).test(t),legacy:(e,t)=>new RegExp(e,"i").test(t)});function wn(e,t){const{matchType:n,pattern:i}=e,r=n?ui[n]:ui.legacy;let s=!1;try{s=r(i,t)}catch(o){const a=`[Sprig] (ERR-445) Failed to check url match with pattern ${i}`;o instanceof Error&&(console.warn(a,o),o.stack=JSON.stringify(e),window.UserLeap.reportError(a,o))}return s}async function se(e,t){var s,o,a;const{shouldDropOnRateLimit:n,...i}=t;i.headers=Object.assign(Fe(window.UserLeap),i.headers);const r=await ye(e,{...i,shouldDropOnRateLimit:n});if(r.ok){const l=(s=r.headers)==null?void 0:s.get("Authorization"),u=l?l.split(" "):void 0,c=u&&u.length===2?u[1]:void 0,p=(o=r.headers)==null?void 0:o.get("x-ul-visitor-id");c&&p&&(p!==window.UserLeap.visitorId||window.UserLeap.token!==c)&&(Z("token",c),Z("vid",p),R.emit(C.VisitorIDUpdated,{visitorId:p}),window.UserLeap.token=c,window.UserLeap.visitorId=p)}return(a=r.json)!=null&&a.logMessage&&console.warn(`[Sprig] ${r.json.logMessage}`),r}function Z(e,t){const n=ee.getItem("userleap.ids");let i={};if(n)try{i=JSON.parse(n)}catch(s){s instanceof Error&&(s.stack=n,window.UserLeap.reportError("Failed to parse local storage credentials",s)),console.warn("[Sprig] (ERR-427) Failed to lookup saved ids",s)}let r=i[window.UserLeap.envId];r?r[e]=t:r={[e]:t},i[window.UserLeap.envId]=r;try{ee.setItem("userleap.ids",JSON.stringify(i))}catch(s){s instanceof Error&&console.warn(`[Sprig] (ERR-426) Unable to write to Local Storage:: ${s.message}`)}}function Tr(){return window.previewMode?"0":window.UserLeap.visitorId??""}function ne(e,t,n){const i=[window.UserLeap._API_URL,"sdk",e];return t&&t.forEach(r=>{i.push(r),r===Le?i.push(window.UserLeap.envId):r===Ee&&i.push(Tr())}),n&&i.push(n),i.join("/")}const yt=async e=>{var le,ce;const{context:t,forceBrandedLogo:n,endCard:i,isFeedback:r=!1,locale:s,productConfig:o,questions:a,responseGroupUid:l,surveyId:u,uuid:c,vid:p,sessionReplay:d,studyType:h}=e,g=Fe(window.UserLeap),y=Mr(g),w=Br(g);if(I(`Attempting to display survey: ${u}`),d&&(I("Survey has replay attached"),y?R.emit(C.ReplayCapture,{responseGroupUid:l,hasQuestions:!!(a!=null&&a.length),surveyId:u,uploadId:d.uploadId,replayType:d.replayDurationType??"before",seconds:d.replayDurationSeconds,generateVideoUploadUrlPayload:{mediaRecordingUid:$e(),mediaType:"screen",questionId:1,responseGroupUid:l,surveyId:u,updatedAt:new Date().toISOString(),visitorId:window.UserLeap.visitorId,isReplay:!0}}):ms({responseGroupId:l,surveyId:u,visitorId:p,replayParams:d,completeUploadHeaders:g,apiUrl:window.UserLeap._API_URL,triggerTimestamp:Date.now(),isStandalone:a.length===0})),p==null||!(a!=null&&a.length))return I(`Not displaying survey: vid: ${p} / questions: ${a}`),{success:!1,message:"[Sprig] no survey found",surveyState:"no survey"};if(window.UserLeap.container){I("Already displaying a survey");const D="[Sprig] (ERR-409) Found an existing Survey container, aborting rendering of this survey";return console.warn(D),{success:!1,message:D,surveyState:"no survey"}}if(p!==window.UserLeap.visitorId&&c!==window.UserLeap.visitorId&&!window.previewMode){const D="Attempted to display survey to a different visitor";return I(D),window.UserLeap.reportError("DisplaySurvey",new Error(D)),{success:!1,message:D,surveyState:"no survey"}}I(`Showing survey: ${u}`),Va({id:u,userAgent:window.navigator.userAgent}),gi.disable(),R.emit(C.SurveyWillPresent,{name:C.SurveyWillPresent,"survey.id":u});let m,f=document.createElement("div"),b,_,v;const k=D=>{const{"view.version":ue}=D;ue!==g["x-ul-sdk-version"]&&ws(),R.removeListener("verify.view.version",k)};R.on("verify.view.version",k),window.UserLeap.useMobileStyling=w,bi(g)?(m="ul-direct-embeded-frame",b=document.head,_=window,v=!1,y&&(gs(r),f.id=m,window.UserLeap.container.appendChild(f),vs(),R.emit(C.SurveyLifeCycle,{state:"presented"}),R.emit(C.SurveyPresented,{name:C.SurveyPresented,"survey.id":u}))):{frameId:m,contentWinDocHead:b,contentWindow:_,hasOverlay:v,iframe:f}=tl({productConfig:o,useMobileStyling:w,surveyId:u,isFeedback:r}),window.UserLeap.frameId=m;const S=D=>{R.once(C.CloseSurveyOnOverlayClick,D)},A={apiURL:window.UserLeap._API_URL,cards:a,configureExitOnOverlayClick:S,context:t,endCard:i,envId:window.UserLeap.envId,eventEmitFn:R.emit.bind(R),fontFamily:window.UserLeap.fontFamily,fontFamilyURL:window.UserLeap.fontFamilyURL,forceBrandedLogo:n,frame:f,headers:g,locale:s,mobileSDKVersion:window.UserLeap.mobileSDKVersion,previewKey:ee.getItem("sprig.previewKey"),productConfig:{framePosition:o==null?void 0:o.framePosition,desktopDisplay:o==null?void 0:o.desktopDisplay,placement:o==null?void 0:o.placement},responseGroupUid:l,startingQuestionIdx:(le=window.UserLeap.config)==null?void 0:le.startingQuestionIdx,studyType:h,styleNonce:window.UserLeap.styleNonce,surveyId:u,tabTitle:document.title,ulEvents:wt,useMobileStyling:w,userId:c,viewDocument:_==null?void 0:_.document,viewWindow:_,visitorAttributes:{externalUserId:window.UserLeap.userId,email:window.UserLeap.email},...window.UserLeap._config};(ce=window.UserLeap._config)!=null&&ce.startingQuestionIdx&&(window.UserLeap._config={...window.UserLeap._config,startingQuestionIdx:null});const E=(r?window.UserLeap.feedbackCustomStyles:window.UserLeap.customStyles)??o.customStyles;A.customStyles=E,_&&(_.__cfg=A);function j(){const D=document.createElement("script");return window.UserLeap.nonce&&D.setAttribute("nonce",window.UserLeap.nonce),D.id=ci,D}const P=window.UserLeap.viewSDKURL?window.UserLeap.viewSDKURL:A.path,W=document.getElementById(ci);W&&W.remove();const $=j(),M=()=>{window.UserLeap.container&&Object.assign(window.UserLeap.container.style,{display:"flex"})};if(A.installationMethod==="web-npm"||A.installationMethod==="web-npm-bundled"){const{default:D}=await Promise.resolve().then(()=>require("./view-oWj5EBWB.cjs"));D.configure(A),v&&window.UserLeap.container&&M()}else P&&($.src=P,v&&$.addEventListener("load",()=>{window.UserLeap.container&&M()}),_==null||_.addEventListener("error",D=>{D.target instanceof HTMLScriptElement&&D.target.src===P&&window.UserLeap.reportError("loadFrameScript",new Error("Frame script failed to load"))},{capture:!0,once:!0}));return b==null||b.appendChild($),{success:!0,surveyState:"ready",surveyId:u,responseGroupUid:l}};function Br(e){var n;if(window.UserLeap.useMobileStyling!==void 0)return window.UserLeap.useMobileStyling;const t=((n=window.UserLeap.windowDimensions)==null?void 0:n.width)??document.body.clientWidth;return Mr(e)||t>10&&t<$s}function Mr(e){return Ja.includes(e["userleap-platform"])}const Fr="ul-frame";window.UserLeap&&window.Sprig&&(window.Sprig._gtm?window.Sprig=window.UserLeap:window.UserLeap=window.Sprig);window.UserLeap||(window.UserLeap=window.Sprig);window.Sprig||(window.Sprig=window.UserLeap);const Qa="rgba(255,255,255, 0.95)",Xa="rgba(0,0,0,0.9)",An="0px",gs=(e,t)=>{window.UserLeap.container=document.createElement("div"),window.UserLeap.container.className=`ul-container ${e&&"ul-container-feedback"}`;const n=Ss();t&&n&&!window.UserLeap.useMobileStyling?n.appendChild(window.UserLeap.container):document.body.appendChild(window.UserLeap.container)},ws=(e,t)=>{var i;rl();const n=window.UserLeap.container;if(n)try{(i=n.parentNode)==null||i.removeChild(n),window.UserLeap.container=null,Z("trackStartUrl",null),R.emit(C.SurveyLifeCycle,{state:"dismissed"}),R.emit(C.SurveyClosed,{name:C.SurveyClosed,initiator:e,studyType:t})}catch(r){console.warn(`[Sprig] (ERR-412) Error removing UserLeap container by ${e} `+n),r instanceof Error&&window.UserLeap.reportError("dismissActiveSurvey",r)}},vs=()=>{R.once(C.SurveyWillClose,({initiator:e,studyType:t})=>{R.removeAllListeners(C.CloseSurveyOnOverlayClick),ws(e,t)})},Za=(e,t)=>{const i={...{position:"fixed",overflow:"auto",top:"0px",left:"0px",display:"none",height:"100%",width:"100%",transition:"background-color 0.3s ease-out",zIndex:2147483646}},r=t?e.overlayStyleMobile:e.overlayStyle;i["background-color"]=r==="light"?Qa:Xa,t||(i.margin="auto"),window.UserLeap.container&&Object.assign(window.UserLeap.container.style,i)},el=(e,t,n,i)=>{var c,p;const r={position:"fixed",bottom:"0px",right:An,border:0,backgroundColor:"rgba(0,0,0,0)",zIndex:2147483646,transition:"width 0.2s ease-in-out, height 0.2s ease-in-out",maxWidth:"100%"},s=Object.assign({},t,window.UserLeap),{desktopDisplay:o}=t||{},a=o==="center-modal";a&&(s.framePosition="center");let l,u=!1;if(n)(c=window.UserLeap.windowDimensions)!=null&&c.width?r.width=`${window.UserLeap.windowDimensions.width}px`:r.width="100%",(p=window.UserLeap.windowDimensions)!=null&&p.height?r.maxHeight=`${window.UserLeap.windowDimensions.height-20}px`:window.UserLeap.maxHeight?r.maxHeight=window.UserLeap.maxHeight:r.maxHeight=`${document.body.clientHeight-20}px`,["light","dark"].includes(s.overlayStyleMobile)&&(u=!0);else{r.width=mi,r.maxHeight=window.UserLeap.maxHeight||"66vh";const d=()=>{u=!0,l={margin:"auto",position:"static"}};if(i)a?d():l={position:"relative",height:"300px"};else switch(s.framePosition){case"bottomLeft":l={left:An};break;case"topLeft":l={left:An,top:0};break;case"topRight":l={top:0};break;case"center":d();break}}return u&&Za(s,n),Object.assign(e.style,r,l),u},tl=({productConfig:e,useMobileStyling:t,surveyId:n,isFeedback:i})=>{var p,d;const r=Fr,s=i&&e.desktopDisplay==="slider";gs(i,s),nl();const o=document.createElement("iframe");o.id=r,o.setAttribute("title","Sprig User Feedback Dialog");const a=el(o,e,t,i);vs(),o.setHeight=h=>{parseInt(o.style.height)!=h&&(o.style.height=`${h}px`,R.emit(C.SurveyHeight,{name:C.SurveyHeight,contentFrameHeight:h}))};let l=!1;o.setWidth=h=>{(parseInt(o.style.width)!=h||!l)&&(l=!0,o.style.width=`${h}px`,R.emit(C.SurveyWidth,{name:C.SurveyWidth,contentFrameWidth:h}))},(p=window.UserLeap.container)==null||p.appendChild(o),e&&(t?e.exitOnOverlayClickMobile:e.exitOnOverlayClick)&&window.UserLeap.container&&(window.UserLeap.container.onclick=()=>{R.emit(C.CloseSurveyOnOverlayClick)}),R.emit(C.SurveyLifeCycle,{state:"presented"}),R.emit(C.SurveyPresented,{name:C.SurveyPresented,"survey.id":n});const u=(d=o.contentWindow)==null?void 0:d.document;if(u&&(u.open("text/html","replace"),u.write("<!doctype html><head></head><body></body></html>"),u.close(),!t)){const h=u.body;h.style.display="flex",h.style.alignItems="center"}const c=u==null?void 0:u.head;return{frameId:r,contentWinDocHead:c,contentWindow:o.contentWindow,hasOverlay:a,iframe:o}},bs={[C.SurveyFadingOut]:()=>{window.UserLeap.container&&Object.assign(window.UserLeap.container.style,{"background-color":"rgba(0,0,0,0)"})}},nl=()=>{Object.entries(bs).forEach(([e,t])=>{R.on(e,t)})},rl=()=>{Object.entries(bs).forEach(([e,t])=>{R.off(e,t)})},il=1,di=e=>e instanceof HTMLElement||e instanceof SVGElement,un=(e,t,n)=>{const i="ul-custom-style",r=e.getElementById(i);if(r){r.textContent=t;return}const s=e.createElement("style");n&&(s.nonce=n),s.textContent=t,s.id=i,e.head.appendChild(s)},_s=e=>{const t=e.querySelector(".ul-card__container");let n=600,i=360;if(t){n=t.scrollHeight;const r=getComputedStyle(t),s=parseFloat(r.marginTop)+parseFloat(r.marginBottom),o=parseFloat(r.borderTopWidth)+parseFloat(r.borderBottomWidth);n+=s+o;const a=t.querySelector(".ul-card--matrix_grid");i=a?a.scrollWidth:t.scrollWidth;const l=parseFloat(r.paddingLeft)+parseFloat(r.paddingRight),u=parseFloat(r.marginLeft)+parseFloat(r.marginRight),c=parseFloat(r.borderLeftWidth)+parseFloat(r.borderRightWidth);i+=u+c+l}return[n+il,i]},sl=e=>{const t=e.querySelector(".ul-card__container");t&&(t.scrollTop=0)},Ss=()=>T,Je=()=>document.getElementById("sprig-feedback-container"),jr=()=>document.getElementById("sprig-feedback-loading-animation"),ol=()=>{if(jr())return;const e=document.createElement("div");return e.className="ul-loading-spinner-container",e.id="sprig-feedback-loading-animation",e.role="progressbar",e.setAttribute("aria-live","polite"),e.setAttribute("aria-busy","true"),e.setAttribute("aria-label","Processing..."),e.innerHTML=`
9
+ <div class="ul-loading-spinner">
10
+ <div class="first"></div>
11
+ <div class="second"></div>
12
+ <div class="third"></div>
13
+ <div class="fourth"></div>
14
+ </div>
15
+ `,e},Es=()=>!!document.getElementById(Fr);let Rn=!1,T=null,oe=null,Kr=!1,gt=null,Ce=null;const al=["bottom-left","bottom-right","center-left","center-right"],ll=e=>{if(Je()||!al.includes(e))return;const[t,n]=e.split("-"),i=document.createElement("div");i.id="sprig-feedback-container",i.classList.add(`sprig-feedback-container-${n}`,`sprig-feedback-container-${t}`),document.body.appendChild(i)},vn=()=>{var t;const e=window.UserLeap.container;return((t=e==null?void 0:e.parentElement)==null?void 0:t.id)==="sprig-feedback-loading-container"},ks=()=>document.getElementById("sprig-feedback-error-container"),Ls=()=>{if(!T)return 0;const e=T==null?void 0:T.clientWidth,t=window.getComputedStyle(T),n=parseInt(t.borderRightWidth||"0"),i=parseInt(t.borderLeftWidth||"0");return e+n+i},dn=e=>{const t=Je();t&&(Ce!=null&&Ce.endsWith("right")?t.style.right=`${e}px`:Ce!=null&&Ce.endsWith("left")&&(t.style.left=`${e}px`))},Cn=()=>{if(T&&(vn()||ks())){R.off(C.SurveyAppeared,ut),yr();const e=Ls();return dn(-e),!0}return!1},ut=()=>{if(!T||!oe)return;const e=jr();e&&e.remove(),T.style.height="auto",T.style.width="auto",oe.disabled=!1,Kr=!1},yr=()=>{if(!T)return;if(!jr()){const t=ol();t&&(T.style.height="300px",T.style.width="360px",T.appendChild(t))}},pi=()=>{!T||!oe||(dn(0),oe.disabled=!0,Kr=!0)},cl=async e=>{const t=await se(ne("1",[Ee],"startFeedbackStudy"),{body:JSON.stringify({surveyUuid:e}),method:"POST"});return t.ok?t.json:null},Is=async(e,t)=>{const{buttonTheme:n,customStyles:i,eventId:r,placement:s,desktopDisplay:o,feedbackLabel:a,surveyUuid:l,surveyId:u}=e;window.UserLeap.feedbackCustomStyles=void 0;let c=Je();if(c){if(!t&&r===gt)return;c.remove(),R.off(wt.SURVEY_FADING_OUT,Cn)}if(gt=r,!document.getElementById("sprig-feedback-style")){const{head:m}=document,f=document.createElement("style");f.id="sprig-feedback-style",f.textContent=Fs,f.nonce=window.UserLeap.styleNonce,m.appendChild(f)}un(document,i??"",window.UserLeap.styleNonce),Rn=o==="center-modal",Ce=s;const[d,h]=s.split("-");ll(s),c=Je(),oe=document.createElement("button");const g=document.createElement("div");g.className="sprig-feedback-button-label",g.innerText=a,oe.appendChild(g),oe.id="sprig-feedback-button",oe.classList.add(`sprig-feedback-button-${h}`,`sprig-feedback-button-${d}`,`sprig-feedback-button-${n}`,"fade-in-transition"),R.on(wt.SURVEY_FADING_OUT,Cn),oe.addEventListener("click",async()=>{const m=document.getElementById("sprig-feedback-error-container");if(Es()||ks()){if(Cn()){R.emit(C.SurveyWillClose,{name:C.SurveyWillClose,initiator:he.FeedbackClosed,studyType:"feedbackButton"});const v=Je();m&&v&&(v.remove(),gt=null,T=null)}return}const f=Fe(window.UserLeap);if(!Br(f)&&!Kr&&pi(),t){T&&T.classList.add("sprig-feedback-loading-container-previews"),await yt(t),ut();return}const _=await cl(l);if(_)R.once(C.SurveyAppeared,ut),yt({..._,studyType:"feedbackButton"});else if(T){const v=dl();T.appendChild(v),ut(),T.style.height="300px",T.style.width="360px"}}),c==null||c.appendChild(oe),R.emit(C.FeedbackButtonLoaded,{name:C.FeedbackButtonLoaded,"survey.id":u});const{useMobileStyling:y,_config:{border:w}}=window.UserLeap;if(!Rn&&!y){const m=document.createElement("div");m.id="sprig-feedback-loading-container",m.className=`sprig-feedback-loading-container sprig-feedback-loading-container-${h}`,m.style.setProperty("--feedback-border",w),T=m,yr(),c==null||c.appendChild(m);const f=Ls();dn(-f)}else Rn&&dn(0);window.UserLeap._config.isOnQuestionsTab&&t&&!vn()&&T&&(pi(),yr(),T&&T.classList.add("sprig-feedback-loading-container-previews"),yt(t),ut())},ul=e=>{if(vn())return;const t=Je();if(!t)return;const{pageUrlEvents:n}=window.UserLeap._config,i=n==null?void 0:n.find(s=>s.id===gt);if(!i)return;wn(i,e)||(t.remove(),gt=null,T=null)},dl=()=>{const e=document.createElement("div");e.id="sprig-feedback-error-container",e.innerHTML=`<svg xmlns="http://www.w3.org/2000/svg" width="40" height="40" viewBox="0 0 40 40" fill="none">
16
+ <circle cx="20" cy="20" r="14.5" stroke="#B0B5B7" stroke-width="3"/>
17
+ <path d="M20 12L20 21.6" stroke="#B0B5B7" stroke-width="3" stroke-linecap="round"/>
18
+ <circle cx="19.9984" cy="27.6" r="1.6" fill="#B0B5B7"/>
19
+ </svg>`;const t=document.createElement("h3");return t.className="sprig-feedback-error-text",t.innerText="There was an error while loading the survey",e.appendChild(t),e},pl="!launch_darkly_";class hl{constructor(){N(this,"_ldData",{})}getAllLaunchDarklyVariations(){return this._ldData}setLDFlagsVariations(t){try{return!t||typeof t!="object"||Array.isArray(t)?!1:(Object.keys(this._ldData).forEach(n=>{delete this._ldData[n]}),Object.keys(t).forEach(n=>this._ldData[`${pl}${n}`]=(t[n]??0)+1),!0)}catch(n){return n instanceof Error&&window.UserLeap.reportError("setAllLDFlagsVariations",n),console.warn("[Sprig] An issue had occured when setting LaunchDarkly flags and variations."),!1}}}const gr=new hl;Object.freeze(gr);const fl="!optimizely_experiments_";class ml{constructor(){N(this,"_optimizelyData",{})}setOptimizelyExperiment(t,n=!0){if(!t||typeof t!="object")return!1;const{experiments:i}=t;try{return n&&Object.keys(this._optimizelyData).map(r=>{delete this._optimizelyData[r]}),i&&i.map(r=>{const{id:s,variation:o}=r,a=this.transformExperimentId(s);o&&typeof o=="string"&&(this._optimizelyData[a]=o)}),!0}catch(r){return r instanceof Error&&window.UserLeap.reportError("setOptimizelyExperiment",r),!1}}getAllOptimizelyExperiments(){return this._optimizelyData}getOptimizelyVariationName(t){return this._optimizelyData[this.transformExperimentId(t)]}transformExperimentId(t){return fl+t}getAndSetWebOptimizelyExperiments(){var t;try{if(window&&window.optimizely&&typeof window.optimizely.get=="function"){const n=(t=window.optimizely.get("state"))==null?void 0:t.getExperimentStates({isActive:!0});if(n){const i=Object.keys(n).map(r=>{var s,o;return(s=n[r].variation)!=null&&s.name?{id:r,variation:(o=n[r].variation)==null?void 0:o.name}:{id:r,variation:"Original"}});return this.setOptimizelyExperiment({experiments:i},!1),!0}return!1}return!1}catch(n){return n instanceof Error&&window.UserLeap.reportError("getAndSetWebOptimizely",n),!1}}}const Qt=new ml;Object.freeze(Qt);class yl{constructor(t,n){N(this,"paused");N(this,"queue");N(this,"ul");this.ul=t,this.paused=!1,this.queue=[],this.flush(n)}flush(t){const n=t.length;if(n)for(let i=0;i<n;i++)this.push(t[i])}isPaused(){return this.paused}pause(){this.paused=!0}unpause(){this.paused=!1;const t=this.queue.slice();this.empty(),this.flush(t)}push(t){if(this.paused)this.queue.push(t);else if(t instanceof Function)t();else{const n=Array.prototype.slice.call(t,1),i=t[0],r=this.ul[i];r instanceof Function?r.apply(this.ul,n):i&&console.warn("[Sprig] (ERR-100) No valid UserLeap action called",i)}}perform(t){if(this.paused){let n=()=>{};const i=new Promise(function(r){n=function(){r(t())}});return this.queue.push(n),i}else return t()}empty(){this.queue.length=0}}const wr=(e,t)=>{const n=performance.now();document.hidden?setTimeout(()=>wr(e,t),e):setTimeout(()=>{const i=performance.now()-n;t.report(i/1e3),setTimeout(()=>wr(e,t),e)},0)},gl=(e=1e3)=>{const t=yn("sdk_event_queue_latency_seconds");wr(e,t)},wl=({webMetricsEnabled:e,reportingIntervalSeconds:t,thresholds:n,postMetrics:i})=>{ia(n,(r,s)=>{if(ys()){const o=`Value: ${r} on ${s.metric} violated threshold of ${s.type} ${s.value}`;rt("Threshold violated",new Error(o),{reportError:!1}),ta()}}),oa({reportingIntervalSeconds:t,postMetrics:i}),e&&gl()},On={capture:!0},vl=["a","button","input","option","li","link"],bl=["Escape","Enter","Backspace","F5","Tab"],_l=["label","type","role","title","placeholder","errormessage","valuetext","href"],hi="aria-",Sl=e=>{if(!e.tagName)return"No tagName";const t=e.getAttribute("type");return t?`${t} ${e.tagName.toLowerCase()}`:e.tagName.toLowerCase()},fi=e=>{var i;if(((i=e.tagName)==null?void 0:i.toLowerCase())==="html")return{element:"html"};const t=e.textContent,n=t?{text:t}:{};n.element=Sl(e);for(const r of e.attributes){let s=r.name;const o=r.value;s.startsWith(hi)&&(s=s.substring(hi.length)),_l.includes(s)&&(n[s]=o)}return n},El=e=>{var r;if(!e)return{};const n={...fi(e)},i=e.parentElement;if(i&&vl.includes((r=i.tagName)==null?void 0:r.toLowerCase())){const s=fi(i);Object.assign(n,s)}return n},Us=(e,t)=>{za({x:t.x,y:t.y,type:e,elementAttributes:El(t.target)})},kl=e=>t=>Us(e,t),Ll=e=>{bl.includes(e.key)&&Ya({key:e.key})},Il=()=>{window.performance.getEntriesByType("navigation").map(t=>t.type).includes("reload")&&Ha({url:window.location.href,currentPageTitle:document.title})},Ul=()=>{window.performance.getEntriesByType("navigation").map(t=>t.type).includes("back_forward")&&Ga({curUrl:window.location.href,fromUrl:document.referrer,currentPageTitle:document.title})},xl=()=>{window.addEventListener("click",kl("left_click"),On),window.addEventListener("mousedown",e=>{e.button===2&&Us("right_click",e)},On),window.addEventListener("keydown",Ll,On),Il(),Ul()},Al={test:"test"},Rl=["popState","pushState","replaceState"],ot="!email",vr="pageUrl";function Cl(e,t){const{pageUrlEvents:n,interactiveEvents:i,dismissOnPageChange:r}=window.UserLeap._config;if(!r)return!0;const s=[];n&&n.length&&s.push(...n),i&&i.length&&s.push(...i);const o=e&&s.find(a=>a.id===e);return o?wn(o,window.location.href):t===window.location.href}function Ut(e){const{pageUrlEvents:t,interactiveEvents:n,dismissOnPageChange:i,platform:r}=window.UserLeap._config;if(r&&r!=="web")return;const s=Oe("trackStartUrl"),o=s?String(s):null;t&&Cs(window.location.href),n&&(As(),Ol()),Ss()&&ul(window.location.href),!vn()&&i&&o&&o!==window.location.href&&e&&Rl.includes(e.type)&&window.UserLeap("dismissActiveSurvey",he.PageChange)}const xs={capture:!0},Ol=()=>{const t=window.UserLeap._config.interactiveEvents.filter(i=>wn(i,window.location.href)).map(i=>{const{name:r,properties:s}=i,{selector:o,innerText:a}=s;return o?l=>{if(di(l.target))try{l.target.closest(o)&&window.UserLeap("track",r)}catch{}return!1}:l=>(di(l.target)&&l.target.innerText===a&&window.UserLeap("track",r),!1)}),n=i=>t.forEach(r=>r(i));window.UserLeap._config.interactiveEventsHandler=n,window.addEventListener("click",n,xs)},As=()=>{window.UserLeap._config.interactiveEventsHandler&&window.removeEventListener("click",window.UserLeap._config.interactiveEventsHandler,xs),delete window.UserLeap._config.interactiveEventsHandler};function Dl(){["hashchange","popstate"].forEach(e=>window.addEventListener(e,Ut,!0))}function Pl(){["hashchange","popstate"].forEach(e=>window.removeEventListener(e,Ut,!0)),window.UserLeap._config.interactiveEvents&&As()}function Tl(e){const t=new URL(ne("1",[Le],"questions"));return Object.entries(e||{}).forEach(([n,i])=>{i&&t.searchParams.append(n,String(i))}),t.toString()}function Oe(e){const t=ee.getItem("userleap.ids");if(t)try{const i=JSON.parse(t)[window.UserLeap.envId];return i&&i[e]||null}catch(n){n instanceof Error&&(n.stack=t,window.UserLeap.reportError("Failed to parse local storage credentials",n)),console.warn("[Sprig] (ERR-427) Failed to lookup saved ids",n)}return null}function Rs(){window.previewMode||(window.UserLeap.visitorId=$e(),I(`Generating new vid: ${window.UserLeap.visitorId}`),Z("vid",window.UserLeap.visitorId),R.emit(C.VisitorIDUpdated,{visitorId:window.UserLeap.visitorId}))}function Cs(e,t,n){var c;if(e.endsWith("mock_snippet.html"))return;I(`Tracking page view: ${e}`);const i=window.UserLeap._config.pageUrlEvents;let r=!1;if(i&&i.length)for(let p=0;p<i.length&&(r=wn(i[p],e),!r);p++);if(!r)return;window.UserLeap.debugMode&&console.info("[DEBUG] Sprig trackPageView",e);const s=10,o=1;let a=[];const l={viewedAt:Date.now(),location:e},u=ee.getItem("userleap.pageviews");try{if(a=u?JSON.parse(u):[],Array.isArray(a)||(a=[]),a.length>0){const p=a[a.length-1],d=(Date.now()-p.viewedAt)/1e3;if(p.location!=e&&d>o){const h=(c=document==null?void 0:document.querySelector('meta[name="description"]'))==null?void 0:c.getAttribute("content");li({...h&&{description:h},url:e,referrer:document.referrer,pageTitle:document.title})}(p.location!=e&&d>o||d>s)&&(window.UserLeap._queue.push(["track",vr,t,{url:e},n]),a.push(l))}else window.UserLeap._queue.push(["track",vr,t,{url:e},n]),a.push(l),li({url:e});a.length>5&&a.splice(0,a.length-5),ee.setItem("userleap.pageviews",JSON.stringify(a))}catch(p){p instanceof Error&&window.UserLeap.reportError("trackPageView",p,{pageViewsStorage:u}),console.warn("[Sprig] (ERR-425) Failed to update page views in local storage")}}function Bl(){const e="Backbone"in window&&window.Backbone&&window.Backbone.history?window.Backbone.history:window.history;"pushState"in e&&(e.pushState=(t=>function(...i){const r=t.apply(this,i),s=new Event("pushState");return window.dispatchEvent(s),Ut(s),r})(e.pushState)),"replaceState"in e&&(e.replaceState=(t=>function(...i){const r=t.apply(this,i),s=new Event("replaceState");return window.dispatchEvent(s),Ut(s),r})(e.replaceState)),Dl()}async function Dn(e,t){const n=Tr();e&&!t&&(window.UserLeap._config.mode=Al.test);const i=Fe(window.UserLeap),r=Br(i),s=await se(Tl({desktopDisplay:window.UserLeap._config.desktopDisplay,isMobile:r,previewLanguage:window.UserLeap._config.previewLanguage,surveyid:e==null?void 0:e.surveyId,surveytemplateid:e==null?void 0:e.surveyTemplateId,vid:n}),{shouldDropOnRateLimit:!0});if(!s.ok)return s.reportError&&s.error&&(console.warn("[Sprig] (ERR-414) Failed to request questions from the server",s.error),window.UserLeap.reportError("getQuestions",s.error)),{success:!1,surveyState:"no survey"};if(s.json.delay&&await Xt(s.json.delay),s.json.isFeedback){const{feedbackLabel:o,productConfig:a,surveyUuid:l,feedbackCustomStyles:u}=s.json,{buttonTheme:c,placement:p,desktopDisplay:d}=a,h={customStyles:u,buttonTheme:c,desktopDisplay:d,eventId:0,feedbackLabel:o,placement:p,surveyUuid:l,surveyId:e==null?void 0:e.surveyId};Is(h,s.json)}else return yt(s.json)}function Ml(e){let t=e.length;for(;t;){const n=Math.floor(Math.random()*t);t-=1;const i=e[t];e[t]=e[n],e[n]=i}}function Fl(e){if(!e)return;window.UserLeap._config=e,e.mute&&window.UserLeap._queue.pause();const{interactiveEvents:t,pageUrlEvents:n,dismissOnPageChange:i}=e;t&&Ml(t),(t||n||i)&&(Bl(),Ut())}async function jl(e,t){var i,r;let n=!0;return t&&((i=e==null?void 0:e.json)!=null&&i.surveyId)&&(window.UserLeap.delayingSurvey=!0,n=await t(e.json.surveyId),window.UserLeap.delayingSurvey=!1,!n)?!1:((r=e==null?void 0:e.json)!=null&&r.delay&&(window.UserLeap.delayingSurvey=!0,await Xt(e.json.delay),window.UserLeap.delayingSurvey=!1),n)}const Kl=function(e){if(!window.UserLeap)return;const t=async(r={})=>{var m,f,b,_;const{userId:s,anonymousId:o,metadata:a={},properties:l,showSurveyCallback:u}=r;let{eventName:c}=r;if(window.UserLeap.debugMode&&c!==vr&&console.info("[DEBUG] Sprig track",r),e.mode==="test")return;const p=ee.getItem("sprig.previewKey")??void 0;if(e.requireUserIdForTracking&&!window.UserLeap.userId&&!s){const v="[Sprig] - Skipping tracking without userId";return console.warn(v),{success:!1,message:v,surveyState:"no survey"}}if(!c||c.trim().length===0){c=c?String(c):"";const v="[Sprig] - Invalid event name "+c;return console.warn(v),{success:!1,message:v,surveyState:"no survey"}}const d=window.location.href;if(a.url||(a.url=d),Z("trackStartUrl",d),(f=(m=window.UserLeap)==null?void 0:m._config)!=null&&f.optimizelyEnabled){const v=Fe(window.UserLeap);Mr(v)||Qt.getAndSetWebOptimizelyExperiments(),a.optimizelyExperiments=Object.assign({},Qt.getAllOptimizelyExperiments())}(_=(b=window.UserLeap)==null?void 0:b._config)!=null&&_.launchDarklyEnabled&&(a.launchDarklyFlags=gr.getAllLaunchDarklyVariations()),s&&(window.UserLeap.userId=s),o&&(window.UserLeap.partnerAnonymousId=o),l&&(a.eventProperties=l),qa({name:c,url:a.url}),I(`Tracking event: ${c}`);const h=window.UserLeap.delayingSurvey||Es()?await se(ne("1",[Ee],"events/batch"),{body:JSON.stringify({events:[{event:c,metadata:a}],previewKey:p}),method:"POST",shouldDropOnRateLimit:!0}):await se(ne("1",[Ee],"events"),{body:JSON.stringify({event:c,metadata:a,previewKey:p}),method:"POST",shouldDropOnRateLimit:!0});if(!h.ok){const v="[Sprig] (ERR-421) Failed to track event";return h.reportError&&(console.warn(v,h.error),h.error&&window.UserLeap.reportError("track",h.error)),{success:!1,message:v,error:h.error,surveyState:"no survey"}}s&&Z("uid",s),o&&Z("aid",o);const g=h.json;return g.invalidPreviewKey&&ee.removeItem("sprig.previewKey"),!!(g!=null&&g.feedbackButton)&&Is(g.feedbackButton),await jl(h,u)?Cl(g.eventId,d)?yt(g):{success:!1,message:"Study should not be displayed after page navigation",surveyState:"no survey"}:{success:!1,message:"[Sprig] Callback returned false, aborting rendering of survey",surveyState:"no survey"}},n=(r,s)=>{var a;const o=(a=r==null?void 0:r.querySelector(`[id="${Fr}"]`))==null?void 0:a.contentDocument;o&&un(o,s)},i={async displaySurvey(r){return console.warn("[Sprig] displaySurvey should only be used to debug your studies; not intended for production usage."),window.UserLeap("dismissActiveSurvey",he.Override),Dn({surveyId:r},!0)},_previewSurvey(r){window.UserLeap("dismissActiveSurvey",he.Override),Dn({surveyTemplateId:r},!1)},_reviewSurvey(r){window.UserLeap("dismissActiveSurvey",he.Override),Dn({surveyId:r},!1)},previewSurvey(r){i._previewSurvey(r)},reviewSurvey(r){i._reviewSurvey(r)},mute(){window.UserLeap._queue.pause()},unmute(){window.UserLeap._queue.unpause()},setVisitorToken(){console.warn("[Sprig] setVisitorToken is deprecated.")},dismissActiveSurvey(r=he.API){R.emit(C.SurveyWillClose,{name:C.SurveyWillClose,initiator:r})},async setAttribute(r,s){if(!r||!s&&s!==0&&s!==!1){const o="[Sprig] - Disregarding empty attribute / value provided";return console.warn(o),{success:!1,message:o}}return this.setAttributes({[r]:s})},async setAttributes(r){if(r==null||Object.keys(r).length===0){const s="[Sprig] - Disregarding empty attributes provided";return console.warn(s),{success:!1,message:s}}return this.identifyAndSetAttributes({attributes:r})},async identifyAndSetAttributes(r){if(window.UserLeap.debugMode&&console.info("[DEBUG] Sprig identifyAndSetAttributes",r),e.mode==="test")return;if(r===null||typeof r!="object"||!(r.userId||r.anonymousId||r.attributes)){const c="[Sprig] - Disregarding empty payload provided";return console.warn(c),{success:!1,message:c}}const{userId:s,anonymousId:o,attributes:a}=r;if(e.requireUserIdForTracking&&!window.UserLeap.userId&&!s){const c="[Sprig] - Skipping tracking without userId";return console.warn(c),{success:!1,message:c}}if(!a&&(!s||window.UserLeap.userId===s)&&(!o||window.UserLeap.partnerAnonymousId===o))return{success:!0};const l={};s&&(l.userId=window.UserLeap.userId=s),o&&(l.partnerAnonymousId=window.UserLeap.partnerAnonymousId=o);let u;return a?(a.email&&!Object.prototype.hasOwnProperty.call(a,ot)&&(a[ot]=a.email,delete a.email),I(`Setting attributes: ${JSON.stringify(a)}`),u=await se(ne("1",[Le,Ee],"attributes"),{body:JSON.stringify(a),method:"PUT"}),!u.ok&&u.reportError&&(console.warn("[Sprig] (ERR-432) identifyAndSetAttributes failed",u.error),u.error&&window.UserLeap.reportError("identifyAndSetAttributes",u.error))):u=await se(ne("1",[Le,Ee]),{body:JSON.stringify(l),method:"PUT"}),a&&a[ot]&&(window.UserLeap.email=a[ot]),u.ok&&(s&&Z("uid",s),o&&Z("aid",o)),{success:!!u.ok}},async removeAttributes(r){if(window.UserLeap.debugMode&&console.info("[DEBUG] Sprig removeAttributes",r),e.mode==="test")return;if(r==null||r.length===0){const o="[Sprig] - Disregarding empty attributes provided";return console.warn(o),{success:!1,message:o}}if(e.requireUserIdForTracking&&!window.UserLeap.userId){const o="[Sprig] - Skipping tracking without userId";return console.warn(o),{success:!1,message:o}}const s=await se(ne("1",[Le,Ee],"attributes"),{body:JSON.stringify({delete:r}),method:"DELETE"});return!s.ok&&s.reportError&&(console.warn("[Sprig] (ERR-433) Remove attributes failed",s.error),s.error&&window.UserLeap.reportError("removeAttributes",s.error)),{success:!!s.ok}},async addSurveyListener(r){R.on(C.SurveyLifeCycle,r)},async removeSurveyListener(r){R.removeListener(C.SurveyLifeCycle,r)},async addListener(r,s){R.on(r,s)},async removeListener(r,s){R.removeListener(r,s)},async removeAllListeners(){R.removeAllListeners()},setPreviewKey(r){!r||typeof r!="string"||ee.isStorageAvailable&&r&&ee.setItem("sprig.previewKey",r)},async setUserId(r){if(window.UserLeap.debugMode&&console.info("[DEBUG] Sprig setUserId",r),r==null){const a=`[Sprig] - Invalid userId ${r}`;return console.warn(a),{success:!1,message:a}}if(e.mode==="test"||r===window.UserLeap.userId)return;window.UserLeap.userId=r;const s=window.UserLeap.visitorId,o=await se(ne("1",[Le,Ee]),{body:JSON.stringify({userId:r}),method:"PUT"});if(!o.ok){o.reportError&&(console.warn("[Sprig] (ERR-420) Failed to set user id",o.error),o.error&&window.UserLeap.reportError("setUserId",o.error));return}s!==window.UserLeap.visitorId&&ai(),Z("uid",r)},async setPartnerAnonymousId(r){if(window.UserLeap.debugMode&&console.info("[DEBUG] Sprig setPartnerAnonymousId",r),r==null){const s=`[Sprig] - Invalid partnerAnonymousId ${r}`;return console.warn(s),{success:!1,message:s}}return window.UserLeap.partnerAnonymousId=r,Z("aid",r),{success:!0}},async track(r,s,o={},a=void 0){return t({eventName:r,properties:s,metadata:o,showSurveyCallback:a})},async identifyAndTrack(r){return await t(r)},trackPageView(r,s=void 0,o=void 0){Cs(r,s,o)},applyFeedbackStyles({button:r="",view:s=""}){window.UserLeap.feedbackCustomStyles=s,document.getElementById("sprig-feedback-style")&&un(document,r,window.UserLeap.styleNonce),n(document.querySelector(".ul-container-feedback"),s)},applyStyles(r){window.UserLeap.customStyles=r,n(window.UserLeap.container,r)},setWindowDimensions(r,s){var u,c;const o=typeof r=="string"?parseInt(r,10):r,a=typeof s=="string"?parseInt(s,10):s;if(!isNaN(o)&&!isNaN(a)&&(window.UserLeap.windowDimensions={width:o,height:a}),!window.UserLeap.frameId)return;const l=document.getElementById(window.UserLeap.frameId);l&&(window.UserLeap.useMobileStyling&&((u=window.UserLeap.windowDimensions)!=null&&u.width&&(l.style.width=`${window.UserLeap.windowDimensions.width}px`),(c=window.UserLeap.windowDimensions)!=null&&c.height&&(l.style.maxHeight=`${window.UserLeap.windowDimensions.height-20}px`),l.contentDocument&&(l.style.height=String(_s(l.contentDocument)[0])+"px")),R.emit(C.SurveyDimensions,{name:C.SurveyDimensions,contentFrameWidth:l.clientWidth,contentFrameHeight:l.clientHeight}))},logoutUser(){window.UserLeap.debugMode&&console.info("[DEBUG] Sprig logout"),I(`Logging out user: ${window.UserLeap.userId} / vid: ${window.UserLeap.visitorId}`),window.UserLeap.visitorId=null,window.UserLeap.userId=null,window.UserLeap.partnerAnonymousId=null,window.UserLeap.token=null,window.UserLeap.email=null,ee.removeItem("userleap.ids"),ee.removeItem("userleap.pageviews"),window.UserLeap._queue.isPaused()&&window.UserLeap._queue.empty(),Rs(),ai(),window.UserLeap._queue.unpause()},teardown(){Pl(),window.UserLeap("dismissActiveSurvey",he.API),delete window.UserLeap,delete window.Sprig,delete window._Sprig},integrateOptimizely(r,s=!0){var o,a;if(!((a=(o=window.UserLeap)==null?void 0:o._config)!=null&&a.optimizelyEnabled)){console.warn("[SPRIG] Optimizely integration is currently not enabled for your product.");return}try{const l=typeof r=="string"?JSON.parse(r):r;Qt.setOptimizelyExperiment(l,s)}catch(l){console.warn("[Sprig] Error with integrating Optimizely data"),l instanceof Error&&window.UserLeap.reportError("integrateOptimizely",l)}},integrateOptimizelyClient(r){var o,a;if(!((a=(o=window.UserLeap)==null?void 0:o._config)!=null&&a.optimizelyEnabled)){console.warn("[SPRIG] Optimizely integration is currently not enabled for your product.");return}const s=({experiment:l,variation:u})=>{const c={experiments:[{id:l.id,variation:u.key}]};window.UserLeap("integrateOptimizely",c,!1)};r.notificationCenter.addNotificationListener("ACTIVATE:experiment, user_id,attributes, variation, event",s)},importLaunchDarklyData(r){var s,o;if(!((o=(s=window.UserLeap)==null?void 0:s._config)!=null&&o.launchDarklyEnabled)){console.warn("[SPRIG] LaunchDarkly integration is currently not enabled for your product.");return}gr.setLDFlagsVariations(r)},setVisitorAttribute(r,s){return console.warn("[Sprig] setVisitorAttribute is deprecated. Please use setAttribute"),i.setAttribute(r,s)},async setEmail(r){return i.setAttribute(ot,r)},async setVisitorEmail(r){return console.warn("[Sprig] setVisitorEmail is deprecated. Please use setEmail"),i.setEmail(r)},async _generateVideoUploadUrl(r){return Vl(r)},_reportMetric(r,s){as(r,s)},async _completeSessionReplay({surveyId:r,responseGroupUuid:s,eventDigest:o}){if(!r||!s)return!1;const a=window.UserLeap._API_URL;try{const l=await xi({surveyId:r,responseGroupUuid:s,eventDigest:o,apiUrl:a,headers:Fe(window.UserLeap)},!0);return!(l!=null&&l.error)}catch(l){return console.warn("[Sprig] Error with completing session replay"),l instanceof Error&&window.UserLeap.reportError("completeSessionReplay",l),!1}}};Object.assign(window.UserLeap,i)};async function Nl(e){const t=Fe(window.UserLeap);document.addEventListener("securitypolicyviolation",Pn);const n=await ye(ne("1",[Le],"config"),{headers:t}),i="TypeError";if(window.UserLeap.error=n.error,!n.ok&&n.error&&n.error.name===i?(window.UserLeap._API_URL="https://api.sprig.com",window.UserLeap.reportError("sprigDomainRequest",n.error)):document.removeEventListener("securitypolicyviolation",Pn),!n.ok)return n.reportError&&(console.warn("[Sprig] (ERR-422) Failed to load configuration",n.error),n.error&&window.UserLeap.reportError("applyRemoteConfig",n.error)),Tn("Disabled: failed to fetch configuration"),e;const r=n.json;return r!=null&&r.disabled?(Tn(`Disabled: ${r.disabled}`),{disabled:r.disabled}):Object.assign({},r,e)}const $l=e=>typeof e=="object"&&e&&"inner"in e&&!!e.inner&&typeof e.inner=="object";async function ql(e,t,n={}){var p,d;const i=window.__cfg&&window.__cfg.mode,r=Tr(),s=window.UserLeap.envId,o=window.document.documentElement,a=$l(t)?{inner:{message:(p=t.inner)==null?void 0:p.message,stack:(d=t.inner)==null?void 0:d.stack}}:{},l={mode:i,screenWidth:window.screen.width,screenHeight:window.screen.height,clientWidth:o.clientWidth,clientHeight:o.clientHeight,location:window.location.href,language:window.navigator.language,...n,...a},u={action:e,err:{message:t.message,stack:t.stack},meta:l,vid:r,envId:s},c=await se(ne("1",null,"errors"),{method:"POST",headers:{"x-ul-error":window.btoa(`userleap-${Date.now()}-error`)},body:JSON.stringify(u),shouldDropOnRateLimit:!0});if(!c.ok)console.warn("[Sprig] (ERR-444) Failed to report error to API",t);else{const{presignedUrl:h}=c.json;Ii(h)}}async function Vl(e){var n;if(!e)return;const t=`${window.UserLeap._API_URL}/2/environments/integrations/upload`;try{const i=await fetch(t,{method:"POST",cache:"no-cache",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(i.ok){const r=await i.json();return(n=r==null?void 0:r.upload)==null?void 0:n.url}else return null}catch(i){console.warn("[Sprig] Error with generating video upload url"),i instanceof Error&&window.UserLeap.reportError("generateVideoUploadUrl",i)}}function Wl(e={}){const t=new URLSearchParams(window.location.search).get("sprigPreviewKey")??"";window.UserLeap.UPDATES=wt,window.UserLeap("setPreviewKey",t);async function n(){if(window.UserLeap.loaded)return;if(I("Loading sprig on page load"),window.UserLeap.reportError=ql,window.UserLeap.loaded=!0,window.UserLeap._config=Object.assign({},e,window.UserLeap.config),window.UserLeap.delayingSurvey=!1,window.UserLeap._config&&typeof window.UserLeap._config=="object")for(const a in window.UserLeap._config)window.UserLeap[a]=window.UserLeap._config[a];if(!window.UserLeap.envId)if(window.UserLeap.appId)window.UserLeap.envId=window.UserLeap.appId;else throw new Error("Missing Environment id");window.UserLeap.debugMode&&console.info("[DEBUG] Sprig debug mode enabled");const i=window.UserLeap.sampleRate;if(i){let a=Oe("sampled");if(a===null&&(a=Math.random()<i,Z("sampled",a)),!a)return}else Oe("sampled")!==null&&Z("sampled",null);window.UserLeap._API_URL||(window.UserLeap._API_URL="https://api.sprig.com");const r=[...window.UserLeap._queue];window.UserLeap._queue=new yl(window.UserLeap,[]),window.UserLeap._queue.pause();for(let a=0;a<r.length;a++)window.UserLeap._queue.push(r[a]);const s=Oe("token");s?(window.UserLeap.token=s,window.UserLeap.visitorId=Oe("vid"),window.UserLeap.userId=Oe("uid"),window.UserLeap.partnerAnonymousId=Oe("aid")):(ee.removeItem("userleap.ids"),Rs());const o=await Nl(e);wl({webMetricsEnabled:o.metricsReportingEnabled,reportingIntervalSeconds:o.metricsReportingEnabled||o.mobileMetricsReportingEnabled?o.metricsReportingIntervalSeconds:0,thresholds:o.metricThresholds,postMetrics:async a=>{await se(ne("1",[Le],"metrics"),{body:a,method:"POST",headers:{"x-ul-replay-enabled":`${ys()}`},shouldDropOnRateLimit:!0})}}),Ra(window.document,o.maxReplayDurationSeconds,window.UserLeap.replayNonce,window.UserLeap.maxInflightReplayRequests,o.replaySettings).then(()=>{xl()}),io(o.logBufferLimit,o.logLevel),Kl(o),await Fl(o),window.UserLeap._queue.unpause(),R.emit(C.SDKReady,{mobileMetricsReportingEnabled:!!o.mobileMetricsReportingEnabled,metricsReportingInterval:o.metricsReportingIntervalSeconds||0,metricsThresholds:o.metricThresholds||[],maxMobileReplayDurationSeconds:o.maxMobileReplayDurationSeconds,mobileReplaySettings:o.mobileReplaySettings}),R.emit(C.VisitorIDUpdated,{visitorId:window.UserLeap.visitorId})}document.readyState==="complete"?n():window.attachEvent?window.attachEvent("onload",n):window.addEventListener("load",()=>{n()},!1)}class pn{constructor(){N(this,"UPDATES",wt)}displaySurvey(t){window.Sprig("displaySurvey",t)}mute(){window.Sprig("mute")}unmute(){window.Sprig("unmute")}dismissActiveSurvey(){window.Sprig("dismissActiveSurvey")}setAttribute(t,n){window.Sprig("setAttribute",t,n)}setAttributes(t){window.Sprig("setAttributes",t)}identifyAndSetAttributes(t){window.Sprig("identifyAndSetAttributes",t)}removeAttributes(t){window.Sprig("removeAttributes",t)}addListener(t,n){window.Sprig("addListener",t,n)}removeListener(t,n){window.Sprig("removeListener",t,n)}removeAllListeners(){window.Sprig("removeAllListeners")}setEmail(t){window.Sprig("setAttribute","!email",t)}setUserId(t){window.Sprig("setUserId",t)}setPartnerAnonymousId(t){window.Sprig("setPartnerAnonymousId",t)}track(t,n={},i={}){window.Sprig("track",t,n,i)}identifyAndTrack(t){window.Sprig("identifyAndTrack",t)}trackPageView(t,n,i){window.Sprig("trackPageView",t,n,i)}applyStyles(t){window.Sprig("applyStyles",t)}setWindowDimensions(t,n){window.Sprig("setWindowDimensions",t,n)}logoutUser(){window.Sprig("logoutUser")}teardown(){window.Sprig("teardown")}}const br={configure:e=>{if(!e.envId&&!e.environmentId)throw new Error("Initialization Error: Sprig configure requires an environmentId");if(e.envId||(e.envId=e.environmentId||""),e.installationMethod="web-npm",window.Sprig)return window.Sprig;window.Sprig=function(){window.Sprig._queue.push(arguments)},Object.getOwnPropertyNames(pn.prototype).map(n=>{n!=="constructor"&&(window.Sprig[n]=pn.prototype[n])});const t=window.Sprig;return t.appId=e.envId,t._queue=[],window.UserLeap=t,Wl(e),window.Sprig}},zl={sprig:br,SprigAPI:pn,configure:br.configure};exports.APP_ID=js;exports.ConflictingWidgets=gi;exports.DEFAULT_BORDER_COLOR=Ks;exports.DEFAULT_WIDTH=mi;exports.DismissReason=he;exports.EMBED_MOBILE_MAX_WIDTH=qs;exports.ERROR_BORDER_COLOR=Ns;exports.SprigAPI=pn;exports.SprigEvent=C;exports.calculateFrameDimensions=_s;exports.eventEmitter=R;exports.index=zl;exports.info=I;exports.overrideStyles=un;exports.resetScrollPosition=sl;exports.shouldDirectEmbed=bi;exports.sprig=br;exports.sprigFetch=ye;exports.uploadLogfile=Ii;exports.v4=$e;